예제 #1
0
def submit_a_feed(request):
    """
    用户添加一个自定义的订阅源
    """
    feed_url = request.POST.get('url', '').strip()[:1024]
    user = get_login_user(request)

    if feed_url:
        host = get_host_name(feed_url)

        if 'ershicimi.com' in host:
            rsp = parse_wemp_ershicimi(feed_url)
        elif host in settings.ALLOWED_HOSTS:
            rsp = parse_self_atom(feed_url)
        else:
            rsp = parse_atom(feed_url)

        if rsp:
            logger.warning(f"有新订阅源被提交:`{feed_url}")

            # 已登录用户,自动订阅
            if user:
                add_user_sub_feeds(user.oauth_id, [
                    rsp['name'],
                ])
            return JsonResponse(rsp)
        else:
            logger.warning(f"RSS 解析失败:`{feed_url}")

    return HttpResponseNotFound("Param error")
예제 #2
0
def submit_a_feed(request):
    """
    用户添加一个自定义的订阅源
    """
    feed_url = request.POST.get('url', '').strip()[:1024]
    user = get_login_user(request)

    if feed_url:
        host = get_host_name(feed_url)

        if settings.ERSHICIMI_HOST in host:
            feed_url = feed_url.replace('/user/analysis?bid=', '/a/')
            rsp = add_ershicimi_feed(feed_url)
        elif host in settings.ALLOWED_HOSTS:
            rsp = add_self_feed(feed_url)
        elif settings.QNMLGB_HOST in host:
            rsp = add_qnmlgb_feed(feed_url)
        elif settings.WEMP_HOST in host:
            rsp = add_wemp_feed(feed_url)
        elif settings.CHUANSONGME_HOST in host:
            rsp = add_chuansongme_feed(feed_url)
        elif settings.ANYV_HOST in host:
            rsp = add_anyv_feed(feed_url)
        else:
            # 区分播客还是普通 RSS
            feed_obj = feedparser.parse(feed_url)

            if is_podcast_feed(feed_obj):
                rsp = add_postcast_feed(feed_obj)
            else:
                rsp = add_atom_feed(feed_obj)

        if rsp:
            logger.warning(f"有新订阅源被提交:`{feed_url}")

            set_active_site(rsp['site'])

            # 已登录用户,自动订阅
            if user:
                add_user_sub_feeds(user.oauth_id, [
                    rsp['site'],
                ])

            if rsp.get('creator') == 'user':
                # 新增的普通 RSS 才触发异步更新任务
                django_rq.enqueue(update_sites_async, [
                    rsp['site'],
                ],
                                  result_ttl=1,
                                  ttl=3600,
                                  failure_ttl=3600)

            return JsonResponse(rsp)
        else:
            logger.warning(f"RSS 解析失败:`{feed_url}")

    return HttpResponseNotFound("Param Error")
예제 #3
0
def user_subscribe_feed(request):
    """
    已登录用户订阅源
    """
    feed = request.POST.get('feed', '').strip()[:32]

    user = get_login_user(request)

    if user and feed:
        try:
            Site.objects.get(name=feed)
            add_user_sub_feeds(user.oauth_id, [feed, ])
            return JsonResponse({"name": feed})
        except:
            logger.warning(f'用户订阅出现异常:`{feed}`{user.oauth_id}')

    return HttpResponseNotFound("Param error")
예제 #4
0
def user_subscribe_feed(request):
    """
    已登录用户订阅源
    """
    site_id = request.POST.get('site_id', '').strip()[:32]

    user = get_login_user(request)
    site = Site.objects.get(pk=site_id, status='active')

    if user and site:
        # 先判断是否达到限制
        if user.level < 10:
            if len(get_user_subscribe_feeds(user.oauth_id, from_user=False, user_level=user.level)) \
                    == settings.USER_SUBS_LIMIT:

                logger.warning(f"已达到订阅上限:`{user.oauth_name}")
                return JsonResponse({
                    "code":
                    1,
                    "msg":
                    f"已达到 {settings.USER_SUBS_LIMIT} 个订阅数,请先取消一部分!"
                })

        add_user_sub_feeds(user.oauth_id, [
            site_id,
        ])

        # 异步更新
        django_rq.enqueue(update_sites_async, [
            site.pk,
        ],
                          result_ttl=1,
                          ttl=3600,
                          failure_ttl=3600)

        logger.warning(f"登陆用户订阅动作:`{user.oauth_name}`{site_id}")

        return JsonResponse({"code": 0, "msg": '订阅成功 ^o^'})

    return HttpResponseForbidden("Param Error")
예제 #5
0
def submit_a_feed(request):
    """
    用户添加一个自定义的订阅源
    """
    feed_url = request.POST.get('url', '').strip()[:1024]
    user = get_login_user(request)

    if feed_url:
        host = get_host_name(feed_url)

        if 'ershicimi.com' in host:
            feed_url = feed_url.replace('/user/analysis?bid=', '/a/')
            rsp = parse_wemp_ershicimi(feed_url)
        elif host in settings.ALLOWED_HOSTS:
            rsp = parse_self_atom(feed_url)
        elif 'qnmlgb.tech' in host:
            rsp = parse_qnmlgb_atom(feed_url)
        else:
            rsp = parse_atom(feed_url)

        if rsp:
            logger.warning(f"有新订阅源被提交:`{feed_url}")

            # 已登录用户,自动订阅
            if user:
                add_user_sub_feeds(user.oauth_id, [
                    rsp['site'],
                ])

            # 异步更新任务
            django_rq.enqueue(update_sites_async, [
                rsp['site'],
            ])

            return JsonResponse(rsp)
        else:
            logger.warning(f"RSS 解析失败:`{feed_url}")

    return HttpResponseNotFound("Param Error")
예제 #6
0
def github_callback(request):
    """
    接收 github 的登录回调
    """
    try:
        code = request.GET.get('code')

        if code:
            rsp = requests.post('https://github.com/login/oauth/access_token',
                                data={
                                    "client_id": settings.GITHUB_OAUTH_KEY,
                                    "client_secret":
                                    settings.GITHUB_OAUTH_SECRET,
                                    "code": code,
                                },
                                headers={"Accept": "application/json"},
                                timeout=10)

            if rsp.ok:
                access_token = rsp.json().get('access_token')

                if access_token:
                    rsp = requests.get('https://api.github.com/user',
                                       headers={
                                           "Accept":
                                           "application/json",
                                           "Authorization":
                                           f"token {access_token}",
                                       },
                                       timeout=10)

                    if rsp.ok:
                        if rsp.json().get('id'):
                            oauth_id = f'github/{rsp.json()["id"]}'
                            oauth_name = rsp.json().get(
                                'name') or rsp.json().get('login')
                            oauth_avatar = rsp.json().get('avatar_url')
                            oauth_email = rsp.json().get('email')
                            oauth_blog = rsp.json().get(
                                'blog') or rsp.json().get('html_url')
                            oauth_ext = json.dumps(rsp.json())

                            # 用户信息入库
                            user, created = User.objects.update_or_create(
                                oauth_id=oauth_id,
                                defaults={
                                    "oauth_name": oauth_name,
                                    "oauth_avatar": oauth_avatar,
                                    "oauth_email": oauth_email,
                                    "oauth_blog": oauth_blog,
                                    "oauth_ext": oauth_ext,
                                })

                            if created:
                                logger.warning(f"欢迎新用户登录:`{user.oauth_name}")
                                add_user_sub_feeds(
                                    oauth_id,
                                    get_visitor_subscribe_feeds('',
                                                                '',
                                                                star=28))
                                add_register_count()

                                # 用户头像存储到本地一份,国内网络会丢图
                                avatar = save_avatar(oauth_avatar, oauth_id)

                                user.avatar = avatar
                                user.save()

                            response = redirect('index')
                            response.set_signed_cookie('oauth_id',
                                                       oauth_id,
                                                       max_age=10 * 365 *
                                                       86400)
                            response.set_signed_cookie('toast',
                                                       'LOGIN_SUCC_MSG',
                                                       max_age=20)

                            return response
    except (ConnectTimeout, HTTPError, ReadTimeout, Timeout, ConnectionError):
        logger.warning("OAuth 认证网络出现异常!")
    except:
        logger.error("OAuth 认证出现未知异常")

    response = redirect('index')
    response.set_signed_cookie('toast', 'LOGIN_ERROR_MSG', max_age=20)

    return response