memberjojo 2.1__py3-none-any.whl → 2.3__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.
memberjojo/__init__.py CHANGED
@@ -10,3 +10,5 @@ except ModuleNotFoundError:
10
10
 
11
11
  from .mojo_member import Member
12
12
  from .mojo_transaction import Transaction
13
+ from .download import Download
14
+ from .url import URL
memberjojo/_version.py CHANGED
@@ -28,7 +28,7 @@ version_tuple: VERSION_TUPLE
28
28
  commit_id: COMMIT_ID
29
29
  __commit_id__: COMMIT_ID
30
30
 
31
- __version__ = version = '2.1'
32
- __version_tuple__ = version_tuple = (2, 1)
31
+ __version__ = version = '2.3'
32
+ __version_tuple__ = version_tuple = (2, 3)
33
33
 
34
34
  __commit_id__ = commit_id = None
memberjojo/download.py ADDED
@@ -0,0 +1,116 @@
1
+ """
2
+ A class for downloading from membermojo
3
+ """
4
+
5
+ import getpass
6
+ import re
7
+ from http.cookiejar import MozillaCookieJar
8
+ from pathlib import Path
9
+ import requests
10
+
11
+ from .url import URL
12
+
13
+
14
+ class Download:
15
+ """A class for managing Membermojo downloads"""
16
+
17
+ def __init__(self, shortname: str, cookie_jar: MozillaCookieJar):
18
+ """
19
+ Initialise the class
20
+
21
+ :param shortname: the membermojo shortname
22
+ :param cookie_jar: a MozillaCookieJar with the session cookie, or empty to get one
23
+ """
24
+ self.url = URL(shortname)
25
+ self.cookie_jar = cookie_jar
26
+ self.session = requests.Session()
27
+ self.session.cookies = self.cookie_jar
28
+
29
+ def fill_login(self):
30
+ """
31
+ Prompt for email and password to get login data
32
+
33
+ :return: a dict of the login data
34
+ """
35
+ email = input("📧 Enter your Membermojo email: ").strip()
36
+ password = getpass.getpass("🔐 Enter your password: ").strip()
37
+
38
+ # Submit login form (this triggers verification email if needed)
39
+ return {"email": email, "password": password}
40
+
41
+ def mojo_login(self, login_data: dict, email_verify: bool = False):
42
+ """
43
+ Login to membermojo, cookie jar should be saved afterwards with updated cookie
44
+
45
+ :param login_data: a dict containing email and password for requests
46
+ :param email_verify: if True membermojo email verification will be triggered
47
+ if login fails, or no cookie found to create a new session cookie
48
+
49
+ :raises ValueError: If authentication fails and email_verify is False
50
+ """
51
+ if not self.session.cookies:
52
+ if email_verify:
53
+ print("🍪 No cookies saved, triggering email verification.")
54
+ self.trigger_email(login_data)
55
+ else:
56
+ raise ValueError("⚠️ No cookies found — email verification required.")
57
+ self.session.post(self.url.login, data=login_data)
58
+
59
+ # Attempt to access a protected page to verify login worked
60
+ print(f"Verifying login with: {self.url.test}")
61
+ verify_response = self.session.get(self.url.test)
62
+ if "<mm2-loginpage" in verify_response.text:
63
+ if email_verify:
64
+ print("📧 Authentication failed, triggering email verification")
65
+ self.trigger_email(login_data)
66
+ else:
67
+ raise ValueError(
68
+ "⚠️ Authentication Failed — email verification required."
69
+ )
70
+
71
+ def trigger_email(self, login_data: dict):
72
+ """
73
+ Triggers a login verification email, prompts the user for the verification URL,
74
+ and then submits it to complete the login process.
75
+
76
+ :param login_data: A dictionary containing login credentials (e.g., email)
77
+
78
+ :raises: ValueError: If a CSRF token cannot be found or if the login form submission fails
79
+ """
80
+ self.session.cookies.clear()
81
+ response = self.session.post(self.url.login, data=login_data)
82
+
83
+ if "check your email" in response.text.lower() or response.ok:
84
+ print("✅ Login submitted — check your inbox for a verification link.")
85
+
86
+ # Get CSRF token from homepage
87
+ homepage = self.session.get(self.url.base_url)
88
+ match = re.search(r'"csrf_token":"([^"]+)"', homepage.text)
89
+ if not match:
90
+ raise ValueError("❌ Could not find CSRF token.")
91
+
92
+ csrf_token = match.group(1)
93
+ print(f"✅ CSRF token: {csrf_token}")
94
+
95
+ # Ask user for the verification link
96
+ verification_url = input(
97
+ "🔗 Paste the verification URL from the email: "
98
+ ).strip()
99
+
100
+ # Submit the verification request
101
+ verify_response = self.session.post(
102
+ verification_url, data={"csrf_token": csrf_token}
103
+ )
104
+
105
+ # Output
106
+ if verify_response.ok:
107
+ print("✅ Verification successful. You're now logged in.")
108
+ else:
109
+ print("⚠️ Verification may have failed.")
110
+ verify_html = Path("verify.html")
111
+ with verify_html.open("w", encoding="UTF-8") as f:
112
+ f.write(verify_response.text)
113
+
114
+ else:
115
+ print(response.text)
116
+ raise ValueError("❌ Failed to submit login form.")
memberjojo/mojo_common.py CHANGED
@@ -1,72 +1,112 @@
1
1
  """
2
2
  MojoSkel base class
3
3
 
4
- This module provides a common base class (`MojoSkel`) for other `memberjojo` modules.
5
- It includes helper methods for working with SQLite databases.
4
+ This module provides a common base class (`MojoSkel`) for other `memberjojo` modules
5
+ It includes helper methods for working with SQLite databases
6
6
  """
7
7
 
8
- # pylint: disable=no-member
9
-
10
8
  from dataclasses import make_dataclass
11
9
  from decimal import Decimal, InvalidOperation
12
10
  from pathlib import Path
13
- from typing import Union, List
11
+ from pprint import pprint
12
+ from typing import Any, Iterator, List, Type, Union
13
+
14
+ import requests
15
+
16
+ try:
17
+ from sqlcipher3 import dbapi2 as sqlite3
14
18
 
15
- from sqlcipher3 import dbapi2 as sqlite3
19
+ HAS_SQLCIPHER = True
20
+ except ImportError:
21
+ import sqlite3 # stdlib
22
+
23
+ HAS_SQLCIPHER = False
16
24
 
17
25
  from . import mojo_loader
26
+ from .sql_query import Like
18
27
 
19
28
 
20
29
  class MojoSkel:
21
30
  """
22
31
  Establishes a connection to a SQLite database and provides helper methods
23
- for querying tables.
32
+ for querying tables
24
33
  """
25
34
 
26
35
  def __init__(self, db_path: str, db_key: str, table_name: str):
27
36
  """
28
- Initialize the MojoSkel class.
37
+ Initialize the MojoSkel class
29
38
 
30
39
  Connects to the SQLite database and sets the row factory for
31
40
  dictionary-style access to columns.
32
41
 
33
- :param db_path: Path to the SQLite database file.
34
- :param db_key: key to unlock the encrypted sqlite database, or encrypt new one.
35
- :param table_name: Name of the table to operate on, or create when importing.
42
+ :param db_path: Path to the SQLite database file
43
+ :param db_key: key to unlock the encrypted sqlite database,
44
+ unencrypted if sqlcipher3 not installed or unset
45
+ :param table_name: Name of the table to operate on, or create when importing
36
46
  """
37
47
  self.db_path = db_path
38
48
  self.table_name = table_name
39
49
  self.db_key = db_key
50
+ self.debug = False
40
51
 
41
52
  # Open connection
42
- self.conn = sqlite3.connect(self.db_path)
43
- self.conn.row_factory = sqlite3.Row
53
+ self.conn = sqlite3.connect(self.db_path) # pylint: disable=no-member
54
+ self.conn.row_factory = sqlite3.Row # pylint: disable=no-member
44
55
  self.cursor = self.conn.cursor()
45
56
 
46
- # Apply SQLCipher key
47
- self.cursor.execute(f"PRAGMA key='{db_key}'")
48
- self.cursor.execute("PRAGMA cipher_compatibility = 4")
49
- print("Cipher:", self.cursor.execute("PRAGMA cipher_version;").fetchone()[0])
50
- print(f"Encrypted database {self.db_path} loaded securely.")
57
+ if HAS_SQLCIPHER and db_key:
58
+ # Apply SQLCipher key
59
+ self.cursor.execute(f"PRAGMA key='{db_key}'")
60
+ self.cursor.execute("PRAGMA cipher_compatibility = 4")
61
+ print(
62
+ "Cipher:", self.cursor.execute("PRAGMA cipher_version;").fetchone()[0]
63
+ )
64
+ print(f"Encrypted database {self.db_path} loaded securely.")
65
+ else:
66
+ print(f"Unencrypted database {self.db_path} loaded securely.")
51
67
 
52
68
  # After table exists (or after import), build the dataclass
53
- if self.table_exists(table_name):
69
+ if self.table_exists():
54
70
  self.row_class = self._build_dataclass_from_table()
55
71
  else:
56
72
  self.row_class = None
57
73
 
58
- def __iter__(self):
74
+ def __iter__(self) -> Iterator[Any]:
59
75
  """
60
- Allow iterating over the class, by outputing all members.
76
+ Allow iterating over the class, by outputing all members
61
77
  """
62
78
  if not self.row_class:
63
79
  raise RuntimeError("Table not loaded yet — no dataclass available")
64
80
  return self._iter_rows()
65
81
 
66
- def _iter_rows(self):
82
+ def _row_to_obj(self, row: sqlite3.Row) -> Type[Any]:
83
+ """
84
+ Convert an sqlite3 row into a dataclass object
85
+
86
+ :param row: The sqlite3 row to convert
87
+
88
+ :return: A dataclass object of the row
89
+ """
90
+ row_dict = dict(row)
91
+
92
+ # Convert REAL → Decimal (including numeric strings)
93
+ for k, v in row_dict.items():
94
+ if isinstance(v, float):
95
+ row_dict[k] = Decimal(str(v))
96
+ elif isinstance(v, str):
97
+ try:
98
+ row_dict[k] = Decimal(v)
99
+ except InvalidOperation:
100
+ pass
101
+
102
+ return self.row_class(**row_dict)
103
+
104
+ def _iter_rows(self) -> Iterator[Any]:
67
105
  """
68
- Iterate over table rows and yield dynamically-created dataclass objects.
69
- Converts REAL columns to Decimal automatically.
106
+ Iterate over table rows and yield dynamically-created dataclass objects
107
+ Converts REAL columns to Decimal automatically
108
+
109
+ :return: An interator of dataclass objects for rows
70
110
  """
71
111
 
72
112
  sql = f'SELECT * FROM "{self.table_name}"'
@@ -75,29 +115,18 @@ class MojoSkel:
75
115
  cur.execute(sql)
76
116
 
77
117
  for row in cur.fetchall():
78
- row_dict = dict(row)
79
-
80
- # Convert REAL → Decimal
81
- for k, v in row_dict.items():
82
- if isinstance(v, float):
83
- row_dict[k] = Decimal(str(v))
84
- elif isinstance(v, str):
85
- # Try converting numeric strings
86
- try:
87
- row_dict[k] = Decimal(v)
88
- except InvalidOperation:
89
- pass
118
+ yield self._row_to_obj(row)
90
119
 
91
- yield self.row_class(**row_dict)
92
-
93
- def _build_dataclass_from_table(self):
120
+ def _build_dataclass_from_table(self) -> Type[Any]:
94
121
  """
95
- Dynamically create a dataclass from the table schema.
122
+ Dynamically create a dataclass from the table schema
96
123
  INTEGER → int
97
124
  REAL → Decimal
98
125
  TEXT → str
99
126
 
100
- :return: A dataclass built from the table columns and types.
127
+ :return: A dataclass built from the table columns and types
128
+
129
+ :raises ValueError: If no table
101
130
  """
102
131
  self.cursor.execute(f'PRAGMA table_info("{self.table_name}")')
103
132
  cols = self.cursor.fetchall()
@@ -120,22 +149,89 @@ class MojoSkel:
120
149
 
121
150
  return make_dataclass(f"{self.table_name}_Row", fields)
122
151
 
152
+ def rename_old_table(self, existing: bool) -> str:
153
+ """
154
+ If there was an exising table rename for comparison
155
+
156
+ :param existing: bool for table exists
157
+
158
+ :return: the old table name
159
+ """
160
+ old_table = f"{self.table_name}_old"
161
+ self.conn.execute(f"DROP TABLE IF EXISTS {old_table}")
162
+ # Preserve existing table
163
+ if existing:
164
+ self.conn.execute(f"ALTER TABLE {self.table_name} RENAME TO {old_table}")
165
+ return old_table
166
+
167
+ def print_diff(self, old_table: str):
168
+ """
169
+ Print out diff between old and new db
170
+
171
+ :param old_table: The name the existing table was renamed to
172
+ """
173
+ try:
174
+ # Diff old vs new (SQLCipher → sqlite3 → dataclasses)
175
+ diff_rows = mojo_loader.diff_cipher_tables(
176
+ self.conn,
177
+ new_table=self.table_name,
178
+ old_table=old_table,
179
+ )
180
+
181
+ if diff_rows:
182
+ for diff in diff_rows:
183
+ # diff is a DiffRow dataclass
184
+ print(diff.diff_type, diff.preview)
185
+
186
+ finally:
187
+ # Cleanup old table (always)
188
+ self.conn.execute(f"DROP TABLE {old_table}")
189
+
190
+ def download_csv(self, session: requests.Session, url: str):
191
+ """
192
+ Download the CSV from url and import into the sqlite database
193
+ If a previous table exists, generate a diff
194
+
195
+ :param session: Requests session to use for download
196
+ :param url: url of the csv to download
197
+ """
198
+ had_existing = self.table_exists()
199
+ old_table = self.rename_old_table(had_existing)
200
+
201
+ # Download CSV as new table
202
+ mojo_loader.download_csv_helper(self.conn, self.table_name, url, session)
203
+ self.row_class = self._build_dataclass_from_table()
204
+
205
+ if not had_existing:
206
+ return
207
+
208
+ self.print_diff(old_table)
209
+
123
210
  def import_csv(self, csv_path: Path):
124
211
  """
125
- import the passed CSV into the sqlite database
212
+ Import the passed CSV into the encrypted sqlite database
126
213
 
127
- :param csv_path: Path like path of csv file.
214
+ :param csv_path: Path like path of csv file
128
215
  """
216
+ had_existing = self.table_exists()
217
+ old_table = self.rename_old_table(had_existing)
218
+
219
+ # Import CSV as new table
129
220
  mojo_loader.import_csv_helper(self.conn, self.table_name, csv_path)
130
221
  self.row_class = self._build_dataclass_from_table()
131
222
 
223
+ if not had_existing:
224
+ return
225
+
226
+ self.print_diff(old_table)
227
+
132
228
  def show_table(self, limit: int = 2):
133
229
  """
134
- Print the first few rows of the table as dictionaries.
230
+ Print the first few rows of the table as dictionaries
135
231
 
136
- :param limit: (optional) Number of rows to display. Defaults to 2.
232
+ :param limit: (optional) Number of rows to display. Defaults to 2
137
233
  """
138
- if self.table_exists(self.table_name):
234
+ if self.table_exists():
139
235
  self.cursor.execute(f'SELECT * FROM "{self.table_name}" LIMIT ?', (limit,))
140
236
  rows = self.cursor.fetchall()
141
237
 
@@ -148,42 +244,43 @@ class MojoSkel:
148
244
 
149
245
  def count(self) -> int:
150
246
  """
151
- :return: count of the number of rows in the table, or 0 if no table.
247
+ :return: count of the number of rows in the table, or 0 if no table
152
248
  """
153
- if self.table_exists(self.table_name):
249
+ if self.table_exists():
154
250
  self.cursor.execute(f'SELECT COUNT(*) FROM "{self.table_name}"')
155
251
  result = self.cursor.fetchone()
156
252
  return result[0] if result else 0
157
253
 
158
254
  return 0
159
255
 
160
- def get_row(self, entry_name: str, entry_value: str) -> dict:
256
+ def get_row(
257
+ self, entry_name: str, entry_value: str, only_one: bool = True
258
+ ) -> Union[sqlite3.Row, List[sqlite3.Row], None]:
161
259
  """
162
- Retrieve a single row matching column = value (case-insensitive).
260
+ Retrieve a single row matching column = value (case-insensitive)
163
261
 
164
- :param entry_name: Column name to filter by.
165
- :param entry_value: Value to match.
262
+ :param entry_name: Column name to filter by
263
+ :param entry_value: Value to match
264
+ :param only_one: If True (default), return the first matching row
265
+ If False, return a list of all matching rows
166
266
 
167
- :return: The matching row as a dictionary, or None if not found.
267
+ :return:
268
+ - If only_one=True → a single sqlite3.Row or None
269
+ - If only_one=False → list of sqlite3.Row (may be empty)
168
270
  """
169
- if not entry_value:
170
- return None
171
- query = (
172
- f'SELECT * FROM "{self.table_name}" WHERE LOWER("{entry_name}") = LOWER(?)'
173
- )
174
- self.cursor.execute(query, (entry_value,))
175
- row = self.cursor.fetchone()
176
- return dict(row) if row else None
271
+ match_dict = {f"{entry_name}": entry_value}
272
+
273
+ return self.get_row_multi(match_dict, only_one)
177
274
 
178
275
  def get_row_multi(
179
276
  self, match_dict: dict, only_one: bool = True
180
277
  ) -> Union[sqlite3.Row, List[sqlite3.Row], None]:
181
278
  """
182
- Retrieve one or many rows matching multiple column=value pairs.
279
+ Retrieve one or many rows matching multiple column=value pairs
183
280
 
184
- :param match_dict: Dictionary of column names and values to match.
185
- :param only_one: If True (default), return the first matching row.
186
- If False, return a list of all matching rows.
281
+ :param match_dict: Dictionary of column names and values to match
282
+ :param only_one: If True (default), return the first matching row
283
+ If False, return a list of all matching rows
187
284
 
188
285
  :return:
189
286
  - If only_one=True → a single sqlite3.Row or None
@@ -195,6 +292,23 @@ class MojoSkel:
195
292
  for col, val in match_dict.items():
196
293
  if val is None or val == "":
197
294
  conditions.append(f'"{col}" IS NULL')
295
+ elif isinstance(val, Like):
296
+ conditions.append(f'LOWER("{col}") LIKE LOWER(?)')
297
+ values.append(val.pattern)
298
+ elif isinstance(val, (tuple, list)) and len(val) == 2:
299
+ lower, upper = val
300
+ if lower is not None and upper is not None:
301
+ conditions.append(f'"{col}" BETWEEN ? AND ?')
302
+ values.extend([lower, upper])
303
+ elif lower is not None:
304
+ conditions.append(f'"{col}" >= ?')
305
+ values.append(lower)
306
+ elif upper is not None:
307
+ conditions.append(f'"{col}" <= ?')
308
+ values.append(upper)
309
+ else:
310
+ # Both are None, effectively no condition on this column
311
+ pass
198
312
  else:
199
313
  conditions.append(f'"{col}" = ?')
200
314
  values.append(
@@ -203,25 +317,30 @@ class MojoSkel:
203
317
  else val
204
318
  )
205
319
 
320
+ # Base query string
206
321
  base_query = (
207
322
  f'SELECT * FROM "{self.table_name}" WHERE {" AND ".join(conditions)}'
208
323
  )
324
+ if self.debug:
325
+ print("Sql:")
326
+ pprint(base_query)
209
327
 
210
328
  if only_one:
211
329
  query = base_query + " LIMIT 1"
212
330
  self.cursor.execute(query, values)
213
- return self.cursor.fetchone()
331
+ if row := self.cursor.fetchone():
332
+ return self._row_to_obj(row)
333
+ return None
214
334
 
215
- # Return *all* rows
216
335
  self.cursor.execute(base_query, values)
217
- return self.cursor.fetchall()
336
+ return [self._row_to_obj(row) for row in self.cursor.fetchall()]
218
337
 
219
- def table_exists(self, table_name: str) -> bool:
338
+ def table_exists(self) -> bool:
220
339
  """
221
- Return true or false if a table exists
340
+ Return True or False if a table exists
222
341
  """
223
342
  self.cursor.execute(
224
343
  "SELECT 1 FROM sqlite_master WHERE type='table' AND name=? LIMIT 1;",
225
- (table_name,),
344
+ (self.table_name,),
226
345
  )
227
346
  return self.cursor.fetchone() is not None