def get_upload_token(request): response = Response.ResponseObj() user_id = request.GET.get('user_id') # print('request.POST -->', request.POST) if request.method == "GET": redis_obj = get_redis_obj() upload_token = redis_obj.get('xhs_qiniu_upload_token') if not upload_token: qiniu_data_path = os.path.join(os.getcwd(), "publicFunc", "qiniu", "qiniu_data.json") with open(qiniu_data_path, "r", encoding="utf8") as f: data = json.loads(f.read()) access_key = data.get('access_key') secret_key = data.get('secret_key') obj = Auth(access_key, secret_key) upload_token = obj.upload_token("xcx_wgw_zhangcong") redis_obj.set("xhs_qiniu_upload_token", upload_token, ex=60 * 50) # 使用redis缓存50分钟 response.code = 200 response.msg = "获取成功" response.data = { 'upload_token': upload_token } return JsonResponse(response.__dict__)
def upload_qiniu(img_path, img_size): redis_obj = get_redis_obj() url = 'https://up-z1.qiniup.com/' upload_token = redis_obj.get('qiniu_upload_token') if not upload_token: qiniu_data_path = os.path.join(os.getcwd(), "publicFunc", "qiniu", "qiniu_data.json") with open(qiniu_data_path, "r", encoding="utf8") as f: data = json.loads(f.read()) access_key = data.get('access_key') secret_key = data.get('secret_key') obj = Auth(access_key, secret_key) upload_token = obj.upload_token("xcx_wgw_zhangcong") headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13' } with open(img_path, 'rb') as f: imgdata = f.read() files = { 'file': imgdata } data = { 'token': upload_token, } ret = requests.post(url, data=data, files=files, headers=headers) key = "http://qiniu.bjhzkq.com/{key}?imageView2/0/h/{img_size}".format( key=ret.json()["key"], img_size=img_size ) if os.path.exists(img_path): os.remove(img_path) # 删除本地图片 return key
def get_qiniu_token(): redis_obj = get_redis_obj() upload_token = redis_obj.get('qiniu_upload_token') if not upload_token: qiniu_data_path = os.path.join(os.getcwd(), "publicFunc", "qiniu", "qiniu_data.json") with open(qiniu_data_path, "r", encoding="utf8") as f: data = json.loads(f.read()) access_key = data.get('access_key') secret_key = data.get('secret_key') obj = Auth(access_key, secret_key) upload_token = obj.upload_token("xcx_wgw_zhangcong") return upload_token
def xhs_phone_log_oper(request, oper_type, o_id): start_time = time.time() response = Response.ResponseObj() user_id = request.GET.get('user_id') # print('request.POST -->', request.POST) if request.method == "POST": # if oper_type == "add": form_data = { 'log_msg': request.POST.get('log_msg'), 'macaddr': request.POST.get('macaddr'), 'ip_addr': request.POST.get('ip_addr'), 'iccid': request.POST.get('iccid'), 'imsi': request.POST.get('imsi'), 'phone_type': request.POST.get('phone_type', 1), } xhs_version = request.POST.get('xhs_version') # 创建 form验证 实例(参数默认转成字典) forms_obj = AddForm(form_data) if forms_obj.is_valid(): stop_time = time.time() - start_time print(stop_time, "cleaned_data --> ", forms_obj.cleaned_data) log_msg = forms_obj.cleaned_data.get('log_msg') macaddr = forms_obj.cleaned_data.get('macaddr') ip_addr = forms_obj.cleaned_data.get('ip_addr') iccid = forms_obj.cleaned_data.get('iccid') imsi = forms_obj.cleaned_data.get('imsi') phone_type = int(forms_obj.cleaned_data.get('phone_type')) # 查覆盖的机器 if phone_type == 1: objs = models.XiaohongshuPhone.objects.filter( phone_type=phone_type, macaddr=macaddr) if objs: obj = objs[0] obj.ip_addr = ip_addr obj.save() else: obj = models.XiaohongshuPhone.objects.create( macaddr=macaddr, ip_addr=ip_addr) else: data = { "phone_type": phone_type, "imsi": imsi, "iccid": iccid } ip = request.META['HTTP_X_FORWARDED_FOR'] objs = models.XiaohongshuPhone.objects.filter(**data) request_type = request.GET.get('request_type', None) if request_type and objs: response.code = 301 response.msg = '设备已存在, 请联系负责人处理' response.data = { 'imsi': imsi, 'iccid': iccid, } return JsonResponse(response.__dict__) if objs: obj = objs[0] obj.ip_addr = ip_addr obj.request_ip_addr = ip obj.save() else: obj = models.XiaohongshuPhone.objects.create(**data) if log_msg == '已查询完评论信息': # 记录 创建评论日志 最后一次更新时间 obj.comment_last_updated = datetime.datetime.today() obj.save() redis_obj = get_redis_obj() redis_key = str(iccid + imsi) if not redis_obj.get(redis_key): redis_obj.set(redis_key, 1) redis_obj.expire(redis_key, 30) # 更新最后一次 签到时间 models.XiaohongshuPhone.objects.filter( iccid=iccid, imsi=imsi).update( last_sign_in_time=datetime.datetime.today()) # models.XiaohongshuPhoneLog.objects.create( # log_msg=log_msg, # parent=obj # ) # 将日志存入redis中 phone_log_id_key = "phone_log_{phone_id}".format( phone_id=obj.id) phone_log_list_key = "phone_log_list" if redis_obj.llen(phone_log_id_key) > 500: redis_obj.rpop(phone_log_id_key) redis_obj.lpush( phone_log_id_key, json.dumps({ "log_msg": log_msg, "create_date": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') })) stop_time = time.time() - start_time print("redis_stop -->", stop_time, "cleaned_data --> ", forms_obj.cleaned_data) phone_id = obj.id phone_name = obj.name phone_objs = models.XiaohongshuUserProfile.objects.filter( phone_id_id=phone_id) if xhs_version and phone_id: phone_objs.update(xhs_version=xhs_version, ) # 更新版本号 if log_msg.startswith('没有找到回复私信用户'): # 报错 if phone_type == 1: text_type = '查覆盖' else: text_type = '任务发布' text = '类型:{}, 设备名称:{}, 日志:{}'.format( text_type, phone_name, log_msg) content = """{} \n小红书添加日志中出现-->没有找到回复私信用户,请及时处理: \n{}""".format( datetime.datetime.today(), text) send_error_msg(content, 6) # 发送消息 now_date_time = datetime.datetime.today() if log_msg.startswith( '自动更新日志'): # 判断时间 与当前时间相差五分钟 and 版本号是否为最新 send_msg_flag = False # 是否发送错误提示 content = '' json_data = json.loads( log_msg.split((log_msg.split(':')[0]) + ':')[1]) if json_data.get('runtime'): deletionTime = (now_date_time - datetime.timedelta(minutes=10)) if json_data.get('runtime'): package_type = json_data.get('package_type') current_version = json_data.get('current_version') if 'unknown' not in json_data.get('runtime'): runtime = datetime.datetime.strptime( json_data.get('runtime'), '%Y-%m-%d %H:%M:%S') if runtime > deletionTime: phone_objs.update( package_version=current_version) # package_objs = models.InstallationPackage.objects.filter( # package_type=package_type # ).order_by('-id') # if package_objs: # package_obj = package_objs[0] # if int(package_obj.id) != int(current_version): # send_msg_flag = True # content = '{}\n {} 移动设备 发布程序不是最新版,请及时更新'.format(now_date_time, phone_name) # else: # send_msg_flag = True # content = '{}\n {} 移动设备 发布程序没有版本,请及时查看'.format(now_date_time, phone_name) else: objs.update(status=3) else: phone_objs.update( package_version=current_version) # send_msg_flag = True # content = '{}\n {} 移动设备 自动更新程序异常,请及时处理'.format(now_date_time, phone_name) # else: # send_msg_flag = True # content = '{}\n {} 移动设备 自动更新程序异常runtime字符为空,请及时处理, \nlog_msg参数:{}'.format(now_date_time, phone_name, log_msg) if send_msg_flag: send_error_msg(content, 6) if log_msg.startswith('请求接口异常'): create_xhs_admin_response(request, log_msg, 3) # log_msg_one = log_msg.replace('请求接口异常: ', '') # log_msg_one = log_msg_one.split('返回数据->') # request_url = log_msg_one[0].split('api_url->')[1] # response_data = '' # if len(log_msg_one) > 2: # response_data = log_msg_one[1] # obj = models.PhoneRequestsBackgroundRecords.objects.create( # request_url=request_url, # response_data=response_data # ) # content = '{}\n 设备请求接口 非200 告警, \n 表名:PhoneRequestsBackgroundRecords, \n 报错日志ID:{}'.format(now_date_time,obj.id) # send_error_msg(content, 1) # last_there_days = (now_date_time - datetime.timedelta(days=1)) # models.PhoneRequestsBackgroundRecords.objects.filter( # create_datetime__lte=last_there_days # ).delete() response.code = 200 response.msg = "日志记录成功" else: print("验证不通过") response.code = 301 response.msg = json.loads(forms_obj.errors.as_json()) stop_time = time.time() - start_time print("stop_time -->", stop_time, "cleaned_data --> ", forms_obj.cleaned_data) else: response.code = 402 response.msg = "请求异常" return JsonResponse(response.__dict__)
def DMS_screenshots(request, oper_type): response = Response.ResponseObj() redis_obj = get_redis_obj() # 截图 if oper_type == "save_screenshots": start_time = time.time() form_data = { 'img_base64_data': request.POST.get('img_base64_data'), 'iccid': request.POST.get('iccid'), 'imsi': request.POST.get('imsi') } form_obj = Screenshots(form_data) if form_obj.is_valid(): forms_data = form_obj.cleaned_data imgdata = forms_data.get('img_base64_data') img_base64_data = request.POST.get('img_base64_data') md5_obj = hashlib.md5() md5_obj.update(img_base64_data.encode('utf8')) img_base64_data = md5_obj.hexdigest() judge_key = "dms_screenshots_" + forms_data.get( 'iccid') + forms_data.get('imsi') judge_key_objs = redis_obj.get(judge_key) img_flag = False key = '' if judge_key_objs: for i in json.loads(judge_key_objs): if img_base64_data == i['img_base64_data']: img_flag = True key = i['key'] break # print("1111 -->", time.time() - start_time) # print("key -->", key) if not img_flag: print("没有保存过,提交七牛云获取url") upload_token = get_qiniu_token() headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13' } url = 'https://up-z1.qiniup.com/' files = {'file': imgdata} data = { 'token': upload_token, } ret = requests.post(url, data=data, files=files, headers=headers) print("七牛云返回数据 -->", ret.json()) print("222 -->", time.time() - start_time) key = "http://qiniu.bjhzkq.com/{key}?imageView2/0/h/400".format( key=ret.json()["key"]) if judge_key_objs: data_list = json.loads(judge_key_objs) data_list.append({ 'key': key, 'img_base64_data': img_base64_data }) redis_obj.delete(judge_key) redis_obj.set(judge_key, json.dumps(data_list)) else: redis_obj.set( judge_key, json.dumps([{ 'img_base64_data': img_base64_data, 'key': key }])) # ===================保存最后 十张截图===================== num = 0 while True: num += 1 xhs_screenshots = redis_obj.llen('xhs_screenshots') # 保存截图 if int(xhs_screenshots) < 10: # 只保存十个 追加 redis_obj.rpush('xhs_screenshots', key) break else: redis_obj.lpop('xhs_screenshots') if num >= 10: break print("333 -->", time.time() - start_time) response.code = 200 response.msg = "提交成功" response.data = {'key': key} else: response.code = 301 response.msg = json.loads(form_obj.errors.as_json()) # print("444 -->", time.time() - start_time) # create_xhs_admin_response(request, response, 3) # 创建请求日志(手机端) # print("555 -->", time.time() - start_time) # print("response.data -->", response.data, response.code, response.code) # 上传截图 elif oper_type == 'upload_img': img_base64_data = request.POST.get('img_base64_data') imgdata = base64.b64decode(img_base64_data) upload_token = get_qiniu_token() headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13' } url = 'https://up-z1.qiniup.com/' files = {'file': imgdata} data = { 'token': upload_token, } ret = requests.post(url, data=data, files=files, headers=headers) key = "http://qiniu.bjhzkq.com/{key}?imageView2/0/h/400".format( key=ret.json()["key"]) response.code = 200 response.msg = '上传成功' response.data = {'key': key} else: # 查询截图 if oper_type == 'get_screenshots': ret_data = [] for i in redis_obj.lrange('xhs_screenshots', 0, 10): ret_data.append(i) response.code = 200 response.msg = '查询成功' response.data = list(reversed(ret_data)) else: response.code = 402 response.msg = '请求异常' return JsonResponse(response.__dict__)
def xiaohongshu_direct_essages_oper(request, oper_type, o_id): response = Response.ResponseObj() user_id = request.GET.get('user_id') # print('request.POST -->', request.POST) if request.method == "POST": start_time = time.time() # 保存私信截图(手机) if oper_type == "save_screenshots": timestamp = request.POST.get('timestamp') form_data = { 'name': request.POST.get('name'), 'iccid': request.POST.get('iccid'), 'imsi': request.POST.get('imsi'), 'img_base64_data': request.POST.get('img_base64_data') } # 创建 form验证 实例(参数默认转成字典) forms_obj = SaveScreenshotsForm(form_data) if forms_obj.is_valid(): print("验证通过") name = forms_obj.cleaned_data.get('name') iccid = forms_obj.cleaned_data.get('iccid') imsi = forms_obj.cleaned_data.get('imsi') img_base64_data = forms_obj.cleaned_data.get('img_base64_data') img_base64_data = img_base64_data.replace(' ', '+') objs = models.XiaohongshuUserProfile.objects.filter( phone_id__iccid=iccid, phone_id__imsi=imsi) if objs: obj = objs[0] imgdata = base64.b64decode(img_base64_data) flag = True if timestamp: message_objs = models.XiaohongshuDirectMessages.objects.filter( user_id=obj, time_stamp=timestamp) if message_objs: flag = False if flag: # with open('t.png', 'wb') as f: # f.write(imgdata) # img_url = '' redis_obj = get_redis_obj() upload_token = redis_obj.get('qiniu_upload_token') if not upload_token: qiniu_data_path = os.path.join( os.getcwd(), "publicFunc", "qiniu", "qiniu_data.json") with open(qiniu_data_path, "r", encoding="utf8") as f: data = json.loads(f.read()) access_key = data.get('access_key') secret_key = data.get('secret_key') qny_obj = Auth(access_key, secret_key) upload_token = qny_obj.upload_token( "xcx_wgw_zhangcong") headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13' } url = 'https://up-z1.qiniup.com/' files = {'file': imgdata} data = { 'token': upload_token, 'key': "xiaohongshu_fabu_" + str(int(time.time() * 1000)) } ret = requests.post(url, data=data, files=files, headers=headers) # print("ret.text -->", ret.json) key = ret.json()["key"] img_url = "http://qiniu.bjhzkq.com/{key}?imageView2/0/h/400".format( key=key) direct_message_objs = models.XiaohongshuDirectMessages.objects.filter( user_id=obj, time_stamp=timestamp) if not direct_message_objs: direct_message_obj = models.XiaohongshuDirectMessages.objects.create( user_id=obj, img_url=img_url, name=name, time_stamp=timestamp, ) else: direct_message_obj = direct_message_objs[0] from_blogger = 0 if request.POST.get('from_blogger'): from_blogger = 1 # 来自于博主 # 把私信截图发送给小红书后台 for i in range(3): try: data = { "id": direct_message_obj.id, "name": name, "img_url": img_url, "xiaohongshu_id": obj.xiaohongshu_id, "from_blogger": from_blogger, "platform": direct_message_obj.user_id.platform, "create_datetime": direct_message_obj.create_datetime. strftime('%Y-%m-%d %H:%M:%S'), } api_url = 'https://www.ppxhs.com/api/v1/sync/sync-chat' ret = requests.post(api_url, data=data) print("ret.json", ret.json()) create_xhs_admin_response(request, ret.json(), 1, url=api_url, req_type=2) break except: pass response.code = 200 response.msg = "保存成功" else: print("验证不通过", forms_obj.errors.as_json()) response.code = 301 response.msg = json.loads(forms_obj.errors.as_json()) # 回复私信(小红书后台) elif oper_type == "reply": form_data = { 'xiaohongshu_id': request.POST.get('xiaohongshu_id'), 'name': request.POST.get('name'), 'msg': request.POST.get('msg') } # 创建 form验证 实例(参数默认转成字典) forms_obj = ReplyForm(form_data) if forms_obj.is_valid(): print("验证通过") xiaohongshu_id = forms_obj.cleaned_data.get('xiaohongshu_id') name = forms_obj.cleaned_data.get('name') msg = forms_obj.cleaned_data.get('msg') objs = models.XiaohongshuUserProfile.objects.filter( xiaohongshu_id=xiaohongshu_id) if objs: obj = objs[0] if models.XiaohongshuDirectMessages.objects.filter( user_id=obj, name=name): msg_reply_obj = models.XiaohongshuDirectMessagesReply.objects.create( user_id=obj, name=name, msg=msg) response.code = 200 response.msg = "添加成功" response.data = {"id": msg_reply_obj.id} else: response.code = 0 response.msg = "私信用户不存在" else: response.code = 0 response.msg = "博主账号不存在" else: print("验证不通过") response.code = 301 response.msg = json.loads(forms_obj.errors.as_json()) # 手机操作回复完成后,修改状态和更新时间 elif oper_type == "reply_save": task_id = request.POST.get('task_id') objs = models.XiaohongshuDirectMessagesReply.objects.filter( id=task_id) objs.update(status=2, update_datetime=datetime.datetime.now()) post_data = { "id": objs[0].id, "platform": objs[0].user_id.platform } api_url = 'https://www.ppxhs.com/api/v1/sync/sync-chat-log' ret = requests.post(api_url, data=post_data) print(ret.text) create_xhs_admin_response(request, ret.json(), 1, url=api_url, req_type=2) # 记录请求日志 response.code = 200 response.msg = "操作完成" # 回复评论私信 / 回复私信 手动操作完成 elif oper_type == 'manual_operation_completed': direct_messages_types = request.POST.get( 'direct_messages_types') # 私信类型 回复评论私信1 / 私信2 direct_messages_id = request.POST.get('direct_messages_id') # 私信ID direct_messages_screenshots = request.POST.get( 'direct_messages_screenshots') # 私信截图 now = datetime.datetime.today() code = 301 msg = '未找到该评论' # 私信 if direct_messages_types in [1, '1']: objs = models.XiaohongshuDirectMessagesReply.objects.filter( id=direct_messages_id) if objs: objs.update(status=2, update_datetime=now) post_data = { "id": objs[0].id, "platform": objs[0].user_id.platform } api_url = 'https://www.ppxhs.com/api/v1/sync/sync-chat-log' ret = requests.post(api_url, data=post_data) create_xhs_admin_response(request, ret.json(), 1, url=api_url, req_type=2) # 记录请求日志 uid = objs[0].user_id name = objs[0].name code = 200 msg = '完成' # 回复评论私信 else: objs = models.commentResponseForm.objects.filter( comment_type=2, id=direct_messages_id) if objs: objs.update(comment_completion_time=now) form_data = { 'id': direct_messages_id, # 回复的消息ID 'comment_completion_time': now, # 完成时间 'transfer_type': 2, 'platform': objs[0].comment.xhs_user.platform } asynchronous_transfer_data.delay(form_data) uid = objs[0].comment.xhs_user_id name = objs[0].comment.nick_name code = 200 msg = '完成' from_blogger = 0 if request.POST.get('from_blogger'): from_blogger = 1 # 来自于博主 if code == 200: direct_message_obj = models.XiaohongshuDirectMessages.objects.create( user_id=uid, img_url=direct_messages_screenshots, name=name, # time_stamp=timestamp, ) data = { "id": direct_message_obj.id, "name": name, "img_url": direct_messages_screenshots, "xiaohongshu_id": uid, "from_blogger": from_blogger, "platform": direct_message_obj.user_id.platform, "create_datetime": direct_message_obj.create_datetime.strftime( '%Y-%m-%d %H:%M:%S'), } api_url = 'https://www.ppxhs.com/api/v1/sync/sync-chat' ret = requests.post(api_url, data=data) print("ret.json", ret.json()) create_xhs_admin_response(request, ret.json(), 1, url=api_url, req_type=2) response.code = code response.msg = msg else: response.code = 402 response.msg = "请求异常" else: # 获取回复私信任务 if oper_type == "get_reply": form_data = { 'imsi': request.GET.get('imsi'), 'iccid': request.GET.get('iccid'), 'platform': request.GET.get('platform', 1), } forms_obj = GetReplyForm(form_data) if forms_obj.is_valid(): iccid = forms_obj.cleaned_data['iccid'] imsi = forms_obj.cleaned_data['imsi'] platform = forms_obj.cleaned_data['platform'] objs = models.XiaohongshuDirectMessagesReply.objects.filter( user_id__phone_id__iccid=iccid, user_id__phone_id__imsi=imsi, status=1, user_id__platform=platform) if objs: obj = objs[0] response.data = { "id": obj.id, "name": obj.name, "msg": obj.msg, "platform": obj.user_id.platform } else: response.msg = "当前无任务" response.code = 200 else: print("forms_obj.errors -->", forms_obj.errors) response.code = 402 response.msg = "请求异常" response.data = json.loads(forms_obj.errors.as_json()) # 获取休息时间 elif oper_type == "get_screenshot_time": form_data = { 'imsi': request.GET.get('imsi'), 'iccid': request.GET.get('iccid'), } forms_obj = GetReplyForm(form_data) if forms_obj.is_valid(): iccid = forms_obj.cleaned_data['iccid'] imsi = forms_obj.cleaned_data['imsi'] objs = models.XiaohongshuUserProfile.objects.filter( phone_id__imsi=imsi, phone_id__iccid=iccid) now_date = datetime.datetime.today() now_hours = int(now_date.strftime('%H')) if objs: obj = objs[0] if now_hours > 8 and now_hours < 22: screenshot_time = obj.screenshot_time else: screenshot_time = obj.late_screenshot_time response.code = 200 response.data = { "screenshot_time": screenshot_time, } else: response.code = 0 response.msg = "请求异常" else: print("forms_obj.errors -->", forms_obj.errors) response.code = 402 response.msg = "请求异常" response.data = json.loads(forms_obj.errors.as_json()) # 查询回复私信(胡蓉后台) elif oper_type == 'get_reply_info': forms_obj = SelectForm(request.GET) if forms_obj.is_valid(): user_id = request.GET.get('user_id') current_page = forms_obj.cleaned_data['current_page'] length = forms_obj.cleaned_data['length'] order = request.GET.get('order', '-create_datetime') field_dict = { 'user_id_id': '', 'user_id__name': '__contains', 'name': '__contains', 'msg': '__contains', 'status': '__contains', } q = conditionCom(request, field_dict) objs = models.XiaohongshuDirectMessagesReply.objects.select_related( 'user_id').filter(q).order_by(order) count = objs.count() if length != 0: start_line = (current_page - 1) * length stop_line = start_line + length objs = objs[start_line:stop_line] ret_data = [] for obj in objs: update_datetime = obj.update_datetime if update_datetime: update_datetime = update_datetime.strftime( '%Y-%m-%d %H:%M:%S') ret_data.append({ 'id': obj.id, 'user_id': obj.user_id_id, 'user_name': obj.user_id.name, 'phone_name': obj.user_id.phone_id.name, 'phone_number': obj.user_id.phone_id.phone_num, 'phone_id': obj.user_id.phone_id_id, 'name': obj.name, 'msg': obj.msg, 'status_id': obj.status, 'status': obj.get_status_display(), 'update_datetime': update_datetime, 'create_datetime': obj.create_datetime.strftime('%Y-%m-%d %H:%M:%S'), }) response.code = 200 response.msg = '查询成功' response.data = { 'ret_data': ret_data, 'count': count, 'status_choices': [{ 'id': i[0], 'name': i[1] } for i in models.XiaohongshuDirectMessagesReply.status_choices] } else: response.code = 301 response.msg = json.loads(forms_obj.errors.as_json()) # 查询历史私信 elif oper_type == 'inquire_historical_private_messages': forms_obj = SelectForm(request.GET) if forms_obj.is_valid(): user_id = request.GET.get('user_id') current_page = forms_obj.cleaned_data['current_page'] length = forms_obj.cleaned_data['length'] order = request.GET.get('order', '-create_datetime') field_dict = { 'user_id_id': '', 'name': '__contains', 'user_id__name': '__contains', } q = conditionCom(request, field_dict) objs = models.XiaohongshuDirectMessages.objects.filter( q).order_by(order) count = objs.count() if length != 0: start_line = (current_page - 1) * length stop_line = start_line + length objs = objs[start_line:stop_line] ret_data = [] for obj in objs: user_id = '' user_name = '' if obj.user_id: user_id = obj.user_id_id user_name = obj.user_id.name ret_data.append({ 'user_id': user_id, 'name': obj.name, 'user_name': user_name, 'img_url': obj.img_url, 'create_datetime': obj.create_datetime.strftime('%Y-%m-%d %H:%M:%S'), }) response.code = 200 response.msg = '查询成功' response.data = {'ret_data': ret_data, 'count': count} else: response.code = 301 response.msg = json.loads(forms_obj.errors.as_json()) else: response.code = 402 response.msg = "请求异常" return JsonResponse(response.__dict__)
def template(request): response = Response.ResponseObj() if request.method == "GET": forms_obj = SelectForm(request.GET) if forms_obj.is_valid(): current_page = forms_obj.cleaned_data['current_page'] length = forms_obj.cleaned_data['length'] print('forms_obj.cleaned_data -->', forms_obj.cleaned_data) is_all = request.GET.get('is_all') # order = request.GET.get('order', '-create_datetime') field_dict = { 'id': '', 'name': '__contains', 'template_class_id': '', 'create_user_id': '', 'create_datetime': '', 'template_class__class_type': '', } q = conditionCom(request, field_dict) user_id = request.GET.get('user_id') user_obj = models.UserProfile.objects.get(id=user_id) if user_obj.inviter: user_id = user_obj.inviter_id obj = models.UserProfile.objects.get(id=user_id) if obj.role_id in [7, '7'] and not is_all: q.add(Q(create_user_id=user_id), Q.AND) else: # q.add(Q(create_user__role_id__in=admin_list), Q.AND) q.add(Q(create_user__role_id__in=[6, 8]), Q.AND) print('q----------> ', q) objs = models.Template.objects.select_related( 'template_class', 'create_user').filter(q).order_by(order) count = objs.count() if length != 0 and not request.GET.get('id'): start_line = (current_page - 1) * length stop_line = start_line + length objs = objs[start_line:stop_line] # 返回的数据 ret_data = [] for obj in objs: template_class_id = '' template_class_name = '' template_class_type = '' if obj.template_class: template_class_id = obj.template_class_id template_class_name = obj.template_class.name template_class_type = obj.template_class.class_type is_authorization = False apple_objs = obj.clientapplet_set.all() if apple_objs and apple_objs[0].is_authorization: is_authorization = True xcx_appid = '' xcx_id = '' if apple_objs and apple_objs[0].template: xcx_id = apple_objs[0].id xcx_appid = apple_objs[0].appid # 将查询出来的数据 加入列表 dict_data = { 'id': obj.id, 'name': obj.name, 'template_class_type': template_class_type, 'is_authorization': is_authorization, 'share_qr_code': obj.share_qr_code, 'logo_img': obj.logo_img, 'xcx_id': xcx_id, 'qrcode': obj.qrcode, 'xcx_qrcode': obj.xcx_qrcode, 'baidu_xcx_qrcode': obj.baidu_xcx_qrcode, 'xcx_appid': xcx_appid, 'thumbnail': obj.thumbnail, 'template_class_name': template_class_name, 'template_class_id': template_class_id, 'create_user__username': base64_encryption.b64decode(obj.create_user.name), 'create_datetime': obj.create_datetime.strftime('%Y-%m-%d %H:%M:%S'), } if request.GET.get('id'): if user_obj.role_id in admin_list: # 管理员角色的公共组件从redis中取出 # objs_two = models.Template.objects.select_related('create_user').filter(create_user__role_id__in=admin_list) # data = [] # for i in objs_two: # if i.common_components: # data.extend(json.loads(i.common_components)) # dict_data['common_components'] = json.dumps(data) redis_obj = get_redis_obj() redis_key = "xcx::template::add_modify_common_components" dict_data['common_components'] = redis_obj.get( redis_key) else: dict_data['common_components'] = obj.common_components ret_data.append(dict_data) # 查询成功 返回200 状态码 response.code = 200 response.msg = '查询成功' response.data = { 'ret_data': ret_data, 'data_count': count, } response.note = { 'id': "模板id", 'name': '模板名称', 'create_datetime': '创建时间', 'share_qr_code': '分享二维码', 'logo_img': 'logo图片', 'is_authorization': '是否授权', "搜索条件": { "name": "模板名称,支持模糊搜索", "template_class_id": "模板分类id", "create_user_id": "创建人id", } } else: response.code = 402 response.msg = "请求异常" response.data = json.loads(forms_obj.errors.as_json()) return JsonResponse(response.__dict__)
def template_oper(request, oper_type, o_id): response = Response.ResponseObj() user_id = request.GET.get('user_id') user_obj = models.UserProfile.objects.get(id=user_id) if user_obj.inviter: user_id = user_obj.inviter_id if request.method == "POST": # 创建模板 if oper_type == "add": form_data = { 'create_user_id': request.GET.get('user_id'), 'name': request.POST.get('name'), 'thumbnail': request.POST.get('thumbnail'), # 缩略图 'template_class_id': request.POST.get('template_class_id'), # 缩略图 } forms_obj = AddForm(form_data) if forms_obj.is_valid(): template_obj = models.Template.objects.create( create_user_id=forms_obj.cleaned_data.get( 'create_user_id'), name=forms_obj.cleaned_data.get('name'), thumbnail=forms_obj.cleaned_data.get('thumbnail'), template_class_id=forms_obj.cleaned_data.get( 'template_class_id'), ) get_gzh_qrcode.delay(template_obj.id, 'https://xcx.bjhzkq.com/wx/?id={}'.format( template_obj.id)) # 生成公众号二维码 if not template_obj.xcx_qrcode: get_xcx_qrcode.delay(template_obj.id, user_id, user_obj.token) # 生成小程序二维码 # 生成百度小程序二维码 if not template_obj.baidu_xcx_qrcode: get_baidu_xcx_qicode.delay(template_obj.id, user_id, user_obj.token) page_group_obj = models.PageGroup.objects.create( name="默认组", template=template_obj) page_obj = models.Page.objects.create( name="首页", page_group=page_group_obj, data=json.dumps(page_base_data), data_dev=json.dumps(page_base_data)) tab_bar_base_data = { "type": "tab_bar", "txt": "底部导航", "style": { 'iconWidth': 32, # 图标大小 'borderStyle': 'solid', # 顶部边框 solid->实线 dotted->点线 dashed->虚线 'borderColor': '#d8d8d8', # 顶部边框颜色 'borderWidth': 1, # 顶部边框粗细 'backgroundColor': '#ffffff', # 背景颜色 'color': '#515a6e', # 文字颜色-未选中 'selectedColor': '#1296db' # 文字颜色-选中 }, "data": [{ "page_id": page_obj.id, "text": '导航1', "icon_path": '/statics/admin_imgs/tabbar/homepage.png', "selected_icon_path": '/statics/admin_imgs/tabbar/homepage_selected.png' }, { "page_id": page_obj.id, "text": '导航2', "icon_path": '/statics/admin_imgs/tabbar/people.png', "selected_icon_path": '/statics/admin_imgs/tabbar/people_selected.png' }] } template_obj.tab_bar_data = json.dumps(tab_bar_base_data) template_obj.tab_bar_data_dev = template_obj.tab_bar_data template_obj.save() response.code = 200 response.msg = "添加成功" response.data = {'testCase': template_obj.id} else: print("验证不通过") response.code = 301 response.msg = json.loads(forms_obj.errors.as_json()) # 删除 模板 elif oper_type == "delete": objs = models.Template.objects.filter(id=o_id) if objs: models.ClientApplet.objects.filter(template_id=o_id).delete() objs.delete() response.code = 200 response.msg = "删除成功" else: response.code = 302 response.msg = '删除ID不存在' # 更改模板 elif oper_type == "update": form_data = { 'o_id': o_id, 'name': request.POST.get('name'), 'logo_img': request.POST.get('logo_img'), 'tab_bar_data': request.POST.get('tab_bar_data'), } forms_obj = UpdateForm(form_data) if forms_obj.is_valid(): # print("验证通过") # print(forms_obj.cleaned_data) o_id = forms_obj.cleaned_data['o_id'] name = forms_obj.cleaned_data['name'] logo_img = forms_obj.cleaned_data['logo_img'] tab_bar_data = forms_obj.cleaned_data['tab_bar_data'] update_data = {} if logo_img: update_data['logo_img'] = logo_img if name: update_data['name'] = name if tab_bar_data: # 此处修改设计模式的数据 # update_data['tab_bar_data'] = tab_bar_data update_data['tab_bar_data_dev'] = tab_bar_data # 更新数据 models.Template.objects.filter(id=o_id).update(**update_data) response.code = 200 response.msg = "修改成功" else: response.code = 301 response.msg = json.loads(forms_obj.errors.as_json()) # 修改到期时间 elif oper_type == "update_expire_date": expire_date = request.POST.get('expire_date') form_data = { "expire_date": expire_date, 'o_id': o_id, } forms_obj = UpdateExpireDateForm(form_data) if forms_obj.is_valid(): # print("验证通过") # print(forms_obj.cleaned_data) o_id = forms_obj.cleaned_data['o_id'] expire_date = forms_obj.cleaned_data['expire_date'] # 更新数据 models.Template.objects.filter(id=o_id).update( expire_datetime=expire_date) response.code = 200 response.msg = "修改成功" else: response.code = 301 response.msg = json.loads(forms_obj.errors.as_json()) # 修改模板分类id/name elif oper_type == "update_class": # 获取需要修改的信息 form_data = { 'o_id': o_id, 'class_id': request.POST.get('class_id'), 'name': request.POST.get('name'), 'thumbnail': request.POST.get('thumbnail'), } forms_obj = UpdateClassForm(form_data) if forms_obj.is_valid(): # print("验证通过") # print(forms_obj.cleaned_data) o_id = forms_obj.cleaned_data['o_id'] name = forms_obj.cleaned_data['name'] class_id = forms_obj.cleaned_data['class_id'] thumbnail = forms_obj.cleaned_data['thumbnail'] # 更新数据 models.Template.objects.filter(id=o_id).update( template_class_id=class_id, name=name, thumbnail=thumbnail, ) response.code = 200 response.msg = "修改成功" else: response.code = 301 response.msg = json.loads(forms_obj.errors.as_json()) # 客户创建模板 elif oper_type == 'user_add_template': # 新建新模板 和 更换模板(需要传递旧模板ID 删除数据) old_template_id = request.POST.get('template_id') form_data = { 'template_id': o_id, } form_obj = UserAddTemplateForm(form_data) if form_obj.is_valid(): template_id, data = form_obj.cleaned_data.get('template_id') if old_template_id: # 如果有旧模板ID 则删掉 template_objs = models.Template.objects.filter( id=old_template_id) page_group_objs = models.PageGroup.objects.filter( template_id=template_objs[0].id) for page_group_obj in page_group_objs: models.Page.objects.filter( page_group_id=page_group_obj.id).delete() page_group_objs.delete() template_objs.update(**data) obj = template_objs[0] else: # 生成新模板 data['create_user_id'] = user_id obj = models.Template.objects.create(**data) get_gzh_qrcode.delay( obj.id, 'https://xcx.bjhzkq.com/wx/?id={}'.format( obj.id)) # 生成公众号二维码 if not obj.xcx_qrcode: get_xcx_qrcode.delay(obj.id, user_id, user_obj.token) # 生成小程序二维码 if not obj.baidu_xcx_qrcode: get_baidu_xcx_qicode.delay( obj.id, user_id, user_obj.token) # 生成百度小程序二维码 tab_bar_data = json.loads(obj.tab_bar_data) # 将page_id 更改 page_group_objs = models.PageGroup.objects.filter( template_id=template_id) for page_group_obj in page_group_objs: PageGroupObj = models.PageGroup.objects.create( name=page_group_obj.name, template_id=obj.id, create_user_id=user_id, ) for page_set in page_group_obj.page_set.all(): page_obj = models.Page.objects.get(id=page_set.id) page_obj = models.Page.objects.create( name=page_obj.name, page_group=PageGroupObj, data=page_obj.data_dev, data_dev=page_obj.data_dev, create_user_id=user_id) for tab_data in tab_bar_data.get('data'): if str(page_set.id) == str( tab_data.get('page_id')): tab_data['page_id'] = page_obj.id if old_template_id: template_objs.update( tab_bar_data=json.dumps(tab_bar_data), tab_bar_data_dev=json.dumps(tab_bar_data), ) else: obj.tab_bar_data = json.dumps(tab_bar_data) obj.tab_bar_data_dev = json.dumps(tab_bar_data) obj.save() response.code = 200 response.msg = '创建成功' response.data = { 'id': obj.id, } else: response.code = 301 response.msg = json.loads(form_obj.errors.as_json()) # 绑定模板和小程序 elif oper_type == 'bind_templates_and_applets': form_data = { 'template_id': request.POST.get('template_id'), 'appid': request.POST.get('appid'), 'user_id': user_id, } form_obj = BindTemplatesAndApplets(form_data) if form_obj.is_valid(): appid = form_obj.cleaned_data.get('appid') template_id = form_obj.cleaned_data.get('template_id') models.ClientApplet.objects.filter(appid=appid).update( template_id=template_id) response.code = 200 response.msg = '绑定成功' else: response.code = 301 response.msg = json.loads(form_obj.errors.as_json()) # 解除绑定小程序和模板 elif oper_type == 'unbind_applet_and_template': form_data = { 'appid': request.POST.get('appid'), 'user_id': user_id, } form_obj = UnbindAppletAndTemplate(form_data) if form_obj.is_valid(): appid = form_obj.cleaned_data.get('appid') user_id = form_obj.cleaned_data.get('user_id') objs = models.ClientApplet.objects.filter(appid=appid, user_id=user_id) objs.update(template=None) response.code = 200 response.msg = '解除绑定成功' else: response.code = 301 response.msg = json.loads(form_obj.errors.as_json()) # 公用组件 添加/修改 elif oper_type == 'add_modify_common_components': form_data = { 'common_components': request.POST.get('common_components'), 'o_id': o_id, } form_objs = AddModifyCommonComponents(form_data) if form_objs.is_valid(): common_components = form_objs.cleaned_data.get( 'common_components') if user_obj.role_id in admin_list: # 管理员角色的公共组件存入redis中 redis_obj = get_redis_obj() redis_key = "xcx::template::add_modify_common_components" redis_obj.set(redis_key, common_components) else: o_id, objs = form_objs.cleaned_data.get('o_id') objs.update(common_components=common_components) response.code = 200 response.msg = '操作成功' else: response.code = 301 response.msg = json.loads(form_objs.errors.as_json()) # 修改触发日志场景 elif oper_type == 'update_triggered_logging_scenario': scenario = request.POST.get('scenario') scenario_id = request.POST.get('scenario_id', 1) objs = models.Template.objects.filter(create_user_id=user_id, id=o_id) data = {scenario: scenario_id} if objs: objs.update(**data) response.code = 200 response.msg = '修改成功' else: response.code = 301 response.msg = '模板错误' # 保存历史版本数据 elif oper_type == "save_history_version": redis_obj = get_redis_obj() template_id = o_id # 模板id remark = request.POST.get('remark') # 备注信息 redis_key = "xcx::template::history_version::{template_id}".format( template_id=template_id) # 查找所有页面数据 template_obj = models.Template.objects.filter(id=template_id) template_data = { "pages_data": [], # 所有页面数据 "tab_bar_data": template_obj[0].tab_bar_data_dev, # 底部导航数据 "remark": remark, # 备注信息 "is_public": False, # 是否为发布版本 "create_datetime": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), "time_stamp": int(time.time() * 10000000) } page_objs = models.Page.objects.filter( page_group__template_id=template_id) for obj in page_objs: page_data = {'page_id': obj.id, 'page_data': obj.data_dev} template_data["pages_data"].append(page_data) redis_data = redis_obj.get(redis_key) if redis_data: redis_data = json.loads(redis_data) else: redis_data = [] redis_data.insert(0, template_data) redis_data = json.dumps(redis_data[:10]) redis_obj.set(redis_key, redis_data) # 只保留最近十次数据 response.code = 200 response.msg = '保存成功' # response.data = redis_data # 历史版本回滚 elif oper_type == "rollback_history_version": redis_obj = get_redis_obj() template_id = o_id # 模板id time_stamp = request.POST.get('time_stamp') # 版本唯一时间戳 redis_key = "xcx::template::history_version::{template_id}".format( template_id=template_id) redis_data = redis_obj.get(redis_key) if redis_data: rollback_data = None redis_data = json.loads(redis_data) for i in redis_data: print("i['time_stamp'] -->", i['time_stamp'], time_stamp, i['time_stamp'] == time_stamp) if str(i['time_stamp']) == time_stamp: # 匹配到版本数据 rollback_data = i tab_bar_data = i["tab_bar_data"] # 底部导航数据 models.Template.objects.filter(id=template_id).update( tab_bar_data_dev=tab_bar_data) pages_data = i["pages_data"] # 页面数据 for page_data in pages_data: page_id = page_data["page_id"] page_data = page_data["page_data"] models.Page.objects.filter(id=page_id).update( data_dev=page_data) break if rollback_data: rollback_data['remark'] = '版本回退, 回退到 {time_stamp}'.format( time_stamp=rollback_data['time_stamp']) rollback_data['time_stamp'] = int(time.time() * 10000000) rollback_data['create_datetime'] = datetime.datetime.now( ).strftime('%Y-%m-%d %H:%M:%S') redis_data.append(rollback_data) response.code = 200 response.msg = '版本回滚成功' else: response.code = 0 response.msg = '请求异常' else: response.code = 0 response.msg = '请求异常' # 版本上线 elif oper_type == "online_history_version": redis_obj = get_redis_obj() template_id = o_id # 模板id time_stamp = request.POST.get('time_stamp') # 版本唯一时间戳 redis_key = "xcx::template::history_version::{template_id}".format( template_id=template_id) redis_data = redis_obj.get(redis_key) if redis_data: redis_data = json.loads(redis_data) for index, i in enumerate(redis_data): print(index, i['time_stamp']) if str(i['time_stamp']) == time_stamp: # 匹配到版本数据 print( "======================> 匹配到版本数据匹配到版本数据匹配到版本数据匹配到版本数据" ) i['is_public'] = True tab_bar_data = i["tab_bar_data"] # 底部导航数据 models.Template.objects.filter(id=template_id).update( tab_bar_data=tab_bar_data) pages_data = i["pages_data"] # 页面数据 for page_data in pages_data: print( "======================> 更换页面数据更换页面数据更换页面数据更换页面数据" ) page_id = page_data["page_id"] page_data = page_data["page_data"] models.Page.objects.filter(id=page_id).update( data=page_data) else: i['is_public'] = False # redis_data.append(i) redis_data[index] = i redis_data = json.dumps(redis_data[:10]) redis_obj.set(redis_key, redis_data) # 只保留最近十次数据 response.code = 200 response.msg = '版本发布成功' else: response.code = 0 response.msg = '请求异常' else: # 获取底部导航数据 if oper_type == "get_tab_bar_data": # 获取需要修改的信息 form_data = {'o_id': o_id} forms_obj = GetTabBarDataForm(form_data) if forms_obj.is_valid(): # print("验证通过") # print(forms_obj.cleaned_data) o_id = forms_obj.cleaned_data['o_id'] template_objs = models.Template.objects.filter(id=o_id) if template_objs: response.code = 200 response.data = { # 'data': template_objs[0].tab_bar_data 'data': template_objs[0].tab_bar_data_dev } else: response.code = 301 response.msg = "模板id异常" else: response.code = 301 response.msg = json.loads(forms_obj.errors.as_json()) # 发布审核时 判断模板是否关联 小程序 elif oper_type == 'determines_whether_template_associated_applet': objs = models.ClientApplet.objects.filter(user_id=user_id) flag = False for obj in objs: if obj.template: if obj.template_id == int(o_id): flag = True response.code = 200 response.msg = '查询成功' response.data = {'flag': flag} # 查询该用户 模板绑定的小程序信息 elif oper_type == 'template_binding_applet_information': binding_type = request.GET.get('binding_type') # 查询绑定类型 data_dict = { 'xcx_appid': '', 'xcx_head_img': '', 'xcx_nick_name': '', 'xcx_id': '', } code = 301 msg = '未绑定小程序' if binding_type in [2, '2']: # 百度小程序 objs = models.BaiduSmallProgramManagement.objects.filter( user_id=user_id, template_id=o_id, ) if objs: appid = objs[0].appid head_img = objs[0].photo_addr nick_name = objs[0].program_name id = objs[0].id else: # 微信小程序 objs = models.ClientApplet.objects.filter( user_id=user_id, template_id=o_id, ) if objs: appid = objs[0].appid head_img = objs[0].head_img nick_name = objs[0].nick_name id = objs[0].id if objs: data_dict['xcx_appid'] = appid data_dict['xcx_head_img'] = head_img data_dict['xcx_nick_name'] = nick_name data_dict['xcx_id'] = id code = 200 msg = '查询成功' response.code = code response.msg = msg response.data = {'data_dict': data_dict} # 查询触发日志场景 elif oper_type == 'query_triggered_logging_scenario': objs = models.Template.objects.filter(id=o_id) if objs: obj = objs[0] ret_data = { 'name_card_details': obj.name_card_details, 'name_save_address_book': obj.name_save_address_book, 'name_make_phone_call': obj.name_make_phone_call, 'name_my': obj.name_my, 'name_article_details': obj.name_article_details, 'name_service_details': obj.name_service_details, 'name_share_page': obj.name_share_page, 'phone_card_details': obj.phone_card_details, 'phone_save_address_book': obj.phone_save_address_book, 'phone_make_phone_call': obj.phone_make_phone_call, 'phone_my': obj.phone_my, 'phone_article_details': obj.phone_article_details, 'phone_service_details': obj.phone_service_details, 'phone_submit_form': obj.phone_submit_form, 'phone_submit_article': obj.phone_submit_article, 'phone_submit_service_order': obj.phone_submit_service_order, 'phone_vote': obj.phone_vote, 'phone_share_page': obj.phone_share_page, } response.code = 200 response.msg = '查询成功' response.data = ret_data else: response.code = 301 response.msg = '模板错误' response.note = { 'name_card_details': '进入名片详情', 'name_save_address_book': '保存通讯录', 'name_make_phone_call': '拨打电话', 'name_my': '我的', 'name_article_details': '文章详情', 'name_service_details': '服务详情', 'name_share_page': '分享页面', 'phone_card_details': '进入名片详情', 'phone_save_address_book': '保存通讯录', 'phone_make_phone_call': '拨打电话', 'phone_my': '我的', 'phone_article_details': '文章详情', 'phone_service_details': '服务详情', 'phone_submit_form': '提交表单', 'phone_submit_article': '提交文章', 'phone_submit_service_order': '提交服务订单', 'phone_vote': '投票', 'phone_share_page': '分享页面', } # 获取模板历史版本数据 elif oper_type == "get_history_version": redis_obj = get_redis_obj() template_id = o_id # 模板id redis_key = "xcx::template::history_version::{template_id}".format( template_id=template_id) redis_data = redis_obj.get(redis_key) if redis_data: redis_data = json.loads(redis_data) else: redis_data = [] """ template_data = { "pages_data": [], # 所有页面数据 "tab_bar_data": template_obj[0].tab_bar_data_dev, # 底部导航数据 "remark": remark, # 备注信息 "is_public": False, # 是否为发布版本 "create_datetime": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') } """ result_data = [] # print("redis_data -->", redis_data) for data in redis_data: # 倒序,最新排最上面 # print("data -->", data) result_data.append({ "remark": data["remark"], "create_datetime": data["create_datetime"], "is_public": data["is_public"], "time_stamp": data["time_stamp"], }) response.code = 200 response.msg = '查询成功' response.data = {"ret_data": result_data} response.note = { "remark": "备注信息", "create_datetime": "创建时间", "is_public": "是否为发布版本", "time_stamp": "时间戳", } else: response.code = 402 response.msg = "请求异常" return JsonResponse(response.__dict__)
def xiaohongshu_phone_management(request, oper_type): response = Response.ResponseObj() user_id = request.GET.get('user_id') if request.method == "GET": # 获取手机工作状态(是否离线)(离线返回True) if oper_type == "get_phone_work_status": form_data = { 'iccid': request.GET.get('iccid'), 'imsi': request.GET.get('imsi'), 'macaddr': request.GET.get('macaddr'), 'phone_type': request.GET.get('phone_type'), } flag = True form_obj = GetPhoneWorkStatus(form_data) if form_obj.is_valid(): iccid = form_obj.cleaned_data.get('iccid') imsi = form_obj.cleaned_data.get('imsi') macaddr = form_obj.cleaned_data.get('macaddr') phone_type = int(form_obj.cleaned_data.get('phone_type')) if phone_type == 1: # 查覆盖 objs = models.XiaohongshuPhone.objects.filter( phone_type=phone_type, macaddr=macaddr) else: objs = models.XiaohongshuPhone.objects.filter( phone_type=phone_type, iccid=iccid, imsi=imsi, ) if objs: obj = objs[0] now = datetime.datetime.today() deletionTime = (now - datetime.timedelta(minutes=5) ) # 当前时间减去5分钟 if obj.last_sign_in_time and obj.last_sign_in_time >= deletionTime: flag = False # phone_log_objs = models.XiaohongshuPhoneLog.objects.filter( # parent=obj.id, # create_datetime__gte=deletionTime # ).order_by('-create_datetime') # if phone_log_objs: response.code = 200 response.data = {'flag': flag} response.note = {'flag': '如果为True 则异常'} else: response.code = 301 response.msg = '该手机不存在' else: response.code = 301 response.msg = json.loads(form_obj.errors.as_json()) # 获取未使用的手机号 绑定关系 elif oper_type == 'get_phone_number': form_data = { 'iccid': request.GET.get('iccid'), 'imsi': request.GET.get('imsi'), # 'macaddr': request.GET.get('macaddr'), } form_obj = GetPhoneNumber(form_data) if form_obj.is_valid(): iccid = form_obj.cleaned_data.get('iccid') imsi = form_obj.cleaned_data.get('imsi') # macaddr = form_obj.cleaned_data.get('macaddr') # if macaddr: data = {"iccid": iccid, "imsi": imsi} # else: # data = { # "macaddr": macaddr # } phone_objs = models.XiaohongshuPhone.objects.filter(**data) if phone_objs: phone_obj = phone_objs[0] number_objs = models.PhoneNumber.objects.filter( phone=phone_obj) if not number_objs: number_objs = models.PhoneNumber.objects.filter( status=1, phone__isnull=True) if number_objs: number_obj = number_objs[0] number_obj.phone_id = phone_objs[ 0].id # 将手机号和设备进行关联 number_obj.status = 2 number_obj.save() phone_num = number_obj.phone_num else: response.code = 301 response.msg = '暂无可用手机号' phone_num = '' else: phone_num = number_objs[0].phone_num response.code = 200 response.data = {'phone_number': phone_num} else: response.code = 301 response.msg = '该设备不存在' else: response.code = 301 response.msg = json.loads(form_obj.errors.as_json()) # 获取验证码 elif oper_type == 'get_verification_code': form_data = {'phone_number': request.GET.get('phone_number')} form_obj = GetVerificationCode(form_data) if form_obj.is_valid(): phone_number = form_obj.cleaned_data.get('phone_number') phone_management_objs = phone_management() phone_management_objs.login() verification_code, yzm_time = phone_management_objs.query_verification_code( phone_number) if verification_code: response.code = 200 response.msg = '查询成功' response.data = { 'verification_code': verification_code, 'yzm_time': yzm_time } else: response.code = 301 response.msg = '暂无验证码' else: response.code = 301 response.msg = json.loads(form_obj.errors.as_json()) # 获取小红书未注册的账号信息 elif oper_type == 'get_xhs_unregistered_information': form_data = { 'get_info_number': request.GET.get('get_info_number', 1) # 获取几个信息 } response.code = 301 form_obj = GetXhsUnregisteredInformation(form_data) if form_obj.is_valid(): get_info_number = int( form_obj.cleaned_data.get('get_info_number')) objs = models.XiaohongshuUserProfileRegister.objects.filter( is_register=False, register_datetime__isnull=True ) # is_register 未被注册 register_datetime 注册时间 count = objs.count() if get_info_number > count: msg = '当前未注册小红书账号低于{}条, 剩余{}条'.format( get_info_number, count) else: data_list = [] for obj in objs[0:get_info_number]: platform_name = '小红书' if obj.platform in [2, '2']: platform_name = '美图秀秀' data_list.append({ 'gender_id': obj.gender, 'gender': obj.get_gender_display(), 'head_portrait': obj.head_portrait, 'birthday': obj.birthday, 'name': obj.name, 'platform': obj.platform, 'platform_name': platform_name, }) response.code = 200 msg = '查询成功' response.data = {'ret_data': data_list, 'count': count} else: msg = json.loads(form_obj.errors.as_json()) response.msg = msg # 查询小红书所有设备信息 elif oper_type == 'get_phone_number_info': forms_obj = SelectForm(request.GET) if forms_obj.is_valid(): current_page = forms_obj.cleaned_data['current_page'] length = forms_obj.cleaned_data['length'] order = request.GET.get('order', '-create_datetime') field_dict = { 'id': '', 'phone_type': '', 'is_debug': '', 'name': '__contains', 'status': '', 'phone_num': '__contains', 'recharge_card_number': '__contains', } q = conditionCom(request, field_dict) select_id = request.GET.get('id') objs = models.XiaohongshuPhone.objects.filter(q) status = request.GET.get('status') if status: objs = objs.exclude(is_debug=True) objs = objs.order_by(order) count = objs.count() if length != 0: start_line = (current_page - 1) * length stop_line = start_line + length objs = objs[start_line:stop_line] ret_data = [] for obj in objs: phone_num = obj.phone_num phone_objs = obj.phonenumber_set.all() if not phone_num and phone_objs: phone_obj = phone_objs[0] phone_num = phone_obj.phone_num try: comment_last_updated = obj.comment_last_updated.strftime( '%Y-%m-%d %H:%M:%S') except Exception: comment_last_updated = obj.comment_last_updated result_data = { 'id': obj.id, 'name': obj.name, 'ip_addr': obj.ip_addr, 'phone_num': phone_num, 'imsi': obj.imsi, 'status_id': obj.status, 'status': obj.get_status_display(), 'iccid': obj.iccid, 'phone_type_id': obj.phone_type, 'phone_type': obj.get_phone_type_display(), 'is_debug': obj.is_debug, 'macaddr': obj.macaddr, 'recharge_card_number': obj.recharge_card_number, 'comment_last_updated': comment_last_updated, 'create_datetime': obj.create_datetime.strftime('%Y-%m-%d %H:%M:%S'), } if select_id: phone_log_objs = models.XiaohongshuPhoneLog.objects.filter( parent_id=obj.id).order_by('-create_datetime') if phone_log_objs.count() > 5: phone_log_objs = phone_log_objs[:5] phone_log_data_list = [] for phone_log_obj in phone_log_objs: phone_log_data_list.append(phone_log_obj.log_msg) result_data[ 'phone_log_data_list'] = phone_log_data_list ret_data.append(result_data) response.code = 200 response.msg = '查询成功' response.data = { 'ret_data': ret_data, 'count': count, 'status_choices': [{ 'id': i[0], 'name': i[1] } for i in models.XiaohongshuPhone.status_choices] } else: response.code = 301 response.msg = json.loads(forms_obj.errors.as_json()) # 查询小红书 单设备 日志信息 elif oper_type == 'get_equipment_log': equipment_id = request.GET.get('equipment_id') forms_obj = SelectForm(request.GET) if forms_obj.is_valid(): current_page = forms_obj.cleaned_data['current_page'] length = forms_obj.cleaned_data['length'] order = request.GET.get('order', '-create_datetime') # objs = models.XiaohongshuPhoneLog.objects.filter(parent_id=equipment_id).order_by(order) redis_obj = get_redis_obj() # 从redis中获取数据 phone_log_id_key = "phone_log_{phone_id}".format( phone_id=equipment_id) count = redis_obj.llen(phone_log_id_key) start_line = (current_page - 1) * length stop_line = start_line + length objs = redis_obj.lrange(phone_log_id_key, start_line, stop_line) ret_data = [] n = 0 for obj in objs: msg = json.loads(obj)['log_msg'] create_date = json.loads(obj)['create_date'] n += 1 ret_data.append({ 'id': n, 'msg': msg, 'create_date': create_date }) response.code = 200 response.msg = '查询成功' response.data = {'ret_data': ret_data, 'count': count} else: response.code = 402 response.msg = "请求异常" else: # 修改 移动设备 (设备名称 是否调试) if oper_type == 'update_mobile_devices': form_data = { 'phone_id': request.POST.get('phone_id'), # 要修改的设备ID 'device_name': request.POST.get('device_name'), # 设备名称 'is_debug': request.POST.get('is_debug'), # 是否调试 } forms_obj = UpdateMobileDevices(form_data) if forms_obj.is_valid(): form_data_obj = forms_obj.cleaned_data phone_id = form_data_obj.get('phone_id') device_name = form_data_obj.get('device_name') is_debug = form_data_obj.get('is_debug') models.XiaohongshuPhone.objects.filter(id=phone_id).update( is_debug=is_debug, name=device_name) response.msg = '修改成功' response.code = 200 else: response.code = 301 response.msg = json.loads(forms_obj.errors.as_json()) else: response.code = 402 response.msg = "请求异常" return JsonResponse(response.__dict__)