Ejemplo n.º 1
0
Archivo: pre.py Proyecto: xunpu/yun
 def upload(self, rw):
     filename = None
     buf = None
     for reader in multipart(rw, filename_encoding='utf-8'):
         if 'file' == reader.name:
             filename = reader.filename
             buf = reader.read()
         else:
             token = reader.read()
             try:
                 data = tokenizer.unpack(token)
             except VerificationError:
                 data = json.dumps({'code': 1, 'msg': 'Invalid token'})
             else:
                 phone = data.split('&')[0]
         reader.close()
     if len(buf) > 0 and phone:
         db = yun.runtime.get_userspace_db_by_phone(phone)
         cr = db.cursor()
         cr.execute('CREATE TABLE IF NOT EXISTS user ('
                    'id               INTEGER       PRIMARY KEY,'
                    'phone            NVARCHAR( 64),'
                    'username         NVARCHAR( 64),'
                    'avatar           LONGBLOB'
                    ');')
         zero_blob = apsw.zeroblob(len(buf))
         db.cursor().execute('UPDATE user SET avatar=? WHERE phone=?',
                             (zero_blob, phone))
         blob = db.blobopen("main", "user", "avatar", 1, 1)
         blob.write(buf)
         blob.close()
     data = json.dumps({'code': 0, 'msg': 'ok', 'data': ''})
     self.rw.send_response_and_close(headers=[('Content-Type',
                                               'application/json')],
                                     content=bytes(data, 'utf-8'))
Ejemplo n.º 2
0
Archivo: pre.py Proyecto: xunpu/yun
 def modify_avatar(self, rw):
     filename = None
     buf = None
     for reader in multipart(rw, filename_encoding='utf-8'):
         if 'file' == reader.name:
             filename = reader.filename
             buf = reader.read()
         else:
             token = reader.read()
             try:
                 data = tokenizer.unpack(token)
             except VerificationError:
                 data = json.dumps({'code': 1, 'msg': 'Invalid token'})
             else:
                 phone = data.split('&')[0]
         reader.close()
     if len(buf) > 0 and phone:
         db = yun.runtime.get_users_db()
         zero_blob = apsw.zeroblob(len(buf))
         db.cursor().execute('UPDATE users SET avatar=? WHERE phone=?',
                             (zero_blob, phone))
         row = db.cursor().execute('SELECT id FROM users WHERE phone=?',
                                   (phone, )).fetchone()
         blob = db.blobopen("main", "users", "avatar", row[0], 1)
         blob.write(buf)
         blob.close()
     data = json.dumps({'code': 0, 'msg': 'ok', 'data': ''})
     self.rw.send_response_and_close(headers=[('Content-Type',
                                               'application/json')],
                                     content=bytes(data, 'utf-8'))
Ejemplo n.º 3
0
 def _writeblob(self, fileid, stream):
     '''
     extract the data from stream and write it as blob.
     '''
     size = stream.tell()
     last_modified = datetime.datetime.now().isoformat()
     self._updatecur.execute('UPDATE FsFileTable SET size=?, last_modified=?, contents=? where rowid=?',
             (size, last_modified, apsw.zeroblob(size), fileid))
     blob_stream=self.dbcon.blobopen("main", "FsFileTable", "contents", fileid, True) # 1 is for read/write
     stream.seek(0)
     blob_stream.write(stream.read())
     blob_stream.close()
Ejemplo n.º 4
0
 def _writeblob(self, fileid, stream):
     '''
     extract the data from stream and write it as blob.
     '''
     size = stream.tell()
     last_modified = datetime.datetime.now().isoformat()
     self._updatecur.execute('UPDATE FsFileTable SET size=?, last_modified=?, contents=? where rowid=?',
             (size, last_modified, apsw.zeroblob(size), fileid))
     blob_stream=self.dbcon.blobopen("main", "FsFileTable", "contents", fileid, True) # 1 is for read/write
     stream.seek(0)
     blob_stream.write(stream.read())
     blob_stream.close()
Ejemplo n.º 5
0
connection.setupdatehook(myupdatehook)
cursor.execute("insert into s values(?)", ("file93", ))
cursor.execute("update s set str=? where str=?", ("file94", "file93"))
cursor.execute("delete from s where str=?", ("file94", ))
connection.setupdatehook(None)
#@@ENDCAPTURE

###
### Blob I/O    @@ example-blobio
###

cursor.execute("create table blobby(x,y)")
# Add a blob we will fill in later
cursor.execute("insert into blobby values(1,zeroblob(10000))")
# Or as a binding
cursor.execute("insert into blobby values(2,?)", (apsw.zeroblob(20000), ))
# Open a blob for writing.  We need to know the rowid
rowid = inext(cursor.execute("select ROWID from blobby where x=1"))[0]
blob = connection.blobopen("main", "blobby", "y", rowid,
                           1)  # 1 is for read/write
blob.write(b"hello world")
blob.seek(2000)
blob.write(b"hello world, again")
blob.close()

###
### Virtual tables  @@ example-vtable
###

# This virtual table stores information about files in a set of
# directories so you can execute SQL queries
Ejemplo n.º 6
0
connection.setupdatehook(myupdatehook)
cursor.execute("insert into s values(?)", ("file93",))
cursor.execute("update s set str=? where str=?", ("file94", "file93"))
cursor.execute("delete from s where str=?", ("file94",))
connection.setupdatehook(None)
#@@ENDCAPTURE

###
### Blob I/O    @@ example-blobio
###

cursor.execute("create table blobby(x,y)")
# Add a blob we will fill in later
cursor.execute("insert into blobby values(1,zeroblob(10000))")
# Or as a binding
cursor.execute("insert into blobby values(2,?)", (apsw.zeroblob(20000),))
# Open a blob for writing.  We need to know the rowid
rowid=cursor.execute("select ROWID from blobby where x=1").next()[0]
blob=connection.blobopen("main", "blobby", "y", rowid, 1) # 1 is for read/write
blob.write("hello world")
blob.seek(2000)
blob.write("hello world, again")
blob.close()

###
### Virtual tables  @@ example-vtable
###

# This virtual table stores information about files in a set of
# directories so you can execute SQL queries
Ejemplo n.º 7
0
def real_upload(params, fileobj):
    try:
        data = yun.runtime.tokenizer.unpack(params['token'])
    except VerificationError:
        return DATA_INVALID_TOKEN
    else:
        phone = data.split('&')[0]
        mydb, user_id = get_userdb_by_phone(phone)
        userspace = get_userspace_by_phone(phone)[0]

    cr = mydb.cursor()
    pid = params['pid'] or ROOT
    if not user_id or fileobj is None:
        return {'code': 51, 'msg': '上传错误', 'data': []}
    create_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S %f')
    filename = fileobj.filename
    res = cr.execute(('SELECT COUNT(*) FROM fs WHERE state=0 '
                      'AND name="{}" AND parent="{}"').format(filename, pid))
    if res.fetchone()[0] > 0:
        time_str = datetime.now().strftime('%Y%m%d_%H%M%S_%f')
        filename = '{}-{}'.format(time_str, filename)
    buf = BytesIO()
    while True:
        data = fileobj.read1(8192)
        buf.write(data)
        if buf.tell() > FILE_SIZE_BOUNDARY:
            break
        elif not data:
            fileobj.close()
            break
    if buf.tell() <= 0:
        return {'code': 52, 'msg': '上传错误', 'data': []}
    uuid_ = uuid4().hex
    path = '/'
    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)

    if buf.tell() <= FILE_SIZE_BOUNDARY:
        zero_blob = apsw.zeroblob(buf.tell())
        hash_name = ''
    else:
        zero_blob = apsw.zeroblob(0)

    typeguess = filetype.guess(buf.getvalue())
    extension, mime = '', ''
    if typeguess is None:
        if len(filename.split('.')) >= 2:
            extension = filename.split('.')[-1]
            mime = 'application/{}'.format(extension)
    else:
        mime = typeguess.mime
        extension = typeguess.extension

    is_image, thumb_zero_blob = False, apsw.zeroblob(0)
    if buf.tell() <= FILE_SIZE_BOUNDARY:
        if filetype.is_image(buf.getvalue()):
            is_image = True
            thumb_bytes = BytesIO()
            im = Image.open(buf)
            im.thumbnail((750, 750), Image.ANTIALIAS)
            im.save(thumb_bytes, 'png')
            thumb_zero_blob = apsw.zeroblob(len(thumb_bytes.getvalue()))
    else:
        os_path = os.path.join(userspace, uuid_[:2], uuid_[2:4])
        try:
            fs.os.makedirs(os_path)
        except FileExistsError:
            pass
        os_path = os.path.join(os_path, uuid_)
        f = fs.open(os_path, 'w+b')
        f.write(buf.getvalue())
        while True:
            data = fileobj.read1(8192)
            f.write(data)
            if not data:
                fileobj.close()
                break
        f.seek(0)
        bytesio = BytesIO(f.read())
        if filetype.is_image(bytesio.read(64)):
            is_image = True
            thumb_bytes = BytesIO()
            im = Image.open(bytesio)
            im.thumbnail((750, 750), Image.ANTIALIAS)
            im.save(thumb_bytes, 'png')
            thumb_zero_blob = apsw.zeroblob(len(thumb_bytes.getvalue()))
        f.close()

    cr.execute(
        ('INSERT INTO fs (creator, phone, state, type, name, extension, mime,'
         ' size, blob, thumb, uuid, create_time, modify_time, parent, path)'
         ' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'),
        (user_id, phone, 0, 2, filename, extension, mime, buf.tell(),
         zero_blob, thumb_zero_blob, uuid_, create_time, create_time, pid,
         path))
    fid_ = None
    if is_image:
        fid_ = cr.execute(
            ('SELECT id FROM fs WHERE uuid="{}"'.format(uuid_))).fetchone()[0]
        blob = mydb.blobopen("main", "fs", "thumb", fid_, 1)
        blob.write(thumb_bytes.getvalue())
        blob.close()
    if buf.tell() <= FILE_SIZE_BOUNDARY:
        if not fid_:
            fid_ = cr.execute(
                ('SELECT id FROM fs WHERE uuid="{}"'.format(uuid_)
                 )).fetchone()[0]
        blob = mydb.blobopen("main", "fs", "blob", fid_, 1)
        blob.write(buf.getvalue())
        blob.close()
    else:
        pass
    return DATA_OK