def put()

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


def put(id, icon, user, cache, apps):
    debug('icons.py::put::id', id)
    debug('icons.py::put::icon', icon)

    # Get the requested app
    app = apps.get(id)
    if isNull(app):
        debug('icons.py::put', 'app not found', id)
        return False

    # Check app author
    if author(app) != user.get(()) and user.get(()) != 'admin':
        debug('icons.py::put', 'different author', author(app))
        return False

    # Get image and token from input icon
    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(icon))
    tok = token(content(icon))

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

        # Token alone, store token with existing image, if any
        if isNull(img):
            eicon = cache.get(iconid(id))
            eimg = None if isNull(eicon) else image(content(eicon))
            if isNull(eimg):
                iconentry = mkentry(title(app), car(id), author(app), now(), ("'icon", ("'token", tok)))
                debug('icons.py::put::iconentry', iconentry)
                return cache.put(iconid(id), iconentry)

            debug('icons.py::put::eimg', eimg)
            iconentry = mkentry(title(app), car(id), author(app), now(), ("'icon", ("'image", eimg), ("'token", tok)))
            debug('icons.py::put::iconentry', iconentry)
            return cache.put(iconid(id), iconentry)

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

        iconentry = mkentry(title(app), car(id), author(app), now(), ("'icon", ("'image", img)))
        debug('icons.py::put::iconentry', iconentry)
        return cache.put(iconid(id), iconentry)

    # Update icon image
    if not isNull(img):
        debug('icons.py::put::img', img)
        iconentry = mkentry(title(app), car(id), author(app), now(), ("'icon", ("'image", img)))
        debug('icons.py::put::iconentry', iconentry)
        rc = cache.put(iconid(id), iconentry)
        if rc == False:
            return False

        # Update the app's updated date
        return apps.put(id, app)

    # Put default empty icon
    iconentry = mkentry(title(app), car(id), author(app), now(), ())
    debug('icons.py::put::iconentry', iconentry)
    rc = cache.put(iconid(id), iconentry)
    if rc == False:
        return False

    # Update the app's updated date
    return apps.put(id, app)