示例#1
0
    def meme(self, top_text=" ", bottom_text=" ", filename=""):
        if len(top_text) < 2:
            top_text = " "
        if len(bottom_text) < 2:
            bottom_text = " "

        img = ImageOps.expand(Image.open(filename), border=80, fill='white')
        image_size = img.size

        # find biggest font size that works
        font_size = int(image_size[1] / 10)
        font = ImageFont.truetype(
            STATICFILES_DIRS[0] + "/fonts/impact-opt.ttf", font_size)
        top_text_size = font.getsize(top_text)
        bottom_text_size = font.getsize(bottom_text)
        while top_text_size[0] > image_size[0] - 20 or bottom_text_size[
                0] > image_size[0] - 20:
            font_size = font_size - 1
            font = ImageFont.truetype(
                STATICFILES_DIRS[0] + "/fonts/Impact.ttf", font_size)
            top_text_size = font.getsize(top_text)
            bottom_text_size = font.getsize(bottom_text)

        # find top centered position for top text
        top_text_x = (image_size[0] / 2) - (top_text_size[0] / 2)
        top_text_y = 0
        top_text_position = (top_text_x, top_text_y)

        # find bottom centered position for bottom text
        bottom_text_x = (image_size[0] / 2) - (bottom_text_size[0] / 2)
        bottom_text_y = image_size[1] - bottom_text_size[1]
        bottom_text_position = (bottom_text_x, bottom_text_y)

        draw = ImageDraw.Draw(img)

        # draw outlines
        # there may be a better way
        # outline_range = int(font_size / 10)
        outline_range = 0
        for x in range(-outline_range, outline_range + 1):
            for y in range(-outline_range, outline_range + 1):
                draw.text((top_text_position[0] + x, top_text_position[1] + y),
                          top_text, (0, 0, 0),
                          font=font)
                draw.text(
                    (bottom_text_position[0] + x, bottom_text_position[1] + y),
                    bottom_text, (0, 0, 0),
                    font=font)

        draw.text(top_text_position, top_text, (0, 0, 0), font=font)
        draw.text(bottom_text_position, bottom_text, (0, 0, 0), font=font)
        output_path = str(uuid.uuid4().hex) + ".png"
        img.save(output_path)
        obj = Upload(provider=OBJECT_STORAGE_PROVIDER,
                     credentials=OBJECT_STORAGE_CREDENTIALS,
                     file=output_path)
        cloud_url = obj.upload_file()
        os.remove(os.getcwd() + '/' + output_path)
        return cloud_url
示例#2
0
    def meme(self, image_path):
        # base_dir = BASE_DIR

        # base_dir += '/' if not base_dir == '/' else ''
        image_path = image_path
        # thug life meme mask image path
        mask_path = STATICFILES_DIRS[0] + "/images/mask.png"
        # haarcascade path
        casc_path = STATICFILES_DIRS[
            0] + "/xml/haarcascade_frontalface_default.xml"

        # cascade classifier object
        face_cascade = cv2.CascadeClassifier(casc_path)

        # read input image
        image = cv2.imread(image_path)
        print(os.listdir())
        print(image, image_path)
        # convert image to grayscale
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        # detect faces in grayscale image
        faces = face_cascade.detectMultiScale(gray, 1.15)

        # open input image as PIL image
        background = Image.open(image_path)

        # paste mask on each detected face in input image
        for (x, y, w, h) in faces:
            # just to show detected faces
            cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2)
            # imshow('face detected', image)
            # waitKey(50)

            # open mask as PIL image
            mask = Image.open(mask_path)
            # resize mask according to detected face
            mask = mask.resize((w, h), Image.ANTIALIAS)

            # define o
            # ffset for mask
            offset = (x, y)
            # paste mask on background
            background.paste(mask, offset, mask=mask)

        # paste final thug life meme
        file_name = os.path.basename(image_path)

        output_path = "thug_" + str(file_name.split(".")[0]) + ".png"
        background.save(output_path)
        obj = Upload(provider=OBJECT_STORAGE_PROVIDER,
                     credentials=OBJECT_STORAGE_CREDENTIALS,
                     file=output_path)
        cloud_url = obj.upload_file()
        os.remove(os.getcwd() + '/' + output_path)
        return cloud_url
示例#3
0
 def __upload_avatar(self):
     """ Upload the avatar """
     form = self.params
     self.user['image_tmp'] = form['image_uploaded']
     
     if self.message or not self.user['image_tmp']:
         return False
     
     file_name = os.path.join(UP_AVATARS_TMP_FOLDER, self.user['image_tmp'])
     if os.path.exists(file_name):
         with open(file_name) as image:
             up = Upload(self.user['username'], image)
             up.avatar_upload(self.user['_id'])
         
         self.list_images = up.names_list
         return True
     
     self.message = g.users_msg('error_upload_2')
     return False
示例#4
0
    def __upload_avatar(self):
        """ Upload the avatar """
        form = self.params
        self.user['image_tmp'] = form['image_uploaded']

        if self.message or not self.user['image_tmp']:
            return False

        file_name = os.path.join(UP_AVATARS_TMP_FOLDER, self.user['image_tmp'])
        if os.path.exists(file_name):
            with open(file_name) as image:
                up = Upload(self.user['username'], image)
                up.avatar_upload(self.user['_id'])

            self.list_images = up.names_list
            return True

        self.message = g.users_msg('error_upload_2')
        return False
示例#5
0
def upload_avatar():
    """ """

    name = secure_filename(request.headers.get('X-File-Name'))
    extension = name.rsplit('.', 1)[1].lower()
    
    up = Upload()
    path_image = up.ajax_upload(UP_AVATARS_TMP_FOLDER, extension)
    
    if not up.allowed_file():
        success = False
        message = g.users_msg('error_upload_1')
    else:
        up.thumb((128, 128), os.path.join(UP_AVATARS_TMP_FOLDER, path_image))
        if path_image != 'error':
            success = True
            message = path_image

    data = {
        "success": success,
        "message": message
    }

    return jsonify(data)
示例#6
0
def upload_avatar():
    """ """

    name = secure_filename(request.headers.get('X-File-Name'))
    extension = name.rsplit('.', 1)[1].lower()

    up = Upload()
    path_image = up.ajax_upload(UP_AVATARS_TMP_FOLDER, extension)

    if not up.allowed_file():
        success = False
        message = g.users_msg('error_upload_1')
    else:
        up.thumb((128, 128), os.path.join(UP_AVATARS_TMP_FOLDER, path_image))
        if path_image != 'error':
            success = True
            message = path_image

    data = {"success": success, "message": message}

    return jsonify(data)
示例#7
0
    def upload(self):
        # recv info code {'info': "upload", "code": "", "filename": filename, "filesize": filesize, "hash": fileHashCode }
        # check file is exist
        try:
            fileInfo = self.session.query(self.file).filter(
                and_(self.file.uid == self.userid,
                     self.file.hashcode == self.recvInfo['hash'])).first()
            # self.session.add(self.file(uid= self.userid, name= downloadFileName, size= downloadFileSize, hashcode= downloadFileHashCode,updatetime= currentTime, postfix= postfix))
        except Exception as e:
            remsg = {
                'info': 'upload',
                'code': self.recvInfo['code'],
                'status': '1',
                'reason': str(e)
            }
            self.sendMsg(remsg)
        else:
            if fileInfo:
                self.log.info(fileInfo.__dict__)
                remsg = {
                    'info': 'upload',
                    'code': self.recvInfo['code'],
                    'status': '1',
                    'reason': 'file has exsited'
                }
                self.sendMsg(remsg)
            else:
                self.log.info('start create data of file')
                uploadFileInfo = self.recvInfo
                fileHashCode = uploadFileInfo['hash']
                fileName, postfix = utils.seperateFileName(
                    uploadFileInfo['filename'])
                fileSize = uploadFileInfo['filesize']
                currentTime = utils.getCurrentTime()

                encryption = uploadFileInfo['encryption']
                encryption_type = uploadFileInfo['encryption_type']
                encsize = uploadFileInfo['encsize']
                # to do
                # to determeine whether have repeat value in db
                try:
                    self.session.add(
                        self.file(uid=self.userid,
                                  name=fileName,
                                  size=fileSize,
                                  encryption=encryption,
                                  encryption_type=encryption_type,
                                  encsize=encsize,
                                  hashcode=fileHashCode,
                                  updatetime=currentTime,
                                  postfix=postfix))
                except Exception as e:
                    remsg = {
                        'info': 'upload',
                        'code': uploadFileInfo['code'],
                        'status': '1',
                        'reason': str(e)
                    }
                    self.sendMsg(remsg)

                authToken = utils.generateAuthToken()
                if self.settings.default.cluster == '1':
                    data_channel_info = ('127.0.0.1', 2334)
                    self.r.set(authToken, 0)
                else:
                    retInfo = self.createDataSock()  #return (int, port)
                    if retInfo[0] == 1:
                        self.log.info('createDataSock fails: {}'.format(
                            retInfo[1]))
                    data_channel_info = (self.settings.server.bind_address,
                                         retInfo[1])

                remsg = {
                    'info': 'upload',
                    'code': uploadFileInfo['code'],
                    'status': '0',
                    'token': authToken,
                    'dataAddress': data_channel_info
                }
                retInfo = self.sendMsg(remsg)
                if retInfo[0] == 1:
                    self.log.info('sendMsg fails: {}'.format(retInfo[1]))
                elif self.settings.default.cluster != '1':
                    if uploadFileInfo['encryption'] == 1:
                        uploadFileSize = uploadFileInfo['encsize']
                    else:
                        uploadFileSize = uploadFileInfo['filesize']
                    self.uploadProcess = Upload(self.sslContext,
                                                self.dataSocket, fileHashCode,
                                                uploadFileSize, authToken)
                    self.uploadProcess.start()
示例#8
0
class Worker(threading.Thread, BaseSocket):
    """docstring for Worker."""
    def __init__(self, client, address, db_session, sslContext=None):
        BaseSocket.__init__(self, clientSocket=client, clientAddress=address)
        threading.Thread.__init__(self)
        self.sslContext = sslContext
        self.authenticated = False
        self.user_address = address
        self.settings = Settings()
        # db init
        self.session = db_session()
        self.user = schema.user.User
        self.file = schema.file.File
        self.syslog = schema.syslog.Syslog

        if self.settings.default.cluster == '1':
            self.r = redis.Redis(host='redis',
                                 port=int(self.settings.redis.port),
                                 db=int(self.settings.redis.db))

    def run(self):
        self.log.info('start worker process')
        while True:
            recvInfo = self.recvMsg()
            if recvInfo[0] == 1:
                self.log.info("recvMsg error : {}".format(recvInfo[1]))
                self.log.error('exit worker process !!')
                self.exit()
            elif recvInfo[0] == 2:
                self.log.info('recvMsg is null, close the connecting.')
                self.exit()
            elif recvInfo[0] == 3:
                self.log.info('recvMsg can\'t convert a dict')
                self.exit()

            if self.recvInfo:
                self.log.info('Received cmd code : {}'.format(self.recvInfo))
                cmd = self.recvInfo['info']
                try:
                    func = getattr(self, cmd)
                    func()
                except AttributeError as err:
                    self.log.info('Receive : {}'.format(err))
            else:
                self.exit()

    def auth(func):
        """A decorator for auth worker action."""
        def wrapper(self):
            if self.loginStatus == True:
                func(self)
            else:
                self.sendMsg('Not Login')

        return wrapper

    def send_log(func):
        """A decorator for auth worker action."""
        def wrapper(self):
            func(self)
            try:
                self.session.add(
                    self.syslog(uid=self.userid,
                                ip=self.user_address[0],
                                event=str(self.recvInfo),
                                update_time=utils.getCurrentTime()))
            except Exception as e:
                self.log.info(str(e))
            else:
                self.log.info('recorder log')
                self.session.commit()

        return wrapper

    @auth
    @send_log
    def upload(self):
        # recv info code {'info': "upload", "code": "", "filename": filename, "filesize": filesize, "hash": fileHashCode }
        # check file is exist
        try:
            fileInfo = self.session.query(self.file).filter(
                and_(self.file.uid == self.userid,
                     self.file.hashcode == self.recvInfo['hash'])).first()
            # self.session.add(self.file(uid= self.userid, name= downloadFileName, size= downloadFileSize, hashcode= downloadFileHashCode,updatetime= currentTime, postfix= postfix))
        except Exception as e:
            remsg = {
                'info': 'upload',
                'code': self.recvInfo['code'],
                'status': '1',
                'reason': str(e)
            }
            self.sendMsg(remsg)
        else:
            if fileInfo:
                self.log.info(fileInfo.__dict__)
                remsg = {
                    'info': 'upload',
                    'code': self.recvInfo['code'],
                    'status': '1',
                    'reason': 'file has exsited'
                }
                self.sendMsg(remsg)
            else:
                self.log.info('start create data of file')
                uploadFileInfo = self.recvInfo
                fileHashCode = uploadFileInfo['hash']
                fileName, postfix = utils.seperateFileName(
                    uploadFileInfo['filename'])
                fileSize = uploadFileInfo['filesize']
                currentTime = utils.getCurrentTime()

                encryption = uploadFileInfo['encryption']
                encryption_type = uploadFileInfo['encryption_type']
                encsize = uploadFileInfo['encsize']
                # to do
                # to determeine whether have repeat value in db
                try:
                    self.session.add(
                        self.file(uid=self.userid,
                                  name=fileName,
                                  size=fileSize,
                                  encryption=encryption,
                                  encryption_type=encryption_type,
                                  encsize=encsize,
                                  hashcode=fileHashCode,
                                  updatetime=currentTime,
                                  postfix=postfix))
                except Exception as e:
                    remsg = {
                        'info': 'upload',
                        'code': uploadFileInfo['code'],
                        'status': '1',
                        'reason': str(e)
                    }
                    self.sendMsg(remsg)

                authToken = utils.generateAuthToken()
                if self.settings.default.cluster == '1':
                    data_channel_info = ('127.0.0.1', 2334)
                    self.r.set(authToken, 0)
                else:
                    retInfo = self.createDataSock()  #return (int, port)
                    if retInfo[0] == 1:
                        self.log.info('createDataSock fails: {}'.format(
                            retInfo[1]))
                    data_channel_info = (self.settings.server.bind_address,
                                         retInfo[1])

                remsg = {
                    'info': 'upload',
                    'code': uploadFileInfo['code'],
                    'status': '0',
                    'token': authToken,
                    'dataAddress': data_channel_info
                }
                retInfo = self.sendMsg(remsg)
                if retInfo[0] == 1:
                    self.log.info('sendMsg fails: {}'.format(retInfo[1]))
                elif self.settings.default.cluster != '1':
                    if uploadFileInfo['encryption'] == 1:
                        uploadFileSize = uploadFileInfo['encsize']
                    else:
                        uploadFileSize = uploadFileInfo['filesize']
                    self.uploadProcess = Upload(self.sslContext,
                                                self.dataSocket, fileHashCode,
                                                uploadFileSize, authToken)
                    self.uploadProcess.start()

    @auth
    @send_log
    def uploadComfirm(self):
        if self.recvInfo['status'] == '0':
            self.session.commit()
        else:
            self.session.rollback()

    @auth
    @send_log
    def download(self):
        # recv info code {'info': 'download', 'code': '', 'filename': downloadFileName}

        downloadFileHash = self.recvInfo['filehash']
        # downloadFileType = self.recvInfo['type']
        # baseFileName, postfix = utils.seperateFileName(downloadFileName)
        # downloadFileSize = self.recvInfo['filesize']
        # currentTime = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
        # to do
        # to determeine whether have repeat value in db
        try:
            fileInfo = self.session.query(self.file).filter(
                or_(
                    and_(self.file.uid == self.userid,
                         self.file.hashcode == downloadFileHash),
                    and_(self.file.hashcode == downloadFileHash,
                         self.file.public == 1))).all()
            # self.session.add(self.file(uid= self.userid, name= downloadFileName, size= downloadFileSize, hashcode= downloadFileHashCode,updatetime= currentTime, postfix= postfix))
        except Exception as e:
            remsg = {
                'info': 'download',
                'code': self.recvInfo['code'],
                'status': '1',
                'reason': str(e)
            }
            self.sendMsg(remsg)
        else:
            self.log.info('search file has : {}\'s'.format(len(fileInfo)))
            if len(fileInfo) == 1:
                fileInfo = fileInfo[0]
            elif len(fileInfo) >= 2:
                fileInfo = fileInfo[0]
            else:
                remsg = {
                    'info': 'download',
                    'code': self.recvInfo['code'],
                    'status': '1',
                    'reason': 'can\'t find download file'
                }
                retInfo = self.sendMsg(remsg)

            authToken = utils.generateAuthToken()

            if self.settings.default.cluster == '1':
                data_channel_info = ('127.0.0.1', 2334)
                self.r.set(authToken, 0)
            else:
                retInfo = self.createDataSock()  #return (int, tuple(ip,port))
                if retInfo[0] == 1:
                    self.log.info('createDataSock fails: {}'.format(
                        retInfo[1]))
                data_channel_info = (self.settings.server.bind_address,
                                     retInfo[1])

            fileInfo = fileInfo.__dict__
            del fileInfo['_sa_instance_state']
            remsg = {
                'info': 'download',
                'code': self.recvInfo['code'],
                'status': '0',
                'token': authToken,
                'dataAddress': data_channel_info,
                'fileinfo': fileInfo
            }
            retInfo = self.sendMsg(remsg)
            if retInfo[0] == 1:
                self.log.info('sendMsg fails: {}'.format(retInfo[1]))
            elif self.settings.default.cluster != '1':
                downloadFilePath = utils.joinFilePath(
                    self.settings.storage.datapath, fileInfo['hashcode'])
                self.downloadProcess = Download(self.sslContext,
                                                self.dataSocket,
                                                downloadFilePath, authToken)
                self.downloadProcess.start()

    @auth
    @send_log
    def list(self):
        # listInfo = self.session.query(self.file).filter_by(uid= self.userid).all()
        files_list = self.session.query(self.file).filter(
            or_(and_(self.file.uid == self.userid, self.file.is_delete == 0),
                and_(self.file.public == 1, self.file.is_delete == 0))).all()
        res = []
        for l in files_list:
            res_t = {}
            for i in l.__dict__:
                res_t[i] = getattr(l, i)
            del res_t['_sa_instance_state']
            res.append(res_t)

        remsg = {
            'info': 'list',
            'code': self.recvInfo['code'],
            'status': '0',
            'list': res
        }
        self.sendMsg(remsg)

    @auth
    @send_log
    def openFile(self):
        try:
            openfile = self.session.query(self.file).filter(
                and_(self.file.uid == self.userid,
                     self.file.hashcode == self.recvInfo['filehash'])).first()
            openfile.public = '1'
            self.session.commit()
        except Exception as e:
            remsg = {
                'info': 'openFile',
                'code': self.recvInfo['code'],
                'status': '1',
                'reason': str(e)
            }
        else:
            remsg = {
                'info': 'openFile',
                'code': self.recvInfo['code'],
                'status': '0'
            }
        self.sendMsg(remsg)

    @auth
    @send_log
    def closeFile(self):
        try:
            openfile = self.session.query(self.file).filter(
                and_(self.file.uid == self.userid,
                     self.file.hashcode == self.recvInfo['filehash'])).first()
            openfile.public = '0'
            self.session.commit()
        except Exception as e:
            remsg = {
                'info': 'closeFile',
                'code': self.recvInfo['code'],
                'status': '1',
                'reason': str(e)
            }
        else:
            remsg = {
                'info': 'closeFile',
                'code': self.recvInfo['code'],
                'status': '0'
            }
        self.sendMsg(remsg)

    @auth
    @send_log
    def deleteFile(self):
        try:
            openfile = self.session.query(self.file).filter(
                and_(self.file.uid == self.userid,
                     self.file.hashcode == self.recvInfo['filehash'])).first()
            openfile.is_delete = 1
            self.session.commit()
        except Exception as e:
            remsg = {
                'info': 'deleteFile',
                'code': self.recvInfo['code'],
                'status': '1',
                'reason': str(e)
            }
        else:
            remsg = {
                'info': 'deleteFile',
                'code': self.recvInfo['code'],
                'status': '0'
            }
        self.sendMsg(remsg)

    @auth
    @send_log
    def getPubKey(self):
        try:
            user = self.session.query(
                self.user).filter_by(email=self.recvInfo['email']).first()
        except Exception as e:
            remsg = {
                'info': 'getPubKey',
                'code': self.recvInfo['code'],
                'status': '1',
                'reason': str(e)
            }
        else:
            remsg = {
                'info': 'getPubKey',
                'code': self.recvInfo['code'],
                'public_key': user.pubkey
            }
        self.sendMsg(remsg)

    @auth
    @send_log
    def transferFile(self):
        try:
            user = self.session.query(
                self.user).filter_by(email=self.recvInfo['email']).first()
            openfile = self.session.query(self.file).filter_by(
                hashcode=self.recvInfo['filehash']).first()
            self.session.add(
                self.file(uid=user.id,
                          name=openfile.name,
                          size=openfile.size,
                          encryption=openfile.encryption,
                          encryption_type=openfile.encryption_type,
                          encsize=openfile.encsize,
                          hashcode=openfile.hashcode,
                          updatetime=openfile.updatetime,
                          postfix=openfile.postfix,
                          is_transfer=1,
                          transfer_own=self.userid,
                          c_enc=self.recvInfo['cipher_enc']))
            self.session.commit()
        except Exception as e:
            remsg = {
                'info': 'transferFile',
                'code': self.recvInfo['code'],
                'status': '1',
                'reason': str(e)
            }
        else:
            remsg = {
                'info': 'transferFile',
                'code': self.recvInfo['code'],
                'status': '0'
            }
        self.sendMsg(remsg)

    @send_log
    def login(self):
        res = self.session.query(
            self.user).filter_by(username=self.recvInfo['u']).first()
        if res and res.password == self.recvInfo['p']:
            self.username = res.username
            self.userid = res.id
            self.loginStatus = True
            remsg = {
                'info': 'login',
                'code': self.recvInfo['code'],
                'status': '0',
                'uid': str(self.userid)
            }
            self.sendMsg(remsg)
            #send info to web console
            # self.recorder()
        else:
            remsg = {
                'info': 'login',
                'code': self.recvInfo['code'],
                'status': '1',
                'reason': 'user not exist or authentication fails'
            }
            self.sendMsg(remsg)

    @auth
    @send_log
    def logout(self):
        logoutInfo = {
            "info": "logout",
            "code": self.recvInfo['code'],
            'status': '0'
        }
        self.session.rollback()
        self.sendMsg(logoutInfo)
        self.close()
        self.exit()

    def exit(self):
        self.session.close()
        exit()
示例#9
0
    def upload(self, filepath):
        filename = utils.getBaseNameByPath(filepath)
        filesize = utils.getSizeByPath(filepath)
        # check if need to encrypt files
        if self.encryption is True:
            retInfo = self.crypt.encrypt(str(self.encryption_cipher).strip(),
                                         filepath,
                                         mode=str(
                                             self.encryption_type).strip())
            if retInfo[0] == 0:
                enctryptedFilePath = retInfo[1]
            else:
                return (1, retInfo[1])
            encryptedFileSize = utils.getSizeByPath(enctryptedFilePath)

            fileHashCode = utils.calculateHashCodeForFile(enctryptedFilePath)
            uploadCmdCode = {
                'info': "upload",
                "code": "",
                "filename": filename,
                "filesize": filesize,
                "encryption": 1,
                "encsize": encryptedFileSize,
                "encryption_type": self.encryption_type,
                "hash": fileHashCode
            }
        else:

            fileHashCode = utils.calculateHashCodeForFile(filepath)
            uploadCmdCode = {
                'info': "upload",
                "code": "",
                "filename": filename,
                "filesize": filesize,
                "encryption": 0,
                "encryption_type": "0",
                "encsize": "0",
                "hash": fileHashCode
            }

        uploadInfo = self.sendMsg(uploadCmdCode)
        if uploadInfo[0] == 1:
            self.log.info(uploadInfo[1])
        else:
            retInfo = self.recvMsg()
            if retInfo[0] == 1:
                return (1, retInfo[1])
            elif self.recvInfo['status'] == '0':
                uploadAuthCode = self.recvInfo['token']
                remoteDataInfo = self.recvInfo['dataAddress']
                self.log.info(
                    'recv upload auth token is : {}'.format(uploadAuthCode))
                self.log.info('remote open data info : {}:{}'.format(
                    remoteDataInfo[0], remoteDataInfo[1]))

                if self.encryption:
                    filepath = enctryptedFilePath

                self.uploadProcess = Upload(remoteDataInfo, filepath,
                                            uploadAuthCode, uploadCmdCode)
                self.uploadProcess.signal.p.connect(self.setUpbarValue)
                self.uploadProcess.start()

                return (0, 'ok')
            else:
                return (1, self.recvInfo['reason'])
示例#10
0
class FTPClient(BaseSocket):
    """docstring for FTPClient."""
    def __init__(self, **arg):
        super(FTPClient, self).__init__(**arg)
        self.signal = Signal()
        self.settings = Settings()
        self.crypt = Cryptogram()

        self.encryption = False
        self.encryption_type = None
        self.encryption_cipher = None
        self.upbar = None
        self.dpbar = None

    def login(self):
        self.log.info('start login')
        loginCmdCode = {
            'info': 'login',
            'code': '1234',
            'u': self.username,
            'p': utils.calculateHashCodeForString(self.password)
        }
        loginInfo = self.sendMsg(loginCmdCode)
        if loginInfo[0] == 1:
            self.log.info(loginInfo[1])
            return (1, loginInfo[1])

        recvInfo = self.recvMsg()
        if recvInfo[0] == 1:
            self.log.info(recvInfo[1])
            return (1, recvInfo[1])

        if self.recvInfo['status'] == '0':
            return (0, 'Login Successd', self.certInfo, self.recvInfo['uid'])
        else:
            return (1, self.recvInfo['reason'])

    def logout(self):
        self.log.info('start logout')
        logoutCmdCode = {'info': 'logout', 'code': ''}
        logoutInfo = self.sendMsg(logoutCmdCode)
        if logoutInfo[0] == 1:
            return (1, logoutInfo[1])

        recvInfo = self.recvMsg()
        if recvInfo[0] == 1:
            return (1, recvInfo[1])

        if self.recvInfo['status'] == '0':
            return (0, 'Logout Successd')
        else:
            return (1, self.recvInfo['reason'])
        self.clearCert()

    def reconnect(self):
        self.logout()

    # @encrypt
    def upload(self, filepath):
        filename = utils.getBaseNameByPath(filepath)
        filesize = utils.getSizeByPath(filepath)
        # check if need to encrypt files
        if self.encryption is True:
            retInfo = self.crypt.encrypt(str(self.encryption_cipher).strip(),
                                         filepath,
                                         mode=str(
                                             self.encryption_type).strip())
            if retInfo[0] == 0:
                enctryptedFilePath = retInfo[1]
            else:
                return (1, retInfo[1])
            encryptedFileSize = utils.getSizeByPath(enctryptedFilePath)

            fileHashCode = utils.calculateHashCodeForFile(enctryptedFilePath)
            uploadCmdCode = {
                'info': "upload",
                "code": "",
                "filename": filename,
                "filesize": filesize,
                "encryption": 1,
                "encsize": encryptedFileSize,
                "encryption_type": self.encryption_type,
                "hash": fileHashCode
            }
        else:

            fileHashCode = utils.calculateHashCodeForFile(filepath)
            uploadCmdCode = {
                'info': "upload",
                "code": "",
                "filename": filename,
                "filesize": filesize,
                "encryption": 0,
                "encryption_type": "0",
                "encsize": "0",
                "hash": fileHashCode
            }

        uploadInfo = self.sendMsg(uploadCmdCode)
        if uploadInfo[0] == 1:
            self.log.info(uploadInfo[1])
        else:
            retInfo = self.recvMsg()
            if retInfo[0] == 1:
                return (1, retInfo[1])
            elif self.recvInfo['status'] == '0':
                uploadAuthCode = self.recvInfo['token']
                remoteDataInfo = self.recvInfo['dataAddress']
                self.log.info(
                    'recv upload auth token is : {}'.format(uploadAuthCode))
                self.log.info('remote open data info : {}:{}'.format(
                    remoteDataInfo[0], remoteDataInfo[1]))

                if self.encryption:
                    filepath = enctryptedFilePath

                self.uploadProcess = Upload(remoteDataInfo, filepath,
                                            uploadAuthCode, uploadCmdCode)
                self.uploadProcess.signal.p.connect(self.setUpbarValue)
                self.uploadProcess.start()

                return (0, 'ok')
            else:
                return (1, self.recvInfo['reason'])
        # uploadProcess = Upload()

    # @decrypt
    def download(self, filehash, savefilepath):
        # filename = os.path.basename(filepath)
        # filesize = os.path.getsize(filepath)
        # try:
        #     with open(filepath, 'rb') as f:
        #         fileHashCode = hashlib.md5(f.read()).hexdigest()
        # except Exception as e:
        #     return (1, str(e))
        downloadCmdCode = {
            'info': 'download',
            'code': '',
            'filehash': filehash
        }
        retInfo = self.sendMsg(downloadCmdCode)
        if retInfo[0] == 1:
            self.log.info(retInfo[1])
        else:
            retInfo = self.recvMsg()
            if retInfo[0] == 1:
                return (1, retInfo[1])
            elif self.recvInfo['status'] == '0':
                downloadAuthCode = self.recvInfo['token']
                remoteDataInfo = self.recvInfo['dataAddress']
                fileInfo = self.recvInfo['fileinfo']

                if fileInfo['encryption'] != 0:
                    # saveFilePath = utils.joinFilePath('/tmp/', fileInfo['name'] + '.enc')
                    # fileSize = fileInfo['encsize']
                    decryptInfo = {
                        #     "encryption_type": self.encryption_type,
                        "cipher": self.encryption_cipher,
                        # "savefilepath": savefilepath
                    }
                else:
                    # saveFilePath = savefilepath
                    # fileSize = fileInfo['size']
                    decryptInfo = None
                self.log.info('recv download auth token is : {}'.format(
                    downloadAuthCode))
                self.log.info('remote open data info : {}:{}'.format(
                    remoteDataInfo[0], remoteDataInfo[1]))
                self.downloadProcess = Download(remoteDataInfo, savefilepath,
                                                downloadAuthCode, fileInfo,
                                                decryptInfo)
                # print(self.uploadProcess.__dict__)
                self.downloadProcess.signal.p.connect(self.setDpbarValue)
                self.downloadProcess.start()

                return (0, 'ok')
            else:
                return (1, self.recvInfo['reason'])
        # uploadProcess = Upload()

    def setUpbarValue(self, progress):
        self.upbar.ui.Progress.setValue(progress[0])
        self.upbar.ui.Percentage_label.setText(progress[1])

    def setDpbarValue(self, progress):
        self.dpbar.ui.Progress.setValue(progress[0])
        self.dpbar.ui.Percentage_label.setText(progress[1])

    def uploadComfirm(self):
        uploadComfirmCmdCode = {
            'info': 'uploadComfirm',
            'code': '',
            'status': '0'
        }
        self.sendMsg(uploadComfirmCmdCode)
        self.upbar.close()
        self.signal.refresh.emit()

    def downloadComfirm(self):
        self.dpbar.close()

    def open_file(self, filehash):
        openFileCmdCode = {
            'info': 'openFile',
            'code': '',
            'filehash': filehash
        }
        self.log.info('start open file')
        retInfo = self.sendMsg(openFileCmdCode)
        if retInfo[0] == 1:
            self.log.info(retInfo[1])
            return (1, retInfo[1])

        recvInfo = self.recvMsg()
        if recvInfo[0] == 1:
            self.log.info(recvInfo[1])
            return (1, recvInfo[1])

        if self.recvInfo['status'] == '0':
            return (0, 'file open successd.')
        else:
            return (1, self.recvInfo['reason'])

    def close_file(self, filehash):
        closeFileCmdCode = {
            'info': 'closeFile',
            'code': '',
            'filehash': filehash
        }
        self.log.info('start close file')
        retInfo = self.sendMsg(closeFileCmdCode)
        if retInfo[0] == 1:
            self.log.info(retInfo[1])
            return (1, retInfo[1])

        recvInfo = self.recvMsg()
        if recvInfo[0] == 1:
            self.log.info(recvInfo[1])
            return (1, recvInfo[1])

        if self.recvInfo['status'] == '0':
            return (0, 'file close successd.')
        else:
            return (1, self.recvInfo['reason'])

    def delete_file(self, filehash):
        deleteFileCmdCode = {
            'info': 'deleteFile',
            'code': '',
            'filehash': filehash
        }
        self.log.info('start delete file')
        retInfo = self.sendMsg(deleteFileCmdCode)
        if retInfo[0] == 1:
            self.log.info(retInfo[1])
            return (1, retInfo[1])

        recvInfo = self.recvMsg()
        if recvInfo[0] == 1:
            self.log.info(recvInfo[1])
            return (1, recvInfo[1])

        if self.recvInfo['status'] == '0':
            return (0, 'file delete successd.')
        else:
            return (1, self.recvInfo['reason'])

    def transfer_file(self, target_email, filehash):
        getPubKeyCmdCode = {
            'info': 'getPubKey',
            'code': '',
            'email': target_email
        }
        self.log.info('start get public_key')
        retInfo = self.sendMsg(getPubKeyCmdCode)
        if retInfo[0] == 1:
            self.log.info(retInfo[1])
            return (1, retInfo[1])

        recvInfo = self.recvMsg()
        if recvInfo[0] == 1:
            self.log.info(recvInfo[1])
            return (1, recvInfo[1])
        else:
            # get public key
            public_key = self.recvInfo['public_key'].strip()
            if public_key == 'None':
                return (1, 'can\'t acquire public_key')
            elif utils.check_public_key(public_key):
                # encrypt user cipher with public_key
                enc = self.crypt.encrypt_text(self.encryption_cipher,
                                              public_key)
                transferFileCmdCode = {
                    'info': 'transferFile',
                    'code': '',
                    'email': target_email,
                    'filehash': filehash,
                    'cipher_enc': enc[1]
                }
                self.log.info('start transfer file to {}'.format(target_email))
                retInfo = self.sendMsg(transferFileCmdCode)
                if retInfo[0] == 1:
                    self.log.info(retInfo[1])
                    return (1, retInfo[1])

                recvInfo = self.recvMsg()
                if recvInfo[0] == 1:
                    self.log.info(recvInfo[1])
                    return (1, recvInfo[1])

                if self.recvInfo['status'] == '0':
                    return (0, 'file transfer successd.')
                else:
                    return (1, self.recvInfo['reason'])

            else:
                return (1, 'the public_key is\'t valid')

        if self.recvInfo['status'] == '0':
            return (0, 'file delete successd.')
        else:
            return (1, self.recvInfo['reason'])

    def refresh(self, folder):
        return self.list(folder)

    def list(self, folder='/'):
        listCmdCode = {'info': 'list', 'code': '', 'dir': folder}
        try:
            self.sendMsg(listCmdCode)
        except Exception as e:
            return (1, str(e))

        try:
            self.recvMsg()
        except Exception as e:
            self.log.info(str(e))
            return (1, str(e))
        else:
            return (0, self.recvInfo['list'])