Ejemplo n.º 1
0
def celery_get_phone_content(request):
    try:
        phone_management_objs = phone_management()
        data_list = phone_management_objs.get_all_information_day()

        for data in data_list:
            serial_number = data.get('serial_number')  # 流水号
            content = data.get('content')  # 信息
            date_time = data.get('date_time')  # 接收信息时间
            phone_number = data.get('phone_number')  # 接收信息手机号

            objs = models.text_messages_received_cell_phone_number.objects.filter(
                serial_number=serial_number, )
            if not objs:
                phone_objs = models.PhoneNumber.objects.filter(
                    phone_num=phone_number)
                if phone_objs:
                    phone_obj = phone_objs[0]
                    models.text_messages_received_cell_phone_number.objects.create(
                        serial_number=serial_number,
                        phone_id=phone_obj.id,
                        message_content=content,
                        receiving_time=date_time,
                    )
    except Exception as e:
        content = '{} \n 获取 手机号短信报错\n错误:{}'.format(datetime.datetime.today(),
                                                   e)
        send_error_msg(content, 5)

    return HttpResponse('')
Ejemplo n.º 2
0
def error_asynchronous_transfer_data(request):
    objs = models.littleRedBookReviewForm.objects.filter(status=1)
    for obj in objs:
        try:
            data = {
                'xhs_user_id': obj.xhs_user_id,  # 小红书用户
                'comments_status': obj.comments_status,  # 评论类型
                'article_picture_address':
                obj.article_picture_address,  # 文章图片地址
                'link': obj.screenshots_address,
                'name': obj.nick_name,
                'content': obj.comments_content,
                'head_portrait': obj.head_portrait,
                'comment_id': obj.id,
            }

            url = 'https://a.ppxhs.com/api/v1/sync/sync-comment'
            ret = requests.post(url, data=data)
            models.AskLittleRedBook.objects.create(  # 创建日志
                request_url=url,
                get_request_parameter='',
                post_request_parameter=data,
                response_data=ret.json(),
                request_type=2,
                status=1,
            )

            obj.status = 2
            obj.save()
        except Exception as e:
            content = '{} \n 异步上传手机抓取的评论报错\n错误:{}'.format(
                datetime.datetime.today(), e)
            send_error_msg(content, 5)

    return HttpResponse('')
Ejemplo n.º 3
0
def xiaohongshu_phone_monitor():
    # hour_now = datetime.datetime.now().strftime("%H")  # 当前的时间
    # if 7 < int(hour_now) < 21:  # 只在 8:00 - 21:00 运行
    err_phone = []
    # expire_date = (datetime.datetime.now() - datetime.timedelta(minutes=5)).strftime("%Y-%m-%d %H:%M:%S")
    expire_date = (datetime.datetime.now() - datetime.timedelta(minutes=5))
    phone_objs = models.XiaohongshuPhone.objects.filter(is_debug=False)
    for phone_obj in phone_objs:

        # # 如果5分钟之内没有提交日志,说明机器异常了
        # objs = phone_obj.xiaohongshuphonelog_set.filter(create_datetime__gt=expire_date)
        if phone_obj.last_sign_in_time and phone_obj.last_sign_in_time < expire_date:
            phone_obj.status = 2
            seconds = (expire_date - phone_obj.last_sign_in_time).seconds

            name = phone_obj.name
            if seconds > 60 * 60 * 2:
                name = name + " 异常超过2小时"
            elif seconds > 60 * 60 * 1:
                name = name + " 异常超过1小时"
            else:
                name = name + " 异常%s分钟" % (int(seconds / 60))

            err_phone.append(name)
        else:
            phone_obj.status = 1
        phone_obj.save()
        # print("err_phone -->", err_phone)

    if len(err_phone) > 0:
        content = """{time} \n 小红书机器异常{phone}台,请及时处理:  \n{phone_names}""".format(
            phone_names="\n".join(err_phone),
            phone=len(err_phone),
            time=datetime.datetime.today())
        send_error_msg(content)  # 发送异常
Ejemplo n.º 4
0
def xiaohongshu_userprofile_register_monitor():
    hour_now = datetime.datetime.now().strftime("%H")  # 当前的时间
    # if 7 < int(hour_now) < 21:  # 只在 8:00 - 21:00 运行
    from hurong import models
    objs = models.XiaohongshuUserProfileRegister.objects.filter(
        is_register=False)
    if objs:
        content = """{} \n小红书有新的账号需要注册,请及时处理""".format(
            datetime.datetime.today())
        send_error_msg(content, 3)
Ejemplo n.º 5
0
def celery_task_toomuch_alarm():
    redis_obj = redis.StrictRedis(host='redis',
                                  port=6379,
                                  db=15,
                                  decode_responses=True)
    celery_task_num = redis_obj.llen('celery')
    if celery_task_num:
        celery_task_num = int(celery_task_num)
        if celery_task_num >= 1000:
            send_error_msg('celery任务大于1000条 请及时处理 {}'.format(celery_task_num),
                           5)
Ejemplo n.º 6
0
def determine_phone_number_ownership(request):
    try:
        phone_management_objs = phone_management()
        phone_num_list = phone_management_objs.get_all_phone_num()
        models.XiaohongshuPhone.objects.filter(
            phone_num__in=phone_num_list).update(phone_num_attribution=1)

    except Exception as e:
        content = '{}查询手机号平台异常, 错误{}'.format(datetime.datetime.today(), e)
        send_error_msg(content, 5)

    return HttpResponse('')
Ejemplo n.º 7
0
def xiaohongshu_biji_monitor():
    hour_now = datetime.datetime.now().strftime("%H")  # 当前的时间
    # if 7 < int(hour_now) < 21:  # 只在 8:00 - 21:00 运行
    from hurong import models
    # user_id_id = 5 是测试账号
    # objs = models.XiaohongshuBiji.objects.exclude(status=2).exclude(user_id_id=5)
    objs = models.XiaohongshuBiji.objects.filter(status=3).exclude(
        user_id_id=5)
    if objs:
        content = """{} \n 小红书有新的笔记需要发布,请及时处理""".format(
            datetime.datetime.today())
        send_error_msg(content, 3)
Ejemplo n.º 8
0
def delete_phone_log(request):
    try:
        now_date = datetime.date.today()
        models.XiaohongshuPhoneLog.objects.filter(
            create_datetime__lt=(now_date -
                                 datetime.timedelta(days=2))).delete()
        models.AskLittleRedBook.objects.filter(
            create_datetime__lt=now_date).delete()
        models.MobileEquipmentAbnormalSendMessageEnterpriseRecord.objects.filter(
            create_datetime__lt=(now_date -
                                 datetime.timedelta(days=2))).delete()
    except Exception as e:
        content = '{} \n 定期删除 设备日志报错\n错误:{}'.format(datetime.datetime.today(),
                                                    e)
        send_error_msg(content, 5)
    return HttpResponse('')
Ejemplo n.º 9
0
def get_traffic_information(request):
    try:
        id = request.GET.get('id')
        q = Q()
        if id:
            q.add(Q(id=id), Q.AND)
        q.add(
            Q(select_datetime__lt=datetime.datetime.today())
            | Q(select_datetime__isnull=True), Q.AND)

        objs = models.MobileTrafficInformation.objects.filter(
            q, select_number__isnull=False)
        for obj in objs:
            ret_json = get_phone_info(obj.select_number)
            if ret_json.get('code') != 0:
                obj.errmsg = ret_json.get('msg')
                obj.save()

            else:
                cardbaldata = ret_json.get('cardbaldata')
                cardimsi = ret_json.get('cardimsi').strip()
                cardstatus = ret_json.get('cardstatus')

                phone_objs = models.XiaohongshuPhone.objects.filter(
                    imsi=cardimsi)
                if phone_objs:
                    phone_obj = phone_objs[0]
                    obj.phone_id = phone_obj.id  # 外键到手机

                obj.cardbaldata = cardbaldata  # 剩余流量
                obj.cardenddate = ret_json.get('cardenddate')  # 卡到期时间
                obj.cardimsi = cardimsi  # ismi号
                obj.cardno = ret_json.get('cardno')  # 卡编号
                obj.cardnumber = ret_json.get('cardnumber')  # 卡号
                obj.cardstatus = cardstatus  # 用户状态
                obj.cardstartdate = ret_json.get('cardstartdate')  # 卡开户时间
                obj.cardtype = ret_json.get('cardtype')  # 套餐类型
                obj.cardusedata = ret_json.get('cardusedata')  # 已用流量
                obj.errmsg = ''
                obj.save()

                flag = False
                if cardstatus != '已停用':
                    flag = True

                if flag and cardbaldata and float(cardbaldata) <= 500:
                    content = '{} \n 流量低于五百兆提醒, 查询号码:{}, 剩余流量:{}, ISMI号:{}'.format(
                        datetime.datetime.today(), obj.select_number,
                        cardbaldata, cardimsi)
                    send_error_msg(content, 5)

                if flag:  # 查询 充值情况
                    info_json = query_device_recharge_information(
                        obj.select_number)
                    if info_json.get('data_list'):
                        for i in info_json.get('data_list'):
                            info_objs = models.MobilePhoneRechargeInformation.objects.filter(
                                equipment_package=i.get('pkName'),
                                prepaid_phone_time=i.get('payTime'),
                                equipment_id=obj.id,
                            )
                            if not info_objs:
                                models.MobilePhoneRechargeInformation.objects.create(
                                    equipment_package=i.get('pkName'),
                                    prepaid_phone_time=i.get('payTime'),
                                    equipment_id=obj.id,
                                )

            obj.select_datetime = datetime.datetime.today()
            obj.save()

    except Exception as e:
        content = '{} \n 查询 流量信息报错\n错误:{}'.format(datetime.datetime.today(), e)
        send_error_msg(content, 5)
    return HttpResponse('')
Ejemplo n.º 10
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('')
Ejemplo n.º 11
0
def unused_cell_phone_number_below_alarms():
    count = models.PhoneNumber.objects.filter(status=1).count()
    if int(count) < 200:
        content = '{}\n 手机号未使用的剩余{}个'.format(datetime.datetime.today(), count)
        send_error_msg(content, 4)
Ejemplo n.º 12
0
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__)
Ejemplo n.º 13
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__)