Esempio n. 1
0
def storymap_create(user):
    """Create a storymap"""
    try:
        title, data = _request_get_required('title', 'd')

        id = _make_storymap_id(user, title)

        key_prefix = storage.key_prefix(user['uid'], id)

        content = json.loads(data)
        storage.save_json(key_prefix+'draft.json', content)

        user['storymaps'][id] = {
            'id': id,
            'title': title,
            'draft_on': _utc_now(),
            'published_on': ''
        }
        _user.save(user)

        _write_embed_draft(key_prefix, user['storymaps'][id])

        return jsonify({'id': id})
    except Exception, e:
        traceback.print_exc()
        return jsonify({'error': str(e)})
Esempio n. 2
0
def _import_metadata(user, data):
    """Add a StoryMap to a user based on imported metadata"""

    id = _make_storymap_id(user, data['title'])
    data['id'] = id
    user['storymaps'][id] = data
    _user.save(user)

    return id
Esempio n. 3
0
def storymap_migrate_done(user):
    """Flag user as migrated"""
    try:
        user['migrated'] = 1
        _user.save(user)

        return jsonify({})
    except Exception, e:
        traceback.print_exc()
        return jsonify({'error': str(e)})
Esempio n. 4
0
def google_auth_verify():
    """Finalize google authorization"""
    try:
        if 'error' in request.args:
            raise Exception(_format_err(
                'Error getting authorization', request.args.get('error')))

        code = _request_get_required('code')

        flow = OAuth2WebServerFlow(
            settings.GOOGLE_CLIENT_ID,
            settings.GOOGLE_CLIENT_SECRET,
            _GOOGLE_OAUTH_SCOPES,
            redirect_uri='https://'+request.host+url_for('google_auth_verify')
        )
        credentials = flow.step2_exchange(code)
        # ^ this is an oauth2client.client.OAuth2Credentials object

        # Get user info
        userinfo = google.get_userinfo(
            google.get_userinfo_service(credentials))
        if not userinfo:
            raise Exception('Could not get Google user info')

        info = {
            'id': userinfo.get('id'),
            'name': userinfo.get('name'),
            'credentials': credentials.to_json()
        }
        if not info['id']:
            raise Exception('Could not get Google user ID')

        # Upsert user record
        uid = _get_uid('google:'+info['id'])

        user = _user.find_one({'uid': uid})
        if user:
            user['google'] = info
        else:
            user = {
                'uid': uid,
                'migrated': 0,
                'storymaps': {},
                'google': info
            }
        user['uname'] = info['name']
        _user.save(user)

        # Update session
        session['uid'] = uid

        return redirect(url_for('select'))
    except Exception, e:
        traceback.print_exc()
        return jsonify({'error': str(e)})
Esempio n. 5
0
def storymap_migrate(user):
    """
    Migrate a storymap
    @title = storymap title
    @url = storymap base url
    @draft_on = ...
    @published_on = ...
    @file_list = json encoded list of file names
    """
    try:
        title, src_url, draft_on, file_list_json = _request_get_required(
            'title', 'url', 'draft_on', 'file_list')
        published_on = _request_get('published_on')

        file_list = json.loads(file_list_json)

        dst_id = _make_storymap_id(user, title)
        dst_key_prefix = storage.key_prefix(user['uid'], dst_id)
        dst_url = settings.AWS_STORAGE_BUCKET_URL+dst_key_prefix
        dst_img_url = dst_url+'_images/'

        re_img = re.compile(r'.*\.(png|gif|jpg|jpeg)$', re.I)
        re_src = re.compile(r'%s' % src_url)

        for file_name in file_list:
            file_url = "%s%s" % (src_url, file_name)

            if file_name.endswith('.json'):
                key_name = storage.key_name(user['uid'], dst_id, file_name)
                r = requests.get(file_url)
                storage.save_json(key_name, re_src.sub(dst_img_url, r.text))
            elif re_img.match(file_name):
                key_name = storage.key_name(user['uid'], dst_id, '_images', file_name)
                storage.save_from_url(key_name, file_url)
            else:
                continue # skip

        user['storymaps'][dst_id] = {
            'id': dst_id,
            'title': title,
            'draft_on': draft_on,
            'published_on': published_on
        }
        _user.save(user)

        _write_embed_draft(dst_key_prefix, user['storymaps'][dst_id])
        if published_on:
            _write_embed_published(dst_key_prefix, user['storymaps'][dst_id])

        return jsonify(user['storymaps'][dst_id])
    except Exception, e:
        traceback.print_exc()
        return jsonify({'error': str(e)})
Esempio n. 6
0
def storymap_delete(user, id):
    """Delete storymap"""
    try:
        key_name = storage.key_name(user['uid'], id)
        key_list, marker = storage.list_keys(key_name, 50)
        for key in key_list:
            storage.delete(key.name);

        del user['storymaps'][id]
        _user.save(user)

        return jsonify({})
    except Exception, e:
        traceback.print_exc()
        return jsonify({'error': str(e)})
Esempio n. 7
0
def storymap_delete(user, id):
    """Delete storymap"""
    try:
        key_prefix = storage.key_prefix(user['uid'], id)
        key_list, marker = storage.list_keys(key_prefix, 50)
        for key in key_list:
            storage.delete(key.name)

        del user['storymaps'][id]
        _user.save(user)

        return jsonify({})
    except Exception, e:
        traceback.print_exc()
        return jsonify({'error': str(e)})
Esempio n. 8
0
def storymap_save(user, id):
    """Save draft storymap"""
    try:
        data = _request_get_required("d")

        key_name = storage.key_name(user["uid"], id, "draft.json")
        content = json.loads(data)
        storage.save_json(key_name, content)

        user["storymaps"][id]["draft_on"] = _utc_now()
        _user.save(user)

        return jsonify({"meta": user["storymaps"][id]})
    except storage.StorageException, e:
        traceback.print_exc()
        return jsonify({"error": str(e), "error_detail": e.detail})
Esempio n. 9
0
def storymap_save(user, id):
    """Save draft storymap"""
    try:
        data = _request_get_required('d')

        key_name = storage.key_name(user['uid'], id, 'draft.json')
        content = json.loads(data)
        storage.save_json(key_name, content)

        user['storymaps'][id]['draft_on'] = _utc_now()
        _user.save(user)

        return jsonify({'meta': user['storymaps'][id]})
    except storage.StorageException, e:
        traceback.print_exc()
        return jsonify({'error': str(e), 'error_detail': e.detail})
Esempio n. 10
0
def storymap_migrate(user):
    """
    Migrate a storymap
    @title = storymap title
    @url = storymap base url
    @draft_on = ...
    @published_on = ...
    @file_list = json encoded list of file names
    """
    try:
        title, src_url, draft_on, file_list_json = _request_get_required("title", "url", "draft_on", "file_list")
        published_on = _request_get("published_on")

        file_list = json.loads(file_list_json)

        dst_id = _make_storymap_id(user, title)
        dst_key_prefix = storage.key_prefix(user["uid"], dst_id)
        dst_url = settings.AWS_STORAGE_BUCKET_URL + dst_key_prefix
        dst_img_url = dst_url + "_images/"

        re_img = re.compile(r".*\.(png|gif|jpg|jpeg)$", re.I)
        re_src = re.compile(r"%s" % src_url)

        for file_name in file_list:
            file_url = "%s%s" % (src_url, file_name)

            if file_name.endswith(".json"):
                key_name = storage.key_name(user["uid"], dst_id, file_name)
                r = requests.get(file_url)
                storage.save_json(key_name, re_src.sub(dst_img_url, r.text))
            elif re_img.match(file_name):
                key_name = storage.key_name(user["uid"], dst_id, "_images", file_name)
                storage.save_from_url(key_name, file_url)
            else:
                continue  # skip

        user["storymaps"][dst_id] = {"id": dst_id, "title": title, "draft_on": draft_on, "published_on": published_on}
        _user.save(user)

        _write_embed_draft(dst_key_prefix, user["storymaps"][dst_id])
        if published_on:
            _write_embed_published(dst_key_prefix, user["storymaps"][dst_id])

        return jsonify(user["storymaps"][dst_id])
    except Exception, e:
        traceback.print_exc()
        return jsonify({"error": str(e)})
Esempio n. 11
0
def storymap_copy(user, id):
    """
    Copy storymap
    @id = storymap to copy
    @title = name of new copy
    """
    try:
        title = _request_get_required('title')
        dst_id = _make_storymap_id(user, title)

        src_key_prefix = storage.key_prefix(user['uid'], id)
        dst_key_prefix = storage.key_prefix(user['uid'], dst_id)

        src_re = re.compile(r'%s' % src_key_prefix)

        src_key_list, more = storage.list_keys(src_key_prefix, 999, '')
        for src_key in src_key_list:
            file_name = src_key.name.split(src_key_prefix)[-1]
            dst_key_name = "%s%s" % (dst_key_prefix, file_name)

            if file_name.endswith('.json'):
                json_string = src_key.get_contents_as_string()
                storage.save_json(dst_key_name,
                    src_re.sub(dst_key_prefix, json_string))
            else:
                storage.copy_key(src_key.name, dst_key_name)

        # Update meta
        user['storymaps'][dst_id] = {
            'id': dst_id,
            'title': title,
            'draft_on': user['storymaps'][id]['draft_on'],
            'published_on': user['storymaps'][id]['published_on']
        }
        _user.save(user)

        # Write new embed pages
        _write_embed_draft(dst_key_prefix, user['storymaps'][dst_id])
        if user['storymaps'][dst_id].get('published_on'):
            _write_embed_published(dst_key_prefix, user['storymaps'][dst_id])

        return jsonify(user['storymaps'][dst_id])
    except Exception, e:
        traceback.print_exc()
        return jsonify({'error': str(e)})
Esempio n. 12
0
def storymap_publish(user, id):
    """Save published storymap"""
    try:
        data = _request_get_required("d")

        key_prefix = storage.key_prefix(user["uid"], id)
        content = json.loads(data)
        storage.save_json(key_prefix + "published.json", content)

        user["storymaps"][id]["published_on"] = _utc_now()
        _user.save(user)

        _write_embed_published(key_prefix, user["storymaps"][id])

        return jsonify({"meta": user["storymaps"][id]})
    except storage.StorageException, e:
        traceback.print_exc()
        return jsonify({"error": str(e), "error_detail": e.detail})
Esempio n. 13
0
def storymap_publish(user, id):
    """Save published storymap"""
    try:
        data = _request_get_required('d')

        key_prefix = storage.key_prefix(user['uid'], id)
        content = json.loads(data)
        storage.save_json(key_prefix+'published.json', content)

        user['storymaps'][id]['published_on'] = _utc_now()
        _user.save(user)

        _write_embed_published(key_prefix, user['storymaps'][id])

        return jsonify({'meta': user['storymaps'][id]})
    except storage.StorageException, e:
        traceback.print_exc()
        return jsonify({'error': str(e), 'error_detail': e.detail})
Esempio n. 14
0
def storymap_copy(user, id):
    """
    Copy storymap
    @id = storymap to copy
    @title = name of new copy
    """
    try:
        title = _request_get_required("title")
        dst_id = _make_storymap_id(user, title)

        src_key_prefix = storage.key_prefix(user["uid"], id)
        dst_key_prefix = storage.key_prefix(user["uid"], dst_id)

        src_re = re.compile(r"%s" % src_key_prefix)

        src_key_list, more = storage.list_keys(src_key_prefix, 999, "")
        for src_key in src_key_list:
            file_name = src_key.name.split(src_key_prefix)[-1]
            dst_key_name = "%s%s" % (dst_key_prefix, file_name)

            if file_name.endswith(".json"):
                json_string = src_key.get_contents_as_string()
                storage.save_json(dst_key_name, src_re.sub(dst_key_prefix, json_string))
            else:
                storage.copy_key(src_key.name, dst_key_name)

        # Update meta
        user["storymaps"][dst_id] = {
            "id": dst_id,
            "title": title,
            "draft_on": user["storymaps"][id]["draft_on"],
            "published_on": user["storymaps"][id]["published_on"],
        }
        _user.save(user)

        # Write new embed pages
        _write_embed_draft(dst_key_prefix, user["storymaps"][dst_id])
        if user["storymaps"][dst_id].get("published_on"):
            _write_embed_published(dst_key_prefix, user["storymaps"][dst_id])

        return jsonify(user["storymaps"][dst_id])
    except Exception, e:
        traceback.print_exc()
        return jsonify({"error": str(e)})
Esempio n. 15
0
def google_auth_verify():
    """Finalize google authorization"""
    try:
        if "error" in request.args:
            raise Exception(_format_err("Error getting authorization", request.args.get("error")))

        code = _request_get_required("code")

        flow = OAuth2WebServerFlow(
            settings.GOOGLE_CLIENT_ID,
            settings.GOOGLE_CLIENT_SECRET,
            _GOOGLE_OAUTH_SCOPES,
            redirect_uri="https://" + request.host + url_for("google_auth_verify"),
        )
        credentials = flow.step2_exchange(code)
        # ^ this is an oauth2client.client.OAuth2Credentials object

        # Get user info
        userinfo = google.get_userinfo(google.get_userinfo_service(credentials))
        if not userinfo:
            raise Exception("Could not get Google user info")

        info = {"id": userinfo.get("id"), "name": userinfo.get("name"), "credentials": credentials.to_json()}
        if not info["id"]:
            raise Exception("Could not get Google user ID")

        # Upsert user record
        uid = _get_uid("google:" + info["id"])

        user = _user.find_one({"uid": uid})
        if user:
            user["google"] = info
        else:
            user = {"uid": uid, "migrated": 0, "storymaps": {}, "google": info}
        user["uname"] = info["name"]
        _user.save(user)

        # Update session
        session["uid"] = uid

        return redirect(url_for("select"))
    except Exception, e:
        traceback.print_exc()
        return jsonify({"error": str(e)})
Esempio n. 16
0
def storymap_update_meta(user, id):
    """Update storymap meta value"""
    try:
        key, value = _request_get_required("key", "value")

        user["storymaps"][id][key] = value
        _user.save(user)

        key_prefix = storage.key_prefix(user["uid"], id)

        if key in ["title", "description", "image_url"]:
            _write_embed_draft(key_prefix, user["storymaps"][id])

            if user["storymaps"][id].get("published_on"):
                _write_embed_published(key_prefix, user["storymaps"][id])

        return jsonify(user["storymaps"][id])
    except Exception, e:
        traceback.print_exc()
        return jsonify({"error": str(e)})
Esempio n. 17
0
def storymap_update_meta(user, id):
    """Update storymap meta value"""
    try:
        key, value = _request_get_required('key', 'value')

        user['storymaps'][id][key] = value
        _user.save(user)

        key_prefix = storage.key_prefix(user['uid'], id)

        if key in ['title', 'description', 'image_url']:
            _write_embed_draft(key_prefix, user['storymaps'][id])

            if user['storymaps'][id].get('published_on'):
                _write_embed_published(key_prefix, user['storymaps'][id])

        return jsonify(user['storymaps'][id])
    except Exception, e:
        traceback.print_exc()
        return jsonify({'error': str(e)})
Esempio n. 18
0
def storymap_create(user):
    """Create a storymap"""
    try:
        title, data = _request_get_required("title", "d")

        id = _make_storymap_id(user, title)

        key_prefix = storage.key_prefix(user["uid"], id)

        content = json.loads(data)
        storage.save_json(key_prefix + "draft.json", content)

        user["storymaps"][id] = {"id": id, "title": title, "draft_on": _utc_now(), "published_on": ""}
        _user.save(user)

        _write_embed_draft(key_prefix, user["storymaps"][id])

        return jsonify({"id": id})
    except Exception, e:
        traceback.print_exc()
        return jsonify({"error": str(e)})
Esempio n. 19
0
def google_auth_verify():
    """Finalize google authorization"""
    try:
        if 'error' in request.args:
            raise Exception(_format_err(
                'Error getting authorization', request.args.get('error')))

        code = _request_get_required('code')

        flow = OAuth2WebServerFlow(
            settings.GOOGLE_CLIENT_ID,
            settings.GOOGLE_CLIENT_SECRET,
            _GOOGLE_OAUTH_SCOPES,
            redirect_uri=_build_oauth_redirect(request, url_for('google_auth_verify'))
        )
        credentials = flow.step2_exchange(code)
        # ^ this is an oauth2client.client.OAuth2Credentials object

        # Get user info
        userinfo = google.get_userinfo(
            google.get_userinfo_service(credentials))
        if not userinfo:
            raise Exception('Could not get Google user info')

        info = {
            'id': userinfo.get('id'),
            'name': userinfo.get('name'),
            'credentials': credentials.to_json()
        }
        if not info['id']:
            raise Exception('Could not get Google user ID')

        if 'storymap.knilab.com' in domains and not info['id'] in allowed_ids:
            print('User id not in ALLOWED_IDS:  %s ' % info['id'])
            raise Exception('You are not authorized to access this page. Please send the following information to [email protected]: storymap.knilab.com unauthorized %s' % info['id'])

        # Upsert user record
        uid = _get_uid('google:'+info['id'])

        user = _user.find_one({'uid': uid})
        if user:
            user['google'] = info
        else:
            user = {
                'uid': uid,
                'migrated': 0,
                'storymaps': {},
                'google': info
            }
        user['uname'] = info['name']
        _user.save(user)

        # Update session
        session['uid'] = uid
        url = url_for('select')

        app.logger.info("google_auth_verify url: {}".format(url))
        return redirect(url)
    except Exception, e:
        traceback.print_exc()
        return jsonify({'error': str(e)})