def put()

in hosting/server/pictures.py [0:0]


def put(id, picture, user, cache):
    debug('pictures.py::put::id', id)
    debug('pictures.py::put::picture', picture)

    picid = user.get(()) if isNull(id) else car(id)

    # Only the admin can update other user's pictures
    if picid != user.get(()) and user.get(()) != 'admin':
        debug('pictures.py::put', 'not owner or admin', user.get(()))
        return False

    # Get image and token from input picture
    def image(c):
        img = assoc("'image", c)
        return None if isNull(img) else urlto50x50jpeg(cadr(img))
    def token(c):
        tok = assoc("'token", c)
        return None if isNull(tok) else cadr(tok)
    img = image(content(picture))
    tok = token(content(picture))

    # Update the picture
    # Put with an upload token
    if not isNull(tok):
        debug('pictures.py::put::token', tok)

        # Token alone, store token with existing image, if any
        if isNull(img):
            epicture = cache.get(pictureid(picid))
            eimg = None if isNull(epicture) else image(content(epicture))
            if isNull(eimg):
                picentry = mkentry(title(picture), picid, picid, now(), ("'picture", ("'token", tok)))
                debug('pictures.py::put::picentry', picentry)
                return cache.put(pictureid(picid), picentry)

            debug('pictures.py::put::eimg', eimg)
            picentry = mkentry(title(picture), picid, picid, now(), ("'picture", ("'image", eimg), ("'token", tok)))
            debug('pictures.py::put::picentry', picentry)
            return cache.put(pictureid(picid), picentry)

        # Token plus image, put image if token is valid, removing the token
        debug('pictures.py::put::img', img)
        epicture = cache.get(pictureid(picid))
        etok = None if isNull(epicture) else token(content(epicture))
        debug('pictures.py::put::etok', etok)
        if isNull(etok) or tok != etok:
            debug('pictures.py::put', 'invalid token', tok)
            return False

        picentry = mkentry(title(picture), picid, picid, now(), ("'picture", ("'image", img)))
        debug('pictures.py::put::picentry', picentry)
        return cache.put(pictureid(picid), picentry)

    # Update picture image
    if not isNull(img):
        debug('pictures.py::put::img', img)
        picentry = mkentry(title(picture), picid, picid, now(), ("'picture", ("'image", img)))
        debug('pictures.py::put::picentry', picentry)
        return cache.put(pictureid(picid), picentry)

    # Put default empty picture
    picentry = mkentry(title(picture), picid, picid, now(), ())
    debug('pictures.py::put::picentry', picentry)
    return cache.put(pictureid(picid), picentry)