actualpy 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
actual/__init__.py ADDED
@@ -0,0 +1,441 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import datetime
5
+ import io
6
+ import json
7
+ import pathlib
8
+ import re
9
+ import sqlite3
10
+ import tempfile
11
+ import uuid
12
+ import zipfile
13
+ from os import PathLike
14
+ from typing import IO, Union
15
+
16
+ from sqlmodel import Session, create_engine, select
17
+
18
+ from actual.api import ActualServer
19
+ from actual.api.models import RemoteFileListDTO
20
+ from actual.crypto import create_key_buffer, decrypt_from_meta, encrypt, make_salt
21
+ from actual.database import (
22
+ Accounts,
23
+ MessagesClock,
24
+ Transactions,
25
+ get_attribute_by_table_name,
26
+ get_class_by_table_name,
27
+ strong_reference_session,
28
+ )
29
+ from actual.exceptions import ActualError, InvalidZipFile, UnknownFileId
30
+ from actual.protobuf_models import HULC_Client, Message, SyncRequest
31
+ from actual.queries import (
32
+ get_account,
33
+ get_accounts,
34
+ get_ruleset,
35
+ get_transactions,
36
+ reconcile_transaction,
37
+ )
38
+ from actual.version import __version__ # noqa: F401
39
+
40
+
41
+ class Actual(ActualServer):
42
+ def __init__(
43
+ self,
44
+ base_url: str = "http://localhost:5006",
45
+ token: str = None,
46
+ password: str = None,
47
+ file: str = None,
48
+ encryption_password: str = None,
49
+ data_dir: Union[str, pathlib.Path] = None,
50
+ bootstrap: bool = False,
51
+ sa_kwargs: dict = None,
52
+ ):
53
+ """
54
+ Implements the Python API for the Actual Server in order to be able to read and modify information on Actual
55
+ books using Python.
56
+
57
+ Parts of the implementation are available at the following file:
58
+ https://github.com/actualbudget/actual/blob/2178da0414958064337b2c53efc95ff1d3abf98a/packages/loot-core/src/server/cloud-storage.ts
59
+
60
+ :param base_url: url of the running Actual server
61
+ :param token: the token for authentication, if this is available (optional)
62
+ :param password: the password for authentication. It will be used on the .login() method to retrieve the token.
63
+ :param file: the name or id of the file to be set
64
+ :param encryption_password: password used to configure encryption, if existing
65
+ :param data_dir: where to store the downloaded files from the server. If not specified, a temporary folder will
66
+ be created instead.
67
+ :param bootstrap: if the server is not bootstrapped, bootstrap it with the password.
68
+ :param sa_kwargs: additional kwargs passed to the SQLAlchemy session maker. Examples are `autoflush` (enabled
69
+ by default), `autocommit` (disabled by default). For a list of all parameters, check the SQLAlchemy
70
+ documentation: https://docs.sqlalchemy.org/en/20/orm/session_api.html#sqlalchemy.orm.Session.__init__
71
+ """
72
+ super().__init__(base_url, token, password, bootstrap)
73
+ self._file: RemoteFileListDTO | None = None
74
+ self._data_dir = pathlib.Path(data_dir) if data_dir else None
75
+ self.engine = None
76
+ self._session: Session | None = None
77
+ self._client: HULC_Client | None = None
78
+ # set the correct file
79
+ if file:
80
+ self.set_file(file)
81
+ self._encryption_password = encryption_password
82
+ self._master_key = None
83
+ self._in_context = False
84
+ self._sa_kwargs = sa_kwargs or {}
85
+ if "autoflush" not in self._sa_kwargs:
86
+ self._sa_kwargs["autoflush"] = True
87
+
88
+ def __enter__(self) -> Actual:
89
+ self._in_context = True
90
+ if self._file:
91
+ self.download_budget(self._encryption_password)
92
+ return self
93
+
94
+ def __exit__(self, exc_type, exc_val, exc_tb):
95
+ if self._session:
96
+ self._session.close()
97
+ self._in_context = False
98
+
99
+ @property
100
+ def session(self) -> Session:
101
+ if not self._session:
102
+ raise ActualError("No session defined. Use `with Actual() as actual:` construct to generate one.")
103
+ return self._session
104
+
105
+ def set_file(self, file_id: Union[str, RemoteFileListDTO]) -> RemoteFileListDTO:
106
+ """Sets the file id for the class for further requests. The file_id argument can be either a name or remote
107
+ id from the file. If the name is provided, only the first match is taken."""
108
+ if isinstance(file_id, RemoteFileListDTO):
109
+ self._file = file_id
110
+ return file_id
111
+ else:
112
+ selected_files = []
113
+ user_files = self.list_user_files()
114
+ for file in user_files.data:
115
+ if (file.file_id == file_id or file.name == file_id) and file.deleted == 0:
116
+ selected_files.append(file)
117
+ if len(selected_files) == 0:
118
+ raise UnknownFileId(f"Could not find a file id or identifier '{file_id}'")
119
+ elif len(selected_files) > 1:
120
+ raise UnknownFileId(f"Multiple files found with identifier '{file_id}'")
121
+ return self.set_file(selected_files[0])
122
+
123
+ def run_migrations(self, migration_files: list[str]):
124
+ """Runs the migration files, skipping the ones that have already been run. The files can be retrieved from
125
+ .data_file_index() method. This first file is the base database, and the following files are migrations.
126
+ Migrations can also be .js files. In this case, we have to extract and execute queries from the standard JS."""
127
+ conn = sqlite3.connect(self._data_dir / "db.sqlite")
128
+ for file in migration_files:
129
+ if not file.startswith("migrations"):
130
+ continue # in case db.sqlite file gets passed as one of the migrations files
131
+ file_id = file.split("_")[0].split("/")[1]
132
+ if conn.execute(f"SELECT id FROM __migrations__ WHERE id = '{file_id}';").fetchall():
133
+ continue # skip migration as it was already ran
134
+ migration = self.data_file(file) # retrieves file from actual server
135
+ sql_statements = migration.decode()
136
+ if file.endswith(".js"):
137
+ # there is one migration which is Javascript. All entries inside db.execQuery(`...`) must be executed
138
+ exec_entries = re.findall(r"db\.execQuery\(`([^`]*)`\)", sql_statements, re.DOTALL)
139
+ sql_statements = "\n".join(exec_entries)
140
+ conn.executescript(sql_statements)
141
+ conn.execute(f"INSERT INTO __migrations__ (id) VALUES ({file_id});")
142
+ conn.commit()
143
+ conn.close()
144
+
145
+ def create_budget(self, budget_name: str):
146
+ """Creates a budget using the remote server default database and migrations. If password is provided, the
147
+ budget will be encrypted."""
148
+ migration_files = self.data_file_index()
149
+ # create folder for the files
150
+ if not self._data_dir:
151
+ self._data_dir = pathlib.Path(tempfile.mkdtemp())
152
+ # first migration file is the default database
153
+ migration = self.data_file(migration_files[0])
154
+ (self._data_dir / "db.sqlite").write_bytes(migration)
155
+ # also write the metadata file with default fields
156
+ random_id = str(uuid.uuid4()).replace("-", "")[:7]
157
+ file_id = str(uuid.uuid4())
158
+ self.update_metadata(
159
+ {
160
+ "id": f"My-Finances-{random_id}",
161
+ "budgetName": budget_name,
162
+ "userId": self._token,
163
+ "cloudFileId": file_id,
164
+ "resetClock": True,
165
+ }
166
+ )
167
+ self._file = RemoteFileListDTO(name=budget_name, fileId=file_id, groupId=None, deleted=0, encryptKeyId=None)
168
+ # create engine for downloaded database and run migrations
169
+ self.run_migrations(migration_files[1:])
170
+ # generate a session
171
+ self.engine = create_engine(f"sqlite:///{self._data_dir}/db.sqlite")
172
+ if self._in_context:
173
+ self._session = strong_reference_session(Session(self.engine, **self._sa_kwargs))
174
+ # create a clock
175
+ self.load_clock()
176
+
177
+ def rename_budget(self, budget_name: str):
178
+ if not self._file:
179
+ raise UnknownFileId("No current file loaded.")
180
+ self.update_user_file_name(self._file.file_id, budget_name)
181
+
182
+ def export_data(self, output_file: str | PathLike[str] | IO[bytes] = None) -> bytes:
183
+ """Export your data as a zip file containing db.sqlite and metadata.json files. It can be imported into another
184
+ Actual instance by closing an open file (if any), then clicking the “Import file” button, then choosing
185
+ “Actual.” Even though encryption is enabled, the exported zip file will not have any encryption."""
186
+ if not output_file:
187
+ output_file = io.BytesIO()
188
+ with zipfile.ZipFile(output_file, "a", zipfile.ZIP_DEFLATED, False) as z:
189
+ z.write(self._data_dir / "db.sqlite", "db.sqlite")
190
+ z.write(self._data_dir / "metadata.json", "metadata.json")
191
+ return output_file.getvalue()
192
+
193
+ def encrypt(self, encryption_password: str):
194
+ """Encrypts the local database using a new key, and re-uploads to the server.
195
+
196
+ WARNING: this resets the file on the server. Make sure you have a copy of the database before attempting this
197
+ operation.
198
+ """
199
+ if encryption_password and not self._file.encrypt_key_id:
200
+ # password was provided, but encryption key not, create one
201
+ key_id = str(uuid.uuid4())
202
+ salt = make_salt()
203
+ self.user_create_key(self._file.file_id, key_id, encryption_password, salt)
204
+ self.update_metadata({"encryptKeyId": key_id})
205
+ self._file.encrypt_key_id = key_id
206
+ elif self._file.encrypt_key_id:
207
+ key_info = self.user_get_key(self._file.file_id)
208
+ salt = key_info.data.salt
209
+ else:
210
+ raise ActualError("Budget is encrypted but password was not provided")
211
+ self._master_key = create_key_buffer(encryption_password, salt)
212
+ # encrypt binary data with
213
+ encrypted = encrypt(self._file.encrypt_key_id, self._master_key, self.export_data())
214
+ binary_data = io.BytesIO(base64.b64decode(encrypted["value"]))
215
+ encryption_meta = encrypted["meta"]
216
+ self.reset_user_file(self._file.file_id)
217
+ self.upload_user_file(binary_data.getvalue(), self._file.file_id, self._file.name, encryption_meta)
218
+ self.set_file(self._file.file_id)
219
+
220
+ def upload_budget(self):
221
+ """Uploads the current file to the Actual server."""
222
+ if not self._data_dir:
223
+ raise UnknownFileId("No current file loaded.")
224
+ binary_data = io.BytesIO()
225
+ with zipfile.ZipFile(binary_data, "a", zipfile.ZIP_DEFLATED, False) as z:
226
+ z.write(self._data_dir / "db.sqlite", "db.sqlite")
227
+ z.write(self._data_dir / "metadata.json", "metadata.json")
228
+ # we have to first upload the user file so the reference id can be used to generate a new encryption key
229
+ self.upload_user_file(binary_data.getvalue(), self._file.file_id, self._file.name)
230
+ # reset local file id to retrieve the grouping id
231
+ self.set_file(self._file.file_id)
232
+ # encrypt the file and re-upload
233
+ if self._encryption_password or self._master_key or self._file.encrypt_key_id:
234
+ self.encrypt(self._encryption_password)
235
+
236
+ def reupload_budget(self):
237
+ self.reset_user_file(self._file.file_id)
238
+ self.upload_budget()
239
+
240
+ def apply_changes(self, messages: list[Message]):
241
+ """Applies a list of sync changes, based on what the sync method returned on the remote."""
242
+ if not self.engine:
243
+ raise UnknownFileId("No valid file available, download one with download_budget()")
244
+ with Session(self.engine) as s:
245
+ for message in messages:
246
+ if message.dataset == "prefs":
247
+ # write it to metadata.json instead
248
+ self.update_metadata({message.row: message.get_value()})
249
+ continue
250
+ table = get_class_by_table_name(message.dataset)
251
+ if table is None:
252
+ raise ActualError(
253
+ f"Actual found a table not supported by the library: table '{message.dataset}' not found"
254
+ )
255
+ column = get_attribute_by_table_name(message.dataset, message.column)
256
+ if column is None:
257
+ raise ActualError(
258
+ f"Actual found a column not supported by the library: "
259
+ f"column '{message.column}' at table '{message.dataset}' not found"
260
+ )
261
+ entry = s.get(table, message.row)
262
+ if not entry:
263
+ entry = table(id=message.row)
264
+ setattr(entry, column, message.get_value())
265
+ s.add(entry)
266
+ # this seems to be required for sqlmodel, remove if not needed anymore when querying from cache
267
+ s.flush()
268
+ s.commit()
269
+
270
+ def update_metadata(self, patch: dict):
271
+ """Updates the metadata.json from the Actual file with the patch fields. The patch is a dictionary that will
272
+ then be merged on the metadata and written again to a file."""
273
+ metadata_file = self._data_dir / "metadata.json"
274
+ if metadata_file.is_file():
275
+ config = json.loads(metadata_file.read_text()) | patch
276
+ else:
277
+ config = patch
278
+ metadata_file.write_text(json.dumps(config, separators=(",", ":")))
279
+
280
+ def download_budget(self, encryption_password: str = None):
281
+ """Downloads the budget file from the remote. After the file is downloaded, the sync endpoint is queries
282
+ for the list of pending changes. The changes are individual row updates, that are then applied on by one to
283
+ the downloaded database state.
284
+
285
+ If the budget is password protected, the password needs to be present to download the budget, otherwise it will
286
+ fail.
287
+ """
288
+ file_bytes = self.download_user_file(self._file.file_id)
289
+ encryption_password = encryption_password or self._encryption_password
290
+
291
+ if self._file.encrypt_key_id and encryption_password is None:
292
+ raise ActualError("File is encrypted but no encryption password provided.")
293
+ if encryption_password is not None and self._file.encrypt_key_id:
294
+ file_info = self.get_user_file_info(self._file.file_id)
295
+ key_info = self.user_get_key(self._file.file_id)
296
+ self._master_key = create_key_buffer(encryption_password, key_info.data.salt)
297
+ # decrypt file bytes
298
+ file_bytes = decrypt_from_meta(self._master_key, file_bytes, file_info.data.encrypt_meta)
299
+ self.import_zip(io.BytesIO(file_bytes))
300
+ # actual js always calls validation
301
+ self.validate()
302
+ self.sync()
303
+ # create session if not existing
304
+ if self._in_context and not self._session:
305
+ self._session = strong_reference_session(Session(self.engine, **self._sa_kwargs))
306
+
307
+ def import_zip(self, file_bytes: str | PathLike[str] | IO[bytes]):
308
+ try:
309
+ zip_file = zipfile.ZipFile(file_bytes)
310
+ except zipfile.BadZipfile as e:
311
+ raise InvalidZipFile(f"Invalid zip file: {e}") from None
312
+ if not self._data_dir:
313
+ self._data_dir = pathlib.Path(tempfile.mkdtemp())
314
+ # this should extract 'db.sqlite' and 'metadata.json' to the folder
315
+ zip_file.extractall(self._data_dir)
316
+ self.engine = create_engine(f"sqlite:///{self._data_dir}/db.sqlite")
317
+ # load the client id
318
+ self.load_clock()
319
+
320
+ def sync(self):
321
+ # after downloading the budget, some pending transactions still need to be retrieved using sync
322
+ request = SyncRequest(
323
+ {
324
+ "messages": [],
325
+ "fileId": self._file.file_id,
326
+ "groupId": self._file.group_id,
327
+ "keyId": self._file.encrypt_key_id,
328
+ }
329
+ )
330
+ request.set_null_timestamp(client_id=self._client.client_id) # using 0 timestamp to retrieve all changes
331
+ changes = self.sync_sync(request)
332
+ self.apply_changes(changes.get_messages(self._master_key))
333
+ if changes.messages:
334
+ self._client = HULC_Client.from_timestamp(changes.messages[-1].timestamp)
335
+
336
+ def load_clock(self) -> MessagesClock:
337
+ """See implementation at:
338
+ https://github.com/actualbudget/actual/blob/5bcfc71be67c6e7b7c8b444e4c4f60da9ea9fdaa/packages/loot-core/src/server/db/index.ts#L81-L98
339
+ """
340
+ with Session(self.engine) as session:
341
+ clock = session.exec(select(MessagesClock)).one_or_none()
342
+ if not clock:
343
+ clock_message = {
344
+ "timestamp": HULC_Client().timestamp(now=datetime.datetime(1970, 1, 1, 0, 0, 0, 0)),
345
+ "merkle": {},
346
+ }
347
+ clock = MessagesClock(id=1, clock=json.dumps(clock_message, separators=(",", ":")))
348
+ session.add(clock)
349
+ session.commit()
350
+ # add clock id to client id
351
+ self._client = HULC_Client.from_timestamp(json.loads(clock.clock)["timestamp"])
352
+ return clock
353
+
354
+ def commit(self):
355
+ """Adds all pending entries to the local database, and sends a sync request to the remote server to synchronize
356
+ the local changes. It's important to note that this process is not atomic, so if the process is interrupted
357
+ before it completes successfully, the files would end up in a unknown state, leading you to have to redo
358
+ the budget download."""
359
+ if not self._session:
360
+ raise ActualError("No session has been created for the file.")
361
+ # create sync request based on the session reference that is tracked
362
+ req = SyncRequest({"fileId": self._file.file_id, "groupId": self._file.group_id})
363
+ if self._file.encrypt_key_id:
364
+ req.keyId = self._file.encrypt_key_id
365
+ req.set_null_timestamp(client_id=self._client.client_id)
366
+ # flush to database, so that all data is evaluated on the database for consistency
367
+ self._session.flush()
368
+ # first we add all new entries and modify is required
369
+ if "messages" in self._session.info:
370
+ req.set_messages(self._session.info["messages"], self._client, master_key=self._master_key)
371
+ # commit to local database to clear the current flush cache
372
+ self._session.commit()
373
+ # sync all changes to the server
374
+ self.sync_sync(req)
375
+
376
+ def run_rules(self):
377
+ ruleset = get_ruleset(self.session)
378
+ transactions = get_transactions(self.session)
379
+ ruleset.run(transactions)
380
+
381
+ def _run_bank_sync_account(self, acct: Accounts, start_date: datetime.date) -> list[Transactions]:
382
+ sync_method = acct.account_sync_source
383
+ account_id = acct.account_id
384
+ requisition_id = acct.bank.bank_id if sync_method == "goCardless" else None
385
+ new_transactions_data = self.bank_sync_transactions(
386
+ sync_method.lower(), account_id, start_date, requisition_id=requisition_id
387
+ )
388
+ new_transactions = new_transactions_data.data.transactions.all
389
+ imported_transactions = []
390
+ for transaction in new_transactions:
391
+ payee = transaction.imported_payee or "" if sync_method == "goCardless" else transaction.notes
392
+ reconciled = reconcile_transaction(
393
+ self.session,
394
+ transaction.date,
395
+ acct,
396
+ payee,
397
+ transaction.notes,
398
+ amount=transaction.transaction_amount.amount,
399
+ imported_id=transaction.transaction_id,
400
+ cleared=transaction.booked,
401
+ imported_payee=payee,
402
+ already_matched=imported_transactions,
403
+ )
404
+ if reconciled.changed():
405
+ imported_transactions.append(reconciled)
406
+ return imported_transactions
407
+
408
+ def run_bank_sync(
409
+ self, account: str | Accounts | None = None, start_date: datetime.date | None = None
410
+ ) -> list[Transactions]:
411
+ """
412
+ Runs the bank synchronization for the selected account. If missing, all accounts are synchronized. If a
413
+ start_date is provided, is used as a reference, otherwise, the last timestamp of each account will be used. If
414
+ the account does not have any transaction, the last 90 days are considered instead.
415
+ """
416
+ # if no account is provided, sync all of them, otherwise just the account provided
417
+ if account is None:
418
+ accounts = get_accounts(self.session)
419
+ else:
420
+ account = get_account(self.session, account)
421
+ accounts = [account]
422
+ imported_transactions = []
423
+
424
+ default_start_date = start_date
425
+ for acct in accounts:
426
+ sync_method = acct.account_sync_source
427
+ account_id = acct.account_id
428
+ if not (account_id and sync_method):
429
+ continue
430
+ status = self.bank_sync_status(sync_method.lower())
431
+ if not status.data.configured:
432
+ continue
433
+ if start_date is None:
434
+ all_transactions = get_transactions(self.session, account=acct)
435
+ if all_transactions:
436
+ default_start_date = all_transactions[0].get_date()
437
+ else:
438
+ default_start_date = datetime.date.today() - datetime.timedelta(days=90)
439
+ transactions = self._run_bank_sync_account(acct, default_start_date)
440
+ imported_transactions.extend(transactions)
441
+ return imported_transactions