def getUserInfo(request):
    if request.method == 'POST':
        # get information through analyzing json
        username = json.loads(request.body.decode("utf-8")).get('username')
        isAnchor = json.loads(request.body.decode("utf-8")).get('is_anchor')
        print(username, isAnchor)

        # check if the password reset successfully
        obj = models.User.objects.filter(userName=username, isAnchor=isAnchor)
        if obj.exists() is True:
            obj2 = models.User.objects.get(userName=username,
                                           isAnchor=isAnchor)
            email = obj2.eMail
            headPortrait = obj2.headPortrait
            print(email, headPortrait.name)
            print("get info successfully")
            # add a new logging
            functions_cz.save_success_log(request.path, obj2)
            data = {'email': email, 'headPortrait': headPortrait.name}
        else:
            print("get info failed")
            # add a new logging
            functions_cz.save_fail_log(request.path)
            data = {'email': '', 'headPortrait': ''}
        return HttpResponse(json.dumps(data), content_type="application/json")
def change_streaming_status(request, anchor_name, current_status):
    with transaction.atomic():
        result = 0
        request_path = request.path
        try:
            if re.match(r'^\w{1,15}$', anchor_name) is None:
                raise exceptions_cz.ReFailed
            # check if the user exists or not
            user_queryset = models.User.objects.filter(userName=anchor_name,
                                                       isAnchor=True)
            if user_queryset.exists() is False:
                raise exceptions_cz.ModelNotExist
            # find room of the user
            user_object = models.User.objects.get(userName=anchor_name,
                                                  isAnchor=True)
            streaming_room = models.Room.objects.get(roomId=user_object)

            if current_status == streaming_room.isStreaming:
                raise exceptions_cz.DuplicatedStatus

            #==================================
            if current_status == 0:
                # calculate time difference
                startTime = streaming_room.lastStreaming
                endTime = datetime.datetime.now()
                timeDiff = (endTime - startTime).seconds
                streaming_room.streamingTime += timeDiff
                streaming_room.streamingNum += 1
            #==================================

            # change the status of the room
            streaming_room.isStreaming = current_status
            streaming_room.save()

            msg = message.CdlpMessage()
            msg.type = 4
            msg.anchorName = anchor_name
            msg.level = current_status

            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect((settings.SOCKET_HOST_IP, settings.SOCKET_HOST_PORT))
            sock.send(msg.SerializeToString())
            sock.send(b'\n')
            sock.close()

            result = 1
            functions_cz.save_success_log(request_path, user_object)
        # field empty case
        except TypeError:
            functions_cz.save_fail_log(request_path)
        except exceptions_cz.ReFailed:
            functions_cz.save_fail_log(request_path)
        except exceptions_cz.ModelNotExist:
            functions_cz.save_fail_log(request_path)
        except exceptions_cz.DuplicatedStatus:
            functions_cz.save_fail_log(request_path)
        return result
Esempio n. 3
0
def register(request):
    with transaction.atomic():
        result = {'ret': '0'}
        request_path = request.path
        try:
            user_info = json.loads(request.body.decode())
            username = user_info.get('username')
            password = user_info.get('password')
            email = user_info.get('email')
            is_anchor = user_info.get('is_anchor')

            if re.match(r'^\w{1,15}$', username) is None \
                    or re.match(r'^\w{1,129}$', password) is None \
                    or re.match(r'^\w{1,20}@\w{1,20}\.com$', email) is None \
                    or is_anchor not in [0, 1]:
                raise exceptions_cz.ReFailed
            # find whether same username and email exists or not
            temp_user_1 = models.User.objects.filter(userName=username)
            temp_user_2 = models.User.objects.filter(eMail=email)
            # if they both not exist, the user can be registered
            if temp_user_1.exists() is False and temp_user_2.exists() is False:
                new_user = models.User(userName=username, passWord=password, isAnchor=is_anchor, eMail=email)
                new_user.save()
                if is_anchor is 1:
                    new_streaming_room = models.Room(roomId=new_user, roomName="%s's room" % username)
                    new_streaming_room.save()

                    msg = message_pb2.CdlpMessage()
                    msg.type = 3
                    msg.anchorName = username

                    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    sock.connect((settings.SOCKET_HOST_IP, settings.SOCKET_HOST_PORT))
                    sock.send(msg.SerializeToString())
                    sock.send(b'\n')
                    sock.close()
                user_id = models.User.objects.get(userName=username, isAnchor=is_anchor)
                functions_cz.save_success_log(request.path, user_id)
                result['ret'] = '1'
        # catch errors that brought by inappropriate json format
        except json.decoder.JSONDecodeError:
            functions_cz.save_fail_log(request_path)
        # catch field missing error
        except TypeError:
            functions_cz.save_fail_log(request_path)
        except exceptions_cz.ReFailed:
            functions_cz.save_fail_log(request_path)

        return HttpResponse(json.dumps(result), content_type='application/json')
def uploadPortrait(request):
    if request.method == 'POST':
        # get information through analyzing json
        # username = json.loads(request.body.decode()).get('username')
        # headportrait = json.loads(request.body.decode()).get('image')
        username = request.POST.get('username')
        isAnchor = int(request.POST.get('is_anchor'))
        f = request.FILES.get("image")
        print(username)
        print(isAnchor)

        # 文件在服务器端的路径
        if f:
            uploadDir = os.path.abspath(settings.MEDIA_ROOT)
            # today = dt.datetime.today()
            # dirName = uploadDir + '/%d/%d/'% (today.year,today.month)
            if not os.path.exists(uploadDir):
                os.makedirs(uploadDir)
            filepath = os.path.join(uploadDir, f.name)
            with open(filepath, 'wb+') as destination:
                for chunk in f.chunks():
                    destination.write(chunk)
                destination.close()

        # check if the head portrait upload successfully
        try:
            obj = models.User.objects.get(userName=username, isAnchor=isAnchor)
            obj.headPortrait = settings.MEDIA_URL + f.name
            obj.save()
            # ret = 1
            ret = settings.MEDIA_URL + f.name
            print("upload sucessfully")
            # add a new logging
            functions_cz.save_success_log(request.path, obj)
        except models.User.DoesNotExist:
            print("upload failure")
            ret = '0'
            # add a new logging
            functions_cz.save_fail_log(request.path)
        except:
            print("upload failure")
            ret = '0'
            # add a new logging
            functions_cz.save_fail_log(request.path)

        data = {'ret': ret}
        return HttpResponse(json.dumps(data), content_type="application/json")
def end_streaming(request):
    with transaction.atomic():
        result = {'ret': '0'}
        request_path = request.path
        try:
            user_info = json.loads(request.body.decode())
            username = user_info.get('username')
            room_name = user_info.get('roomname')

            if re.match(r'^\w{1,15}$', username) is None or re.match(r'^\w{1,15}$', room_name) is None:
                raise exceptions_cz.ReFailed
            # check if the user exists or not
            user_queryset = models.User.objects.filter(userName=username, isAnchor=True)
            if user_queryset.exists() is False:
                raise exceptions_cz.ModelNotExist
            # find room of the user
            user_object = models.User.objects.get(userName=username, isAnchor=True)
            streaming_room = models.Room.objects.get(roomId=user_object)
            # change the status of the room
            streaming_room.isStreaming = 0
            streaming_room.roomName = room_name
            #==================================
            # calculate time difference
            startTime = streamingRoom.lastStreaming
            endTime = datetime.datetime.now()
            timeDiff = (endTime - startTime).seconds
            streamingRoom.streamingTime += timeDiff
            #==================================
            streaming_room.save()

            result['ret'] = '1'
            functions_cz.save_success_log(request_path, user_object)
        except json.JSONDecodeError:
            functions_cz.save_fail_log(request_path)
        # field empty case
        except TypeError:
            functions_cz.save_fail_log(request_path)
        except exceptions_cz.ReFailed:
            functions_cz.save_fail_log(request_path)
        except exceptions_cz.ModelNotExist:
            functions_cz.save_fail_log(request_path)

        return HttpResponse(json.dumps(result), content_type='application/json')
def forgetPwd(request):
    if request.method == 'POST':
        # get information through analyzing json
        username = json.loads(request.body.decode()).get('username')
        email = json.loads(request.body.decode()).get('email')
        isAnchor = json.loads(request.body.decode()).get('is_anchor')
        print(username, email)

        # check if username and email are correct

    try:
        object = models.User.objects.get(userName=username, eMail=email)
        ret = 1
        print(object.userName, object.eMail)
        print("verify successfully")
        # add a new logging
        functions_cz.save_success_log(request.path, object)

    except models.User.DoesNotExist:
        print('doesnotexist')

        try:
            models.User.objects.get(userName=username, isAnchor=isAnchor)
            ret = 2
            print("info not correct")
            # add a new logging
            functions_cz.save_fail_log(request.path)
        except models.User.DoesNotExist:
            print('doesnotexist')
        except:
            ret = 0
            print("user not exist")
            # add a new logging
            functions_cz.save_fail_log(request.path)

    data = {'ret': ret}
    return HttpResponse(json.dumps(data), content_type="application/json")