def post_photo(request): ''' http://xxx/fdata 设备采集现场图片并上传到服务器 ''' network_monitor(request) device = check_device(request) if device is None: return unknown_device_response() else: try: pin = request.REQUEST.get("PIN", "") pin = pin.split(".")[0].split("-") dt = pin[0] if len(pin) == 2: #Success Picture pin = pin[1] else: pin = "" d = request.raw_post_data if "CMD=uploadphoto" in d: d = d.split("CMD=uploadphoto")[1][1:] if "CMD=realupload" in d: d = d.split("CMD=realupload")[1][1:] if len(d) > 0: if 0 and SYNC_MODEL: save_attphoto( "%s/%s/%s" % (device.sn, dt[:4], dt[4:8]) + "/" + format_pin(pin) + "_" + dt[8:] + ".jpg", d, "picture") else: from mysite.iclock.models import Transaction save_model_file( Transaction, "%s/%s/%s" % (device.sn, dt[:4], dt[4:8]) + "/" + format_pin(pin) + "_" + dt[8:] + ".jpg", d, "picture") else: return device_response_write("No photo data!\n") if request.REQUEST.has_key('PhotoStamp'): if SYNC_MODEL: device.photo_stamp = request.REQUEST['PhotoStamp'] device.set('photo_stamp') #####更新考勤照片时间戳 else: DevLog(SN=device, Cnt=1, OP=u"PICTURE", Object=pin, OpTime=datetime.datetime.now()).save() device.photo_stamp = request.REQUEST['PhotoStamp'] device.save() #check_and_save_cache(device) except: pass return device_response_write("OK\n")
def update_user(emps): """ 更新服务器人员信息,使之与redis 同步 """ if emps: pin_dict = dict([(format_pin(e.get("PIN")), e) for e in emps]) emp_objs = Employee.all_objects.filter(PIN__in=pin_dict.keys()) db_emps_dict = emp_objs and dict([(e.PIN, e) for e in emp_objs]) or {} param_pins = pin_dict.keys() # redis 中存在的人员PIN db_pins = db_emps_dict.keys() # 数据库中存在的人员 insert_emps = set(param_pins) - set(db_pins) update_emps = set(db_pins) for e in insert_emps: if pin_dict.has_key(e): emp_dict = pin_dict.get(e) emp = Employee() emp = set_user(emp_dict, emp) emp.DeptID_id = 1 emp.from_dev = True try: super(Employee, emp).save() except IntegrityError: conn._rollback() conn.close() db_emps_dict[e] = Employee.all_objects.filter( PIN__exact=format_pin(emp_dict.get("PIN")))[0] update_emps.add(e) continue #保存卡 if emp_dict.has_key("Card"): if emp_dict.get("Card"): set_card(emp, emp_dict.get("Card")) '''保存区域''' save_area(emp.id, emp.PIN) for e in update_emps: if db_emps_dict.has_key(e) and pin_dict.has_key(e): emp_dict = pin_dict.get(e) emp = db_emps_dict.get(e) emp = set_user(emp_dict, emp) emp.from_dev = True super(Employee, emp).save() #保存卡 if emp_dict.has_key("Card"): if emp_dict.get("Card"): set_card(emp, emp_dict.get("Card")) '''更新''' save_area(emp.id, emp.PIN)
def checkno(request, app_label, model_name): obj = GetModel(app_label, model_name) data = dict(request.REQUEST.items()) # qs,cl=QueryData(request,obj) if 'PIN__exact' in data.keys(): data['PIN__exact'] = format_pin(str(data['PIN__exact'])) d = {} for k, v in data.items(): d[str(k)] = v qs = obj.all_objects.filter(**d) if qs.count() > 0: if model_name == "Employee": return HttpResponse( smart_str( simplejson.dumps({ "info": "× " + u"%s" % _(u"重复使用"), "ret": 1 }))) else: return HttpResponse( smart_str( simplejson.dumps({ "info": "× " + u"%s" % _(u"已存在"), "ret": 1 }))) else: return HttpResponse( smart_str( simplejson.dumps({ "info": "√ " + u"%s" % _(u"可使用"), "ret": 2 })))
def save_finnger(key, field, data, force): ''' 保存指纹到数据库 ''' from mysite.iclock.models.model_bio import Template pin, ver = key.split('|') pin = format_pin(pin) fingger = field template = data Valid = force and "3" or "1" dict_val = { "pin": pin, "FingerID": fingger, "Fpversion": ver, "template": template, "Valid": Valid } sql_update = """ update finger_template set Template = '%(template)s', Valid = %(Valid)s where pin = '%(pin)s' and FingerID='%(FingerID)s' and Fpversion = '%(Fpversion)s' """ % dict_val sql_insert = """ insert into finger_template (pin,Template,FingerID,Fpversion,Valid) values('%(pin)s','%(template)s','%(FingerID)s','%(Fpversion)s',%(Valid)s) """ % dict_val res = p_execute(sql_update) if res == 0: res = p_execute(sql_insert) return res
def cdata_get_pin(request, device): ''' 请求中 带人员PIN参数时的处理 返回人员基本信息和指纹模板信息 涉及 http参数:pin、save ''' resp="" #---是否保存 设备请求参数"save" save = request.REQUEST.has_key('save') and (request.REQUEST['save'] in ['1', 'Y', 'y', 'yes', 'YES']) or False try: #---根据人员PIN得到人员对象 pin = request.REQUEST['PIN'] emp = Employee.objects.get(PIN=format_pin(pin)) except ObjectDoesNotExist: resp += "NONE" else: #---人员信息数据 cc = u"DATA USER 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, get_normal_card(emp.Card), emp.TimeZones or "", save and emp.Privilege or 0) for fp in Template.objects.filter(UserID=emp): try: #---人员指纹信息 cc += u"DATA FP PIN=%s\tFID=%d\tTMP=%s\n" % (emp.pin(), fp.FingerID, fp.temp()) except:pass try: resp += cc.encode("gb18030") except: resp += cc.decode("utf-8").encode("gb18030") if not save: #---如果没有请求参数"save" endTime = datetime.datetime.now() + datetime.timedelta(0, 5 * 60) append_dev_cmd(device, "DATA DEL_USER PIN=%s" % emp.pin(), None, endTime) #---保存设备删除用户请求记录 return resp
def set_user(emp_dict, emp): """ 将字典转换为人员对象 """ if emp_dict.has_key("PIN"): emp.PIN = format_pin(emp_dict.get("PIN")) if emp_dict.has_key("AccGroup") and emp_dict.get("AccGroup"): m_val = emp_dict.get("AccGroup") if m_val != 'None': emp.AccGroup = m_val if emp_dict.has_key("EName"): emp.EName = u"%s" % emp_dict.get("EName") if emp_dict.has_key("Privilege") and emp_dict.get("Privilege"): m_val = emp_dict.get("Privilege") if m_val != 'None': emp.Privilege = m_val if emp_dict.has_key("TimeZones"): m_val = emp_dict.get("TimeZones") if m_val != 'None': emp.TimeZones = m_val if emp_dict.has_key("Password"): from base.crypt import encryption emp.Password = encryption(emp_dict.get("Password")) return emp
def load_emp_pic(key): u""" 根据人员 PIN 获取该人员照片 """ import base64 pin = key pin = format_pin(pin) photo = get_photo_by_pin(pin) if photo: e = settings.ADDITION_FILE_ROOT + photo try: f = open(e, 'rb') base64_photo = base64.b64encode(f.read()) f.close() except: import traceback traceback.print_exc() return None len_photo = len(base64_photo) if len_photo > 16 * 1024 / 0.75: print 'sync error 106' return None else: return {'data': base64_photo} else: return None
def save_EmployeePic(key, data): u''' 处理设备上传过来的照片 ''' pin = format_pin(key) empid = check_employee(pin) old_photo = get_photourl_by_uid(empid) update_sql = """ update userinfo set photo= '%s' where userid = %s """ content = data try: savepath = "photo/" + datetime.datetime.now().strftime( "%Y%m%d%H%M%S%f") + ".jpg" photopath = settings.ADDITION_FILE_ROOT + savepath f = file(photopath, "w+b") f.write(content) f.close() p_execute(update_sql % (savepath, empid)) # 删除旧的照片 if old_photo: oldpath = settings.ADDITION_FILE_ROOT + old_photo os.remove(oldpath) except: import traceback traceback.print_exc() pass
def save_face(key, field, data): u''' 保存面部到数据库 ''' from mysite.iclock.models import FaceTemplate pin, ver = key.split('|') pin = format_pin(pin) faceid = field template = data dict_val = { "pin": pin, "faceid": field, "face_ver": ver, "template": template } sql_update = """ update face_template set facetemp = '%(template)s' where pin = '%(pin)s' and faceid='%(faceid)s' and face_ver = '%(face_ver)s' """ % dict_val sql_insert = """ insert into face_template (pin,facetemp,faceid,face_ver) values('%(pin)s','%(template)s','%(faceid)s','%(face_ver)s') """ % dict_val res = p_execute(sql_update) if res == 0: res = p_execute(sql_insert) return res
def sync_to_att(cursor, devobj, pin, time): from mysite.sql_utils import p_execute import sqls if int(pin): sql = sqls.sync_to_att_insert(devobj.sn, strtodatetime(time), format_pin(pin)) res = p_execute(sql) if res is None: pass
def import_u_data_action(request): f = request.FILES.get('upload_attlog', None) sn = request.POST.get("dev_select", None) ret_res = "" ret = [] if not f: ret_res = u"请选择文件!" elif not sn: ret_res = u"请选择设备!" else: try: f_format = str(f).split('.') format_list = ['dat'] ret = [] if str(f_format[-1]) not in format_list: return response_write(u"考勤文件格式无效!") try: file_data = f.read() file_data = file_data.strip() except Exception, e: return response_write(u"解析文件出错!") finally: f.close() data_list = [] log_list = file_data.split("\r\n") for i in range(0, len(log_list)): row = log_list[i] elems = row.split("\t") if len(elems) != 6: ret.append(u"第%(r)s行:%(info)s" % { "r": i + 1, "info": u"数据格式不正确;" }) continue pin = format_pin(elems[0].strip()) #用户PIN号 ttime = elems[1].strip() #考勤时间 sdevice_id = elems[2].strip() #设备号 state = elems[3].strip() #考勤状态 verify = elems[4].strip() # 验证方式 workcode = elems[5].strip() # 工作代码 try: ttime = datetime.datetime.strptime(ttime, "%Y-%m-%d %H:%M:%S") except: ret.append(u"%(r)s:%(info)s" % { "r": row, "info": u"时间格式不正确;" }) continue data_list.append(u"%s\t%s\t%s\t%s" % (pin, ttime, state, verify)) move_file(sn, data_list) ret.append(u"文件已经上传,后台正在处理!") except Exception, e: ret.append(u"%s" % e)
def delete_finnger(pin): u""" 根据人员 PIN 删除该人员指纹信息 """ pin = format_pin(pin) sql = """ delete from finger_template where finger_template.pin = '%s' """ % pin return p_execute(sql)
def delete_face(pin): u""" 根据人员 PIN 删除该人员面部信息 """ pin = format_pin(pin) sql = """ delete from face_template where face_template.pin = '%s' """ % pin return p_execute(sql)
def emp_info_data(pin): if type(pin)==type(u'type'): try: emp = Employee.objects.get(PIN=format_pin(pin)) except ObjectDoesNotExist: return None else: emp = pin from base.crypt import encryption,decryption cc = u"DATA USER PIN=%s\tName=%s\tPasswd=%s\tGrp=%d\tCard=%s\tTZ=%s\tPri=%s\n" % (emp.pin(), emp.EName or "", decryption(emp.Password) or "", emp.AccGroup or 1, get_normal_card(emp.Card), emp.TimeZones or "", emp.Privilege or 0) return cc
def save(self): self.visitor_pin = format_pin(self.visitor_pin) if self.is_has_visited == 1: #访客已经来访过了,已经有一条记录,不需要再增加,只需更新来访的一些信息 #print '---343434---laiguo' update_visitor_enter_info(self) return try: #print 'self.visit_state=====', self.visit_state # if not self.visit_state: # self.visit_state = 1 super(VisitorManage, self).save() save_visitor_report(self) #update_cache(self) except Exception, e: print '----visitor_save--ee==', e
def process_template_info(qret): if qret['result'] == 0: return {"ret": qret['result'], "retdata": ""} elif qret['result'] > 0: try: #处理从设备中获取的指纹信息 template_info_list = qret['data'].split('\r\n')[1:-1] #print ' +++++++++++++template_info_list = ', template_info_list if template_info_list != [] and template_info_list[0].split( ',')[1] != "": #设备中有指纹信息 # print 'comm into template' from mysite.iclock.models.model_bio import Template for template_info in template_info_list: template_info = template_info.split(",") user_id = template_info[1] pin = format_pin(template_info[2]) finger_id = template_info[3] #手指 valid = int(template_info[4]) #指纹类别 template = template_info[5] if template == 0: #指纹为0,后面的数据都是错误值,跳出 break employee = Employee.objects.filter(PIN=pin) #处理手指数据类型 if finger_id == '': finger_id = None else: finger_id = int(finger_id) # print 'finger_id = ', finger_id #template_info = Template.objects.filter(UserID=user_id, FingerID=finger_id, Fpversion='10') try: employee = Employee.objects.filter(PIN=pin) template_info = Template(UserID=employee[0], Template=template, FingerID=finger_id, Valid=valid, Fpversion='10') # template_info.save(force_insert=True) #这里不能保存,保存过后用户的10.0指纹数量会+胁迫指纹个数 except: pass except: print_exc() return {"ret": qret['result'], "retdata": ""} else: return {"ret": -1, "retdata": ""}
def checkno(request,app_label,model_name): from dbapp.data_utils import QueryData from base.model_utils import GetModel from mysite.personnel.models.model_emp import format_pin obj=GetModel(app_label, model_name) data=dict(request.REQUEST.items()) if 'PIN__exact' in data.keys(): data['PIN__exact']=format_pin(str(data['PIN__exact'])) d={} for k,v in data.items(): d[str(k)]=v qs=obj.all_objects.filter(**d) if qs.count()>0: return HttpResponse("× " + u"%s"%_(u"已存在")); else: return HttpResponse("√ " + u"%s"%_(u"可使用"));
def fingerprint_data(pin,Fpversion): if type(pin)==type(u'type'): try: emp = Employee.objects.get(PIN=format_pin(pin)) except ObjectDoesNotExist: return None else: emp = pin fingerprint = Template.objects.filter(UserID=emp,Fpversion=Fpversion) cc = u'' for fp in fingerprint: try: cc += u"DATA FP PIN=%s\tFID=%d\tTMP=%s\n" % (emp.pin(), fp.FingerID, fp.temp()) except: return None return cc
def line_to_log(device, lines, event=True): ''' 处理一批考勤记录数据 ''' from mysite.personnel.models.model_emp import format_pin m_result = [] for line in lines: if line: flds = line.split("\t") + ["", "", "", "", "", "", "", ""] #检查员工号码的合法性 pin = flds[0] #---第一个元素为人员编号 logtime = datetime.datetime.strptime( flds[1], "%Y-%m-%d %H:%M:%S") #---第二个元素为打卡时间 #---检查考勤记录时间的合法性 # if event: # if (now + datetime.timedelta(1, 0, 0)) < logtime: # print u"时间比当前时间还要多一天" # return None # if logtime<now-datetime.timedelta(days=settings.VALID_DAYS): # print u"时间比当前要早...天", settings.VALID_DAYS # return None #根据考勤机的时区矫正考勤记录的时区,使之同服务器的时区保持一致 # if device.tz_adj <> None: # count_minutes = None # tz_adj = int(device.tz_adj) # if abs(tz_adj)<=13: # count_minutes = tz_adj*3600 # else: # count_minutes = tz_adj*60 # logtime = logtime - datetime.timedelta(0, count_minutes) + server_time_delta() #UTC TIM attrecord = { "pin": format_pin(pin), "checktime": logtime, "checktype": normal_state(flds[2]), "verifycode": normal_verify(flds[3]), "WorkCode": flds[4], "Reserved": flds[5], "sn_name": device.sn } m_result.append(attrecord) rtn = save_attrecord(m_result, event) return rtn
def get_employee(pin, Device=None): ''' 根据给定员工PIN查找员工,若不存在就创建改PIN的员工 ''' s_pin = format_pin(pin) try: e=Employee.objects.get(PIN=s_pin) if e: e.IsNewEmp=False return e else: raise ObjectDoesNotExist except ObjectDoesNotExist: e = Employee(PIN=s_pin, EName=pin) e.save() e.IsNewEmp=True return e
def save_attrecord(att_dict_list, event=True): ''' 保存考勤原始记录到数据库 realtime: True: 设备实时上传过来的数据 False: 文件解析过来的数据 ''' from mysite.personnel.models.model_emp import format_pin if att_dict_list: insert_sql = """ if not exists(select id from checkinout where pin = '%(pin)s' and checktime= '%(checktime)s') insert into checkinout (pin, checktime, checktype, verifycode, WorkCode, Reserved,sn_name) values('%(pin)s', '%(checktime)s', '%(checktype)s','%(verifycode)s', '%(WorkCode)s', '%(Reserved)s', '%(sn_name)s'); """ batch_sql = [] for ad in att_dict_list: ad["pin"] = format_pin(pin) batch_sql.append(insert_sql % ad) success, res = p_mutiexec(batch_sql) if not success: # 出现异常,一条一条插入: if res and res[0] == -2: att_deal_logger( "Insert attrecord failed ,Database has been disconnected!") if event <> "files": # # 数据库连接失败,导致数据没有插入,由设备直接传过来的数据,写成文件,返回 True # data_list = [] # for d in att_dict_list: # data_list.append(u"%s\t%s\t%s\t%s"%(d["pin"],d["checktime"],d["checktype"],d["verifycode"])) # save_att_file(att_dict_list[0]["sn_name"],("\r\n").join(data_list)) time.sleep( 2 * 60) # 机器post 数据,如果服务器一段时间没有返回,则机器会默认为服务器没有收到,会再次post. return False else: for bs in batch_sql: num = p_execute(bs) if num is None: att_deal_logger("Error sql -->%s" % bs) if event <> "files": # 设备上传数据,数据异常导致保存失败 time.sleep(2 * 60) return True return True
def get_employee(pin, Device=None): ''' 根据给定员工PIN查找员工,若不存在就创建改PIN的员工 ''' s_pin = format_pin(pin) try: e = Employee.objects.get(PIN=s_pin) if e: e.IsNewEmp = False return e else: raise ObjectDoesNotExist except ObjectDoesNotExist: e = Employee(PIN=s_pin, EName=pin) e.save() e.IsNewEmp = True return e
def load_emp_face(key): u""" 根据人员 PIN 获取该人员面部信息 """ pin, ver = key.split('|') pin = format_pin(pin) sql = """ select faceid,facetemp from face_template where face_template.pin = '%s' and face_template.face_ver = '%s' """ % (pin, ver) temps = p_query(sql) res = {} if temps: for e in temps: res["face" + str(e[0])] = e[1] else: res = None return res
def load_emp_fg(key): u""" 根据人员 PIN 获取该人员指纹信息 """ pin, ver = key.split('|') pin = format_pin(pin) sql = """ select FingerID,Template from finger_template where finger_template.pin = '%s' and finger_template.Fpversion= '%s' """ % (pin, ver) temps = p_query(sql) res = {} if temps: for e in temps: res["fp" + str(e[0])] = e[1] else: res = None return res
def get_employee(pin, Device=None): ''' 根据给定员工PIN查找员工,若不存在就创建改PIN的员工 ''' s_pin = format_pin(pin) try: e=Employee.all_objects.get(PIN=s_pin) if e: e.IsNewEmp=False return e else: raise ObjectDoesNotExist except ObjectDoesNotExist: if not settings.DEVICE_CREATEUSER_FLAG: return None e = Employee(PIN=s_pin, EName=pin) e.save() e.IsNewEmp=True return e
def process_row(self, row_data, calculate_dict): from mysite.personnel.models import Employee from mysite.personnel.models.model_emp import format_pin from base.middleware import threadlocals op = threadlocals.get_current_user() key = u"%s" % _(u"人员编号") emp_pin = u"%s" % calculate_dict[key] emp_pin = format_pin(emp_pin) try: obj_emp = Employee.objects.get(PIN=emp_pin) row_data["user_id"] = obj_emp.pk #初始化人员 except: row_data["user_id"] = '0000' row_data["batch"] = datetime.datetime.now().strftime("%Y%m")[2:] row_data["date"] = datetime.datetime.now() row_data["is_pass"] = 1 row_data["pass_name"] = op.username row_data["user_pin"] = emp_pin return row_data
def save_addition_emp(pin): ''' 将人员新增到数据库 ''' from mysite.personnel.models import Employee pin = format_pin(pin) emp = Employee() emp.PIN = pin emp.EName = '' #str(pin) emp.DeptID_id = 1 emp.from_dev = True try: super(Employee, emp).save() eid = emp.id except IntegrityError: eid = get_uid_by_pin(pin) finally: # '''保存区域''' save_area(eid, pin) return eid
def action(self, **args): users=[] users = args['user'] print 'users:',users if self.request: depts=self.request.POST.getlist('deptIDs') if len(depts)>0: users=Employee.objects.filter(DeptID__in=depts) pin = None if len(args['PIN'])>0: try: pin = str(int(args['PIN'])) except: raise Exception(_(u'人员编号只能为数字')) if int(args['PIN']) == 0: raise Exception(_(u'人员编号不能为0')) if len(args['PIN']) > settings.PIN_WIDTH: raise Exception(_(u'%(f)s 人员编号长度不能超过%(ff)s位') % {"f":args['PIN'], "ff":settings.PIN_WIDTH}) pin = format_pin(args['PIN']) push_emp_cmd(users,pin)
def before_insert(self): from mysite.personnel.models import Employee from mysite.personnel.models.model_emp import format_pin from base.middleware import threadlocals from mysite.personnel.models.model_iccard import ICcard from mysite.personnel.models.model_issuecard import IssueCard, CARD_VALID, CARD_OVERDUE from mysite.pos.models.model_allowance import Allowance calculate_dict = {} count_head = len(self.head) u = datetime.datetime.now() for row in self.records: for index in range(count_head): for k, v in self.calculate_fields_index.items(): if v == index: calculate_dict[k] = row[index] key = u"%s" % _(u"人员编号") emp_pin = u"%s" % calculate_dict[key] emp_pin = format_pin(emp_pin) try: obj_emp = Employee.objects.get(PIN=emp_pin) user_id = obj_emp.pk #初始化人员 except: user_id = '0000' try: now_time = datetime.datetime.now() if ONLINE_ALLOWANCE: #在线补贴模式 batch = ((now_time.year - 2000) * 12 + now_time.month) * 31 + now_time.day else: batch = now_time.strftime("%Y%m")[2:] objcard = IssueCard.objects.get( UserID=user_id, cardstatus__in=[CARD_VALID, CARD_OVERDUE], sys_card_no__isnull=False) sys_card_no = objcard.sys_card_no allow_data = Allowance.objects.get(sys_card_no=sys_card_no, batch=batch) except: pass
def process_row(self, row_data, calculate_dict): u''' 特殊情况给开发人员提供的接口 row_data 这一行的数据 calculate_dict 文档附加的列,如人员编号, 记录表是没有人员编号的,人员编号是用来初始化员工字段UserID的 ''' from mysite.personnel.models import Employee #print "calculate_dict:",calculate_dict,"\n" key = u"%s" % _(u"人员编号") emp_pin = u"%s" % calculate_dict[key] emp_pin = format_pin(emp_pin) try: obj_emp = Employee.all_objects.get(PIN=emp_pin) except: #判断是使用默认还是创建新的人员 obj_emp = Employee() obj_emp.PIN = emp_pin obj_emp.DeptID_id = 1 obj_emp.save() row_data["userid"] = u"%s" % obj_emp.pk #初始化人员 return row_data
def cdata_get_pin(request, device): ''' 请求中 带人员PIN参数时的处理 返回人员基本信息和指纹模板信息 涉及 http参数:pin、save ''' resp = "" #---是否保存 设备请求参数"save" save = request.REQUEST.has_key('save') and ( request.REQUEST['save'] in ['1', 'Y', 'y', 'yes', 'YES']) or False try: #---根据人员PIN得到人员对象 pin = request.REQUEST['PIN'] emp = Employee.objects.get(PIN=format_pin(pin)) except ObjectDoesNotExist: resp += "NONE" else: #---人员信息数据 cc = u"DATA USER 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, get_normal_card( emp.Card), emp.TimeZones or "", save and emp.Privilege or 0) for fp in Template.objects.filter(UserID=emp): try: #---人员指纹信息 cc += u"DATA FP PIN=%s\tFID=%d\tTMP=%s\n" % ( emp.pin(), fp.FingerID, fp.temp()) except: pass try: resp += cc.encode("gb18030") except: resp += cc.decode("utf-8").encode("gb18030") if not save: #---如果没有请求参数"save" endTime = datetime.datetime.now() + datetime.timedelta(0, 5 * 60) append_dev_cmd(device, "DATA DEL_USER PIN=%s" % emp.pin(), None, endTime) #---保存设备删除用户请求记录 return resp
def get_redis_rtlog(request): logid = int(request.GET.get('logid', FIRSTVISIT_OR_DELBACKEND)) step = int(request.GET.get('step', 0))#步长:即要log的最大条数 rt_type = request.GET.get('type', '')#all alarm devid = request.REQUEST.get("devid", 0)#默认为0,表示监控所有设备的所有门的状态 #再获取实时监控记录 q_server = check_and_start_queqe_server() #print "--",logid+step # cfg = dict4ini.DictIni(os.getcwd()+"/appconfig.ini",values={"iaccess": {"down_newlog": 0}}) #默认0点定时下载新记录,定时删除缓存 # now_hour = datetime.datetime.now().hour # if now_hour == cfg.iaccess.down_newlog: # q_server.delete("MONITOR_RT") # q_server.delete("ALARM_RT") # logid = -1#重新取 rtid_all = 0#缓存里所有的记录条数 rtid_alarm = 0#缓存里所有的报警事件记录 log_count = 0#返回的有效记录条数 valid_devices = [] if rt_type == "all": rtid_all = q_server.lock_rlen("MONITOR_RT")#被锁住时以及文件缓存为空时都返回-1,即该值不可能为0 此时前端继续使用原来的logid取数据 if (rtid_all != LOCKED_OR_NOTHING) and (rtid_all < logid):#主要用于后台服务0时定时删除监控缓存时可能导致的不一致,故重新取,当数据量少时未必准确。 logid = FIRSTVISIT_OR_DELBACKEND#重新取 #获取门状态door_states valid_devices = obtain_valid_devices(request) #print '---valid_devices=',valid_devices door_states = door_state_monitor(valid_devices)#门状态不涉及辅助输入点,故不需调整 if logid == FIRSTVISIT_OR_DELBACKEND:#监控全部时获取报警记录的初始id值 rtid_alarm = q_server.llen("ALARM_RT") rtlog = q_server.lrange("MONITOR_RT", logid, logid + step) elif rt_type == "alarm": rtid_alarm = q_server.lock_rlen("ALARM_RT") if (rtid_alarm != LOCKED_OR_NOTHING) and (rtid_alarm < logid):#主要用于后台服务0时定时删除监控缓存时可能导致的不一致,故重新取,当数据量少时未必准确。--包含发现报警事件的按钮如果被删除,那么跳转后直接重新开始 logid = FIRSTVISIT_OR_DELBACKEND#重新取 door_states = { "data": []} rtlog = q_server.lrange("ALARM_RT", logid, logid + step) #rtlog数据格式如下“0-时间 + 1-PIN号 + 2-门id + 3-事件类型 + 4-出入状态 +5-验证方式 +6-卡号+7-设备号” #rtlog = ['2010-03-07 09:53:51,370,4,6,0,221,36656656'] #print 'door_states=',door_states #print "----------------------rtlog=", rtlog q_server.connection.disconnect() cdatas = [] a_logids = [] #如下代码测试时请注释掉 if logid == FIRSTVISIT_OR_DELBACKEND: cc={ 'log_id': logid, 'all_id': (rtid_all != LOCKED_OR_NOTHING) and rtid_all or 0,#redis中所有记录条数 'alarm_id': rtid_alarm, 'log_count': log_count,#返回的记录条数 'data': cdatas, 'door_states': door_states["data"], } rtdata = simplejson.dumps(cc) return HttpResponse(smart_str(rtdata)) if not valid_devices:#如果之前没有进入“all”则需要重新获取有效设备(主要是避免重新获取,每次请求只获取一次即可) valid_devices = obtain_valid_devices(request)#通过设备找到对应的门以及辅助输入,作为事件点 for alog in rtlog: log = alog.strip() #print "log=", log #验证数据合法性,保证了除了时间之外的数据都是数字字符,从而可以使用int()而不会出错 p1 = re.compile(r'(((^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(10|12|0?[13578])([-\/\._])(3[01]|[12][0-9]|0?[1-9]))|(^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(11|0?[469])([-\/\._])(30|[12][0-9]|0?[1-9]))|(^((1[8-9]\d{2})|([2-9]\d{3}))([-\/\._])(0?2)([-\/\._])(2[0-8]|1[0-9]|0?[1-9]))|(^([2468][048]00)([-\/\._])(0?2)([-\/\._])(29))|(^([3579][26]00)([-\/\._])(0?2)([-\/\._])(29))|(^([1][89][0][48])([-\/\._])(0?2)([-\/\._])(29))|(^([2-9][0-9][0][48])([-\/\._])(0?2)([-\/\._])(29))|(^([1][89][2468][048])([-\/\._])(0?2)([-\/\._])(29))|(^([2-9][0-9][2468][048])([-\/\._])(0?2)([-\/\._])(29))|(^([1][89][13579][26])([-\/\._])(0?2)([-\/\._])(29))|(^([2-9][0-9][13579][26])([-\/\._])(0?2)([-\/\._])(29)))((\s+(0?[1-9]|1[012])(:[0-5]\d){0,2}(\s[AP]M))?$|(\s+([01]\d|2[0-3])(:[0-5]\d){0,2})?$))') p2 = re.compile(r'^,(((\d+),){6}\d+)$')#r'^,(((\d+),){4}\d+)?$' 5-6 if p1.match(log[0:19]) and p2.match(log[19:]): log_count += 1 str = log.split(",",8)#0-7 共8部分 #print "accmonitorlog=", str #设备名称 dev_id = int(str[7]) dev = Device.objects.filter(pk=dev_id) alias = dev and unicode(dev[0].alias) or "" if dev and dev[0] not in valid_devices:#设备级别的过滤--辅助输入(含联动中触发条件为辅助输入点的) break #事件类型 event = int(str[3]) #验证方式(或源事件类型),但是当事件为联动事件时为联动事件的原事件 veri_event = int(str[5]) #卡号-联动时复用为联动id号(pk) card_no = int(str[6]) and str[6] or '' door_id = 0 link_video = [] #print '---vari_event=',veri_event,' event=',event,' door_id',door_id, if event == 220 or event == 221:#辅助输入点的事件 #事件点 in_address_id = int(str[2])#辅助输入点,如1,2,3,4 9,10,11,12 event_point = unicode(dict(IN_ADDRESS_CHOICES)[in_address_id]) #验证方式 try: verified = unicode(dict(VERIFIED_CHOICES)[veri_event])#the true verified method("others" included) except: verified = unicode(_(u"数据异常")) else:#与门相关 door_id_limit = obtain_valid_doors(request, valid_devices)#可控的ip地址,不包含辅助输入点 if event == 6:#事件类型为联动事件 #print '----------------event=',event #verified = ''#联动事件验证方式为空-固件字段复用--触发的原事件 verified = unicode(dict(VERIFIED_CHOICES)[200])#其他 if veri_event == 220 or veri_event == 221: number = int(str[2]) #如C4 9,10,11,12 event_point = unicode(dict(IN_ADDRESS_CHOICES)[number]) #linkage = AccLinkageIO.objects.filter(Q(device__id=dev_id), Q(trigger_opt=veri_event), Q(in_address_hide=number)|Q(in_address_hide=0))#输入点inout或0只能居其一 else: door_id = int(str[2])#门id(不同于门编号) if door_id not in door_id_limit:#门级别的过滤 break #跳出for循环,该记录无效 #事件点 doors = AccDoor.objects.filter(id=door_id) event_point = doors and unicode(doors[0]) or "" #视频联动处理 try: link_id = int(card_no) or 0#联动时卡号复用为联动id号 except: link_id = 1 card_no = ''#联动时不需要显示卡号 #print "link_id=", link_id from mysite.iaccess.models import AccLinkageIO try: linkage = AccLinkageIO.objects.filter(id = link_id) if linkage: pwd = linkage[0].video_linkageio.comm_pwd link_video.append(linkage[0].video_linkageio.ipaddress) link_video.append(linkage[0].video_linkageio.ip_port) link_video.append(linkage[0].video_linkageio.video_login) link_video.append(pwd and decrypt(pwd) or "") link_video.append(linkage[0].lchannel_num) except: print_exc() else:#其他事件--门相关或设备相关 door_id = int(str[2])#门id--如果为0,指的是事件点为设备(如取消报警事件) if door_id:#不为0 if door_id not in door_id_limit:#门级别的过滤 break #跳出for循环,该记录无效 #事件点 doors = AccDoor.objects.filter(id=door_id) event_point = doors and unicode(doors[0]) or "" else: event_point = ""#如取消报警事件 try: verified = unicode(dict(VERIFIED_CHOICES)[veri_event])#the true verified method("others" included) except: verified = unicode(_(u"数据异常")) try: event_content = unicode(dict(EVENT_CHOICES)[event])#description of the triggered event except: event_content = unicode(_(u"数据异常")) #print 'str[1]=',str[1] pin_str = int(str[1]) and unicode(format_pin(str[1])) or '' #print '---pin_str=',pin_str emps = pin_str and Employee.objects.filter(PIN = pin_str) or '' #print 'emps=',emps if emps: empname = emps[0].EName and u"%s(%s)"%(str[1], emps[0].EName) or u"%s"%(str[1]) photo = emps[0].photo and '/file/' + unicode(emps[0].photo) or '' else: empname = '' photo = '' #print '--str[6]=',str[6] #state = int(str[4])!=2 and unicode(dict(STATE_CHOICES)[int(str[4])]) or ''#2直接显示空 #连动视频 #print "link_video=", link_video #print '---photo=',photo cdata={ 'time': str[0], 'card': card_no, #'door': doorname,#输入点,包含门名称或者辅助输入点 'device': alias,#设备名称 'event_point': event_point,#输入点,包含门名称或者辅助输入点 'door_id': door_id,#doorid 'event_type': int(str[3]), 'content': event_content, 'state': unicode(dict(STATE_CHOICES)[int(str[4])]),#0出,1入 'verified': verified, 'emp': empname,#用户名(包含用户编号) 'photo': photo,#有人员照片的要显示,如/file/photo/000000121.jpg 空代表无照片(或无此人) 'link_video': link_video, } cdatas.append(cdata) else: print "DATA ERROR" cc={ 'log_id': logid, 'all_id': rtid_all,#无效 'alarm_id': rtid_alarm, 'log_count': log_count,#返回的有效的记录条数,用于改变logid 'data':cdatas, 'door_states':door_states["data"],#门状态数据 } #print "**########**cc=",cc rtdata = simplejson.dumps(cc) return HttpResponse(smart_str(rtdata))
def process_user_info(qret): if qret['result'] == 0: return {"ret": qret['result'], "retdata": ""} elif qret['result'] > 0: try: #处理从设备中获取的用户信息 ret_data = qret['data'].split('\r\n') user_info_list = ret_data[1:-1] #print '+++++++++user_info_list =',qret['data'] if user_info_list != []: i = 0 if ret_data[0].split(",")[0] == "UID": #inbio 比C3多一个字段 i = 1 # print 'come into user_info' from mysite.personnel.models.model_morecardempgroup import AccMoreCardEmpGroup from mysite.personnel.models.model_issuecard import IssueCard, CARD_VALID, CARD_OVERDUE pin_list = [] #人员编号列表 pin_emp_dict = {} #字典,存储人员 emps = Employee.all_objects.all() for emp in emps: pin_list.append(emp.PIN) pin_emp_dict[emp.PIN] = emp #将设备中的用户存放到一个默认部门 from mysite.personnel.models.model_dept import Department dept = Department.objects.get(id=1) #发卡表 issue_card_dict = {} issue_card = IssueCard.objects.filter( cardstatus__in=[CARD_OVERDUE, CARD_VALID]) for issue in issue_card: issue_card_dict[issue.UserID] = issue for user_info in user_info_list: user_info = user_info.split(",") card = int(user_info[0 + i]) pin = format_pin(user_info[1 + i]) password = user_info[2 + i] group = int(user_info[3 + i]) #人员组 start = user_info[4 + i] #启用门禁日期 end = user_info[5 + i] #结束门禁日期 start_time = start != '0' and str_to_date(start) or None end_time = end != '0' and str_to_date(end) or None card = card or "" more_card_group = AccMoreCardEmpGroup.objects.filter( id=group) #查询人员组 if more_card_group: #人员组存在 more_card_group = more_card_group[0] else: more_card_group = None # if pin in pin_list:#如果用户存在,更新数据 # emp = pin_emp_dict[pin] ## print 'pin in pin_list' # # emp.acc_startdate = start_time # emp.acc_enddate = end_time # emp.morecard_group = more_card_group # emp.Password = password # emp.save(force_update=True) if pin not in pin_list: #不存在, 插入数据库 employee = Employee(PIN=pin, DeptID=dept, Password=password, acc_startdate=start_time, acc_enddate=end_time, morecard_group=more_card_group) employee.save(force_insert=True) if issue_card_dict.has_key(employee): iss_card = issue_card_dict[employee] iss_card.cardno = card iss_card.save() else: iss_card = IssueCard() iss_card.UserID = employee iss_card.cardno = card iss_card.cardstatus = CARD_VALID iss_card.save() except: print_exc() return {"ret": qret['result'], "retdata": ""} else: return {"ret": -1, "retdata": ""}
def get_emp(pin): try: emp = Employee.objects.get(PIN=format_pin(pin)) return emp except ObjectDoesNotExist: return None
def verification(request,device,Auty): ''' 后台验证(后台比对)的几个方式 ''' rawData = request.raw_post_data xx=rawData.split("\t") data_dict={} for x in xx: d=x.split("=",1) data_dict[d[0]]=d[1] devpin=data_dict["PIN"] tmp = data_dict["TMP"] size = data_dict["Size"] if int(size) !=len(tmp): return 'AUTH=Failed\n' re_succ="AUTH=Success\tPIN=%s\tName=%s\tPri=%s\tGrp=%s\tTZ=%s" if Auty == 'CARD':####################卡比对 emp = Employee.objects.filter(Card=tmp) if len(emp)>0: emp = emp[0] else: emp = None if devpin=='0': if emp: re_succ = re_succ%(device_pin(emp.PIN),emp.EName,str(emp.Privilege),str(emp.AccGroup),str(emp.TimeZones)) return get_photo(emp.photo,re_succ) else: if emp.PIN==format_pin(devpin): re_succ = re_succ%(device_pin(emp.PIN),emp.EName,str(emp.Privilege),str(emp.AccGroup),str(emp.TimeZones)) return get_photo(emp.photo,re_succ) elif Auty == 'FP':####################指纹比对 if devpin=='0': emp = compare_cache_bio_emp(tmp) if emp: re_succ = re_succ%(device_pin(emp.PIN),emp.EName,str(emp.Privilege),str(emp.AccGroup),str(emp.TimeZones)) return get_photo(emp.photo,re_succ) # emps = Employee.objects.all() # mathpro = windll.LoadLibrary("match.dll") # send_tmp = create_string_buffer(tmp.decode()) # for emp in emps: # tmps =emp.template_set.all() # if tmps: # for t in tmps: # try: # user_tep = create_string_buffer(t.Template) # math_result = mathpro.process10(user_tep, send_tmp) # if math_result == FP_IDENTIFY_SUCCESS: # re_succ = re_succ%(device_pin(emp.PIN),emp.EName,str(emp.Privilege),str(emp.AccGroup),str(emp.TimeZones)) # return get_photo(emp.photo,re_succ) # except: # print_exc() else: emps = Employee.objects.filter(PIN=format_pin(devpin)) if emps and len(emps)>0: emp = emps[0] else: return 'AUTH=Failed\t' tmps =Template.objects.filter(UserID=emp,Fpversion=device.Fpversion) mathpro = windll.LoadLibrary("match.dll") send_tmp = create_string_buffer(tmp.decode()) for t in tmps: source_tmp = create_string_buffer(t.Template) if device.Fpversion=='10': math_result = mathpro.process10(source_tmp, send_tmp) else: math_result = mathpro.process(source_tmp, send_tmp) if math_result == FP_IDENTIFY_SUCCESS: re_succ = re_succ%(device_pin(emp.PIN),emp.EName,str(emp.Privilege),str(emp.AccGroup),str(emp.TimeZones)) return get_photo(emp.photo,re_succ) elif Auty == 'Face':####################面部模板比对 pass else: pass return 'AUTH=Failed\t'