notification.py 7.36 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
# Deprecated
16 17 18 19 20 21 22 23 24 25 26
def index():
    if not auth.is_admin() :
        res = {"message": ACCESS_DENIED}
        log.error(res)
        return gluon.contrib.simplejson.dumps(res, separators=(',',':'))    

    query = db(db.notification).select(orderby=~db.notification.id)

    return dict(message="Notifications",
        query=query)

27
def info():
28
    user_id = auth.user.id if auth.user else None    
29 30 31 32

    query = None
    if request.vars['id']:
        query = db.notification[request.vars['id']]
33 34 35 36 37 38 39 40 41 42
    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'])

43 44
            # Clear cache of this user
            cache.ram.clear(regex=NOTIFICATION_CACHE_PREFIX + str(user_id))
45

46
    notifications = db(db.notification).select(orderby=~db.notification.id)
47 48 49
    if not auth.is_admin():
         notifications = notifications.find(lambda row: row.expiration >= date.today())
         
50 51
    return dict(message="Notifications",
                query=query,
52
                notifications=notifications)
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

# 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 = ""
71 72
    if request.vars['title'] =="":
        error += "title needed, "
73 74 75 76 77 78
    if request.vars["message_content"] == "" :
        error += "message content needed, "
    if request.vars["message_type"] == "" :
        error += "type needed, "
    if request.vars["priority"] == "" :
        error += "priority needed, "
79 80 81
    if request.vars["expiration"] == "" :
        erro += "expiration date required"
    else:
82
        try:
83
            datetime.strptime(""+request.vars['expiration'], '%Y-%m-%d')
84 85 86 87
        except ValueError:
            error += "date (wrong format)"

    if error=="" :
88
        id = db.notification.insert(title=request.vars["title"],
89 90 91 92
                            message_content=XML(request.vars["message_content"], sanitize=True).xml(),
                            message_type=request.vars["message_type"],
                            priority=request.vars["priority"],
                            expiration=request.vars["expiration"],
93 94
                            creator=auth.user_id,
                            creation_datetime=datetime.now())
95 96 97 98 99

        res = {"redirect": "notification/index",
               "args" : { "id" : id },
               "message": "notification added"}
        log.info(res)
100 101
        # Clear cache of all notifications
        cache.ram.clear(regex=NOTIFICATION_CACHE_PREFIX + '*')
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
        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, "
134 135 136
    if request.vars["expiration"] == "" :
        error += "expiration date required"
    else:
137
        try:
138
            datetime.strptime(""+request.vars['expiration'], '%Y-%m-%d')
139 140 141 142
        except ValueError:
            error += "date (wrong format)"

    if error=="" :
143
        db.notification[request.vars['id']] = dict(title=request.vars["title"],
144 145 146 147
                            message_content=XML(request.vars["message_content"], sanitize=True).xml(),
                            message_type=request.vars["message_type"],
                            priority=request.vars["priority"],
                            expiration=request.vars["expiration"])
148

149 150 151
        db((db.user_preference.val==request.vars['id'])
            &(db.user_preference.preference=='mail')).delete()

152 153 154 155
        res = {"redirect": "notification/index",
               "args" : { "id" : request.vars['id'] },
               "message": "notification updated"}
        log.info(res)
156 157
        # Clear cache of all notifications
        cache.ram.clear(regex=NOTIFICATION_CACHE_PREFIX + '*')
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
        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()
174 175 176
    # Cascade the notification deletion onto associated preferences
    db((db.user_preference.val==request.vars['id'])
        &(db.user_preference.preference=='mail')).delete()
177 178 179 180
    res = {"redirect": "notification/index",
               "success": "true",
               "message": "notification " + request.vars['id'] + " deleted"}
    log.info(res)
181 182
    # Clear cache of all notifications
    cache.ram.clear(regex=NOTIFICATION_CACHE_PREFIX + '*')
183 184
    return gluon.contrib.simplejson.dumps(res, separators=(',',':')) 

185
#
186 187
def get_active_notifications():
    today = date.today()
188
    user_id = auth.user.id if auth.user else None    
189 190 191 192 193
    if user_id:
        key = NOTIFICATION_CACHE_PREFIX + str(user_id)
    else:
        key = NOTIFICATION_CACHE_PREFIX

194 195
    # Force retrieval of the cache even if no value is set 
    cached = cache.ram(key, lambda: None, time_expire=None)
196 197
    if not cached:
        # No cache found: query database
198 199 200 201 202 203 204
        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)))
205 206

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

HERBERT Ryan's avatar
HERBERT Ryan committed
209
    #TODO sanitize this response
210 211
    return cached.as_json()