Example #1
0
def headline(rw):
    form = Form(rw)
    uuid = form.get('uuid')
    mydb, user_id = get_userspace_by_permission(1)
    if uuid is None:
        article = mydb.cursor().execute(
            ('SELECT uuid, title FROM article WHERE state=0 '
             'ORDER BY create_time DESC '
             'LIMIT 5 OFFSET 0')).fetchall()
    else:
        article = mydb.cursor().execute((
            'SELECT title, desc, create_time, content, img, creator FROM article WHERE state=0 AND uuid=?'
        ), (uuid, )).fetchone()
        article = [article]
    return {'code': 0, 'msg': 'ok', 'data': article}
Example #2
0
def rename(rw):
    form = Form(rw)
    name = form['name']
    token = form['token']
    fid = form['fid']
    pid = form['pid'] or ROOT
    if not name:
        return {'code': 31, 'msg': '文件名错误', 'data': []}
    try:
        data = yun.runtime.tokenizer.unpack(token)
    except VerificationError:
        return DATA_INVALID_TOKEN
    else:
        phone = data.split('&')[0]
        mydb, user_id = get_userdb_by_phone(phone)

    cr = mydb.cursor()
    exsit = cr.execute(
        'SELECT COUNT(*) FROM fs WHERE state=0 AND creator=? AND name=? AND parent=?',
        (user_id, name, pid)).fetchone()[0]
    if exsit > 0:
        return {'code': 32, 'msg': '文件名已存在', 'data': []}
    cr.execute('UPDATE fs SET name=? WHERE creator=? AND uuid=?',
               (name, user_id, fid))
    return DATA_OK
Example #3
0
def modify(rw):
    form = Form(rw)
    name = form['name']
    title = form['title']
    desc = form['desc']
    img = form['img']
    content = form['content']
    token = form['token']
    uuid = form['uuid']
    if not (name and title and desc and content and img):
        return {'code': 121, 'msg': '缺少必要参数', 'data': []}
    try:
        data = yun.runtime.tokenizer.unpack(token)
    except VerificationError:
        return DATA_INVALID_TOKEN
    else:
        phone = data.split('&')[0]
        mydb, user_id = get_userdb_by_phone(phone)

    cr = mydb.cursor()
    pid = cr.execute('SELECT parent FROM fs WHERE uuid=?',
                     (uuid, )).fetchone()[0]
    exsit = cr.execute(('SELECT COUNT(*) FROM fs WHERE state=0 '
                        'AND creator=? AND name=? AND parent=? AND uuid!=?'),
                       (user_id, name, pid, uuid)).fetchone()[0]
    if exsit > 0:
        return {'code': 122, 'msg': '卡片已存在', 'data': []}

    modify_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S %f')
    cr.execute('UPDATE fs SET name=?, modify_time=? WHERE uuid=?',
               (name, modify_time, uuid))
    cr.execute(
        'UPDATE article SET name=?, title=?, desc=?, img=?, content=?, modify_time=? WHERE uuid=?',
        (name, title, desc, img, content, modify_time, uuid))
    return DATA_OK
Example #4
0
 def create(self, rw):
     form = Form(rw)
     actors = []
     if form['actor']:
         actors = list(int(x) for x in form['actor'].split(','))
     data = tokenizer.unpack(form['token'])
     phone = data.split('&')[0]
     db = yun.runtime.get_users_db()
     cr = db.cursor()
     creator_id = cr.execute('SELECT id FROM users WHERE phone=?',
                             (phone, )).fetchone()[0]
     if creator_id not in actors:
         actors.append(creator_id)
     create_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S %f')
     cr.execute((
         'INSERT INTO job(creator, phone, title, start_time, end_time, actor, create_time, modify_time)'
         ' VALUES (?,?,?,?,?,?,?,?)'),
                (creator_id, phone, form['title'], form['start_time'],
                 form['end_time'], form['actor'], create_time, create_time))
     job_id = cr.execute(
         'select last_insert_rowid() from job').fetchone()[0]
     for actor_id in actors:
         cr.execute(
             ('INSERT INTO job_user(job, actor, creator, create_time)'
              'VALUES (?,?,?,?)'),
             (job_id, actor_id, creator_id, create_time))
     data = json.dumps({'code': 0, 'msg': 'ok', 'data': {}})
     return rw.send_response_and_close(headers=[('Content-Type',
                                                 'application/json')],
                                       content=bytes(data, 'utf-8'))
Example #5
0
def create(rw):
    form = Form(rw)
    name = form['name']
    title = form['title']
    desc = form['desc']
    img = form['img']
    content = form['content']
    token = form['token']
    pid = form['pid'] or ROOT
    if not (name and title and desc and content and img):
        return {'code': 111, 'msg': '缺少必要参数', 'data': []}
    pid = form.get('pid') or ROOT
    path = '/'
    try:
        data = yun.runtime.tokenizer.unpack(token)
    except VerificationError:
        return DATA_INVALID_TOKEN
    else:
        phone = data.split('&')[0]
        mydb, user_id = get_userdb_by_phone(phone)

    cr = mydb.cursor()
    exsit = cr.execute(
        'SELECT COUNT(*) FROM fs WHERE state=0 AND creator=? AND name=? AND parent=?',
        (user_id, name, pid)).fetchone()[0]
    if exsit > 0:
        return {'code': 112, 'msg': '卡片已存在', 'data': []}
    if pid != ROOT:
        path = cr.execute('SELECT path FROM fs WHERE state=0 AND uuid=?',
                          (pid, )).fetchone()[0]
        if path == '/':
            path = '{}{}'.format(path, pid)
        else:
            path = '{}/{}'.format(path, pid)
    create_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S %f')
    uuid_ = uuid4().hex
    cr.execute(('INSERT INTO fs (creator, phone, state, type, name, '
                ' uuid, create_time, modify_time, parent, path) '
                ' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'),
               (user_id, phone, 0, 4, name, uuid_, create_time, create_time,
                pid, path))
    cr.execute(('INSERT INTO article (creator, uuid, phone, state, type, '
                ' name, title, desc, img, content, create_time, modify_time) '
                ' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'),
               (user_id, uuid_, phone, 0, 1, name, title, desc, img, content,
                create_time, create_time))
    return DATA_OK
Example #6
0
File: logout.py Project: xunpu/yun
def POST(rw):
    # cookie = yun.runtime.del_session()
    form = Form(rw)
    # data = tokenizer.unpack(form['token'])
    # phone, stime = data.split('&')
    data = json.dumps({'code': 0, 'msg': '登出成功', 'data': {'token': ''}})
    rw.send_response_and_close(headers=[('Content-Type', 'application/json')],
                               content=bytes(data, 'utf-8'))
Example #7
0
def ls(rw):
    form = Form(rw)
    token = form['token']
    try:
        code = yun.runtime.tokenizer.unpack(token)
    except VerificationError:
        return DATA_INVALID_TOKEN
    else:
        phone = code.split('&')[0]
        mydb, user_id = get_userdb_by_phone(phone)

    page = (int(form.get('page', 1)) - 1) * SELECT_LIMIT
    articles = mydb.cursor().execute(
        ('SELECT * FROM (SELECT * FROM article WHERE state=0 AND creator=? '
         ' ORDER BY create_time DESC)'
         ' LIMIT ? OFFSET ?'), (user_id, SELECT_LIMIT, page)).fetchall()
    return {'code': 0, 'msg': 'ok', 'data': articles}
Example #8
0
File: pre.py Project: xunpu/yun
 def list(self, rw):
     form = Form(rw)
     page = int(form['p'])
     db = yun.runtime.get_users_db()
     data = pagination(db, 'users', page, self.limit,
                       ('id', 'phone', 'username'))
     data = json.dumps({'code': 0, 'msg': 'ok', 'data': data})
     self.rw.send_response_and_close(headers=[('Content-Type',
                                               'application/json')],
                                     content=bytes(data, 'utf-8'))
Example #9
0
def view(rw):
    form = Form(rw)
    path = rw.environ['locals.api_info'].lstrip('/').split('/')
    if len(path) == 1:
        is_thumb = False
        id_ = path[0].split('.')[0]
    else:
        is_thumb = True
        id_ = path[1].split('.')[0]
    user_id = int(form['id'])
    mydb = get_userdb_by_id(user_id)
    try:
        fileobj = mydb.cursor().execute(
            'SELECT uuid, name, mime, size, blob, thumb FROM fs WHERE uuid=?',
            (id_, )).fetchone()
    except:
        return rw.not_found()
    else:
        if is_thumb:
            return rw.send_response_and_close(headers=[('Content-Type',
                                                        fileobj[2])],
                                              content=fileobj[-1])
        else:
            if fileobj[-3] <= FILE_SIZE_BOUNDARY:
                return rw.send_response_and_close(headers=[('Content-Type',
                                                            fileobj[2])],
                                                  content=fileobj[-2])
            else:
                # token = form['token']
                # try:
                #     code = yun.runtime.tokenizer.unpack(token)
                # except VerificationError:
                #     return DATA_INVALID_TOKEN
                # else:
                #     phone = code.split('&')[0]
                #     userspace = get_userspace_by_id(user_id)
                userspace = get_userspace_by_id(user_id)
                path = os.path.join(userspace, fileobj[0][:2], fileobj[0][2:4],
                                    fileobj[0])
                f = fs.open(path)
                rw.start_chunked(headers=[('Content-Type', fileobj[2])])
                while True:
                    data = f.read(8192)
                    rw.write(data)
                    rw.flush()
                    if not data:
                        break
                f.close()
                rw.close()
Example #10
0
def mkdir(rw):
    form = Form(rw)
    name = form['name']
    if not name:
        return {'code': 41, 'msg': '文件名错误', 'data': []}
    token = form['token']
    pid = form.get('pid') or ROOT
    path = '/'
    try:
        data = yun.runtime.tokenizer.unpack(token)
    except VerificationError:
        return DATA_INVALID_TOKEN
    else:
        phone = data.split('&')[0]
        mydb, user_id = get_userdb_by_phone(phone)

    cr = mydb.cursor()
    exsit = cr.execute(
        'SELECT COUNT(*) FROM fs WHERE type=1 AND state=0 AND creator=? AND name=? AND parent=?',
        (user_id, name, pid)).fetchone()[0]
    if exsit > 0:
        return {'code': 42, 'msg': '目录已存在', 'data': []}
    if pid != ROOT:
        path = cr.execute('SELECT path FROM fs WHERE state=0 AND uuid=?',
                          (pid, )).fetchone()[0]
        if path == '/':
            path = '{}{}'.format(path, pid)
        else:
            path = '{}/{}'.format(path, pid)
    create_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S %f')
    cr.execute(('INSERT INTO fs (creator, phone, state, type, name '
                ', uuid, create_time, modify_time, parent, path) '
                ' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'),
               (user_id, phone, 0, 1, name, uuid4().hex, create_time,
                create_time, pid, path))
    return DATA_OK
Example #11
0
def view(rw):
    form = Form(rw)
    token = form['token']
    uuid = form['uuid']
    try:
        code = yun.runtime.tokenizer.unpack(token)
    except VerificationError:
        return DATA_INVALID_TOKEN
    else:
        phone = code.split('&')[0]
        mydb, user_id = get_userdb_by_phone(phone)

    article = mydb.cursor().execute(
        'SELECT * FROM article WHERE state=0 AND creator=? AND uuid=?',
        (user_id, uuid)).fetchone()
    return {'code': 0, 'msg': 'ok', 'data': [article]}
Example #12
0
File: pre.py Project: xunpu/yun
 def avatar(self, rw):
     form = Form(rw)
     phone = form['phone']
     db = yun.runtime.get_users_db()
     row = db.cursor().execute('SELECT id FROM users WHERE phone=?',
                               (phone, )).fetchone()
     buf = None
     if row is None:
         return rw.not_found()
     try:
         blob = db.blobopen('main', 'users', 'avatar', row[0], 1)
         buf = blob.read()
         blob.close()
     except apsw.SQLError:
         return rw.not_found()
     else:
         headers = [('Content-Type', 'image/png'),
                    ('Content-Length', '{}'.format(len(buf)))]
         return rw.send_response_and_close('200 OK', headers, buf)
Example #13
0
 def list(self, rw):
     form = Form(rw)
     data = tokenizer.unpack(form['token'])
     phone = data.split('&')[0]
     db = yun.runtime.get_users_db()
     cr = db.cursor()
     user_id = cr.execute('SELECT id FROM users WHERE phone=?',
                          (phone, )).fetchone()[0]
     job_user = cr.execute(
         'SELECT job FROM job_user WHERE actor=? ORDER BY create_time DESC',
         (user_id, )).fetchall()
     job_user = tuple(x[0] for x in job_user)
     if len(job_user) == 1:
         job_user = '******'.format(job_user[0])
     data = cr.execute(
         'SELECT * FROM job WHERE id IN {}'.format(job_user)).fetchall()
     data.reverse()
     data = json.dumps({'code': 0, 'msg': 'ok', 'data': data})
     return rw.send_response_and_close(headers=[('Content-Type',
                                                 'application/json')],
                                       content=bytes(data, 'utf-8'))
Example #14
0
File: pre.py Project: xunpu/yun
 def living(self, rw):
     form = Form(rw)
     token = form['token']
     try:
         data = tokenizer.unpack(token)
     except VerificationError:
         data = json.dumps({'code': 1, 'msg': 'Invalid token'})
     except:
         data = json.dumps({'code': -1, 'msg': 'Error'})
     else:
         phone = data.split('&')[0]
         data = json.dumps({
             'code': 0,
             'msg': 'ok',
             'data': {
                 'phone': phone,
             }
         })
     return rw.send_response_and_close(headers=[('Content-Type',
                                                 'application/json')],
                                       content=bytes(data, 'utf-8'))
Example #15
0
def remove(rw):
    form = Form(rw)
    token = form['token']
    ids_orig = form['ids'].split(',')
    ids = tuple(ids_orig)
    if len(ids) == 0:
        return {'code': 21, 'msg': '未选择文件', 'data': []}
    if len(ids) == 1:
        ids = '("{}")'.format(ids[0])
    try:
        code = yun.runtime.tokenizer.unpack(token)
    except VerificationError:
        return DATA_INVALID_TOKEN
    else:
        phone = code.split('&')[0]
        mydb, user_id = get_userdb_by_phone(phone)

    cr = mydb.cursor()
    for id_ in ids_orig:
        ids_ = cr.execute(
            'SELECT uuid FROM fs WHERE state=0 AND creator="{}" AND path LIKE "%{}%"'
            .format(user_id, id_)).fetchall()
        for uid in ids_:
            cr.execute('UPDATE card SET state=1 WHERE uuid=?', (uid[0], ))
            cr.execute('UPDATE article SET state=1 WHERE uuid=?', (uid[0], ))
        cr.execute(
            'UPDATE fs SET state=1 WHERE state=0 AND creator="{}" AND path LIKE "%{}%"'
            .format(user_id, id_))
    cr.execute(
        'UPDATE card SET state=1 WHERE state=0 AND creator="{}" AND uuid IN {}'
        .format(user_id, ids))
    cr.execute(
        'UPDATE article SET state=1 WHERE state=0 AND creator="{}" AND uuid IN {}'
        .format(user_id, ids))
    cr.execute(
        'UPDATE fs SET state=1 WHERE state=0 AND creator="{}" AND uuid IN {}'.
        format(user_id, ids))
    return DATA_OK
Example #16
0
def ls(rw):
    form = Form(rw)
    token = form['token']
    range = form.get('range')
    try:
        code = yun.runtime.tokenizer.unpack(token)
    except VerificationError:
        return DATA_INVALID_TOKEN
    else:
        phone = code.split('&')[0]
        mydb, user_id = get_userdb_by_phone(phone)

    filetype = form.get('type', '')
    if filetype:
        filetype = 'AND type={}'.format(filetype)

    ext = tuple(filter(None, set(form.get('ext', '').split(','))))
    if len(ext) > 1:
        ext_str = 'AND extension IN {}'.format(ext)
    elif len(ext) == 1:
        ext_str = 'AND extension IN ("{}")'.format(ext[0])
    else:
        ext_str = ''

    pid = rw.environ['locals.api_info'].lstrip('/') or ROOT
    if range == 'all':
        pid_str = ''
    else:
        pid_str = 'AND parent="{}"'.format(pid)

    page = (int(form.get('page', 1)) - 1) * SELECT_LIMIT
    files = mydb.cursor().execute(
        ('SELECT creator, phone, name, type, extension, size,'
         ' parent, path, uuid, create_time, modify_time, creator'
         ' FROM (SELECT * FROM fs WHERE state=0 AND creator=? '
         ' {} {} {} '
         ' ORDER BY create_time DESC)'
         ' LIMIT ? OFFSET ?').format(filetype, ext_str, pid_str),
        (user_id, SELECT_LIMIT, page)).fetchall()
    return {'code': 0, 'msg': 'ok', 'data': files}
Example #17
0
def move(rw):
    form = Form(rw)
    pid = form['pid'] or ROOT
    token = form['token']
    ids_orig = form['ids'].split(',')
    ids = tuple(ids_orig)

    try:
        code = yun.runtime.tokenizer.unpack(token)
    except VerificationError:
        return DATA_INVALID_TOKEN
    else:
        phone = code.split('&')[0]
        mydb, user_id = get_userdb_by_phone(phone)

    if pid in ids:
        return {'code': 11, 'msg': '移动位置冲突', 'data': []}
    if len(ids) == 0:
        return {'code': 12, 'msg': '未选择文件', 'data': []}
    if len(ids) == 1:
        ids = '("{}")'.format(ids[0])

    cr = mydb.cursor()
    if pid != ROOT:
        path = cr.execute(
            'SELECT path FROM fs WHERE creator=? AND type=1 AND uuid=?', (
                user_id,
                pid,
            )).fetchone()[0]
        for id_ in list(filter(None, path.split('/'))):
            if id_ in ids:
                return {'code': 13, 'msg': '移动位置冲突', 'data': []}
    else:
        path = '/'
    res = cr.execute(
        'SELECT * FROM fs WHERE creator="{}" AND uuid IN {}'.format(
            user_id, ids)).fetchall()
    for data in res:
        parent = data[-1]
        path_ = data[-2]
        id_ = data[11]
        type_ = data[4]
        if parent == pid:
            break
        else:
            new_path = '{}/{}'.format(path,
                                      (pid != ROOT and pid or '')).replace(
                                          '//', '/')
            cr.execute(
                'UPDATE fs SET path=?, parent=? WHERE creator=? AND uuid=?',
                (new_path, pid, user_id, id_))
            if path_ == '/' and not new_path.endswith('/'):
                new_path += '/'
            if new_path == '/':
                new_path = ''
            if type_ == 1:
                like_path = '{}/{}'.format(path_, id_).replace('//', '/')
                cr.execute(
                    ('UPDATE fs SET path=replace(path, ?, ?) '
                     'WHERE creator=? AND uuid!=? AND path LIKE ?'),
                    (path_, new_path, user_id, id_, "%{}%".format(like_path)))
    return DATA_OK