add logic for removing deleted notes from users histories

This commit is contained in:
Julian Schacher 2024-12-02 19:46:28 +01:00
parent b471bbd4d3
commit 48ba4ef7ca

View file

@ -1,5 +1,7 @@
#!/bin/env python
import argparse
import base64
import binascii
import email
import json
import smtplib
@ -219,6 +221,41 @@ class HedgedocExpire:
if self.config.verbose:
url = self.config.url + '/' + (note["alias"] if note["alias"] is not None else note["shortid"])
print(f'Note "{note["title"]}" ({url}) emailed to {msg["To"]}')
try:
with conn.cursor(row_factory=dict_row) as user_history_cur:
# Calculate the urlid of the note from its id.
# See:
# - https://github.com/hedgedoc/hedgedoc/blob/380587b7fd65bc1eb71eef51a3aab324f9877650/lib/models/note.js#L167-L172
# - https://git.cccv.de/infra/ansible/roles/hedgedoc/-/blob/d69cef4bf6c7fe4e67570363659e4c20b0e102af/files/hedgedoc-util.py#L84
urlid = base64.urlsafe_b64encode(binascii.unhexlify(f"{note['id']}".replace('-', ''))).decode().replace('=', '')
# Get all users with note in history.
user_history_cur.execute('''SELECT
"Users"."id",
"Users"."history",
"Users"."email",
"Users"."profile"
FROM "Users"
WHERE jsonb_path_exists("Users"."history"::jsonb, '$[*] ? (@.id == $urlid)', jsonb_build_object('urlid', %s::text))
''', [urlid])
users_with_note = user_history_cur.fetchall()
for user in users_with_note:
history = json.loads(user["history"])
history_without_note = json.dumps([ entry for entry in history if entry["id"] != urlid ])
user_history_cur.execute('''UPDATE "Users"
SET "history" = %s
WHERE "id" = %s
''', [history_without_note, user["id"]])
conn.commit()
if self.config.verbose:
for user in users_with_note:
print(f' deleted history entry for {self.email_from_email_or_profile(user)}')
except Exception as e:
conn.rollback()
print(f'An error occured while trying to delete {note["id"]} from the users history: {e}', file=sys.stderr)
except Exception as e:
print(f'Unable to send email to {self.email_from_email_or_profile(note)}: {e}', file=sys.stderr)