Esempio n. 1
0
    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'])
Esempio n. 2
0
    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()
Esempio n. 3
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()
Esempio n. 4
0
from core.download import Download

url = 'https://upload.wikimedia.org/wikipedia/en/thumb/d/d8/Game_of_Thrones_title_card.jpg/250px-Game_of_Thrones_title_card.jpg'
download = Download(url)
print(download)
print(download.source_url)
print(download.get_destination_path())
print(download.total_bytes)
download.start_downloading()
Esempio n. 5
0
from core.download import Download

url = 'https://upload.wikimedia.org/wikipedia/en/thumb/d/d8/Game_of_Thrones_title_card.jpg/250px-Game_of_Thrones_title_card.jpg'
download = Download(url)
download.start_downloading()
print(download)
Esempio n. 6
0
def main():
    # Init Colorama
    init(strip=not sys.stdout.isatty())

    # Constants
    root_dir = os.path.dirname(os.path.abspath(__file__))
    title = "Chika's Script\nv0.1"

    # Set routines
    add_anime = AddAnime()
    download = Download()
    history = History()

    # Grab ASCII Art to display
    chika = MenuArt().chika

    # Get username
    try:
        with open(os.path.join(root_dir, 'data\\settings.json'),
                  'r',
                  encoding='utf-8') as settings:
            data = json.load(settings)
            username = '******' + data["username"] if data["username"] != '' else ''

    except Exception as e:
        username = ''
        print("Error parsing JSON settings file: ", e)

    exit_script = False
    while not exit_script:

        # Clear the screen
        sp.call('cls', shell=True)

        # Show main menu
        print(title)
        print(colored(chika, "cyan"))
        print('\t\t\t\tOptions:', end="")
        print(colored(' 1) Download ', 'magenta'), end="")
        print('⡇', end="")
        print(colored(' 2) Add new anime ', 'green'), end="")
        print('⡇', end="")
        print(colored(' 3) History ', 'yellow'), end="")
        print('⡇', end="")
        print(colored(' 0) Exit ', 'red'))

        # Run routines
        try:
            opt = int(input(f'Welcome{username}!\nPlease, select an option: '))

            if opt == 1:
                download.start()
                download.join()
            elif opt == 2:
                add_anime.start(root_dir)
            elif opt == 3:
                history.display_history(root_dir)
            elif opt == 0:
                print('See ya ;)')
                exit_script = True
            else:
                print('This is not a valid option!')

        except Exception as e:
            print('Error: ', e)
Esempio n. 7
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'])