Exemple #1
0
def rename_user(from_user, to_user):
    user = (db.User.named(from_user)
            if type(from_user) == 'string' else from_user)
    user.update(updated=False, name=to_user)
    for r in db.Expr.search(mq(owner=user.id)):
        r.update(updated=False, owner_name=to_user)
    for r in db.Feed.search(mq(initiator=user.id)):
        r.update(updated=False, initiator_name=to_user)
Exemple #2
0
    def __new__(klass, kind, amt, from_user=None, to_user=None):
        """ Move money from one user account to another.
        Args:
            from (User): take from from_user's moneys
            to (User): put into to_user's moneys
            amt (float): dolar ammount
            kind (int): must be 1, 2, or 3 - Deposit, Debit, Transfer
        """

        # make sure from and to users actually have accounts:
        from_user.set_if(mq().exists('moneys', False), DefaultMoneys)
        to_user.set_if(mq().exists('moneys', False), DefaultMoneys)
Exemple #3
0
def merge_collection(db_remote, cn, do_write=False):
    remote = db_remote.mdb[cn]
    local = db.mdb[cn]

    # determine sort key depending on if index for "updated" field exists
    sort_attr = 'updated' if True in [
        index['key'][0][0] == 'updated'
        for index in remote.index_information().values()
    ] else '_id'
    newest_local = local.find().sort(sort_attr, -1).limit(1)[0]
    cur = remote.find(mq().gt(sort_attr,
                              newest_local[sort_attr])).sort(sort_attr, 1)

    print 'merging %d records from %s' % (cur.count(), cn)
    if not do_write: return

    count = 0
    for r in cur:
        try:
            local.update({'_id': r['_id']}, r, True)
        except DuplicateKeyError:
            print r['_id'], 'duplicate!! shits'
        if not count % 100: print r[sort_attr]
        count += 1
    print 'finished merging %d records from %s' % (count, cn)
    counts[cn] = count
Exemple #4
0
def switch_user(from_user, to_user, session_id=None, from_id=None):
    from_user = get_entity(db.User, from_user)
    to_user = get_entity(db.User, to_user)
    if not from_user or not to_user:
        print('User not found')
        return False
    session = (db.Session.fetch(session_id) if session_id else db.Session.last(
        mq(user=from_user.id)))
    session.update(user=to_user.id)
Exemple #5
0
def get_exprs(query_and={}):
    time_last = now() - 10 * 60  # Don't re-snapshot within 10 minutes
    q = mq(**snapshots_pending(time_last))

    and_exp = []
    if query_and: and_expr.append(query_and)
    if test:
        and_exp.append({'owner_name': 'abram'})
    if and_exp:
        and_exp.append(q)
        q = {'$and': and_exp}

    expressions_to_snapshot = db.Expr.search(q, sort=[('updated', -1)])
    return expressions_to_snapshot
Exemple #6
0
def follow_count(d, q={}):
    q.update(
        mq(class_name='Star', entity_class='User').ne(
            'entity',
            '4e0fcd5aba28392572000044'))  # exclude default newhive follow
    return db.Feed.count(mq(q).day('created', d))
Exemple #7
0
def user_count(days_ago, days=1, query={}):
    return db.User.count(mq(query).day('created', days_ago, days))
Exemple #8
0
def expr_count(days_ago, days=1, query={}):
    return db.Expr.count(mq(query).day('created', days_ago, days))
Exemple #9
0
def recent_snapshot_fails(days=1):
    return db.Expr.search(mq().bt('snapshot_fails', 5,
                                  12).gt('updated',
                                         now() - days * 86400))
def migrate_exprs_name():
    return Apply.apply_continue(expr_name, db.Expr,
                                mq().js('this.name.length > 80'))
Exemple #11
0
    def admin_query(self, tdata, db_args={}, **kwargs):
        if not self.flags.get('admin'):
            return {}

        parse = json.loads
        args = tdata.request.args
        out = args.get('out', 'cards')
        collection = collection_of(self.db,
                                   args.get('collection', 'Expr').capitalize())
        q = mq(parse(args.get('q', '{}')))
        if args.get('day'):
            (time_prop, days_ago, day_span) = args['day'].split(',')
            days_ago, day_span = float(days_ago), float(day_span)
            q.day(time_prop, days_ago, day_span)
        fields = None
        if args.get('fields'): fields = args['fields'].split(',')
        db_args.update(spec=q,
                       sort=args.get('sort', 'created'),
                       order=parse(args.get('order', '-1')),
                       limit=parse(args.get('limit', '0' if fields else '20')),
                       fields=fields)
        help = """
Query parameters:
    q: database query, e.g., {"owner_name": "zach"}
    day: time_property,days_ago,day_span
    sort: default updated
    order: default -1
    fields: prop1,prop2,prop3 (outputs fields in CSV format)
    collection: 'user' | 'feed' | 'trash' | 'expr' (default)
    special: 'top_tags' | 'top_lovers' |  None
    help: ...this...

Examples:
    Get list of emails from recent signups in the last 14 days
        /home/admin/query?day=created,14,14&collection=user&fields=email,name,fullname
    Show users with given email
        /home/admin/query?q={"email":"*****@*****.**"}&collection=user
"""

        # Special cases
        special = args.get('special')
        if special == 'top_tags':
            if tdata.request.args.get('help', False) != False:
                return {'text_result': 'limit: default 1000'}
            db_args.update(limit=parse(args.get('limit', '1000')))
            common = self.db.tags_by_frequency(collection=collection,
                                               **db_args)
            return {
                'data': "\n".join([x[0] + ": " + str(x[1]) for x in common])
            }
        elif special == 'top_lovers':
            if tdata.request.args.get('help', False) != False:
                return {'text_result': 'last_days: default 30'}
            last_days = parse(args.get('last_days', '30'))
            loves_by_users = Counter()
            for r in self.db.Feed.search(
                    mq(class_name='Star',
                       entity_class='Expr').gt('created',
                                               now() - 86400 * last_days)):
                loves_by_users[r['initiator_name']] += 1
            resp = json.dumps(loves_by_users.most_common())
            return {'text_result': re.sub(r'\],', '],\n', resp)}
        if tdata.request.args.get('help', False) != False:
            return {'data': help}

        data = {}
        res = collection.paginate(**db_args)
        if fields:
            rows = [[r.get(k, '') for k in fields] for r in res]
            data['data'] = '\n'.join([','.join(row) for row in rows])
        else:
            data['cards'] = list(res)
        return data
Exemple #12
0
def snapshots_pending(time_last=False):
    if not time_last: time_last = now()
    return mq(snapshot_needed=True).js(
        '!this.password && (!this.snapshot_fails || this.snapshot_fails < 6)' +
        '&& (!this.snapshot_fail_time || ' + 'this.snapshot_fail_time < ' +
        str(time_last) + ')')