Ejemplo n.º 1
0
 def clean_content(self):
     content_objs = self.data.get('content')
     content = json.loads(content_objs)
     biji_type = 1
     try:
         if content.get('type') and content.get('type') != 'images':
             biji_type = 2
     except Exception:
         pass
     title = content.get('title')
     return b64encode(title), content_objs, biji_type
Ejemplo n.º 2
0
def xcx_login(request):
    response = Response.ResponseObj()
    if request.method == "POST":
        js_code = request.POST.get('js_code')
        appid = request.POST.get('appid')
        userInfo = request.POST.get('userInfo')  # 客户信息
        print('userInfo, type(userInfo)------> ', userInfo, type(userInfo))
        userInfo = json.loads(userInfo)
        tripartite_platform_objs = tripartite_platform()  # 实例化三方平台
        ret_data = tripartite_platform_objs.get_customer_openid(
            appid, js_code)  # 获取客户openid
        openid = ret_data.get('openid')
        session_key = ret_data.get('session_key')  # 用于加密
        objs = models.Customer.objects.filter(openid=openid)
        nickName = base64_encryption.b64encode(userInfo.get('nickName'))

        if objs:
            objs.update(
                **{
                    'head_portrait': userInfo.get('avatarUrl'),
                    'sex': userInfo.get('gender'),
                    'country': userInfo.get('country'),
                    'province': userInfo.get('province'),
                    'city': userInfo.get('city'),
                    'name': nickName,
                    'session_key': session_key,
                })
            obj = objs[0]

        else:
            token = account.get_token(account.str_encrypt(openid))
            obj = models.Customer.objects.create(
                **{
                    'head_portrait': userInfo.get('avatarUrl'),
                    'sex': userInfo.get('gender'),
                    'country': userInfo.get('country'),
                    'province': userInfo.get('province'),
                    'city': userInfo.get('city'),
                    'session_key': session_key,
                    'name': nickName,
                    'openid': openid,
                    'token': token,
                })
        response.code = 200
        response.msg = '登录成功'
        response.data = {
            'user_id': obj.id,
            'token': obj.token,
        }

    return JsonResponse(response.__dict__)
Ejemplo n.º 3
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__)
Ejemplo n.º 4
0
def team_oper(request, oper_type, o_id):
    # print('oper_type -->', oper_type)
    response = Response.ResponseObj()
    user_id = request.GET.get('user_id')
    if request.method == "POST":
        # 添加团队
        if oper_type == "add":
            form_data = {
                'create_user_id': user_id,
                'name': request.POST.get('name'),
            }
            #  创建 form验证 实例(参数默认转成字典)
            forms_obj = AddForm(form_data)
            if forms_obj.is_valid():
                print("验证通过")
                # print(forms_obj.cleaned_data)
                #  添加数据库
                # print('forms_obj.cleaned_data-->',forms_obj.cleaned_data)
                obj = models.Team.objects.create(**forms_obj.cleaned_data)
                obj.userprofileteam_set.create(user_id=user_id,
                                               team_id=obj.id,
                                               type=2)
                response.code = 200
                response.msg = "添加成功"
                response.data = {'id': obj.id}
            else:
                response.code = 301
                response.msg = json.loads(forms_obj.errors.as_json())

        # 修改团队名称
        elif oper_type == "update":
            # 获取需要修改的信息
            form_data = {
                'o_id': o_id,  # 团队id
                'user_id': user_id,
                'name': request.POST.get('name'),
            }

            forms_obj = UpdateForm(form_data)
            if forms_obj.is_valid():
                # print("验证通过")
                # print(forms_obj.cleaned_data)
                o_id = forms_obj.cleaned_data['o_id']
                name = forms_obj.cleaned_data['name']

                #  查询更新 数据
                models.Team.objects.filter(id=o_id).update(name=name, )

                response.code = 200
                response.msg = "修改成功"

            else:
                print("验证不通过")
                # print(forms_obj.errors)
                response.code = 301
                # print(forms_obj.errors.as_json())
                #  字符串转换 json 字符串
                response.msg = json.loads(forms_obj.errors.as_json())

        # 删除团队成员
        elif oper_type == "delete_member":
            delete_user_id = request.POST.get('delete_user_id')  # 要移除的成员id
            form_data = {
                'o_id': o_id,  # 团队id
                'user_id': user_id,
                'delete_user_id': delete_user_id,
            }

            forms_obj = DeleteMemberForm(form_data)
            if forms_obj.is_valid():
                # print("验证通过")
                # print(forms_obj.cleaned_data)
                team_id = forms_obj.cleaned_data['o_id']
                delete_user_id_list = forms_obj.cleaned_data['delete_user_id']
                print('team_id -->', team_id)
                print('delete_user_id -->', delete_user_id)
                # 删除团队中的成员
                models.UserprofileTeam.objects.filter(
                    team_id=team_id, type=1,
                    user_id__in=delete_user_id_list).delete()

                response.code = 200
                response.msg = "删除成功"

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

        # 设置普通成员成为管理员
        elif oper_type == "set_management":
            print('request.POST -->', request.POST)
            print('request.GET -->', request.GET)
            set_user_id = request.POST.get('set_user_id')
            print('set_user_id -->', set_user_id)
            form_data = {
                'o_id': o_id,  # 团队id
                'user_id': user_id,
                'set_user_id': set_user_id,
            }

            forms_obj = SetManagementForm(form_data)
            if forms_obj.is_valid():
                set_user_id_list = forms_obj.cleaned_data.get('set_user_id')
                team_id = forms_obj.cleaned_data.get('o_id')

                # 先将所有成员改成普通用户
                models.UserprofileTeam.objects.filter(team_id=team_id).update(
                    type=1)

                # 修改成员类型为管理员
                models.UserprofileTeam.objects.filter(
                    team_id=team_id,
                    user_id__in=set_user_id_list).update(type=2)

                response.code = 200
                response.msg = "修改成功"
            else:
                response.code = 301
                response.data = json.loads(forms_obj.errors.as_json())

        # 删除团队
        elif oper_type == 'delete':
            member_objs = models.UserprofileTeam.objects.filter(team_id=o_id)
            user_id_list = [
                i.get('user_id')
                for i in member_objs.filter(type=2).values('user_id')
            ]
            user_list = [
                i.get('user_id')
                for i in member_objs.filter(type=1).values('user_id')
            ]  # 普通用户
            if int(user_id) in user_id_list:  # 该团队管理员列表
                models.Article.objects.filter(ownership_team_id=o_id).update(
                    ownership_team_id=None)
                member_objs.delete()
                models.Team.objects.filter(id=o_id).delete()
                response.code = 200
                response.msg = '删除团队成功'
            else:
                if int(user_id) in user_list:
                    member_objs.filter(user_id=user_id).delete()
                    response.code = 200
                    response.msg = '退出团队成功'
                else:
                    response.code = 301
                    response.msg = '权限不足'

    else:
        # 查看团队人员列表
        if oper_type == "select_user_list":
            form_data = {
                'team_id': o_id,
                'current_page': request.GET.get('current_page', 1),
                'length': request.GET.get('length', 10),
            }
            forms_obj = SelectUserListForm(form_data)
            if forms_obj.is_valid():
                print('forms_obj.cleaned_data -->', forms_obj.cleaned_data)
                current_page = forms_obj.cleaned_data['current_page']
                length = forms_obj.cleaned_data['length']
                team_id = forms_obj.cleaned_data['team_id']
                order = request.GET.get('order', 'create_datetime')
                field_dict = {
                    'id': '',
                    'type': '',
                    # 'user__name': '__contains',
                    'create_datetime': '',
                }
                q = conditionCom(request, field_dict)

                print('q -->', q)
                objs = models.UserprofileTeam.objects.select_related(
                    'user').filter(q).filter(team_id=team_id).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:
                    #  将查询出来的数据 加入列表
                    print('base64_encryption.b64encode(obj.user.name) -->',
                          base64_encryption.b64encode(obj.user.name))
                    ret_data.append({
                        'id':
                        obj.user_id,
                        'user_type_name':
                        obj.get_type_display(),
                        'user_type':
                        obj.type,
                        'name':
                        base64_encryption.b64decode(obj.user.name),
                        'set_avator':
                        obj.user.set_avator,
                        'create_datetime':
                        obj.create_datetime.strftime('%Y-%m-%d %H:%M:%S'),
                    })
                #  查询成功 返回200 状态码
                response.code = 200
                response.msg = '查询成功'
                response.data = {
                    'ret_data': ret_data,
                    'data_count': count,
                }

                response.note = {
                    'id': "用户id",
                    'name': "用户名称",
                    'user_type': "用户在团队中的类型/角色id,  1 ==> 普通用户   2 ==> 管理员",
                    'user_type_name': "用户在团队中的类型/角色名称",
                    'set_avator': "用户头像",
                    'create_datetime': "用户加入时间",
                }
            else:
                response.code = 301
                response.data = json.loads(forms_obj.errors.as_json())

    return JsonResponse(response.__dict__)
Ejemplo n.º 5
0
def share_article(request, oper_type):
    code = request.GET.get('code')
    code_objs = models.save_code.objects.filter(save_code=code)
    if not code_objs:
        models.save_code.objects.create(save_code=code)
        state = request.GET.get('state')  # 分享文章的用户id
        data = get_ent_info(state)
        weichat_api_obj = weixin_gongzhonghao_api.WeChatApi(data)
        ret_obj = weichat_api_obj.get_openid(code)
        openid = ret_obj.get('openid')
        # print('ret_obj-----------> ', ret_obj)
        encode_username = b64encode(ret_obj['nickname'])
        user_data = {
            "sex": ret_obj.get('sex'),
            "country": ret_obj.get('country'),
            "province": ret_obj.get('province'),
            "city": ret_obj.get('city'),
            'name': encode_username,
            'set_avator': ret_obj.get('headimgurl')
        }
        customer_objs = models.Customer.objects.filter(openid=openid)
        if customer_objs:  # 客户已经存在
            customer_objs.update(**user_data)
            customer_obj = customer_objs[0]
        # 不存在,创建用户
        else:
            subscribe = ret_obj.get('subscribe')

            user_data['set_avator'] = ret_obj.get('headimgurl')
            # 如果没有关注,获取个人信息判断是否关注
            if not subscribe:
                ret_obj_subscribe = weichat_api_obj.get_user_info(
                    openid=openid)
                subscribe = ret_obj_subscribe.get('subscribe')

            # print('ret_objret_obj--ret_obj---> ', ret_obj)
            user_data['subscribe'] = subscribe
            user_data['name'] = encode_username
            user_data['openid'] = ret_obj.get('openid')
            user_data['token'] = get_token()
            print("user_data --->", user_data)
            customer_obj = models.Customer.objects.create(**user_data)
        objs = models.Customer.objects.filter(openid=openid)
        obj = objs[0]

        _type = oper_type
        oid = ''
        if '_' in oper_type:
            _type = oper_type.split('_')[0]  # 类型
            oid = oper_type.split('_')[1]  # ID

        # print('o_id---o_id--o_id--> ', oper_type)
        if _type == 'article':
            # 此处跳转到文章页面 文章
            redirect_url = '{host_url}#/share_article?user_id={user_id}&token={token}&id={article_id}&inviter_user_id={inviter_user_id}'.format(
                host_url=host_url,
                article_id=oid,  # 分享文章的id
                user_id=customer_obj.id,
                token=obj.token,
                inviter_user_id=state,
            )
        elif _type == 'micro':
            # 此处跳转到微店宝贝页面
            redirect_url = '{host_url}#/share_micro_store?user_id={user_id}&token={token}&id={goods_id}&inviter_user_id={inviter_user_id}'.format(
                host_url=host_url,
                goods_id=oid,  # 分享商品的id
                user_id=customer_obj.id,
                token=obj.token,
                inviter_user_id=state,
            )
        elif _type == 'card':
            # 此处跳到我的名片页面
            redirect_url = '{host_url}#/Share_Card?user_id={user_id}&token={token}&inviter_user_id={inviter_user_id}'.format(
                host_url=host_url,
                user_id=customer_obj.id,
                token=obj.token,
                inviter_user_id=state,
            )

        else:
            redirect_url = ''

        update_customer_set_avator.delay()  # 更新客户头像到七牛云
        return redirect(redirect_url)
Ejemplo n.º 6
0
def updateUserInfo(openid,
                   inviter_user_id,
                   ret_obj,
                   msg=None,
                   enterprise_id=1):  # msg访问日志记录 enterprise_id 公司ID
    """
    :param openid:  微信openid
    :param inviter_user_id: 邀请人id
    :param ret_obj:  微信数据
    :return:
    """
    print('ret_obj -->', ret_obj)
    """
        {
            'subscribe_scene': 'ADD_SCENE_QR_CODE',
            'city': '丰台',
            'openid': 'oX0xv1pJPEv1nnhswmSxr0VyolLE',
            'qr_scene': 0,
            'tagid_list': [],
            'nickname': '张聪',
            'subscribe_time': 1527689396,
            'country': '中国',
            'groupid': 0,
            'subscribe': 1,
            'qr_scene_str': '{"timestamp": "1527689369548"}',
            'headimgurl': 'http://thirdwx.qlogo.cn/mmopen/oFswpUmYn53kTv5QdmmONicVJqp3okrhHospu6icoLF7Slc5XyZWR
                            96STN9RiakoBQn1uoFJIWEicJgJ1QjR5iaGOgWNQ5BSVqFe5/132',
            'province': '北京',
            'sex': 1,
            'language': 'zh_CN',
            'remark': ''
        }


        {
            "openid":"oX0xv1pJPEv1nnhswmSxr0VyolLE",
            "nickname":"张聪",
            "sex":1,
            "language":"zh_CN",
            "city":"丰台",
            "province":"北京",
            "country":"中国",
            "headimgurl":"http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJWGnNTvluYlHj8qt8HnxMlwbRiad
                            bv4TNrp4watI2ibPPAp2Hu6Sm1BqYf6IicNWsSrUyaYjIoy2Luw/132",
            "privilege":[]
        }
    """
    # 保证1个微信只能够关联1个账号
    user_objs = models.Userprofile.objects.filter(openid=openid)

    encode_username = base64_encryption.b64encode(ret_obj['nickname'])

    path = requests_img_download(ret_obj.get('headimgurl'))
    set_avator = update_qiniu(path)

    user_data = {
        "sex": ret_obj.get('sex'),
        "country": ret_obj.get('country'),
        "province": ret_obj.get('province'),
        "city": ret_obj.get('city'),
        "headimgurl": ret_obj.get('headimgurl'),
        "wechat_name": encode_username,
        "last_active_time": datetime.datetime.today(),
        "is_send_msg": 0,
    }

    if user_objs:
        user_obj = user_objs[0]
        if int(user_obj.is_send_msg) == 1:  # 解除24小时未互动限制
            post_data = {
                "touser": user_obj.openid,
                "msgtype": "text",
                "text": {
                    "content": """限制已解除, 天眼将继续为您推送消息!{}""".format(zhayan)
                }
            }
            data = get_ent_info(user_obj.id)
            weixin_objs = WeChatApi(data)

            # 发送客服消息
            post_data = bytes(json.dumps(post_data, ensure_ascii=False),
                              encoding='utf-8')
            weixin_objs.news_service(post_data)

        user_id = user_objs[0].id
        user_objs.update(**user_data)
    else:
        # encodestr = base64.b64encode(ret_obj['nickname'].encode('utf8'))
        # encode_username = str(encodestr, encoding='utf8')
        overdue_date = datetime.datetime.now() + datetime.timedelta(days=30)

        subscribe = ret_obj.get('subscribe')
        # 如果没有关注,获取个人信息判断是否关注
        if not subscribe:
            data = get_ent_info(inviter_user_id)
            weichat_api_obj = WeChatApi(data)
            ret_obj = weichat_api_obj.get_user_info(openid=openid)
            subscribe = ret_obj.get('subscribe')

        user_data['enterprise_id'] = enterprise_id
        user_data['last_active_time'] = datetime.datetime.today()
        user_data['wechat_name'] = encode_username
        user_data['headimgurl'] = ret_obj.get('headimgurl')
        user_data['inviter_id'] = inviter_user_id
        user_data['set_avator'] = set_avator
        user_data['subscribe'] = subscribe
        user_data['name'] = encode_username
        user_data['openid'] = ret_obj.get('openid')
        user_data['overdue_date'] = overdue_date
        user_data['token'] = get_token()
        print("user_data --->", user_data)
        user_obj = models.Userprofile.objects.create(**user_data)
        user_id = user_obj.id

    pub_log_access(user_id, msg)  # 记录访问日志
    return user_id
Ejemplo n.º 7
0
def user_login_oper(request, oper_type):
    response = Response.ResponseObj()
    # 判断该用户是否存在
    now = datetime.datetime.today()
    models.save_code.objects.filter(create_datetime__lt=now).delete()

    code = request.GET.get('code')
    objs = models.save_code.objects.filter(save_code=code)
    if not objs:
        appid = oper_type.split('_')[-1]
        oper_type = oper_type.split('_' + appid)[0]

        models.save_code.objects.create(save_code=code)
        data = get_ent_info(1, appid)
        weichat_api_obj = WeChatApi(data)
        ret_obj = weichat_api_obj.get_openid(code)  # 获取用户信息
        print("ret_obj['nickname']------------> ", ret_obj['nickname'])
        try:
            encode_username = b64encode(ret_obj['nickname'])
        except Exception:
            encode_username = ''

        openid = ret_obj.get('openid')
        user_data = {
            "sex": ret_obj.get('sex'),
            "country": ret_obj.get('country'),
            "province": ret_obj.get('province'),
            "city": ret_obj.get('city'),
            "headimgurl": ret_obj.get('headimgurl'),  # 更新微信头像
            "wechat_name": encode_username,
            "last_active_time": datetime.datetime.today(),
            "is_send_msg": 0,  # 互动超时消息 互动过改为未发
        }
        user_objs = models.Userprofile.objects.filter(openid=openid)
        if user_objs:  # 客户已经存在
            user_obj = user_objs[0]
            # uf user_obj.enterprise.status == 1: # 如果后台开启
            if int(user_obj.is_send_msg) == 1:  # 解除24小时未互动限制
                post_data = {
                    "touser": user_obj.openid,
                    "msgtype": "text",
                    "text": {
                        "content": """限制已解除, 天眼将继续为您推送消息!{}""".format(zhayan)
                    }
                }
                data = get_ent_info(user_obj.id)
                weixin_objs = WeChatApi(data)

                # 发送客服消息
                post_data = bytes(json.dumps(post_data, ensure_ascii=False),
                                  encoding='utf-8')
                weixin_objs.news_service(post_data)

            user_objs.update(**user_data)
            user_objs = user_objs[0]

        else:  # 不存在,创建用户
            path = requests_img_download(ret_obj.get('headimgurl'))
            set_avator = update_qiniu(path)  # 上传至七牛云

            # # 如果没有关注,获取个人信息判断是否关注
            # if not subscribe:
            #     weichat_api_obj = WeChatApi()
            #     ret_obj = weichat_api_obj.get_user_info(openid=openid)
            #     subscribe = ret_obj.get('subscribe')

            user_data['last_active_time'] = datetime.datetime.today()
            user_data['wechat_name'] = encode_username
            user_data['set_avator'] = set_avator
            user_data['headimgurl'] = ret_obj.get('headimgurl')
            user_data['subscribe'] = True
            user_data['name'] = encode_username
            user_data['openid'] = ret_obj.get('openid')
            user_data['token'] = get_token()
            user_data['overdue_date'] = datetime.datetime.now(
            ) + datetime.timedelta(days=30)
            user_objs = models.Userprofile.objects.create(**user_data)
        user_id = user_objs.id

        pub_log_access(user_id, msg='用户点击公众号菜单栏登录')  # 记录访问日志
        redirect_url = '{host}?user_id={user_id}&token={token}&classify_type=1&page_type={page_type}'.format(
            host=host_url,
            token=user_objs.token,
            user_id=user_id,
            page_type=oper_type,
        )
        print('redirect_url----------------------------> ', redirect_url)
        return redirect(redirect_url)

    else:
        response.code = 301
        response.msg = '请重新登录'

    return JsonResponse(response.__dict__)
Ejemplo n.º 8
0
def user_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_recommend_classify":
            classify_id = request.POST.get('classify_id[]')
            if classify_id:
                recommend_classify_list = [
                    int(i) for i in json.loads(classify_id)
                ]
                print("recommend_classify_list -->", recommend_classify_list)
                user_obj = models.Userprofile.objects.get(id=user_id)
                user_obj.recommend_classify = recommend_classify_list
                response.code = 200
                response.msg = "设置成功"
            else:
                response.code = 301
                response.msg = "分类id传参异常"

        # 修改头像
        elif oper_type == "update_head_portrait":
            img_path = request.POST.get('img_path')
            if img_path:
                models.Userprofile.objects.filter(id=user_id).update(
                    set_avator=img_path)
                response.code = 200
                response.msg = "修改成功"
            else:
                response.code = 301
                response.msg = "头像不能传参异常"

        # 修改姓名
        elif oper_type == "update_name":
            name = request.POST.get('name')
            if name:
                if len(name) <= 9:
                    name = b64encode(name)
                    models.Userprofile.objects.filter(id=user_id).update(
                        name=name)
                    response.code = 200
                    response.msg = "修改成功"
                else:
                    response.code = 301
                    response.msg = '名字最大长度为8'
            else:
                response.code = 301
                response.msg = "姓名传参异常"

        # 修改手机号
        elif oper_type == "update_phone_number":
            phone_number = request.POST.get('phone_number')
            if verify_mobile_phone_number(phone_number):
                models.Userprofile.objects.filter(id=user_id).update(
                    phone_number=phone_number)
                response.code = 200
                response.msg = "修改成功"

            else:
                response.code = 301
                response.msg = "请填写正确手机号"

        # 修改微信二维码
        elif oper_type == "update_qr_code":
            qr_code = request.POST.get('qr_code')
            if qr_code:
                models.Userprofile.objects.filter(id=user_id).update(
                    qr_code=qr_code)
                response.code = 200
                response.msg = "修改成功"
            else:
                response.code = 301
                response.msg = "微信二维码传参异常"

        # 修改个性签名
        elif oper_type == "update_signature":
            signature = request.POST.get('signature')
            if signature:
                models.Userprofile.objects.filter(id=user_id).update(
                    signature=signature)
                response.code = 200
                response.msg = "修改成功"
            else:
                response.code = 301
                response.msg = "个性签名传参异常"

        # 修改文章底部是否显示产品
        elif oper_type == "update_show_product":
            show_product = request.POST.get('show_product')
            flag = re.match(r"^[01]$", show_product)

            if show_product and flag:
                models.Userprofile.objects.filter(id=user_id).update(
                    show_product=int(show_product))
                response.code = 200
                response.msg = "修改成功"
            else:
                response.code = 301
                response.msg = "是否显示产品传参异常"

        # 设置消息提醒
        elif oper_type == 'message_remind_setting':
            objs = models.Userprofile.objects.filter(id=user_id)
            objs.update(message_remind=o_id)
            response.code = 200
            response.msg = '修改成功'

    else:
        # 查询我的会员 有效期 和剩余天数/会员类型
        if oper_type == "member_info":
            obj = models.Userprofile.objects.get(id=user_id)

            # vip 类型
            vip_type = obj.get_vip_type_display()

            # 时间对象 - 年月日时分秒
            now_datetime_obj = datetime.datetime.now()

            # 时间对象 - 年月日
            now_date_obj = datetime.date(now_datetime_obj.year,
                                         now_datetime_obj.month,
                                         now_datetime_obj.day)

            # 计算剩余天数
            remaining_days = (obj.overdue_date - now_date_obj).days

            # 如果已经过期,则剩余过期时间为0,vip类型为vip已过期
            if remaining_days <= 0:

                if remaining_days == 0:
                    remaining_days = '今'
                else:
                    remaining_days = 0
                    obj.vip_type = 0
                    obj.save()
                    obj = models.Userprofile.objects.get(id=user_id)
                vip_type = obj.get_vip_type_display()

            response.code = 200
            response.data = {
                'vip_type': vip_type,
                'overdue_date': obj.overdue_date.strftime('%Y-%m-%d'),
                'remaining_days': str(remaining_days) + '天'
            }

            response.note = {
                'vip_type': "vip类型",
                'overdue_date': "有效期至",
                'remaining_days': "剩余天数"
            }

        # 使用微信头像
        elif oper_type == 'use_wechat_avatar':
            objs = models.Userprofile.objects.filter(id=user_id)
            path = requests_img_download(objs[0].headimgurl)
            set_avator = update_qiniu(path)
            objs.update(set_avator=set_avator)
            response.code = 200
            response.msg = '修改成功'

        # 推广赚钱 展示数据
        elif oper_type == 'affiliate':
            user_pub_objs = models.Userprofile.objects
            response_data = {}
            user_obj = user_pub_objs.get(id=user_id)

            response_data[
                'cumulative_amount'] = user_obj.cumulative_amount  # 累计钱数
            response_data['make_money'] = user_obj.make_money  # 待提钱数

            invite_objs = user_pub_objs.filter(inviter_id=user_id)
            invite_friend_list = [
                i.get('id') for i in invite_objs.values('id')
            ]  # 该邀请人 邀请的好友ID

            print('invite_friend_list----------> ', invite_friend_list)
            # data_list = []
            # for i in invite_friend_list:
            #     data_list.insert(0, i)
            #     data_list.extend([i.get('id') for i in models.Userprofile.objects.filter(inviter_id=i).values('id')])
            # print('data_list--------------> ', data_list)

            invite_objs = models.Userprofile.objects.filter(
                id__in=invite_friend_list)
            response_data['invite_number_count'] = invite_objs.count()  # 邀请人数量

            # 查询充值自己分销的钱数
            number_clinch_deal_objs = models.distribute_money_log.objects.filter(
                inviter_id=user_id).order_by('-create_date')

            response_data[
                'number_clinch_count'] = number_clinch_deal_objs.count(
                )  # 成交人数

            if o_id and int(o_id) == 1:  # 邀请人数详情
                invite_number_list = []
                for invite_number_obj in invite_objs:

                    # 该用户未充值展示的话
                    prepaid_text = '用户未开通会员, 邀请付款有现金奖励{}!'.format(qian)
                    if invite_number_obj.renewal_log_set.count(
                    ) >= 1:  # 判断该用户是否充值
                        money_objs = models.distribute_money_log.objects.filter(
                            inviter_id=user_id, user_id=invite_number_obj.id)
                        if money_objs:
                            money = money_objs[0].money
                            prepaid_text = '成为会员, 加入账户{}元!{}'.format(
                                money, qian)

                    invite_number_list.append({
                        'create_user__set_avator':
                        invite_number_obj.set_avator,
                        'name':
                        b64decode(invite_number_obj.name),
                        'prepaid_text':
                        prepaid_text,
                    })
                response_data['invite_number_list'] = invite_number_list

            elif o_id and int(o_id) == 2:  # 成交人数
                number_clinch_deal_list = []
                for number_clinch_deal_obj in number_clinch_deal_objs:
                    number_clinch_deal_list.append({
                        'user_set_avator':
                        number_clinch_deal_obj.user.set_avator,
                        'user_name':
                        b64decode(number_clinch_deal_obj.user.name),
                        'price':
                        number_clinch_deal_obj.price,
                        'money':
                        number_clinch_deal_obj.money,
                    })
                response_data[
                    'number_clinch_deal_list'] = number_clinch_deal_list

            response.code = 200
            response.msg = '查询成功'
            response.data = response_data
            response.note = {
                'number_clinch_deal_list': {
                    'user_set_avator': '充值人头像',
                    'user_name': '充值人名称',
                    'price': '充值钱数',
                    'money': '应得钱数',
                },
                "invite_number_count": '邀请人数量',
                "cumulative_amount": '累计钱数',
                "make_money": '待提钱数',
                "number_clinch_count": '成交人数',
                "invite_number_list": '邀请人详情',
            }

        # 推广赚钱 二维码截图
        elif oper_type == 'affiliate_screenshots':
            user_obj = models.Userprofile.objects.get(id=user_id)
            img_path = user_obj.promote_earning_qr_code_pictures
            expire_date = user_obj.generate_models_qr_code_pictures_time
            if img_path and expire_date > datetime.date.today():  # 如果有 图片
                pass
            else:
                if img_path:
                    os.remove(img_path)  # 删除原图
                img_path, expire_date = tuiguang(user_id)
                user_obj.promote_earning_qr_code_pictures = img_path
                user_obj.generate_models_qr_code_pictures_time = expire_date
                user_obj.save()

            response.code = 200
            response.msg = '生成成功'
            response.data = {'path': img_path}

        # 查询消息提醒设置
        elif oper_type == 'get_message_remind':
            user_obj = models.Userprofile.objects.get(id=user_id)

            objs = models.Userprofile.message_remind_status
            data_list = []

            for obj in objs:
                is_choose = False
                if obj[0] == user_obj.message_remind:
                    is_choose = True

                data_list.append({
                    'id': obj[0],
                    'name': obj[1],
                    'is_choose': is_choose
                })
            response.code = 200
            response.msg = '查询成功'
            response.data = {'data_list': data_list}

        # 复制昵称
        elif oper_type == 'copy_nickname':
            obj = models.Customer.objects.get(id=o_id)
            response.code = 200
            response.msg = '查询成功'
            response.data = {'nickname': b64decode(obj.name)}

        # 判断该用户是否到期 (到期后不能转发任何东西)
        elif oper_type == 'is_whether':
            obj = models.Userprofile.objects.get(id=user_id)
            now = datetime.date.today()
            flag = False
            if obj.overdue_date >= now:
                flag = True
            response.code = 200
            response.data = {'flag': flag}

        # 判断是否有手机号
        elif oper_type == 'is_phone':
            obj = models.Userprofile.objects.get(id=user_id)
            flag = False
            if obj.phone_number:
                flag = True

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

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

    return JsonResponse(response.__dict__)
Ejemplo n.º 9
0
def get_article(article_url, get_content=None):
    headers = {'User-Agent': pcRequestHeader[random.randint(0, len(pcRequestHeader) - 1)]}
    ret = requests.get(article_url, headers=headers, timeout=10, verify=False)
    ret.encoding = 'utf-8'
    s = requests.session()
    is_video_original_link = None # 是否有视频 如果有则返回原文链接
    soup = BeautifulSoup(ret.text, 'lxml')

    if not get_content:
        title = re.compile(r'var msg_title = (.*);').findall(ret.text)[0].replace('"', '')  # 标题
        summary = re.compile(r'var msg_desc = (.*);').findall(ret.text)[0].replace('"', '')  # 摘要
        cover_url = re.compile(r'var msg_cdn_url = (.*);').findall(ret.text)[0].replace('"', '')  # 封面

        ## 把封面图片下载到本地
        now_time = time.time()
        # print('--------------------请求封面-0-----------> ', datetime.datetime.today(), cover_url)
        html = s.get(cover_url)
        # print('--------------------结束请求封面-0-----------> ', datetime.datetime.today())
        if 'wx_fmt=gif' in cover_url:
            cover_name = "/cover_%s.gif" % (now_time)
        else:
            cover_name = "/cover_%s.jpg" % (now_time)
        cover_url = os.path.join('statics', 'img') + cover_name
        with open(cover_url, 'wb') as file:
            file.write(html.content)
        cover_url = update_qiniu(cover_url)

    # 获取所有样式
    style = ""
    style_tags = soup.find_all('style')
    for style_tag in style_tags:
        style += str(style_tag)

    # 获取所有图片
    body = soup.find('div', id="js_content")
    body.attrs['style'] = "padding: 20px 16px 12px;"
    img_tags = soup.find_all('img')
    for img_tag in img_tags:
        data_src = img_tag.attrs.get('data-src')
        if data_src:
            if img_tag.attrs.get('style'):
                img_tag.attrs['style'] = img_tag.attrs.get('style')

            now_time = time.time()
            # print('------------------开始请求图片----------->', datetime.datetime.today(), data_src)
            html = s.get(data_src)
            # print('------------------结束请求图片----------->', datetime.datetime.today())

            if 'wx_fmt=gif' in data_src:
                img_name = "/article_%s.gif" % (now_time)
            else:
                img_name = "/article_%s.jpg" % (now_time)

            file_dir = os.path.join('statics', 'img') + img_name
            with open(file_dir, 'wb') as file:
                file.write(html.content)
            img_url = update_qiniu(file_dir)
            img_tag.attrs['data-src'] = img_url
            #  img_tag.attrs['data-src'] = URL + '/statics/img' + img_name

    ## 处理视频的URL
    flag = False # 判断是否有 视频
    iframe = body.find_all('iframe', attrs={'class': 'video_iframe'})
    for iframe_tag in iframe:
        shipin_url = iframe_tag.get('data-src')
        data_cover_url = iframe_tag.get('data-cover') # 封面
        if data_cover_url:
            data_cover_url = unquote(data_cover_url, 'utf-8')
        data_cover_url = requests_img_download(data_cover_url) # 下载到本地
        data_cover_url = update_qiniu(data_cover_url)
        vid = shipin_url.split('vid=')[1]
        if 'wxv' in vid:  # 下载
            flag = True
            iframe_url = 'https://mp.weixin.qq.com/mp/videoplayer?vid={}&action=get_mp_video_play_url'.format(vid)
            ret = requests.get(iframe_url)
            video_path = ret.json().get('url_info')[0].get('url')
            iframe_tag_new = """<div style="width: 100%; background: #000; position:relative; height: 0; padding-bottom:75%;">
                                       <video style="width: 100%; height: 100%; position:absolute;left:0;top:0;" id="videoBox" src="{}" poster="{}" controls="controls" allowfullscreen=""></video>
                                   </div>""".format(video_path, data_cover_url)

        else:
            shipin_url = 'https://v.qq.com/txp/iframe/player.html?origin=https%3A%2F%2Fmp.weixin.qq.com&vid={}&autoplay=false&full=true&show1080p=false&isDebugIframe=false'.format(
                vid
            )
            iframe_tag.attrs['data-src'] = shipin_url
            iframe_tag.attrs['allowfullscreen'] = True  # 是否允许全屏
            iframe_tag.attrs['data-cover'] = data_cover_url

            iframe_tag_new = str(iframe_tag).replace('></iframe>', ' width="100%" height="300px"></iframe>')


        body = str(body).replace(str(iframe_tag), iframe_tag_new)
        body = BeautifulSoup(body, 'html.parser')

    content = str(style) + str(body)
    content = BeautifulSoup(content, 'html.parser')
    if not get_content:
        # 生成css 文件
        now = time.time()
        style = style.replace('<style>', '').replace('</style>', '')
        style_path = os.path.join('statics', 'article_css') + '/{}.css'.format(now)
        with open(style_path, 'w') as e:
            e.write(style)
        # style_path = URL + '/statics/article_css/{}.css'.format(now)

    # 分布标签
    data_list = []
    for i in content:
        content = convert_content(s, str(i)) # 替换内容
        data_list.append(content)

    if flag:
        is_video_original_link = article_url # 原文链接

    if not get_content:
        data = {
            'title': title,
            'summary':b64encode(summary),
            'cover_img':cover_url,
            'content': json.dumps(data_list),
            'style': style_path,
            'original_link': is_video_original_link,
        }
    else:
        data = {
            'content': json.dumps(data_list),
        }
    return data
Ejemplo n.º 10
0
def external_login(request):
    response = Response.ResponseObj()
    external_token = request.GET.get('token')  # 平台token
    source = request.GET.get('source')  # 来自哪个平台
    userId = request.GET.get('userId')  # 来自哪个平台

    login_type = 2

    is_login_flag = True
    if source == 'dingdong':  # 叮咚营销宝
        pass

    else:
        is_login_flag = False
        response.code = 402
        response.msg = '请求错误'

    if is_login_flag:  # 验证通过
        user_data = {
            'role_id': 7,  # 默认普通用户
            'token': external_token,
            'login_type': login_type,
            'ding_dong_marketing_treasure_user_id': userId,
        }
        objs = models.UserProfile.objects.filter(token=external_token)
        if objs:
            obj = objs[0]

        else:
            get_user_info_url = 'http://a.yingxiaobao.org.cn/api/user/info/{}?token={}&user_id={}'.format(
                userId, external_token, userId)
            ret = requests.get(get_user_info_url)
            info_data = ret.json().get('data')
            user_data['username'] = base64_encryption.b64encode(
                info_data.get('username'))
            user_data['head_portrait'] = info_data.get('head_portrait')
            obj = models.UserProfile.objects.create(**user_data)

        role_obj = models.Role.objects.filter(id=obj.role_id)
        data_list = []
        for i in role_obj[0].permissions.all():
            data_list.append(i.name)

        inviter = 0
        if obj.inviter:
            inviter = 1

        try:
            username = base64_encryption.b64decode(obj.username)
        except Exception:
            username = obj.username

        response.code = 200
        response.msg = '登录成功'
        response.data = {
            'username': username,
            'token': obj.token,
            'id': obj.id,
            'role_id': obj.role_id,
            'role_name': obj.role.name,
            'head_portrait': obj.head_portrait,
            'permissions_list': data_list,
            'inviter': inviter,
        }

    return JsonResponse(response.__dict__)
Ejemplo n.º 11
0



# 向下小手四个
xiajiantou = b64decode('8J+Rhw==') + b64decode('8J+Rhw==') + b64decode('8J+Rhw==') + b64decode('8J+Rhw==')

# 难受表情 一个
nanshou = b64decode('8J+Ynw==')

# 彩带 🎉
caidai = b64decode('8J+OiQ==')

# 白眼🙄
baiyan = b64decode('8J+ZhO+4jw==')

# 眨眼
zhayan = b64decode('8J+YiQ==')


# 钱
qian = b64decode('8J+StO+4jw==')





if __name__ == '__main__':
    encode =  b64encode('😉')
    print('encode----> ', encode)
    print(b64decode(encode))