#
# Copyright (c) 2008-2015 Thierry Florac <tflorac AT ulthar.net>
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
__docformat__ = 'restructuredtext'
import pickle
from datetime import datetime
from pyramid.view import view_config
from pyams_cache.cache import get_cache_handler
from pyams_cache.interfaces import ICacheHandler
from pyams_notify.interfaces import CACHE_CONFIGURATION_KEY, CACHE_QUEUE_KEY
from pyams_skin.layer import IPyAMSLayer
from pyams_utils.date import format_datetime
from pyams_utils.timezone import tztime
[docs]def get_user_notifications(cache_server, request):
"""Get notifications for given request"""
def filtered(notification, request):
"""Filter notification against current request"""
if request.host != notification.get('host'):
return False
target = notification.pop('target', {})
return request.principal.id in target.get('principals', ())
timestamp = format_datetime(tztime(datetime.utcnow()), request=request)
if cache_server is not None:
client = get_cache_handler(cache_server, ICacheHandler)
if client is None:
return {'timestamp': timestamp,
'notifications': ()}
notifications = client.get(CACHE_QUEUE_KEY)
if notifications is None:
return {'timestamp': timestamp,
'notifications': ()}
else:
return {'timestamp': timestamp,
'notifications': [n for n in reversed(list(filter(lambda x: filtered(x, request),
pickle.loads(notifications))))]}
else:
return {'timestamp': timestamp,
'notifications': ()}
[docs]@view_config(name='get-user-notifications.json', request_type=IPyAMSLayer, renderer='json', xhr=True)
class UserNotificationsView(object):
"""User notifications view"""
def __init__(self, request):
self.request = request
self.context = request.context
@property
def cache_server(self):
return self.request.registry.settings.get(CACHE_CONFIGURATION_KEY)
def __call__(self):
return get_user_notifications(self.cache_server, self.request)