Skip to content

Commit

Permalink
Merge pull request eee555#165 from eee555/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
eee555 authored Nov 23, 2024
2 parents 34c1d2c + 74a2a81 commit 839fa4a
Show file tree
Hide file tree
Showing 24 changed files with 560 additions and 138 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/backend.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ on:
branches:
- main # Adjust the branch name as needed
pull_request:
paths:
- 'back_end/saolei/**'

jobs:
check_flag:
Expand Down
3 changes: 3 additions & 0 deletions back_end/saolei/identifier/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@
from utils.response import HttpResponseConflict
from videomanager.models import VideoModel
from videomanager.view_utils import update_state, update_personal_record_stock
from userprofile.decorators import login_required_error

# 请求修改自己的标识
@require_POST
@login_required_error
def add_identifier(request):
user = UserProfile.objects.filter(id=request.user.id).first()
if user == None:
Expand Down Expand Up @@ -41,6 +43,7 @@ def add_identifier(request):

# 请求删除自己的标识
@require_POST
@login_required_error
def del_identifier(request):
user = UserProfile.objects.filter(id=request.user.id).first()
if user == None:
Expand Down
33 changes: 7 additions & 26 deletions back_end/saolei/msuser/views.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import logging
logger = logging.getLogger('userprofile')
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .forms import UserUpdateRealnameForm, UserUpdateAvatarForm, UserUpdateSignatureForm
# from .models import VideoModel, ExpandVideoModel
from django.http import HttpResponse, JsonResponse, HttpResponseNotAllowed, HttpResponseBadRequest, HttpResponseNotFound
from django.http import JsonResponse, HttpResponseBadRequest, HttpResponseNotFound
# from asgiref.sync import sync_to_async
import json
from utils import ComplexEncoder
# from django.core.paginator import Paginator
from msuser.models import UserMS
from userprofile.models import UserProfile
import base64
import decimal
Expand All @@ -18,11 +16,9 @@
cache = get_redis_connection("saolei_website")
from django.conf import settings
import os
from django.utils import timezone
from datetime import datetime, timedelta
from utils import verify_text
from django_ratelimit.decorators import ratelimit
from django.views.decorators.http import require_GET, require_POST
from userprofile.utils import user_metadata

from config.global_settings import *

Expand All @@ -38,7 +34,7 @@ def default(self, o):


# 获取我的地盘里的头像、姓名、个性签名、过审标识
@ratelimit(key='ip', rate='60/h')
@ratelimit(key='ip', rate='20/m')
@require_GET
def get_info(request):
user_id = request.GET.get('id')
Expand All @@ -50,28 +46,12 @@ def get_info(request):

user.popularity += 1
user.save(update_fields=["popularity"])

if user.avatar:
avatar_path = os.path.join(settings.MEDIA_ROOT, urllib.parse.unquote(user.avatar.url)[7:])
image_data = open(avatar_path, "rb").read()
image_data = base64.b64encode(image_data).decode()
else:
image_data = None
response = {"id": user_id,
"username": user.username,
"realname": user.realname,
"avatar": image_data,
"signature": user.signature,
"popularity": user.popularity,
"identifiers": user.userms.identifiers,
"is_banned": user.is_banned,
"country": user.country
}
return JsonResponse(response)

return JsonResponse(user_metadata(user))


# 获取我的地盘里的姓名、全部纪录
@ratelimit(key='ip', rate='60/h')
@ratelimit(key='ip', rate='15/m')
@require_GET
def get_records(request):
user_id = request.GET.get('id')
Expand All @@ -93,6 +73,7 @@ def get_records(request):


# 鼠标移到人名上时,展现头像、姓名、id、记录
@ratelimit(key='ip', rate='5/s')
@require_GET
def get_info_abstract(request):
# 此处要防攻击
Expand Down
3 changes: 2 additions & 1 deletion back_end/saolei/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ django-ratelimit==4.1.0
requests==2.28.1
ms_toollib==1.4.8
psutil==5.9.1
lxml==5.1.0
lxml==5.1.0
websocket-client==1.8.0
28 changes: 28 additions & 0 deletions back_end/saolei/userprofile/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
from captcha.models import CaptchaStore
from django.utils import timezone
from .models import EmailVerifyRecord
from .models import UserProfile
from videomanager.models import VideoModel
import os
from django.conf import settings
import urllib.parse
import base64

# 验证验证码
def judge_captcha(captchaStr, captchaHashkey):
Expand All @@ -25,3 +31,25 @@ def judge_email_verification(email, email_captcha, emailHashkey):
EmailVerifyRecord.objects.filter(hashkey=emailHashkey).delete()
return False
return get_email_captcha.code == email_captcha and get_email_captcha.email == email

def user_metadata(user: UserProfile):
if user.avatar:
avatar_path = os.path.join(settings.MEDIA_ROOT, urllib.parse.unquote(user.avatar.url)[7:])
image_data = open(avatar_path, "rb").read()
image_data = base64.b64encode(image_data).decode()
else:
image_data = None

videos = VideoModel.objects.filter(player=user).values('id', 'upload_time', "level", "mode", "timems", "bv", "state", "software")
return {"id": user.id,
"username": user.username,
"realname": user.realname,
"avatar": image_data,
"signature": user.signature,
"popularity": user.popularity,
"identifiers": user.userms.identifiers,
"is_banned": user.is_banned,
"is_staff": user.is_staff,
"country": user.country,
"videos": list(videos),
}
24 changes: 9 additions & 15 deletions back_end/saolei/userprofile/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from .decorators import staff_required
from django.utils import timezone
from config.flags import EMAIL_SKIP
from .utils import judge_captcha, judge_email_verification
from .utils import judge_captcha, judge_email_verification, user_metadata

# Create your views here.

Expand Down Expand Up @@ -42,11 +42,10 @@ def user_login(request):
return JsonResponse({'type': 'error', 'object': 'login', 'category': 'password'})
# 将用户数据保存在 session 中,即实现了登录动作
login(request, user)
userdata = {"id": user.id, "username": user.username, "realname": user.realname, "is_banned": user.is_banned, "is_staff": user.is_staff}
if 'user_id' in data and data['user_id'] != str(user.id):
# 检测到小号
logger.warning(f'{data["user_id"][:50]} is different from {str(user.id)}.')
return JsonResponse({'type': 'success', 'user': userdata})
return JsonResponse({'type': 'success', 'user': user_metadata(user)})


@require_GET
Expand Down Expand Up @@ -83,8 +82,7 @@ def user_retrieve(request):
login(request, user)
logger.info(f'用户 {user.username}#{user.id} 邮箱找回密码')
EmailVerifyRecord.objects.filter(hashkey=emailHashkey).delete()
userdata = {"id": user.id, "username": user.username, "realname": user.realname, "is_banned": user.is_banned, "is_staff": user.is_staff}
return JsonResponse({'type': 'success', 'user': userdata})
return JsonResponse({'type': 'success', 'user': user_metadata(user)})


# 用户注册
Expand Down Expand Up @@ -113,10 +111,7 @@ def user_register(request):
logger.info(f'用户 {new_user.username}#{new_user.id} 注册')
# 顺手把过期的验证码删了
EmailVerifyRecord.objects.filter(hashkey=emailHashkey).delete()
return JsonResponse({'type': 'success', 'user': {
"id": new_user.id, "username": new_user.username,
"realname": new_user.realname, "is_banned": new_user.is_banned, "is_staff": new_user.is_staff}
})
return JsonResponse({'type': 'success', 'user': user_metadata(new_user)})
else:
return JsonResponse({'type': 'error', 'object': 'emailcode'})
else:
Expand All @@ -133,11 +128,10 @@ def user_register(request):
@require_GET
def check_collision(request):
user = None
if request.GET.get('username'):
print(request.GET.get('username'))
user = UserProfile.objects.filter(username=request.GET.get('username')).first()
elif request.GET.get('email'):
user = UserProfile.objects.filter(email=request.GET.get('email')).first()
if username := request.GET.get('username'):
user = UserProfile.objects.filter(username=username).first()
elif email := request.GET.get('email'):
user = UserProfile.objects.filter(email=email).first()
else:
return HttpResponseBadRequest()
if not user:
Expand Down Expand Up @@ -201,7 +195,7 @@ def refresh_captcha(request):
return HttpResponse(json.dumps(c), content_type='application/json')

# 验证验证码,若通过,发送email
@ratelimit(key='ip', rate='20/h')
@ratelimit(key='ip', rate='1/m')
@require_POST
def get_email_captcha(request):
data = request.POST
Expand Down
55 changes: 55 additions & 0 deletions back_end/saolei/utils/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import unittest
from unittest.mock import MagicMock
import time
from wom import WOM
import json


class TestWOM(unittest.TestCase):

def test_insert_video_id(self):
self.count = 0
# 创建 WOM 实例并传入 mock_callback
wom = WOM(videoInfoFunc=self.callbackFunc, disConnectTime=10, raiseReConnectTime=60,errorFunc=self.errorFunc)
wom.start() # 启动 WOM

wom.insertVideoId('3071736950')
wom.insertVideoId('3071736950')
time.sleep(5)
# 断言当前是连接状态
self.assertEqual(wom.isConnected(), True, "Connect")

# 等待 20 秒
time.sleep(20)
# 断言当前是断开状态
self.assertEqual(wom.isConnected(), False, "Disconnect")
wom.insertVideoId('3071736950')

# 再次等待 5 ,等待异步重连
time.sleep(5)
# 断言当前是连接状态
self.assertEqual(wom.isConnected(), True, "Connect")

time.sleep(20)
# 确保总共调用了6次 callback
self.assertEqual(self.count, 6, "Callback")
wom.stop()
time.sleep(5)
# 断言当前是断开状态
self.assertEqual(wom.isConnected(), False, "Disconnect")

def callbackFunc(self, message):
data = json.loads(message)
if data[0][1] == 203:
self.assertEqual(data[1][2][0]['id'],
3071736950, "Insert video Info 203")
if data[0][1] == 214:
self.assertEqual(data[1][2][0], 3071736950,
"Insert video Info 214")
self.count += 1

def errorFunc(self, e:Exception):
print(f"Error: {e}")

if __name__ == '__main__':
unittest.main()
Loading

0 comments on commit 839fa4a

Please sign in to comment.