Commit 39788382 authored by Martin Matějek's avatar Martin Matějek

Use uuid as random id of notification

Use first 8 characters as short id
parent 34e2fcc0
import json
import random
import uuid
from datetime import datetime
from jinja2 import TemplateError
......@@ -198,15 +199,11 @@ class Notification:
@staticmethod
def _generate_id():
"""
Generate unique id of message based on timestamp
Generate unique id of message based on uuid
returned as string
Returned as string
"""
ts = int(datetime.utcnow().timestamp())
rand = random.randint(10000, 99999)
# add random number for uniqueness
return "{}-{}".format(ts, rand)
return uuid.uuid4().hex
def __str__(self):
out = "{\n"
......
......@@ -15,6 +15,7 @@ from .notification import Notification
class NotificationStorage:
"""In-memory notification storage that serialize and deserialize them"""
SHORTID_LENGTH = 8
def __init__(self, volatile_dir, persistent_dir):
self.storage_dirs = {
......@@ -37,21 +38,19 @@ class NotificationStorage:
Render fallback in default languages
"""
self.notifications[n.notif_id] = n
self.shortid_map[n.notif_id[-5:]] = n.notif_id
self.shortid_map[n.notif_id[:self.SHORTID_LENGTH]] = n.notif_id
if n.persistent:
storage_dir = self.storage_dirs['persistent']
else:
storage_dir = self.storage_dirs['volatile']
json_data = n.serialize()
# save to disk
file_path = os.path.join(storage_dir, "{}.json".format(n.notif_id))
try:
with open(file_path, 'w') as f:
f.write(json_data)
f.write(n.serialize())
except OSError:
logger.error("Error during writing notification to disk!")
......@@ -67,7 +66,7 @@ class NotificationStorage:
if n:
self.notifications[n.notif_id] = n
self.shortid_map[n.notif_id[-5:]] = n.notif_id
self.shortid_map[n.notif_id[:self.SHORTID_LENGTH]] = n.notif_id
def _sort_notifications(self, dictionary):
"""Sort notifications after load to maintain time-based order"""
......@@ -75,7 +74,7 @@ class NotificationStorage:
def valid_id(self, msgid):
"""Check if msgid is valid and message with that id exists"""
if len(msgid) != 5 and len(msgid) != 16:
if len(msgid) != self.SHORTID_LENGTH and len(msgid) != 32:
logger.warning("Notification id is invalid - incorrect format")
return False
......@@ -89,7 +88,7 @@ class NotificationStorage:
def _full_id(self, msgid):
"""Get full id of notification based on short id"""
if len(msgid) == 5:
if len(msgid) == self.SHORTID_LENGTH:
return self.shortid_map[msgid]
return msgid
......@@ -148,7 +147,7 @@ class NotificationStorage:
n = self.notifications[msgid]
del self.notifications[msgid]
del self.shortid_map[msgid[-5:]]
del self.shortid_map[msgid[:self.SHORTID_LENGTH]]
logger.debug("Dismissing notification '%s'", msgid)
if n.persistent:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment