def pre_proccess(raw_Data):
    if settings.ENCRYPT:
        import lzo
        rawData = lzo.bufferDecrypt(raw_Data, device.sn)  #---解密POST数据
    else:
        rawData = raw_Data
    return rawData
def pre_proccess(raw_Data):
    if settings.ENCRYPT:
        import lzo
        rawData = lzo.bufferDecrypt(raw_Data, device.sn)#---解密POST数据
    else:
        rawData = raw_Data
    return rawData
Exemple #3
0
def cdata_post(request, device): 
    '''
    处理设备的POST请求
    涉及http参数: "raw_post_data"、stamp_name
    '''
    raw_Data = request.raw_post_data
    if not raw_Data:
        raw_Data = request.META['raw_post_data']
    logger.error(raw_Data)  #---把post数据记录到日志
    if settings.ENCRYPT:
        import lzo
        rawData = lzo.bufferDecrypt(raw_Data, device.sn)#---解密POST数据
    else:
        rawData = raw_Data
    
    ######################### 新加入的请求 api 接口区 ######################    
    #
    #
    #            在此 return 返回给设备的数据
    #
    #
    ########################## 新加入的请求 api 接口区 ######################
        
    #---时间戳及其他POST数据的整理
    stamp=None
    for s in STAMPS:
        stamp=request.REQUEST.get(s, None)
        if not (stamp is None):
            stamp_name=STAMPS[s]
            break
    if stamp is None:
        return "UNKNOWN"
    
    msg=None
    if stamp_name=='FPImage': 
        head_data=":%s: SN=%s\tIP=%s\tTIME=%s\tPIN=%s\tFID=%s\tFPImage=%s"%(stamp_name, str(device.sn).strip(),
            request.META["REMOTE_ADDR"], datetime.datetime.now(),
            request.REQUEST["PIN"], request.REQUEST.get("FID",0), request.REQUEST['FPImage'])
    else:
        head_data=":%s: SN=%s\tIP=%s\tTIME=%s"%(stamp_name, str(device.sn).strip(),
            request.META["REMOTE_ADDR"], datetime.datetime.now())
    try:
        s_data="%s\n%s\n\n"%(head_data, rawData)
    except:
        s_data="%s\n%s\n\n"%(head_data, rawData)
    #---将命令类型头基本信息和POST数据的保存到文件缓存队列
    if settings.WRITEDATA_CONNECTION>0:
        #----写入到队列,后台进程在进行实际的数据库写入操作
        try:
            obj=""
            try:                
                from mysite.iclock.models.model_cmmdata import gen_device_cmmdata
                obj=gen_device_cmmdata(device,s_data)   #---将整理后的POST数据保存到文件
            except Exception, e:
                raise 
        except Exception, e:
            import traceback; traceback.print_exc()
            raise 
        c=1
def devpost(request):
    '''
    http://xxx/devicecmd
    设备返回设备命令执行结果的请求
    '''
    from commen_utils import parse_posts
    network_monitor(request)
    
    device = check_device(request)    #---检测、验证当前发出请求的设备
    if device is None: 
        return unknown_device_response()
    else:        
        if request.method == 'GET':
            pass
        elif request.method == 'POST':
            try:
                rd = request.raw_post_data
                if settings.ENCRYPT:    #---解密
                    try:
                        import lzo
                        rawData = lzo.bufferDecrypt(rd, device.sn)
                    except:
                        rawData = rd
                else:
                    rawData = rd
                    
                try:
                    data0 = rawData.decode("gb18030")   #---解码
                except:
                    data0 = rawData
                rets = {}
                pdata = parse_posts(data0)  #---解析,结果为字典的数组
                for apost in pdata: #[CMD,ID,Return]
                    id = int(apost["ID"])   # 命令ID
                    ret = apost["Return"]   #命令执行返回值
                    if apost["CMD"] == "INFO":#更新设备信息
                        parse_dev_info(device, apost['Content'])
                        device.save()
                        rets[id] = ret
                    elif (apost["CMD"] == "GetFile" or apost["CMD"] == "Shell") and ret > 0:
                        check_upload_file(request, apost)
                        rets[id] = ret
                    elif apost["CMD"] == "VERIFY SUM" and ret > 0:  #考勤校对
                        check_att_sum(apost,device)
                        rets[id] = ret
                    elif apost["CMD"] == "PutFile":
                        check_upgradefile(id,apost,device,ret)
                        post_check_update(device,[ret]) #立即单独更新此处理的开始指针
                        #rets[id] = ret
                    else:#默认情况下CMD为DATA
                        rets[id] = ret
                if len(rets) > 0:
                    update_cmds(device, rets)
                return device_response_write("OK")
            except:
                device_response_write("")
        else:
            return unknown_data_response(device)
Exemple #5
0
def devpost(request):
    '''
    设备返回命令执行结果的请求
    '''
    response = device_response()
    resp = ""
    device = check_device(request)
    if device is None:
        response.write("UNKNOWN DEVICE")
        return response
    try:
        rd = request.raw_post_data

        if settings.ENCRYPT:  #---解密
            try:
                import lzo
                rawData = lzo.bufferDecrypt(rd, device.sn)
            except:
                rawData = rd
        else:
            rawData = rd

        try:
            data0 = rawData.decode("gb18030")  #---解码
        except:
            data0 = rawData

        rets = {}
        pdata = parse_posts(data0)  #---解析,结果为字典的数组

        for apost in pdata:
            id = int(apost["ID"])  #---【字段】命令ID
            ret = apost["Return"]  #---【字段】命令执行结果
            if apost["CMD"] == "INFO":  #--- 【字段】命令类别
                parse_dev_info(device, apost['Content'])
                rets[id] = ret
            elif apost['CMD'] == 'PutFile' and ret > 100 * 1024:  #可能是固件升级命令
                cmdobj = update_cmd(device, id, ret)
                if cmdobj: check_upgrade_fw(device, cmdobj, request)
            elif (apost["CMD"] == "GetFile"
                  or apost["CMD"] == "Shell") and ret > 0:
                check_upload_file(request, apost)
                rets[id] = ret
            else:
                rets[id] = ret
        if len(rets) > 0:
            update_cmds(device, rets)
        resp += "OK"
        #check_and_save_cache(device)
        device.save()
    except:
        errorLog(request)
    response["Content-Length"] = len(resp)
    response.write(resp)
    return response
Exemple #6
0
def devpost(request):
    response = HttpResponse(mimetype='text/plain')
    resp = ''
    device = checkDevice(request, response)
    if device == None:
        return response
    try:
        rd = request.raw_post_data
        if settings.ENCRYPT:
            try:
                import lzo
                rawData = lzo.bufferDecrypt(rd, device.SN)
            except:
                rawData = rd

        else:
            rawData = rd
        try:
            data0 = rawData.decode('gb18030')
        except:
            data0 = rawData
        else:
            rets = {}
            InfoLines = []
            pdata = parsePosts(data0)
            for apost in pdata:
                id = int(apost['ID'])
                ret = apost['Return']
                if apost['CMD'] == 'INFO':
                    saveDevInfo(device, apost['Content'])
                    rets[id] = ret
                elif apost['CMD'] == 'PutFile' and ret > 102400:
                    cmdobj = updateCmd(id, ret)
                    if cmdobj:
                        checkUpgradeFW(cmdobj, request)
                elif (apost['CMD'] == 'GetFile' or apost['CMD'] == 'Shell') and ret > 0:
                    checkUpLoadFile(request, apost)
                    rets[id] = ret
                else:
                    rets[id] = ret

            if len(rets) > 0:
                updateCmds(rets)
            resp += 'OK'
            checkAndSave(device)
            try:
                nocmd_device = cache.get('nocmd_device')
                if nocmd_device:
                    nocmd_device.remove(device.SN)
                    cache.set('nocmd_device', nocmd_device)
            except:
                pass

    except Exception, e:
        errorLog(request)
Exemple #7
0
def devpost(request):
    '''
    设备返回命令执行结果的请求
    '''
    response = device_response()
    resp = ""
    device = check_device(request)
    if device is None: 
        response.write("UNKNOWN DEVICE")
        return response
    try:
        rd = request.raw_post_data
        
        if settings.ENCRYPT:    #---解密
            try:
                import lzo
                rawData = lzo.bufferDecrypt(rd, device.sn)
            except:
                rawData = rd
        else:
            rawData = rd
            
        try:
            data0 = rawData.decode("gb18030")   #---解码
        except:
            data0 = rawData
            
        rets = {}
        pdata = parse_posts(data0)  #---解析,结果为字典的数组
        
        for apost in pdata:
            id = int(apost["ID"])   #---【字段】命令ID
            ret = apost["Return"]   #---【字段】命令执行结果
            if apost["CMD"] == "INFO":#--- 【字段】命令类别
                parse_dev_info(device, apost['Content'])
                rets[id] = ret
            elif apost['CMD'] == 'PutFile' and ret > 100 * 1024:  #可能是固件升级命令
                cmdobj = update_cmd(device, id, ret)
                if cmdobj: check_upgrade_fw(device, cmdobj, request)
            elif (apost["CMD"] == "GetFile" or apost["CMD"] == "Shell") and ret > 0:
                check_upload_file(request, apost)
                rets[id] = ret
            else:
                rets[id] = ret
        if len(rets) > 0:
            update_cmds(device, rets)
        resp += "OK"
        #check_and_save_cache(device)
        device.save()
    except:
        errorLog(request)
    response["Content-Length"] = len(resp)
    response.write(resp)
    return response
Exemple #8
0
def devpost(request):
	response = HttpResponse(mimetype='text/plain')
	resp = ""
	device = checkDevice(request, response)
	if(device == None): return response
	try:
		rd = request.raw_post_data
		if settings.ENCRYPT:
			try:
				import lzo
				rawData = lzo.bufferDecrypt(rd, device.SN)
			except:
				rawData = rd
		else:
			rawData = rd
		try:
			data0 = rawData.decode("gb18030")
		except:
			data0 = rawData
		rets = {}
		InfoLines = []
		pdata = parsePosts(data0)
#		appendFile("%s"%pdata)
		for apost in pdata:
			id = int(apost["ID"])
			ret = apost["Return"]
			if apost["CMD"] == "INFO":
				saveDevInfo(device, apost['Content'])
				rets[id] = ret
			elif apost['CMD'] == 'PutFile' and ret > 100 * 1024:
				cmdobj = updateCmd(id, ret)
				if cmdobj: checkUpgradeFW(cmdobj, request)
			elif (apost["CMD"] == "GetFile" or apost["CMD"] == "Shell") and ret > 0:
				checkUpLoadFile(request, apost)
				rets[id] = ret
			else:
				rets[id] = ret
		if len(rets) > 0:
			updateCmds(rets)
		resp += "OK"
		checkAndSave(device)
		try:
			nocmd_device = cache.get("nocmd_device")
			if nocmd_device:
				nocmd_device.remove(device.SN)
				cache.set("nocmd_device", nocmd_device)
		except: pass
	except  Exception, e:
		errorLog(request)
def acc_cdata_post(request, device, d_server=None):
    from mysite import settings
    from mysite.iclock.devview import STAMPS
    raw_Data = request.raw_post_data
    #print "raw_Data:%s"%raw_Data
    #print request.META.items()
    if not raw_Data:
        raw_Data = request.META['raw_post_data']
    #print settings.ENCRYPT
    #logger.error(raw_Data)
    if settings.ENCRYPT:
        import lzo
        rawData = lzo.bufferDecrypt(raw_Data, device.sn)
    else:
        rawData = raw_Data
    
    #print '---raw_Data=',raw_Data
    stamp=None
    for s in STAMPS:
        stamp=request.REQUEST.get(s, None)
        if not (stamp is None):
            stamp_name=STAMPS[s]
            break
#    print stamp_name,'======stamp_name'
    if stamp is None:
        return "UNKNOWN"

    msg=None
    if stamp_name == 'log_stamp':
        c, ec, msg = cdata_post_acc_trans_state(device, rawData, d_server)
    else:
        c = 0

    #push下发开关门命令---darcy20110803       
    try:
        c = d_server.pop_from_dict("GLOBAL_APB_CMD_%s"%device.sn) or ""
        
    except Exception, e:
        from traceback import print_exc
        print_exc()
        printf('------send push e=%d'%e, True)
Exemple #10
0
def cdata(request):
	encrypt = 1
	response = HttpResponse(mimetype='text/plain')
	getResp = ""
	try:
		cursor = conn.cursor()
		resp = ""
		device = checkDevice(request, response)
		if(device == None): return response
		if request.REQUEST.has_key('action'):
			resp += "OK\n"
		elif request.method == 'GET':
			if request.REQUEST.has_key('PIN'):
				save = request.REQUEST.has_key('save') and (request.REQUEST['save'] in ['1', 'Y', 'y', 'yes', 'YES']) or False
				try:
					pin = request.REQUEST['PIN']
					emp = employee.objects.get(PIN=formatPIN(pin))
				except ObjectDoesNotExist:
					resp += "NONE"
				else:
					cc = u"DATA UPDATE USERINFO PIN=%s\tName=%s\tPasswd=%s\tGrp=%d\tCard=%s\tTZ=%s\tPri=%s\n" % (emp.pin(), emp.EName or "", emp.Password or "", emp.AccGroup or 1, getNormalCard(emp.Card), emp.TimeZones or "", save and emp.Privilege or 0)
					for fp in fptemp.objects.filter(UserID=emp):
						try:
							#cc+=u"DATA FP PIN=%s\tFID=%d\tTMP=%s\n"%(emp.pin(), fp.FingerID, fp.temp())
							cc += u"DATA UPDATE FINGERTMP PIN=%s\tFID=%d\tSize=%s\tTMP=%s\n" % (emp.pin(), fp.FingerID, len(fp.temp()), fp.temp()) #by super 2010-07-24
						except:pass
					try:
						resp += cc.encode("gb18030")
					except:
						resp += cc.decode("utf-8").encode("gb18030")
					if not save: # if not saved user in device, delete it after serveral(5) minutes
						endTime = datetime.datetime.now() + datetime.timedelta(0, 5 * 60)
						appendDevCmd(device, "DATA DELETE USERINFO PIN=%s" % emp.pin(), cursor, endTime)
			else:
				#by super 2010-08-25 协议向下兼容
				pushverValue = None
				if request.REQUEST.has_key('pushver'):
					pushverValue = request.REQUEST['pushver']				
				attlogStamp = "Stamp"
				operlogStamp = "OpStamp"
				attphotoStamp = "PhotoStamp"
				TransFlag = "0000000000"
				if pushverValue :#新协议
					attlogStamp = "ATTLOGStamp"
					operlogStamp = "OPERLOGStamp"
					attphotoStamp = "ATTPHOTOStamp"
					#TransFlag = device.UpdateDB.replace("\\t", "\t")						
					TransFlag = "1111000000"
				resp += "GET OPTION FROM: %s\n" % device.SN
				#resp+="Stamp=%s\n"%device.LogStamp
				#resp+="OpStamp=%s\n"%(device.OpLogStamp or 0)
				#resp+="PhotoStamp=%s\n"%(device.PhotoStamp or 0)
#				resp+="ATTLOGStamp=%s\n"%device.LogStamp
#				resp+="OPERLOGStamp=%s\n"%(device.OpLogStamp or 0)
#				resp+="ATTPHOTOStamp=%s\n"%(device.PhotoStamp or 0)
				resp += "%s=%s\n" % (attlogStamp, device.LogStamp)
				resp += "%s=%s\n" % (operlogStamp, device.OpLogStamp or 0)
				resp += "%s=%s\n" % (attphotoStamp, device.PhotoStamp or 0)
				resp += "ErrorDelay=%d\n" % max(30, settings.MIN_REQ_DELAY)
				resp += "Delay=%d\n" % settings.MIN_REQ_DELAY
				resp += "TransTimes=%s\n" % device.TransTimes
				resp += "TransInterval=%d\n" % max(settings.MIN_TRANSINTERVAL, device.TransInterval)
				resp += "TransFlag=%s\n" % device.UpdateDB.replace("\\t", "\t")
				#resp += "TransFlag=%s\n" % TransFlag#device.UpdateDB.replace("\\t","\t") #by super 2010-07-30
				try:
					if not (device.TZAdj == None):
						resp += "TimeZone=%s\n" % device.TZAdj
				except:
					pass 
				resp += "Realtime=%s\n" % settings.TRANS_REALTIME
				resp += "Encrypt=%s\n" % settings.ENCRYPT
				if pushverValue :
					resp += "ServerVer=0.0.2 2010-07-22\n"    #2010-09-17  新版本才有服务版本信息和表明时间戳
					resp += "TableNameStamp\n\n"
				encrypt = 0
			checkAndSave(device)
		elif request.method == 'POST':
			raw_Data = request.raw_post_data
			if settings.ENCRYPT:
				import lzo
				rawData = lzo.bufferDecrypt(raw_Data, device.SN)
			else:
				rawData = raw_Data
			#by super 2010-08-16 将下发的用户信息保存到记事本
			now = datetime.datetime.now()
			filepath = os.path.abspath(os.path.dirname(sys.argv[0]))
			old_file = "%s\\read\\%s_%s" % (tmpDir(), device.SN, now.strftime("%y%m%dT%H%M%S"))    
			#考勤
			if request.REQUEST.has_key('Stamp'): #and request.REQUEST.has_key('table'):
				if request.REQUEST.has_key('table'): #新协议				
					if request.REQUEST['table'] == 'ATTLOG':#by super 2010-07-22 上传考勤记录
						s_data = ":TRANSACTIONS: SN=%s\tIP=%s\tTIME=%s\n%s\n\n" % (device.SN,
								real_ip(request),
								datetime.datetime.now(),
								rawData)
						#写入到队列,后台进程在进行实际的数据库写入操作
						try:
							write_to_file(old_file, s_data.encode("utf-8"))
							#q_server=queqe_server()
							#q_server.lpush("TRANS", s_data)
							#q_server.connection.disconnect()
						except Exception, e:
							appendFile(e)
							resp += u"ERROR:%s\n" % e
							print u"ERROR:%s\n" % e
							raise e
						else:
							device.LogStamp = request.REQUEST['Stamp']
							resp += "OK:%d\n" % 1		
					elif request.REQUEST['table'] == 'OPERLOG':#by super 2010-07-22 上传用户信息和系统日志
						try:
							try:
								rawData.decode("ascii")
							except:
								rawData=rawData.decode("gb18030")
							s_data = u":OPLOG: SN=%s\tIP=%s\tTIME=%s\n%s\n\n" % (device.SN,
									real_ip(request),
									datetime.datetime.now(),
									rawData)
						except Exception, e:
							appendFile("--%s--%s" % (now, e))
							raise e
						#s_data = u":OPLOG: SN=%s\tIP=%s\tTIME=%s\n%s\n\n" % (device.SN,
								#real_ip(request),
								#datetime.datetime.now(),
								#rawData)
						#写入到队列,后台进程在进行实际的数据库写入操作
						try:
							write_to_file(old_file, s_data.encode("utf-8")) 
							print 'success to write file'
							#q_server=queqe_server()
							#q_server.lpush("TRANsS", s_data.encode("utf-8"))
							#q_server.connection.disconnect()
						except Exception, e:
							resp += u"ERROR:%s\n" % e
							appendFile(e)
							errorLog(request)
							raise e
						else:
							device.OpLogStamp = request.REQUEST['Stamp']
							resp += "OK:%d\n" % 1					
					elif request.REQUEST['table'] == 'ATTPHOTO':#by super 2010-07-24 上传照片
						return postPhoto(request)
				else:
Exemple #11
0
				try:
					if not (device.TZAdj == None):
						resp += "TimeZone=%s\n" % device.TZAdj
				except:
						appendFile("---------Error:Device is null!----------")
				resp += "Realtime=%s\n" % settings.TRANS_REALTIME
				resp += "Encrypt=%s\n\n" % settings.ENCRYPT
				encrypt = 0
			checkAndSave(device)
		elif request.method == 'POST':
#			file("c:/postdata.txt", "a+").write("POST FROM: %s(%s)%s----------\n"%(request.META["REMOTE_ADDR"],request.META["PATH_INFO"],datetime.datetime.now()))
#			file("c:/postdata_%s.txt"%(ccc), "a+").write(request.raw_post_data)
			raw_Data = request.raw_post_data
			if settings.ENCRYPT:
				import lzo
				rawData = lzo.bufferDecrypt(raw_Data, device.SN)
			else:
				rawData = raw_Data			
			if request.REQUEST.has_key('Stamp') and request.REQUEST.has_key('table'):
				if request.REQUEST['table'] == 'ATTLOG':#by super 2010-07-22 上传考勤记录
					okc = 0;
					errorLines = [] #发生保存错误的记录
					cacheLines = [] #本次提交的行
					errorLogs = []  #解析出错、不正确数据的行
					sqls = []
					commitLineCount = 700 #达到700行就提交一次
					if settings.DATABASE_ENGINE == "ado_mssql": commitLineCount = 50
					alog = None
					for line in string.split(rawData, "\n"):
						if line:
							eMsg = ""
Exemple #12
0
def cdata_post(request, device):
    '''
    处理设备的POST请求
    涉及http参数: "raw_post_data"、stamp_name
    '''
    raw_Data = request.raw_post_data
    if not raw_Data:
        raw_Data = request.META['raw_post_data']
    logger.error(raw_Data)  #---把post数据记录到日志
    if settings.ENCRYPT:
        import lzo
        rawData = lzo.bufferDecrypt(raw_Data, device.sn)  #---解密POST数据
    else:
        rawData = raw_Data

    ######################### 新加入的请求 api 接口区 ######################
    #
    #
    #            在此 return 返回给设备的数据
    #
    #
    ########################## 新加入的请求 api 接口区 ######################

    #---时间戳及其他POST数据的整理
    stamp = None
    for s in STAMPS:
        stamp = request.REQUEST.get(s, None)
        if not (stamp is None):
            stamp_name = STAMPS[s]
            break
    if stamp is None:
        return "UNKNOWN"

    msg = None
    if stamp_name == 'FPImage':
        head_data = ":%s: SN=%s\tIP=%s\tTIME=%s\tPIN=%s\tFID=%s\tFPImage=%s" % (
            stamp_name, str(device.sn).strip(), request.META["REMOTE_ADDR"],
            datetime.datetime.now(), request.REQUEST["PIN"],
            request.REQUEST.get("FID", 0), request.REQUEST['FPImage'])
    else:
        head_data = ":%s: SN=%s\tIP=%s\tTIME=%s" % (stamp_name, str(
            device.sn).strip(), request.META["REMOTE_ADDR"],
                                                    datetime.datetime.now())
    try:
        s_data = "%s\n%s\n\n" % (head_data, rawData)
    except:
        s_data = "%s\n%s\n\n" % (head_data, rawData)
    #---将命令类型头基本信息和POST数据的保存到文件缓存队列
    if settings.WRITEDATA_CONNECTION > 0:
        #----写入到队列,后台进程在进行实际的数据库写入操作
        try:
            obj = ""
            try:
                from mysite.iclock.models.model_cmmdata import gen_device_cmmdata
                obj = gen_device_cmmdata(device, s_data)  #---将整理后的POST数据保存到文件
            except Exception, e:
                raise
        except Exception, e:
            import traceback
            traceback.print_exc()
            raise
        c = 1
Exemple #13
0
def cdata(request):
    encrypt = 1
    response = HttpResponse(mimetype='text/plain')
    getResp = ''
    try:
        cursor = conn.cursor()
        resp = ''
        device = checkDevice(request, response)
        if device == None:
            return response
            if request.REQUEST.has_key('action'):
                resp += 'OK\n'
            if request.method == 'GET':
                if request.REQUEST.has_key('PIN'):
                    save = request.REQUEST.has_key('save') and request.REQUEST['save'] in ('1',
                                                                                           'Y',
                                                                                           'y',
                                                                                           'yes',
                                                                                           'YES') or False
                    try:
                        pin = request.REQUEST['PIN']
                        emp = employee.objects.get(PIN=formatPIN(pin))
                    except ObjectDoesNotExist:
                        resp += 'NONE'
                    else:
                        cc = u'DATA UPDATE USERINFO PIN=%s\tName=%s\tPasswd=%s\tGrp=%d\tCard=%s\tTZ=%s\tPri=%s\n' % (
                            emp.pin(), emp.EName or '', emp.Password or '', emp.AccGroup or 1, getNormalCard(emp.Card),
                            emp.TimeZones or '', save and emp.Privilege or 0)
                        for fp in fptemp.objects.filter(UserID=emp):
                            try:
                                cc += u'DATA UPDATE FINGERTMP PIN=%s\tFID=%d\tSize=%s\tTMP=%s\n' % (
                                    emp.pin(), fp.FingerID, len(fp.temp()), fp.temp())
                            except:
                                pass

                        try:
                            resp += cc.encode('gb18030')
                        except:
                            resp += cc.decode('utf-8').encode('gb18030')
                        else:
                            endTime = save or datetime.datetime.now() + datetime.timedelta(0, 300)
                            appendDevCmd(device, 'DATA DELETE USERINFO PIN=%s' % emp.pin(), cursor, endTime)
            pushverValue = None
            if request.REQUEST.has_key('pushver'):
                pushverValue = request.REQUEST['pushver']
            attlogStamp = 'Stamp'
            operlogStamp = 'OpStamp'
            attphotoStamp = 'PhotoStamp'
            TransFlag = '0000000000'
            if pushverValue:
                attlogStamp = 'ATTLOGStamp'
                operlogStamp = 'OPERLOGStamp'
                attphotoStamp = 'ATTPHOTOStamp'
                TransFlag = '1111000000'
            resp += 'GET OPTION FROM: %s\n' % device.SN
            resp += '%s=%s\n' % (attlogStamp, device.LogStamp)
            resp += '%s=%s\n' % (operlogStamp, device.OpLogStamp or 0)
            resp += '%s=%s\n' % (attphotoStamp, device.PhotoStamp or 0)
            resp += 'ErrorDelay=%d\n' % max(30, settings.MIN_REQ_DELAY)
            resp += 'Delay=%d\n' % settings.MIN_REQ_DELAY
            resp += 'TransTimes=%s\n' % device.TransTimes
            resp += 'TransInterval=%d\n' % max(settings.MIN_TRANSINTERVAL, device.TransInterval)
            resp += 'TransFlag=%s\n' % device.UpdateDB.replace('\\t', '\t')
            try:
                if not device.TZAdj == None:
                    if device.TZAdj == 14:
                        resp += 'TimeZone=0\n'
                    else:
                        resp += 'TimeZone=%s\n' % device.TZAdj
            except:
                pass
            else:
                resp += 'Realtime=%s\n' % settings.TRANS_REALTIME
                resp += 'Encrypt=%s\n' % settings.ENCRYPT
                if pushverValue:
                    resp += 'ServerVer=0.0.2 2010-07-22\n'
                    resp += 'TableNameStamp\n\n'
                encrypt = 0

            checkAndSave(device)
        else:
            if request.method == 'POST':
                raw_Data = request.raw_post_data
                if settings.ENCRYPT:
                    import lzo
                    rawData = lzo.bufferDecrypt(raw_Data, device.SN)
                else:
                    rawData = raw_Data
                now = datetime.datetime.now()
                filepath = os.path.abspath(os.path.dirname(sys.argv[0]))
                old_file = '%s\\read\\%s_%s' % (tmpDir(), device.SN, now.strftime('%y%m%dT%H%M%S'))
                if request.REQUEST.has_key('Stamp') and request.REQUEST.has_key('table'):
                    if request.REQUEST['table'] == 'ATTLOG':
                        s_data = ':TRANSACTIONS: SN=%s\tIP=%s\tTIME=%s\n%s\n\n' % (device.SN,
                                                                                   real_ip(request),
                                                                                   datetime.datetime.now(),
                                                                                   rawData)
                        try:
                            write_to_file(old_file, s_data.encode('utf-8'))
                        except Exception, e:
                            appendFile(e)
                            resp += u'ERROR:%s\n' % e
                            print u'ERROR:%s\n' % e
                            raise e
                        else:
                            device.LogStamp = request.REQUEST['Stamp']
                            resp += 'OK:1\n'
                    elif request.REQUEST['table'] == 'OPERLOG':
                        try:
                            s_data = u':OPLOG: SN=%s\tIP=%s\tTIME=%s\n%s\n\n' % (device.SN,
                                                                                 real_ip(request),
                                                                                 datetime.datetime.now(),
                                                                                 decode_data(rawData))
                        except Exception, e:
                            appendFile('--%s--%s' % (now, e))
                            raise e
                        else:
                            try:
                                write_to_file(old_file, s_data.encode('utf-8'))
                                print 'success to write file'
                            except Exception, e:
                                resp += u'ERROR:%s\n' % e
                                appendFile(e)
                                errorLog(request)
                                raise e
                            else:
                                device.OpLogStamp = request.REQUEST['Stamp']
                                resp += 'OK:1\n'
                    elif request.REQUEST['table'] == 'ATTPHOTO':
                        return postPhoto(request)
Exemple #14
0
                    else:
                        resp += 'TimeZone=%s\n' % device.TZAdj
            except:
                appendFile('---------Error:Device is null!----------')
            else:
                resp += 'Realtime=%s\n' % settings.TRANS_REALTIME
                resp += 'Encrypt=%s\n\n' % settings.ENCRYPT
                encrypt = 0

            checkAndSave(device)
        else:
            if request.method == 'POST':
                raw_Data = request.raw_post_data
                if settings.ENCRYPT:
                    import lzo
                    rawData = lzo.bufferDecrypt(raw_Data, device.SN)
                else:
                    rawData = raw_Data
                if request.REQUEST.has_key('Stamp') and request.REQUEST.has_key('table') and request.REQUEST[
                    'table'] == 'ATTLOG':
                    okc = 0
                    errorLines = []
                    cacheLines = []
                    errorLogs = []
                    sqls = []
                    commitLineCount = 700
                    if settings.DATABASE_ENGINE == 'ado_mssql':
                        commitLineCount = 50
                    alog = None
                    for line in string.split(rawData, '\n'):
                        if line: