notification.py 7.38 KB
Newer Older
1 2
# coding: utf8
from datetime import date
3 4
from datetime import datetime

5 6 7 8 9 10 11 12
import gluon.contrib.simplejson
if request.env.http_origin:
    response.headers['Access-Control-Allow-Origin'] = request.env.http_origin  
    response.headers['Access-Control-Allow-Credentials'] = 'true'
    response.headers['Access-Control-Max-Age'] = 86400

    
ACCESS_DENIED = "access denied"
13
NOTIFICATION_CACHE_PREFIX = 'notification_'
14 15

def index():
16
    user_id = auth.user.id if auth.user else None    
17 18 19 20

    query = None
    if request.vars['id']:
        query = db.notification[request.vars['id']]
21 22 23
        log.debug('read notification %s' % request.vars["id"])
    else:
        log.debug('notification list')
24 25 26 27 28 29 30 31 32 33
    if auth.user:
        rows = db((db.user_preference.user_id==auth.user.id)
            &(db.user_preference.preference=='mail')
            &(db.user_preference.val==request.vars['id'])).select()
        if len(rows) == 0:
            db.user_preference.insert(
                user_id=auth.user.id,
                preference='mail',
                val=request.vars['id'])

34 35
            # Clear cache of this user
            cache.ram.clear(regex=NOTIFICATION_CACHE_PREFIX + str(user_id))
36

37
    notifications = db(db.notification).select(orderby=~db.notification.id)
38
         
39
    return dict(message="News",
40
                query=query,
41
                notifications=notifications)
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

# serve for to add a notification
def add():
    if (auth.is_admin()):
        return dict(message=T('add notification'))
    res = {"message": ACCESS_DENIED}
    log.error(res)
    return gluon.contrib.simplejson.dumps(res, separators=(',',':'))


# validate the form the user has posted
def add_form(): 
    if (not auth.is_admin()):
        res = {"message": ACCESS_DENIED}
        log.error(res)
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))

    error = ""
60 61
    if request.vars['title'] =="":
        error += "title needed, "
62 63 64 65 66 67
    if request.vars["message_content"] == "" :
        error += "message content needed, "
    if request.vars["message_type"] == "" :
        error += "type needed, "
    if request.vars["priority"] == "" :
        error += "priority needed, "
68
    if request.vars["expiration"] == "" :
69
        error += "expiration date required"
70
    else:
71
        try:
72
            datetime.strptime(""+request.vars['expiration'], '%Y-%m-%d')
73 74 75 76
        except ValueError:
            error += "date (wrong format)"

    if error=="" :
77
        id = db.notification.insert(title=request.vars["title"],
78 79 80 81
                            message_content=XML(request.vars["message_content"], sanitize=True).xml(),
                            message_type=request.vars["message_type"],
                            priority=request.vars["priority"],
                            expiration=request.vars["expiration"],
82 83
                            creator=auth.user_id,
                            creation_datetime=datetime.now())
84 85 86 87

        res = {"redirect": "notification/index",
               "args" : { "id" : id },
               "message": "notification added"}
88 89 90
        log.info(res, extra={'user_id': auth.user.id,
                'record_id': id,
                'table_name': "notification"})
91 92
        # Clear cache of all notifications
        cache.ram.clear(regex=NOTIFICATION_CACHE_PREFIX + '*')
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))

    else :
        res = {"success" : "false",
               "message" : error}
        log.error(res)
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))


# edit existing notification
def edit():
    if (auth.is_admin()):
        return dict(message=T('edit notification'))
    res = {"message": ACCESS_DENIED}
    log.error(res)
    return gluon.contrib.simplejson.dumps(res, separators=(',',':'))


# process submitted edit form
def edit_form():
    if (not auth.is_admin()):
        res = {"message": ACCESS_DENIED}
        log.error(res)
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))

    error = ""
    if request.vars["message_content"] == "" :
        error += "message body needed, "
    if request.vars["message_type"] == "" :
        error += "type needed, "
    if request.vars["priority"] == "" :
        error += "priority needed, "
125 126 127
    if request.vars["expiration"] == "" :
        error += "expiration date required"
    else:
128
        try:
129
            datetime.strptime(""+request.vars['expiration'], '%Y-%m-%d')
130 131 132 133
        except ValueError:
            error += "date (wrong format)"

    if error=="" :
134
        db.notification[request.vars['id']] = dict(title=request.vars["title"],
135 136 137 138
                            message_content=XML(request.vars["message_content"], sanitize=True).xml(),
                            message_type=request.vars["message_type"],
                            priority=request.vars["priority"],
                            expiration=request.vars["expiration"])
139

140 141 142
        db((db.user_preference.val==request.vars['id'])
            &(db.user_preference.preference=='mail')).delete()

143 144 145
        res = {"redirect": "notification/index",
               "args" : { "id" : request.vars['id'] },
               "message": "notification updated"}
146 147 148
        log.info(res, extra={'user_id': auth.user.id,
                'record_id': request.vars["id"],
                'table_name': "notification"})
149 150
        # Clear cache of all notifications
        cache.ram.clear(regex=NOTIFICATION_CACHE_PREFIX + '*')
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))

    else :
        res = {"success" : "false",
               "message" : error}
        log.error(res)
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))


def delete():
    if (not auth.is_admin()):
        res = {"message": ACCESS_DENIED}
        log.error(res)
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))

    db(db.notification.id==request.vars['id']).delete()
167 168 169
    # Cascade the notification deletion onto associated preferences
    db((db.user_preference.val==request.vars['id'])
        &(db.user_preference.preference=='mail')).delete()
170 171 172
    res = {"redirect": "notification/index",
               "success": "true",
               "message": "notification " + request.vars['id'] + " deleted"}
173 174 175
    log.info(res, extra={'user_id': auth.user.id,
            'record_id': request.vars["id"],
            'table_name': "notification"})
176 177
    # Clear cache of all notifications
    cache.ram.clear(regex=NOTIFICATION_CACHE_PREFIX + '*')
178 179
    return gluon.contrib.simplejson.dumps(res, separators=(',',':')) 

180
#
181 182
def get_active_notifications():
    today = date.today()
183
    user_id = auth.user.id if auth.user else None    
184 185 186 187 188
    if user_id:
        key = NOTIFICATION_CACHE_PREFIX + str(user_id)
    else:
        key = NOTIFICATION_CACHE_PREFIX

189 190
    # Force retrieval of the cache even if no value is set 
    cached = cache.ram(key, lambda: None, time_expire=None)
191 192
    if not cached:
        # No cache found: query database
193 194 195 196 197 198 199
        query = db(
            (db.notification.expiration >= today) | (db.notification.expiration == None)
        ).select(
            db.notification.ALL, db.user_preference.val,
            left=db.user_preference.on(
                (db.user_preference.val==db.notification.id)
                &(db.user_preference.user_id==user_id)))
200 201

        query = query.find(lambda row: row.user_preference.val is None)
202
        cached = cache.ram(key, lambda: query, time_expire=0)
203

HERBERT Ryan's avatar
HERBERT Ryan committed
204
    #TODO sanitize this response
205 206
    return cached.as_json()