Exemple #1
0
def asynchronous_transfer_data(request):
    """
    transfer_type: 传递类型(
        1传递到小红书后台
        2传递小红书评论成功
        3更改笔记阅读量
        4删除评论是否成功
        5传递更改笔记为发布异常
        6更改博主是否开启地图
        7更改评论对应的笔记
    )
    :param request:
    :return:
    """
    transfer_type = request.POST.get('transfer_type')
    msg = '异步传送小红书后台数据'
    try:
        if transfer_type in [1, '1']:
            msg = '异步传输小红书评论数据'
            url = 'https://a.ppxhs.com/api/v1/sync/sync-comment'
            ret = requests.post(url, data=request.POST)
            obj = models.littleRedBookReviewForm.objects.get(
                id=request.POST.get('comment_id'))  # 修改上传状态
            obj.status = 2
            obj.save()

        elif transfer_type in [3, '3']:
            msg = '异步传输小红书阅读量'
            url = 'https://a.ppxhs.com/api/v1/sync/sync-read-num'
            ret = requests.post(url, data=request.POST)

        elif transfer_type in [4, '4']:
            msg = '异步传输小红书回复评论是否删除'
            url = 'https://a.ppxhs.com/api/v1/sync/sync-delete-comment'
            ret = requests.post(url, data=request.POST)

        elif transfer_type in [5, '5']:
            msg = '异步传输 笔记改为发布异常'
            url = 'https://a.ppxhs.com/api/v1/sync/article-error'
            ret = requests.post(url, data=request.POST)

        elif transfer_type in [6, '6']:
            msg = '异步传输 更改博主是否开启地图'
            url = 'https://a.ppxhs.com/api/v1/sync/open-location'
            ret = requests.post(url, data=request.POST)

        elif transfer_type in [7, '7']:
            msg = '异步传输 更改评论对应的笔记'
            url = 'https://a.ppxhs.com/api/v1/sync/comment-article'
            ret = requests.post(url, data=request.POST)

        else:  # 2
            msg = '异步传输小红书回复评论状态'
            url = 'https://a.ppxhs.com/api/v1/sync/sync-reply-status'
            ret = requests.post(url, data=request.POST)

        response_content = ret.json()

    except Exception as e:
        response_content = e
        content = '{} \n {}报错{}\n错误:{}'.format(datetime.datetime.today(), msg,
                                               transfer_type, e)
        send_error_msg(content, 5)
    req_type = 1
    if request.method == 'POST':
        req_type = 2

    create_xhs_admin_response(request,
                              response_content,
                              1,
                              url=url,
                              req_type=req_type)  # 创建请求日志 后台请求小红书

    return HttpResponse('')
Exemple #2
0
def xiaohongshu_biji_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":
        # 添加
        if oper_type == "add":
            form_data = {
                'xiaohongshu_id': request.POST.get('xiaohongshu_id'),
                'content': request.POST.get('content'),
                'release_time': request.POST.get('release_time', datetime.datetime.now())
            }
            #  创建 form验证 实例(参数默认转成字典)
            forms_obj = AddForm(form_data)
            if forms_obj.is_valid():
                print("验证通过")


                xiaohongshu_id = forms_obj.cleaned_data.get('xiaohongshu_id')
                title, content, biji_type = forms_obj.cleaned_data.get('content')
                release_time = forms_obj.cleaned_data.get('release_time')
                platform = request.POST.get('platform', 1)
                xiaohongshu_user_objs = models.XiaohongshuUserProfile.objects.filter(xiaohongshu_id=xiaohongshu_id, platform=platform)
                if xiaohongshu_user_objs:
                    xiaohongshu_user_obj = xiaohongshu_user_objs[0]

                    biji_id = request.POST.get('biji_id') # 如果有 该值 则更新 待审核状态
                    if biji_id:
                        biji_objs = models.XiaohongshuBiji.objects.filter(id=biji_id)
                        obj = biji_objs[0]
                        biji_objs.update(status=3, content=content, release_time=release_time, title=title, biji_type=biji_type, user_id_id=xiaohongshu_user_obj.id)
                        response.code = 200
                        response.msg = "更新成功"

                    else:
                        objs = models.XiaohongshuBiji.objects.filter(
                            title=title,
                            user_id_id=xiaohongshu_user_obj.id,
                            user_id__platform=platform
                        )
                        if objs:
                            response.code = 301
                            response.msg = '笔记已存在, 请勿重复添加'
                            return JsonResponse(response.__dict__)

                        else:
                            obj = models.XiaohongshuBiji.objects.create(
                                user_id=xiaohongshu_user_obj,
                                content=content,
                                release_time=release_time,
                                title=title,
                                biji_type=biji_type
                            )
                            response.msg = "添加成功"
                        response.code = 200
                    response.data = {
                        'biji_id': obj.id
                    }
                else:
                    response.code = 0
                    response.msg = "添加失败, 小红书id不存在"

            else:
                print("验证不通过")
                response.code = 301
                response.msg = json.loads(forms_obj.errors.as_json())
            create_xhs_admin_response(request, response, 2)

        # 提交反链
        elif oper_type == "upload_url":
            form_data = {
                'task_id': request.POST.get('task_id'),
                'url': request.POST.get('url'),
            }
            forms_obj = UploadUrlForm(form_data)
            if forms_obj.is_valid():
                print("验证通过")

                task_id = forms_obj.cleaned_data.get('task_id')
                url = forms_obj.cleaned_data.get('url')
                link = get_existing_url(url) # 获取真实链接

                completion_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                biji_objs = models.XiaohongshuBiji.objects.filter(id=task_id)
                biji_objs.update(
                    biji_existing_url=link,
                    biji_url=link,
                    status=2,
                    completion_time=completion_time
                )

                api_url = "https://www.ppxhs.com/api/v1/sync/sync-screen-article"
                data = {
                    "id": task_id,
                    "link": link,
                    "platform": biji_objs[0].user_id.platform,
                    "pubTime": completion_time,
                    "online_pic": "http://qiniu.bjhzkq.com/xiaohongshu_fabu_1560934704790"
                }
                ret = requests.post(url=api_url, data=data)
                create_xhs_admin_response(request, ret.json(), 1, url=api_url, req_type=2)  # 记录请求日志
                response.code = 200
                response.msg = "提交成功"

            else:
                print("验证不通过")
                response.code = 301
                response.msg = json.loads(forms_obj.errors.as_json())
            create_xhs_admin_response(request, response, 3)

        # 发布笔记(后台)
        elif oper_type == 'published_articles':
            now = datetime.datetime.today()
            flag = False
            hms_date = datetime.datetime.today().strftime('%H:%M:%S')
            hms_date = datetime.datetime.strptime(hms_date, '%H:%M:%S')

            if datetime.datetime.strptime('8:30:00', '%H:%M:%S') >= hms_date >= datetime.datetime.strptime('7:30:00', '%H:%M:%S'):
                flag = True
            elif datetime.datetime.strptime('13:30:00', '%H:%M:%S') >= hms_date >= datetime.datetime.strptime('12:00:00', '%H:%M:%S'):
                flag = True
            elif datetime.datetime.strptime('21:30:00', '%H:%M:%S') >= hms_date >= datetime.datetime.strptime('17:00:00', '%H:%M:%S'):
                flag = True

            if flag:
                id_list = json.loads(request.POST.get('id_list'))
                objs = models.XiaohongshuBiji.objects.filter(id__in=id_list)
                for obj in objs:
                    obj.status = 1
                    obj.save()
                response.code = 200
                response.msg = '发布成功'

            else:
                response.code = 301
                response.msg = '当前时间不在发布时间段'
            create_xhs_admin_response(request, response, 3)  # 创建请求日志(手机端)

        # 阅读量更改(后台)
        elif oper_type == 'update_reding':
            """
            o_id: 笔记ID
            reading_num: 阅读量
            """
            form_data = {
                'o_id': o_id,
                'reading_num': request.POST.get('reading_num')
            }

            form_obj = UpdateReding(form_data)
            if form_obj.is_valid():
                o_id = form_obj.cleaned_data.get('o_id')
                reading_num = int(form_obj.cleaned_data.get('reading_num'))
                if reading_num > 0:

                    objs = models.XiaohongshuBiji.objects.filter(
                        id=o_id
                    )
                    objs.update(
                        reading_num=reading_num,
                        update_reding_num_time=datetime.datetime.today()
                    )
                    form_data['num'] = reading_num
                    form_data['transfer_type'] = 3
                    form_data['id'] = o_id
                    form_data['platform'] = objs[0].user_id.platform
                    asynchronous_transfer_data.delay(form_data) # 传递到小红书后台
                response.code = 200
                response.msg = '阅读量更新完成'

            else:
                response.code = 301
                response.msg = json.loads(form_obj.errors.as_json())
            create_xhs_admin_response(request, response, 3)

        # 发布中的笔记 可以改为发布异常(后台)
        elif oper_type == 'instead_abnormal_release_notes':
            form_data = {
                'o_id': o_id,
                'error_msg': request.POST.get('error_msg')
            }
            form_obj = InsteadAbnormalReleaseNotes(form_data)
            if form_obj.is_valid():
                o_id = form_obj.cleaned_data.get('o_id')
                error_msg = form_obj.cleaned_data.get('error_msg')
                obj = models.XiaohongshuBiji.objects.get(id=o_id)
                obj.status = 4
                obj.error_msg = error_msg
                obj.save()
                response.code = 200
                response.msg = '更改发布异常成功'

                form_data['transfer_type'] = 5
                form_data['id'] = o_id
                form_data['platform'] = obj.user_id.platform
                form_data['content'] = error_msg
                asynchronous_transfer_data.delay(form_data)  # 传递到小红书后台
            else:
                response.code = 301
                response.msg = json.loads(form_obj.errors.as_json())
            create_xhs_admin_response(request, response, 2)

        # 已发布的可修改回链(后台)
        elif oper_type == 'published_notes_back_chain':
            form_data = {
                'o_id': o_id,
                'back_url': request.POST.get('back_url')
            }
            form_obj = PublishedNotesBackChain(form_data)
            if form_obj.is_valid():
                o_id = form_obj.cleaned_data.get('o_id')
                back_url, link = form_obj.cleaned_data.get('back_url')
                obj = models.XiaohongshuBiji.objects.get(id=o_id)
                obj.biji_url = back_url
                obj.biji_existing_url = link
                obj.save()
                response.code = 200
                response.msg = '修改反链成功'
                asynchronous_synchronous_trans.delay(o_id) # 异步更改小红书后台回链
            else:
                response.code = 301
                response.msg = json.loads(form_obj.errors.as_json())
            create_xhs_admin_response(request, response, 1)

        # 修改笔记是否存在内容的状态
        elif oper_type == "update_exist_content":
            status = request.POST.get('status')
            form_data = {
                'status': request.POST.get('status'),
                'o_id': o_id,
            }
            print("status -->", status, type(status))
            #  创建 form验证 实例(参数默认转成字典)
            forms_obj = UpdateExistContentForm(form_data)
            if forms_obj.is_valid():
                status = forms_obj.cleaned_data.get('status')
                models.XiaohongshuBiji.objects.filter(id=o_id).update(exist_content=status)
                response.code = 200
                response.msg = "修改成功"

            else:
                print("验证不通过")
                response.code = 301
                response.msg = json.loads(forms_obj.errors.as_json())

        # 已发布的笔记 改为重新发布(小红书后台) 404
        elif oper_type == 'republish_instead':
            form_data = {
                'o_id':o_id,
            }
            form_obj = RepublishInsteadForm(form_data)
            if form_obj.is_valid():
                o_id = form_obj.cleaned_data.get('o_id')
                models.XiaohongshuBiji.objects.filter(id=o_id).update(
                    status=5,
                    is_delete_old_biji=False
                )
                response.code = 200
                response.msg = '修改成功'

            else:
                response.code = 301
                response.msg = json.loads(form_obj.errors.as_json())
            create_xhs_admin_response(request, response, 2)

        # 重新发布的笔记 改为待审核(后台)
        elif oper_type == 'change_pending_review':
            form_data = {
                'biji_id_list': request.POST.get('biji_id_list')
            }
            form_obj = ChangePendingReview(form_data)
            if form_obj.is_valid():
                biji_id_list = form_obj.cleaned_data.get('biji_id_list')
                objs = models.XiaohongshuBiji.objects.filter(
                    id__in=biji_id_list
                )
                objs.update(
                    is_delete_old_biji=True
                )
                for obj in objs:
                    url = 'https://www.ppxhs.com/api/v1/sync/screen-notfound'
                    data = {
                        'id':obj.id,
                        'platform':obj.user_id.platform
                    }
                    ret = requests.post(url, data=data)
                    models.AskLittleRedBook.objects.create(  # 更新日志
                        request_type=2,  # POST请求
                        request_url=url,
                        get_request_parameter='',
                        post_request_parameter=data,
                        response_data=ret.json(),
                        status=1
                    )
                response.code = 200
                response.msg = '删除成功'

            else:
                response.code = 301
                response.msg = json.loads(form_obj.errors.as_json())
            create_xhs_admin_response(request, response, 2)

        else:
            response.code = 402
            response.msg = "请求异常"

    else:
        # 获取发布任务
        if oper_type == "get_release_task":
            form_data = {
                'imsi': request.GET.get('imsi'),
                'iccid': request.GET.get('iccid'),
                'platform': request.GET.get('platform', 1),
            }
            forms_obj = GetReleaseTaskForm(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.XiaohongshuBiji.objects.select_related('user_id').filter(
                    user_id__platform=platform,
                    user_id__phone_id__iccid=iccid,
                    user_id__phone_id__imsi=imsi,
                    status=1,
                    release_time__lt=datetime.datetime.now()
                )

                if objs:
                    obj = objs[0]

                    response.data = {
                        "id": obj.id,
                        "content": obj.content,
                        "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())
            create_xhs_admin_response(request, response, 3)
        # 查询 小红书笔记(后台)
        elif oper_type == 'get_xhs_notes':
            forms_obj = select_form(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': '',
                    'uid': '__contains',
                    'status': '',
                    'biji_type': '',
                    'user_id__name': '__contains',
                    'is_delete_old_biji': '',
                    'user_id__phone_id__name': '',
                    'biji_existing_url': '__contains',
                    'reading_num': '',
                }
                q = conditionCom(request, field_dict)
                content = request.GET.get('content')
                xhs_user_id = request.GET.get('xhs_user_id')
                if content:
                    q.add(Q(title__contains=b64encode(content)), Q.AND)
                if xhs_user_id:
                    q.add(Q(user_id=xhs_user_id), Q.AND)
                objs = models.XiaohongshuBiji.objects.select_related('user_id').filter(
                    q,
                ).exclude(user_id_id=5).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:
                    # biji_type = 'img'
                    # if json.loads(obj.content).get('type') and json.loads(obj.content).get('type') != 'images':
                    #     biji_type = 'video'
                    release_time = obj.release_time
                    if release_time:
                        release_time = obj.release_time.strftime('%Y-%m-%d %H:%M:%S')

                    completion_time = obj.completion_time
                    if completion_time:
                        completion_time = obj.completion_time.strftime('%Y-%m-%d %H:%M:%S')

                    update_reding_num_time = ''
                    if obj.update_reding_num_time:
                        update_reding_num_time = obj.update_reding_num_time.strftime('%Y-%m-%d %H:%M:%S')
                    result_data = {
                        'id': obj.id,
                        'user_id': obj.user_id_id,
                        'phone_id': obj.user_id.phone_id_id,
                        'phone_name': obj.user_id.phone_id.name,
                        'phone_number': obj.user_id.phone_id.phone_num,
                        'user_name': obj.user_id.name,
                        'status_id': obj.status,
                        'reading_num': obj.reading_num,
                        'status': obj.get_status_display(),
                        'release_time': release_time,
                        'completion_time': completion_time,
                        'biji_url': obj.biji_url,
                        'error_msg': obj.error_msg,
                        'biji_type_id': obj.biji_type,
                        'biji_type': obj.get_biji_type_display(),
                        'biji_existing_url': obj.biji_existing_url,
                        'is_delete_old_biji': obj.is_delete_old_biji,
                        'update_reding_num_time': update_reding_num_time,
                        'platform': obj.user_id.platform,
                        'exist_content': obj.exist_content,
                        'create_datetime': obj.create_datetime.strftime('%Y-%m-%d %H:%M:%S'),
                    }
                    result_data['content'] = json.loads(obj.content)
                    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.XiaohongshuBiji.status_choices],
                    'biji_type_choices': [{'id':i[0], 'name':i[1]} for i in models.XiaohongshuBiji.biji_type_choices]
                }
            else:
                response.code = 301
                response.msg = json.loads(forms_obj.errors.as_json())

        # 获取 exist_content 字段为False的笔记链接,请求小红书接口进行获取数据,判断文章内容是否正常
        elif oper_type == "exist_content_get_url":
            objs = models.XiaohongshuBiji.objects.filter(status=2, exist_content=0)
            if objs:
                obj = objs[0]
                response.code = 200
                biji_id = obj.biji_existing_url.split('/')[-1]
                response.data = {
                    'biji_id': biji_id,
                    'task_id': obj.id
                }
            else:
                response.code = 0
                response.msg = "当前无任务"


        else:
            response.code = 402
            response.msg = "请求异常"
    return JsonResponse(response.__dict__)
def xiaohongshu_userprofile_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":
        # 更新小红书用户信息
        if oper_type == "update_userinfo":
            form_data = {
                'phone_num': request.POST.get('phone_num'),
                'imsi': request.POST.get('imsi'),
                'iccid': request.POST.get('iccid'),
                'name': request.POST.get('name'),
                'xiaohongshu_id': request.POST.get('xiaohongshu_id'),
                'home_url': request.POST.get('home_url'),
                'macaddr': request.POST.get('macaddr'),
                'platform': request.POST.get('platform', 1),
            }
            #  创建 form验证 实例(参数默认转成字典)
            forms_obj = UpdateUserinfoForm(form_data)
            if forms_obj.is_valid():

                phone_num = forms_obj.cleaned_data.get('phone_num')
                imsi = forms_obj.cleaned_data.get('imsi')
                iccid = forms_obj.cleaned_data.get('iccid')
                name = forms_obj.cleaned_data.get('name')
                xiaohongshu_id = forms_obj.cleaned_data.get('xiaohongshu_id')
                home_url = forms_obj.cleaned_data.get('home_url')
                macaddr = forms_obj.cleaned_data.get('macaddr')
                platform = forms_obj.cleaned_data.get('platform')
                if macaddr:
                    data = {'macaddr': macaddr}
                else:
                    data = {'imsi': imsi, 'iccid': iccid}
                objs = models.XiaohongshuPhone.objects.filter(**data)

                # print("objs --->", objs)
                if objs:
                    obj = objs[0]
                    print('obj.id-----> ', obj.id, name)

                    # else:
                    #     xiaohongshu_userprofile_obj = models.XiaohongshuUserProfile.objects.get(
                    #         phone_id=obj
                    #     )
                    #     xiaohongshu_userprofile_obj.platform = platform
                    #     xiaohongshu_userprofile_obj.name = name
                    #     xiaohongshu_userprofile_obj.xiaohongshu_id = xiaohongshu_id
                    #     xiaohongshu_userprofile_obj.home_url = home_url
                    #     xiaohongshu_userprofile_obj.save()

                    # 如果小红书博主注册表中有未注册的,则将信息提交给小红书后台
                    xhs_userprofile_register_objs = models.XiaohongshuUserProfileRegister.objects.filter(
                        name=name,
                        is_register=False,
                    )
                    if xhs_userprofile_register_objs:
                        if not obj.xiaohongshuuserprofile_set.all():
                            objs.update(phone_num=phone_num, is_debug=False)
                            xiaohongshu_userprofile_obj = obj.xiaohongshuuserprofile_set.create(
                                name=name,
                                xiaohongshu_id=xiaohongshu_id,
                                home_url=home_url,
                                platform=platform)

                            xhs_userprofile_register_obj = xhs_userprofile_register_objs[
                                0]
                            # print("===============>", xhs_userprofile_register_obj.name, xhs_userprofile_register_obj.uid)
                            # 将注册成功的小红书账号推送到小红书后台
                            api_url = "https://www.ppxhs.com/api/v1/sync/sync-screen-blogger"
                            data = {
                                "id": xhs_userprofile_register_obj.uid,
                                "xhs_id": xiaohongshu_id,
                                "link": home_url,
                                "mobile": phone_num,
                                "platform": platform,
                            }
                            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)  # 记录请求日志
                            xhs_userprofile_register_objs.update(
                                is_register=True,
                                register_datetime=datetime.datetime.now())
                            response.code = 200
                            response.msg = "更新成功"

                        else:
                            # 第二次更新数据
                            response.code = 301
                            response.msg = "更新异常,不能重复提交注册信息,请联系管理员"
                    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 == "registre":
            form_data = {
                'uid': request.POST.get('uid'),
                'name': request.POST.get('name'),
                'head_portrait': request.POST.get('head_portrait'),
                'gender': request.POST.get('gender'),
                'birthday': request.POST.get('birthday'),
                'remark': request.POST.get('remark'),
                'platform': request.POST.get('platform', 1)
            }
            #  创建 form验证 实例(参数默认转成字典)
            forms_obj = RegistreForm(form_data)
            if forms_obj.is_valid():
                models.XiaohongshuUserProfileRegister.objects.create(
                    **forms_obj.cleaned_data)
                response.code = 200
                response.msg = "添加成功"
            else:
                print("验证不通过")
                response.code = 301
                response.msg = json.loads(forms_obj.errors.as_json())

        # 修改阅读量更新时间(手机)
        elif oper_type == 'update_reading_update_time':
            form_data = {
                'imsi': request.POST.get('imsi'),
                'iccid': request.POST.get('iccid')
            }
            form_obj = IsTodayUpdateReading(form_data)
            if form_obj.is_valid():
                imsi = form_obj.cleaned_data.get('imsi')
                obj = models.XiaohongshuUserProfile.objects.get(id=imsi)
                obj.update_reading_date = datetime.date.today()
                obj.save()
                response.code = 200
                response.msg = '修改成功'

            else:
                response.code = 301
                response.msg = json.loads(form_obj.errors.as_json())

        # 更改是否开启地图
        elif oper_type == 'change_whether_open_the_map':
            objs = models.XiaohongshuUserProfile.objects.filter(id=o_id)
            if objs:
                obj = objs[0]
                add_map_not = 1 - obj.add_map_not
                objs.update(add_map_not=add_map_not)
                response.code = 200
                response.msg = '更改成功'
                data = {
                    'transfer_type': 6,
                    'xiaohongshu_id': obj.xiaohongshu_id,
                    'pubStatus': add_map_not
                }
                asynchronous_transfer_data.delay(data)

            else:
                response.code = 301
                response.msg = '博主不存在'

    else:
        # 判断是否需要更新个人信息
        if oper_type == "is_update_userinfo":
            form_data = {
                'imsi': request.GET.get('imsi'),
                'iccid': request.GET.get('iccid')
            }
            forms_obj = IsUpdateUserinfoForm(form_data)
            if forms_obj.is_valid():
                imsi = forms_obj.cleaned_data['imsi']
                iccid = forms_obj.cleaned_data['iccid']

                objs = models.XiaohongshuUserProfile.objects.filter(
                    phone_id__imsi=imsi, phone_id__iccid=iccid)

                is_update = False
                if not objs:  # 没有数据,需要更新
                    is_update = True

                #  查询成功 返回200 状态码
                response.code = 200
                response.msg = '查询成功'
                response.data = {
                    "is_update": is_update,
                }
            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 == 'check_updated_today':

            response.code = 200
            response.msg = '查询成功'
            response.data = {"flag": True}

            # form_data = {
            #     'imsi': request.GET.get('imsi'),
            #     'iccid': request.GET.get('iccid')
            # }
            # form_obj = IsTodayUpdateReading(form_data)
            # if form_obj.is_valid():
            #     imsi = form_obj.cleaned_data.get('imsi')
            #     obj = models.XiaohongshuUserProfile.objects.get(
            #         id=imsi
            #     )
            #     flag = False # 更新
            #
            #     if not models.XiaohongshuBiji.objects.filter(user_id_id=obj.id, status=2):
            #         flag = True
            #     else:
            #         update_reading_date = obj.update_reading_date
            #         if update_reading_date and update_reading_date == datetime.date.today():
            #             flag = True
            #
            #     response.code = 200
            #     response.msg = '查询成功'
            #     response.data = {
            #         "flag": flag
            #     }
            #
            # else:
            #     response.code = 301
            #     response.msg = json.loads(form_obj.errors.as_json())

        else:
            response.code = 402
            response.msg = "请求异常"
    return JsonResponse(response.__dict__)
def comment_management(request, oper_type):
    response = Response.ResponseObj()
    user_id = request.GET.get('user_id')
    if request.method == 'POST':


        # 手机端添加接口  (获取用户的评论内容提交到接口保存)③
        if oper_type == "mobile_phone_reviews":
            iccid = request.POST.get('iccid')
            imsi = request.POST.get('imsi')

            objs = models.XiaohongshuPhone.objects.filter(
                iccid=iccid,
                imsi=imsi
            )
            if not objs:
                response.code = 301
                response.msg = '该设备不存在'

            else:
                obj = objs[0]
                user_objs = obj.xiaohongshuuserprofile_set.all()
                if not user_objs:
                    response.code = 301
                    response.msg = '该设备 未关联小红书客户'
                else:
                    xhs_user_id = user_objs[0].id
                    form_data = {
                        'xhs_user_id': xhs_user_id, # 小红书用户
                        'head_portrait': request.POST.get('head_portrait'), # 头像
                        'nick_name': request.POST.get('nick_name'), # 昵称
                        'comments_status': request.POST.get('comments_status'), # 评论类型
                        'comments_content': request.POST.get('comments_content'), # 评论内容
                        'article_picture_address': request.POST.get('article_picture_address'), # 文章图片地址
                        'article_notes_id': request.POST.get('article_notes_id'), # 文章笔记
                        'screenshots_address': request.POST.get('screenshots_address'), # 截图地址
                    }
                    forms_obj = mobilePhoneReviews(form_data)
                    if forms_obj.is_valid():
                        forms_data = forms_obj.cleaned_data
                        article_picture_address = forms_data.get('article_picture_address')
                        nick_name = forms_data.get('nick_name')
                        comments_content = forms_data.get('comments_content')
                        response.code = 200



                        rule_not_message_flag = True # 是否创建
                        rule_not_message = ['通知消息', '已被删除', '违规', '收藏', '新增关注', '评记']
                        for i in rule_not_message:
                            if i in comments_content:
                                rule_not_message_flag = False
                                break
                        article_notes_id = forms_data.get('article_notes_id')
                        if rule_not_message_flag and article_picture_address: # 如果没有截图不记录
                            objs = models.littleRedBookReviewForm.objects.filter(
                                        xhs_user_id=xhs_user_id,
                                        nick_name=nick_name,
                                        comments_content=comments_content
                                    )
                            print("**forms_obj.cleaned_data -->", forms_obj.cleaned_data)

                            if not objs and forms_data.get('comments_content') != "该评论已被删除":
                                obj = models.littleRedBookReviewForm.objects.create(**forms_obj.cleaned_data)
                                # 异步传递给小红书后台
                                form_data['link'] = forms_data.get('screenshots_address')
                                form_data['name'] = forms_data.get('nick_name')
                                form_data['content'] = forms_data.get('comments_content')
                                form_data['head_portrait'] = forms_data.get('head_portrait')
                                form_data['comment_id'] = obj.id
                                form_data['id'] = article_notes_id
                                form_data['transfer_type'] = 1  # 传递到小红书后台
                                form_data['platform'] = obj.xhs_user.platform
                                asynchronous_transfer_data.delay(form_data)
                                response.msg = '创建成功'
                        else:
                            response.msg = '通知消息, 未收录'


                    else:
                        response.code = 301
                        response.msg = json.loads(forms_obj.errors.as_json())

            create_xhs_admin_response(request, response, 3) # 创建请求日志(手机)

        # 创建回复评论 小红书后台添加接口   (博主回复内容)④
        elif oper_type == 'reply_comment':
            form_data = {
                'comment_id': request.POST.get('comment_id'),               # 回复哪个评论ID
                'comment_type': request.POST.get('comment_type'),           # (回复评论类型 1回复评论 2 回复私信)
                'comment_response': request.POST.get('comment_response'),   # 回复评论内容
            }

            forms_obj = ReplyCommentForm(form_data)
            if forms_obj.is_valid():
                comment_type = forms_obj.cleaned_data.get('comment_type')

                is_perform = True
                # if comment_type in [2, '2']:
                #     is_perform = False

                data = {
                    'comment_id': forms_obj.cleaned_data.get('comment_id'),
                    'comment_response': forms_obj.cleaned_data.get('comment_response'),
                    'comment_type': comment_type,
                    'is_perform': is_perform,
                }
                print(data)
                obj = models.commentResponseForm.objects.create(**data)
                response.code = 200
                response.msg = '创建成功'
                response.data = obj.id

            else:
                response.code = 301
                response.msg = json.loads(forms_obj.errors.as_json())
            create_xhs_admin_response(request, response, 2) # 创建请求日志(小红书后台请求后台)

        # 刪除评论(小红书请求)
        elif oper_type == 'delete_comment':
            form_data = {
                'comment_id': request.POST.get('comment_id'),  # 删除哪个评论ID
            }
            form_obj = DeleteComment(form_data)
            if form_obj.is_valid():
                comment_id, objs = form_obj.cleaned_data.get('comment_id')
                delete = 2
                if objs[0].comments_content in ['该评论已被删除', '该评论违规']:
                    models.commentResponseForm.objects.filter(comment=objs).delete()
                    delete = 3
                    msg = '删除成功'
                    code = 0

                else:
                    code = 200
                    msg = '操作成功, 等待删除...'

                objs.update(delete=delete)
                response.code = code
                response.msg = msg

            else:
                response.code = 301
                response.msg = json.loads(form_obj.errors.as_json())
            create_xhs_admin_response(request, response, 2) # 创建请求日志(小红书后台请求后台)

        # 手机端 删除评论是否完成
        elif oper_type == 'reply_comment_is_delete':
            id = request.POST.get('comment_id')      # 删除的消息ID
            objs = models.littleRedBookReviewForm.objects.filter(
                id=id
            )
            if objs:
                models.commentResponseForm.objects.filter(comment_id=id).delete()
                objs.update(
                    delete=3
                )
                data = {
                    'transfer_type': 4,
                    'id': id
                }
                asynchronous_transfer_data.delay(data)
                create_xhs_admin_response(request, response, 3)  # 创建请求日志(手机端)
            response.code = 200
            response.msg = '操作完成'

        # 手机端 通知回复消息完成时间⑥
        elif oper_type == 'reply_comment_is_success':
            now = datetime.datetime.today()
            form_data = {
                'id': request.POST.get('comment_id'),  # 回复的消息ID
                'comment_completion_time': request.POST.get('comment_completion_time', now),  # 完成时间
            }

            form_objs = ReplyCommentIsSuccess(form_data)
            if form_objs.is_valid():
                comment_id = form_objs.cleaned_data.get('id')
                comment_completion_time = form_objs.cleaned_data.get('comment_completion_time')

                objs = models.commentResponseForm.objects.filter(id=comment_id)
                objs.update(
                    comment_completion_time=comment_completion_time
                )
                response.code = 200
                response.msg = '成功'

                # 异步传递给小红书后台
                form_data['transfer_type'] = 2
                form_data['platform'] = objs[0].comment.xhs_user.platform
                asynchronous_transfer_data.delay(form_data)

            else:
                response.code = 301
                response.msg = json.loads(form_objs.errors.as_json())
            create_xhs_admin_response(request, response, 3)  # 创建请求日志(手机端)

        # 关联 笔记链接 和 文章截图②
        elif oper_type == 'associated_screenshots':
            form_data = {
                'notes_url': request.POST.get('notes_url'),  # 笔记回链
                'screenshots': request.POST.get('screenshots')  # 文章截图
            }
            print('form_data-----------> ', form_data)
            code = 301
            form_obj = AssociatedScreenshots(form_data)
            if form_obj.is_valid():
                forms_data = form_obj.cleaned_data
                screenshots = forms_data.get('screenshots')
                screenshots = screenshots.split('?')[0]
                notes_url, biji_id = forms_data.get('notes_url')

                objs = models.noteAssociationScreenshot.objects.filter(
                    screenshots=screenshots,
                    notes_id=biji_id
                )
                if not objs:

                    models.noteAssociationScreenshot.objects.create(
                        screenshots=screenshots,
                        notes_id=biji_id
                    )

                    code = 200
                    msg = '关联成功'
                    response.data = biji_id
                else:
                    code = 200
                    msg = '重复关联'
                    response.data = biji_id

            else:
                iccid = request.POST.get('iccid')
                imsi = request.POST.get('imsi')
                phone_objs = models.XiaohongshuPhone.objects.filter(iccid=iccid, imsi=imsi)
                device_number = '设备不存在, iccid:{}, imsi:{}'.format(iccid, imsi)
                if phone_objs:
                    device_number = phone_objs[0].name
                content = '{datetime}关联笔记截图异常, \n设备号:{device_number}, \n笔记回链:{notes_url}'.format(
                    datetime=datetime.datetime.today(),
                    device_number=device_number,
                    notes_url=form_data.get('notes_url')
                )
                send_error_msg(content, 2)
                msg = json.loads(form_obj.errors.as_json())

            response.code = code
            response.msg = msg
            create_xhs_admin_response(request, response, 3)  # 创建请求日志(手机端)

        # 修改 回复(管理/私信) 是否开放
        elif oper_type == 'whether_the_modification_open':
            comment_id = request.POST.get('comment_id')
            objs = models.commentResponseForm.objects.filter(id=comment_id)
            if objs:
                obj = objs[0]
                obj.is_perform = bool(1-obj.is_perform)
                obj.save()
                response.code = 200
                response.msg = '修改成功'

            else:
                response.code = 301
                response.msg = '修改的任务不存在'



        # 回复评论管理 发布异常(手机)
        elif oper_type == 'comment_management_changed_publish_exceptions':
            comment_id = request.POST.get('comment_id')
            objs = models.commentResponseForm.objects.filter(
                id=comment_id,
                comment_completion_time__isnull=True
            )
            if objs:
                objs.update(
                    is_error=True,
                    comment_completion_time=datetime.datetime.today()
                )
                response.code = 200
                response.msg = '发布异常成功'
            else:
                response.code = 301
                response.msg = '该任务不存在或已发布'

        # 回复评论管理 发布正常(后台)
        elif oper_type == 'reply_comment_management_release_normal':
            comment_id = request.POST.get('comment_id')
            objs = models.commentResponseForm.objects.filter(id=comment_id)
            if objs:
                objs.update(
                    is_error=False,
                    comment_completion_time=None,
                )
                response.code = 200
                response.msg = '重新发布成功'

            else:
                response.code = 301
                response.msg = '该任务不存在'

        # 评论改为删除异常 (手机)
        elif oper_type == 'comment_post_exception_instead':
            comment_id = request.POST.get('comment_id')
            objs = models.littleRedBookReviewForm.objects.filter(id=comment_id)
            if objs and objs[0].is_error == False:
                objs.update(is_error=True)
                response.code = 200
                response.msg = '删除异常成功'

            else:
                if objs:
                    response.msg = '该评论不存在'
                else:
                    response.msg = '该评论已经为删除异常'
                response.code = 301


        """当 手机找不到 评论 和 回复评论 时 改为发布异常"""

    else:

        order = request.GET.get('order', '-create_datetime')

        # 查询 截图和 笔记是否关联①
        if oper_type == 'determine_correlation':

            flag = False
            iccid = request.GET.get('iccid')
            imsi = request.GET.get('imsi')
            screenshots = request.GET.get('screenshots') # 文章截图
            # notes_url = request.GET.get('notes_url') # 笔记回链
            biji_id = ''
            if screenshots:
                objs = models.noteAssociationScreenshot.objects.filter(
                    screenshots=screenshots,
                    notes__user_id__phone_id__iccid=iccid,
                    notes__user_id__phone_id__imsi=imsi,
                )
                if objs:
                    obj = objs[0]
                    biji_id = obj.notes_id
                    flag = True

                response.code = 200
                response.msg = '查询完成'
                response.data = {
                    'flag': flag,
                    'biji_id': biji_id
                }

            else:
                response.code = 301
                response.msg = '参数异常'
            create_xhs_admin_response(request, response, 3)  # 创建请求日志(手机端)

        # 查询回复任务(手机)⑤
        elif oper_type == 'query_reply_task':
            form_data = {
                'imsi': request.GET.get('imsi'),
                'iccid': request.GET.get('iccid'),
                'platform': request.GET.get('platform', 1),
            }
            form_obj = QueryReplyTask(form_data)
            if form_obj.is_valid():
                iccid = form_obj.cleaned_data.get('iccid')
                platform = form_obj.cleaned_data.get('platform')

                objs = models.commentResponseForm.objects.select_related('comment').filter(
                    comment__xhs_user__phone_id_id=iccid,
                    comment_completion_time__isnull=True,
                    comment__isnull=False,
                    comment_response__isnull=False,
                    is_perform=True,
                    is_error=False,
                    comment__xhs_user__platform=platform
                ).order_by('create_datetime')

                if objs:
                    obj = objs[0]
                    comment_response = obj.comment_response

                    ret_data = {
                        'comment_type': obj.comment_type,
                        'comments_content': obj.comment.comments_content,
                        'nick_name': obj.comment.nick_name,
                        'article_picture_address': obj.comment.article_picture_address,
                        'screenshots_address': obj.comment.screenshots_address,
                        'id': obj.id,
                        'platform': obj.comment.xhs_user.platform,
                        'comment_response': comment_response,
                        'create_datetime': obj.create_datetime.strftime('%Y-%m-%d %H:%M:%S'),
                    }

                    response.msg = '查询成功'
                    response.data = ret_data
                    response.note = {
                        'id': '回复评论ID',
                        'comment_response': '回复评论内容',
                        'create_datetime': '创建时间',
                        'screenshots_address': '文章截图',
                        'nick_name': '昵称',
                        'comments_content': '评论内容',
                        'comment_type': '评论类型 1为回复评论 2为回复私信',
                    }

                else:
                    response.msg = '无任务'

                response.code = 200
            else:
                response.code = 301
                response.msg = json.loads(form_obj.errors.as_json())
            create_xhs_admin_response(request, response, 3)  # 创建请求日志(手机端)

        # 查询删除评论任务(手机)
        elif oper_type == 'query_delete_comment':
            form_data = {
                'imsi': request.GET.get('imsi'),
                'iccid': request.GET.get('iccid'),
                'platform': request.GET.get('platform'),
            }
            form_obj = QueryDeleteComment(form_data)
            if form_obj.is_valid():
                iccid = form_obj.cleaned_data.get('iccid')
                platform = form_obj.cleaned_data.get('platform')

                objs = models.littleRedBookReviewForm.objects.filter(
                    xhs_user__phone_id_id=iccid,
                    delete=2,
                    is_error=False,
                    xhs_user__platform=platform
                )
                data = {}
                if objs:
                    obj = objs[0]
                    data = {
                        'id': obj.id,
                        'comments_content':obj.comments_content,
                        'screenshots_address':obj.screenshots_address,
                        'phone_name':obj.xhs_user.phone_id.name,
                        'user_name':obj.nick_name,
                        'platform':obj.xhs_user.platform,
                    }

                else:
                    response.msg = '无任务'
                response.code = 200
                response.data = data
                response.note = {
                    'id': '删除评论ID',
                    'comments_content': '删除评论',
                    'screenshots_address': '截图',
                    'phone_name': '设备名称',
                    'user_name': '小红书博主名称',
                }

            else:
                response.code = 301
                response.msg = json.loads(form_obj.errors.as_json())
            create_xhs_admin_response(request, response, 3)  # 创建请求日志(手机端)

        # 查询评论(胡蓉后台)
        elif oper_type == 'query_comments':
            forms_obj = SelectForm(request.GET)
            if forms_obj.is_valid():
                current_page = forms_obj.cleaned_data['current_page']
                length = forms_obj.cleaned_data['length']
                field_dict = {
                    'id': '',
                    'comments_status': '',
                    'xhs_user_id': '',
                    'xhs_user__phone_id__name': '__contains',
                    'delete': '',
                    'xhs_user__name': '__contains',
                    'comments_content': '__contains',
                    'article_notes__isnull': '',
                }

                q = conditionCom(request, field_dict)

                objs = models.littleRedBookReviewForm.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:
                    article_notes_title = ''
                    article_notes_id = ''
                    if obj.article_notes:
                        article_notes_id = obj.article_notes_id
                        article_notes_title = b64decode(obj.article_notes.title)

                    ret_data.append({
                        'id': obj.id,
                        'phone_name': obj.xhs_user.phone_id.name,
                        'phone_id': obj.xhs_user.phone_id_id,
                        'phone_number': obj.xhs_user.phone_id.phone_num,
                        'xhs_user_id': obj.xhs_user_id,
                        'xhs_user_name': obj.xhs_user.name,
                        'head_portrait': obj.head_portrait,
                        'screenshots_address': obj.screenshots_address,
                        'nick_name': obj.nick_name,
                        'comments_status_id': obj.comments_status,
                        'comments_status': obj.get_comments_status_display(),
                        'comments_content': obj.comments_content,
                        'article_picture_address': obj.article_picture_address,
                        'delete_id': obj.delete,
                        'delete': obj.get_delete_display(),
                        'article_notes_id': article_notes_id,
                        'article_notes_title': article_notes_title,
                        'create_datetime': obj.create_datetime.strftime('%Y-%m-%d %H:%M:%S'),
                    })
                response.note = {
                    'xhs_user_id': '小红书用户ID',
                    'xhs_user_name': '小红书用户名称',
                    'head_portrait': '头像',
                    'nick_name': '昵称',
                    'comments_status_id': '评论类型ID',
                    'screenshots_address': '截图地址',
                    'comments_status': '评论类型',
                    'comments_content': '评论内容',
                    'article_picture_address': '文章图片地址',
                    'article_notes_id': '笔记ID',
                    'create_datetime': '创建时间',
                }
                response.code = 200
                response.msg = '查询成功'
                response.data = {
                    'ret_data':ret_data,
                    'count':count,
                    'comments_choices': [{'id':i[0], 'name':i[1]} for i in models.littleRedBookReviewForm.comments_choices],
                    'delete_choices': [{'id':i[0], 'name':i[1]} for i in models.littleRedBookReviewForm.delete_choices],
                }

            else:
                response.code = 301
                response.msg = json.loads(forms_obj.errors.as_json())

        # 查询回复评论(胡蓉后台)
        elif oper_type == 'query_reply_comment':
            forms_obj = SelectForm(request.GET)
            if forms_obj.is_valid():
                current_page = forms_obj.cleaned_data['current_page']
                length = forms_obj.cleaned_data['length']
                field_dict = {
                    'id': '',
                    'comment_id': '',
                    'comment_type': '',
                    'comment_response': '',
                    'comment_completion_time': '__isnull',
                    'comment__xhs_user__name': '__contains',
                    'comment__xhs_user__phone_id__name': '__contains',
                }

                q = conditionCom(request, field_dict)
                objs = models.commentResponseForm.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:
                    comment_completion_time = obj.comment_completion_time
                    if comment_completion_time:
                        comment_completion_time = obj.comment_completion_time.strftime('%Y-%m-%d %H:%M:%S')

                    phone_id = ''
                    phone_name = ''
                    phone_number = ''
                    if obj.comment.xhs_user.phone_id:
                        phone_id = obj.comment.xhs_user.phone_id_id
                        phone_name = obj.comment.xhs_user.phone_id.name
                        phone_number = obj.comment.xhs_user.phone_id.phone_num

                    try:
                        comment_response =  str(base64.b64decode(obj.comment_response), 'utf8')
                    except Exception:
                        comment_response = obj.comment_response

                    ret_data.append({
                        'id': obj.id,
                        'phone_id': phone_id,
                        'phone_name': phone_name,
                        'phone_number': phone_number,
                        'xhs_user_name': obj.comment.xhs_user.name,
                        'nick_name': obj.comment.nick_name,
                        'head_portrait': obj.comment.head_portrait,
                        'comments_content': obj.comment.comments_content,
                        'comment_id': obj.comment_id,
                        'comment_response':comment_response,
                        'comment_type_id':obj.comment_type,
                        'comment_type':obj.get_comment_type_display(),
                        'is_perform':obj.is_perform,
                        'is_error':obj.is_error,
                        'comment_completion_time': comment_completion_time,
                        '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,
                    'comment_type_choices': [{'id':i[0], 'name':i[1]} for i in models.commentResponseForm.comment_type_choices]
                }

        # 查询评论最后一次更新时间
        elif oper_type == 'query_when_comments_were_last_updated':
            form_data = {
                'iccid':request.GET.get('iccid'),
                'imsi': request.GET.get('imsi')
            }
            objs = models.XiaohongshuPhone.objects.filter(**form_data)
            if objs:
                obj = objs[0]
                comment_last_updated = obj.comment_last_updated
                deletionTime = (datetime.datetime.today() - datetime.timedelta(hours=12))  # 当前时间减去12小时
                more_than_12_hours = False
                if comment_last_updated:
                    comment_last_updated = comment_last_updated.strftime('%Y-%m-%d %H:%M:%S')
                    if deletionTime > obj.comment_last_updated:
                        more_than_12_hours = True
                else:
                    more_than_12_hours = True

                response.data = {
                    'comment_last_updated': comment_last_updated,
                    'more_than_12_hours': more_than_12_hours,
                }
                response.note = {
                    'comment_last_updated': '最后一次提交评论时间',
                    'more_than_12_hours': '最后一次提交评论时间 是否超过12小时 True已超过 False未超过',
                }
            response.code = 200

        # 手动关联评论/笔记 (胡蓉后台)
        elif oper_type == 'manually_associate_comments_notes':
            article_notes_id = request.GET.get('article_notes_id')
            comment_id = request.GET.get('comment_id')
            code = 301

            objs = models.littleRedBookReviewForm.objects.filter(id=comment_id)
            if objs:
                if not models.XiaohongshuBiji.objects.filter(id=article_notes_id):
                    msg = '笔记不存在'

                else:
                    objs.update(article_notes_id=article_notes_id)
                    code = 200
                    msg = '修改成功'
                    form_data = {
                        'transfer_type': 7,
                        'id': article_notes_id,
                        'comment_id': comment_id,
                    }
                    asynchronous_transfer_data.delay(form_data)

            else:
                msg = '评论不存在'

            response.code = code
            response.msg = msg

        else:
            response.code = 402
            response.msg = '请求异常'

    return JsonResponse(response.__dict__)
Exemple #5
0
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 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__)