Showing preview only (258K chars total). Download the full file or copy to clipboard to get everything.
Repository: absadiki/whatsapp-msgstore-viewer
Branch: main
Commit: 8fce2779339c
Files: 79
Total size: 237.4 KB
Directory structure:
gitextract_0l64ab7n/
├── .gitignore
├── Controller/
│ ├── chat_screen.py
│ ├── login_screen.py
│ ├── main_screen.py
│ └── template_screen.py
├── LICENSE
├── Model/
│ ├── __init__.py
│ ├── base_model.py
│ ├── chat_screen.py
│ ├── login_screen.py
│ ├── main_screen.py
│ └── template_screen.py
├── README.md
├── Utility/
│ ├── Utils.py
│ ├── __init__.py
│ └── observer.py
├── View/
│ ├── ChatScreen/
│ │ ├── __init__.py
│ │ ├── chat_screen.kv
│ │ └── chat_screen.py
│ ├── LoginScreen/
│ │ ├── __init__.py
│ │ ├── about.kv
│ │ ├── login_screen.kv
│ │ ├── login_screen.py
│ │ └── settings.kv
│ ├── MainScreen/
│ │ ├── __init__.py
│ │ ├── main_screen.kv
│ │ └── main_screen.py
│ ├── base_screen.py
│ ├── components/
│ │ ├── MLabel.kv
│ │ ├── __init__.py
│ │ ├── attachment.kv
│ │ ├── avatar.kv
│ │ ├── call_list_item.kv
│ │ ├── chat_list_item.kv
│ │ ├── chat_message.kv
│ │ ├── quote.kv
│ │ └── textfield_filemanger.kv
│ └── screens.py
├── about
├── assets/
│ └── fonts/
│ └── EmojiOneColor.otf
├── credits
├── dbs/
│ ├── __init__.py
│ ├── abstract_db.py
│ ├── v1/
│ │ ├── __init__.py
│ │ └── db.py
│ ├── v2/
│ │ ├── __init__.py
│ │ └── db.py
│ └── v3/
│ ├── __init__.py
│ └── db.py
├── decryption/
│ ├── __init__.py
│ └── dbs/
│ ├── WhatsAppCrypt14Crypt15Decrypter/
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── SECURITY.md
│ │ ├── __init__.py
│ │ ├── decrypt14_15.py
│ │ ├── proto/
│ │ │ ├── C14_cipher.proto
│ │ │ ├── C14_cipher_pb2.py
│ │ │ ├── C14_cipher_version.proto
│ │ │ ├── C14_cipher_version_pb2.py
│ │ │ ├── C15_IV.proto
│ │ │ ├── C15_IV_pb2.py
│ │ │ ├── key_type.proto
│ │ │ ├── key_type_pb2.py
│ │ │ ├── prefix.proto
│ │ │ ├── prefix_pb2.py
│ │ │ ├── version_features.proto
│ │ │ └── version_features_pb2.py
│ │ ├── requirements.txt
│ │ └── utils/
│ │ ├── WA_HMACSHA256_Loop.java
│ │ ├── hex_string_to_encrypted_backup_key.py
│ │ ├── password_data_key_to_hashcat.py
│ │ └── protobuf_bruteforce.py
│ ├── __init__.py
│ └── decrypt_db.py
├── libs/
│ └── __init__.py
├── main.py
├── pyproject.toml
├── requirements.txt
└── version.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
.idea
dbs/test/
================================================
FILE: Controller/chat_screen.py
================================================
import importlib
import multitasking
from kivy.clock import mainthread
import Model.chat_screen
import View.ChatScreen.chat_screen
# We have to manually reload the view module in order to apply the
# changes made to the code on a subsequent hot reload.
# If you no longer need a hot reload, you can delete this instruction.
importlib.reload(View.ChatScreen.chat_screen)
class ChatScreenController:
def __init__(self, model):
self.model: Model.chat_screen.ChatScreenModel = model
self.view = View.ChatScreen.chat_screen.ChatScreenView(controller=self, model=self.model)
self.view.bind(on_enter=self.on_enter)
def get_view(self) -> View.ChatScreen.chat_screen:
return self.view
@mainthread
def task_finished(self, chat_messages):
self.view.show_chat_messages(chat_messages)
self.view.hide_dialog()
@multitasking.task
def get_chat(self, chat_id):
chat_messages = self.model.get_chat(chat_id)
self.task_finished(chat_messages)
def on_enter(self, *args):
chat_id = self.view.app.selected_chat_id
self.view.selected_user = self.view.app.selected_user
self.view.status = self.view.app.status
self.view.show_dialog(msg='Loading chat ...', title='Please wait', auto_dismiss=False)
self.get_chat(chat_id)
def previous_screen(self):
self.view.app.screens_manager.current = self.view.app.screens_manager.previous()
================================================
FILE: Controller/login_screen.py
================================================
import importlib
import os.path
import traceback
from typing import NoReturn
import multitasking
from Utility.Utils import check_path, strip_quotes
multitasking.set_max_threads(10)
import View.LoginScreen.login_screen
# We have to manually reload the view module in order to apply the
# changes made to the code on a subsequent hot reload.
# If you no longer need a hot reload, you can delete this instruction.
importlib.reload(View.LoginScreen.login_screen)
from kivy.clock import mainthread
class LoginScreenController:
def __init__(self, model):
self.model = model # Model.main_screen.MainScreenModel
self.view = View.LoginScreen.login_screen.LoginScreenView(controller=self, model=self.model)
self.decrypt = None
def get_view(self) -> View.LoginScreen.login_screen:
return self.view
def check_files(self):
if self.view.app.msgstore_file is None:
self.view.show_dialog('No msgstore provided!!',
title="Error",
auto_dismiss=True)
return False
if not check_path(self.view.app.msgstore_file):
self.view.show_dialog(f'Please recheck the provided msgstore path\n`{self.view.app.msgstore_file}`'
f'\ndoes not exist',
title="Error", auto_dismiss=True)
return False
if not check_path(self.view.app.wa_file):
self.view.show_dialog(f'Please recheck the provided wa.db path\n`{self.view.app.wa_file}`'
f'\ndoes not exist',
title="Error", auto_dismiss=True)
return False
if not check_path(self.view.app.wp_dir):
self.view.show_dialog(f'Please recheck the provided Whatsapp directory path\n`{self.view.app.wp_dir}`'
f'\ndoes not exist',
title="Error", auto_dismiss=True)
return False
return True
@mainthread
def login(self):
try:
self.view.app.load_db()
self.view.screens_manager.get_screen('main screen').controller.on_enter()
self.view.hide_dialog()
self.view.app.screens_manager.current = "main screen"
except Exception as e:
print(traceback.format_exc())
msg = f"""
{str(e)}
Try to choose another version from the `Database version` drop-down menu.
If no version works, probably the database is encrypted or you have an updated version of Whatsapp and your database schema is not supported yet.
Submit an issue on our Github page to help you add support to your database schema.
"""
self.view.show_dialog(msg=msg, title='Database schema is not supported!', auto_dismiss=True)
@mainthread
def show_decryption_error(self, error):
err = """
Unfortunately, the decryption of the database was not successful.
Maybe you didn't provide the right key or the file is corrupted or the version is not supported.
This app is using the `WhatsApp-Crypt14-Crypt15-Decrypter` library under the hood.
Visit their Github page for more information or to get some help:
<https://github.com/ElDavoo/WhatsApp-Crypt14-Crypt15-Decrypter>
"""
print(traceback.format_exc())
self.view.hide_dialog()
self.view.show_dialog(f'{str(error)}\n\n{err} ', title='Decryption', auto_dismiss=True)
def show_warning(self, warning):
self.view.show_toast(f"{warning}")
@mainthread
def show_decryption_success(self, path):
self.view.show_toast(f"Database decrypted successfully, the decrypted file is stored in {path}")
@mainthread
def update_dialog(self, msg):
self.view.dialog.text = msg
@multitasking.task
def decrypt_dbs(self, key):
# decrypting msgstore
if self.view.app.wa_file is not None:
try:
self.update_dialog("Decrypting wa.db ...")
enc_db = self.view.app.wa_file
dec_db = enc_db + '-decrypted.db'
self.decrypt_db(key, enc_db, dec_db)
self.view.app.wa_file = dec_db
self.show_decryption_success(dec_db)
except Exception as e:
self.show_decryption_error(e)
os.remove(dec_db)
try:
self.update_dialog("Decrypting msgstore.db ...")
enc_db = self.view.app.msgstore_file
dec_db = enc_db + '-decrypted.db'
self.decrypt_db(key, enc_db, dec_db)
self.view.app.msgstore_file = dec_db
self.show_decryption_success(dec_db)
self.login()
except Exception as e:
self.show_decryption_error(e)
os.remove(dec_db)
def decrypt_db(self, key, enc_db, dec_db):
from decryption.dbs.decrypt_db import decrypt_db
decrypt_db(keyfile=key, encrypted=enc_db, decrypted=dec_db)
if not check_path(dec_db):
raise Exception('Decryption error\nNo decrypted database was found in path')
self.show_decryption_success(dec_db)
def on_tap_button_login(self) -> NoReturn:
"""Called when the `LOGIN` button is pressed."""
self.view.show_dialog('Login ...', title='Please wait ...', auto_dismiss=False)
self.view.app.msgstore_file = None if self.view.ids['msgstore_file_path'].text == '' else strip_quotes(self.view.ids[
'msgstore_file_path'].text)
self.view.app.wa_file = None if self.view.ids['wa_file_path'].text == '' else strip_quotes(self.view.ids['wa_file_path'].text)
self.view.app.wp_dir = None if self.view.ids['wp_dir'].text == '' else strip_quotes(self.view.ids['wp_dir'].text)
if not self.check_files():
return
if self.view.ids['enc_checkbox'].active:
# decrypt first
key = strip_quotes(self.view.key_file_widget.text)
if key == '':
self.view.show_dialog('Encrypted database is selected but no key has been provided!', title='Error',
auto_dismiss=True)
return
else:
# trying to decrypt
self.view.show_dialog('Trying to decrypt ...', title='Please wait ...', auto_dismiss=False)
self.decrypt_dbs(key)
else:
self.login()
================================================
FILE: Controller/main_screen.py
================================================
import importlib
from typing import NoReturn
import View.MainScreen.main_screen
import View.screens
# We have to manually reload the view module in order to apply the
# changes made to the code on a subsequent hot reload.
# If you no longer need a hot reload, you can delete this instruction.
importlib.reload(View.MainScreen.main_screen)
class MainScreenController:
"""
The `MainScreenController` class represents a controller implementation.
Coordinates work of the view with the model.
The controller implements the strategy pattern. The controller connects to
the view to control its actions.
"""
def __init__(self, model):
self.model = model # Model.main_screen.MainScreenModel
self.view = View.MainScreen.main_screen.MainScreenView(controller=self, model=self.model)
def get_view(self) -> View.MainScreen.main_screen:
return self.view
def on_tap_button_login(self) -> NoReturn:
"""Called when the `LOGIN` button is pressed."""
self.view.show_dialog_wait()
def on_enter(self, *args):
self.view.show_dialog_wait()
contact_chats = self.model.get_contact_chats()
self.view.show_chats_list(contact_chats)
group_chats = self.model.get_group_chats()
self.view.build_group_chat_list(group_chats)
calls = self.model.get_calls(how_many=self.view.app.call_log_size)
self.view.build_calls_list(calls)
self.view.dialog.dismiss()
def show_chat_screen(self, chat_id, user, jid):
self.view.app.selected_chat_id = chat_id
self.view.app.selected_user = user
self.view.app.status = self.model.get_status(jid)
self.view.app.screens_manager.current = "chat screen"
def clear_session(self):
for screen in View.screens.screens:
if screen == 'login screen':
continue
self.view.screens_manager.remove_widget(self.view.screens_manager.get_screen(screen))
def log_out(self, *args):
print('Logging out ...')
self.view.app.screens_manager.current = 'login screen'
# clear
self.clear_session()
================================================
FILE: Controller/template_screen.py
================================================
import importlib
from typing import NoReturn
import View.TemplateScreen.template_screen
# We have to manually reload the view module in order to apply the
# changes made to the code on a subsequent hot reload.
# If you no longer need a hot reload, you can delete this instruction.
importlib.reload(View.TemplateScreen.template_screen)
from kivymd.tools.hotreload.app import MDApp
class TemplateScreenController:
"""
The `MainScreenController` class represents a controller implementation.
Coordinates work of the view with the model.
The controller implements the strategy pattern. The controller connects to
the view to control its actions.
"""
def __init__(self, model):
self.model = model # Model.main_screen.MainScreenModel
self.view = View.TemplateScreen.template_screen.TemplateScreenView(controller=self, model=self.model)
self.app = MDApp.get_running_app()
def get_view(self) -> View.TemplateScreen.template_screen:
return self.view
def on_tap_button_login(self) -> NoReturn:
"""Called when the `LOGIN` button is pressed."""
self.view.show_dialog_wait()
# self.app.screens_manager.current = "main screen"
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
================================================
FILE: Model/__init__.py
================================================
================================================
FILE: Model/base_model.py
================================================
# The model implements the observer pattern. This means that the class must
# support adding, removing, and alerting observers. In this case, the model is
# completely independent of controllers and views. It is important that all
# registered observers implement a specific method that will be called by the
# model when they are notified (in this case, it is the `model_is_changed`
# method). For this, observers must be descendants of an abstract class,
# inheriting which, the `model_is_changed` method must be overridden.
class BaseScreenModel:
"""Implements a base class for model modules."""
_observers = []
def add_observer(self, observer) -> None:
self._observers.append(observer)
def remove_observer(self, observer) -> None:
self._observers.remove(observer)
def notify_observers(self, name_screen: str) -> None:
"""
Method that will be called by the observer when the model data changes.
:param name_screen:
name of the view for which the method should be called
:meth:`model_is_changed`.
"""
for observer in self._observers:
if observer.name == name_screen:
observer.model_is_changed()
break
================================================
FILE: Model/chat_screen.py
================================================
from Model.base_model import BaseScreenModel
from dbs.abstract_db import AbstractDatabase
class ChatScreenModel(BaseScreenModel):
"""
Implements the logic of the
:class:`~View.main_screen.ChatScreen.ChatScreenView` class.
"""
def __init__(self, base):
self.base: AbstractDatabase = base
def get_chat(self, chat_id):
return self.base.fetch_chat(chat_id)
================================================
FILE: Model/login_screen.py
================================================
from Model.base_model import BaseScreenModel
class LoginScreenModel(BaseScreenModel):
def __init__(self, base):
self.base = base
self._observers = []
================================================
FILE: Model/main_screen.py
================================================
from Model.base_model import BaseScreenModel
from dbs.abstract_db import AbstractDatabase
class MainScreenModel(BaseScreenModel):
"""
Implements the logic of the
:class:`~View.main_screen.MainScreen.MainScreenView` class.
"""
def __init__(self, base):
self.base: AbstractDatabase = base
def set_base(self, base):
self.base = base
def get_contact_chats(self):
contact_chat_list = self.base.fetch_contact_chats()
if self.base.contacts is not None:
for contact_chat in contact_chat_list:
raw_jid = contact_chat.get('raw_string_jid')
if raw_jid in self.base.contacts:
display_name = self.base.contacts[raw_jid].get('display_name', '')
if display_name:
contact_chat['user'] = f"{display_name} <{contact_chat['user']}>"
else:
contact_chat['user'] = f"{contact_chat['user']}"
else:
print(f"Contact {raw_jid} does not exist")
return contact_chat_list
def get_group_chats(self):
group_chat_list = self.base.fetch_group_chats()
return group_chat_list
def get_calls(self, how_many=None):
calls = self.base.fetch_calls(how_many)
if self.base.contacts is not None:
# users with their display names
for call in calls:
try:
call['user'] = self.base.contacts[call['raw_string']]['display_name'] + \
f" <{call['user']}> "
except KeyError:
pass # already mentioned
return calls
def get_status(self, jid):
try:
st = self.base.contacts[jid]['status']
if st is not None:
return st
else:
raise KeyError
except Exception:
return "<No Status>"
================================================
FILE: Model/template_screen.py
================================================
from Model.base_model import BaseScreenModel
class TemplateScreenModel(BaseScreenModel):
"""
Implements the logic of the
:class:`~View.main_screen.MainScreen.MainScreenView` class.
"""
def __init__(self, base):
self.base = base
================================================
FILE: README.md
================================================
# whatsapp Msgstore Viewer
Free, open source and cross-platform app to decrypt, read and view the Whatsapp `msgstore.db` database.
<br/>
<p align="center">
<img src="./assets/demo/demo_gif_2.gif">
</p>
# Features
* View contact and group chats.
* View call logs with their durations.
* Easy access to media files (images, audio, and video) from within the chat, if the local WhatsApp directory has been provided.
* Decrypt and view the database if you have the decryption `key` (Should support **crypt12**, **crypt14**, and **crypt15**).
* Cross-platform (Should work on Linux, Windows, and Mac)
# Installation
### Prerequisites
- Python 3.9 or later
```bash
git clone https://github.com/absadiki/whatsapp-msgstore-viewer
cd whatsapp-msgstore-viewer
pip install -e .
```
### Run
```bash
wmv
```
> **Note for Ubuntu users:** Additional system dependencies might be needed. See [#19](https://github.com/absadiki/whatsapp-msgstore-viewer/issues/19) for details.
# Usage
To use the app, you will need:
* The `msgstore.db` (`msgstore.db.cryptX` if it is encrypted) database: It is a database where Whatsapp is storing all your messages.
* 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.
* 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).
* 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.
(See below for more information).
# Notes
#### Where to find the databases
Check out the great tutorial "[Retrieving WhatsApp Databases](https://github.com/Dexter2389/whatsapp-backup-chat-viewer#retrieving-whatsapp-databases)" by [@Dexter2389](https://github.com/Dexter2389).
#### About the decryption process
The app uses the [WhatsApp-Crypt14-Crypt15-Decrypter](https://github.com/ElDavoo/WhatsApp-Crypt14-Crypt15-Decrypter) by [ElDavoo](https://github.com/ElDavoo) under the hood.
Please check their repository if you face any issues with the decryption.
#### About the Database schema
This 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.
I've made it easy to add support for more schemas (It's a simple SQLite exercise :D).
All contributions are welcome.
Follow these steps to add support for other schemas (see `db/v1/db.py` as an example):
* Create a package in the `dbs` package and give your schema a name (for example `v2`).
* Inside the newly created package, create a Python module `db.py`.
* Inherit the abstract class `AbstractDatabase` located in the `dbs/abstract_db.py` module.
* The app will dynamically load existing schemas when starting.
* Submit a pull request.
#### About different languages
- You might encounter an issue where messages are displayed incorrectly (as square characters).
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.
- For RTL languages, please see [RTL Support #8](https://github.com/absadiki/whatsapp-msgstore-viewer/discussions/8)
# Contributing
If you find a bug, have a suggestion or feedback, please open an issue for discussion.
# License
This project is licensed under the GNU General Public License version 3 or later. You can modify or redistribute it under the conditions
of these licenses (See [LICENSE](./LICENSE) for more information).
# DISCLAIMER
This project is not endorsed or certified by WhatsApp Inc. and is meant for **personal and educational purposes only**.
It is provided 'as is' without any express or implied warranties.
The authors, maintainers, and contributors assume no responsibility for errors, omissions, or damages resulting from the use of this information.
================================================
FILE: Utility/Utils.py
================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Helper functions
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
"""
import os
import emoji
def fix_emojis(text, font):
def add_font(chars, data_dict):
return f"[font={font}]{chars}[/font]"
res = emoji.replace_emoji(text, replace=add_font)
return res
def strip_quotes(path):
if path.startswith('"') and path.endswith('"'):
return path[1:-1]
return path
def check_path(path=None):
if path is None:
return True
else:
return os.path.exists(path)
if __name__ == '__main__':
pass
================================================
FILE: Utility/__init__.py
================================================
================================================
FILE: Utility/observer.py
================================================
# Of course, "very flexible Python" allows you to do without an abstract
# superclass at all or use the clever exception `NotImplementedError`. In my
# opinion, this can negatively affect the architecture of the application.
# I would like to point out that using Kivy, one could use the on-signaling
# model. In this case, when the state changes, the model will send a signal
# that can be received by all attached observers. This approach seems less
# universal - you may want to use a different library in the future.
class Observer:
"""Abstract superclass for all observers."""
def model_is_changed(self):
"""
The method that will be called on the observer when the model changes.
"""
================================================
FILE: View/ChatScreen/__init__.py
================================================
================================================
FILE: View/ChatScreen/chat_screen.kv
================================================
#:import hex kivy.utils.get_color_from_hex
<ChatScreenView>:
FitImage:
source: "assets/images/bg.png"
pos: self.pos
size: self.size
MDBoxLayout:
orientation: "vertical"
MDBoxLayout:
size_hint_y: None
height: 50
spacing: 5
md_bg_color: app.theme_cls.primary_color
padding: [0, 0, 10, 0]
MDIconButton:
icon: 'arrow-left'
theme_text_color: 'Custom'
user_font_size: 18
size_hint: (None, None)
pos_hint: {'center_y':.5}
size: 30, 30
padding: 0
pos_hint: {'center_y':.5}
on_press: root.controller.previous_screen()
MDBoxLayout:
size_hint: None, None
size: 30, 30
orientation: 'vertical'
pos_hint: {'center_y': .5}
Avatar:
source: 'assets/images/avatar.png'
size: 30, 30
size_hint: None, None
MDBoxLayout:
orientation: "vertical"
padding: [0, 10, 0, 10]
MLabel:
markup: True
text: root.selected_user
size: self.texture_size
size_hint_y: None
size_hint_x: None
font_size: 12
bold: True
adaptive_size: True
MDBoxLayout:
size_hint_x: None
spacing: 5
MDIcon:
icon: 'circle'
theme_text_color: 'Custom'
color: [0, 1, 0, 1] if root.active == True else [.5, .5, .5, 1]
font_size: 10
size: 10, 10
size_hint: None, None
MLabel:
text: root.status
size: self.texture_size
size_hint_y: None
size_hint_x: None
font_size: 10
color: app.theme_cls.opposite_bg_normal
adaptive_size: True
RV:
id: rv
viewclass: 'ChatMessage'
size_hint_y: 0.9
key_size: 'size'
effect_cls: 'ScrollEffect'
bar_width: 10
scroll_type: ['content', 'bars']
RecycleBoxLayout:
id: rvbox
orientation: 'vertical'
size_hint_y: None
height: self.minimum_height
default_size_hint: 1, None
padding: 10
spacing: 5
================================================
FILE: View/ChatScreen/chat_screen.py
================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Chat Screen
"""
import os
from typing import NoReturn
from PIL import Image
from kivy.uix.behaviors import ButtonBehavior
from kivy.properties import OptionProperty, StringProperty, DictProperty, NumericProperty, ObjectProperty
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivymd.app import MDApp
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.dialog import MDDialog
from kivymd.uix.behaviors import RectangularRippleBehavior, CommonElevationBehavior
from kivymd.uix.spinner import MDSpinner
from Utility.Utils import fix_emojis, check_path
from View.MainScreen.main_screen import MLabel
from View.base_screen import BaseScreenView
import webbrowser
from kivy.clock import Clock
class RV(RecycleView):
def __init__(self, **kwargs):
super().__init__(**kwargs)
class Attachment(ButtonBehavior, RectangularRippleBehavior, CommonElevationBehavior, MLabel):
def __init__(self, **kwargs):
super().__init__(**kwargs)
class Quote(MLabel):
def __init__(self, **kwargs):
super().__init__(**kwargs)
class ChatMessage(RecycleDataViewBehavior, MDBoxLayout):
index = 0
txt_data = StringProperty()
from_me = NumericProperty() # 1 -> me;
timestamp = StringProperty()
media_filename = StringProperty()
file_path = ObjectProperty(allownone=True)
text_width = NumericProperty()
msg_quoted_text_data = StringProperty()
message_quoted_from_me = NumericProperty(allownone=True)
dialog = None
def dialog_dismiss(self):
del self.dialog
def hide_dialog(self):
self.dialog.dismiss()
def show_dialog(self, msg, title=None, auto_dismiss=True) -> NoReturn:
"""Displays a wait dialog while the model is processing data."""
self.dialog = MDDialog(title='Login', radius=[20, 7, 20, 7])
self.dialog.bind(on_dismiss=lambda x: self.dialog_dismiss())
self.dialog.auto_dismiss = auto_dismiss
if title:
self.dialog.title = title + '\n'
self.dialog.text = msg
if not auto_dismiss:
progress = MDSpinner(determinate=False, size_hint=(None, None), size=(48, 48), pos_hint={'right: 1'})
self.dialog.add_widget(progress)
self.dialog.open()
def open_media(self, file_path):
print(f'Opening {file_path}')
if MDApp.get_running_app().wp_dir is None:
self.show_dialog(msg='No Whatsapp directory has been provided.\n'
'To View this file, provide the `Whatsapp directory path` in the login screen', title='Error')
return
path = os.path.join(MDApp.get_running_app().wp_dir, file_path)
if not check_path(path):
self.show_dialog(msg=f'{path}\n'
'Does not exist, Maybe the file was removed or you provided an incorrect'
'`Whatsapp directory path`',
title='Error')
return
webbrowser.open(path)
def get_msg_widget(self):
return self.ids['msg_content']
def refresh_view_attrs(self, rv, index, data):
self.index = index
self.txt_data = fix_emojis(data['text_data'], MDApp.get_running_app().emojis_font)
if data['file_path'] is not None:
self.media_filename = data['file_path'].split('/')[-1]
else:
self.media_filename = ''
if data['message_quoted_text_data'] is not None:
self.msg_quoted_text_data = fix_emojis(data['message_quoted_text_data'], MDApp.get_running_app().emojis_font)
else:
self.msg_quoted_text_data = ''
return super().refresh_view_attrs(rv, index, data)
def refresh_view_layout(self, rv, index, layout, viewport):
return super().refresh_view_layout(rv, index, layout, viewport)
class ChatScreenView(BaseScreenView):
active = True
text = 'text'
image = 'image'
selected_user = StringProperty()
status = StringProperty()
def __init__(self, **kw):
super(ChatScreenView, self).__init__(**kw)
self.dialog = MDDialog()
self.dialog.bind(on_dismiss=lambda x: print('run something on dialog dismissed'))
self.image = 'image'
self.selected_user = self.app.selected_user
def dialog_dismiss(self):
del self.dialog
def hide_dialog(self):
self.dialog.dismiss()
def show_dialog(self, msg, title=None, auto_dismiss=True) -> NoReturn:
self.dialog = MDDialog(title='Login', radius=[20, 7, 20, 7])
self.dialog.bind(on_dismiss=lambda x: self.dialog_dismiss())
self.dialog.auto_dismiss = auto_dismiss
if title:
self.dialog.title = title + '\n'
self.dialog.text = msg
if not auto_dismiss:
progress = MDSpinner(determinate=False, size_hint=(None, None), size=(48, 48), pos_hint={'right: 1'})
self.dialog.add_widget(progress)
self.dialog.open()
def show_chat_messages(self, chat_messages):
self.ids.rvbox.clear_widgets()
self.ids.rv.data = chat_messages
Clock.schedule_once(lambda dt: self.scroll_to_bottom(), 0)
def scroll_to_bottom(self):
self.ids.rv.scroll_y = 0
def model_is_changed(self) -> None:
"""
Called whenever any change has occurred in the data model.
The view in this method tracks these changes and updates the UI
according to these changes.
"""
================================================
FILE: View/LoginScreen/__init__.py
================================================
================================================
FILE: View/LoginScreen/about.kv
================================================
#:import hex kivy.utils.get_color_from_hex
<About>
size_hint_y: None
height: "400dp"
MDTabs:
tab_indicator_anim: True
tab_indicator_height: 5
tab_hint_x: True
allow_stretch: True
background_color: app.theme_cls.accent_color
indicator_color: app.theme_cls.primary_color
Tab:
title: "About"
ScrollView:
do_scroll_y: True
bar_width: 10
MDBoxLayout:
orientation: 'vertical'
md_bg_color: app.theme_cls.bg_normal
size_hint_y: None
adaptive_height: True
padding: [10, 10, 10, 10]
MDLabel:
id: about_label
markup: True
adaptive_height: True
text: root.about
Tab:
title: "License"
ScrollView:
do_scroll_y: True
bar_width: 10
MDBoxLayout:
orientation: 'vertical'
md_bg_color: app.theme_cls.bg_normal
size_hint_y: None
adaptive_height: True
padding: [10, 10, 10, 10]
MDLabel:
markup: True
adaptive_size: True
text: root.license
================================================
FILE: View/LoginScreen/login_screen.kv
================================================
<LoginScreenView>
FitImage:
source: "assets/images/bg.png"
MDBoxLayout:
orientation: "vertical"
spacing: 15
FitImage:
source: "assets/images/logo.png"
padding: 4
pos_hint: {"center_x": .5, "center_y": .5}
size_hint: None, None
MDLabel:
id: app_name
text: "Whatsapp Msgstore Viewer"
font_style: "H5"
adaptive_height: True
halign: "center"
MDRectangleFlatIconButton:
text: "Check the source code on Github"
icon: "github"
pos_hint: {"center_x": .5, "center_y": .5}
size_hint: None, None
on_press: root.open_github_page()
MDFloatLayout:
MDBoxLayout:
orientation: "vertical"
adaptive_height: True
size_hint_x: None
width: root.width - dp(72)
radius: 12
padding: "12dp"
md_bg_color: 1, 1, 1, .5
pos_hint: {"center_x": .5, "center_y": .5}
MDBoxLayout:
orientation: "vertical"
adaptive_height: True
padding: "25dp"
spacing: "20dp"
TextFieldFileManager:
id: msgstore_file_path
hint_text: "msgstore.db file path"
pos_hint: {"center_x": .5, "center_y": .5}
TextFieldFileManager:
id: wa_file_path
hint_text: "wa.db file path (Optional)"
pos_hint: {"center_x": .5, "center_y": .5}
helper_text: "To view contact names instead of just their numbers"
TextFieldFileManager:
id: wp_dir
hint_text: "`Whatsapp` Directory (Optional)"
pos_hint: {"center_x": .5, "center_y": .5}
helper_text: "In case you want to view the media in the chat (audios, videos, images ...), leave it blank otherwise"
MDTextField:
id: db_version
pos_hint: {'center_x': .5, 'center_y': .5}
text: app.db_version
hint_text: "Database version"
readonly: True
on_focus: if self.focus: root.menu.open()
helper_text: 'Check the github page for more details'
MDBoxLayout:
id: key_file_container
orientation: 'horizontal'
MDCheckbox:
id: enc_checkbox
size_hint: None, None
size: "48dp", "48dp"
pos_hint: {'center_x': .5, 'center_y': .5}
on_active: root.on_enc_checkbox(self.active)
MDLabel:
markup: True
text: "Encrypted database"
font_style: "Body2"
valign: "center"
theme_text_color: 'Secondary'
MDRoundFlatButton:
text: "Advanced settings"
on_release: root.open_settings()
MDFillRoundFlatButton:
text: "LOGIN" if not enc_checkbox.active else 'DECRYPT & LOGIN'
on_release: root.controller.on_tap_button_login()
pos_hint: {"center_x": .5, "center_y": .1}
Attachment:
# not an attachment but same ui attributes
markup: True
text: "[ref=about]About[/ref]"
adaptive_height: True
halign: "center"
theme_text_color: 'Secondary'
padding_y: dp(10)
pos_hint: {"center_x": .5, "center_y": 0.025}
on_ref_press: root.open_about()
================================================
FILE: View/LoginScreen/login_screen.py
================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Login screen
"""
import os
import webbrowser
from typing import NoReturn
from kivy.metrics import dp
from kivy.properties import StringProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.scrollview import ScrollView
from kivymd.app import MDApp
from kivymd.toast import toast
from kivymd.uix.button import MDFlatButton, MDRaisedButton
from kivymd.uix.dialog import MDDialog
from kivymd.uix.filemanager import MDFileManager
from kivymd.uix.menu import MDDropdownMenu
from kivymd.uix.relativelayout import MDRelativeLayout
from kivymd.uix.spinner import MDSpinner
from Utility.Utils import check_path
from View.base_screen import BaseScreenView
import json
class TextFieldFileManager(MDRelativeLayout):
text = StringProperty()
hint_text = StringProperty()
helper_text = StringProperty()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.manager_open = False
self.file_manager = MDFileManager(
exit_manager=self.exit_manager, select_path=self.select_path
)
def file_manager_open(self):
self.file_manager.show(os.path.expanduser("~")) # output manager to the screen
self.manager_open = True
def select_path(self, path: str):
self.exit_manager()
toast(path)
self.text = path
def on_text(self, instance, value):
self.text = value
def exit_manager(self, *args):
self.manager_open = False
self.file_manager.close()
def events(self, instance, keyboard, keycode, text, modifiers):
'''Called when buttons are pressed on the mobile device.'''
if keyboard in (1001, 27):
if self.manager_open:
self.file_manager.back()
return True
def open_file_manager(self, hint_text):
self.file_manager.show(os.path.expanduser("~")) # output manager to the screen
self.manager_open = True
class SettingsContent(ScrollView):
pass
class About(BoxLayout):
about = StringProperty()
license = StringProperty()
credits = StringProperty()
def __init__(self, **kwargs):
super().__init__(**kwargs)
with open('about', 'r') as file:
content = file.read()
self.about = content.replace('$$version$$', MDApp.get_running_app().version)\
.replace('$$g_page$$', MDApp.get_running_app().g_page)
with open('LICENSE', 'r') as file:
self.license = file.read()
with open('credits', 'r') as file:
self.credits = file.read()
self.ids.about_label.bind(on_ref_press=self.open_link)
def open_link(self, instance, link):
webbrowser.open(link)
class LoginScreenView(BaseScreenView):
def __init__(self, **kw):
super(LoginScreenView, self).__init__(**kw)
self.dialog = None
menu_items = [
{
"viewclass": "OneLineListItem",
"height": dp(56),
"text": f"{version}",
"on_release": lambda x=version: self.set_item(x),
}
for version in MDApp.get_running_app().db_versions
]
self.menu = MDDropdownMenu(
caller=self.ids.db_version,
items=menu_items,
position="bottom",
width_mult=4,
)
self.settings_content = SettingsContent()
self.settings_dialog = MDDialog(
title="Advanced Settings",
type="custom",
content_cls=self.settings_content,
buttons=[
MDFlatButton(
text="CANCEL",
theme_text_color="Custom",
text_color=self.theme_cls.primary_color,
on_release=self.settings_cancel
),
MDRaisedButton(
text="Save",
theme_text_color="Custom",
on_release=self.settings_save
),
],
)
self.about = About()
self.about_dialog = MDDialog(
title="About",
type="custom",
content_cls=self.about,
)
self.key_file_widget = TextFieldFileManager(id='key_file', hint_text="Key",
pos_hint={"center_x": .5, "center_y": .5},
helper_text="To decrypt the database")
self.login_data_file = os.path.join(self.app.user_data_dir, "login_data.json")
def set_item(self, text__item):
self.ids.db_version.text = text__item
self.app.db_version = text__item
self.menu.dismiss()
def dialog_dismiss(self):
self.dialog = None
def hide_dialog(self):
if self.dialog is not None:
self.dialog.dismiss()
def show_dialog(self, msg, title=None, auto_dismiss=False) -> NoReturn:
"""Displays a wait dialog while the model is processing data."""
self.hide_dialog()
self.dialog = MDDialog(title='Login', radius=[20, 7, 20, 7])
self.dialog.bind(on_dismiss=lambda x: self.dialog_dismiss())
self.dialog.auto_dismiss = auto_dismiss
if title:
self.dialog.title = title + '\n'
self.dialog.text = msg
if auto_dismiss is False:
progress = MDSpinner(determinate=False, size_hint=(None, None), size=(48, 48), pos_hint={'right: 1'})
self.dialog.add_widget(progress)
self.dialog.open()
def on_enc_checkbox(self, state, *args):
if state:
self.ids.key_file_container.add_widget(self.key_file_widget)
else:
self.ids.key_file_container.remove_widget(self.key_file_widget)
def open_settings(self):
print('opening settings')
self.settings_dialog.open()
def settings_cancel(self, *args):
self.settings_dialog.dismiss()
def settings_save(self, *args):
general_font_path = self.settings_content.ids['general_font'].text
if general_font_path == '':
self.app.general_font = self.app.default_settings['general_font']
else:
if not check_path(general_font_path):
self.show_dialog(msg=f'The path `{general_font_path}` does not exist', title='General Font error',
auto_dismiss=True)
return
self.app.general_font = general_font_path
# I am exhausted, I don't want to think of any other abstraction !! Let us do it stupidly
emojis_font_path = self.settings_content.ids['emojis_font'].text
if emojis_font_path == '':
self.app.emojis_font = self.app.default_settings['emojis_font']
else:
if not check_path(general_font_path):
self.show_dialog(msg=f'The path `{emojis_font_path}` does not exist', title='Emojis Font error',
auto_dismiss=True)
return
self.app.emojis_font = emojis_font_path
# call log size
call_log_size = self.settings_content.ids['call_log_size'].text
if call_log_size == '':
self.app.call_log_size = self.app.default_settings['call_log_size']
else:
try:
call_log_size_int = int(call_log_size)
self.app.call_log_size = call_log_size_int
except Exception as e:
self.show_dialog(msg=f'Call log size`{call_log_size}` is not a number', title='Calls log size error',
auto_dismiss=True)
return
self.settings_dialog.dismiss()
toast('Settings saved successfully')
def show_toast(self, msg):
toast(msg)
def open_about(self):
self.about_dialog.open()
def open_github_page(self):
webbrowser.open(self.app.g_page)
def model_is_changed(self) -> None:
"""
Called whenever any change has occurred in the data model.
The view in this method tracks these changes and updates the UI
according to these changes.
"""
def on_kv_post(self, base_widget):
self.ids.msgstore_file_path.bind(text=self.save_fields)
self.ids.wa_file_path.bind(text=self.save_fields)
self.ids.wp_dir.bind(text=self.save_fields)
self.ids.db_version.bind(text=self.save_fields)
def save_fields(self, *args):
data = {
'msgstore_file_path': self.ids.msgstore_file_path.text,
'wa_file_path': self.ids.wa_file_path.text,
'wp_dir': self.ids.wp_dir.text,
'db_version': self.ids.db_version.text
}
with open(self.login_data_file, "w") as f:
json.dump(data, f)
def on_pre_enter(self, *args):
try:
with open(self.login_data_file, "r") as f:
data = json.load(f)
self.ids.msgstore_file_path.text = data.get('msgstore_file_path', '')
self.ids.wa_file_path.text = data.get('wa_file_path', '')
self.ids.wp_dir.text = data.get('wp_dir', '')
self.ids.db_version.text = data.get('db_version', '')
self.app.db_version = data.get('db_version', '')
except FileNotFoundError:
pass
================================================
FILE: View/LoginScreen/settings.kv
================================================
<SettingsContent>:
size_hint_y: None
height: "300dp"
bar_width: 10
scroll_type: ['content', 'bars']
BoxLayout:
size_hint_y: None
height: self.minimum_height
default_size_hint: 1, None
orientation: "vertical"
spacing: "12dp"
TextFieldFileManager:
id: general_font
hint_text: "General font (Leave it blank to load the default font)"
pos_hint: {"center_x": .5, "center_y": .5}
helper_text: "In case you are seeing wierd characters, it is probably a font issue, \ntry to load another one that supports your language"
TextFieldFileManager:
id: emojis_font
hint_text: "Emojis font (Leave it blank to load the default font)"
pos_hint: {"center_x": .5, "center_y": .5}
helper_text: "Load a different emojis font"
MDTextField:
id: call_log_size
input_type: 'number'
hint_text: "Calls log size"
text: '10'
pos_hint: {"center_x": .5, "center_y": .5}
helper_text: "Limit the loaded calls log size (for a fast loading of the app)"
================================================
FILE: View/MainScreen/__init__.py
================================================
================================================
FILE: View/MainScreen/main_screen.kv
================================================
<MainScreenView>
MDBoxLayout:
orientation: "vertical"
MDTopAppBar:
id: logoToolBar
height: 50
anchor_title: 'left'
opposite_colors: True
title: "Whatsapp"
right_action_items: [['logout', root.controller.log_out, 'Log out']]
margin: 0
MDTabs:
tab_indicator_anim: True
tab_indicator_height: 5
tab_hint_x: True
allow_stretch: True
Tab:
title: "Chats"
RV:
id: contact_chat_list
viewclass: 'ChatListItem'
bar_width: 10
scroll_type: ['content', 'bars']
key_size: 'height'
RecycleBoxLayout:
default_size: None, dp(72)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
Tab:
title: "Groups"
RV:
id: group_chat_list
viewclass: 'ChatListItem'
bar_width: 10
scroll_type: ['content', 'bars']
key_size: 'height'
RecycleBoxLayout:
default_size: None, dp(72)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
Tab:
title: "Calls"
RV:
id: calls
viewclass: 'CallListItem'
bar_width: 10
scroll_type: ['content', 'bars']
key_size: 'height'
RecycleBoxLayout:
default_size: None, dp(72)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
================================================
FILE: View/MainScreen/main_screen.py
================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Main Screen
"""
from typing import NoReturn
from kivy.properties import StringProperty, NumericProperty, ObjectProperty
from kivymd.uix.card import MDCard
from kivymd.uix.dialog import MDDialog
from kivymd.uix.floatlayout import MDFloatLayout
from kivymd.uix.label import MDLabel
from kivymd.uix.tab import MDTabsBase
from Utility.Utils import fix_emojis
from View.base_screen import BaseScreenView
from kivy.uix.recycleview.views import RecycleDataViewBehavior
class Tab(MDFloatLayout, MDTabsBase):
pass
class MLabel(MDLabel):
def __init__(self, **kwargs):
super().__init__(**kwargs)
class ChatListItem(RecycleDataViewBehavior, MDCard):
controller = ObjectProperty()
id = ObjectProperty()
jid = StringProperty()
contact_name = StringProperty()
last_message = StringProperty()
timestamp = StringProperty()
class CallListItem(RecycleDataViewBehavior, MDCard):
# controller = ObjectProperty()
id = ObjectProperty()
jid = StringProperty()
user = StringProperty()
from_me = NumericProperty()
timestamp = StringProperty()
video_call = NumericProperty()
duration = StringProperty()
class MainScreenView(BaseScreenView):
def __init__(self, **kw):
super(MainScreenView, self).__init__(**kw)
self.dialog = MDDialog()
def show_dialog_wait(self) -> NoReturn:
"""Displays a wait dialog while the model is processing data."""
self.dialog.auto_dismiss = True
self.dialog.text = "Loading ..."
self.dialog.open()
def model_is_changed(self) -> None:
"""
Called whenever any change has occurred in the data model.
The view in this method tracks these changes and updates the UI
according to these changes.
"""
pass
def show_chats_list(self, contact_chats):
self.ids.contact_chat_list.data = [{
'controller': self.controller,
'id': chat['_id'],
'contact_name': chat["user"],
'last_message': fix_emojis(chat['text_data'], self.app.emojis_font) if chat['text_data'] else '',
'timestamp': '\n'.join(chat['timestamp'].split(' ')),
'jid': chat['raw_string_jid'],
} for chat in contact_chats]
def build_group_chat_list(self, group_chats):
self.ids.group_chat_list.data = [{
'id': chat['_id'],
'contact_name': fix_emojis(chat['user'], self.app.emojis_font),
'last_message': fix_emojis(chat['text_data'], self.app.emojis_font) if chat['text_data'] else '',
'timestamp': '\n'.join(chat['timestamp'].split(' ')),
'controller': self.controller,
} for chat in group_chats]
def build_calls_list(self, calls):
self.ids.calls.data = [{
'id': call['_id'],
'jid': call['raw_string_jid'],
'user': fix_emojis(call['user'], self.app.emojis_font),
'from_me': call['from_me'],
'video_call': call['video_call'],
'timestamp': call['timestamp'],
'duration': str(call['duration']),
} for call in calls]
================================================
FILE: View/base_screen.py
================================================
from kivy.properties import ObjectProperty
from kivymd.app import MDApp
from kivymd.uix.screen import MDScreen
from Utility.observer import Observer
class BaseScreenView(MDScreen, Observer):
"""
A base class that implements a visual representation of the model data.
The view class must be inherited from this class.
"""
controller = ObjectProperty()
"""
Controller object - :class:`~Controller.controller_screen.ClassScreenController`.
:attr:`controller` is an :class:`~kivy.properties.ObjectProperty`
and defaults to `None`.
"""
model = ObjectProperty()
"""
Model object - :class:`~Model.model_screen.ClassScreenModel`.
:attr:`model` is an :class:`~kivy.properties.ObjectProperty`
and defaults to `None`.
"""
manager_screens = ObjectProperty()
"""
Screen manager object - :class:`~kivymd.uix.screenmanager.MDScreenManager`.
:attr:`manager_screens` is an :class:`~kivy.properties.ObjectProperty`
and defaults to `None`.
"""
def __init__(self, **kw):
super().__init__(**kw)
# Often you need to get access to the application object from the view
# class. You can do this using this attribute.
self.app = MDApp.get_running_app()
# Adding a view class as observer.
self.model.add_observer(self)
================================================
FILE: View/components/MLabel.kv
================================================
<MLabel>:
markup: True
font_name: app.general_font
================================================
FILE: View/components/__init__.py
================================================
================================================
FILE: View/components/attachment.kv
================================================
<Attachment>:
markup: True
color: (0,0,1,1)
================================================
FILE: View/components/avatar.kv
================================================
<Avatar@RelativeLayout>:
size: (45, 45)
size_hint: (None, None)
source: root.source
MDCard:
size: root.size
size_hint: (None, None)
radius: [30, ]
md_bg_color: app.theme_cls.accent_color
elevation: 0
pos_hint: {'center_x': .5, 'center_y': .5}
FitImage:
size: root.size[0] - 3, root.size[1]-3
radius: [30, ]
size_hint: (None, None)
source: root.source
pos_hint: {'center_x': .5, 'center_y': .5}
================================================
FILE: View/components/call_list_item.kv
================================================
<CallListItem>:
ripple_behavior: True
md_bg_color: 0, 0, 0, 0
elevation: 0
size_hint_y: None
padding: [10, 0, 10, 0]
spacing: 10
height: avatar.height + 10
Avatar:
id: avatar
source: 'assets/images/avatar.png'
pos_hint: {"center_y": .5}
radius: [30, ]
MDBoxLayout:
# md_bg_color: 1, 0, 1, 1
orientation: "vertical"
padding: [0, 0, 0, 10]
spacing: 2
Label:
markup: True
id: user_name
text: root.user
theme_text_color: 'Custom'
size: self.texture_size
size_hint_y: None
size_hint_x: None
font_size: 15
color: app.theme_cls.opposite_bg_normal
bold: True
MDBoxLayout:
orientation: "horizontal"
# padding: [0, 0, 0, 10]
spacing: 5
MDIcon:
id: out_in_call_icon
theme_text_color: 'Custom'
icon: 'arrow-top-right' if root.from_me == 1 else 'arrow-bottom-left'
size_hint: None, None
font_size: 18
size: 20, 20
pos_hint: {"center_x": .5, 'center_y': .5}
text_color: 'green' if root.from_me == 1 else 'red'
MLabel:
id: timestamp
text: root.timestamp
height: self.texture_size[1]
theme_text_color: 'Custom'
size_hint_y: None
bold: True
font_size: 15
shorten: True
markup: True
shorten_from: 'right'
MLabel:
id: call_duration
text: root.duration
height: self.texture_size[1]
theme_text_color: 'Custom'
adaptive_size: True
size_hint_y: None
pos_hint: {"center_x": .5, 'center_y': .5}
bold: True
font_size: 15
markup: True
MDIcon:
id: audio_video_icon
theme_text_color: 'Custom'
icon: 'video' if root.video_call == 1 else 'phone'
size_hint: None, None
font_size: 18
size: 20, 20
pos_hint: {"center_x": .5, 'center_y': .5}
text_color: app.theme_cls.primary_color
================================================
FILE: View/components/chat_list_item.kv
================================================
<ChatListItem>:
ripple_behavior: True
md_bg_color: 0, 0, 0, 0
elevation: 0
size_hint_y: None
padding: [10, 0, 10, 0]
spacing: 10
height: chatAvatar.height + 10
on_press: root.controller.show_chat_screen(root.id, root.contact_name, root.jid)
Avatar:
id: chatAvatar
source: 'assets/images/avatar.png'
pos_hint: {"center_y": .5}
radius: [30, ]
MDBoxLayout:
orientation: "vertical"
padding: [0, 0, 0, 10]
spacing: 2
MLabel:
id: contactName
adaptive_size: True
text: root.contact_name
theme_text_color: 'Custom'
size: self.texture_size
size_hint_y: None
size_hint_x: None
font_size: 17
color: app.theme_cls.opposite_bg_normal
bold: True
MDBoxLayout:
orientation: "horizontal"
spacing: 5
MDIcon:
theme_text_color: 'Custom'
icon: 'check-all'
size_hint: None, None
font_size: 18
size: 20, 20
pos_hint: {"center_x": .5, 'center_y': .5}
text_color: (0, 0, 1, 1)
MLabel:
id: lastMessage
text: root.last_message
height: self.texture_size[1]
theme_text_color: 'Custom'
size_hint_y: None
bold: True
font_size: 15
color: [.5, .5, .5, 1]
shorten: True
markup: True
shorten_from: 'right'
valign: 'center'
Label:
id: time
text: root.timestamp
size: self.texture_size
pos_hint: {'center_y': 0.5}
size_hint_y: None
size_hint_x: None
font_size: 13
color: app.theme_cls.opposite_bg_normal
valign: 'center'
halign: 'center'
================================================
FILE: View/components/chat_message.kv
================================================
#:import hex kivy.utils.get_color_from_hex
<ChatMessage>:
orientation: 'vertical'
height: chat_message.height
MDCard:
id: chat_message
padding: 10
orientation: 'vertical'
md_bg_color: hex('#D9FDD3') if root.from_me == 1 else hex('#FFFFFF')
pos_hint: {'right': 1} if root.from_me == 1 else {'left': 1}
width: max(msg_text.width, time.width, attachment.width, quote.width) + 20
height: msg_text.height + time.height + attachment.height + quote.height + 20
size_hint: None, None
Quote:
id: quote
text: f"{root.msg_quoted_text_data}"
adaptive_size: True
pos_hint: {'right': 1} if root.from_me == 1 else {'left': 1}
halign: 'right' if root.from_me == 1 else 'left'
md_bg_color: hex('#d1f4cc') if root.from_me == 1 else hex('#f5f6f6')
line_color: hex('#06cf9c') if root.message_quoted_from_me == 0 else hex('#53bdeb')
padding: (10, 10)
MLabel:
id: msg_text
allow_copy: True
allow_selection: True
pos_hint: {'right': 1} if root.from_me == 1 else {'left': 1}
halign: 'right' if root.from_me == 1 else 'left'
valign: 'center'
text: root.txt_data
size_hint: None, None
adaptive_size: True
size: self.texture_size
Attachment:
id: attachment
text: f"[u][ref=link]{root.media_filename}[/ref][/u]"
on_ref_press: root.open_media(root.file_path)
adaptive_size: True
pos_hint: {'right': 1} if root.from_me == 1 else {'left': 1}
size_hint: None, None
padding: (10, 10)
MLabel:
id: time
pos_hint: {'right': 1} if root.from_me == 1 else {'left': 1}
text: root.timestamp
adaptive_size: True
font_size: 11
color: 0,0,0,0.5
================================================
FILE: View/components/quote.kv
================================================
<Quote>:
markup: True
allow_copy: True
allow_selection: True
valign: 'center'
size_hint: None, None
adaptive_size: True
size: self.texture_size
================================================
FILE: View/components/textfield_filemanger.kv
================================================
<TextFieldFileManager>:
size_hint_y: None
height: text_field.height
MDTextField:
id: text_field
hint_text: root.hint_text
text: root.text
helper_text: root.helper_text
on_text: root.on_text(self, self.text)
MDIconButton:
icon: "folder-open-outline"
pos_hint: {"center_y": .5}
pos: text_field.width - self.width + dp(8), 0
theme_text_color: "Hint"
on_release: root.open_file_manager(root.hint_text)
================================================
FILE: View/screens.py
================================================
# The screens dictionary contains the objects of the models and controllers
# of the screens of the application.
from Model.login_screen import LoginScreenModel
from Controller.login_screen import LoginScreenController
from Model.main_screen import MainScreenModel
from Controller.main_screen import MainScreenController
from Model.chat_screen import ChatScreenModel
from Controller.chat_screen import ChatScreenController
screens = {
"login screen": {
"model": LoginScreenModel,
"controller": LoginScreenController,
},
"main screen": {
"model": MainScreenModel,
"controller": MainScreenController,
},
"chat screen": {
"model": ChatScreenModel,
"controller": ChatScreenController,
},
}
================================================
FILE: about
================================================
[b]Whatsapp Msgstore Viewer[/b] (WMV)
Version $$version$$
(C) 2023 [ref=https://github.com/absadiki][color=0000ff]absadiki[/color][/ref]
[color=ffffff]\n[/color]
WMV is a free, open source and cross-platform app to decrypt, read and view the Whatsapp [i]msgstore.db[/i] database.
It is licenced under the GNU General Licence version 3 or later. You can modify or redistribute it under the conditions
of these licences. (See the licence tab for more information)
[color=ffffff]\n[/color]
Visit the [ref=$$g_page$$][color=0000ff]Github[/color][/ref] page for more information.
================================================
FILE: credits
================================================
This software would not possible without:
[color=ffffff]\n[/color]
- [ref=https://kivy.org][color=0000ff]Kivy[/color][/ref] & [ref=https://kivymd.readthedocs.io][color=0000ff]KivyMD[/color][/ref] for the UI framework.
- [ref=https://github.com/haddiebakrie/WhatsApp-Redesign][color=0000ff]WhatsApp-Redesign[/color][/ref] for the design inspiration and some UI components.
- [ref=https://github.com/ElDavoo/WhatsApp-Crypt14-Crypt15-Decrypter][color=0000ff]WhatsApp-Crypt14-Crypt15-Decrypter[/color][/ref] for the decryption algorithm.
- [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]).
- [ref=https://github.com/Pustur/whatsapp-chat-parser-website][color=0000ff]whatsapp-chat-parser-website[/color][/ref] for the background image.
[color=ffffff]\n[/color]
- And so many more libraries and frameworks.
[color=ffffff]\n[/color]
================================================
FILE: dbs/__init__.py
================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Short description of this Python module.
Longer description of this module.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
"""
__author__ = "One solo developer"
__authors__ = ["One developer", "And another one", "etc"]
__contact__ = "mail@example.com"
__copyright__ = "Copyright 2023, "
__credits__ = ["One developer", "And another one", "etc"]
__date__ = "YYYY/MM/DD"
__deprecated__ = False
__email__ = "mail@example.com"
__license__ = "GPLv3"
__maintainer__ = "developer"
__status__ = "Production"
__version__ = "0.0.1"
if __name__ == '__main__':
pass
================================================
FILE: dbs/abstract_db.py
================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file describes how the database should look like and what it should return.
Because this app is only a reverse engineering attempt of the Whatsapp database, it is very likely that it might break
in case there have been any updates to the database.
The `schema` variable and the `AbstractDatabase` class are introduced to make it easy to add support to
different versions of databases.
"""
import sqlite3
from abc import ABC, abstractmethod
class AbstractDatabase(ABC):
def __init__(self, msgstore, wa=None, schema=None):
self.msgstore = msgstore
self.wa = wa
self.contacts = None
self.schema: dict = schema # a simple map between the (tables, attributes) used in the code and their real
# in the database, see the `check_database_schema` method for more details
msgstore_con = sqlite3.connect(self.msgstore, check_same_thread=False)
msgstore_con.row_factory = lambda c, r: dict([(col[0], r[idx]) for idx, col in enumerate(c.description)])
self.msgstore_cursor = msgstore_con.cursor()
if wa is not None:
wa_con = sqlite3.connect(self.wa, check_same_thread=False)
wa_con.row_factory = lambda c, r: dict([(col[0], r[idx]) for idx, col in enumerate(c.description)])
self.wa_cursor = wa_con.cursor()
self.load_contacts(self.wa_cursor)
@abstractmethod
def fetch_contact_chats(self):
"""
This function should return a list of dicts of the available contact chat views,
The list should look like this:
[
{'_id': 1,
'user': '123456789',
'raw_string_jid': '123456789@s.whatsapp.net',
'text_data': 'See my last message',
'timestamp': '2022-10-29 17:45:21'
},
{'_id': 2,
'user': '123456780',
'raw_string_jid': '123456780@s.whatsapp.net',
'text_data': 'See my last message',
'timestamp': '2022-04-30 17:45:21'
},
]
"""
pass
@abstractmethod
def fetch_group_chats(self):
"""
This function should return a list of dicts of the available grou chats
The list should look like this:
[
{'_id': 3,
'user': 'Group 1', # usually the subject field
'raw_string_jid': '1234567890987654321@g.us',
'text_data': 'See my last message',
'timestamp': '2022-10-29 17:45:21'
},
{'_id': 4,
'user': 'Group 2',
'raw_string_jid': '1234567809087654321@g.us',
'text_data': 'See my last message',
'timestamp': '2022-04-30 17:45:21'
},
]
"""
pass
@abstractmethod
def fetch_calls(self, how_many=None):
"""
This function should return a list of dicts of the available call logs
The list should look like this:
[
{'_id': 1,
'from_me': 0,
'user': '123456789',
'raw_string_jid': '123456789@s.whatsapp.net',
'duration': '00:15:12',
'video_call': 0,
'timestamp': '2022-10-29 17:45:21'
},
{'_id': 2,
'from_me': 1,
'user': '123456780',
'raw_string_jid': '123456780@s.whatsapp.net',
'duration': '00:15:12',
'video_call': 1,
'timestamp': '2022-10-29 17:45:21'
}
]
"""
pass
@abstractmethod
def fetch_chat(self, chat_id):
"""
This function should return a list of dicts of the available chat messages related to the `chat_id` given as
input.
This list should look like this:
[
{
'_id': 1,
'key_id': '4552235ASAASDJKHASH',
'from_me': 1,
'timestamp': '2022-06-28 22:23:13',
'text_data': 'Hello bro, How are you ?',
'file_path': None,
'message_quoted_text_data': None,
'message_quoted_from_me': None,
'message_quoted_key_id': None
},
{
'_id': 1,
'key_id': '4552235ASAASDJKHASH',
'from_me': 0,
'timestamp': '2022-06-28 22:23:13',
'text_data': '',
'file_path': '/media/images/image.png',
'message_quoted_text_data': None,
'message_quoted_from_me': None,
'message_quoted_key_id': None
}
],
"""
pass
def load_contacts(self, wa_cursor):
sql_query = """
SELECT
jid,
status,
display_name,
number,
given_name,
family_name
FROM
wa_contacts
"""
contacts_list = wa_cursor.execute(sql_query).fetchall()
self.contacts = {}
for contact in contacts_list:
self.contacts[contact['jid']] = contact
def check_database_schema(self):
"""
This method checks that the database contains the tables and attributes provided with its schema
It will fail in case a table (or attribute) does not exist, or it has a different name
"""
if self.schema is None:
raise Exception('No schema has been provided!')
for table in self.schema:
table_name = self.schema[table]['name']
attributes = self.schema[table]['attributes']
sql_query = f"SELECT {','.join(attributes)} from {table_name}"
self.msgstore_cursor.execute(sql_query).fetchone() # this will fail if the table or the attributes do not
# exist
================================================
FILE: dbs/v1/__init__.py
================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Short description of this Python module.
Longer description of this module.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
"""
__author__ = "One solo developer"
__authors__ = ["One developer", "And another one", "etc"]
__contact__ = "mail@example.com"
__copyright__ = "Copyright 2023, "
__credits__ = ["One developer", "And another one", "etc"]
__date__ = "YYYY/MM/DD"
__deprecated__ = False
__email__ = "mail@example.com"
__license__ = "GPLv3"
__maintainer__ = "developer"
__status__ = "Production"
__version__ = "0.0.1"
if __name__ == '__main__':
pass
================================================
FILE: dbs/v1/db.py
================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from dbs.abstract_db import AbstractDatabase
class Database(AbstractDatabase):
def __init__(self, msgstore, wa):
schema = {
'chat_view': {
'name': 'chat_view',
'attributes': [
'_id',
'raw_string_jid',
'sort_timestamp',
'last_message_row_id'
]
},
'message': {
'name': 'message',
'attributes': [
'_id',
'chat_row_id',
'key_id',
'from_me',
'timestamp',
'text_data',
]
},
'message_media': {
'name': 'message_media',
'attributes': [
'message_row_id',
'file_path',
]
},
'message_quoted': {
'name': 'message_quoted',
'attributes': [
'message_row_id',
'text_data',
'from_me',
'key_id'
]
},
}
super(Database, self).__init__(msgstore, wa, schema=schema)
def fetch_contact_chats(self):
chat_view_table = self.schema['chat_view']['name'] # I will continue later
sql_query = """
select
chat_view._id,
jid.user,
chat_view.raw_string_jid,
message.text_data,
DATETIME(ROUND(chat_view.sort_timestamp / 1000), 'unixepoch') as timestamp
from chat_view INNER JOIN jid ON chat_view.raw_string_jid=jid.raw_string
INNER JOIN message ON chat_view.last_message_row_id = message._id
WHERE
chat_view.raw_string_jid not LIKE '%g.us'
order by timestamp desc
"""
return self.msgstore_cursor.execute(sql_query).fetchall()
def fetch_group_chats(self):
sql_query = """
select
chat_view._id,
chat_view.subject as user,
chat_view.raw_string_jid,
message.text_data,
DATETIME(ROUND(chat_view.sort_timestamp / 1000), 'unixepoch') as timestamp
from chat_view INNER JOIN jid ON chat_view.raw_string_jid=jid.raw_string
INNER JOIN message ON chat_view.last_message_row_id = message._id
WHERE
chat_view.raw_string_jid LIKE '%g.us'
"""
return self.msgstore_cursor.execute(sql_query).fetchall()
def fetch_calls(self, how_many=None):
sql_query = """
select
call_log._id, call_log.from_me,
DATETIME(ROUND(call_log.timestamp / 1000), 'unixepoch') as timestamp,
call_log.video_call,
Time(call_log.duration, 'unixepoch') as duration,
jid.user,
jid.raw_string as raw_string_jid
from call_log LEFT JOIN jid
ON call_log.jid_row_id = jid._id
"""
if how_many:
return self.msgstore_cursor.execute(sql_query).fetchmany(how_many)
else:
return self.msgstore_cursor.execute(sql_query).fetchall()
def fetch_chat(self, chat_id):
sql_query = f"""
select message._id, message.key_id, message.from_me, DATETIME(ROUND(message.timestamp / 1000), 'unixepoch') as timestamp, ifnull(message.text_data, '') as text_data,
message_media.file_path,
message_quoted.text_data as message_quoted_text_data,
message_quoted.from_me as message_quoted_from_me,
message_quoted.key_id as message_quoted_key_id
from message LEFT JOIN message_media
ON message._id = message_media.message_row_id
LEFT JOIN message_quoted
ON message._id = message_quoted.message_row_id
WHERE message.chat_row_id={chat_id}
"""
return self.msgstore_cursor.execute(sql_query).fetchall()
================================================
FILE: dbs/v2/__init__.py
================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Database interface for accessing and retrieving WhatsApp chat, message, and call data.
This module defines the `Database` class, which extends the `AbstractDatabase` to provide
methods for interacting with WhatsApp's SQLite databases. It facilitates the retrieval of
various data types, including:
- **Chats**: Fetches both individual and group chats with relevant details such as user
information, last message content, and timestamps.
- **Messages**: Retrieves messages associated with a specific chat, including text data,
media file paths, and quoted message details.
- **Calls**: Obtains call logs with information on call direction, type (video or audio),
duration, and associated user details.
The `Database` class constructs SQL queries to extract this information, ensuring that the
retrieved data is organized and accessible for further processing or analysis.
Classes:
Database: Extends `AbstractDatabase` to implement methods for fetching chats, messages,
and call logs from WhatsApp's databases.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
"""
__author__ = "Voice-less"
__copyright__ = "Copyright 2025"
__credits__ = ["Voice-less"]
__date__ = "2025/04/02"
__deprecated__ = False
__license__ = "GPLv3"
__maintainer__ = "Voice-less"
__status__ = "Production"
__version__ = "1.0.0"
if __name__ == '__main__':
pass
================================================
FILE: dbs/v2/db.py
================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from dbs.abstract_db import AbstractDatabase
class Database(AbstractDatabase):
def __init__(self, msgstore, wa):
schema = {
'chat': {
'name': 'chat',
'attributes': [
'_id', # chat id
'jid_row_id', # reference to jid table
'sort_timestamp', # timestamp for sorting/display
'last_message_row_id' # last message id in the chat
]
},
'message': {
'name': 'message',
'attributes': [
'_id', # message id
'chat_row_id', # chat id reference
'key_id', # key id
'from_me', # sent flag
'timestamp', # message timestamp
'text_data' # message text
]
},
'message_media': {
'name': 'message_media',
'attributes': [
'message_row_id', # message reference
'file_path' # media file path
]
},
'message_quoted': {
'name': 'message_quoted',
'attributes': [
'message_row_id', # message reference
'text_data', # quoted message text
'from_me', # quoted message from_me flag
'key_id' # quoted message key id
]
},
}
super(Database, self).__init__(msgstore, wa, schema=schema)
def fetch_contact_chats(self):
sql_query = """
SELECT
chat._id,
jid.user,
jid.raw_string AS raw_string_jid,
message.text_data,
DATETIME(ROUND(chat.sort_timestamp / 1000), 'unixepoch') as timestamp
FROM chat
INNER JOIN jid ON chat.jid_row_id = jid._id
INNER JOIN message ON chat.last_message_row_id = message._id
WHERE jid.raw_string NOT LIKE '%g.us'
ORDER BY timestamp DESC
"""
return self.msgstore_cursor.execute(sql_query).fetchall()
def fetch_group_chats(self):
sql_query = """
SELECT
chat._id,
chat.subject as user,
jid.raw_string,
message.text_data,
DATETIME(ROUND(chat.sort_timestamp / 1000), 'unixepoch') as timestamp
FROM chat
INNER JOIN jid ON chat.jid_row_id = jid._id
INNER JOIN message ON chat.last_message_row_id = message._id
WHERE jid.raw_string LIKE '%g.us'
ORDER BY timestamp DESC
"""
return self.msgstore_cursor.execute(sql_query).fetchall()
def fetch_calls(self, how_many=None):
sql_query = """
SELECT
call_log._id,
call_log.from_me,
DATETIME(ROUND(call_log.timestamp / 1000), 'unixepoch') as timestamp,
call_log.video_call,
TIME(call_log.duration, 'unixepoch') as duration,
jid.user,
jid.raw_string as raw_string_jid
FROM call_log
LEFT JOIN jid ON call_log.jid_row_id = jid._id
"""
if how_many:
return self.msgstore_cursor.execute(sql_query).fetchmany(how_many)
else:
return self.msgstore_cursor.execute(sql_query).fetchall()
def fetch_chat(self, chat_id):
sql_query = f"""
SELECT
message._id,
message.key_id,
message.from_me,
DATETIME(ROUND(message.timestamp / 1000), 'unixepoch') as timestamp,
IFNULL(message.text_data, '') as text_data,
message_media.file_path,
message_quoted.text_data as message_quoted_text_data,
message_quoted.from_me as message_quoted_from_me,
message_quoted.key_id as message_quoted_key_id
FROM message
LEFT JOIN message_media ON message._id = message_media.message_row_id
LEFT JOIN message_quoted ON message._id = message_quoted.message_row_id
WHERE message.chat_row_id = {chat_id}
ORDER BY message.timestamp ASC
"""
return self.msgstore_cursor.execute(sql_query).fetchall()
================================================
FILE: dbs/v3/__init__.py
================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Version 3 database schema support for Whatsapp Msgstore Viewer.
This package is automatically discovered by the application; it only needs
to expose the `Database` class implemented in `db.py`.
"""
__author__ = "Auto-generated by AI"
__version__ = "1.0.0"
if __name__ == '__main__':
pass
================================================
FILE: dbs/v3/db.py
================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from dbs.abstract_db import AbstractDatabase
class Database(AbstractDatabase):
def __init__(self, msgstore, wa):
# Updated schema to match the tables/columns present in the provided DDL
schema = {
# ------------ chat list ------------
'chat': {
'name': 'chat',
'attributes': [
'_id', # Primary key
'jid_row_id', # FK → jid._id
'subject', # Group name (NULL for 1-to-1)
'sort_timestamp', # Sorting timestamp
'last_message_row_id' # FK → message._id
]
},
# ------------ messages ------------
'message': {
'name': 'message',
'attributes': [
'_id', # Primary key
'chat_row_id', # FK → chat._id
'key_id',
'from_me',
'timestamp',
'text_data'
]
},
# ------------ media ------------
'message_media': {
'name': 'message_media',
'attributes': [
'message_row_id', # FK → message._id
'file_path'
]
},
# ------------ quoted messages ------------
'message_quoted': {
'name': 'message_quoted',
'attributes': [
'message_row_id', # FK → message._id
'text_data',
'from_me',
'key_id'
]
},
# ------------ call log ------------
'call_log': {
'name': 'call_log',
'attributes': [
'_id',
'jid_row_id', # FK → jid._id
'from_me',
'timestamp',
'video_call',
'duration'
]
},
# ------------ jid / contacts ------------
'jid': {
'name': 'jid',
'attributes': [
'_id',
'user',
'raw_string'
]
},
}
super(Database, self).__init__(msgstore, wa, schema=schema)
# --- fetch_* methods copied from v2 without modification ---
def fetch_contact_chats(self):
sql_query = """
SELECT
chat._id,
IFNULL(jid.user, '') AS user,
jid.raw_string AS raw_string_jid,
message.text_data,
DATETIME(ROUND(chat.sort_timestamp / 1000), 'unixepoch') AS timestamp
FROM chat
INNER JOIN jid ON chat.jid_row_id = jid._id
INNER JOIN message ON chat.last_message_row_id = message._id
WHERE jid.raw_string NOT LIKE '%g.us'
ORDER BY timestamp DESC
"""
return self.msgstore_cursor.execute(sql_query).fetchall()
def fetch_group_chats(self):
sql_query = """
SELECT
chat._id,
IFNULL(chat.subject, '') AS user,
jid.raw_string AS raw_string_jid,
message.text_data,
DATETIME(ROUND(chat.sort_timestamp / 1000), 'unixepoch') AS timestamp
FROM chat
INNER JOIN jid ON chat.jid_row_id = jid._id
INNER JOIN message ON chat.last_message_row_id = message._id
WHERE jid.raw_string LIKE '%g.us'
ORDER BY timestamp DESC
"""
return self.msgstore_cursor.execute(sql_query).fetchall()
def fetch_calls(self, how_many=None):
sql_query = """
SELECT
call_log._id,
call_log.from_me,
DATETIME(ROUND(call_log.timestamp / 1000), 'unixepoch') AS timestamp,
call_log.video_call,
TIME(call_log.duration, 'unixepoch') AS duration,
IFNULL(jid.user, '') AS user,
jid.raw_string AS raw_string_jid
FROM call_log
LEFT JOIN jid ON call_log.jid_row_id = jid._id
"""
if how_many:
return self.msgstore_cursor.execute(sql_query).fetchmany(how_many)
else:
return self.msgstore_cursor.execute(sql_query).fetchall()
def fetch_chat(self, chat_id):
sql_query = f"""
SELECT
message._id,
message.key_id,
message.from_me,
DATETIME(ROUND(message.timestamp / 1000), 'unixepoch') AS timestamp,
IFNULL(message.text_data, '') AS text_data,
message_media.file_path,
message_quoted.text_data AS message_quoted_text_data,
message_quoted.from_me AS message_quoted_from_me,
message_quoted.key_id AS message_quoted_key_id
FROM message
LEFT JOIN message_media ON message._id = message_media.message_row_id
LEFT JOIN message_quoted ON message._id = message_quoted.message_row_id
WHERE message.chat_row_id = {chat_id}
ORDER BY message.timestamp ASC
"""
return self.msgstore_cursor.execute(sql_query).fetchall()
================================================
FILE: decryption/__init__.py
================================================
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Short description of this Python module.
Longer description of this module.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
"""
__author__ = "One solo developer"
__authors__ = ["One developer", "And another one", "etc"]
__contact__ = "mail@example.com"
__copyright__ = "Copyright 2023, "
__credits__ = ["One developer", "And another one", "etc"]
__date__ = "YYYY/MM/DD"
__deprecated__ = False
__email__ = "mail@example.com"
__license__ = "GPLv3"
__maintainer__ = "developer"
__status__ = "Production"
__version__ = "0.0.1"
if __name__ == '__main__':
pass
================================================
FILE: decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
================================================
FILE: decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/README.md
================================================
# WhatsApp Crypt14-15 Backup Decrypter
Decrypts WhatsApp .crypt12, .crypt14 and .crypt15 files, **given the key file** or the 64-characters long key.
The key file is named "key" if the backup is crypt14 or
"encrypted_backup.key" if the backup is crypt15 (encrypted E2E backups).
The output result is either a SQLite database
or a ZIP file (in case of wallpapers and stickers).
This is the only thing this script does.
Those who are looking for a complete suite for
WhatsApp forensics, check out [whapa.](https://github.com/B16f00t/whapa)
# Quickstart
Just copy-paste this block into your terminal
(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)
```
git clone https://github.com/ElDavoo/WhatsApp-Crypt14-Crypt15-Decrypter.git
cd WhatsApp-Crypt14-Crypt15-Decrypter
python -m venv venv
source venv/bin/activate
.\venv\Scripts\activate.bat
.\venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
```
## Requirements
**Remember to download the proto folder!**
Python 3.7 or more recent
pycriptodomex or pycryptodome
javaobj-py3
protobuf 3.20 or more recent
... or just install the `requirements.txt` file
Use:
```
python -m pip install -r requirements.txt
```
Or:
```
python -m pip install pycryptodomex javaobj-py3 protobuf
```
## Usage
```
usage: decrypt14_15.py [-h] [-f] [-nm] [-bs BUFFER_SIZE] [-ng] [-np]
[-ivo IV_OFFSET] [-do DATA_OFFSET] [-v]
[keyfile] [encrypted] [decrypted]
Decrypts WhatsApp backup files encrypted with crypt12, 14 or 15
positional arguments:
keyfile The WhatsApp encrypted_backup key file or the hex
encoded key. Default: encrypted_backup.key
encrypted The encrypted crypt12, 14 or 15 file. Default:
msgstore.db.crypt15
decrypted The decrypted output file. Default: msgstore.db
options:
-h, --help show this help message and exit
-f, --force Makes errors non fatal. Default: false
-nm, --no-mem Does not load files in RAM, stresses the disk more.
Default: load files into RAM
-bs BUFFER_SIZE, --buffer-size BUFFER_SIZE
How many bytes of data to process at a time. Implies
-nm. Default: 8192
-ng, --no-guess Does not try to guess the offsets, only protobuf
parsing.
-np, --no-protobuf Does not try to parse the protobuf message, only
offset guessing.
-ivo IV_OFFSET, --iv-offset IV_OFFSET
The default offset of the IV in the encrypted file.
Only relevant in offset guessing mode. Default: 8
-do DATA_OFFSET, --data-offset DATA_OFFSET
The default offset of the encrypted data in the
encrypted file. Only relevant in offset guessing mode.
Default: 122
-v, --verbose Prints all offsets and messages
```
### Examples, with output
#### Crypt15
```
python ./decrypt14_15.py ./encrypted_backup.key ./msgstore.db.crypt15 ./msgstore.db
[I] Crypt15 key loaded
[I] Database header parsed
[I] Done
```
or
```
python ./decrypt14_15.py b1ef5568c31686d3339bcae4600c56cf7f0cb1ae982157060879828325257c11 ./msgstore.db.crypt15 ./msgstore.db
[I] Crypt15 key loaded
[I] Database header parsed
[I] Done
```
#### Crypt14
```
python ./decrypt14_15.py ./key ./msgstore.db.crypt14 ./msgstore.db
[I] Crypt12/14 key loaded
[I] Database header parsed
[I] Done
```
#### Crypt12
```
python ./decrypt14_15.py ./key ./msgstore.db.crypt12 ./msgstore.db
[I] Crypt12/14 key loaded
[I] Database header parsed
[I] Done
```
## I had to use --force to decrypt
Please open an issue.
## Not working / crash / etc
Please open an issue and attach:
1) Output of the program (both with and without --force)
2) Hexdump of keyfile
3) Hexdump of first 512 bytes of encrypted DB
### I will happily accept pull requests for the currently open issues. :)
### Where do I get the key(file)?
On a rooted Android device, you can just copy
`/data/data/com.whatsapp/files/key`
(or `/data/data/com.whatsapp/files/encrypted_backup.key` if backups are crypt15).
If you enabled E2E backups, and you did not use a password
(you have a copy of the 64-digit key, for example a screenshot),
you can just transcribe and use it in lieu of the key file parameter.
**There are other ways, but it is not in the scope of this project
to tell you.
Issues asking for this will be closed as invalid.**
### Last tested version (don't expect this to be updated)
Stable:
2.22.15.74
Beta:
2.23.2.6
#### Protobuf classes generation
You can replace the provided generated protobuf classes with your own.
In order to do that, download the protoc 21.0 from
[here](https://github.com/protocolbuffers/protobuf/releases).
After that put protoc in the proto folder and run:
`./protoc *.proto --python_out=.`
**We then need to manually patch the generated classes to fix import errors.**
Open `prefix_pb2.py` and `C14_cipher_pb2.py`
Add `proto.` after any `import` keyword.
For example:
`import C14_cipher_version_pb2 as C14__cipher__version__pb2`
becomes
`import proto.C14_cipher_version_pb2 as C14__cipher__version__pb2`
---
## Donations
Thank you so much to each one of you!
- **🎉🎉🎉 [courious875](https://github.com/courious875) 🎉🎉🎉**
---
#### Credits:
Original implementation for crypt12: [TripCode](https://github.com/TripCode)
Some help at the beginning: [DjEdu28](https://github.com/DjEdu28)
Actual crypt14/15 implementation with protobuf: [ElDavoo](https://github.com/ElDavoo)
Help with crypt14/15 footer: [george-lam](https://github.com/georg-lam)
### Stargazers over time
[](https://star-history.com/#ElDavoo/WhatsApp-Crypt14-Crypt15-Decrypter&Date)
================================================
FILE: decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/SECURITY.md
================================================
# Security Policy
## Supported Versions
Latest
## Reporting a Vulnerability
Open an issue
================================================
FILE: decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/__init__.py
================================================
================================================
FILE: decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/decrypt14_15.py
================================================
#!/usr/bin/env python
"""
This script decrypts WhatsApp's DB files encrypted with Crypt12, Crypt14 or Crypt15.
"""
from __future__ import annotations
# AES import party!
# pycryptodome and PyCryptodomex's implementations of AES are the same,
# so we try to import one of these twos.
try:
# pycryptodomex
from Cryptodome.Cipher import AES
except ModuleNotFoundError:
try:
# pycryptodome
# noinspection PyUnresolvedReferences
from Crypto.Cipher import AES
if not hasattr(AES, 'MODE_GCM'):
# pycrypto
print("You installed pycrypto and not pycryptodome(x).")
print("Pycrypto is old, deprecated and not supported.")
print("Run: python -m pip uninstall pycrypto")
print("And: python -m pip install pycryptodomex")
print("Or: python -m pip install pycryptodome")
exit(1)
except ModuleNotFoundError:
# crypto (or nothing)
print("You need pycryptodome(x) to run this script")
print("python -m pip install pycryptodomex")
print("Or: python -m pip install pycryptodome")
print("You can also remove \"crypto\" if you have it installed")
print("python -m pip uninstall crypto")
exit(1)
# noinspection PyPackageRequirements
# This is from javaobj-py3
import javaobj.v2 as javaobj
# noinspection PyPackageRequirements
from google.protobuf.message import DecodeError
import collections
from hashlib import sha256, md5
import io
from re import findall
from sys import exit, maxsize
from time import sleep
from datetime import date
import argparse
import hmac
import zlib
__author__ = 'ElDavo'
__copyright__ = 'Copyright (C) 2023'
__license__ = 'GPLv3'
__status__ = 'Production'
__version__ = '6.1'
# These constants are only used by the guessing logic.
# zlib magic header is 78 01 (Low Compression).
# The first two bytes of the decrypted data should be those,
# in case of single file backup, or PK in case of multi file.
ZLIB_HEADERS = [
b'x\x01',
b'PK'
]
ZIP_HEADER = b'PK\x03\x04'
# Size of bytes to test (number chosen arbitrarily, but values less than ~310 makes test_decompression fail)
HEADER_SIZE = 384
DEFAULT_DATA_OFFSET = 122
DEFAULT_IV_OFFSET = 8
class SimpleLog:
"""Simple logger class. Supports 4 verbosity levels."""
def __init__(self, verbose: bool, force: bool):
self.verbose = verbose
self.force = force
def v(self, msg: str):
"""Will only print message if verbose mode is enabled."""
if self.verbose:
print('[V] {}'.format(msg))
@staticmethod
def i(msg: str):
"""Always prints message."""
print('[I] {}'.format(msg))
def e(self, msg: str):
"""Prints message and exit, unless force is enabled."""
print('[E] {}'.format(msg))
if not self.force:
print("To bypass checks, use the \"--force\" parameter")
exit(1)
@staticmethod
def f(msg: str):
"""Always prints message and exit."""
print('[F] {}'.format(msg))
exit(1)
def from_hex(logger, string: str) -> bytes:
"""Converts a hex string into a bytes array"""
if len(string) != 64:
logger.f("The key file specified does not exist.\n "
"If you tried to specify the key directly, note it should be "
"64 characters long and not {} characters long.".format(len(string)))
barr = None
try:
barr = bytes.fromhex(string)
except ValueError as e:
logger.f("Couldn't convert the hex string.\n "
"Exception: {}".format(e))
if len(barr) != 32:
logger.e("The key is not 32 bytes long but {} bytes long.".format(len(barr)))
return barr
def parsecmdline() -> argparse.Namespace:
"""Sets up the argument parser"""
parser = argparse.ArgumentParser(description='Decrypts WhatsApp backup files'
' encrypted with crypt12, 14 or 15')
parser.add_argument('keyfile', nargs='?', type=str, default="encrypted_backup.key",
help='The WhatsApp encrypted_backup key file or the hex encoded key. '
'Default: encrypted_backup.key')
parser.add_argument('encrypted', nargs='?', type=argparse.FileType('rb'), default="msgstore.db.crypt15",
help='The encrypted crypt12, 14 or 15 file. Default: msgstore.db.crypt15')
parser.add_argument('decrypted', nargs='?', type=argparse.FileType('wb'), default="msgstore.db",
help='The decrypted output file. Default: msgstore.db')
parser.add_argument('-f', '--force', action='store_true',
help='Makes errors non fatal. Default: false')
parser.add_argument('-nm', '--no-mem', action='store_true',
help='Does not load files in RAM, stresses the disk more. '
'Default: load files into RAM')
parser.add_argument('-bs', '--buffer-size', type=int, help='How many bytes of data to process at a time. '
'Implies -nm. Default: {}'.format(io.DEFAULT_BUFFER_SIZE))
parser.add_argument('-ng', '--no-guess', action='store_true',
help='Does not try to guess the offsets, only protobuf parsing.')
parser.add_argument('-np', '--no-protobuf', action='store_true',
help='Does not try to parse the protobuf message, only offset guessing.')
parser.add_argument('-ivo', '--iv-offset', type=int, default=DEFAULT_IV_OFFSET,
help='The default offset of the IV in the encrypted file. '
'Only relevant in offset guessing mode. '
'Default: {}'.format(DEFAULT_IV_OFFSET))
parser.add_argument('-do', '--data-offset', type=int, default=DEFAULT_DATA_OFFSET,
help='The default offset of the encrypted data in the encrypted file. '
'Only relevant in offset guessing mode. '
'Default: {}'.format(DEFAULT_DATA_OFFSET))
parser.add_argument('-v', '--verbose', action='store_true', help='Prints all offsets and messages')
return parser.parse_args()
class Key:
""" This class represents a key used to decrypt the DB.
Only the key is mandatory. The other parameters are optional, and if they are not None,
means that the key type is crypt14."""
# These constants are only used with crypt12/14 keys.
SUPPORTED_CIPHER_VERSION = b'\x00\x01'
SUPPORTED_KEY_VERSIONS = [b'\x01', b'\x02', b'\x03']
# This constant is only used with crypt15 keys.
BACKUP_ENCRYPTION = b'backup encryption\x01'
def is_crypt15(self):
"""Returns True if the key is crypt15, False if it is crypt12/14"""
return self.key_version is None
def __str__(self):
"""Returns a string representation of the key"""
try:
string: str = "Key("
if self.key is not None:
string += "key: {}".format(self.key.hex())
if self.serversalt is not None:
string += " , serversalt: {}".format(self.serversalt.hex())
if self.googleid is not None:
string += " , googleid: {}".format(self.googleid.hex())
if self.key_version is not None:
string += " , key_version: {}".format(self.key_version.hex())
if self.cipher_version is not None:
string += " , cipher_version: {}".format(self.cipher_version.hex())
return string + ")"
except Exception as e:
return "Exception printing key: {}".format(e)
def __init__(self, logger, key_file_name):
"""Deserializes a key file into a byte array."""
self.key = None
self.serversalt = None
self.googleid = None
self.key_version = None
self.cipher_version = None
keyfile: bytes = b''
logger.v("Reading keyfile...")
# Try to open the keyfile.
try:
key_file_stream = open(key_file_name, 'rb')
try:
# Deserialize the byte object written in the file
jarr: javaobj.beans.JavaArray = javaobj.load(key_file_stream).data
# Convert from a list of Int8 to a byte array
keyfile: bytes = javaintlist2bytes(jarr)
except (ValueError, RuntimeError) as e:
logger.f("The keyfile is not a valid Java object: {}".format(e))
except OSError:
# Try to see if it is a hex-encoded key.
keyfile = from_hex(logger, key_file_name)
# We guess the key type from its length
if len(keyfile) == 131:
self.load_crypt14(logger, keyfile=keyfile)
elif len(keyfile) == 32:
self.load_crypt15(logger, keyfile=keyfile)
else:
logger.f("Unrecognized key file format.")
def load_crypt14(self, logger, keyfile: bytes):
"""Extracts the fields from a crypt14 loaded key file."""
# key file format and encoding explanation:
# The key file is actually a serialized byte[] object.
# After deserialization, we will have a byte[] object that we have to split in:
# 1) The cipher version (2 bytes). Known values are 0x0000 and 0x0001. So far we only support the latter.
# SUPPORTED_CIPHER_VERSION = b'\x00\x01'
# 2) The key version (1 byte). All the known versions are supported.
# SUPPORTED_KEY_VERSIONS = [b'\x01', b'\x02', b'\x03']
# Looks like nothing actually changes between the versions.
# 3) Server salt (32 bytes)
# 4) googleIdSalt (unused?) (16 bytes)
# 5) hashedGoogleID (The SHA-256 hash of googleIdSalt) (32 bytes)
# 6) encryption IV (zeroed out, as it is read from the database) (16 bytes)
# 7) cipherKey (The actual AES-256 decryption key) (32 bytes)
# Check if the keyfile has a supported cipher version
self.cipher_version = keyfile[:len(self.SUPPORTED_CIPHER_VERSION)]
if self.SUPPORTED_CIPHER_VERSION != self.cipher_version:
logger.e("Invalid keyfile: Unsupported cipher version {}"
.format(keyfile[:len(self.SUPPORTED_CIPHER_VERSION)].hex()))
index = len(self.SUPPORTED_CIPHER_VERSION)
# Check if the keyfile has a supported key version
version_supported = False
for v in self.SUPPORTED_KEY_VERSIONS:
if v == keyfile[index:index + len(self.SUPPORTED_KEY_VERSIONS[0])]:
version_supported = True
self.key_version = v
break
if not version_supported:
logger.e('Invalid keyfile: Unsupported key version {}'
.format(keyfile[index:index + len(self.SUPPORTED_KEY_VERSIONS[0])].hex()))
self.serversalt = keyfile[3:35]
# Check the SHA-256 of the salt
self.googleid = keyfile[35:51]
expected_digest = sha256(self.googleid).digest()
actual_digest = keyfile[51:83]
if expected_digest != actual_digest:
logger.e("Invalid keyfile: Invalid SHA-256 of salt.\n "
"Expected: {}\n Got:{}".format(expected_digest, actual_digest))
padding = keyfile[83:99]
# Check if IV is made of zeroes
for byte in padding:
if byte:
logger.e("Invalid keyfile: IV is not zeroed out but is: {}".format(padding.hex()))
break
self.key = keyfile[99:]
logger.i("Crypt12/14 key loaded")
def load_crypt15(self, logger, keyfile: bytes):
"""Extracts the key from a loaded crypt15 key file."""
# encrypted_backup.key file format and encoding explanation:
# The E2E key file is actually a serialized byte[] object.
# After deserialization, we will have the root key (32 bytes).
# The root key is further encoded with three different strings, depending on what you want to do.
# These three ways are "backup encryption";
# "metadata encryption" and "metadata authentication", for Google Drive E2E encrypted metadata.
# We are only interested in the local backup encryption.
# Why the \x01 at the end of the BACKUP_ENCRYPTION constant?
# Whatsapp uses a nested encryption function to encrypt many times the same data.
# The iteration counter is appended to the end of the encrypted data. However,
# since the loop is actually executed only one time, we will only have one interaction,
# and thus a \x01 at the end.
# Take a look at utils/wa_hmacsha256_loop.java that is the original code.
if len(keyfile) != 32:
logger.f("Crypt15 loader trying to load a crypt14 key")
# First do the HMACSHA256 hash of the file with an empty private key
self.key: bytes = hmac.new(b'\x00' * 32, keyfile, sha256).digest()
# Then do the HMACSHA256 using the previous result as key and ("backup encryption" + iteration count) as data
self.key = hmac.new(self.key, self.BACKUP_ENCRYPTION, sha256).digest()
logger.i("Crypt15 / Raw key loaded")
def oscillate(n: int, n_min: int, n_max: int) -> collections.Iterable:
"""Yields n, n-1, n+1, n-2, n+2..., with constraints:
- n is in [min, max]
- n is never negative
Reverts to range() when n touches min or max. Example:
oscillate(8, 2, 10) => 8, 7, 9, 6, 10, 5, 4, 3, 2
"""
if n_min < 0:
n_min = 0
i = n
c = 1
# First phase (n, n-1, n+1...)
while True:
if i == n_max:
break
yield i
i = i - c
c = c + 1
if i == 0 or i == n_min:
break
yield i
i = i + c
c = c + 1
# Second phase (range of remaining numbers)
# n != i/2 fixes a bug where we would yield min and max two times if n == (max-min)/2
if i == n_min and n != i / 2:
yield i
i = i + c
for j in range(i, n_max + 1):
yield j
if i == n_max and n != i / 2:
yield n_max
i = i - c
for j in range(i, n_min - 1, -1):
yield j
def test_decompression(logger, test_data: bytes) -> bool:
"""Returns true if the SQLite header is valid.
It is assumed that the data are valid.
(If it is valid, it also means the decryption and decompression were successful.)"""
# If we get a ZIP file header, return true
if test_data[:4] == ZIP_HEADER:
return True
try:
zlib_obj = zlib.decompressobj().decompress(test_data)
# These two errors should never happen
if len(zlib_obj) < 16:
logger.e("Test decompression: chunk too small")
return False
if zlib_obj[:15].decode('ascii') != 'SQLite format 3':
logger.e("Test decompression: Decryption and decompression ok but not a valid SQLite database")
return logger.force
else:
return True
except zlib.error:
return False
def find_data_offset(logger, header: bytes, iv_offset: int, key: bytes, starting_data_offset: int) -> int:
"""Tries to find the offset in which the encrypted data starts.
Returns the offset or -1 if the offset is not found.
Only works with ZLIB stream, not with ZIP file."""
iv = header[iv_offset:iv_offset + 16]
# oscillate ensures we try the closest values to the default value first.
for i in oscillate(n=starting_data_offset, n_min=iv_offset + len(iv), n_max=HEADER_SIZE - 128):
cipher = AES.new(key, AES.MODE_GCM, iv)
# We only decrypt the first two bytes.
test_bytes = cipher.decrypt(header[i:i + 2])
for zheader in ZLIB_HEADERS:
if test_bytes == zheader:
# We found a match, but this might also happen by chance.
# Let's run another test by decrypting some hundreds of bytes.
# We need to reinitialize the cipher everytime as it has an internal status.
cipher = AES.new(key, AES.MODE_GCM, iv)
decrypted = cipher.decrypt(header[i:])
if test_decompression(logger, decrypted):
return i
return -1
def guess_offsets(logger, key: bytes, file_hash: _Hash, encrypted: BufferedReader, def_iv_offset: int,
def_data_offset: int):
"""Gets the IV, shifts the stream to the beginning of the encrypted data and returns the cipher.
It does so by guessing the offset."""
# Assign variables to suppress warnings
db_header, data_offset, iv_offset = None, None, None
# Restart the file stream
encrypted.seek(0)
db_header = encrypted.read(HEADER_SIZE)
if len(db_header) < HEADER_SIZE:
logger.f("The encrypted database is too small.\n "
"Did you swap the keyfile and the encrypted database file by mistake?")
raise Exception("The encrypted database is too small.\n "
"Did you swap the keyfile and the encrypted database file by mistake?")
try:
if db_header[:15].decode('ascii') == 'SQLite format 3':
logger.e("The database file is not encrypted.\n "
"Did you swap the input and the output files by mistake?")
raise Exception("The database file is not encrypted.\n "
"Did you swap the input and the output files by mistake?")
except ValueError:
pass
# Finding WhatsApp's version is nice
version = findall(b"\\d(?:\\.\\d{1,3}){3}", db_header)
if len(version) != 1:
logger.i('WhatsApp version not found (Crypt12?)')
else:
logger.v("WhatsApp version: {}".format(version[0].decode('ascii')))
# Determine IV offset and data offset.
for iv_offset in oscillate(n=def_iv_offset, n_min=0, n_max=HEADER_SIZE - 128):
data_offset = find_data_offset(logger, db_header, iv_offset, key, def_data_offset)
if data_offset != -1:
logger.i("Offsets guessed (IV: {}, data: {}).".format(iv_offset, data_offset))
if iv_offset != def_iv_offset or data_offset != def_data_offset:
logger.i("Next time, use -ivo {} -do {} for guess-free decryption".format(iv_offset, data_offset))
break
if data_offset == -1:
return None
iv = db_header[iv_offset:iv_offset + 16]
encrypted.seek(data_offset)
file_hash.update(db_header[:data_offset])
return AES.new(key, AES.MODE_GCM, iv)
def javaintlist2bytes(barr: javaobj.beans.JavaArray) -> bytes:
"""Converts a javaobj bytearray which somehow became a list of signed integers back to a Python byte array"""
out: bytes = b''
for i in barr:
out += i.to_bytes(1, byteorder='big', signed=True)
return out
def check_crypt12(logger, file_hash, key, encrypted):
"""Checks if the file is a Crypt12 file.
Returns the cipher if it is, None otherwise."""
"""
The crypt12 file format is similar to the crypt14 file format.
It is a "raw" header, which means it's not a protobuf message,
nor a serialized java object.
Structure:
Cipher version (2 bytes)
Key version (1 byte)
Server salt (32 bytes)
Google ID (16 bytes)
IV (16 bytes)
( so we finally understood why the IV is at offset 51 ... )
"""
def quit_12():
encrypted.seek(0)
logger.v("Not a Crypt12 file, or corrupted")
raise ValueError
if key.is_crypt15():
quit_12()
# We can read and discard the bytes, because the information
# are already in the keyfile.
test_bytes = encrypted.read(2)
if test_bytes != key.cipher_version:
quit_12()
file_hash.update(test_bytes)
test_bytes = encrypted.read(1)
if test_bytes != key.key_version:
quit_12()
file_hash.update(test_bytes)
test_bytes = encrypted.read(32)
if test_bytes != key.serversalt:
quit_12()
file_hash.update(test_bytes)
test_bytes = encrypted.read(16)
if test_bytes != key.googleid:
quit_12()
file_hash.update(test_bytes)
iv = encrypted.read(16)
file_hash.update(iv)
# We are done here
logger.i("Database header parsed")
return AES.new(key.key, AES.MODE_GCM, iv)
def parse_protobuf(logger, file_hash: _Hash, key: Key, encrypted):
"""Parses the database header, gets the IV,
shifts the stream to the beginning of the encrypted data and returns the cipher.
It does so by parsing the protobuf message."""
try:
import decryption.dbs.WhatsAppCrypt14Crypt15Decrypter.proto.prefix_pb2 as prefix
import decryption.dbs.WhatsAppCrypt14Crypt15Decrypter.proto.key_type_pb2 as key_type
except ImportError as e:
logger.e("Could not import the proto classes: {}".format(e))
if str(e).startswith("cannot import name 'builder' from 'google.protobuf.internal'"):
logger.e("You need to upgrade the protobuf library to at least 3.20.0.\n"
" python -m pip install --upgrade protobuf")
elif str(e).startswith("no module named"):
logger.e("Please download them and put them in the \"proto\" sub folder.")
return None
except AttributeError as e:
logger.e("Could not import the proto classes: {}\n ".format(e) +
"Your protobuf library is probably too old.\n "
"Please upgrade to at least version 3.20.0 , by running:\n "
"python -m pip install --upgrade protobuf")
return None
p = prefix.prefix()
logger.v("Parsing database header...")
try:
# The first byte is the size of the upcoming protobuf message
protobuf_size = encrypted.read(1)
file_hash.update(protobuf_size)
protobuf_size = int.from_bytes(protobuf_size, byteorder='big')
# It is my guess this is the backup type.
# Looks like it is 1 for msgstore and 8 for other types.
backup_type_raw = encrypted.read(1)
backup_type = int.from_bytes(backup_type_raw, byteorder='big')
if backup_type != 1:
if backup_type == 8:
logger.v("Not a (recent) msgstore database")
# For some reason we need to go backward one byte
encrypted.seek(-1, 1)
else:
logger.e("Unexpected backup type: {}".format(backup_type))
else:
file_hash.update(backup_type_raw)
try:
protobuf_raw = encrypted.read(protobuf_size)
file_hash.update(protobuf_raw)
if p.ParseFromString(protobuf_raw) != protobuf_size:
logger.e("Protobuf message not fully read. Please report a bug.")
else:
# Checking and printing WA version and phone number
version = findall(r"\d(?:\.\d{1,3}){3}", p.info.whatsapp_version)
if len(version) != 1:
logger.e('WhatsApp version not found')
else:
logger.v("WhatsApp version: {}".format(version[0]))
if len(p.info.substringedUserJid) != 2:
logger.e("The phone number end is not 2 characters long")
logger.v("Your phone number ends with {}".format(p.info.substringedUserJid))
if len(p.c15_iv.IV) != 0:
# DB Header is crypt15
if not key.is_crypt15():
logger.e("You are using a crypt14 key file with a crypt15 backup.")
if len(p.c15_iv.IV) != 16:
logger.e("IV is not 16 bytes long but is {} bytes long".format(len(p.c15_iv.IV)))
iv = p.c15_iv.IV
elif len(p.c14_cipher.IV) != 0:
# DB Header is crypt14
if key.is_crypt15():
logger.f("You are using a crypt15 key file with a crypt14 backup.")
# if key.cipher_version != p.c14_cipher.version.cipher_version:
# logger.e("Cipher version mismatch: {} != {}"
# .format(key.cipher_version, p.c14_cipher.cipher_version))
# Fix bytes to string encoding
key.key_version = (key.key_version[0] + 48).to_bytes(1, byteorder='big')
if key.key_version != p.c14_cipher.key_version:
if key.key_version > p.c14_cipher.key_version:
logger.e("Key version mismatch: {} != {} .\n "
.format(key.key_version, p.c14_cipher.key_version) +
"Your backup is too old for this key file.\n " +
"Please try using a newer backup.")
elif key.key_version < p.c14_cipher.key_version:
logger.e("Key version mismatch: {} != {} .\n "
.format(key.key_version, p.c14_cipher.key_version) +
"Your backup is too new for this key file.\n " +
"Please try using an older backup, or getting the new key.")
else:
logger.e("Key version mismatch: {} != {} (?)"
.format(key.key_version, p.c14_cipher.key_version))
if key.serversalt != p.c14_cipher.server_salt:
logger.e("Server salt mismatch: {} != {}".format(key.serversalt, p.c14_cipher.server_salt))
if key.googleid != p.c14_cipher.google_id:
logger.e("Google ID mismatch: {} != {}".format(key.googleid, p.c14_cipher.google_id))
if len(p.c14_cipher.IV) != 16:
logger.e("IV is not 16 bytes long but is {} bytes long".format(len(p.c14_cipher.IV)))
iv = p.c14_cipher.IV
else:
logger.e("Could not parse the IV from the protobuf message. Please report a bug.")
gitextract_0l64ab7n/ ├── .gitignore ├── Controller/ │ ├── chat_screen.py │ ├── login_screen.py │ ├── main_screen.py │ └── template_screen.py ├── LICENSE ├── Model/ │ ├── __init__.py │ ├── base_model.py │ ├── chat_screen.py │ ├── login_screen.py │ ├── main_screen.py │ └── template_screen.py ├── README.md ├── Utility/ │ ├── Utils.py │ ├── __init__.py │ └── observer.py ├── View/ │ ├── ChatScreen/ │ │ ├── __init__.py │ │ ├── chat_screen.kv │ │ └── chat_screen.py │ ├── LoginScreen/ │ │ ├── __init__.py │ │ ├── about.kv │ │ ├── login_screen.kv │ │ ├── login_screen.py │ │ └── settings.kv │ ├── MainScreen/ │ │ ├── __init__.py │ │ ├── main_screen.kv │ │ └── main_screen.py │ ├── base_screen.py │ ├── components/ │ │ ├── MLabel.kv │ │ ├── __init__.py │ │ ├── attachment.kv │ │ ├── avatar.kv │ │ ├── call_list_item.kv │ │ ├── chat_list_item.kv │ │ ├── chat_message.kv │ │ ├── quote.kv │ │ └── textfield_filemanger.kv │ └── screens.py ├── about ├── assets/ │ └── fonts/ │ └── EmojiOneColor.otf ├── credits ├── dbs/ │ ├── __init__.py │ ├── abstract_db.py │ ├── v1/ │ │ ├── __init__.py │ │ └── db.py │ ├── v2/ │ │ ├── __init__.py │ │ └── db.py │ └── v3/ │ ├── __init__.py │ └── db.py ├── decryption/ │ ├── __init__.py │ └── dbs/ │ ├── WhatsAppCrypt14Crypt15Decrypter/ │ │ ├── LICENSE │ │ ├── README.md │ │ ├── SECURITY.md │ │ ├── __init__.py │ │ ├── decrypt14_15.py │ │ ├── proto/ │ │ │ ├── C14_cipher.proto │ │ │ ├── C14_cipher_pb2.py │ │ │ ├── C14_cipher_version.proto │ │ │ ├── C14_cipher_version_pb2.py │ │ │ ├── C15_IV.proto │ │ │ ├── C15_IV_pb2.py │ │ │ ├── key_type.proto │ │ │ ├── key_type_pb2.py │ │ │ ├── prefix.proto │ │ │ ├── prefix_pb2.py │ │ │ ├── version_features.proto │ │ │ └── version_features_pb2.py │ │ ├── requirements.txt │ │ └── utils/ │ │ ├── WA_HMACSHA256_Loop.java │ │ ├── hex_string_to_encrypted_backup_key.py │ │ ├── password_data_key_to_hashcat.py │ │ └── protobuf_bruteforce.py │ ├── __init__.py │ └── decrypt_db.py ├── libs/ │ └── __init__.py ├── main.py ├── pyproject.toml ├── requirements.txt └── version.py
SYMBOL INDEX (201 symbols across 26 files)
FILE: Controller/chat_screen.py
class ChatScreenController (line 14) | class ChatScreenController:
method __init__ (line 15) | def __init__(self, model):
method get_view (line 20) | def get_view(self) -> View.ChatScreen.chat_screen:
method task_finished (line 24) | def task_finished(self, chat_messages):
method get_chat (line 29) | def get_chat(self, chat_id):
method on_enter (line 33) | def on_enter(self, *args):
method previous_screen (line 40) | def previous_screen(self):
FILE: Controller/login_screen.py
class LoginScreenController (line 22) | class LoginScreenController:
method __init__ (line 24) | def __init__(self, model):
method get_view (line 29) | def get_view(self) -> View.LoginScreen.login_screen:
method check_files (line 32) | def check_files(self):
method login (line 59) | def login(self):
method show_decryption_error (line 78) | def show_decryption_error(self, error):
method show_warning (line 90) | def show_warning(self, warning):
method show_decryption_success (line 94) | def show_decryption_success(self, path):
method update_dialog (line 98) | def update_dialog(self, msg):
method decrypt_dbs (line 102) | def decrypt_dbs(self, key):
method decrypt_db (line 127) | def decrypt_db(self, key, enc_db, dec_db):
method on_tap_button_login (line 134) | def on_tap_button_login(self) -> NoReturn:
FILE: Controller/main_screen.py
class MainScreenController (line 12) | class MainScreenController:
method __init__ (line 20) | def __init__(self, model):
method get_view (line 24) | def get_view(self) -> View.MainScreen.main_screen:
method on_tap_button_login (line 27) | def on_tap_button_login(self) -> NoReturn:
method on_enter (line 31) | def on_enter(self, *args):
method show_chat_screen (line 41) | def show_chat_screen(self, chat_id, user, jid):
method clear_session (line 47) | def clear_session(self):
method log_out (line 53) | def log_out(self, *args):
FILE: Controller/template_screen.py
class TemplateScreenController (line 14) | class TemplateScreenController:
method __init__ (line 22) | def __init__(self, model):
method get_view (line 27) | def get_view(self) -> View.TemplateScreen.template_screen:
method on_tap_button_login (line 30) | def on_tap_button_login(self) -> NoReturn:
FILE: Model/base_model.py
class BaseScreenModel (line 10) | class BaseScreenModel:
method add_observer (line 15) | def add_observer(self, observer) -> None:
method remove_observer (line 18) | def remove_observer(self, observer) -> None:
method notify_observers (line 21) | def notify_observers(self, name_screen: str) -> None:
FILE: Model/chat_screen.py
class ChatScreenModel (line 5) | class ChatScreenModel(BaseScreenModel):
method __init__ (line 10) | def __init__(self, base):
method get_chat (line 13) | def get_chat(self, chat_id):
FILE: Model/login_screen.py
class LoginScreenModel (line 4) | class LoginScreenModel(BaseScreenModel):
method __init__ (line 5) | def __init__(self, base):
FILE: Model/main_screen.py
class MainScreenModel (line 5) | class MainScreenModel(BaseScreenModel):
method __init__ (line 11) | def __init__(self, base):
method set_base (line 14) | def set_base(self, base):
method get_contact_chats (line 17) | def get_contact_chats(self):
method get_group_chats (line 32) | def get_group_chats(self):
method get_calls (line 36) | def get_calls(self, how_many=None):
method get_status (line 50) | def get_status(self, jid):
FILE: Model/template_screen.py
class TemplateScreenModel (line 4) | class TemplateScreenModel(BaseScreenModel):
method __init__ (line 9) | def __init__(self, base):
FILE: Utility/Utils.py
function fix_emojis (line 22) | def fix_emojis(text, font):
function strip_quotes (line 29) | def strip_quotes(path):
function check_path (line 34) | def check_path(path=None):
FILE: Utility/observer.py
class Observer (line 11) | class Observer:
method model_is_changed (line 14) | def model_is_changed(self):
FILE: View/ChatScreen/chat_screen.py
class RV (line 26) | class RV(RecycleView):
method __init__ (line 27) | def __init__(self, **kwargs):
class Attachment (line 31) | class Attachment(ButtonBehavior, RectangularRippleBehavior, CommonElevat...
method __init__ (line 32) | def __init__(self, **kwargs):
class Quote (line 36) | class Quote(MLabel):
method __init__ (line 37) | def __init__(self, **kwargs):
class ChatMessage (line 41) | class ChatMessage(RecycleDataViewBehavior, MDBoxLayout):
method dialog_dismiss (line 53) | def dialog_dismiss(self):
method hide_dialog (line 56) | def hide_dialog(self):
method show_dialog (line 59) | def show_dialog(self, msg, title=None, auto_dismiss=True) -> NoReturn:
method open_media (line 72) | def open_media(self, file_path):
method get_msg_widget (line 87) | def get_msg_widget(self):
method refresh_view_attrs (line 90) | def refresh_view_attrs(self, rv, index, data):
method refresh_view_layout (line 105) | def refresh_view_layout(self, rv, index, layout, viewport):
class ChatScreenView (line 109) | class ChatScreenView(BaseScreenView):
method __init__ (line 116) | def __init__(self, **kw):
method dialog_dismiss (line 123) | def dialog_dismiss(self):
method hide_dialog (line 126) | def hide_dialog(self):
method show_dialog (line 129) | def show_dialog(self, msg, title=None, auto_dismiss=True) -> NoReturn:
method show_chat_messages (line 141) | def show_chat_messages(self, chat_messages):
method scroll_to_bottom (line 147) | def scroll_to_bottom(self):
method model_is_changed (line 150) | def model_is_changed(self) -> None:
FILE: View/LoginScreen/login_screen.py
class TextFieldFileManager (line 28) | class TextFieldFileManager(MDRelativeLayout):
method __init__ (line 33) | def __init__(self, **kwargs):
method file_manager_open (line 40) | def file_manager_open(self):
method select_path (line 44) | def select_path(self, path: str):
method on_text (line 49) | def on_text(self, instance, value):
method exit_manager (line 52) | def exit_manager(self, *args):
method events (line 56) | def events(self, instance, keyboard, keycode, text, modifiers):
method open_file_manager (line 64) | def open_file_manager(self, hint_text):
class SettingsContent (line 69) | class SettingsContent(ScrollView):
class About (line 73) | class About(BoxLayout):
method __init__ (line 78) | def __init__(self, **kwargs):
method open_link (line 91) | def open_link(self, instance, link):
class LoginScreenView (line 95) | class LoginScreenView(BaseScreenView):
method __init__ (line 97) | def __init__(self, **kw):
method set_item (line 150) | def set_item(self, text__item):
method dialog_dismiss (line 155) | def dialog_dismiss(self):
method hide_dialog (line 158) | def hide_dialog(self):
method show_dialog (line 162) | def show_dialog(self, msg, title=None, auto_dismiss=False) -> NoReturn:
method on_enc_checkbox (line 176) | def on_enc_checkbox(self, state, *args):
method open_settings (line 182) | def open_settings(self):
method settings_cancel (line 186) | def settings_cancel(self, *args):
method settings_save (line 189) | def settings_save(self, *args):
method show_toast (line 227) | def show_toast(self, msg):
method open_about (line 230) | def open_about(self):
method open_github_page (line 233) | def open_github_page(self):
method model_is_changed (line 236) | def model_is_changed(self) -> None:
method on_kv_post (line 243) | def on_kv_post(self, base_widget):
method save_fields (line 250) | def save_fields(self, *args):
method on_pre_enter (line 260) | def on_pre_enter(self, *args):
FILE: View/MainScreen/main_screen.py
class Tab (line 21) | class Tab(MDFloatLayout, MDTabsBase):
class MLabel (line 25) | class MLabel(MDLabel):
method __init__ (line 26) | def __init__(self, **kwargs):
class ChatListItem (line 30) | class ChatListItem(RecycleDataViewBehavior, MDCard):
class CallListItem (line 39) | class CallListItem(RecycleDataViewBehavior, MDCard):
class MainScreenView (line 50) | class MainScreenView(BaseScreenView):
method __init__ (line 52) | def __init__(self, **kw):
method show_dialog_wait (line 56) | def show_dialog_wait(self) -> NoReturn:
method model_is_changed (line 62) | def model_is_changed(self) -> None:
method show_chats_list (line 70) | def show_chats_list(self, contact_chats):
method build_group_chat_list (line 80) | def build_group_chat_list(self, group_chats):
method build_calls_list (line 89) | def build_calls_list(self, calls):
FILE: View/base_screen.py
class BaseScreenView (line 9) | class BaseScreenView(MDScreen, Observer):
method __init__ (line 39) | def __init__(self, **kw):
FILE: dbs/abstract_db.py
class AbstractDatabase (line 16) | class AbstractDatabase(ABC):
method __init__ (line 18) | def __init__(self, msgstore, wa=None, schema=None):
method fetch_contact_chats (line 35) | def fetch_contact_chats(self):
method fetch_group_chats (line 57) | def fetch_group_chats(self):
method fetch_calls (line 79) | def fetch_calls(self, how_many=None):
method fetch_chat (line 105) | def fetch_chat(self, chat_id):
method load_contacts (line 137) | def load_contacts(self, wa_cursor):
method check_database_schema (line 154) | def check_database_schema(self):
FILE: dbs/v1/db.py
class Database (line 7) | class Database(AbstractDatabase):
method __init__ (line 9) | def __init__(self, msgstore, wa):
method fetch_contact_chats (line 50) | def fetch_contact_chats(self):
method fetch_group_chats (line 71) | def fetch_group_chats(self):
method fetch_calls (line 89) | def fetch_calls(self, how_many=None):
method fetch_chat (line 107) | def fetch_chat(self, chat_id):
FILE: dbs/v2/db.py
class Database (line 6) | class Database(AbstractDatabase):
method __init__ (line 8) | def __init__(self, msgstore, wa):
method fetch_contact_chats (line 50) | def fetch_contact_chats(self):
method fetch_group_chats (line 66) | def fetch_group_chats(self):
method fetch_calls (line 83) | def fetch_calls(self, how_many=None):
method fetch_chat (line 102) | def fetch_chat(self, chat_id):
FILE: dbs/v3/db.py
class Database (line 7) | class Database(AbstractDatabase):
method __init__ (line 9) | def __init__(self, msgstore, wa):
method fetch_contact_chats (line 79) | def fetch_contact_chats(self):
method fetch_group_chats (line 95) | def fetch_group_chats(self):
method fetch_calls (line 111) | def fetch_calls(self, how_many=None):
method fetch_chat (line 129) | def fetch_chat(self, chat_id):
FILE: decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/decrypt14_15.py
class SimpleLog (line 79) | class SimpleLog:
method __init__ (line 82) | def __init__(self, verbose: bool, force: bool):
method v (line 86) | def v(self, msg: str):
method i (line 92) | def i(msg: str):
method e (line 96) | def e(self, msg: str):
method f (line 104) | def f(msg: str):
function from_hex (line 110) | def from_hex(logger, string: str) -> bytes:
function parsecmdline (line 128) | def parsecmdline() -> argparse.Namespace:
class Key (line 163) | class Key:
method is_crypt15 (line 174) | def is_crypt15(self):
method __str__ (line 177) | def __str__(self):
method __init__ (line 195) | def __init__(self, logger, key_file_name):
method load_crypt14 (line 231) | def load_crypt14(self, logger, keyfile: bytes):
method load_crypt15 (line 288) | def load_crypt15(self, logger, keyfile: bytes):
function oscillate (line 317) | def oscillate(n: int, n_min: int, n_max: int) -> collections.Iterable:
function test_decompression (line 363) | def test_decompression(logger, test_data: bytes) -> bool:
function find_data_offset (line 387) | def find_data_offset(logger, header: bytes, iv_offset: int, key: bytes, ...
function guess_offsets (line 415) | def guess_offsets(logger, key: bytes, file_hash: _Hash, encrypted: Buffe...
function javaintlist2bytes (line 469) | def javaintlist2bytes(barr: javaobj.beans.JavaArray) -> bytes:
function check_crypt12 (line 476) | def check_crypt12(logger, file_hash, key, encrypted):
function parse_protobuf (line 534) | def parse_protobuf(logger, file_hash: _Hash, key: Key, encrypted):
function decrypt (line 661) | def decrypt(logger, file_hash: _Hash, cipher, encrypted, decrypted, buff...
function main (line 878) | def main():
FILE: decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/utils/WA_HMACSHA256_Loop.java
class WA_HMACSHA256_Loop (line 13) | public class WA_HMACSHA256_Loop {
method nestedHMACSHA256NoKey (line 15) | public static byte[] nestedHMACSHA256NoKey(byte[] first_iteration_data...
method nestedHmacSHA256 (line 18) | public static byte[] nestedHmacSHA256(byte[] first_iteration_data, byt...
FILE: decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/utils/hex_string_to_encrypted_backup_key.py
class Log (line 19) | class Log:
method i (line 23) | def i(msg: str):
method f (line 28) | def f(msg: str):
function from_hex (line 34) | def from_hex(string: str) -> bytes:
function parsecmdline (line 50) | def parsecmdline() -> argparse.Namespace:
function create_class_description (line 59) | def create_class_description() -> javaobj.JavaClass:
function serialize (line 68) | def serialize(j_key: javaobj.JavaByteArray, o_stream):
function create_encrypted_backup_key_file (line 82) | def create_encrypted_backup_key_file(ikey: str, output):
function main (line 92) | def main():
FILE: decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/utils/password_data_key_to_hashcat.py
class Log (line 26) | class Log:
method i (line 30) | def i(msg: str):
method f (line 35) | def f(msg: str):
function parsecmdline (line 41) | def parsecmdline() -> argparse.Namespace:
function barrtoint (line 49) | def barrtoint(barr: javaobj.beans.BlockData) -> int:
function javaintlist2bytes (line 54) | def javaintlist2bytes(barr: javaobj.beans.JavaArray) -> bytes:
function read_password_data_key (line 62) | def read_password_data_key(passworddatakeyfilestream: argparse.FileType(...
function main (line 99) | def main():
FILE: decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/utils/protobuf_bruteforce.py
function parsecmdline (line 15) | def parsecmdline() -> argparse.Namespace:
function load_file (line 27) | def load_file(file_name: str, byte_range=0, reverse=False) -> bytes:
function get_truncated_stream (line 57) | def get_truncated_stream(content: bytes, start: int, end: int) -> BytesIO:
function main (line 62) | def main():
function protoparse (line 89) | def protoparse(stream):
class Message (line 93) | class Message:
function search (line 99) | def search(whole_file: bytes, keep_going: bool, offset=0):
FILE: decryption/dbs/decrypt_db.py
function decrypt_db (line 21) | def decrypt_db(keyfile: str, encrypted, decrypted, verbose=True, force=T...
FILE: main.py
class whatsappMsgstoreViewer (line 55) | class whatsappMsgstoreViewer(MDApp):
method __init__ (line 60) | def __init__(self, **kwargs):
method load_db (line 100) | def load_db(self):
method build_app (line 118) | def build_app(self) -> MDScreenManager:
function run (line 153) | def run():
Condensed preview — 79 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (257K chars).
[
{
"path": ".gitignore",
"chars": 1816,
"preview": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packagi"
},
{
"path": "Controller/chat_screen.py",
"chars": 1455,
"preview": "import importlib\nimport multitasking\nfrom kivy.clock import mainthread\n\nimport Model.chat_screen\nimport View.ChatScreen."
},
{
"path": "Controller/login_screen.py",
"chars": 6466,
"preview": "import importlib\nimport os.path\nimport traceback\nfrom typing import NoReturn\n\nimport multitasking\n\nfrom Utility.Utils im"
},
{
"path": "Controller/main_screen.py",
"chars": 2149,
"preview": "import importlib\nfrom typing import NoReturn\nimport View.MainScreen.main_screen\nimport View.screens\n\n# We have to manual"
},
{
"path": "Controller/template_screen.py",
"chars": 1213,
"preview": "import importlib\nfrom typing import NoReturn\n\nimport View.TemplateScreen.template_screen\n\n# We have to manually reload t"
},
{
"path": "LICENSE",
"chars": 35149,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "Model/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "Model/base_model.py",
"chars": 1254,
"preview": "# The model implements the observer pattern. This means that the class must\n# support adding, removing, and alerting obs"
},
{
"path": "Model/chat_screen.py",
"chars": 396,
"preview": "from Model.base_model import BaseScreenModel\nfrom dbs.abstract_db import AbstractDatabase\n\n\nclass ChatScreenModel(BaseSc"
},
{
"path": "Model/login_screen.py",
"chars": 172,
"preview": "from Model.base_model import BaseScreenModel\n\n\nclass LoginScreenModel(BaseScreenModel):\n def __init__(self, base):\n "
},
{
"path": "Model/main_screen.py",
"chars": 1974,
"preview": "from Model.base_model import BaseScreenModel\nfrom dbs.abstract_db import AbstractDatabase\n\n\nclass MainScreenModel(BaseSc"
},
{
"path": "Model/template_screen.py",
"chars": 257,
"preview": "from Model.base_model import BaseScreenModel\n\n\nclass TemplateScreenModel(BaseScreenModel):\n \"\"\"\n Implements the lo"
},
{
"path": "README.md",
"chars": 4081,
"preview": "# whatsapp Msgstore Viewer\nFree, open source and cross-platform app to decrypt, read and view the Whatsapp `msgstore.db`"
},
{
"path": "Utility/Utils.py",
"chars": 1159,
"preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nHelper functions\n\nThis program is free software: you can redistribute"
},
{
"path": "Utility/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "Utility/observer.py",
"chars": 725,
"preview": "\n# Of course, \"very flexible Python\" allows you to do without an abstract\n# superclass at all or use the clever exceptio"
},
{
"path": "View/ChatScreen/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "View/ChatScreen/chat_screen.kv",
"chars": 2815,
"preview": "#:import hex kivy.utils.get_color_from_hex\n\n<ChatScreenView>:\n FitImage:\n source: \"assets/images/bg.png\"\n "
},
{
"path": "View/ChatScreen/chat_screen.py",
"chars": 5588,
"preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nChat Screen\n\"\"\"\n\nimport os\nfrom typing import NoReturn\nfrom PIL impor"
},
{
"path": "View/LoginScreen/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "View/LoginScreen/about.kv",
"chars": 1446,
"preview": "#:import hex kivy.utils.get_color_from_hex\n\n<About>\n size_hint_y: None\n height: \"400dp\"\n MDTabs:\n tab_in"
},
{
"path": "View/LoginScreen/login_screen.kv",
"chars": 4020,
"preview": "<LoginScreenView>\n FitImage:\n source: \"assets/images/bg.png\"\n MDBoxLayout:\n orientation: \"vertical\"\n"
},
{
"path": "View/LoginScreen/login_screen.py",
"chars": 9322,
"preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nLogin screen\n\"\"\"\n\nimport os\nimport webbrowser\nfrom typing import NoRe"
},
{
"path": "View/LoginScreen/settings.kv",
"chars": 1169,
"preview": "<SettingsContent>:\n size_hint_y: None\n height: \"300dp\"\n bar_width: 10\n scroll_type: ['content', 'bars']\n "
},
{
"path": "View/MainScreen/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "View/MainScreen/main_screen.kv",
"chars": 2179,
"preview": "<MainScreenView>\n MDBoxLayout:\n orientation: \"vertical\"\n MDTopAppBar:\n id: logoToolBar\n "
},
{
"path": "View/MainScreen/main_screen.py",
"chars": 3183,
"preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nMain Screen\n\"\"\"\n\nfrom typing import NoReturn\nfrom kivy.properties imp"
},
{
"path": "View/base_screen.py",
"chars": 1343,
"preview": "from kivy.properties import ObjectProperty\n\nfrom kivymd.app import MDApp\nfrom kivymd.uix.screen import MDScreen\n\nfrom Ut"
},
{
"path": "View/components/MLabel.kv",
"chars": 60,
"preview": "<MLabel>:\n markup: True\n font_name: app.general_font\n\n"
},
{
"path": "View/components/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "View/components/attachment.kv",
"chars": 52,
"preview": "<Attachment>:\n markup: True\n color: (0,0,1,1)\n"
},
{
"path": "View/components/avatar.kv",
"chars": 519,
"preview": "<Avatar@RelativeLayout>:\r\n size: (45, 45)\r\n size_hint: (None, None)\r\n source: root.source\r\n MDCard:\r\n "
},
{
"path": "View/components/call_list_item.kv",
"chars": 2359,
"preview": "<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 pa"
},
{
"path": "View/components/chat_list_item.kv",
"chars": 2035,
"preview": "<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 pa"
},
{
"path": "View/components/chat_message.kv",
"chars": 2039,
"preview": "#:import hex kivy.utils.get_color_from_hex\r\n\r\n<ChatMessage>:\r\n orientation: 'vertical'\r\n height: chat_message.heig"
},
{
"path": "View/components/quote.kv",
"chars": 172,
"preview": "<Quote>:\n markup: True\n allow_copy: True\n allow_selection: True\n valign: 'center'\n size_hint: None, None\n"
},
{
"path": "View/components/textfield_filemanger.kv",
"chars": 496,
"preview": "<TextFieldFileManager>:\n size_hint_y: None\n height: text_field.height\n\n MDTextField:\n id: text_field\n "
},
{
"path": "View/screens.py",
"chars": 761,
"preview": "# The screens dictionary contains the objects of the models and controllers\n# of the screens of the application.\nfrom Mo"
},
{
"path": "about",
"chars": 579,
"preview": "[b]Whatsapp Msgstore Viewer[/b] (WMV)\nVersion $$version$$\n(C) 2023 [ref=https://github.com/absadiki][color=0000ff]absadi"
},
{
"path": "credits",
"chars": 1065,
"preview": "This software would not possible without:\n[color=ffffff]\\n[/color]\n\n- [ref=https://kivy.org][color=0000ff]Kivy[/color][/"
},
{
"path": "dbs/__init__.py",
"chars": 1172,
"preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\" Short description of this Python module.\nLonger description of this m"
},
{
"path": "dbs/abstract_db.py",
"chars": 5992,
"preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nThis file describes how the database should look like and what it shou"
},
{
"path": "dbs/v1/__init__.py",
"chars": 1172,
"preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\" Short description of this Python module.\nLonger description of this m"
},
{
"path": "dbs/v1/db.py",
"chars": 4163,
"preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom dbs.abstract_db import AbstractDatabase\n\n\nclass Database(AbstractDat"
},
{
"path": "dbs/v2/__init__.py",
"chars": 1977,
"preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Database interface for accessing and retrieving WhatsApp chat, message"
},
{
"path": "dbs/v2/db.py",
"chars": 4398,
"preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom dbs.abstract_db import AbstractDatabase\n\nclass Database(AbstractData"
},
{
"path": "dbs/v3/__init__.py",
"chars": 345,
"preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Version 3 database schema support for Whatsapp Msgstore Viewer.\nThis p"
},
{
"path": "dbs/v3/db.py",
"chars": 5301,
"preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom dbs.abstract_db import AbstractDatabase\n\n\nclass Database(AbstractDat"
},
{
"path": "decryption/__init__.py",
"chars": 1172,
"preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\" Short description of this Python module.\nLonger description of this m"
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/LICENSE",
"chars": 35141,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/README.md",
"chars": 6160,
"preview": "# WhatsApp Crypt14-15 Backup Decrypter\nDecrypts WhatsApp .crypt12, .crypt14 and .crypt15 files, **given the key file** o"
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/SECURITY.md",
"chars": 94,
"preview": "# Security Policy\n\n## Supported Versions\n\nLatest\n\n## Reporting a Vulnerability\n\nOpen an issue\n"
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/decrypt14_15.py",
"chars": 38616,
"preview": "#!/usr/bin/env python\n\"\"\"\nThis script decrypts WhatsApp's DB files encrypted with Crypt12, Crypt14 or Crypt15.\n\"\"\"\n\nfrom"
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/C14_cipher.proto",
"chars": 456,
"preview": "syntax = \"proto3\";\n\nimport \"C14_cipher_version.proto\";\n// crypt14 cipher files.\nmessage C14_cipher {\n //For some reas"
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/C14_cipher_pb2.py",
"chars": 1182,
"preview": "# -*- coding: utf-8 -*-\n# Generated by the protocol buffer compiler. DO NOT EDIT!\n# source: C14_cipher.proto\n\"\"\"Generat"
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/C14_cipher_version.proto",
"chars": 130,
"preview": "syntax = \"proto3\";\n\n// crypt14 cipher files. Actually the field tag is zero.\nmessage C14_cipher_version {\n int32 vers"
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/C14_cipher_version_pb2.py",
"chars": 1016,
"preview": "# -*- coding: utf-8 -*-\n# Generated by the protocol buffer compiler. DO NOT EDIT!\n# source: C14_cipher_version.proto\n\"\""
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/C15_IV.proto",
"chars": 123,
"preview": "syntax = \"proto3\";\n\n// In crypt15 files only the IV is stored.\nmessage C15_IV {\n bytes IV = 1; // The 16-bytes long I"
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/C15_IV_pb2.py",
"chars": 940,
"preview": "# -*- coding: utf-8 -*-\n# Generated by the protocol buffer compiler. DO NOT EDIT!\n# source: C15_IV.proto\n\"\"\"Generated p"
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/key_type.proto",
"chars": 226,
"preview": "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 o"
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/key_type_pb2.py",
"chars": 967,
"preview": "# -*- coding: utf-8 -*-\n# Generated by the protocol buffer compiler. DO NOT EDIT!\n# source: key_type.proto\n\"\"\"Generated"
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/prefix.proto",
"chars": 541,
"preview": "syntax = \"proto3\";\nimport \"C14_cipher.proto\";\nimport \"C15_IV.proto\";\nimport \"key_type.proto\";\nimport \"version_features.p"
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/prefix_pb2.py",
"chars": 1465,
"preview": "# -*- coding: utf-8 -*-\n# Generated by the protocol buffer compiler. DO NOT EDIT!\n# source: prefix.proto\n\"\"\"Generated p"
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/version_features.proto",
"chars": 1916,
"preview": "syntax = \"proto3\";\n// This describes the metadata, e.g. the version, the ph number and various features.\nmessage Version"
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/proto/version_features_pb2.py",
"chars": 4281,
"preview": "# -*- coding: utf-8 -*-\n# Generated by the protocol buffer compiler. DO NOT EDIT!\n# source: version_features.proto\n\"\"\"G"
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/requirements.txt",
"chars": 58,
"preview": "javaobj-py3==0.4.3\npycryptodomex==3.16.0\nprotobuf==4.21.12"
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/utils/WA_HMACSHA256_Loop.java",
"chars": 2502,
"preview": "package com.test;\n\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\nimport java.io.ByteArrayOutputStream"
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/utils/hex_string_to_encrypted_backup_key.py",
"chars": 3048,
"preview": "#!/usr/bin/env python\n\"\"\"\nThis script transforms a hex string in an encrypted_backup.key file.\n\"\"\"\nfrom __future__ impor"
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/utils/password_data_key_to_hashcat.py",
"chars": 3569,
"preview": "#!/usr/bin/env python\n\"\"\"\nThis script transforms a password_data.key file into a hashcat hash.\n\"\"\"\nfrom __future__ impor"
},
{
"path": "decryption/dbs/WhatsAppCrypt14Crypt15Decrypter/utils/protobuf_bruteforce.py",
"chars": 3883,
"preview": "\"\"\"\nThis script tries to find protobuf messages in a file.\nProps to protobuf_inspector for the parser.\n\"\"\"\n\nfrom __futur"
},
{
"path": "decryption/dbs/__init__.py",
"chars": 1172,
"preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\" Short description of this Python module.\nLonger description of this m"
},
{
"path": "decryption/dbs/decrypt_db.py",
"chars": 3399,
"preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nDecryption module\n\nThis program is free software: you can redistribut"
},
{
"path": "libs/__init__.py",
"chars": 54,
"preview": "# This package is for additional application modules.\n"
},
{
"path": "main.py",
"chars": 5323,
"preview": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nWhatsapp Msgstore Viewer(WMV)\nWMV is a free, open source and cross-pl"
},
{
"path": "pyproject.toml",
"chars": 1336,
"preview": "[build-system]\nrequires = [\"setuptools>=42\", \"wheel\"]\nbuild-backend = \"setuptools.build_meta\"\n\n[project]\nname = \"whatsap"
},
{
"path": "requirements.txt",
"chars": 266,
"preview": "watchdog\nKivy>=2.3.0\n#kivymd @ https://github.com/kivymd/KivyMD/archive/a85adc5ee4ee2178b7d353a260f2cbcefce885c7.zip\nkiv"
},
{
"path": "version.py",
"chars": 79,
"preview": "\"\"\"Version information for WhatsApp Msgstore Viewer.\"\"\"\n\n__version__ = \"1.1.2\"\n"
}
]
// ... and 1 more files (download for full content)
About this extraction
This page contains the full source code of the absadiki/whatsapp-msgstore-viewer GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 79 files (237.4 KB), approximately 57.1k tokens, and a symbol index with 201 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.