示例#1
0
def test_get_avatar():
    email = '*****@*****.**'
    avatar_url = get_avatar(email, size=24)
    assert avatar_url
    assert avatar_url.startswith('https://www.gravatar.com/avatar/')
    assert get_avatar('', size=24) == ''
    assert '24' in get_avatar(email, size=0)
示例#2
0
def get_user_route(request, user_id):
    """
    Get the user by their ID.
    """

    db_conn = request["db_conn"]
    user = get_user({"id": user_id}, db_conn)
    current_user = get_current_user(request)
    # Posts if in request params
    # Sets if in request params and allowed
    # Follows if in request params and allowed
    if not user:
        return abort(404)

    data = {}
    data["user"] = deliver_user(user, access="private" if current_user and user["id"] == current_user["id"] else None)

    # TODO-2 SPLITUP create new endpoints for these instead
    if "posts" in request["params"]:
        data["posts"] = [post.deliver() for post in get_posts_facade(db_conn, user_id=user["id"])]
    if "sets" in request["params"] and user["settings"]["view_sets"] == "public":
        u_sets = UserSets.get(db_conn, user_id=user["id"])
        data["sets"] = [set_.deliver() for set_ in u_sets.list_sets(db_conn)]
    if "follows" in request["params"] and user["settings"]["view_follows"] == "public":
        data["follows"] = [follow.deliver() for follow in Follow.list(db_conn, user_id=user["id"])]
    if "avatar" in request["params"]:
        size = int(request["params"]["avatar"])
        data["avatar"] = get_avatar(user["email"], size if size else None)

    return 200, data
示例#3
0
def test_get_avatar():
    """
    Expect to get a URL for a user's avatar.
    """

    email = "*****@*****.**"
    url = get_avatar(email)
    assert url.startswith("https://www.gravatar.com/avatar/" + "55502f40dc8b7c769880b10874abc9d0")
示例#4
0
def test_get_avatar():
    """
    Expect to get a URL for a user's avatar.
    """

    email = '*****@*****.**'
    url = get_avatar(email)
    assert url.startswith('https://www.gravatar.com/avatar/' +
                          '55502f40dc8b7c769880b10874abc9d0')
示例#5
0
def get_user_route(request, user_id):
  """
  Get the user by their ID.
  """

  db_conn = request['db_conn']
  user = get_user(db_conn, {'id': user_id})
  if not user:
    return abort(404, 'Tp5JnWO1SWms2lTdhw3bJQ')
  current_user = get_current_user(request)
  access = 'private' if (current_user and
                         user['id'] == current_user['id']) else None
  data = {'user': deliver_user(user, access)}
  if 'avatar' in request['params']:
    size = int(request['params']['avatar']) or None
    data['avatar'] = get_avatar(user['email'], size)
  return 200, data
示例#6
0
文件: user.py 项目: m3rryqold/sagefy
def get_user_route(request, user_id):
    """
    Get the user by their ID.
    """

    db_conn = request['db_conn']
    user = get_user({'id': user_id}, db_conn)
    current_user = get_current_user(request)
    # Posts if in request params
    # Sets if in request params and allowed
    # Follows if in request params and allowed
    if not user:
        return abort(404)

    data = {}
    data['user'] = deliver_user(user,
                                access='private' if current_user
                                and user['id'] == current_user['id'] else None)

    # TODO-2 SPLITUP create new endpoints for these instead
    if 'posts' in request['params']:
        data['posts'] = [
            post.deliver()
            for post in get_posts_facade(db_conn, user_id=user['id'])
        ]
    if ('sets' in request['params']
            and user['settings']['view_sets'] == 'public'):
        data['sets'] = [
            set_.deliver()
            for set_ in list_user_sets_entity(user['id'], {}, db_conn)
        ]
    if ('follows' in request['params']
            and user['settings']['view_follows'] == 'public'):
        data['follows'] = [
            deliver_follow(follow)
            for follow in list_follows({'user_id': user['id']}, db_conn)
        ]
    if 'avatar' in request['params']:
        size = int(request['params']['avatar'])
        data['avatar'] = get_avatar(user['email'], size if size else None)

    return 200, data
示例#7
0
def list_users_route(request):
  """
  List users by user id. Public facing route.
  """

  db_conn = request['db_conn']
  user_ids = request['params'].get('user_ids')
  if not user_ids:
    return abort(404, 'pNkIvKNRSNiXe4QtQiYdqQ')
  user_ids = user_ids.split(',')
  users = list_users_by_user_ids(db_conn, user_ids)
  if not users:
    return abort(404, 'lYgUJ4jaRv2jpcti0j-5Yw')
  size = int(request['params'].get('avatar') or 0) or None
  avatars = {
    convert_uuid_to_slug(user['id']): get_avatar(user['email'], size)
    for user in users
  }
  return 200, {
    'users': [deliver_user(user, None) for user in users],
    'avatars': avatars,
  }
示例#8
0
    close_db_connection
from framework.elasticsearch import es
from modules.util import json_prep, pick
from database.user import get_avatar

setup_db()
db_conn = make_db_connection()

# Empty the database
es.indices.delete(index='entity', ignore=[400, 404])

# Add users
users = r.table('users').run(db_conn)
for user in users:
    data = pick(json_prep(user), ('id', 'name'))
    data['avatar'] = get_avatar(user['email'])
    es.index(
        index='entity',
        doc_type='user',
        body=data,
        id=user['id'],
    )

# Add units
units = (r.table('units').filter(r.row['status'].eq('accepted')).group(
    'entity_id').max('created').default(None).ungroup().map(
        r.row['reduction']).run(db_conn))

for unit in units:
    es.index(
        index='entity',
示例#9
0
def get_posts_route(request, topic_id):
    """
    Get a reverse chronological listing of posts for given topic.
    Includes topic meta data and posts (or proposals or votes).
    Paginates.
    """

    db_conn = request['db_conn']

    # Is the topic valid?
    topic = get_topic({'id': topic_id}, db_conn)
    if not topic:
        return 404, {
            'errors': [{
                'name': 'topic_id',
                'message': c('no_topic'),
            }],
            'ref': 'pgnNbqSP1VUWkOYq8MVGPrSS',
        }

    # Pull the entity
    entity_kind = topic['entity']['kind']
    entity = get_latest_accepted(db_conn, entity_kind, topic['entity']['id'])

    # Pull all kinds of posts
    posts = get_posts_facade(db_conn,
                             limit=request['params'].get('limit') or 10,
                             skip=request['params'].get('skip') or 0,
                             topic_id=topic_id)

    # For proposals, pull up the proposal entity version
    # ...then pull up the previous version
    # ...make a diff between the previous and the proposal entity version
    diffs = {}
    entity_versions = {}
    for post_ in posts:
        if post_['kind'] == 'proposal':
            entity_version = entity_versions[post_['id']] = get_version(
                db_conn, post_['entity_version']['kind'],
                post_['entity_version']['id'])
            previous_version = get_version(db_conn,
                                           post_['entity_version']['kind'],
                                           entity_version['previous_id'])
            if previous_version:
                diffs[post_['id']] = object_diff(previous_version.deliver(),
                                                 entity_version.deliver())

    # TODO-2 SPLITUP create new endpoint for this instead
    users = {}
    for post_ in posts:
        user_id = post_['user_id']
        if user_id not in users:
            user = get_user({'id': user_id}, db_conn)
            if user:
                users[user_id] = {
                    'name': user['name'],
                    'avatar': get_avatar(user['email'], 48),
                }

    # TODO-2 SPLITUP create new endpoints for these instead
    output = {
        'topic': deliver_topic(topic),
        'posts': [p.deliver() for p in posts],
        'entity_versions':
        {p: ev.deliver('view')
         for p, ev in entity_versions.items()},
        # 'diffs': diffs,  TODO-2 this causes a circular dependency
        'users': users,
    }
    if entity:
        output[entity_kind] = entity.deliver()
    return 200, output
示例#10
0
def get_posts_route(request, topic_id):
    """
    Get a reverse chronological listing of posts for given topic.
    Includes topic meta data and posts (or proposals or votes).
    Paginates.
    """

    db_conn = request['db_conn']

    # Is the topic valid?
    topic = Topic.get(db_conn, id=topic_id)
    if not topic:
        return 404, {
            'errors': [{
                'name': 'topic_id',
                'message': c('no_topic'),
            }],
            'ref': 'pgnNbqSP1VUWkOYq8MVGPrSS',
        }

    # Pull the entity
    entity_kind = topic['entity']['kind']
    entity = get_latest_accepted(db_conn,
                                 entity_kind,
                                 topic['entity']['id'])

    # Pull all kinds of posts
    posts = get_posts_facade(
        db_conn,
        limit=request['params'].get('limit') or 10,
        skip=request['params'].get('skip') or 0,
        topic_id=topic_id
    )

    # For proposals, pull up the proposal entity version
    # ...then pull up the previous version
    # ...make a diff between the previous and the proposal entity version
    diffs = {}
    entity_versions = {}
    for post_ in posts:
        if post_['kind'] == 'proposal':
            entity_version = entity_versions[post_['id']] = get_version(
                db_conn,
                post_['entity_version']['kind'],
                post_['entity_version']['id']
            )
            previous_version = get_version(
                db_conn,
                post_['entity_version']['kind'],
                entity_version['previous_id']
            )
            if previous_version:
                diffs[post_['id']] = object_diff(previous_version.deliver(),
                                                 entity_version.deliver())

    # TODO-2 SPLITUP create new endpoint for this instead
    users = {}
    for post_ in posts:
        user_id = post_['user_id']
        if user_id not in users:
            user = get_user({'id': user_id}, db_conn)
            if user:
                users[user_id] = {
                    'name': user['name'],
                    'avatar': get_avatar(user['email'], 48),
                }

    # TODO-2 SPLITUP create new endpoints for these instead
    output = {
        'topic': topic.deliver(),
        'posts': [p.deliver() for p in posts],
        'entity_versions': {
            p: ev.deliver('view')
            for p, ev in entity_versions.items()
        },
        # 'diffs': diffs,  TODO-2 this causes a circular dependency
        'users': users,
    }
    if entity:
        output[entity_kind] = entity.deliver()
    return 200, output
示例#11
0
def es_populate():
    setup_db()
    db_conn = make_db_connection()

    # Empty the database
    es.indices.delete(index='entity', ignore=[400, 404])

    # Add users
    users = r.table('users').run(db_conn)
    for user in users:
        data = pick(json_prep(user), ('id', 'name'))
        data['avatar'] = get_avatar(user['email'])
        es.index(
            index='entity',
            doc_type='user',
            body=data,
            id=user['id'],
        )

    # Add units
    units = (r.table('units')
              .filter(r.row['status'].eq('accepted'))
              .group('entity_id')
              .max('created')
              .default(None)
              .ungroup()
              .map(r.row['reduction'])
              .run(db_conn))

    for unit in units:
        es.index(
            index='entity',
            doc_type='unit',
            body=json_prep(unit),
            id=unit['entity_id'],
        )

    # Add cards
    cards = (r.table('cards')
              .filter(r.row['status'].eq('accepted'))
              .group('entity_id')
              .max('created')
              .default(None)
              .ungroup()
              .map(r.row['reduction'])
              .run(db_conn))
    for card in cards:
        es.index(
            index='entity',
            doc_type='card',
            body=json_prep(card),
            id=card['entity_id'],
        )

    # Add subjects
    subjects = (r.table('subjects')
                 .filter(r.row['status'].eq('accepted'))
                 .group('entity_id')
                 .max('created')
                 .default(None)
                 .ungroup()
                 .map(r.row['reduction'])
                 .run(db_conn))
    for subject in subjects:
        es.index(
            index='entity',
            doc_type='subject',
            body=json_prep(subject),
            id=subject['entity_id'],
        )

    # Add topics
    topics = r.table('topics').run(db_conn)
    for topic in topics:
        es.index(
            index='entity',
            doc_type='topic',
            body=json_prep(topic),
            id=topic['id'],
        )

    # Add posts
    posts = r.table('posts').run(db_conn)
    for post in posts:
        data = json_prep(post)
        topic = (r.table('topics')
                 .get(data['topic_id'])
                 .run(db_conn))
        user = (r.table('users')
                 .get(data['user_id'])
                 .run(db_conn))
        data['topic'] = json_prep(topic)
        data['user'] = pick(json_prep(user), ('id', 'name'))
        es.index(
            index='entity',
            doc_type='post',
            body=data,
            id=post['id'],
        )

    close_db_connection(db_conn)
示例#12
0
    close_db_connection
from framework.elasticsearch import es
from modules.util import json_prep, pick
from database.user import get_avatar

setup_db()
db_conn = make_db_connection()

# Empty the database
es.indices.delete(index='entity', ignore=[400, 404])

# Add users
users = r.table('users').run(db_conn)
for user in users:
    data = pick(json_prep(user), ('id', 'name'))
    data['avatar'] = get_avatar(user['email'])
    es.index(
        index='entity',
        doc_type='user',
        body=data,
        id=user['id'],
    )

# Add units
units = (r.table('units')
          .filter(r.row['status'].eq('accepted'))
          .group('entity_id')
          .max('created')
          .default(None)
          .ungroup()
          .map(r.row['reduction'])
示例#13
0
def es_populate():
  db_conn = make_db_connection()

  # Empty the database
  es.indices.delete(index='entity', ignore=[400, 404])

  # Add users
  cur = db_conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
  with cur:
    cur.execute("SELECT * FROM users;")
    data = cur.fetchall()
    users = [row for row in data]
    db_conn.commit()
  for user in users:
    data = pick(json_prep(user), ('id', 'name'))
    data['avatar'] = get_avatar(user['email'])
    es.index(
      index='entity',
      doc_type='user',
      body=data,
      id=convert_uuid_to_slug(user['id']),
    )

  # Add units
  cur = db_conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
  with cur:
    cur.execute("""
      SELECT DISTINCT ON (entity_id) *
      FROM units
      WHERE status = 'accepted'
      ORDER BY entity_id, created DESC;
    """)
    data = cur.fetchall()
    units = [row for row in data]
    db_conn.commit()
  for unit in units:
    es.index(
      index='entity',
      doc_type='unit',
      body=json_prep(unit),
      id=convert_uuid_to_slug(unit['entity_id']),
    )

  # Add cards
  cur = db_conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
  with cur:
    cur.execute("""
      SELECT DISTINCT ON (entity_id) *
      FROM cards
      WHERE status = 'accepted'
      ORDER BY entity_id, created DESC;
    """)
    data = cur.fetchall()
    cards = [row for row in data]
    db_conn.commit()
  for card in cards:
    es.index(
      index='entity',
      doc_type='card',
      body=json_prep(card),
      id=convert_uuid_to_slug(card['entity_id']),
    )

  # Add subjects
  cur = db_conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
  with cur:
    cur.execute("""
      SELECT DISTINCT ON (entity_id) *
      FROM subjects
      WHERE status = 'accepted'
      ORDER BY entity_id, created DESC;
    """)
    data = cur.fetchall()
    subjects = [row for row in data]
    db_conn.commit()
  for subject in subjects:
    es.index(
      index='entity',
      doc_type='subject',
      body=json_prep(subject),
      id=convert_uuid_to_slug(subject['entity_id']),
    )

  """
  TODO-1 fix these
  # Add topics
  topics = r.table('topics').run(db_conn)
  for topic in topics:
    es.index(
      index='entity',
      doc_type='topic',
      body=json_prep(topic),
      id=topic['id'],
    )

  # Add posts
  posts = r.table('posts').run(db_conn)
  for post in posts:
    data = json_prep(post)
    topic = (r.table('topics')
         .get(data['topic_id'])
         .run(db_conn))
    user = (r.table('users')
         .get(data['user_id'])
         .run(db_conn))
    data['topic'] = json_prep(topic)
    data['user'] = pick(json_prep(user), ('id', 'name'))
    es.index(
      index='entity',
      doc_type='post',
      body=data,
      id=post['id'],
    )
  """

  close_db_connection(db_conn)