Example #1
0
    def socket_read_data(self, sock, data):
        # zokket收到的是unicode编码 ,转换为utf-8再进行json解析。
        input =data.encode('utf-8')
        d =pack.unpack(self.pwd, input)
        if print_log:
            print 'typeof unpack result:', type(d)
            print 'unpack input=', input
            print 'unpack output=', d
        if len(d)<1:
            return
        if type(d) != type({}):
            return
        # 注意json解析结果是unicode编码 !
        cmd =d['cmd']
        chid =d['chid']
        timenow =d['timenow']
        
        chid_utf8 =chid.encode('utf-8')
        flicker =True 
        if u'new_client_join'==cmd: # 已经在线的人 收到新加入报文,发出自己在线的通知
            self.onNewClientJoin(chid_utf8, timenow)
        if u'client_leave'==cmd: # 已经在线的人 收到其它人离线报文
            if self.all_chids.has_key(chid_utf8):
                del(self.all_chids[chid_utf8])
                self.editOutput.append(u'[%s] [系统消息] %s 离开了聊天'%(self.formatTime(timenow), chid))
            
        elif u'already_online_client'==cmd: # 新加入的人收到其它在线通知 
            if self.chid==d['new_join_chid'].encode('utf-8'): # 只有新加入的人才处理
                self.all_chids[chid_utf8] ={"join_time":d['join_time'],"last_heartbeat_time":d['join_time']}
                
        elif u'sendfile'==cmd: # 收到文件通知
            self.onRecvedFile(d, chid_utf8, timenow)
        elif u'recvfile'==cmd: # 接收文件通知,只有发送者才处理这条报文
            if str(d['sender_chid'].encode('utf-8'))==self.chid:
                QtGui.QMessageBox.information( self, u'系统通知', u'%s 接受了文件%s'%(chid,  d['filename']) )
        elif u'rejectfile'==cmd: # 拒接文件通知,只有发送者才处理这条报文
            if str(d['sender_chid'].encode('utf-8'))==self.chid:
                QtGui.QMessageBox.information( self, u'系统通知', u'%s 拒接了文件%s'%(chid,  d['filename']) )   
                
        elif u'msg'==cmd: # 收到消息
            self.editOutput.append(u'[%s] %s 说: %s'%(self.formatTime(timenow), chid, d['txt']))

        elif u'heartbeat'==cmd: # 收到心跳
            flicker =False
                        
            if self.all_chids.has_key(chid_utf8):
                self.all_chids[chid_utf8]["last_heartbeat_time"] =timenow
            else: 
            # 说明长时间没有收到心跳,已经移除了通道信息。但是过段时间又收到了心跳,故认为网络恢复了。
            #   所以考虑容错时重新保存通道信息,但是丢失了原始的 join_time,用当前时间代替。
                self.all_chids[chid_utf8] ={"join_time":timenow,"last_heartbeat_time":timenow}
                
            self.lableShow.setText(u'%s 收到来自[%s]心跳'%(self.formatTime(timenow), chid))
        else : # 其它消息
            flicker =False

        if flicker:
            QtGui.QApplication.alert(self, 0) # windows任务栏闪烁提醒.   
Example #2
0
 def socket_read_data(self, sock, data):
     input =data.encode('utf-8')
     print 'recved:', data[8:]
     d =pack.unpack(self.pwd, input)
     if len(d)<1:
         return
     chid =d['chid']
     txt =d['txt']
     timenow =d['timenow']
     self.editOutput.append('['+timenow +'] '+chid +u' 说: '+ txt +u'\n')
     
     QtGui.QApplication.alert(self, 0)
Example #3
0
def init():
    if args.args.get('pack'):
        pack.pack(args.args['pack'])
        sys.exit()
    if args.args.get('pack_data'):
        pack.pack_data(args.args['pack_data'])
        sys.exit()
    if args.args.get('unpack'):
        pack.unpack(args.args['unpack'])
        sys.exit()

    if not os.path.isdir('accounts'):
        try:
            os.mkdir('accounts')
        except PermissionError:
            print('Unable to create accounts directory')
            sys.exit()
    acc = args.args['account']
    if acc is None:
        acc = forceInput('Enter account name ({}): '.format(
            listAccounts() or 'no existing accounts'))

    if not validateName(acc):
        print('Invalid account name')
        sys.exit()
    if accountExists(acc):
        selectAccount(acc)
    else:
        try:
            if not listAccounts() or input(
                    'Account {} does not exist. Create it? [y/n]'.format(
                        acc)).lower() == 'y':
                print('Creating new account')
                createAccount(acc)
            else:
                sys.exit()
        except EOFError:
            print()
            sys.exit()
Example #4
0
 def recv(self):
     while self.connected:
         try:
             header = self.sock.recv(68)
             header_maps = unpack(header)
             resp_id = header_maps["id"]
             resp_length = header_maps["length"]
             data = ""
             if resp_length > 0:
                 buff = self.sock.recv(resp_length)
                 data = data_unpack(buff)
             self.recv_map[resp_id] = data
         except Exception as e:
             self.connected = False
Example #5
0
 def recv(self, client):
     while self.clients[client]["loop"]:
         try:
             header = client.recv(68)
             header_maps = unpack(header)
             resp_id = header_maps["id"]
             resp_length = header_maps["length"]
             data = ""
             if resp_length > 0:
                 buff = client.recv(resp_length)
                 data = data_unpack(buff)
             self.clients[client]["recv_map"][resp_id] = data
         except Exception as e:
             self.clients[client]["loop"] = False
             break
Example #6
0
def receive(s, fStopped=None, bClose=True, bufsize=2048, fPercentUpdate=None):
    if fStopped:
        s.settimeout(SOCKET_TIMEOUT)
    result = ''
    data = None
    nToReceive = None
    nMetadataLength = 0

    while 1:
        try:
            data = s.recv(bufsize)
        except:
            if fStopped and fStopped():
                if bClose:
                    s.close()
                return None
        if fStopped and fStopped():
            if bClose:
                s.close()
            return None
        if data:
            if not nToReceive:
                match = re.search('[0-9]*', data)
                if not match:
                    return None
                tmp = match.group(0)
                nMetadataLength = len(tmp)+1
                nToReceive = float(int(tmp) + nMetadataLength)
            result += data
            data = None
            if fPercentUpdate:
                fPercentUpdate(len(result)/nToReceive)
            if len(result) >= nToReceive:
                result = result[nMetadataLength:]
                break
        else:
            time.sleep(SOCKET_TIMEOUT)
            continue
    return pack.unpack(result)
Example #7
0
def parseData(sx, addr, data):
    opcode, ts, identity, verif, encrypted, actdata = pack.unpack_json(data)
    if encrypted:
        query = session.query(identity=identity).first()
        if query:
            opcode, ts, identity, verif, encrypted, actdata = pack.unpack(data, key=query.key)

    operation=None
    for op, code in pack.opcode_mapping.items():
        if code==opcode:
            operation=op
    
    if operation=='register':
        _key=secrets.token_hex(16).encode()
        key = base64.b64encode(_key).decode()
        identity = secrets.token_hex(16)
        keycollection(rand=actdata['rand'], key=key).save()
        connection_send(sx,addr,pack.pack_json('success',{
            'message':'Identity created',
            'identity': identity
        }, encrypted=True, key=_key))
    elif operation=='tokenexchange':
        session(identity = identity, token = actdata['token'], key = query.key).save()
Example #8
0
            if not args.password:
                args.password = raw_input('Password: '******'compression']:
            n, f = info['compression']
            log("Compression: %s" % n)
            data = f(data)
            if data is None:
                die("Decompression failed")

        log("Unpacking...")

        numFiles, numBytes = unpack(data, args.outdir or '.')

        log("Unpacked %d file(s) (%s)" % (numFiles, bytesToStr(numBytes)))

    elif args.create:
        dst = args.create
        info = [VERSION] + [0] * 11
        data = pack(args.src)
        pieces = []

        if args.compress != False:
            args.compress = args.compress or 'zlib'
            log('Compression: %s' % args.compress)
            n, f = {
                'zlib': (1, comp.zlib.compress),
                'hmc': (2, comp.hmc.compress),
Example #9
0
    def socket_read_data(self, sock, data):
        # zokket收到的是unicode编码 ,转换为utf-8再进行json解析。
        input = data.encode('utf-8')
        d = pack.unpack(self.pwd, input)
        if print_log:
            print 'typeof unpack result:', type(d)
            print 'unpack input=', input
            print 'unpack output=', d
        if len(d) < 1:
            return
        if type(d) != type({}):
            return
        # 注意json解析结果是unicode编码 !
        cmd = d['cmd']
        chid = d['chid']
        timenow = d['timenow']

        chid_utf8 = chid.encode('utf-8')
        flicker = True
        if u'new_client_join' == cmd:  # 已经在线的人 收到新加入报文,发出自己在线的通知
            self.onNewClientJoin(chid_utf8, timenow)
        if u'client_leave' == cmd:  # 已经在线的人 收到其它人离线报文
            if self.all_chids.has_key(chid_utf8):
                del (self.all_chids[chid_utf8])
                self.editOutput.append(u'[%s] [系统消息] %s 离开了聊天' %
                                       (self.formatTime(timenow), chid))

        elif u'already_online_client' == cmd:  # 新加入的人收到其它在线通知
            if self.chid == d['new_join_chid'].encode('utf-8'):  # 只有新加入的人才处理
                self.all_chids[chid_utf8] = {
                    "join_time": d['join_time'],
                    "last_heartbeat_time": d['join_time']
                }

        elif u'sendfile' == cmd:  # 收到文件通知
            self.onRecvedFile(d, chid_utf8, timenow)
        elif u'recvfile' == cmd:  # 接收文件通知,只有发送者才处理这条报文
            if str(d['sender_chid'].encode('utf-8')) == self.chid:
                QtGui.QMessageBox.information(
                    self, u'系统通知', u'%s 接受了文件%s' % (chid, d['filename']))
        elif u'rejectfile' == cmd:  # 拒接文件通知,只有发送者才处理这条报文
            if str(d['sender_chid'].encode('utf-8')) == self.chid:
                QtGui.QMessageBox.information(
                    self, u'系统通知', u'%s 拒接了文件%s' % (chid, d['filename']))

        elif u'msg' == cmd:  # 收到消息
            self.editOutput.append(u'[%s] %s 说: %s' %
                                   (self.formatTime(timenow), chid, d['txt']))

        elif u'heartbeat' == cmd:  # 收到心跳
            flicker = False

            if self.all_chids.has_key(chid_utf8):
                self.all_chids[chid_utf8]["last_heartbeat_time"] = timenow
            else:
                # 说明长时间没有收到心跳,已经移除了通道信息。但是过段时间又收到了心跳,故认为网络恢复了。
                #   所以考虑容错时重新保存通道信息,但是丢失了原始的 join_time,用当前时间代替。
                self.all_chids[chid_utf8] = {
                    "join_time": timenow,
                    "last_heartbeat_time": timenow
                }

            self.lableShow.setText(u'%s 收到来自[%s]心跳' %
                                   (self.formatTime(timenow), chid))
        else:  # 其它消息
            flicker = False

        if flicker:
            QtGui.QApplication.alert(self, 0)  # windows任务栏闪烁提醒.