[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\npip-wheel-metadata/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n.python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n.idea\ndbs/test/\n"
  },
  {
    "path": "Controller/chat_screen.py",
    "content": "import importlib\nimport multitasking\nfrom kivy.clock import mainthread\n\nimport Model.chat_screen\nimport View.ChatScreen.chat_screen\n\n# We have to manually reload the view module in order to apply the\n# changes made to the code on a subsequent hot reload.\n# If you no longer need a hot reload, you can delete this instruction.\nimportlib.reload(View.ChatScreen.chat_screen)\n\n\nclass ChatScreenController:\n    def __init__(self, model):\n        self.model: Model.chat_screen.ChatScreenModel = model\n        self.view = View.ChatScreen.chat_screen.ChatScreenView(controller=self, model=self.model)\n        self.view.bind(on_enter=self.on_enter)\n\n    def get_view(self) -> View.ChatScreen.chat_screen:\n        return self.view\n\n    @mainthread\n    def task_finished(self, chat_messages):\n        self.view.show_chat_messages(chat_messages)\n        self.view.hide_dialog()\n\n    @multitasking.task\n    def get_chat(self, chat_id):\n        chat_messages = self.model.get_chat(chat_id)\n        self.task_finished(chat_messages)\n\n    def on_enter(self, *args):\n        chat_id = self.view.app.selected_chat_id\n        self.view.selected_user = self.view.app.selected_user\n        self.view.status = self.view.app.status\n        self.view.show_dialog(msg='Loading chat ...', title='Please wait', auto_dismiss=False)\n        self.get_chat(chat_id)\n\n    def previous_screen(self):\n        self.view.app.screens_manager.current = self.view.app.screens_manager.previous()"
  },
  {
    "path": "Controller/login_screen.py",
    "content": "import importlib\nimport os.path\nimport traceback\nfrom typing import NoReturn\n\nimport multitasking\n\nfrom Utility.Utils import check_path, strip_quotes\n\nmultitasking.set_max_threads(10)\n\nimport View.LoginScreen.login_screen\n\n# We have to manually reload the view module in order to apply the\n# changes made to the code on a subsequent hot reload.\n# If you no longer need a hot reload, you can delete this instruction.\nimportlib.reload(View.LoginScreen.login_screen)\n\nfrom kivy.clock import mainthread\n\n\nclass LoginScreenController:\n\n    def __init__(self, model):\n        self.model = model  # Model.main_screen.MainScreenModel\n        self.view = View.LoginScreen.login_screen.LoginScreenView(controller=self, model=self.model)\n        self.decrypt = None\n\n    def get_view(self) -> View.LoginScreen.login_screen:\n        return self.view\n\n    def check_files(self):\n        if self.view.app.msgstore_file is None:\n            self.view.show_dialog('No msgstore provided!!',\n                                  title=\"Error\",\n                                  auto_dismiss=True)\n            return False\n        if not check_path(self.view.app.msgstore_file):\n            self.view.show_dialog(f'Please recheck the provided msgstore path\\n`{self.view.app.msgstore_file}`'\n                                  f'\\ndoes not exist',\n                                  title=\"Error\", auto_dismiss=True)\n            return False\n\n        if not check_path(self.view.app.wa_file):\n            self.view.show_dialog(f'Please recheck the provided wa.db path\\n`{self.view.app.wa_file}`'\n                                  f'\\ndoes not exist',\n                                  title=\"Error\", auto_dismiss=True)\n            return False\n\n        if not check_path(self.view.app.wp_dir):\n            self.view.show_dialog(f'Please recheck the provided Whatsapp directory path\\n`{self.view.app.wp_dir}`'\n                                  f'\\ndoes not exist',\n                                  title=\"Error\", auto_dismiss=True)\n            return False\n\n        return True\n\n    @mainthread\n    def login(self):\n        try:\n            self.view.app.load_db()\n            self.view.screens_manager.get_screen('main screen').controller.on_enter()\n            self.view.hide_dialog()\n            self.view.app.screens_manager.current = \"main screen\"\n        except Exception as e:\n            print(traceback.format_exc())\n            msg = f\"\"\"\n{str(e)}\n\nTry to choose another version from the `Database version` drop-down menu.\n\nIf no version works, probably the database is encrypted or you have an updated version of Whatsapp and your database schema is not supported yet.\nSubmit an issue on our Github page to help you add support to your database schema. \n                \"\"\"\n            self.view.show_dialog(msg=msg, title='Database schema is not supported!', auto_dismiss=True)\n\n    @mainthread\n    def show_decryption_error(self, error):\n        err = \"\"\"\nUnfortunately, the decryption of the database was not successful.\nMaybe you didn't provide the right key or the file is corrupted or the version is not supported.\nThis app is using the `WhatsApp-Crypt14-Crypt15-Decrypter` library under the hood. \nVisit their Github page for more information or to get some help:\n<https://github.com/ElDavoo/WhatsApp-Crypt14-Crypt15-Decrypter>\n        \"\"\"\n        print(traceback.format_exc())\n        self.view.hide_dialog()\n        self.view.show_dialog(f'{str(error)}\\n\\n{err} ', title='Decryption', auto_dismiss=True)\n\n    def show_warning(self, warning):\n        self.view.show_toast(f\"{warning}\")\n\n    @mainthread\n    def show_decryption_success(self, path):\n        self.view.show_toast(f\"Database decrypted successfully, the decrypted file is stored in {path}\")\n\n    @mainthread\n    def update_dialog(self, msg):\n        self.view.dialog.text = msg\n\n    @multitasking.task\n    def decrypt_dbs(self, key):\n        # decrypting msgstore\n        if self.view.app.wa_file is not None:\n            try:\n                self.update_dialog(\"Decrypting wa.db ...\")\n                enc_db = self.view.app.wa_file\n                dec_db = enc_db + '-decrypted.db'\n                self.decrypt_db(key, enc_db, dec_db)\n                self.view.app.wa_file = dec_db\n                self.show_decryption_success(dec_db)\n            except Exception as e:\n                self.show_decryption_error(e)\n                os.remove(dec_db)\n        try:\n            self.update_dialog(\"Decrypting msgstore.db ...\")\n            enc_db = self.view.app.msgstore_file\n            dec_db = enc_db + '-decrypted.db'\n            self.decrypt_db(key, enc_db, dec_db)\n            self.view.app.msgstore_file = dec_db\n            self.show_decryption_success(dec_db)\n            self.login()\n        except Exception as e:\n            self.show_decryption_error(e)\n            os.remove(dec_db)\n\n    def decrypt_db(self, key, enc_db, dec_db):\n        from decryption.dbs.decrypt_db import decrypt_db\n        decrypt_db(keyfile=key, encrypted=enc_db, decrypted=dec_db)\n        if not check_path(dec_db):\n            raise Exception('Decryption error\\nNo decrypted database was found in path')\n        self.show_decryption_success(dec_db)\n\n    def on_tap_button_login(self) -> NoReturn:\n        \"\"\"Called when the `LOGIN` button is pressed.\"\"\"\n        self.view.show_dialog('Login ...', title='Please wait ...', auto_dismiss=False)\n        self.view.app.msgstore_file = None if self.view.ids['msgstore_file_path'].text == '' else strip_quotes(self.view.ids[\n            'msgstore_file_path'].text)\n        self.view.app.wa_file = None if self.view.ids['wa_file_path'].text == '' else strip_quotes(self.view.ids['wa_file_path'].text)\n        self.view.app.wp_dir = None if self.view.ids['wp_dir'].text == '' else strip_quotes(self.view.ids['wp_dir'].text)\n        if not self.check_files():\n            return\n\n        if self.view.ids['enc_checkbox'].active:\n            # decrypt first\n            key = strip_quotes(self.view.key_file_widget.text)\n            if key == '':\n                self.view.show_dialog('Encrypted database is selected but no key has been provided!', title='Error',\n                                      auto_dismiss=True)\n                return\n            else:\n                # trying to decrypt\n                self.view.show_dialog('Trying to decrypt ...', title='Please wait ...', auto_dismiss=False)\n                self.decrypt_dbs(key)\n        else:\n            self.login()\n"
  },
  {
    "path": "Controller/main_screen.py",
    "content": "import importlib\nfrom typing import NoReturn\nimport View.MainScreen.main_screen\nimport View.screens\n\n# We have to manually reload the view module in order to apply the\n# changes made to the code on a subsequent hot reload.\n# If you no longer need a hot reload, you can delete this instruction.\nimportlib.reload(View.MainScreen.main_screen)\n\n\nclass MainScreenController:\n    \"\"\"\n    The `MainScreenController` class represents a controller implementation.\n    Coordinates work of the view with the model.\n    The controller implements the strategy pattern. The controller connects to\n    the view to control its actions.\n    \"\"\"\n\n    def __init__(self, model):\n        self.model = model  # Model.main_screen.MainScreenModel\n        self.view = View.MainScreen.main_screen.MainScreenView(controller=self, model=self.model)\n\n    def get_view(self) -> View.MainScreen.main_screen:\n        return self.view\n\n    def on_tap_button_login(self) -> NoReturn:\n        \"\"\"Called when the `LOGIN` button is pressed.\"\"\"\n        self.view.show_dialog_wait()\n\n    def on_enter(self, *args):\n        self.view.show_dialog_wait()\n        contact_chats = self.model.get_contact_chats()\n        self.view.show_chats_list(contact_chats)\n        group_chats = self.model.get_group_chats()\n        self.view.build_group_chat_list(group_chats)\n        calls = self.model.get_calls(how_many=self.view.app.call_log_size)\n        self.view.build_calls_list(calls)\n        self.view.dialog.dismiss()\n\n    def show_chat_screen(self, chat_id, user, jid):\n        self.view.app.selected_chat_id = chat_id\n        self.view.app.selected_user = user\n        self.view.app.status = self.model.get_status(jid)\n        self.view.app.screens_manager.current = \"chat screen\"\n\n    def clear_session(self):\n        for screen in View.screens.screens:\n            if screen == 'login screen':\n                continue\n            self.view.screens_manager.remove_widget(self.view.screens_manager.get_screen(screen))\n\n    def log_out(self, *args):\n        print('Logging out ...')\n        self.view.app.screens_manager.current = 'login screen'\n        # clear\n        self.clear_session()\n"
  },
  {
    "path": "Controller/template_screen.py",
    "content": "import importlib\nfrom typing import NoReturn\n\nimport View.TemplateScreen.template_screen\n\n# We have to manually reload the view module in order to apply the\n# changes made to the code on a subsequent hot reload.\n# If you no longer need a hot reload, you can delete this instruction.\nimportlib.reload(View.TemplateScreen.template_screen)\n\nfrom kivymd.tools.hotreload.app import MDApp\n\n\nclass TemplateScreenController:\n    \"\"\"\n    The `MainScreenController` class represents a controller implementation.\n    Coordinates work of the view with the model.\n    The controller implements the strategy pattern. The controller connects to\n    the view to control its actions.\n    \"\"\"\n\n    def __init__(self, model):\n        self.model = model  # Model.main_screen.MainScreenModel\n        self.view = View.TemplateScreen.template_screen.TemplateScreenView(controller=self, model=self.model)\n        self.app = MDApp.get_running_app()\n\n    def get_view(self) -> View.TemplateScreen.template_screen:\n        return self.view\n\n    def on_tap_button_login(self) -> NoReturn:\n        \"\"\"Called when the `LOGIN` button is pressed.\"\"\"\n        self.view.show_dialog_wait()\n        # self.app.screens_manager.current = \"main screen\""
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "Model/__init__.py",
    "content": ""
  },
  {
    "path": "Model/base_model.py",
    "content": "# The model implements the observer pattern. This means that the class must\n# support adding, removing, and alerting observers. In this case, the model is\n# completely independent of controllers and views. It is important that all\n# registered observers implement a specific method that will be called by the\n# model when they are notified (in this case, it is the `model_is_changed`\n# method). For this, observers must be descendants of an abstract class,\n# inheriting which, the `model_is_changed` method must be overridden.\n\n\nclass BaseScreenModel:\n    \"\"\"Implements a base class for model modules.\"\"\"\n\n    _observers = []\n\n    def add_observer(self, observer) -> None:\n        self._observers.append(observer)\n\n    def remove_observer(self, observer) -> None:\n        self._observers.remove(observer)\n\n    def notify_observers(self, name_screen: str) -> None:\n        \"\"\"\n        Method that will be called by the observer when the model data changes.\n\n        :param name_screen:\n            name of the view for which the method should be called\n            :meth:`model_is_changed`.\n        \"\"\"\n        for observer in self._observers:\n            if observer.name == name_screen:\n                observer.model_is_changed()\n                break\n"
  },
  {
    "path": "Model/chat_screen.py",
    "content": "from Model.base_model import BaseScreenModel\nfrom dbs.abstract_db import AbstractDatabase\n\n\nclass ChatScreenModel(BaseScreenModel):\n    \"\"\"\n    Implements the logic of the\n    :class:`~View.main_screen.ChatScreen.ChatScreenView` class.\n    \"\"\"\n    def __init__(self, base):\n        self.base: AbstractDatabase = base\n\n    def get_chat(self, chat_id):\n        return self.base.fetch_chat(chat_id)\n"
  },
  {
    "path": "Model/login_screen.py",
    "content": "from Model.base_model import BaseScreenModel\n\n\nclass LoginScreenModel(BaseScreenModel):\n    def __init__(self, base):\n        self.base = base\n        self._observers = []\n"
  },
  {
    "path": "Model/main_screen.py",
    "content": "from Model.base_model import BaseScreenModel\nfrom dbs.abstract_db import AbstractDatabase\n\n\nclass MainScreenModel(BaseScreenModel):\n    \"\"\"\n    Implements the logic of the\n    :class:`~View.main_screen.MainScreen.MainScreenView` class.\n    \"\"\"\n\n    def __init__(self, base):\n        self.base: AbstractDatabase = base\n\n    def set_base(self, base):\n        self.base = base\n\n    def get_contact_chats(self):\n        contact_chat_list = self.base.fetch_contact_chats()\n        if self.base.contacts is not None:\n            for contact_chat in contact_chat_list:\n                raw_jid = contact_chat.get('raw_string_jid')\n                if raw_jid in self.base.contacts:\n                    display_name = self.base.contacts[raw_jid].get('display_name', '')\n                    if display_name:\n                        contact_chat['user'] = f\"{display_name} <{contact_chat['user']}>\"\n                    else:\n                        contact_chat['user'] = f\"{contact_chat['user']}\"\n                else:\n                    print(f\"Contact {raw_jid} does not exist\")\n        return contact_chat_list\n\n    def get_group_chats(self):\n        group_chat_list = self.base.fetch_group_chats()\n        return group_chat_list\n\n    def get_calls(self, how_many=None):\n        calls = self.base.fetch_calls(how_many)\n        if self.base.contacts is not None:\n            # users with their display names\n            for call in calls:\n                try:\n                    call['user'] = self.base.contacts[call['raw_string']]['display_name'] + \\\n                                           f\" <{call['user']}> \"\n\n                except KeyError:\n                    pass  # already mentioned\n\n        return calls\n\n    def get_status(self, jid):\n        try:\n            st = self.base.contacts[jid]['status']\n            if st is not None:\n                return st\n            else:\n                raise KeyError\n        except Exception:\n            return \"<No Status>\"\n"
  },
  {
    "path": "Model/template_screen.py",
    "content": "from Model.base_model import BaseScreenModel\n\n\nclass TemplateScreenModel(BaseScreenModel):\n    \"\"\"\n    Implements the logic of the\n    :class:`~View.main_screen.MainScreen.MainScreenView` class.\n    \"\"\"\n    def __init__(self, base):\n        self.base = base"
  },
  {
    "path": "README.md",
    "content": "# whatsapp Msgstore Viewer\nFree, open source and cross-platform app to decrypt, read and view the Whatsapp `msgstore.db` database.\n<br/>\n<p align=\"center\">\n  <img src=\"./assets/demo/demo_gif_2.gif\">\n</p>\n\n# Features\n* View contact and group chats.\n* View call logs with their durations.\n* Easy access to media files (images, audio, and video) from within the chat, if the local WhatsApp directory has been provided.\n* Decrypt and view the database if you have the decryption `key` (Should support **crypt12**, **crypt14**, and **crypt15**).\n* Cross-platform (Should work on Linux, Windows, and Mac)\n\n\n# Installation\n### Prerequisites\n- Python 3.9 or later\n```bash\ngit clone https://github.com/absadiki/whatsapp-msgstore-viewer\ncd whatsapp-msgstore-viewer\npip install -e .\n```\n\n### Run\n```bash\nwmv\n```\n\n> **Note for Ubuntu users:** Additional system dependencies might be needed. See [#19](https://github.com/absadiki/whatsapp-msgstore-viewer/issues/19) for details.\n\n# Usage\nTo use the app, you will need:\n* The `msgstore.db` (`msgstore.db.cryptX` if it is encrypted) database: It is a database where Whatsapp is storing all your messages.\n* The `wa.db` database: It is a database where Whatsapp is storing contact names. It is optional, so if it is not provided you will just see phone numbers.\n* The `WhatsApp directory`: The directory of WhatsApp in the local storage of your phone. This will be used to view the media files (Optional as well).\n* The `key`: If your database is encrypted, you will need to provide the decryption key to decrypt it. The decrypted database will be stored in the same directory as your encrypted database with a `-decrypted.db` suffix.\n  (See below for more information).\n\n# Notes\n#### Where to find the databases\nCheck out the great tutorial \"[Retrieving WhatsApp Databases](https://github.com/Dexter2389/whatsapp-backup-chat-viewer#retrieving-whatsapp-databases)\" by [@Dexter2389](https://github.com/Dexter2389).\n\n#### About the decryption process\nThe app uses the [WhatsApp-Crypt14-Crypt15-Decrypter](https://github.com/ElDavoo/WhatsApp-Crypt14-Crypt15-Decrypter) by [ElDavoo](https://github.com/ElDavoo) under the hood.\nPlease check their repository if you face any issues with the decryption.\n\n#### About the Database schema\nThis app is a reverse engineering attempt of the WhatsApp database and has been tested with my personal `msgstore.db` file. It might break if there are any updates to the `msgstore` database schema.\n\nI've made it easy to add support for more schemas (It's a simple SQLite exercise :D).\n\nAll contributions are welcome.\n\nFollow these steps to add support for other schemas (see `db/v1/db.py` as an example):\n* Create a package in the `dbs` package and give your schema a name (for example `v2`).\n* Inside the newly created package, create a Python module `db.py`.\n* Inherit the abstract class `AbstractDatabase` located in the `dbs/abstract_db.py` module.\n* The app will dynamically load existing schemas when starting.\n* Submit a pull request.\n\n#### About different languages\n\n  - You might encounter an issue where messages are displayed incorrectly (as square characters).\n  This is likely a font issue. To resolve this, find a font that supports your language and specify its path in the `advanced settings` on the login screen.\n  - For RTL languages, please see [RTL Support #8](https://github.com/absadiki/whatsapp-msgstore-viewer/discussions/8)\n\n# Contributing\nIf you find a bug, have a suggestion or feedback, please open an issue for discussion.\n\n\n# License\n\nThis project is licensed under the GNU General Public License version 3 or later. You can modify or redistribute it under the conditions\nof these licenses (See [LICENSE](./LICENSE) for more information).\n\n# DISCLAIMER\nThis project is not endorsed or certified by WhatsApp Inc. and is meant for **personal and educational purposes only**.\n\nIt is provided 'as is' without any express or implied warranties.\n\nThe authors, maintainers, and contributors assume no responsibility for errors, omissions, or damages resulting from the use of this information.\n"
  },
  {
    "path": "Utility/Utils.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nHelper functions\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU General Public License as published by the Free Software\nFoundation, either version 3 of the License, or (at your option) any later\nversion.\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\nYou should have received a copy of the GNU General Public License along with\nthis program. If not, see <http://www.gnu.org/licenses/>.\n\"\"\"\n\nimport os\nimport emoji\n\n\ndef fix_emojis(text, font):\n    def add_font(chars, data_dict):\n        return f\"[font={font}]{chars}[/font]\"\n\n    res = emoji.replace_emoji(text, replace=add_font)\n    return res\n\ndef strip_quotes(path):\n    if path.startswith('\"') and path.endswith('\"'):\n        return path[1:-1]\n    return path\n\ndef check_path(path=None):\n    if path is None:\n        return True\n    else:\n        return os.path.exists(path)\n\n\nif __name__ == '__main__':\n    pass\n"
  },
  {
    "path": "Utility/__init__.py",
    "content": ""
  },
  {
    "path": "Utility/observer.py",
    "content": "\n# Of course, \"very flexible Python\" allows you to do without an abstract\n# superclass at all or use the clever exception `NotImplementedError`. In my\n# opinion, this can negatively affect the architecture of the application.\n# I would like to point out that using Kivy, one could use the on-signaling\n# model. In this case, when the state changes, the model will send a signal\n# that can be received by all attached observers. This approach seems less\n# universal - you may want to use a different library in the future.\n\n\nclass Observer:\n    \"\"\"Abstract superclass for all observers.\"\"\"\n\n    def model_is_changed(self):\n        \"\"\"\n        The method that will be called on the observer when the model changes.\n        \"\"\"\n"
  },
  {
    "path": "View/ChatScreen/__init__.py",
    "content": ""
  },
  {
    "path": "View/ChatScreen/chat_screen.kv",
    "content": "#:import hex kivy.utils.get_color_from_hex\n\n<ChatScreenView>:\n    FitImage:\n        source: \"assets/images/bg.png\"\n        pos: self.pos\n        size: self.size\n    MDBoxLayout:\n        orientation: \"vertical\"\n        MDBoxLayout:\n            size_hint_y: None\n            height: 50\n            spacing: 5\n            md_bg_color: app.theme_cls.primary_color\n            padding: [0, 0, 10, 0]\n            MDIconButton:\n                icon: 'arrow-left'\n                theme_text_color: 'Custom'\n                user_font_size: 18\n                size_hint: (None, None)\n                pos_hint: {'center_y':.5}\n                size: 30, 30\n                padding: 0\n                pos_hint: {'center_y':.5}\n                on_press: root.controller.previous_screen()\n            MDBoxLayout:\n                size_hint: None, None\n                size: 30, 30\n                orientation: 'vertical'\n                pos_hint: {'center_y': .5}\n                Avatar:\n                    source: 'assets/images/avatar.png'\n                    size: 30, 30\n                    size_hint: None, None\n            MDBoxLayout:\n                orientation: \"vertical\"\n                padding: [0, 10, 0, 10]\n                MLabel:\n                    markup: True\n                    text: root.selected_user\n                    size: self.texture_size\n                    size_hint_y: None\n                    size_hint_x: None\n                    font_size: 12\n                    bold: True\n                    adaptive_size: True\n                MDBoxLayout:\n                    size_hint_x: None\n                    spacing: 5\n                    MDIcon:\n                        icon: 'circle'\n                        theme_text_color: 'Custom'\n                        color: [0, 1, 0, 1] if root.active == True else [.5, .5, .5, 1]\n                        font_size: 10\n                        size: 10, 10\n                        size_hint: None, None\n                    MLabel:\n                        text: root.status\n                        size: self.texture_size\n                        size_hint_y: None\n                        size_hint_x: None\n                        font_size: 10\n                        color: app.theme_cls.opposite_bg_normal\n                        adaptive_size: True\n        RV:\n            id: rv\n            viewclass: 'ChatMessage'\n            size_hint_y: 0.9\n            key_size: 'size'\n            effect_cls: 'ScrollEffect'\n            bar_width: 10\n            scroll_type: ['content', 'bars']\n            RecycleBoxLayout:\n                id: rvbox\n                orientation: 'vertical'\n                size_hint_y: None\n                height: self.minimum_height\n                default_size_hint: 1, None\n                padding: 10\n                spacing: 5"
  },
  {
    "path": "View/ChatScreen/chat_screen.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nChat Screen\n\"\"\"\n\nimport os\nfrom typing import NoReturn\nfrom PIL import Image\nfrom kivy.uix.behaviors import ButtonBehavior\nfrom kivy.properties import OptionProperty, StringProperty, DictProperty, NumericProperty, ObjectProperty\nfrom kivy.uix.recycleview import RecycleView\nfrom kivy.uix.recycleview.views import RecycleDataViewBehavior\nfrom kivymd.app import MDApp\nfrom kivymd.uix.boxlayout import MDBoxLayout\nfrom kivymd.uix.dialog import MDDialog\nfrom kivymd.uix.behaviors import RectangularRippleBehavior, CommonElevationBehavior\nfrom kivymd.uix.spinner import MDSpinner\nfrom Utility.Utils import fix_emojis, check_path\nfrom View.MainScreen.main_screen import MLabel\nfrom View.base_screen import BaseScreenView\nimport webbrowser\nfrom kivy.clock import Clock\n\nclass RV(RecycleView):\n    def __init__(self, **kwargs):\n        super().__init__(**kwargs)\n\n\nclass Attachment(ButtonBehavior, RectangularRippleBehavior, CommonElevationBehavior, MLabel):\n    def __init__(self, **kwargs):\n        super().__init__(**kwargs)\n\n\nclass Quote(MLabel):\n    def __init__(self, **kwargs):\n        super().__init__(**kwargs)\n\n\nclass ChatMessage(RecycleDataViewBehavior, MDBoxLayout):\n    index = 0\n    txt_data = StringProperty()\n    from_me = NumericProperty()  # 1 -> me;\n    timestamp = StringProperty()\n    media_filename = StringProperty()\n    file_path = ObjectProperty(allownone=True)\n    text_width = NumericProperty()\n    msg_quoted_text_data = StringProperty()\n    message_quoted_from_me = NumericProperty(allownone=True)\n    dialog = None\n\n    def dialog_dismiss(self):\n        del self.dialog\n\n    def hide_dialog(self):\n        self.dialog.dismiss()\n\n    def show_dialog(self, msg, title=None, auto_dismiss=True) -> NoReturn:\n        \"\"\"Displays a wait dialog while the model is processing data.\"\"\"\n        self.dialog = MDDialog(title='Login', radius=[20, 7, 20, 7])\n        self.dialog.bind(on_dismiss=lambda x: self.dialog_dismiss())\n        self.dialog.auto_dismiss = auto_dismiss\n        if title:\n            self.dialog.title = title + '\\n'\n        self.dialog.text = msg\n        if not auto_dismiss:\n            progress = MDSpinner(determinate=False, size_hint=(None, None), size=(48, 48), pos_hint={'right: 1'})\n            self.dialog.add_widget(progress)\n        self.dialog.open()\n\n    def open_media(self, file_path):\n        print(f'Opening {file_path}')\n        if MDApp.get_running_app().wp_dir is None:\n            self.show_dialog(msg='No Whatsapp directory has been provided.\\n'\n                                 'To View this file, provide the `Whatsapp directory path` in the login screen', title='Error')\n            return\n        path = os.path.join(MDApp.get_running_app().wp_dir, file_path)\n        if not check_path(path):\n            self.show_dialog(msg=f'{path}\\n'\n                                 'Does not exist, Maybe the file was removed or you provided an incorrect'\n                                 '`Whatsapp directory path`',\n                             title='Error')\n            return\n        webbrowser.open(path)\n\n    def get_msg_widget(self):\n        return self.ids['msg_content']\n\n    def refresh_view_attrs(self, rv, index, data):\n        self.index = index\n        self.txt_data = fix_emojis(data['text_data'], MDApp.get_running_app().emojis_font)\n        if data['file_path'] is not None:\n            self.media_filename = data['file_path'].split('/')[-1]\n        else:\n            self.media_filename = ''\n\n        if data['message_quoted_text_data'] is not None:\n            self.msg_quoted_text_data = fix_emojis(data['message_quoted_text_data'], MDApp.get_running_app().emojis_font)\n        else:\n            self.msg_quoted_text_data = ''\n\n        return super().refresh_view_attrs(rv, index, data)\n\n    def refresh_view_layout(self, rv, index, layout, viewport):\n        return super().refresh_view_layout(rv, index, layout, viewport)\n\n\nclass ChatScreenView(BaseScreenView):\n    active = True\n    text = 'text'\n    image = 'image'\n    selected_user = StringProperty()\n    status = StringProperty()\n\n    def __init__(self, **kw):\n        super(ChatScreenView, self).__init__(**kw)\n        self.dialog = MDDialog()\n        self.dialog.bind(on_dismiss=lambda x: print('run something on dialog dismissed'))\n        self.image = 'image'\n        self.selected_user = self.app.selected_user\n\n    def dialog_dismiss(self):\n        del self.dialog\n\n    def hide_dialog(self):\n        self.dialog.dismiss()\n\n    def show_dialog(self, msg, title=None, auto_dismiss=True) -> NoReturn:\n        self.dialog = MDDialog(title='Login', radius=[20, 7, 20, 7])\n        self.dialog.bind(on_dismiss=lambda x: self.dialog_dismiss())\n        self.dialog.auto_dismiss = auto_dismiss\n        if title:\n            self.dialog.title = title + '\\n'\n        self.dialog.text = msg\n        if not auto_dismiss:\n            progress = MDSpinner(determinate=False, size_hint=(None, None), size=(48, 48), pos_hint={'right: 1'})\n            self.dialog.add_widget(progress)\n        self.dialog.open()\n\n    def show_chat_messages(self, chat_messages):\n        self.ids.rvbox.clear_widgets()\n        self.ids.rv.data = chat_messages\n\n        Clock.schedule_once(lambda dt: self.scroll_to_bottom(), 0)\n        \n    def scroll_to_bottom(self):\n        self.ids.rv.scroll_y = 0 \n\n    def model_is_changed(self) -> None:\n        \"\"\"\n        Called whenever any change has occurred in the data model.\n        The view in this method tracks these changes and updates the UI\n        according to these changes.\n        \"\"\"\n"
  },
  {
    "path": "View/LoginScreen/__init__.py",
    "content": ""
  },
  {
    "path": "View/LoginScreen/about.kv",
    "content": "#:import hex kivy.utils.get_color_from_hex\n\n<About>\n    size_hint_y: None\n    height: \"400dp\"\n    MDTabs:\n        tab_indicator_anim: True\n        tab_indicator_height: 5\n        tab_hint_x: True\n        allow_stretch: True\n        background_color: app.theme_cls.accent_color\n        indicator_color: app.theme_cls.primary_color\n        Tab:\n            title: \"About\"\n            ScrollView:\n                do_scroll_y: True\n                bar_width: 10\n                MDBoxLayout:\n                    orientation: 'vertical'\n                    md_bg_color: app.theme_cls.bg_normal\n                    size_hint_y: None\n                    adaptive_height: True\n                    padding: [10, 10, 10, 10]\n                    MDLabel:\n                        id: about_label\n                        markup: True\n                        adaptive_height: True\n                        text: root.about\n        Tab:\n            title: \"License\"\n            ScrollView:\n                do_scroll_y: True\n                bar_width: 10\n\n                MDBoxLayout:\n                    orientation: 'vertical'\n                    md_bg_color: app.theme_cls.bg_normal\n                    size_hint_y: None\n                    adaptive_height: True\n                    padding: [10, 10, 10, 10]\n                    MDLabel:\n                        markup: True\n                        adaptive_size: True\n                        text: root.license"
  },
  {
    "path": "View/LoginScreen/login_screen.kv",
    "content": "<LoginScreenView>\n    FitImage:\n        source: \"assets/images/bg.png\"\n    MDBoxLayout:\n        orientation: \"vertical\"\n        spacing: 15\n        FitImage:\n            source: \"assets/images/logo.png\"\n            padding: 4\n            pos_hint: {\"center_x\": .5, \"center_y\": .5}\n            size_hint: None, None\n        MDLabel:\n            id: app_name\n            text: \"Whatsapp Msgstore Viewer\"\n            font_style: \"H5\"\n            adaptive_height: True\n            halign: \"center\"\n        MDRectangleFlatIconButton:\n            text: \"Check the source code on Github\"\n            icon: \"github\"\n            pos_hint: {\"center_x\": .5, \"center_y\": .5}\n            size_hint: None, None\n            on_press: root.open_github_page()\n        MDFloatLayout:\n            MDBoxLayout:\n                orientation: \"vertical\"\n                adaptive_height: True\n                size_hint_x: None\n                width: root.width - dp(72)\n                radius: 12\n                padding: \"12dp\"\n                md_bg_color: 1, 1, 1, .5\n                pos_hint: {\"center_x\": .5, \"center_y\": .5}\n                MDBoxLayout:\n                    orientation: \"vertical\"\n                    adaptive_height: True\n                    padding: \"25dp\"\n                    spacing: \"20dp\"\n                    TextFieldFileManager:\n                        id: msgstore_file_path\n                        hint_text: \"msgstore.db file path\"\n                        pos_hint: {\"center_x\": .5, \"center_y\": .5}\n                    TextFieldFileManager:\n                        id: wa_file_path\n                        hint_text: \"wa.db file path (Optional)\"\n                        pos_hint: {\"center_x\": .5, \"center_y\": .5}\n                        helper_text: \"To view contact names instead of just their numbers\"\n                    TextFieldFileManager:\n                        id: wp_dir\n                        hint_text: \"`Whatsapp` Directory (Optional)\"\n                        pos_hint: {\"center_x\": .5, \"center_y\": .5}\n                        helper_text: \"In case you want to view the media in the chat (audios, videos, images ...), leave it blank otherwise\"\n                    MDTextField:\n                        id: db_version\n                        pos_hint: {'center_x': .5, 'center_y': .5}\n                        text: app.db_version\n                        hint_text: \"Database version\"\n                        readonly: True\n                        on_focus: if self.focus: root.menu.open()\n                        helper_text: 'Check the github page for more details'\n                    MDBoxLayout:\n                        id: key_file_container\n                        orientation: 'horizontal'\n                        MDCheckbox:\n                            id: enc_checkbox\n                            size_hint: None, None\n                            size: \"48dp\", \"48dp\"\n                            pos_hint: {'center_x': .5, 'center_y': .5}\n                            on_active: root.on_enc_checkbox(self.active)\n                        MDLabel:\n                            markup: True\n                            text: \"Encrypted database\"\n                            font_style: \"Body2\"\n                            valign: \"center\"\n                            theme_text_color: 'Secondary'\n                    MDRoundFlatButton:\n                        text: \"Advanced settings\"\n                        on_release: root.open_settings()\n\n    MDFillRoundFlatButton:\n        text: \"LOGIN\" if not enc_checkbox.active else 'DECRYPT & LOGIN'\n        on_release: root.controller.on_tap_button_login()\n        pos_hint: {\"center_x\": .5, \"center_y\": .1}\n\n    Attachment:\n        # not an attachment but same ui attributes\n        markup: True\n        text: \"[ref=about]About[/ref]\"\n        adaptive_height: True\n        halign: \"center\"\n        theme_text_color: 'Secondary'\n        padding_y: dp(10)\n        pos_hint: {\"center_x\": .5, \"center_y\": 0.025}\n        on_ref_press: root.open_about()\n\n\n\n"
  },
  {
    "path": "View/LoginScreen/login_screen.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nLogin screen\n\"\"\"\n\nimport os\nimport webbrowser\nfrom typing import NoReturn\nfrom kivy.metrics import dp\nfrom kivy.properties import StringProperty\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.scrollview import ScrollView\nfrom kivymd.app import MDApp\nfrom kivymd.toast import toast\nfrom kivymd.uix.button import MDFlatButton, MDRaisedButton\nfrom kivymd.uix.dialog import MDDialog\nfrom kivymd.uix.filemanager import MDFileManager\nfrom kivymd.uix.menu import MDDropdownMenu\nfrom kivymd.uix.relativelayout import MDRelativeLayout\nfrom kivymd.uix.spinner import MDSpinner\nfrom Utility.Utils import check_path\nfrom View.base_screen import BaseScreenView\nimport json\n\n\nclass TextFieldFileManager(MDRelativeLayout):\n    text = StringProperty()\n    hint_text = StringProperty()\n    helper_text = StringProperty()\n\n    def __init__(self, **kwargs):\n        super().__init__(**kwargs)\n        self.manager_open = False\n        self.file_manager = MDFileManager(\n            exit_manager=self.exit_manager, select_path=self.select_path\n        )\n\n    def file_manager_open(self):\n        self.file_manager.show(os.path.expanduser(\"~\"))  # output manager to the screen\n        self.manager_open = True\n\n    def select_path(self, path: str):\n        self.exit_manager()\n        toast(path)\n        self.text = path\n\n    def on_text(self, instance, value):\n        self.text = value\n\n    def exit_manager(self, *args):\n        self.manager_open = False\n        self.file_manager.close()\n\n    def events(self, instance, keyboard, keycode, text, modifiers):\n        '''Called when buttons are pressed on the mobile device.'''\n\n        if keyboard in (1001, 27):\n            if self.manager_open:\n                self.file_manager.back()\n        return True\n\n    def open_file_manager(self, hint_text):\n        self.file_manager.show(os.path.expanduser(\"~\"))  # output manager to the screen\n        self.manager_open = True\n\n\nclass SettingsContent(ScrollView):\n    pass\n\n\nclass About(BoxLayout):\n    about = StringProperty()\n    license = StringProperty()\n    credits = StringProperty()\n\n    def __init__(self, **kwargs):\n        super().__init__(**kwargs)\n        with open('about', 'r') as file:\n            content = file.read()\n            self.about = content.replace('$$version$$', MDApp.get_running_app().version)\\\n                .replace('$$g_page$$', MDApp.get_running_app().g_page)\n        with open('LICENSE', 'r') as file:\n            self.license = file.read()\n        with open('credits', 'r') as file:\n            self.credits = file.read()\n\n        self.ids.about_label.bind(on_ref_press=self.open_link)\n\n    def open_link(self, instance, link):\n        webbrowser.open(link)\n\n\nclass LoginScreenView(BaseScreenView):\n\n    def __init__(self, **kw):\n        super(LoginScreenView, self).__init__(**kw)\n        self.dialog = None\n        menu_items = [\n            {\n                \"viewclass\": \"OneLineListItem\",\n                \"height\": dp(56),\n                \"text\": f\"{version}\",\n                \"on_release\": lambda x=version: self.set_item(x),\n            }\n            for version in MDApp.get_running_app().db_versions\n        ]\n\n        self.menu = MDDropdownMenu(\n            caller=self.ids.db_version,\n            items=menu_items,\n            position=\"bottom\",\n            width_mult=4,\n        )\n\n        self.settings_content = SettingsContent()\n        self.settings_dialog = MDDialog(\n            title=\"Advanced Settings\",\n            type=\"custom\",\n            content_cls=self.settings_content,\n            buttons=[\n                MDFlatButton(\n                    text=\"CANCEL\",\n                    theme_text_color=\"Custom\",\n                    text_color=self.theme_cls.primary_color,\n                    on_release=self.settings_cancel\n                ),\n                MDRaisedButton(\n                    text=\"Save\",\n                    theme_text_color=\"Custom\",\n                    on_release=self.settings_save\n                ),\n            ],\n        )\n\n        self.about = About()\n        self.about_dialog = MDDialog(\n            title=\"About\",\n            type=\"custom\",\n            content_cls=self.about,\n        )\n\n        self.key_file_widget = TextFieldFileManager(id='key_file', hint_text=\"Key\",\n                            pos_hint={\"center_x\": .5, \"center_y\": .5},\n                            helper_text=\"To decrypt the database\")\n        \n        self.login_data_file = os.path.join(self.app.user_data_dir, \"login_data.json\")\n\n    def set_item(self, text__item):\n        self.ids.db_version.text = text__item\n        self.app.db_version = text__item\n        self.menu.dismiss()\n\n    def dialog_dismiss(self):\n        self.dialog = None\n\n    def hide_dialog(self):\n        if self.dialog is not None:\n            self.dialog.dismiss()\n\n    def show_dialog(self, msg, title=None, auto_dismiss=False) -> NoReturn:\n        \"\"\"Displays a wait dialog while the model is processing data.\"\"\"\n        self.hide_dialog()\n        self.dialog = MDDialog(title='Login', radius=[20, 7, 20, 7])\n        self.dialog.bind(on_dismiss=lambda x: self.dialog_dismiss())\n        self.dialog.auto_dismiss = auto_dismiss\n        if title:\n            self.dialog.title = title + '\\n'\n        self.dialog.text = msg\n        if auto_dismiss is False:\n            progress = MDSpinner(determinate=False, size_hint=(None, None), size=(48, 48), pos_hint={'right: 1'})\n            self.dialog.add_widget(progress)\n        self.dialog.open()\n\n    def on_enc_checkbox(self, state, *args):\n        if state:\n            self.ids.key_file_container.add_widget(self.key_file_widget)\n        else:\n            self.ids.key_file_container.remove_widget(self.key_file_widget)\n\n    def open_settings(self):\n        print('opening settings')\n        self.settings_dialog.open()\n\n    def settings_cancel(self, *args):\n        self.settings_dialog.dismiss()\n\n    def settings_save(self, *args):\n        general_font_path = self.settings_content.ids['general_font'].text\n        if general_font_path == '':\n            self.app.general_font = self.app.default_settings['general_font']\n        else:\n            if not check_path(general_font_path):\n                self.show_dialog(msg=f'The path `{general_font_path}` does not exist', title='General Font error',\n                                 auto_dismiss=True)\n                return\n            self.app.general_font = general_font_path\n\n        #  I am exhausted, I don't want to think of any other abstraction !! Let us do it stupidly\n        emojis_font_path = self.settings_content.ids['emojis_font'].text\n        if emojis_font_path == '':\n            self.app.emojis_font = self.app.default_settings['emojis_font']\n        else:\n            if not check_path(general_font_path):\n                self.show_dialog(msg=f'The path `{emojis_font_path}` does not exist', title='Emojis Font error',\n                                 auto_dismiss=True)\n                return\n            self.app.emojis_font = emojis_font_path\n\n        # call log size\n        call_log_size = self.settings_content.ids['call_log_size'].text\n        if call_log_size == '':\n            self.app.call_log_size = self.app.default_settings['call_log_size']\n        else:\n            try:\n                call_log_size_int = int(call_log_size)\n                self.app.call_log_size = call_log_size_int\n            except Exception as e:\n                self.show_dialog(msg=f'Call log size`{call_log_size}` is not a number', title='Calls log size error',\n                                 auto_dismiss=True)\n                return\n\n        self.settings_dialog.dismiss()\n        toast('Settings saved successfully')\n\n    def show_toast(self, msg):\n        toast(msg)\n\n    def open_about(self):\n        self.about_dialog.open()\n\n    def open_github_page(self):\n        webbrowser.open(self.app.g_page)\n\n    def model_is_changed(self) -> None:\n        \"\"\"\n        Called whenever any change has occurred in the data model.\n        The view in this method tracks these changes and updates the UI\n        according to these changes.\n        \"\"\"\n\n    def on_kv_post(self, base_widget):\n        self.ids.msgstore_file_path.bind(text=self.save_fields)\n        self.ids.wa_file_path.bind(text=self.save_fields)\n        self.ids.wp_dir.bind(text=self.save_fields)\n        self.ids.db_version.bind(text=self.save_fields)\n\n\n    def save_fields(self, *args):\n        data = {\n            'msgstore_file_path': self.ids.msgstore_file_path.text,\n            'wa_file_path': self.ids.wa_file_path.text,\n            'wp_dir': self.ids.wp_dir.text,\n            'db_version': self.ids.db_version.text\n        }\n        with open(self.login_data_file, \"w\") as f:\n            json.dump(data, f)\n    \n    def on_pre_enter(self, *args):\n        try:\n            with open(self.login_data_file, \"r\") as f:\n                data = json.load(f)\n                self.ids.msgstore_file_path.text = data.get('msgstore_file_path', '')\n                self.ids.wa_file_path.text = data.get('wa_file_path', '')\n                self.ids.wp_dir.text = data.get('wp_dir', '')\n                self.ids.db_version.text = data.get('db_version', '')\n                self.app.db_version = data.get('db_version', '')\n        except FileNotFoundError:\n            pass"
  },
  {
    "path": "View/LoginScreen/settings.kv",
    "content": "<SettingsContent>:\n    size_hint_y: None\n    height: \"300dp\"\n    bar_width: 10\n    scroll_type: ['content', 'bars']\n    BoxLayout:\n        size_hint_y: None\n        height: self.minimum_height\n        default_size_hint: 1, None\n        orientation: \"vertical\"\n        spacing: \"12dp\"\n        TextFieldFileManager:\n            id: general_font\n            hint_text: \"General font (Leave it blank to load the default font)\"\n            pos_hint: {\"center_x\": .5, \"center_y\": .5}\n            helper_text: \"In case you are seeing wierd characters, it is probably a font issue, \\ntry to load another one that supports your language\"\n        TextFieldFileManager:\n            id: emojis_font\n            hint_text: \"Emojis font (Leave it blank to load the default font)\"\n            pos_hint: {\"center_x\": .5, \"center_y\": .5}\n            helper_text: \"Load a different emojis font\"\n        MDTextField:\n            id: call_log_size\n            input_type: 'number'\n            hint_text: \"Calls log size\"\n            text: '10'\n            pos_hint: {\"center_x\": .5, \"center_y\": .5}\n            helper_text: \"Limit the loaded calls log size (for a fast loading of the app)\""
  },
  {
    "path": "View/MainScreen/__init__.py",
    "content": ""
  },
  {
    "path": "View/MainScreen/main_screen.kv",
    "content": "<MainScreenView>\n    MDBoxLayout:\n        orientation: \"vertical\"\n        MDTopAppBar:\n            id: logoToolBar\n            height: 50\n            anchor_title: 'left'\n            opposite_colors: True\n            title: \"Whatsapp\"\n            right_action_items: [['logout', root.controller.log_out, 'Log out']]\n            margin: 0\n        MDTabs:\n            tab_indicator_anim: True\n            tab_indicator_height: 5\n            tab_hint_x: True\n            allow_stretch: True\n            Tab:\n                title: \"Chats\"\n                RV:  \n                    id: contact_chat_list\n                    viewclass: 'ChatListItem'\n                    bar_width: 10\n                    scroll_type: ['content', 'bars']\n                    key_size: 'height'\n                    RecycleBoxLayout:\n                        default_size: None, dp(72)\n                        default_size_hint: 1, None\n                        size_hint_y: None\n                        height: self.minimum_height\n                        orientation: 'vertical'\n\n            Tab:\n                title: \"Groups\"\n                RV:  \n                    id: group_chat_list\n                    viewclass: 'ChatListItem'\n                    bar_width: 10\n                    scroll_type: ['content', 'bars']\n                    key_size: 'height'\n                    RecycleBoxLayout:\n                        default_size: None, dp(72)\n                        default_size_hint: 1, None\n                        size_hint_y: None\n                        height: self.minimum_height\n                        orientation: 'vertical'\n\n            Tab:\n                title: \"Calls\"\n                RV:  \n                    id: calls\n                    viewclass: 'CallListItem'\n                    bar_width: 10\n                    scroll_type: ['content', 'bars']\n                    key_size: 'height'\n                    RecycleBoxLayout:\n                        default_size: None, dp(72) \n                        default_size_hint: 1, None\n                        size_hint_y: None\n                        height: self.minimum_height\n                        orientation: 'vertical'\n\n\n\n"
  },
  {
    "path": "View/MainScreen/main_screen.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nMain Screen\n\"\"\"\n\nfrom typing import NoReturn\nfrom kivy.properties import StringProperty, NumericProperty, ObjectProperty\nfrom kivymd.uix.card import MDCard\nfrom kivymd.uix.dialog import MDDialog\nfrom kivymd.uix.floatlayout import MDFloatLayout\nfrom kivymd.uix.label import MDLabel\nfrom kivymd.uix.tab import MDTabsBase\nfrom Utility.Utils import fix_emojis\nfrom View.base_screen import BaseScreenView\n\nfrom kivy.uix.recycleview.views import RecycleDataViewBehavior\n\n\nclass Tab(MDFloatLayout, MDTabsBase):\n    pass\n\n\nclass MLabel(MDLabel):\n    def __init__(self, **kwargs):\n        super().__init__(**kwargs)\n\n\nclass ChatListItem(RecycleDataViewBehavior, MDCard):\n    controller = ObjectProperty()\n    id = ObjectProperty()\n    jid = StringProperty()\n    contact_name = StringProperty()\n    last_message = StringProperty()\n    timestamp = StringProperty()\n\n\nclass CallListItem(RecycleDataViewBehavior, MDCard):\n    # controller = ObjectProperty()\n    id = ObjectProperty()\n    jid = StringProperty()\n    user = StringProperty()\n    from_me = NumericProperty()\n    timestamp = StringProperty()\n    video_call = NumericProperty()\n    duration = StringProperty()\n\n\nclass MainScreenView(BaseScreenView):\n\n    def __init__(self, **kw):\n        super(MainScreenView, self).__init__(**kw)\n        self.dialog = MDDialog()\n\n    def show_dialog_wait(self) -> NoReturn:\n        \"\"\"Displays a wait dialog while the model is processing data.\"\"\"\n        self.dialog.auto_dismiss = True\n        self.dialog.text = \"Loading ...\"\n        self.dialog.open()\n\n    def model_is_changed(self) -> None:\n        \"\"\"\n        Called whenever any change has occurred in the data model.\n        The view in this method tracks these changes and updates the UI\n        according to these changes.\n        \"\"\"\n        pass\n\n    def show_chats_list(self, contact_chats):\n        self.ids.contact_chat_list.data = [{\n            'controller': self.controller,\n            'id': chat['_id'],\n            'contact_name': chat[\"user\"],\n            'last_message': fix_emojis(chat['text_data'], self.app.emojis_font) if chat['text_data'] else '',\n            'timestamp': '\\n'.join(chat['timestamp'].split(' ')),\n            'jid': chat['raw_string_jid'],\n        } for chat in contact_chats]\n\n    def build_group_chat_list(self, group_chats):\n        self.ids.group_chat_list.data = [{\n            'id': chat['_id'],\n            'contact_name': fix_emojis(chat['user'], self.app.emojis_font),\n            'last_message': fix_emojis(chat['text_data'], self.app.emojis_font) if chat['text_data'] else '',\n            'timestamp': '\\n'.join(chat['timestamp'].split(' ')),\n            'controller': self.controller,\n        } for chat in group_chats]\n\n    def build_calls_list(self, calls):\n        self.ids.calls.data = [{\n            'id': call['_id'],\n            'jid': call['raw_string_jid'],\n            'user': fix_emojis(call['user'], self.app.emojis_font),\n            'from_me': call['from_me'],\n            'video_call': call['video_call'],\n            'timestamp': call['timestamp'],\n            'duration': str(call['duration']),\n        } for call in calls]\n"
  },
  {
    "path": "View/base_screen.py",
    "content": "from kivy.properties import ObjectProperty\n\nfrom kivymd.app import MDApp\nfrom kivymd.uix.screen import MDScreen\n\nfrom Utility.observer import Observer\n\n\nclass BaseScreenView(MDScreen, Observer):\n    \"\"\"\n    A base class that implements a visual representation of the model data.\n    The view class must be inherited from this class.\n    \"\"\"\n\n    controller = ObjectProperty()\n    \"\"\"\n    Controller object - :class:`~Controller.controller_screen.ClassScreenController`.\n\n    :attr:`controller` is an :class:`~kivy.properties.ObjectProperty`\n    and defaults to `None`.\n    \"\"\"\n\n    model = ObjectProperty()\n    \"\"\"\n    Model object - :class:`~Model.model_screen.ClassScreenModel`.\n\n    :attr:`model` is an :class:`~kivy.properties.ObjectProperty`\n    and defaults to `None`.\n    \"\"\"\n\n    manager_screens = ObjectProperty()\n    \"\"\"\n    Screen manager object - :class:`~kivymd.uix.screenmanager.MDScreenManager`.\n\n    :attr:`manager_screens` is an :class:`~kivy.properties.ObjectProperty`\n    and defaults to `None`.\n    \"\"\"\n\n    def __init__(self, **kw):\n        super().__init__(**kw)\n        # Often you need to get access to the application object from the view\n        # class. You can do this using this attribute.\n        self.app = MDApp.get_running_app()\n        # Adding a view class as observer.\n        self.model.add_observer(self)\n"
  },
  {
    "path": "View/components/MLabel.kv",
    "content": "<MLabel>:\n    markup: True\n    font_name: app.general_font\n\n"
  },
  {
    "path": "View/components/__init__.py",
    "content": ""
  },
  {
    "path": "View/components/attachment.kv",
    "content": "<Attachment>:\n    markup: True\n    color: (0,0,1,1)\n"
  },
  {
    "path": "View/components/avatar.kv",
    "content": "<Avatar@RelativeLayout>:\r\n    size: (45, 45)\r\n    size_hint: (None, None)\r\n    source: root.source\r\n    MDCard:\r\n        size: root.size\r\n        size_hint: (None, None)\r\n        radius: [30, ]\r\n        md_bg_color: app.theme_cls.accent_color\r\n        elevation: 0\r\n        pos_hint: {'center_x': .5, 'center_y': .5}\r\n\r\n    FitImage:\r\n        size: root.size[0] - 3, root.size[1]-3\r\n        radius: [30, ]\r\n        size_hint: (None, None)\r\n        source: root.source\r\n        pos_hint: {'center_x': .5, 'center_y': .5}"
  },
  {
    "path": "View/components/call_list_item.kv",
    "content": "<CallListItem>:\r\n    ripple_behavior: True\r\n    md_bg_color: 0, 0, 0, 0\r\n    elevation: 0\r\n    size_hint_y: None\r\n    padding: [10, 0, 10, 0]\r\n    spacing: 10\r\n    height: avatar.height + 10\r\n    Avatar:\r\n        id: avatar\r\n        source: 'assets/images/avatar.png'\r\n        pos_hint: {\"center_y\": .5}\r\n        radius: [30, ]\r\n    MDBoxLayout:\r\n        # md_bg_color: 1, 0, 1, 1\r\n        orientation: \"vertical\"\r\n        padding: [0, 0, 0, 10]\r\n        spacing: 2\r\n        Label:\r\n            markup: True\r\n            id: user_name\r\n            text: root.user\r\n            theme_text_color: 'Custom'\r\n            size: self.texture_size\r\n            size_hint_y: None\r\n            size_hint_x: None\r\n            font_size: 15\r\n            color: app.theme_cls.opposite_bg_normal\r\n            bold: True\r\n        MDBoxLayout:\r\n            orientation: \"horizontal\"\r\n#            padding: [0, 0, 0, 10]\r\n            spacing: 5\r\n            MDIcon:\r\n                id: out_in_call_icon\r\n                theme_text_color: 'Custom'\r\n                icon: 'arrow-top-right' if root.from_me == 1 else 'arrow-bottom-left'\r\n                size_hint: None, None\r\n                font_size: 18\r\n                size: 20, 20\r\n                pos_hint: {\"center_x\": .5, 'center_y': .5}\r\n                text_color: 'green' if root.from_me == 1 else 'red'\r\n            MLabel:\r\n                id: timestamp\r\n                text: root.timestamp\r\n                height: self.texture_size[1]\r\n                theme_text_color: 'Custom'\r\n                size_hint_y: None\r\n                bold: True\r\n                font_size: 15\r\n                shorten: True\r\n                markup: True\r\n                shorten_from: 'right'\r\n\r\n    MLabel:\r\n        id: call_duration\r\n        text: root.duration\r\n        height: self.texture_size[1]\r\n        theme_text_color: 'Custom'\r\n        adaptive_size: True\r\n        size_hint_y: None\r\n        pos_hint: {\"center_x\": .5, 'center_y': .5}\r\n        bold: True\r\n        font_size: 15\r\n        markup: True\r\n\r\n    MDIcon:\r\n        id: audio_video_icon\r\n        theme_text_color: 'Custom'\r\n        icon: 'video' if root.video_call == 1 else 'phone'\r\n        size_hint: None, None\r\n        font_size: 18\r\n        size: 20, 20\r\n        pos_hint: {\"center_x\": .5, 'center_y': .5}\r\n        text_color: app.theme_cls.primary_color\r\n"
  },
  {
    "path": "View/components/chat_list_item.kv",
    "content": "<ChatListItem>:\r\n    ripple_behavior: True\r\n    md_bg_color: 0, 0, 0, 0\r\n    elevation: 0\r\n    size_hint_y: None\r\n    padding: [10, 0, 10, 0]\r\n    spacing: 10\r\n    height: chatAvatar.height + 10\r\n    on_press: root.controller.show_chat_screen(root.id, root.contact_name, root.jid)\r\n    Avatar:\r\n        id: chatAvatar\r\n        source: 'assets/images/avatar.png'\r\n        pos_hint: {\"center_y\": .5}\r\n        radius: [30, ]\r\n    MDBoxLayout:\r\n        orientation: \"vertical\"\r\n        padding: [0, 0, 0, 10]\r\n        spacing: 2\r\n        MLabel:\r\n            id: contactName\r\n            adaptive_size: True\r\n            text: root.contact_name\r\n            theme_text_color: 'Custom'\r\n            size: self.texture_size\r\n            size_hint_y: None\r\n            size_hint_x: None\r\n            font_size: 17\r\n            color: app.theme_cls.opposite_bg_normal\r\n            bold: True\r\n        MDBoxLayout:\r\n            orientation: \"horizontal\"\r\n            spacing: 5\r\n            MDIcon:\r\n                theme_text_color: 'Custom'\r\n                icon: 'check-all'\r\n                size_hint: None, None\r\n                font_size: 18\r\n                size: 20, 20\r\n                pos_hint: {\"center_x\": .5, 'center_y': .5}\r\n                text_color: (0, 0, 1, 1)\r\n            MLabel:\r\n                id: lastMessage\r\n                text: root.last_message\r\n                height: self.texture_size[1]\r\n                theme_text_color: 'Custom'\r\n                size_hint_y: None\r\n                bold: True\r\n                font_size: 15\r\n                color: [.5, .5, .5, 1]\r\n                shorten: True\r\n                markup: True\r\n                shorten_from: 'right'\r\n                valign: 'center'\r\n\r\n    Label:\r\n        id: time\r\n        text: root.timestamp\r\n        size: self.texture_size\r\n        pos_hint: {'center_y': 0.5}\r\n        size_hint_y: None\r\n        size_hint_x: None\r\n        font_size: 13\r\n        color: app.theme_cls.opposite_bg_normal\r\n        valign: 'center'\r\n        halign: 'center'\r\n"
  },
  {
    "path": "View/components/chat_message.kv",
    "content": "#:import hex kivy.utils.get_color_from_hex\r\n\r\n<ChatMessage>:\r\n    orientation: 'vertical'\r\n    height: chat_message.height\r\n    MDCard:\r\n        id: chat_message\r\n        padding: 10\r\n        orientation: 'vertical'\r\n        md_bg_color: hex('#D9FDD3') if root.from_me == 1 else hex('#FFFFFF')\r\n        pos_hint: {'right': 1} if root.from_me == 1 else {'left': 1}\r\n        width: max(msg_text.width, time.width, attachment.width, quote.width) + 20\r\n        height: msg_text.height + time.height + attachment.height + quote.height + 20\r\n        size_hint: None, None\r\n        Quote:\r\n            id: quote\r\n            text: f\"{root.msg_quoted_text_data}\"\r\n            adaptive_size: True\r\n            pos_hint: {'right': 1} if root.from_me == 1 else {'left': 1}\r\n            halign: 'right' if root.from_me == 1 else 'left'\r\n            md_bg_color: hex('#d1f4cc') if root.from_me == 1 else hex('#f5f6f6')\r\n            line_color: hex('#06cf9c') if root.message_quoted_from_me == 0 else hex('#53bdeb')\r\n            padding: (10, 10)\r\n        MLabel:\r\n            id: msg_text\r\n            allow_copy: True\r\n            allow_selection: True\r\n            pos_hint: {'right': 1} if root.from_me == 1 else {'left': 1}\r\n            halign: 'right' if root.from_me == 1 else 'left'\r\n            valign: 'center'\r\n            text: root.txt_data\r\n            size_hint: None, None\r\n            adaptive_size: True\r\n            size: self.texture_size\r\n        Attachment:\r\n            id: attachment\r\n            text: f\"[u][ref=link]{root.media_filename}[/ref][/u]\"\r\n            on_ref_press: root.open_media(root.file_path)\r\n            adaptive_size: True\r\n            pos_hint: {'right': 1} if root.from_me == 1 else {'left': 1}\r\n            size_hint: None, None\r\n            padding: (10, 10)\r\n        MLabel:\r\n            id: time\r\n            pos_hint: {'right': 1} if root.from_me == 1 else {'left': 1}\r\n            text: root.timestamp\r\n            adaptive_size: True\r\n            font_size: 11\r\n            color: 0,0,0,0.5\r\n\r\n\r\n\r\n\r\n"
  },
  {
    "path": "View/components/quote.kv",
    "content": "<Quote>:\n    markup: True\n    allow_copy: True\n    allow_selection: True\n    valign: 'center'\n    size_hint: None, None\n    adaptive_size: True\n    size: self.texture_size\n"
  },
  {
    "path": "View/components/textfield_filemanger.kv",
    "content": "<TextFieldFileManager>:\n    size_hint_y: None\n    height: text_field.height\n\n    MDTextField:\n        id: text_field\n        hint_text: root.hint_text\n        text: root.text\n        helper_text: root.helper_text\n        on_text: root.on_text(self, self.text)\n\n    MDIconButton:\n        icon: \"folder-open-outline\"\n        pos_hint: {\"center_y\": .5}\n        pos: text_field.width - self.width + dp(8), 0\n        theme_text_color: \"Hint\"\n        on_release: root.open_file_manager(root.hint_text)\n"
  },
  {
    "path": "View/screens.py",
    "content": "# The screens dictionary contains the objects of the models and controllers\n# of the screens of the application.\nfrom Model.login_screen import LoginScreenModel\nfrom Controller.login_screen import LoginScreenController\n\nfrom Model.main_screen import MainScreenModel\nfrom Controller.main_screen import MainScreenController\n\nfrom Model.chat_screen import ChatScreenModel\nfrom Controller.chat_screen import ChatScreenController\n\nscreens = {\n    \"login screen\": {\n        \"model\": LoginScreenModel,\n        \"controller\": LoginScreenController,\n    },\n    \"main screen\": {\n        \"model\": MainScreenModel,\n        \"controller\": MainScreenController,\n    },\n    \"chat screen\": {\n        \"model\": ChatScreenModel,\n        \"controller\": ChatScreenController,\n    },\n}\n"
  },
  {
    "path": "about",
    "content": "[b]Whatsapp Msgstore Viewer[/b] (WMV)\nVersion $$version$$\n(C) 2023 [ref=https://github.com/absadiki][color=0000ff]absadiki[/color][/ref]\n[color=ffffff]\\n[/color]\n\nWMV is a free, open source and cross-platform app to decrypt, read and view the Whatsapp [i]msgstore.db[/i] database.\nIt is licenced under the GNU General Licence version 3 or later. You can modify or redistribute it under the conditions\nof these licences. (See the licence tab for more information)\n[color=ffffff]\\n[/color]\n\n\nVisit the [ref=$$g_page$$][color=0000ff]Github[/color][/ref] page for more information.\n\n"
  },
  {
    "path": "credits",
    "content": "This software would not possible without:\n[color=ffffff]\\n[/color]\n\n- [ref=https://kivy.org][color=0000ff]Kivy[/color][/ref] & [ref=https://kivymd.readthedocs.io][color=0000ff]KivyMD[/color][/ref] for the UI framework.\n- [ref=https://github.com/haddiebakrie/WhatsApp-Redesign][color=0000ff]WhatsApp-Redesign[/color][/ref] for the design inspiration and some UI components.\n- [ref=https://github.com/ElDavoo/WhatsApp-Crypt14-Crypt15-Decrypter][color=0000ff]WhatsApp-Crypt14-Crypt15-Decrypter[/color][/ref] for the decryption algorithm.\n- [ref=https://commons.m.wikimedia.org/wiki/File:Whatsapp_logo.jpg][color=0000ff]Sbk2605[/color][/ref] for the Whatsapp logo (Licenced under [ref=https://creativecommons.org/licenses/by-sa/4.0/deed.en][color=0000ff]Creative Commons Attribution-Share Alike 4.0 International[/color][/ref]).\n- [ref=https://github.com/Pustur/whatsapp-chat-parser-website][color=0000ff]whatsapp-chat-parser-website[/color][/ref] for the background image.\n[color=ffffff]\\n[/color]\n\n- And so many more libraries and frameworks.\n[color=ffffff]\\n[/color]"
  },
  {
    "path": "dbs/__init__.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\" Short description of this Python module.\nLonger description of this module.\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU General Public License as published by the Free Software\nFoundation, either version 3 of the License, or (at your option) any later\nversion.\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\nYou should have received a copy of the GNU General Public License along with\nthis program. If not, see <http://www.gnu.org/licenses/>.\n\"\"\"\n\n__author__ = \"One solo developer\"\n__authors__ = [\"One developer\", \"And another one\", \"etc\"]\n__contact__ = \"mail@example.com\"\n__copyright__ = \"Copyright 2023, \"\n__credits__ = [\"One developer\", \"And another one\", \"etc\"]\n__date__ = \"YYYY/MM/DD\"\n__deprecated__ = False\n__email__ = \"mail@example.com\"\n__license__ = \"GPLv3\"\n__maintainer__ = \"developer\"\n__status__ = \"Production\"\n__version__ = \"0.0.1\"\n\nif __name__ == '__main__':\n    pass\n"
  },
  {
    "path": "dbs/abstract_db.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nThis file describes how the database should look like and what it should return.\nBecause this app is only a reverse engineering attempt of the Whatsapp database, it is very likely that it might break\nin case there have been any updates to the database.\n\nThe `schema` variable and the `AbstractDatabase` class are introduced to make it easy to add support to\ndifferent versions of databases.\n\"\"\"\n\nimport sqlite3\nfrom abc import ABC, abstractmethod\n\n\nclass AbstractDatabase(ABC):\n\n    def __init__(self, msgstore, wa=None, schema=None):\n        self.msgstore = msgstore\n        self.wa = wa\n        self.contacts = None\n        self.schema: dict = schema  # a simple map between the (tables, attributes) used in the code and their real\n        # in the database, see the `check_database_schema` method for more details\n\n        msgstore_con = sqlite3.connect(self.msgstore, check_same_thread=False)\n        msgstore_con.row_factory = lambda c, r: dict([(col[0], r[idx]) for idx, col in enumerate(c.description)])\n        self.msgstore_cursor = msgstore_con.cursor()\n        if wa is not None:\n            wa_con = sqlite3.connect(self.wa, check_same_thread=False)\n            wa_con.row_factory = lambda c, r: dict([(col[0], r[idx]) for idx, col in enumerate(c.description)])\n            self.wa_cursor = wa_con.cursor()\n            self.load_contacts(self.wa_cursor)\n\n    @abstractmethod\n    def fetch_contact_chats(self):\n        \"\"\"\n        This function should return a list of dicts of the available contact chat views,\n        The list should look like this:\n       [\n            {'_id': 1,\n             'user': '123456789',\n             'raw_string_jid': '123456789@s.whatsapp.net',\n             'text_data': 'See my last message',\n             'timestamp': '2022-10-29  17:45:21'\n             },\n            {'_id': 2,\n             'user': '123456780',\n             'raw_string_jid': '123456780@s.whatsapp.net',\n             'text_data': 'See my last message',\n             'timestamp': '2022-04-30  17:45:21'\n             },\n        ]\n        \"\"\"\n        pass\n\n    @abstractmethod\n    def fetch_group_chats(self):\n        \"\"\"\n        This function should return a list of dicts of the available grou chats\n        The list should look like this:\n         [\n            {'_id': 3,\n             'user': 'Group 1', # usually the subject field\n             'raw_string_jid': '1234567890987654321@g.us',\n             'text_data': 'See my last message',\n             'timestamp': '2022-10-29  17:45:21'\n             },\n            {'_id': 4,\n             'user': 'Group 2',\n             'raw_string_jid': '1234567809087654321@g.us',\n             'text_data': 'See my last message',\n             'timestamp': '2022-04-30  17:45:21'\n             },\n        ]\n        \"\"\"\n        pass\n\n    @abstractmethod\n    def fetch_calls(self, how_many=None):\n        \"\"\"\n        This function should return a list of dicts of the available call logs\n        The list should look like this:\n        [\n            {'_id': 1,\n             'from_me': 0,\n             'user': '123456789',\n             'raw_string_jid': '123456789@s.whatsapp.net',\n             'duration': '00:15:12',\n             'video_call': 0,\n             'timestamp': '2022-10-29  17:45:21'\n             },\n            {'_id': 2,\n             'from_me': 1,\n             'user': '123456780',\n             'raw_string_jid': '123456780@s.whatsapp.net',\n             'duration': '00:15:12',\n             'video_call': 1,\n             'timestamp': '2022-10-29  17:45:21'\n             }\n        ]\n        \"\"\"\n        pass\n\n    @abstractmethod\n    def fetch_chat(self, chat_id):\n        \"\"\"\n        This function should return a list of dicts of the available chat messages related to the `chat_id` given as\n        input.\n        This list should look like this:\n         [\n                {\n                    '_id': 1,\n                    'key_id': '4552235ASAASDJKHASH',\n                    'from_me': 1,\n                    'timestamp': '2022-06-28 22:23:13',\n                    'text_data': 'Hello bro, How are you ?',\n                    'file_path': None,\n                    'message_quoted_text_data': None,\n                    'message_quoted_from_me': None,\n                    'message_quoted_key_id': None\n                },\n                {\n                    '_id': 1,\n                    'key_id': '4552235ASAASDJKHASH',\n                    'from_me': 0,\n                    'timestamp': '2022-06-28 22:23:13',\n                    'text_data': '',\n                    'file_path': '/media/images/image.png',\n                    'message_quoted_text_data': None,\n                    'message_quoted_from_me': None,\n                    'message_quoted_key_id': None\n                }\n        ],\n        \"\"\"\n        pass\n\n    def load_contacts(self, wa_cursor):\n        sql_query = \"\"\"\n        SELECT \n            jid,\n            status,\n            display_name,\n            number,\n            given_name,\n            family_name\n        FROM \n            wa_contacts\n        \"\"\"\n        contacts_list = wa_cursor.execute(sql_query).fetchall()\n        self.contacts = {}\n        for contact in contacts_list:\n            self.contacts[contact['jid']] = contact\n\n    def check_database_schema(self):\n        \"\"\"\n        This method checks that the database contains the tables and attributes provided with its schema\n        It will fail in case a table (or attribute) does not exist, or it has a different name\n        \"\"\"\n        if self.schema is None:\n            raise Exception('No schema has been provided!')\n        for table in self.schema:\n            table_name = self.schema[table]['name']\n            attributes = self.schema[table]['attributes']\n            sql_query = f\"SELECT {','.join(attributes)} from {table_name}\"\n            self.msgstore_cursor.execute(sql_query).fetchone()  # this will fail if the table or the attributes do not\n            # exist\n"
  },
  {
    "path": "dbs/v1/__init__.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\" Short description of this Python module.\nLonger description of this module.\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU General Public License as published by the Free Software\nFoundation, either version 3 of the License, or (at your option) any later\nversion.\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\nYou should have received a copy of the GNU General Public License along with\nthis program. If not, see <http://www.gnu.org/licenses/>.\n\"\"\"\n\n__author__ = \"One solo developer\"\n__authors__ = [\"One developer\", \"And another one\", \"etc\"]\n__contact__ = \"mail@example.com\"\n__copyright__ = \"Copyright 2023, \"\n__credits__ = [\"One developer\", \"And another one\", \"etc\"]\n__date__ = \"YYYY/MM/DD\"\n__deprecated__ = False\n__email__ = \"mail@example.com\"\n__license__ = \"GPLv3\"\n__maintainer__ = \"developer\"\n__status__ = \"Production\"\n__version__ = \"0.0.1\"\n\nif __name__ == '__main__':\n    pass\n"
  },
  {
    "path": "dbs/v1/db.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom dbs.abstract_db import AbstractDatabase\n\n\nclass Database(AbstractDatabase):\n\n    def __init__(self, msgstore, wa):\n        schema = {\n            'chat_view': {\n                'name': 'chat_view',\n                'attributes': [\n                    '_id',\n                    'raw_string_jid',\n                    'sort_timestamp',\n                    'last_message_row_id'\n                ]\n            },\n            'message': {\n                'name': 'message',\n                'attributes': [\n                    '_id',\n                    'chat_row_id',\n                    'key_id',\n                    'from_me',\n                    'timestamp',\n                    'text_data',\n                ]\n            },\n            'message_media': {\n                'name': 'message_media',\n                'attributes': [\n                    'message_row_id',\n                    'file_path',\n                ]\n            },\n            'message_quoted': {\n                'name': 'message_quoted',\n                'attributes': [\n                    'message_row_id',\n                    'text_data',\n                    'from_me',\n                    'key_id'\n                ]\n            },\n        }\n        super(Database, self).__init__(msgstore, wa, schema=schema)\n\n    def fetch_contact_chats(self):\n        chat_view_table = self.schema['chat_view']['name']  # I will continue later\n        sql_query = \"\"\"\n        select \n        chat_view._id, \n        jid.user,\n        chat_view.raw_string_jid,\n        message.text_data, \n        DATETIME(ROUND(chat_view.sort_timestamp / 1000), 'unixepoch') as timestamp\n\n        from chat_view INNER JOIN jid ON chat_view.raw_string_jid=jid.raw_string \n        INNER JOIN message ON chat_view.last_message_row_id = message._id\n\n        WHERE \n\n        chat_view.raw_string_jid not LIKE '%g.us'\n        \n        order by timestamp desc\n        \"\"\"\n        return self.msgstore_cursor.execute(sql_query).fetchall()\n\n    def fetch_group_chats(self):\n        sql_query = \"\"\"\n                select \n                chat_view._id, \n                chat_view.subject as user,\n                chat_view.raw_string_jid,\n                message.text_data, \n                DATETIME(ROUND(chat_view.sort_timestamp / 1000), 'unixepoch') as timestamp\n\n                from chat_view INNER JOIN jid ON chat_view.raw_string_jid=jid.raw_string \n                INNER JOIN message ON chat_view.last_message_row_id = message._id\n\n                WHERE \n\n                chat_view.raw_string_jid LIKE '%g.us'\n                \"\"\"\n        return self.msgstore_cursor.execute(sql_query).fetchall()\n\n    def fetch_calls(self, how_many=None):\n        sql_query = \"\"\"\n               select \n                call_log._id, call_log.from_me, \n                DATETIME(ROUND(call_log.timestamp / 1000), 'unixepoch') as timestamp, \n                call_log.video_call,\n                Time(call_log.duration, 'unixepoch') as duration,\n                jid.user, \n                jid.raw_string as raw_string_jid\n\n                from call_log LEFT JOIN jid\n                ON call_log.jid_row_id = jid._id\n                \"\"\"\n        if how_many:\n            return self.msgstore_cursor.execute(sql_query).fetchmany(how_many)\n        else:\n            return self.msgstore_cursor.execute(sql_query).fetchall()\n\n    def fetch_chat(self, chat_id):\n        sql_query = f\"\"\"\n        select  message._id, message.key_id, message.from_me, DATETIME(ROUND(message.timestamp / 1000), 'unixepoch') as timestamp,  ifnull(message.text_data, '') as text_data,\n        message_media.file_path,\n        message_quoted.text_data  as message_quoted_text_data,\n        message_quoted.from_me as message_quoted_from_me,\n        message_quoted.key_id as message_quoted_key_id\n        \n        from  message LEFT JOIN message_media \n        ON message._id = message_media.message_row_id\n        LEFT JOIN message_quoted \n        ON message._id = message_quoted.message_row_id\n        \n        WHERE message.chat_row_id={chat_id}\n        \"\"\"\n        return self.msgstore_cursor.execute(sql_query).fetchall()\n"
  },
  {
    "path": "dbs/v2/__init__.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Database interface for accessing and retrieving WhatsApp chat, message, and call data.\n\n\nThis module defines the `Database` class, which extends the `AbstractDatabase` to provide\nmethods for interacting with WhatsApp's SQLite databases. It facilitates the retrieval of\nvarious data types, including:\n\n- **Chats**: Fetches both individual and group chats with relevant details such as user\n  information, last message content, and timestamps.\n\n- **Messages**: Retrieves messages associated with a specific chat, including text data,\n  media file paths, and quoted message details.\n\n- **Calls**: Obtains call logs with information on call direction, type (video or audio),\n  duration, and associated user details.\n\nThe `Database` class constructs SQL queries to extract this information, ensuring that the\nretrieved data is organized and accessible for further processing or analysis.\n\nClasses:\n    Database: Extends `AbstractDatabase` to implement methods for fetching chats, messages,\n              and call logs from WhatsApp's databases.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU General Public License as published by the Free Software\nFoundation, either version 3 of the License, or (at your option) any later\nversion.\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\nYou should have received a copy of the GNU General Public License along with\nthis program. If not, see <http://www.gnu.org/licenses/>.\n\"\"\"\n\n\n__author__ = \"Voice-less\"\n__copyright__ = \"Copyright 2025\"\n__credits__ = [\"Voice-less\"]\n__date__ = \"2025/04/02\"\n__deprecated__ = False\n__license__ = \"GPLv3\"\n__maintainer__ = \"Voice-less\"\n__status__ = \"Production\"\n__version__ = \"1.0.0\"\n\nif __name__ == '__main__':\n    pass\n"
  },
  {
    "path": "dbs/v2/db.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom dbs.abstract_db import AbstractDatabase\n\nclass Database(AbstractDatabase):\n\n    def __init__(self, msgstore, wa):\n        schema = {\n            'chat': {\n                'name': 'chat',\n                'attributes': [\n                    '_id',                # chat id\n                    'jid_row_id',         # reference to jid table\n                    'sort_timestamp',     # timestamp for sorting/display\n                    'last_message_row_id' # last message id in the chat\n                ]\n            },\n            'message': {\n                'name': 'message',\n                'attributes': [\n                    '_id',         # message id\n                    'chat_row_id', # chat id reference\n                    'key_id',      # key id\n                    'from_me',     # sent flag\n                    'timestamp',   # message timestamp\n                    'text_data'    # message text\n                ]\n            },\n            'message_media': {\n                'name': 'message_media',\n                'attributes': [\n                    'message_row_id',  # message reference\n                    'file_path'        # media file path\n                ]\n            },\n            'message_quoted': {\n                'name': 'message_quoted',\n                'attributes': [\n                    'message_row_id',  # message reference\n                    'text_data',       # quoted message text\n                    'from_me',         # quoted message from_me flag\n                    'key_id'           # quoted message key id\n                ]\n            },\n        }\n        super(Database, self).__init__(msgstore, wa, schema=schema)\n\n\n    def fetch_contact_chats(self):\n        sql_query = \"\"\"\n        SELECT \n            chat._id, \n            jid.user,\n            jid.raw_string AS raw_string_jid,\n            message.text_data, \n            DATETIME(ROUND(chat.sort_timestamp / 1000), 'unixepoch') as timestamp\n        FROM chat \n        INNER JOIN jid ON chat.jid_row_id = jid._id\n        INNER JOIN message ON chat.last_message_row_id = message._id\n        WHERE jid.raw_string NOT LIKE '%g.us'\n        ORDER BY timestamp DESC\n        \"\"\"\n        return self.msgstore_cursor.execute(sql_query).fetchall()\n\n    def fetch_group_chats(self):\n        sql_query = \"\"\"\n        SELECT \n            chat._id, \n            chat.subject as user,\n            jid.raw_string,\n            message.text_data, \n            DATETIME(ROUND(chat.sort_timestamp / 1000), 'unixepoch') as timestamp\n        FROM chat \n        INNER JOIN jid ON chat.jid_row_id = jid._id\n        INNER JOIN message ON chat.last_message_row_id = message._id\n        WHERE jid.raw_string LIKE '%g.us'\n        ORDER BY timestamp DESC\n        \"\"\"\n        return self.msgstore_cursor.execute(sql_query).fetchall()\n    \n    \n    def fetch_calls(self, how_many=None):\n        sql_query = \"\"\"\n        SELECT \n            call_log._id, \n            call_log.from_me, \n            DATETIME(ROUND(call_log.timestamp / 1000), 'unixepoch') as timestamp, \n            call_log.video_call,\n            TIME(call_log.duration, 'unixepoch') as duration,\n            jid.user, \n            jid.raw_string as raw_string_jid\n        FROM call_log \n        LEFT JOIN jid ON call_log.jid_row_id = jid._id\n        \"\"\"\n        if how_many:\n            return self.msgstore_cursor.execute(sql_query).fetchmany(how_many)\n        else:\n            return self.msgstore_cursor.execute(sql_query).fetchall()\n\n\n    def fetch_chat(self, chat_id):\n        sql_query = f\"\"\"\n        SELECT  \n            message._id, \n            message.key_id, \n            message.from_me, \n            DATETIME(ROUND(message.timestamp / 1000), 'unixepoch') as timestamp,  \n            IFNULL(message.text_data, '') as text_data,\n            message_media.file_path,\n            message_quoted.text_data as message_quoted_text_data,\n            message_quoted.from_me as message_quoted_from_me,\n            message_quoted.key_id as message_quoted_key_id\n        FROM message \n        LEFT JOIN message_media ON message._id = message_media.message_row_id\n        LEFT JOIN message_quoted ON message._id = message_quoted.message_row_id\n        WHERE message.chat_row_id = {chat_id}\n        ORDER BY message.timestamp ASC\n        \"\"\"\n        return self.msgstore_cursor.execute(sql_query).fetchall()\n"
  },
  {
    "path": "dbs/v3/__init__.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Version 3 database schema support for Whatsapp Msgstore Viewer.\nThis package is automatically discovered by the application; it only needs\n to expose the `Database` class implemented in `db.py`.\n\"\"\"\n\n__author__ = \"Auto-generated by AI\"\n__version__ = \"1.0.0\"\n\nif __name__ == '__main__':\n    pass "
  },
  {
    "path": "dbs/v3/db.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom dbs.abstract_db import AbstractDatabase\n\n\nclass Database(AbstractDatabase):\n\n    def __init__(self, msgstore, wa):\n        # Updated schema to match the tables/columns present in the provided DDL\n        schema = {\n            # ------------ chat list ------------\n            'chat': {\n                'name': 'chat',\n                'attributes': [\n                    '_id',                 # Primary key\n                    'jid_row_id',          # FK → jid._id\n                    'subject',             # Group name (NULL for 1-to-1)\n                    'sort_timestamp',      # Sorting timestamp\n                    'last_message_row_id'  # FK → message._id\n                ]\n            },\n            # ------------ messages ------------\n            'message': {\n                'name': 'message',\n                'attributes': [\n                    '_id',          # Primary key\n                    'chat_row_id',  # FK → chat._id\n                    'key_id',\n                    'from_me',\n                    'timestamp',\n                    'text_data'\n                ]\n            },\n            # ------------ media ------------\n            'message_media': {\n                'name': 'message_media',\n                'attributes': [\n                    'message_row_id',  # FK → message._id\n                    'file_path'\n                ]\n            },\n            # ------------ quoted messages ------------\n            'message_quoted': {\n                'name': 'message_quoted',\n                'attributes': [\n                    'message_row_id',  # FK → message._id\n                    'text_data',\n                    'from_me',\n                    'key_id'\n                ]\n            },\n            # ------------ call log ------------\n            'call_log': {\n                'name': 'call_log',\n                'attributes': [\n                    '_id',\n                    'jid_row_id',   # FK → jid._id\n                    'from_me',\n                    'timestamp',\n                    'video_call',\n                    'duration'\n                ]\n            },\n            # ------------ jid / contacts ------------\n            'jid': {\n                'name': 'jid',\n                'attributes': [\n                    '_id',\n                    'user',\n                    'raw_string'\n                ]\n            },\n        }\n        super(Database, self).__init__(msgstore, wa, schema=schema)\n\n    # --- fetch_* methods copied from v2 without modification ---\n\n    def fetch_contact_chats(self):\n        sql_query = \"\"\"\n        SELECT \n            chat._id, \n            IFNULL(jid.user, '') AS user,\n            jid.raw_string AS raw_string_jid,\n            message.text_data, \n            DATETIME(ROUND(chat.sort_timestamp / 1000), 'unixepoch') AS timestamp\n        FROM chat \n        INNER JOIN jid ON chat.jid_row_id = jid._id\n        INNER JOIN message ON chat.last_message_row_id = message._id\n        WHERE jid.raw_string NOT LIKE '%g.us'\n        ORDER BY timestamp DESC\n        \"\"\"\n        return self.msgstore_cursor.execute(sql_query).fetchall()\n\n    def fetch_group_chats(self):\n        sql_query = \"\"\"\n        SELECT \n            chat._id, \n            IFNULL(chat.subject, '') AS user,\n            jid.raw_string AS raw_string_jid,\n            message.text_data, \n            DATETIME(ROUND(chat.sort_timestamp / 1000), 'unixepoch') AS timestamp\n        FROM chat \n        INNER JOIN jid ON chat.jid_row_id = jid._id\n        INNER JOIN message ON chat.last_message_row_id = message._id\n        WHERE jid.raw_string LIKE '%g.us'\n        ORDER BY timestamp DESC\n        \"\"\"\n        return self.msgstore_cursor.execute(sql_query).fetchall()\n\n    def fetch_calls(self, how_many=None):\n        sql_query = \"\"\"\n        SELECT \n            call_log._id, \n            call_log.from_me, \n            DATETIME(ROUND(call_log.timestamp / 1000), 'unixepoch') AS timestamp, \n            call_log.video_call,\n            TIME(call_log.duration, 'unixepoch') AS duration,\n            IFNULL(jid.user, '') AS user, \n            jid.raw_string AS raw_string_jid\n        FROM call_log \n        LEFT JOIN jid ON call_log.jid_row_id = jid._id\n        \"\"\"\n        if how_many:\n            return self.msgstore_cursor.execute(sql_query).fetchmany(how_many)\n        else:\n            return self.msgstore_cursor.execute(sql_query).fetchall()\n\n    def fetch_chat(self, chat_id):\n        sql_query = f\"\"\"\n        SELECT  \n            message._id, \n            message.key_id, \n            message.from_me, \n            DATETIME(ROUND(message.timestamp / 1000), 'unixepoch') AS timestamp,  \n            IFNULL(message.text_data, '') AS text_data,\n            message_media.file_path,\n            message_quoted.text_data AS message_quoted_text_data,\n            message_quoted.from_me AS message_quoted_from_me,\n            message_quoted.key_id AS message_quoted_key_id\n        FROM message \n        LEFT JOIN message_media ON message._id = message_media.message_row_id\n        LEFT JOIN message_quoted ON message._id = message_quoted.message_row_id\n        WHERE message.chat_row_id = {chat_id}\n        ORDER BY message.timestamp ASC\n        \"\"\"\n        return self.msgstore_cursor.execute(sql_query).fetchall() "
  },
  {
    "path": "decryption/__init__.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\" Short description of this Python module.\nLonger description of this module.\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU General Public License as published by the Free Software\nFoundation, either version 3 of the License, or (at your option) any later\nversion.\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\nYou should have received a copy of the GNU General Public License along with\nthis program. If not, see <http://www.gnu.org/licenses/>.\n\"\"\"\n\n__author__ = \"One solo developer\"\n__authors__ = [\"One developer\", \"And another one\", \"etc\"]\n__contact__ = \"mail@example.com\"\n__copyright__ = \"Copyright 2023, \"\n__credits__ = [\"One developer\", \"And another one\", \"etc\"]\n__date__ = \"YYYY/MM/DD\"\n__deprecated__ = False\n__email__ = \"mail@example.com\"\n__license__ = \"GPLv3\"\n__maintainer__ = \"developer\"\n__status__ = \"Production\"\n__version__ = \"0.0.1\"\n\nif __name__ == '__main__':\n    pass\n"
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {one line to give the program's name and a brief idea of what it does.}\n    Copyright (C) {year}  {name of author}\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    {project}  Copyright (C) {year}  {fullname}\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/README.md",
    "content": "# WhatsApp Crypt14-15 Backup Decrypter\nDecrypts WhatsApp .crypt12, .crypt14 and .crypt15 files, **given the key file** or the 64-characters long key.  \nThe key file is named \"key\" if the backup is crypt14 or  \n\"encrypted_backup.key\" if the backup is crypt15 (encrypted E2E backups).  \nThe output result is either a SQLite database \nor a ZIP file (in case of wallpapers and stickers).  \nThis is the only thing this script does. \nThose who are looking for a complete suite for\nWhatsApp forensics, check out [whapa.](https://github.com/B16f00t/whapa)\n\n# Quickstart\nJust copy-paste this block into your terminal  \n(should be multi-platform - ignore errors during \"activate\" lines, as one is for Linux/macOS, one is for Windows (Batch) and one is for Windows PowerShell)\n```\ngit clone https://github.com/ElDavoo/WhatsApp-Crypt14-Crypt15-Decrypter.git\ncd WhatsApp-Crypt14-Crypt15-Decrypter\npython -m venv venv\nsource venv/bin/activate\n.\\venv\\Scripts\\activate.bat\n.\\venv\\Scripts\\Activate.ps1\npython -m pip install --upgrade pip\npython -m pip install -r requirements.txt\n```\n\n## Requirements\n\n**Remember to download the proto folder!**\n\nPython 3.7 or more recent   \n\npycriptodomex or pycryptodome  \njavaobj-py3  \nprotobuf 3.20 or more recent  \n\n... or just install the `requirements.txt` file\n\nUse:\n ```\n              python -m pip install -r requirements.txt\n ```\n  Or:\n ```\n              python -m pip install pycryptodomex javaobj-py3 protobuf\n ```\n\n## Usage\n\n ```\nusage: decrypt14_15.py [-h] [-f] [-nm] [-bs BUFFER_SIZE] [-ng] [-np]\n                       [-ivo IV_OFFSET] [-do DATA_OFFSET] [-v]\n                       [keyfile] [encrypted] [decrypted]\n\nDecrypts WhatsApp backup files encrypted with crypt12, 14 or 15\n\npositional arguments:\n  keyfile               The WhatsApp encrypted_backup key file or the hex\n                        encoded key. Default: encrypted_backup.key\n  encrypted             The encrypted crypt12, 14 or 15 file. Default:\n                        msgstore.db.crypt15\n  decrypted             The decrypted output file. Default: msgstore.db\n\noptions:\n  -h, --help            show this help message and exit\n  -f, --force           Makes errors non fatal. Default: false\n  -nm, --no-mem         Does not load files in RAM, stresses the disk more.\n                        Default: load files into RAM\n  -bs BUFFER_SIZE, --buffer-size BUFFER_SIZE\n                        How many bytes of data to process at a time. Implies\n                        -nm. Default: 8192\n  -ng, --no-guess       Does not try to guess the offsets, only protobuf\n                        parsing.\n  -np, --no-protobuf    Does not try to parse the protobuf message, only\n                        offset guessing.\n  -ivo IV_OFFSET, --iv-offset IV_OFFSET\n                        The default offset of the IV in the encrypted file.\n                        Only relevant in offset guessing mode. Default: 8\n  -do DATA_OFFSET, --data-offset DATA_OFFSET\n                        The default offset of the encrypted data in the\n                        encrypted file. Only relevant in offset guessing mode.\n                        Default: 122\n  -v, --verbose         Prints all offsets and messages\n ```  \n\n### Examples, with output\n#### Crypt15\n```  \npython ./decrypt14_15.py ./encrypted_backup.key ./msgstore.db.crypt15 ./msgstore.db\n[I] Crypt15 key loaded\n[I] Database header parsed\n[I] Done\n```  \nor\n```  \npython ./decrypt14_15.py b1ef5568c31686d3339bcae4600c56cf7f0cb1ae982157060879828325257c11 ./msgstore.db.crypt15 ./msgstore.db\n[I] Crypt15 key loaded\n[I] Database header parsed\n[I] Done\n``` \n#### Crypt14\n```  \npython ./decrypt14_15.py ./key ./msgstore.db.crypt14 ./msgstore.db\n[I] Crypt12/14 key loaded\n[I] Database header parsed\n[I] Done\n```  \n#### Crypt12\n```  \npython ./decrypt14_15.py ./key ./msgstore.db.crypt12 ./msgstore.db\n[I] Crypt12/14 key loaded\n[I] Database header parsed\n[I] Done\n```\n\n## I had to use --force to decrypt\nPlease open an issue.\n\n## Not working / crash / etc\n\nPlease open an issue and attach:\n1) Output of the program (both with and without --force)\n2) Hexdump of keyfile\n3) Hexdump of first 512 bytes of encrypted DB\n\n### I will happily accept pull requests for the currently open issues. :)\n\n### Where do I get the key(file)?\nOn a rooted Android device, you can just copy \n`/data/data/com.whatsapp/files/key` \n(or `/data/data/com.whatsapp/files/encrypted_backup.key` if backups are crypt15).  \nIf you enabled E2E backups, and you did not use a password \n(you have a copy of the 64-digit key, for example a screenshot), \nyou can just transcribe and use it in lieu of the key file parameter.  \n**There are other ways, but it is not in the scope of this project \nto tell you.  \nIssues asking for this will be closed as invalid.**  \n\n### Last tested version (don't expect this to be updated)\nStable: \n2.22.15.74  \nBeta: \n2.23.2.6\n\n#### Protobuf classes generation\n\nYou can replace the provided generated protobuf classes with your own.  \nIn order to do that, download the protoc 21.0 from\n[here](https://github.com/protocolbuffers/protobuf/releases).\nAfter that put protoc in the proto folder and run:  \n`./protoc *.proto --python_out=.`   \n**We then need to manually patch the generated classes to fix import errors.**  \nOpen `prefix_pb2.py` and `C14_cipher_pb2.py`  \nAdd `proto.` after any `import` keyword.  \nFor example:  \n`import C14_cipher_version_pb2 as C14__cipher__version__pb2`  \nbecomes  \n`import proto.C14_cipher_version_pb2 as C14__cipher__version__pb2`\n\n---\n\n## Donations\n\nThank you so much to each one of you!\n- **🎉🎉🎉 [courious875](https://github.com/courious875) 🎉🎉🎉** \n\n---\n\n#### Credits:\n Original implementation for crypt12: [TripCode](https://github.com/TripCode)    \n Some help at the beginning: [DjEdu28](https://github.com/DjEdu28)  \n Actual crypt14/15 implementation with protobuf: [ElDavoo](https://github.com/ElDavoo)  \n Help with crypt14/15 footer: [george-lam](https://github.com/georg-lam)\n\n\n### Stargazers over time\n\n[![Star History Chart](https://api.star-history.com/svg?repos=ElDavoo/WhatsApp-Crypt14-Crypt15-Decrypter&type=Date)](https://star-history.com/#ElDavoo/WhatsApp-Crypt14-Crypt15-Decrypter&Date)\n"
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/SECURITY.md",
    "content": "# Security Policy\n\n## Supported Versions\n\nLatest\n\n## Reporting a Vulnerability\n\nOpen an issue\n"
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/__init__.py",
    "content": ""
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/decrypt14_15.py",
    "content": "#!/usr/bin/env python\n\"\"\"\nThis script decrypts WhatsApp's DB files encrypted with Crypt12, Crypt14 or Crypt15.\n\"\"\"\n\nfrom __future__ import annotations\n\n# AES import party!\n# pycryptodome and PyCryptodomex's implementations of AES are the same,\n# so we try to import one of these twos.\ntry:\n    # pycryptodomex\n    from Cryptodome.Cipher import AES\nexcept ModuleNotFoundError:\n    try:\n        # pycryptodome\n        # noinspection PyUnresolvedReferences\n        from Crypto.Cipher import AES\n\n        if not hasattr(AES, 'MODE_GCM'):\n            # pycrypto\n            print(\"You installed pycrypto and not pycryptodome(x).\")\n            print(\"Pycrypto is old, deprecated and not supported.\")\n            print(\"Run: python -m pip uninstall pycrypto\")\n            print(\"And: python -m pip install pycryptodomex\")\n            print(\"Or:  python -m pip install pycryptodome\")\n            exit(1)\n    except ModuleNotFoundError:\n        # crypto (or nothing)\n        print(\"You need pycryptodome(x) to run this script\")\n        print(\"python -m pip install pycryptodomex\")\n        print(\"Or: python -m pip install pycryptodome\")\n        print(\"You can also remove \\\"crypto\\\" if you have it installed\")\n        print(\"python -m pip uninstall crypto\")\n        exit(1)\n\n# noinspection PyPackageRequirements\n# This is from javaobj-py3\nimport javaobj.v2 as javaobj\n\n# noinspection PyPackageRequirements\nfrom google.protobuf.message import DecodeError\n\nimport collections\nfrom hashlib import sha256, md5\nimport io\nfrom re import findall\nfrom sys import exit, maxsize\nfrom time import sleep\nfrom datetime import date\n\nimport argparse\nimport hmac\nimport zlib\n\n__author__ = 'ElDavo'\n__copyright__ = 'Copyright (C) 2023'\n__license__ = 'GPLv3'\n__status__ = 'Production'\n__version__ = '6.1'\n\n# These constants are only used by the guessing logic.\n\n# zlib magic header is 78 01 (Low Compression).\n# The first two bytes of the decrypted data should be those,\n# in case of single file backup, or PK in case of multi file.\nZLIB_HEADERS = [\n    b'x\\x01',\n    b'PK'\n]\nZIP_HEADER = b'PK\\x03\\x04'\n\n# Size of bytes to test (number chosen arbitrarily, but values less than ~310 makes test_decompression fail)\nHEADER_SIZE = 384\nDEFAULT_DATA_OFFSET = 122\nDEFAULT_IV_OFFSET = 8\n\n\nclass SimpleLog:\n    \"\"\"Simple logger class. Supports 4 verbosity levels.\"\"\"\n\n    def __init__(self, verbose: bool, force: bool):\n        self.verbose = verbose\n        self.force = force\n\n    def v(self, msg: str):\n        \"\"\"Will only print message if verbose mode is enabled.\"\"\"\n        if self.verbose:\n            print('[V] {}'.format(msg))\n\n    @staticmethod\n    def i(msg: str):\n        \"\"\"Always prints message.\"\"\"\n        print('[I] {}'.format(msg))\n\n    def e(self, msg: str):\n        \"\"\"Prints message and exit, unless force is enabled.\"\"\"\n        print('[E] {}'.format(msg))\n        if not self.force:\n            print(\"To bypass checks, use the \\\"--force\\\" parameter\")\n            exit(1)\n\n    @staticmethod\n    def f(msg: str):\n        \"\"\"Always prints message and exit.\"\"\"\n        print('[F] {}'.format(msg))\n        exit(1)\n\n\ndef from_hex(logger, string: str) -> bytes:\n    \"\"\"Converts a hex string into a bytes array\"\"\"\n    if len(string) != 64:\n        logger.f(\"The key file specified does not exist.\\n    \"\n                 \"If you tried to specify the key directly, note it should be \"\n                 \"64 characters long and not {} characters long.\".format(len(string)))\n\n    barr = None\n    try:\n        barr = bytes.fromhex(string)\n    except ValueError as e:\n        logger.f(\"Couldn't convert the hex string.\\n    \"\n                 \"Exception: {}\".format(e))\n    if len(barr) != 32:\n        logger.e(\"The key is not 32 bytes long but {} bytes long.\".format(len(barr)))\n    return barr\n\n\ndef parsecmdline() -> argparse.Namespace:\n    \"\"\"Sets up the argument parser\"\"\"\n    parser = argparse.ArgumentParser(description='Decrypts WhatsApp backup files'\n                                                 ' encrypted with crypt12, 14 or 15')\n    parser.add_argument('keyfile', nargs='?', type=str, default=\"encrypted_backup.key\",\n                        help='The WhatsApp encrypted_backup key file or the hex encoded key. '\n                             'Default: encrypted_backup.key')\n    parser.add_argument('encrypted', nargs='?', type=argparse.FileType('rb'), default=\"msgstore.db.crypt15\",\n                        help='The encrypted crypt12, 14 or 15 file. Default: msgstore.db.crypt15')\n    parser.add_argument('decrypted', nargs='?', type=argparse.FileType('wb'), default=\"msgstore.db\",\n                        help='The decrypted output file. Default: msgstore.db')\n    parser.add_argument('-f', '--force', action='store_true',\n                        help='Makes errors non fatal. Default: false')\n    parser.add_argument('-nm', '--no-mem', action='store_true',\n                        help='Does not load files in RAM, stresses the disk more. '\n                             'Default: load files into RAM')\n    parser.add_argument('-bs', '--buffer-size', type=int, help='How many bytes of data to process at a time. '\n                                                               'Implies -nm. Default: {}'.format(io.DEFAULT_BUFFER_SIZE))\n    parser.add_argument('-ng', '--no-guess', action='store_true',\n                        help='Does not try to guess the offsets, only protobuf parsing.')\n    parser.add_argument('-np', '--no-protobuf', action='store_true',\n                        help='Does not try to parse the protobuf message, only offset guessing.')\n    parser.add_argument('-ivo', '--iv-offset', type=int, default=DEFAULT_IV_OFFSET,\n                        help='The default offset of the IV in the encrypted file. '\n                             'Only relevant in offset guessing mode. '\n                             'Default: {}'.format(DEFAULT_IV_OFFSET))\n    parser.add_argument('-do', '--data-offset', type=int, default=DEFAULT_DATA_OFFSET,\n                        help='The default offset of the encrypted data in the encrypted file. '\n                             'Only relevant in offset guessing mode. '\n                             'Default: {}'.format(DEFAULT_DATA_OFFSET))\n    parser.add_argument('-v', '--verbose', action='store_true', help='Prints all offsets and messages')\n\n    return parser.parse_args()\n\n\nclass Key:\n    \"\"\" This class represents a key used to decrypt the DB.\n    Only the key is mandatory. The other parameters are optional, and if they are not None,\n    means that the key type is crypt14.\"\"\"\n    # These constants are only used with crypt12/14 keys.\n    SUPPORTED_CIPHER_VERSION = b'\\x00\\x01'\n    SUPPORTED_KEY_VERSIONS = [b'\\x01', b'\\x02', b'\\x03']\n\n    # This constant is only used with crypt15 keys.\n    BACKUP_ENCRYPTION = b'backup encryption\\x01'\n\n    def is_crypt15(self):\n        \"\"\"Returns True if the key is crypt15, False if it is crypt12/14\"\"\"\n        return self.key_version is None\n    def __str__(self):\n        \"\"\"Returns a string representation of the key\"\"\"\n        try:\n            string: str = \"Key(\"\n            if self.key is not None:\n                string += \"key: {}\".format(self.key.hex())\n            if self.serversalt is not None:\n                string += \" , serversalt: {}\".format(self.serversalt.hex())\n            if self.googleid is not None:\n                string += \" , googleid: {}\".format(self.googleid.hex())\n            if self.key_version is not None:\n                string += \" , key_version: {}\".format(self.key_version.hex())\n            if self.cipher_version is not None:\n                string += \" , cipher_version: {}\".format(self.cipher_version.hex())\n            return string + \")\"\n        except Exception as e:\n            return \"Exception printing key: {}\".format(e)\n\n    def __init__(self, logger, key_file_name):\n        \"\"\"Deserializes a key file into a byte array.\"\"\"\n        self.key = None\n        self.serversalt = None\n        self.googleid = None\n        self.key_version = None\n        self.cipher_version = None\n\n        keyfile: bytes = b''\n\n        logger.v(\"Reading keyfile...\")\n\n        # Try to open the keyfile.\n        try:\n            key_file_stream = open(key_file_name, 'rb')\n            try:\n                # Deserialize the byte object written in the file\n                jarr: javaobj.beans.JavaArray = javaobj.load(key_file_stream).data\n                # Convert from a list of Int8 to a byte array\n                keyfile: bytes = javaintlist2bytes(jarr)\n\n            except (ValueError, RuntimeError) as e:\n                logger.f(\"The keyfile is not a valid Java object: {}\".format(e))\n\n        except OSError:\n            # Try to see if it is a hex-encoded key.\n            keyfile = from_hex(logger, key_file_name)\n\n        # We guess the key type from its length\n        if len(keyfile) == 131:\n            self.load_crypt14(logger, keyfile=keyfile)\n        elif len(keyfile) == 32:\n            self.load_crypt15(logger, keyfile=keyfile)\n        else:\n            logger.f(\"Unrecognized key file format.\")\n\n    def load_crypt14(self, logger, keyfile: bytes):\n        \"\"\"Extracts the fields from a crypt14 loaded key file.\"\"\"\n        # key file format and encoding explanation:\n        # The key file is actually a serialized byte[] object.\n\n        # After deserialization, we will have a byte[] object that we have to split in:\n        # 1) The cipher version (2 bytes). Known values are 0x0000 and 0x0001. So far we only support the latter.\n        # SUPPORTED_CIPHER_VERSION = b'\\x00\\x01'\n        # 2) The key version (1 byte). All the known versions are supported.\n        # SUPPORTED_KEY_VERSIONS = [b'\\x01', b'\\x02', b'\\x03']\n        # Looks like nothing actually changes between the versions.\n        # 3) Server salt (32 bytes)\n        # 4) googleIdSalt (unused?) (16 bytes)\n        # 5) hashedGoogleID (The SHA-256 hash of googleIdSalt) (32 bytes)\n        # 6) encryption IV (zeroed out, as it is read from the database) (16 bytes)\n        # 7) cipherKey (The actual AES-256 decryption key) (32 bytes)\n\n        # Check if the keyfile has a supported cipher version\n        self.cipher_version = keyfile[:len(self.SUPPORTED_CIPHER_VERSION)]\n        if self.SUPPORTED_CIPHER_VERSION != self.cipher_version:\n            logger.e(\"Invalid keyfile: Unsupported cipher version {}\"\n                     .format(keyfile[:len(self.SUPPORTED_CIPHER_VERSION)].hex()))\n        index = len(self.SUPPORTED_CIPHER_VERSION)\n\n        # Check if the keyfile has a supported key version\n        version_supported = False\n        for v in self.SUPPORTED_KEY_VERSIONS:\n            if v == keyfile[index:index + len(self.SUPPORTED_KEY_VERSIONS[0])]:\n                version_supported = True\n                self.key_version = v\n                break\n        if not version_supported:\n            logger.e('Invalid keyfile: Unsupported key version {}'\n                     .format(keyfile[index:index + len(self.SUPPORTED_KEY_VERSIONS[0])].hex()))\n\n        self.serversalt = keyfile[3:35]\n\n        # Check the SHA-256 of the salt\n        self.googleid = keyfile[35:51]\n        expected_digest = sha256(self.googleid).digest()\n        actual_digest = keyfile[51:83]\n        if expected_digest != actual_digest:\n            logger.e(\"Invalid keyfile: Invalid SHA-256 of salt.\\n    \"\n                     \"Expected: {}\\n    Got:{}\".format(expected_digest, actual_digest))\n\n        padding = keyfile[83:99]\n\n        # Check if IV is made of zeroes\n        for byte in padding:\n            if byte:\n                logger.e(\"Invalid keyfile: IV is not zeroed out but is: {}\".format(padding.hex()))\n                break\n\n        self.key = keyfile[99:]\n\n        logger.i(\"Crypt12/14 key loaded\")\n\n    def load_crypt15(self, logger, keyfile: bytes):\n        \"\"\"Extracts the key from a loaded crypt15 key file.\"\"\"\n        # encrypted_backup.key file format and encoding explanation:\n        # The E2E key file is actually a serialized byte[] object.\n\n        # After deserialization, we will have the root key (32 bytes).\n        # The root key is further encoded with three different strings, depending on what you want to do.\n        # These three ways are \"backup encryption\";\n        # \"metadata encryption\" and \"metadata authentication\", for Google Drive E2E encrypted metadata.\n        # We are only interested in the local backup encryption.\n\n        # Why the \\x01 at the end of the BACKUP_ENCRYPTION constant?\n        # Whatsapp uses a nested encryption function to encrypt many times the same data.\n        # The iteration counter is appended to the end of the encrypted data. However,\n        # since the loop is actually executed only one time, we will only have one interaction,\n        # and thus a \\x01 at the end.\n        # Take a look at utils/wa_hmacsha256_loop.java that is the original code.\n\n        if len(keyfile) != 32:\n            logger.f(\"Crypt15 loader trying to load a crypt14 key\")\n\n        # First do the HMACSHA256 hash of the file with an empty private key\n        self.key: bytes = hmac.new(b'\\x00' * 32, keyfile, sha256).digest()\n        # Then do the HMACSHA256 using the previous result as key and (\"backup encryption\" + iteration count) as data\n        self.key = hmac.new(self.key, self.BACKUP_ENCRYPTION, sha256).digest()\n\n        logger.i(\"Crypt15 / Raw key loaded\")\n\n\ndef oscillate(n: int, n_min: int, n_max: int) -> collections.Iterable:\n    \"\"\"Yields n, n-1, n+1, n-2, n+2..., with constraints:\n    - n is in [min, max]\n    - n is never negative\n    Reverts to range() when n touches min or max. Example:\n    oscillate(8, 2, 10) => 8, 7, 9, 6, 10, 5, 4, 3, 2\n    \"\"\"\n\n    if n_min < 0:\n        n_min = 0\n\n    i = n\n    c = 1\n\n    # First phase (n, n-1, n+1...)\n    while True:\n\n        if i == n_max:\n            break\n        yield i\n        i = i - c\n        c = c + 1\n\n        if i == 0 or i == n_min:\n            break\n        yield i\n        i = i + c\n        c = c + 1\n\n    # Second phase (range of remaining numbers)\n    # n != i/2 fixes a bug where we would yield min and max two times if n == (max-min)/2\n    if i == n_min and n != i / 2:\n\n        yield i\n        i = i + c\n        for j in range(i, n_max + 1):\n            yield j\n\n    if i == n_max and n != i / 2:\n\n        yield n_max\n        i = i - c\n        for j in range(i, n_min - 1, -1):\n            yield j\n\n\ndef test_decompression(logger, test_data: bytes) -> bool:\n    \"\"\"Returns true if the SQLite header is valid.\n    It is assumed that the data are valid.\n    (If it is valid, it also means the decryption and decompression were successful.)\"\"\"\n\n    # If we get a ZIP file header, return true\n    if test_data[:4] == ZIP_HEADER:\n        return True\n\n    try:\n        zlib_obj = zlib.decompressobj().decompress(test_data)\n        # These two errors should never happen\n        if len(zlib_obj) < 16:\n            logger.e(\"Test decompression: chunk too small\")\n            return False\n        if zlib_obj[:15].decode('ascii') != 'SQLite format 3':\n            logger.e(\"Test decompression: Decryption and decompression ok but not a valid SQLite database\")\n            return logger.force\n        else:\n            return True\n    except zlib.error:\n        return False\n\n\ndef find_data_offset(logger, header: bytes, iv_offset: int, key: bytes, starting_data_offset: int) -> int:\n    \"\"\"Tries to find the offset in which the encrypted data starts.\n    Returns the offset or -1 if the offset is not found.\n    Only works with ZLIB stream, not with ZIP file.\"\"\"\n\n    iv = header[iv_offset:iv_offset + 16]\n\n    # oscillate ensures we try the closest values to the default value first.\n    for i in oscillate(n=starting_data_offset, n_min=iv_offset + len(iv), n_max=HEADER_SIZE - 128):\n\n        cipher = AES.new(key, AES.MODE_GCM, iv)\n\n        # We only decrypt the first two bytes.\n        test_bytes = cipher.decrypt(header[i:i + 2])\n\n        for zheader in ZLIB_HEADERS:\n\n            if test_bytes == zheader:\n                # We found a match, but this might also happen by chance.\n                # Let's run another test by decrypting some hundreds of bytes.\n                # We need to reinitialize the cipher everytime as it has an internal status.\n                cipher = AES.new(key, AES.MODE_GCM, iv)\n                decrypted = cipher.decrypt(header[i:])\n                if test_decompression(logger, decrypted):\n                    return i\n    return -1\n\n\ndef guess_offsets(logger, key: bytes, file_hash: _Hash, encrypted: BufferedReader, def_iv_offset: int,\n                  def_data_offset: int):\n    \"\"\"Gets the IV, shifts the stream to the beginning of the encrypted data and returns the cipher.\n    It does so by guessing the offset.\"\"\"\n\n    # Assign variables to suppress warnings\n    db_header, data_offset, iv_offset = None, None, None\n\n    # Restart the file stream\n    encrypted.seek(0)\n\n    db_header = encrypted.read(HEADER_SIZE)\n    if len(db_header) < HEADER_SIZE:\n        logger.f(\"The encrypted database is too small.\\n    \"\n                 \"Did you swap the keyfile and the encrypted database file by mistake?\")\n        raise Exception(\"The encrypted database is too small.\\n    \"\n                 \"Did you swap the keyfile and the encrypted database file by mistake?\")\n\n    try:\n        if db_header[:15].decode('ascii') == 'SQLite format 3':\n            logger.e(\"The database file is not encrypted.\\n    \"\n                     \"Did you swap the input and the output files by mistake?\")\n            raise Exception(\"The database file is not encrypted.\\n    \"\n                     \"Did you swap the input and the output files by mistake?\")\n    except ValueError:\n        pass\n\n    # Finding WhatsApp's version is nice\n    version = findall(b\"\\\\d(?:\\\\.\\\\d{1,3}){3}\", db_header)\n    if len(version) != 1:\n        logger.i('WhatsApp version not found (Crypt12?)')\n    else:\n        logger.v(\"WhatsApp version: {}\".format(version[0].decode('ascii')))\n\n    # Determine IV offset and data offset.\n    for iv_offset in oscillate(n=def_iv_offset, n_min=0, n_max=HEADER_SIZE - 128):\n        data_offset = find_data_offset(logger, db_header, iv_offset, key, def_data_offset)\n        if data_offset != -1:\n            logger.i(\"Offsets guessed (IV: {}, data: {}).\".format(iv_offset, data_offset))\n            if iv_offset != def_iv_offset or data_offset != def_data_offset:\n                logger.i(\"Next time, use -ivo {} -do {} for guess-free decryption\".format(iv_offset, data_offset))\n            break\n    if data_offset == -1:\n        return None\n\n    iv = db_header[iv_offset:iv_offset + 16]\n\n    encrypted.seek(data_offset)\n\n    file_hash.update(db_header[:data_offset])\n\n    return AES.new(key, AES.MODE_GCM, iv)\n\n\ndef javaintlist2bytes(barr: javaobj.beans.JavaArray) -> bytes:\n    \"\"\"Converts a javaobj bytearray which somehow became a list of signed integers back to a Python byte array\"\"\"\n    out: bytes = b''\n    for i in barr:\n        out += i.to_bytes(1, byteorder='big', signed=True)\n    return out\n\ndef check_crypt12(logger, file_hash, key, encrypted):\n    \"\"\"Checks if the file is a Crypt12 file.\n    Returns the cipher if it is, None otherwise.\"\"\"\n\n    \"\"\"\n    The crypt12 file format is similar to the crypt14 file format.\n    It is a \"raw\" header, which means it's not a protobuf message,\n    nor a serialized java object.\n    Structure:\n    Cipher version (2 bytes)\n    Key version (1 byte)\n    Server salt (32 bytes)\n    Google ID (16 bytes)\n    IV (16 bytes)\n    ( so we finally understood why the IV is at offset 51 ... )\n    \"\"\"\n    def quit_12():\n        encrypted.seek(0)\n        logger.v(\"Not a Crypt12 file, or corrupted\")\n        raise ValueError\n\n    if key.is_crypt15():\n        quit_12()\n\n    # We can read and discard the bytes, because the information\n    # are already in the keyfile.\n\n    test_bytes = encrypted.read(2)\n    if test_bytes != key.cipher_version:\n        quit_12()\n    file_hash.update(test_bytes)\n\n    test_bytes = encrypted.read(1)\n    if test_bytes != key.key_version:\n        quit_12()\n    file_hash.update(test_bytes)\n\n    test_bytes = encrypted.read(32)\n    if test_bytes != key.serversalt:\n        quit_12()\n    file_hash.update(test_bytes)\n\n    test_bytes = encrypted.read(16)\n    if test_bytes != key.googleid:\n        quit_12()\n    file_hash.update(test_bytes)\n\n    iv = encrypted.read(16)\n    file_hash.update(iv)\n\n    # We are done here\n    logger.i(\"Database header parsed\")\n    return AES.new(key.key, AES.MODE_GCM, iv)\n\n\n\n\n\ndef parse_protobuf(logger, file_hash: _Hash, key: Key, encrypted):\n    \"\"\"Parses the database header, gets the IV,\n     shifts the stream to the beginning of the encrypted data and returns the cipher.\n    It does so by parsing the protobuf message.\"\"\"\n\n    try:\n        import decryption.dbs.WhatsAppCrypt14Crypt15Decrypter.proto.prefix_pb2 as prefix\n        import decryption.dbs.WhatsAppCrypt14Crypt15Decrypter.proto.key_type_pb2 as key_type\n    except ImportError as e:\n        logger.e(\"Could not import the proto classes: {}\".format(e))\n        if str(e).startswith(\"cannot import name 'builder' from 'google.protobuf.internal'\"):\n            logger.e(\"You need to upgrade the protobuf library to at least 3.20.0.\\n\"\n                     \"    python -m pip install --upgrade protobuf\")\n        elif str(e).startswith(\"no module named\"):\n            logger.e(\"Please download them and put them in the \\\"proto\\\" sub folder.\")\n        return None\n    except AttributeError as e:\n        logger.e(\"Could not import the proto classes: {}\\n    \".format(e) +\n                 \"Your protobuf library is probably too old.\\n    \"\n                 \"Please upgrade to at least version 3.20.0 , by running:\\n    \"\n                 \"python -m pip install --upgrade protobuf\")\n        return None\n\n    p = prefix.prefix()\n\n    logger.v(\"Parsing database header...\")\n\n    try:\n\n        # The first byte is the size of the upcoming protobuf message\n        protobuf_size = encrypted.read(1)\n        file_hash.update(protobuf_size)\n        protobuf_size = int.from_bytes(protobuf_size, byteorder='big')\n\n        # It is my guess this is the backup type.\n        # Looks like it is 1 for msgstore and 8 for other types.\n        backup_type_raw = encrypted.read(1)\n        backup_type = int.from_bytes(backup_type_raw, byteorder='big')\n        if backup_type != 1:\n            if backup_type == 8:\n                logger.v(\"Not a (recent) msgstore database\")\n                # For some reason we need to go backward one byte\n                encrypted.seek(-1, 1)\n            else:\n                logger.e(\"Unexpected backup type: {}\".format(backup_type))\n        else:\n            file_hash.update(backup_type_raw)\n\n        try:\n\n            protobuf_raw = encrypted.read(protobuf_size)\n            file_hash.update(protobuf_raw)\n\n            if p.ParseFromString(protobuf_raw) != protobuf_size:\n                logger.e(\"Protobuf message not fully read. Please report a bug.\")\n            else:\n\n                # Checking and printing WA version and phone number\n                version = findall(r\"\\d(?:\\.\\d{1,3}){3}\", p.info.whatsapp_version)\n                if len(version) != 1:\n                    logger.e('WhatsApp version not found')\n                else:\n                    logger.v(\"WhatsApp version: {}\".format(version[0]))\n                if len(p.info.substringedUserJid) != 2:\n                    logger.e(\"The phone number end is not 2 characters long\")\n                logger.v(\"Your phone number ends with {}\".format(p.info.substringedUserJid))\n\n                if len(p.c15_iv.IV) != 0:\n                    # DB Header is crypt15\n                    if not key.is_crypt15():\n                        logger.e(\"You are using a crypt14 key file with a crypt15 backup.\")\n                    if len(p.c15_iv.IV) != 16:\n                        logger.e(\"IV is not 16 bytes long but is {} bytes long\".format(len(p.c15_iv.IV)))\n                    iv = p.c15_iv.IV\n\n                elif len(p.c14_cipher.IV) != 0:\n\n                    # DB Header is crypt14\n                    if key.is_crypt15():\n                        logger.f(\"You are using a crypt15 key file with a crypt14 backup.\")\n\n                    # if key.cipher_version != p.c14_cipher.version.cipher_version:\n                    #    logger.e(\"Cipher version mismatch: {} != {}\"\n                    #    .format(key.cipher_version, p.c14_cipher.cipher_version))\n\n                    # Fix bytes to string encoding\n                    key.key_version = (key.key_version[0] + 48).to_bytes(1, byteorder='big')\n                    if key.key_version != p.c14_cipher.key_version:\n                        if key.key_version > p.c14_cipher.key_version:\n                            logger.e(\"Key version mismatch: {} != {} .\\n    \"\n                                     .format(key.key_version, p.c14_cipher.key_version) +\n                                     \"Your backup is too old for this key file.\\n    \" +\n                                     \"Please try using a newer backup.\")\n                        elif key.key_version < p.c14_cipher.key_version:\n                            logger.e(\"Key version mismatch: {} != {} .\\n    \"\n                                     .format(key.key_version, p.c14_cipher.key_version) +\n                                     \"Your backup is too new for this key file.\\n    \" +\n                                     \"Please try using an older backup, or getting the new key.\")\n                        else:\n                            logger.e(\"Key version mismatch: {} != {} (?)\"\n                                     .format(key.key_version, p.c14_cipher.key_version))\n                    if key.serversalt != p.c14_cipher.server_salt:\n                        logger.e(\"Server salt mismatch: {} != {}\".format(key.serversalt, p.c14_cipher.server_salt))\n                    if key.googleid != p.c14_cipher.google_id:\n                        logger.e(\"Google ID mismatch: {} != {}\".format(key.googleid, p.c14_cipher.google_id))\n                    if len(p.c14_cipher.IV) != 16:\n                        logger.e(\"IV is not 16 bytes long but is {} bytes long\".format(len(p.c14_cipher.IV)))\n                    iv = p.c14_cipher.IV\n\n                else:\n                    logger.e(\"Could not parse the IV from the protobuf message. Please report a bug.\")\n                    return None\n\n                # We are done here\n                logger.i(\"Database header parsed\")\n                return AES.new(key.key, AES.MODE_GCM, iv)\n\n        except DecodeError as e:\n            print(e)\n\n    except OSError as e:\n        logger.f(\"Reading database header failed: {}\".format(e))\n\n    logger.e(\"Could not parse the protobuf message. Please report a bug.\")\n    return None\n\n\ndef decrypt(logger, file_hash: _Hash, cipher, encrypted, decrypted, buffer_size: int = 0):\n    \"\"\"Does the actual decryption.\"\"\"\n\n    z_obj = zlib.decompressobj()\n\n    if cipher is None:\n        logger.f(\"Could not create a decryption cipher\")\n\n    try:\n\n        if buffer_size == 0:\n            # Load the encrypted file into RAM, decrypts into RAM,\n            # decompresses into RAM, writes into disk.\n            # More RAM used (~x3), less I/O used\n            try:\n                encrypted_data = encrypted.read()\n                # Crypt12 moment: the last 4 bytes are --xx, where xx\n                # are the last 2 numbers of the jid (user's phone number).\n                # We need to remove them.\n                crypt12_footer = str(encrypted_data[-4:])\n                # Looks like a complicated regex, but it's just\n                # \"if it's --xx or xxxx\"\n                jid = findall(r\"(?:-|\\d)(?:-|\\d)(\\d\\d)\", crypt12_footer)\n                if len(jid) == 1:\n                    # Confirmed to be crypt12\n                    encrypted_data = encrypted_data[:-4]\n                    logger.v(\"Your phone number ends with {}\".format(jid[0]))\n                checksum = encrypted_data[-16:]\n                authentication_tag = encrypted_data[-32:-16]\n                encrypted_data = encrypted_data[:-32]\n                is_multifile_backup = False\n\n\n                file_hash.update(encrypted_data)\n                file_hash.update(authentication_tag)\n\n                if file_hash.digest() != checksum:\n                    # We are probably in a multifile backup, which does not have a checksum.\n                    is_multifile_backup = True\n                else:\n                    logger.v(\"Checksum OK ({}). Decrypting...\".format(file_hash.hexdigest()))\n\n                try:\n                    output_decrypted: bytearray = cipher.decrypt(encrypted_data)\n                except ValueError as e:\n                    logger.f(\"Decryption failed: {}.\"\n                             \"\\n    This probably means your backup is corrupted.\".format(e))\n                    # Dead code to make pycharm warning go away\n                    exit(1)\n\n                # Verify the authentication tag\n                try:\n                    if is_multifile_backup:\n                        # In multifile backups, there is no checksum.\n                        # This means, the last 16 bytes of the files are not the checksum,\n                        # despite being called \"checksum\", but are the authentication tag.\n                        # Same way, \"authentication tag\" is not the tag, but the last\n                        # 16 bytes of the encrypted file.\n                        output_decrypted += cipher.decrypt(authentication_tag)\n                        cipher.verify(checksum)\n                    else:\n                        cipher.verify(authentication_tag)\n                except ValueError as e:\n                    logger.e(\"Authentication tag mismatch: {}.\"\n                             \"\\n    This probably means your backup is corrupted.\".format(e))\n\n                try:\n                    output_file = z_obj.decompress(output_decrypted)\n                    if not z_obj.eof:\n                        logger.e(\"The encrypted database file is truncated (damaged).\")\n                except zlib.error:\n                    output_file = output_decrypted\n                    if test_decompression(logger, output_file[:io.DEFAULT_BUFFER_SIZE]):\n                        logger.i(\"Decrypted data is a ZIP file that I will not decompress automatically.\")\n                    else:\n                        logger.e(\"I can't recognize decrypted data. Decryption not successful.\\n    \"\n                                 \"The key probably does not match with the encrypted file.\\n    \"\n                                 \"Or the backup is simply empty. (check with --force)\")\n\n                decrypted.write(output_file)\n\n            except MemoryError:\n                logger.f(\"Out of RAM, please use -nm.\")\n\n        else:\n\n            if buffer_size < 17:\n                logger.i(\"Invalid buffer size, will use default of {}\".format(io.DEFAULT_BUFFER_SIZE))\n                buffer_size = io.DEFAULT_BUFFER_SIZE\n\n            # Does the thing above but only with DEFAULT_BUFFER_SIZE bytes at a time.\n            # Less RAM used, more I/O used\n            # TODO use assignment expression, which drops compatibility with 3.7\n            # while chunk := encrypted.read(DEFAULT_BUFFER_SIZE):\n\n            is_zip = True\n\n            chunk = None\n\n            logger.v(\"Reading and decrypting...\")\n\n            while True:\n\n                # We will need to manage two chunks at a time, because we might have\n                # the checksum in both the last chunk and the chunk before that.\n                # This makes the logic more complicated, but it's the only way to.\n\n                next_chunk = None\n                checksum = None\n\n                if chunk is None:\n                    # First read\n                    try:\n                        chunk = encrypted.read(buffer_size)\n                    except MemoryError:\n                        logger.f(\"Out of RAM, please use a smaller buffer size.\")\n                    if len(chunk) < buffer_size:\n                        # Just error out, handling this case is too complicated.\n                        # If the file is so small, the user can just load the whole thing into RAM.\n                        logger.f(\"Buffer size too large, use a smaller buffer size or don't use a buffer.\")\n                    continue\n\n                try:\n                    next_chunk = encrypted.read(buffer_size)\n                except MemoryError:\n                    logger.f(\"Out of RAM, please use a smaller buffer size.\")\n\n                if len(next_chunk) <= 36:\n                    # Last bytes read. Three cases:\n                    # 1. The checksum is entirely in the last chunk\n                    if len(next_chunk) == 36:\n                        checksum = next_chunk\n                    # 2. The checksum is entirely in the chunk before the last\n                    elif len(next_chunk) == 0:\n                        checksum = chunk[-36:]\n                        chunk = chunk[:-36]\n                    # 3. The checksum is split between the last two chunks\n                    else:\n                        checksum = chunk[-(36 - len(next_chunk)):] + next_chunk\n                        chunk = chunk[:-(36 - len(next_chunk))]\n\n                file_hash.update(chunk)\n\n                decrypted_chunk = cipher.decrypt(chunk)\n                if is_zip:\n                    try:\n                        decrypted.write(z_obj.decompress(decrypted_chunk))\n                    except zlib.error:\n                        if test_decompression(logger, decrypted_chunk):\n                            logger.i(\"Decrypted data is a ZIP file that I will not decompress automatically.\")\n                        else:\n                            logger.e(\"I can't recognize decrypted data. Decryption not successful.\\n    \"\n                                     \"The key probably does not match with the encrypted file.\")\n                        is_zip = False\n                        decrypted.write(decrypted_chunk)\n                else:\n                    decrypted.write(decrypted_chunk)\n\n                # The presence of the checksum tells us it's the last chunk\n                if checksum is not None:\n                    is_multifile_backup = False\n\n                    crypt12_footer = str(checksum[-4:])\n                    jid = findall(r\"(?:-|\\d)(?:-|\\d)(\\d\\d)\", crypt12_footer)\n                    if len(jid) == 1:\n                        # Confirmed to be crypt12\n                        checksum = checksum[:-4]\n                        logger.v(\"Your phone number ends with {}\".format(jid[0]))\n                    else:\n                        # Shift everything forward by 4 bytes\n                        chunk = checksum[:4]\n                        file_hash.update(chunk)\n                        decrypted_chunk = cipher.decrypt(chunk)\n                        if is_zip:\n                            try:\n                                decrypted.write(z_obj.decompress(decrypted_chunk))\n                            except zlib.error:\n                                logger.e(\"Backup is corrupted.\")\n                                decrypted.write(decrypted_chunk)\n                        else:\n                            decrypted.write(decrypted_chunk)\n                        checksum = checksum[4:]\n\n                    file_hash.update(checksum[:16])\n                    if file_hash.digest() != checksum[16:]:\n                        is_multifile_backup = True\n                    else:\n                        logger.v(\"Checksum OK ({})!\".format(file_hash.hexdigest()))\n                    try:\n                        if is_multifile_backup:\n                            decrypted.write(cipher.decrypt(checksum[:16]))\n                            cipher.verify(checksum[16:])\n                        else:\n                            cipher.verify(checksum[:16])\n                    except ValueError as e:\n                        logger.e(\"Authentication tag mismatch: {}.\"\n                                 \"\\n    This probably means your backup is corrupted.\".format(e))\n                    break\n\n                chunk = next_chunk\n\n            if is_zip and not z_obj.eof:\n\n                if not logger.force:\n                    decrypted.truncate(0)\n                logger.e(\"The encrypted database file is truncated (damaged).\")\n\n        decrypted.flush()\n\n    except OSError as e:\n        logger.f(\"I/O error: {}\".format(e))\n\n    finally:\n        decrypted.close()\n        encrypted.close()\n\n\ndef main():\n    args = parsecmdline()\n    logger = SimpleLog(verbose=args.verbose, force=args.force)\n    if not (0 < args.data_offset < HEADER_SIZE - 128):\n        logger.f(\"The data offset must be between 1 and {}\".format(HEADER_SIZE - 129))\n    if not (0 < args.iv_offset < HEADER_SIZE - 128):\n        logger.f(\"The IV offset must be between 1 and {}\".format(HEADER_SIZE - 129))\n    if args.buffer_size is not None:\n        if not 1 < args.buffer_size < maxsize:\n            logger.f(\"Invalid buffer size\")\n    # Get the decryption key from the key file or the hex encoded string.\n    key = Key(logger, args.keyfile)\n    logger.v(str(key))\n    cipher = None\n    file_hash = md5()\n    # Now we have to get the IV and to guess where the data starts.\n    # We have two approaches to do so.\n    # First: try parsing the protobuf message.\n    if not args.no_protobuf:\n        # Check if the backup is crypt12 first.\n        try:\n            cipher = check_crypt12(logger, file_hash, key, args.encrypted)\n        except ValueError:\n            cipher = parse_protobuf(logger=logger, file_hash=file_hash, key=key, encrypted=args.encrypted)\n\n    if cipher is None and not args.no_guess:\n        # If parsing the protobuf message failed, we try guessing the offsets.\n        cipher = guess_offsets(logger=logger, file_hash=file_hash, key=key.key, encrypted=args.encrypted,\n                               def_iv_offset=args.iv_offset, def_data_offset=args.data_offset)\n\n    if args.buffer_size is not None:\n        decrypt(logger, file_hash, cipher, args.encrypted, args.decrypted, args.buffer_size)\n    elif args.no_mem:\n        decrypt(logger, file_hash, cipher, args.encrypted, args.decrypted, io.DEFAULT_BUFFER_SIZE)\n    else:\n        decrypt(logger, file_hash, cipher, args.encrypted, args.decrypted)\n\n    if date.today().day == 1 and date.today().month == 4:\n        logger.i(\"Done. Uploading messages to the developer's server...\")\n        sleep(0.5)\n        logger.i(\"Uploaded. The developer will now read and publish your messages!\")\n    else:\n        logger.i(\"Done\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/C14_cipher.proto",
    "content": "syntax = \"proto3\";\n\nimport \"C14_cipher_version.proto\";\n// crypt14 cipher files.\nmessage C14_cipher {\n    //For some reason, the int inside this message has a \"0\" field tag\n    //So we just ignore it.\n    //optional C14_cipher_version version = 1;\n    bytes key_version = 2; // Is usually \"1\"\n    bytes server_salt = 3; // The 32-bytes long server salt\n    bytes google_id = 4; // The 16-bytes long google id salt\n    bytes IV = 5; // The 16-bytes long IV\n}"
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/C14_cipher_pb2.py",
    "content": "# -*- coding: utf-8 -*-\n# Generated by the protocol buffer compiler.  DO NOT EDIT!\n# source: C14_cipher.proto\n\"\"\"Generated protocol buffer code.\"\"\"\nfrom google.protobuf.internal import builder as _builder\nfrom google.protobuf import descriptor as _descriptor\nfrom google.protobuf import descriptor_pool as _descriptor_pool\nfrom google.protobuf import symbol_database as _symbol_database\n# @@protoc_insertion_point(imports)\n\n_sym_db = _symbol_database.Default()\n\n\nimport proto.C14_cipher_version_pb2 as C14__cipher__version__pb2\n\n\nDESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\\n\\x10\\x43\\x31\\x34_cipher.proto\\x1a\\x18\\x43\\x31\\x34_cipher_version.proto\\\"U\\n\\nC14_cipher\\x12\\x13\\n\\x0bkey_version\\x18\\x02 \\x01(\\x0c\\x12\\x13\\n\\x0bserver_salt\\x18\\x03 \\x01(\\x0c\\x12\\x11\\n\\tgoogle_id\\x18\\x04 \\x01(\\x0c\\x12\\n\\n\\x02IV\\x18\\x05 \\x01(\\x0c\\x62\\x06proto3')\n\n_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())\n_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'C14_cipher_pb2', globals())\nif _descriptor._USE_C_DESCRIPTORS == False:\n\n  DESCRIPTOR._options = None\n  _C14_CIPHER._serialized_start=46\n  _C14_CIPHER._serialized_end=131\n# @@protoc_insertion_point(module_scope)\n"
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/C14_cipher_version.proto",
    "content": "syntax = \"proto3\";\n\n// crypt14 cipher files. Actually the field tag is zero.\nmessage C14_cipher_version {\n    int32 version = 1;\n}"
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/C14_cipher_version_pb2.py",
    "content": "# -*- coding: utf-8 -*-\n# Generated by the protocol buffer compiler.  DO NOT EDIT!\n# source: C14_cipher_version.proto\n\"\"\"Generated protocol buffer code.\"\"\"\nfrom google.protobuf.internal import builder as _builder\nfrom google.protobuf import descriptor as _descriptor\nfrom google.protobuf import descriptor_pool as _descriptor_pool\nfrom google.protobuf import symbol_database as _symbol_database\n# @@protoc_insertion_point(imports)\n\n_sym_db = _symbol_database.Default()\n\n\n\n\nDESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\\n\\x18\\x43\\x31\\x34_cipher_version.proto\\\"%\\n\\x12\\x43\\x31\\x34_cipher_version\\x12\\x0f\\n\\x07version\\x18\\x01 \\x01(\\x05\\x62\\x06proto3')\n\n_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())\n_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'C14_cipher_version_pb2', globals())\nif _descriptor._USE_C_DESCRIPTORS == False:\n\n  DESCRIPTOR._options = None\n  _C14_CIPHER_VERSION._serialized_start=28\n  _C14_CIPHER_VERSION._serialized_end=65\n# @@protoc_insertion_point(module_scope)\n"
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/C15_IV.proto",
    "content": "syntax = \"proto3\";\n\n// In crypt15 files only the IV is stored.\nmessage C15_IV {\n    bytes IV = 1; // The 16-bytes long IV\n}"
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/C15_IV_pb2.py",
    "content": "# -*- coding: utf-8 -*-\n# Generated by the protocol buffer compiler.  DO NOT EDIT!\n# source: C15_IV.proto\n\"\"\"Generated protocol buffer code.\"\"\"\nfrom google.protobuf.internal import builder as _builder\nfrom google.protobuf import descriptor as _descriptor\nfrom google.protobuf import descriptor_pool as _descriptor_pool\nfrom google.protobuf import symbol_database as _symbol_database\n# @@protoc_insertion_point(imports)\n\n_sym_db = _symbol_database.Default()\n\n\n\n\nDESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\\n\\x0c\\x43\\x31\\x35_IV.proto\\\"\\x14\\n\\x06\\x43\\x31\\x35_IV\\x12\\n\\n\\x02IV\\x18\\x01 \\x01(\\x0c\\x62\\x06proto3')\n\n_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())\n_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'C15_IV_pb2', globals())\nif _descriptor._USE_C_DESCRIPTORS == False:\n\n  DESCRIPTOR._options = None\n  _C15_IV._serialized_start=16\n  _C15_IV._serialized_end=36\n# @@protoc_insertion_point(module_scope)\n"
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/key_type.proto",
    "content": "syntax = \"proto3\";\n\n// This enum describes if the key is self-managed by WhatsApp of if it is stored in the HSM.\n// In other words, traditional = 0, end-to-end = 1\nenum Key_Type {\n    WA_PROVIDED = 0;\n    HSM_CONTROLLED = 1;\n}"
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/key_type_pb2.py",
    "content": "# -*- coding: utf-8 -*-\n# Generated by the protocol buffer compiler.  DO NOT EDIT!\n# source: key_type.proto\n\"\"\"Generated protocol buffer code.\"\"\"\nfrom google.protobuf.internal import builder as _builder\nfrom google.protobuf import descriptor as _descriptor\nfrom google.protobuf import descriptor_pool as _descriptor_pool\nfrom google.protobuf import symbol_database as _symbol_database\n# @@protoc_insertion_point(imports)\n\n_sym_db = _symbol_database.Default()\n\n\n\n\nDESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\\n\\x0ekey_type.proto*/\\n\\x08Key_Type\\x12\\x0f\\n\\x0bWA_PROVIDED\\x10\\x00\\x12\\x12\\n\\x0eHSM_CONTROLLED\\x10\\x01\\x62\\x06proto3')\n\n_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())\n_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'key_type_pb2', globals())\nif _descriptor._USE_C_DESCRIPTORS == False:\n\n  DESCRIPTOR._options = None\n  _KEY_TYPE._serialized_start=18\n  _KEY_TYPE._serialized_end=65\n# @@protoc_insertion_point(module_scope)\n"
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/prefix.proto",
    "content": "syntax = \"proto3\";\nimport \"C14_cipher.proto\";\nimport \"C15_IV.proto\";\nimport \"key_type.proto\";\nimport \"version_features.proto\";\n\n/*\nThis file describes the header you can find near the start of an encrypted backup file.\n */\nmessage prefix {\n    Key_Type key_type = 1; // 0 if traditional (crypt14), 1 if end-to-end (crypt15)\n    oneof cipher_info {\n        C14_cipher c14_cipher = 2; // If DB is crypt14\n        C15_IV c15_iv = 3; // If DB is crypt15\n    }\n    // Version that generated backup and other infos\n    Version_Features info = 4;\n}"
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/prefix_pb2.py",
    "content": "# -*- coding: utf-8 -*-\n# Generated by the protocol buffer compiler.  DO NOT EDIT!\n# source: prefix.proto\n\"\"\"Generated protocol buffer code.\"\"\"\nfrom google.protobuf.internal import builder as _builder\nfrom google.protobuf import descriptor as _descriptor\nfrom google.protobuf import descriptor_pool as _descriptor_pool\nfrom google.protobuf import symbol_database as _symbol_database\n# @@protoc_insertion_point(imports)\n\n_sym_db = _symbol_database.Default()\n\n\nimport proto.C14_cipher_pb2 as C14__cipher__pb2\nimport proto.C15_IV_pb2 as C15__IV__pb2\nimport proto.key_type_pb2 as key__type__pb2\nimport proto.version_features_pb2 as version__features__pb2\n\n\nDESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\\n\\x0cprefix.proto\\x1a\\x10\\x43\\x31\\x34_cipher.proto\\x1a\\x0c\\x43\\x31\\x35_IV.proto\\x1a\\x0ekey_type.proto\\x1a\\x16version_features.proto\\\"\\x93\\x01\\n\\x06prefix\\x12\\x1b\\n\\x08key_type\\x18\\x01 \\x01(\\x0e\\x32\\t.Key_Type\\x12!\\n\\nc14_cipher\\x18\\x02 \\x01(\\x0b\\x32\\x0b.C14_cipherH\\x00\\x12\\x19\\n\\x06\\x63\\x31\\x35_iv\\x18\\x03 \\x01(\\x0b\\x32\\x07.C15_IVH\\x00\\x12\\x1f\\n\\x04info\\x18\\x04 \\x01(\\x0b\\x32\\x11.Version_FeaturesB\\r\\n\\x0b\\x63ipher_infob\\x06proto3')\n\n_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())\n_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'prefix_pb2', globals())\nif _descriptor._USE_C_DESCRIPTORS == False:\n\n  DESCRIPTOR._options = None\n  _PREFIX._serialized_start=89\n  _PREFIX._serialized_end=236\n# @@protoc_insertion_point(module_scope)\n"
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/version_features.proto",
    "content": "syntax = \"proto3\";\n// This describes the metadata, e.g. the version, the ph number and various features.\nmessage Version_Features {\n    string whatsapp_version = 1; // Whatsapp version, for example \"2.22.4.14\"\n    string substringedUserJid = 3; // The last two characters of the user's Jid (phone number)\n    // This bools are only written if the backup is a msgstore backup.\n    optional bool idk = 4; // No idea what this is\n    optional bool call_log = 5; // Booleans that indicate various features\n    optional bool labeled_jid = 6;\n    optional bool message_fts = 7;\n    optional bool blank_me_jid = 8;\n    optional bool message_link = 9;\n    optional bool message_main = 10;\n    optional bool message_text = 11;\n    optional bool missed_calls = 12;\n    optional bool receipt_user = 13;\n    optional bool message_media = 14;\n    optional bool message_vcard = 15;\n    optional bool message_future = 16;\n    optional bool message_quoted = 17;\n    optional bool message_system = 18;\n    optional bool receipt_device = 19;\n    optional bool message_mention = 20;\n    optional bool message_revoked = 21;\n    optional bool broadcast_me_jid = 22;\n    optional bool message_frequent = 23;\n    optional bool message_location = 24;\n    optional bool participant_user = 25;\n    optional bool message_thumbnail = 26;\n    optional bool message_send_count = 27;\n    optional bool migration_jid_store = 28;\n    optional bool payment_transaction = 29;\n    optional bool migration_chat_store = 30;\n    optional bool quoted_order_message = 31;\n    optional bool media_migration_fixer = 32;\n    optional bool quoted_order_message_v2 = 33;\n    optional bool message_main_verification = 34;\n    optional bool quoted_ui_elements_reply_message = 35;\n    optional bool alter_message_ephemeral_to_message_ephemeral_remove_column = 36;\n    optional bool alter_message_ephemeral_setting_to_message_ephemeral_setting_remove_column = 37;\n}\n"
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/version_features_pb2.py",
    "content": "# -*- coding: utf-8 -*-\n# Generated by the protocol buffer compiler.  DO NOT EDIT!\n# source: version_features.proto\n\"\"\"Generated protocol buffer code.\"\"\"\nfrom google.protobuf.internal import builder as _builder\nfrom google.protobuf import descriptor as _descriptor\nfrom google.protobuf import descriptor_pool as _descriptor_pool\nfrom google.protobuf import symbol_database as _symbol_database\n# @@protoc_insertion_point(imports)\n\n_sym_db = _symbol_database.Default()\n\n\n\n\nDESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\\n\\x16version_features.proto\\\"\\xd6\\x0f\\n\\x10Version_Features\\x12\\x18\\n\\x10whatsapp_version\\x18\\x01 \\x01(\\t\\x12\\x1a\\n\\x12substringedUserJid\\x18\\x03 \\x01(\\t\\x12\\x10\\n\\x03idk\\x18\\x04 \\x01(\\x08H\\x00\\x88\\x01\\x01\\x12\\x15\\n\\x08\\x63\\x61ll_log\\x18\\x05 \\x01(\\x08H\\x01\\x88\\x01\\x01\\x12\\x18\\n\\x0blabeled_jid\\x18\\x06 \\x01(\\x08H\\x02\\x88\\x01\\x01\\x12\\x18\\n\\x0bmessage_fts\\x18\\x07 \\x01(\\x08H\\x03\\x88\\x01\\x01\\x12\\x19\\n\\x0c\\x62lank_me_jid\\x18\\x08 \\x01(\\x08H\\x04\\x88\\x01\\x01\\x12\\x19\\n\\x0cmessage_link\\x18\\t \\x01(\\x08H\\x05\\x88\\x01\\x01\\x12\\x19\\n\\x0cmessage_main\\x18\\n \\x01(\\x08H\\x06\\x88\\x01\\x01\\x12\\x19\\n\\x0cmessage_text\\x18\\x0b \\x01(\\x08H\\x07\\x88\\x01\\x01\\x12\\x19\\n\\x0cmissed_calls\\x18\\x0c \\x01(\\x08H\\x08\\x88\\x01\\x01\\x12\\x19\\n\\x0creceipt_user\\x18\\r \\x01(\\x08H\\t\\x88\\x01\\x01\\x12\\x1a\\n\\rmessage_media\\x18\\x0e \\x01(\\x08H\\n\\x88\\x01\\x01\\x12\\x1a\\n\\rmessage_vcard\\x18\\x0f \\x01(\\x08H\\x0b\\x88\\x01\\x01\\x12\\x1b\\n\\x0emessage_future\\x18\\x10 \\x01(\\x08H\\x0c\\x88\\x01\\x01\\x12\\x1b\\n\\x0emessage_quoted\\x18\\x11 \\x01(\\x08H\\r\\x88\\x01\\x01\\x12\\x1b\\n\\x0emessage_system\\x18\\x12 \\x01(\\x08H\\x0e\\x88\\x01\\x01\\x12\\x1b\\n\\x0ereceipt_device\\x18\\x13 \\x01(\\x08H\\x0f\\x88\\x01\\x01\\x12\\x1c\\n\\x0fmessage_mention\\x18\\x14 \\x01(\\x08H\\x10\\x88\\x01\\x01\\x12\\x1c\\n\\x0fmessage_revoked\\x18\\x15 \\x01(\\x08H\\x11\\x88\\x01\\x01\\x12\\x1d\\n\\x10\\x62roadcast_me_jid\\x18\\x16 \\x01(\\x08H\\x12\\x88\\x01\\x01\\x12\\x1d\\n\\x10message_frequent\\x18\\x17 \\x01(\\x08H\\x13\\x88\\x01\\x01\\x12\\x1d\\n\\x10message_location\\x18\\x18 \\x01(\\x08H\\x14\\x88\\x01\\x01\\x12\\x1d\\n\\x10participant_user\\x18\\x19 \\x01(\\x08H\\x15\\x88\\x01\\x01\\x12\\x1e\\n\\x11message_thumbnail\\x18\\x1a \\x01(\\x08H\\x16\\x88\\x01\\x01\\x12\\x1f\\n\\x12message_send_count\\x18\\x1b \\x01(\\x08H\\x17\\x88\\x01\\x01\\x12 \\n\\x13migration_jid_store\\x18\\x1c \\x01(\\x08H\\x18\\x88\\x01\\x01\\x12 \\n\\x13payment_transaction\\x18\\x1d \\x01(\\x08H\\x19\\x88\\x01\\x01\\x12!\\n\\x14migration_chat_store\\x18\\x1e \\x01(\\x08H\\x1a\\x88\\x01\\x01\\x12!\\n\\x14quoted_order_message\\x18\\x1f \\x01(\\x08H\\x1b\\x88\\x01\\x01\\x12\\\"\\n\\x15media_migration_fixer\\x18  \\x01(\\x08H\\x1c\\x88\\x01\\x01\\x12$\\n\\x17quoted_order_message_v2\\x18! \\x01(\\x08H\\x1d\\x88\\x01\\x01\\x12&\\n\\x19message_main_verification\\x18\\\" \\x01(\\x08H\\x1e\\x88\\x01\\x01\\x12-\\n quoted_ui_elements_reply_message\\x18# \\x01(\\x08H\\x1f\\x88\\x01\\x01\\x12G\\n:alter_message_ephemeral_to_message_ephemeral_remove_column\\x18$ \\x01(\\x08H \\x88\\x01\\x01\\x12W\\nJalter_message_ephemeral_setting_to_message_ephemeral_setting_remove_column\\x18% \\x01(\\x08H!\\x88\\x01\\x01\\x42\\x06\\n\\x04_idkB\\x0b\\n\\t_call_logB\\x0e\\n\\x0c_labeled_jidB\\x0e\\n\\x0c_message_ftsB\\x0f\\n\\r_blank_me_jidB\\x0f\\n\\r_message_linkB\\x0f\\n\\r_message_mainB\\x0f\\n\\r_message_textB\\x0f\\n\\r_missed_callsB\\x0f\\n\\r_receipt_userB\\x10\\n\\x0e_message_mediaB\\x10\\n\\x0e_message_vcardB\\x11\\n\\x0f_message_futureB\\x11\\n\\x0f_message_quotedB\\x11\\n\\x0f_message_systemB\\x11\\n\\x0f_receipt_deviceB\\x12\\n\\x10_message_mentionB\\x12\\n\\x10_message_revokedB\\x13\\n\\x11_broadcast_me_jidB\\x13\\n\\x11_message_frequentB\\x13\\n\\x11_message_locationB\\x13\\n\\x11_participant_userB\\x14\\n\\x12_message_thumbnailB\\x15\\n\\x13_message_send_countB\\x16\\n\\x14_migration_jid_storeB\\x16\\n\\x14_payment_transactionB\\x17\\n\\x15_migration_chat_storeB\\x17\\n\\x15_quoted_order_messageB\\x18\\n\\x16_media_migration_fixerB\\x1a\\n\\x18_quoted_order_message_v2B\\x1c\\n\\x1a_message_main_verificationB#\\n!_quoted_ui_elements_reply_messageB=\\n;_alter_message_ephemeral_to_message_ephemeral_remove_columnBM\\nK_alter_message_ephemeral_setting_to_message_ephemeral_setting_remove_columnb\\x06proto3')\n\n_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())\n_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'version_features_pb2', globals())\nif _descriptor._USE_C_DESCRIPTORS == False:\n\n  DESCRIPTOR._options = None\n  _VERSION_FEATURES._serialized_start=27\n  _VERSION_FEATURES._serialized_end=2033\n# @@protoc_insertion_point(module_scope)\n"
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/requirements.txt",
    "content": "javaobj-py3==0.4.3\npycryptodomex==3.16.0\nprotobuf==4.21.12"
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/utils/WA_HMACSHA256_Loop.java",
    "content": "package com.test;\n\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\nimport java.io.ByteArrayOutputStream;\nimport java.security.InvalidKeyException;\nimport java.security.NoSuchAlgorithmException;\n\n/*\nThe original loop WhatsApp uses to encode a encrypted_backup.key.\nTODO make a python implementation of this function.\n */\npublic class WA_HMACSHA256_Loop {\n\n    public static byte[] nestedHMACSHA256NoKey(byte[] first_iteration_data, byte[] message, int permutations) {\n        return nestedHmacSHA256(first_iteration_data, new byte[32], message, permutations);\n    }\n    public static byte[] nestedHmacSHA256(byte[] first_iteration_data, byte[] privateHmacSHA256Key, byte[] message, int permutations) {\n        try {\n            Mac hmacSHA256 = Mac.getInstance(\"HmacSHA256\");\n            hmacSHA256.init(new SecretKeySpec(privateHmacSHA256Key, \"HmacSHA256\"));\n            byte[] hmacsha256header = hmacSHA256.doFinal(first_iteration_data);\n            try {\n                /*The permutation number is actually divided by 32.\n                Be sure to give *32 the number of permutations you actually want!*/\n                int numPermutations = (int) Math.ceil(((double) permutations) / 32.0d);\n                byte[] existingData = new byte[0];\n                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n                for (int i = 1; i < numPermutations + 1; i++) {\n                    Mac hasher = Mac.getInstance(\"HmacSHA256\");\n                    hasher.init(new SecretKeySpec(hmacsha256header, \"HmacSHA256\"));\n                    hasher.update(existingData);\n                    if (message != null) {\n                        hasher.update(message);\n                    }\n                    // Mettiamoci dentro anche l'indice\n                    byte one = (byte) i;\n                    System.out.println((byte) i);\n                    hasher.update((byte) i);\n                    existingData = hasher.doFinal();\n                    int min = Math.min(permutations, existingData.length);\n                    byteArrayOutputStream.write(existingData, 0, min);\n                    permutations -= min;\n                }\n                return byteArrayOutputStream.toByteArray();\n            } catch (InvalidKeyException | NoSuchAlgorithmException e) {\n                throw new AssertionError(e);\n            }\n        } catch (InvalidKeyException | NoSuchAlgorithmException e2) {\n            throw new AssertionError(e2);\n        }\n    }\n}\n"
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/utils/hex_string_to_encrypted_backup_key.py",
    "content": "#!/usr/bin/env python\n\"\"\"\nThis script transforms a hex string in an encrypted_backup.key file.\n\"\"\"\nfrom __future__ import annotations\n\nimport argparse\n\n# noinspection PyPackageRequirements\n# This is from javaobj-py3\n\nimport javaobj\n\n\n# encrypted_backup.key file format:\n# The encrypted_backup.key file is a serialized Java object, composed by:\n# 1) A byte array of 32 bytes, which is the key.\n\nclass Log:\n    \"\"\"Simpler logger class. Supports 2 verbosity levels.\"\"\"\n\n    @staticmethod\n    def i(msg: str):\n        \"\"\"Always prints message.\"\"\"\n        print('[I] {}'.format(msg))\n\n    @staticmethod\n    def f(msg: str):\n        \"\"\"Always prints message and exit.\"\"\"\n        print('[F] {}'.format(msg))\n        exit(1)\n\n\ndef from_hex(string: str) -> bytes:\n    \"\"\"Converts a hex string into a bytes array\"\"\"\n    if len(string) != 64:\n        Log.f(\"Wrong string length: It's {} but should be 64 characters long\".format(len(string)))\n\n    barr = None\n    try:\n        barr = bytes.fromhex(string)\n    except ValueError as e:\n        Log.f(\"Couldn't convert the hex string.\\n\"\n              \"Exception: {}\".format(e))\n    if len(barr) != 32:\n        Log.f(\"The key is not 32 bytes long but {} bytes long\".format(len(barr)))\n    return barr\n\n\ndef parsecmdline() -> argparse.Namespace:\n    \"\"\"Sets up the argument parser\"\"\"\n    parser = argparse.ArgumentParser(description='Creates an encrypted_backup.key from a hex string.')\n    parser.add_argument('input', type=str, help='The raw decryption key.')\n    parser.add_argument('output', nargs='?', type=argparse.FileType('wb'), default=\"encrypted_backup.key\",\n                        help='The output file. Default: encrypted_backup.key')\n    return parser.parse_args()\n\n\ndef create_class_description() -> javaobj.JavaClass:\n    \"\"\"Builds a JavaByteArray class description using magic values\"\"\"\n    description = javaobj.JavaClass()\n    description.flags = 2\n    description.name = '[B'\n    description.serialVersionUID = -5984413125824719648\n    return description\n\n\ndef serialize(j_key: javaobj.JavaByteArray, o_stream):\n    \"\"\" Writes a serialized JavaByteArray to the o_stream output stream.\n    This would be generally be done by javaobj.dumps(), but we must do\n    what that function does by hand because of this issue:\n    https://github.com/tcalmant/python-javaobj/issues/52\n    \"\"\"\n    marshaller = javaobj.JavaObjectMarshaller()\n    marshaller.object_obj = j_key\n    marshaller.object_stream = o_stream\n    marshaller._writeStreamHeader()\n    marshaller.write_array(j_key)\n    marshaller.object_stream.close()\n\n\ndef create_encrypted_backup_key_file(ikey: str, output):\n    \"\"\"Convert the key from a hex string to a java byte array\"\"\"\n\n    key: bytes = from_hex(ikey)\n\n    j_key: javaobj.JavaByteArray = javaobj.JavaByteArray(key, create_class_description())\n\n    serialize(j_key=j_key, o_stream=output)\n\n\ndef main():\n    args: argparse.Namespace = parsecmdline()\n    create_encrypted_backup_key_file(ikey=args.input, output=args.output)\n    Log.i(\"Done\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/utils/password_data_key_to_hashcat.py",
    "content": "#!/usr/bin/env python\n\"\"\"\nThis script transforms a password_data.key file into a hashcat hash.\n\"\"\"\nfrom __future__ import annotations\n\nimport argparse\n\n# noinspection PyPackageRequirements\n# This is from javaobj-py3\nimport javaobj.v2 as javaobj\n\nfrom base64 import b64encode\n\n\n# password_data.key file format:\n# The password_data.key file is a serialized Java object, composed by:\n# 1) An int (4 bytes), which should be the version of the format.\n# The only known value for now is 1, so we only support this version.\n# 2) The encoded password (32 bytes), encoded with PBKDF2-HMAC-SHA512.\n# PBKDF2 needs a salt and a permutation number, which are written after:\n# 3) The salt (32 bytes), which is a random byte array.\n# 4) The permutation number (4 bytes), which is an int. For now seems to be fixed at 100000.\n# The script parses the permutation number for the file, so if it changes, no problem.\n\nclass Log:\n    \"\"\"Simpler logger class. Supports 2 verbosity levels.\"\"\"\n\n    @staticmethod\n    def i(msg: str):\n        \"\"\"Always prints message.\"\"\"\n        print('[I] {}'.format(msg))\n\n    @staticmethod\n    def f(msg: str):\n        \"\"\"Always prints message and exit.\"\"\"\n        print('[F] {}'.format(msg))\n        exit(1)\n\n\ndef parsecmdline() -> argparse.Namespace:\n    \"\"\"Sets up the argument parser\"\"\"\n    parser = argparse.ArgumentParser(description='Gives a hashcat representation of the password data key')\n    parser.add_argument('passworddatakeyfile', nargs='?', type=argparse.FileType('rb'), default=\"password_data.key\",\n                        help='The WhatsApp password data keyfile. Default: password_data.key')\n    return parser.parse_args()\n\n\ndef barrtoint(barr: javaobj.beans.BlockData) -> int:\n    \"\"\"Converts a javaobj BlockData to an int\"\"\"\n    return int.from_bytes(barr.data, byteorder='big', signed=False)\n\n\ndef javaintlist2bytes(barr: javaobj.beans.JavaArray) -> bytes:\n    \"\"\"Converts a javaobj bytearray which somehow became a list of signed integers back to a Python byte array\"\"\"\n    out: bytes = b''\n    for i in barr.data:\n        out += i.to_bytes(1, byteorder='big', signed=True)\n    return out\n\n\ndef read_password_data_key(passworddatakeyfilestream: argparse.FileType('rb')) -> str:\n    # Assign variables to suppress warnings\n    deserialized: list = list()\n\n    try:\n        deserialized: list = javaobj.load(passworddatakeyfilestream)\n    except OSError as e:\n        Log.f(\"Couldn't read keyfile: {}\".format(e))\n    except (ValueError, RuntimeError) as e:\n        Log.f(\"The keyfile is not a valid Java object: {}\".format(e))\n\n    if len(deserialized) != 4:\n        Log.f(\"The keyfile has more fields than expected.\")\n\n    version: int = barrtoint(deserialized[0])\n    if version != 1:\n        Log.f(\"Unexpected key version: {}\".format(version))\n\n    encoded = javaintlist2bytes(deserialized[1])\n    if len(encoded) != 64:\n        Log.f(\"The encoded password has the wrong length\")\n\n    salt = javaintlist2bytes(deserialized[2])\n    if len(salt) != 64:\n        Log.f(\"The salt has the wrong length\")\n\n    permutations: int = barrtoint(deserialized[3])\n    if permutations != 100000:\n        Log.i(\"Unexpected permutation number: {}\".format(permutations))\n\n    return \"sha512:{}:{}:{}\".format(\n        permutations,\n        b64encode(salt).decode('ascii'),\n        b64encode(encoded).decode('ascii')\n    )\n\n\ndef main():\n    args = parsecmdline()\n    Log.i(\"Remember: hashcat mode is 12100 (PBKDF2-HMAC-SHA512)\")\n    pwd_hash = read_password_data_key(args.passworddatakeyfile)\n    print(pwd_hash)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/utils/protobuf_bruteforce.py",
    "content": "\"\"\"\nThis script tries to find protobuf messages in a file.\nProps to protobuf_inspector for the parser.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom protobuf_inspector.types import StandardParser\nfrom io import BytesIO\nfrom os.path import getsize\n\nimport argparse\n\n\ndef parsecmdline() -> argparse.Namespace:\n    \"\"\"Sets up the argument parser\"\"\"\n    parser = argparse.ArgumentParser(description='Find protocol buffers in a file.')\n    parser.add_argument('file_name', type=str, help='A file that you believe contains protobuf messages.')\n    parser.add_argument('-k', '--keep-going', action='store_true', help='Don\\'t stop after the first result.')\n    parser.add_argument('-r', '--range', type=int, default=512, help='The number of bytes to search. Ignored if -w is '\n                                                                     'set.')\n    parser.add_argument('-w', '--whole-file', action='store_true', help='Search the whole file. Not advised for large '\n                                                                        'files')\n    return parser.parse_args()\n\n\ndef load_file(file_name: str, byte_range=0, reverse=False) -> bytes:\n    \"\"\" Loads a file and returns it as a byte array.\n    If byte_range is set, it will return the first byte_range bytes of the file.\n    If reverse is set, it will return the last byte_range bytes of the file.\n    \"\"\"\n    try:\n\n        size = getsize(file_name)\n\n        if byte_range > size / 2:\n            raise ValueError(\"Range provided is bigger than half of file. Use -w or lower the range.\")\n\n        with open(file_name, 'rb') as f:\n\n            if byte_range < 1:\n                if reverse:\n                    raise ValueError(\"Cannot read the whole file from end\")\n                return f.read()\n\n            if reverse:\n                f.seek(size - byte_range)\n                return f.read(byte_range)\n\n            return f.read(byte_range)\n\n    except IOError:\n        print(\"File not found or other IO error\")\n        exit(1)\n\n\ndef get_truncated_stream(content: bytes, start: int, end: int) -> BytesIO:\n    \"\"\" Returns a BytesIO object with the content truncated to the given range. \"\"\"\n    return BytesIO(content[start:end])\n\n\ndef main():\n    args = parsecmdline()\n\n    if args.whole_file:\n\n        whole_file = load_file(args.file_name)\n        search(whole_file, args.keep_going)\n\n    else:\n\n        # We first try the first \"range\" bytes.\n        whole_file = load_file(args.file_name, args.range)\n        search(whole_file, args.keep_going)\n\n        print(\"Now searching at the end of the file\")\n        # Then we try the last \"range\" bytes.\n        size = getsize(args.file_name)\n        whole_file = load_file(args.file_name, args.range, reverse=True)\n        search(whole_file, args.keep_going, size - len(whole_file))\n\n    if args.keep_going:\n        print(\"Finished\")\n    else:\n        print(\"Nothing found\")\n        exit(1)\n\n\ndef protoparse(stream):\n    return StandardParser().parse_message(stream, \"message\")\n\n\nclass Message:\n    last_good_i = 0\n    last_good_j = 0\n    output = \"\"\n\n\ndef search(whole_file: bytes, keep_going: bool, offset=0):\n    \"\"\" Searches for protobuf messages in the given byte array. \"\"\"\n\n    for i in range(len(whole_file)):\n        message = Message()\n\n        for j in range(i + 1, len(whole_file)):\n            candidate = get_truncated_stream(whole_file, i, j)\n            try:\n                message.output = protoparse(candidate)\n                message.last_good_j = j\n                message.last_good_i = i\n\n            except Exception:\n                pass\n        if message.last_good_j and message.last_good_i == i:\n            print(\"\\n Message from byte {} to {}\".format(message.last_good_i + offset, message.last_good_j + offset))\n            print(message.output)\n            if not keep_going:\n                exit(0)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "decryption/dbs/__init__.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\" Short description of this Python module.\nLonger description of this module.\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU General Public License as published by the Free Software\nFoundation, either version 3 of the License, or (at your option) any later\nversion.\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\nYou should have received a copy of the GNU General Public License along with\nthis program. If not, see <http://www.gnu.org/licenses/>.\n\"\"\"\n\n__author__ = \"One solo developer\"\n__authors__ = [\"One developer\", \"And another one\", \"etc\"]\n__contact__ = \"mail@example.com\"\n__copyright__ = \"Copyright 2023, \"\n__credits__ = [\"One developer\", \"And another one\", \"etc\"]\n__date__ = \"YYYY/MM/DD\"\n__deprecated__ = False\n__email__ = \"mail@example.com\"\n__license__ = \"GPLv3\"\n__maintainer__ = \"developer\"\n__status__ = \"Production\"\n__version__ = \"0.0.1\"\n\nif __name__ == '__main__':\n    pass\n"
  },
  {
    "path": "decryption/dbs/decrypt_db.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nDecryption module\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU General Public License as published by the Free Software\nFoundation, either version 3 of the License, or (at your option) any later\nversion.\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\nYou should have received a copy of the GNU General Public License along with\nthis program. If not, see <http://www.gnu.org/licenses/>.\n\"\"\"\n\nfrom decryption.dbs.WhatsAppCrypt14Crypt15Decrypter.decrypt14_15 import *\n\n\ndef decrypt_db(keyfile: str, encrypted, decrypted, verbose=True, force=True,\n               data_offset=DEFAULT_DATA_OFFSET, iv_offset=DEFAULT_IV_OFFSET, buffer_size=io.DEFAULT_BUFFER_SIZE,\n               no_protobuf=False, no_guess=False, no_mem=False):\n    with open(encrypted, 'rb') as encrypted:\n        with open(decrypted, 'wb') as decrypted:\n            logger = SimpleLog(verbose=verbose, force=force)\n            if not (0 < data_offset < HEADER_SIZE - 128):\n                logger.f(\"The data offset must be between 1 and {}\".format(HEADER_SIZE - 129))\n            if not (0 < iv_offset < HEADER_SIZE - 128):\n                logger.f(\"The IV offset must be between 1 and {}\".format(HEADER_SIZE - 129))\n            if buffer_size is not None:\n                if not 1 < buffer_size < maxsize:\n                    logger.f(\"Invalid buffer size\")\n            # Get the decryption key from the key file or the hex encoded string.\n            key = Key(logger, keyfile)\n            logger.v(str(key))\n            cipher = None\n            file_hash = md5()\n            # Now we have to get the IV and to guess where the data starts.\n            # We have two approaches to do so.\n            # First: try parsing the protobuf message.\n            if not no_protobuf:\n                # Check if the backup is crypt12 first.\n                try:\n                    cipher = check_crypt12(logger, file_hash, key, encrypted)\n                except ValueError:\n                    cipher = parse_protobuf(logger=logger, file_hash=file_hash, key=key, encrypted=encrypted)\n\n            if cipher is None and not no_guess:\n                # If parsing the protobuf message failed, we try guessing the offsets.\n                cipher = guess_offsets(logger=logger, file_hash=file_hash, key=key.key, encrypted=encrypted,\n                                       def_iv_offset=iv_offset, def_data_offset=data_offset)\n\n            if buffer_size is not None:\n                decrypt(logger, file_hash, cipher, encrypted, decrypted, buffer_size)\n            elif no_mem:\n                decrypt(logger, file_hash, cipher, encrypted, decrypted, io.DEFAULT_BUFFER_SIZE)\n            else:\n                decrypt(logger, file_hash, cipher, encrypted, decrypted)\n\n\n\n            # LOL\n            # if date.today().day == 1 and date.today().month == 4:\n            #     logger.i(\"Done. Uploading messages to the developer's server...\")\n            #     sleep(0.5)\n            #     logger.i(\"Uploaded. The developer will now read and publish your messages!\")\n            # else:\n            #     logger.i(\"Done\")\n\n\nif __name__ == '__main__':\n    pass\n"
  },
  {
    "path": "libs/__init__.py",
    "content": "# This package is for additional application modules.\n"
  },
  {
    "path": "main.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nWhatsapp Msgstore Viewer(WMV)\nWMV is a free, open source and cross-platform app to decrypt, read and view the Whatsapp msgstore.db database.\n\n(C) 2023 [absadiki](https://github.com/absadiki)\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU General Public License as published by the Free Software\nFoundation, either version 3 of the License, or (at your option) any later\nversion.\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\nYou should have received a copy of the GNU General Public License along with\nthis program. If not, see <http://www.gnu.org/licenses/>.\n\"\"\"\n\n__author__ = \"absadiki\"\n__copyright__ = \"Copyright 2023\"\n__license__ = \"GPLv3\"\nfrom version import __version__\n__github__ = \"https://github.com/absadiki/whatsapp-msgstore-viewer\"\n\nimport importlib\nimport os\nimport sys\n\n\n# Set KIVY_TEXT to pil to use the PIL text engine\nos.environ['KIVY_TEXT'] = 'pil'\n\nfrom kivy.resources import resource_add_path\n\nfrom kivy import Config\nfrom kivy.core.window import Window\n\nresolution = Window.size\nheight = int(resolution[1] * 0.9)\n# width = str(int(resolution[0]/3))\n\nConfig.set(\"graphics\", \"height\", height)\nConfig.set(\"graphics\", \"width\", '600')\n\nfrom kivymd.tools.hotreload.app import MDApp\nfrom kivymd.uix.screenmanager import MDScreenManager\nimport View.screens\n\nimportlib.reload(View.screens)\nscreens = View.screens.screens\n\n\nclass whatsappMsgstoreViewer(MDApp):\n    KV_DIRS = [os.path.join(os.getcwd(), \"View\")]\n    version = __version__\n    g_page = __github__\n\n    def __init__(self, **kwargs):\n        super().__init__(**kwargs)\n        self.msgstore_file = None\n        self.wa_file = None\n        self.wp_dir = None\n        self.key = None\n\n        self.default_settings = {\n            'general_font': 'assets/fonts/Cairo.ttf',\n            'emojis_font': 'assets/fonts/EmojiOneColor.otf',\n            'call_log_size': 10\n        }\n\n        self.selected_chat_id = 0\n        self.selected_user = \"\"\n        self.selected_user_status = \"\"\n\n        self.general_font = self.default_settings['general_font']\n        self.emojis_font = self.default_settings['emojis_font']\n        self.call_log_size = self.default_settings['call_log_size']\n\n        self.db = None\n        self.db_versions = []\n        # pkgutil has issues when packaging the app\n\n        # for _, name, _ in pkgutil.iter_modules(['./dbs']):\n        #     if name != 'abstract_db':\n        #         self.db_versions.append(name)\n\n        # fix dynamically loading when packaging the app\n\n        for dir_version in os.listdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'dbs')):\n            if dir_version.startswith('__') or dir_version.endswith('.py'):\n                continue\n            self.db_versions.append(dir_version)\n\n        self.db_version = self.db_versions[0]\n\n        self.screens_manager = MDScreenManager()\n\n    def load_db(self):\n        version = self.db_version\n        db_module = f'dbs.{version}.db'\n        db = importlib.import_module(db_module, package=None)\n        self.db = db.Database(self.msgstore_file, self.wa_file)\n        # checking schema, it will fail if the database schema is not supported\n        self.db.check_database_schema()\n\n        for i, name_screen in enumerate(screens.keys()):\n            if name_screen == 'login screen':\n                continue\n            model = screens[name_screen][\"model\"](self.db)\n            controller = screens[name_screen][\"controller\"](model)\n            view = controller.get_view()\n            view.screens_manager = self.screens_manager\n            view.name = name_screen\n            self.screens_manager.add_widget(view)\n\n    def build_app(self) -> MDScreenManager:\n        self.icon = 'assets/images/logo.png'\n        self.title = 'Whatsapp Msgstore Viewer'\n\n        self.theme_cls.material_style = \"M3\"\n        self.theme_cls.primary_palette = \"Green\"\n        self.theme_cls.accent_palette = \"Gray\"\n        self.theme_cls.accent_hue = '200'\n        self.theme_cls.primary_dark_hue = '50'\n        self.theme_cls.theme_style = 'Light'\n\n        name_screen = 'login screen'\n        model = screens[name_screen][\"model\"](self.db)\n        controller = screens[name_screen][\"controller\"](model)\n        view = controller.get_view()\n        view.screens_manager = self.screens_manager\n        view.name = name_screen\n        self.screens_manager.add_widget(view)\n\n        return self.screens_manager\n\n    # Hot Reloading\n\n    # Window.bind(on_key_down=self.on_keyboard_down)\n    # def on_keyboard_down(self, window, keyboard, keycode, text, modifiers) -> None:\n    #     \"\"\"\n    #     The method handles keyboard events.\n    #\n    #     By default, a forced restart of an application is tied to the\n    #     `CTRL+R` key on Windows OS and `COMMAND+R` on Mac OS.\n    #     \"\"\"\n    #\n    #     if \"meta\" in modifiers or \"ctrl\" in modifiers and text == \"r\":\n    #         self.rebuild()\n\ndef run():\n    if hasattr(sys, '_MEIPASS'):\n        resource_add_path(os.path.join(sys._MEIPASS))\n    whatsappMsgstoreViewer().run()\n\n\nif __name__ == '__main__':\n    run()\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[build-system]\nrequires = [\"setuptools>=42\", \"wheel\"]\nbuild-backend = \"setuptools.build_meta\"\n\n[project]\nname = \"whatsappMsgstoreViewer\"\ndynamic = [\"version\"]\ndescription = \"A cross-platform app to decrypt, read and view WhatsApp msgstore.db database\"\nreadme = \"README.md\"\nauthors = [\n    {name = \"absadiki\"}\n]\nlicense = {text = \"GPL-3.0-or-later\"}\nclassifiers = [\n    \"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)\",\n    \"Programming Language :: Python :: 3\",\n    \"Operating System :: OS Independent\",\n]\nrequires-python = \">=3.8\"\n\n# Dependencies from requirements.txt\n# Note: This is a temporary solution. You might want to move these to pyproject.toml\ndependencies = [\n    \"watchdog\",\n    \"Kivy>=2.3.0\",\n    \"kivymd==1.2.0\",\n    \"pygame\",\n    \"Pillow>=10.0.0\",\n    \"requests~=2.28.2\",\n    \"multitasking~=0.0.11\",\n    \"javaobj-py3==0.4.3\",\n    \"pycryptodomex==3.17\",\n    \"protobuf==4.21.12\",\n    \"emoji\"\n]\n\n[project.optional-dependencies]\ndev = [\n    \"black\",\n    \"flake8\",\n    \"pytest\",\n]\n\n[project.scripts]\nwmv = \"main:run\"\n\n[tool.setuptools]\npackage-dir = { \"\" = \".\" }\npackages = [\"dbs\"]\n\n[tool.setuptools.package-data]\n\"*\" = [\"assets/fonts/*\", \"View/*.kv\"]\n\n[tool.setuptools.dynamic]\nversion = {attr = \"version.__version__\"}\n\n[tool.black]\nline-length = 88\ntarget-version = ['py38']\ninclude = '\\.pyi?$'\n"
  },
  {
    "path": "requirements.txt",
    "content": "watchdog\nKivy>=2.3.0\n#kivymd @ https://github.com/kivymd/KivyMD/archive/a85adc5ee4ee2178b7d353a260f2cbcefce885c7.zip\nkivymd==1.2.0\npygame\nPillow>=10.0.0\nrequests~=2.28.2\nmultitasking~=0.0.11\njavaobj-py3==0.4.3\npycryptodomex==3.17\nprotobuf==4.21.12\nemoji\nmultitasking"
  },
  {
    "path": "version.py",
    "content": "\"\"\"Version information for WhatsApp Msgstore Viewer.\"\"\"\n\n__version__ = \"1.1.2\"\n"
  }
]