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 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 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
def refreshRoomList(request):
    if request.method == 'POST':
        print(request.body)
        # get information through analyzing json

        anchorList = []
        try:
            # get all username of all anchors whose is streaming
            object = models.Room.objects.filter(
                isStreaming=1).values('roomId_id').distinct()
            for i in range(object.count()):
                username = models.User.objects.get(
                    userId=object[i]['roomId_id']).userName
                portrait = models.User.objects.get(
                    userId=object[i]['roomId_id']).headPortrait.name
                print(username, portrait)
                newDict = {"username": username, "portrait": portrait}
                anchorList.append(newDict)

            # add a new lauth_userogging
            save_success_log(request.path)
            '''
            object = models.streaming_user.objects.filter(is_anchor=1).values('username').distinct()
            for i in range(object.count()):
                print(object[i]['username'])
                anchorList.append(object[i]['username'])
            '''
        except json.JSONDecodeError:
            print('json decode error')
            anchorList = None
            functions_cz.save_fail_log(request.path)
        except models.User.DoesNotExist:
            print("does not exist")
            anchorList = None
            # add a new logging
            functions_cz.save_fail_log(request.path)

        data = {"ret": anchorList}
        return HttpResponse(json.dumps(data), 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")
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')
Exemplo n.º 7
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 refresh(request):
    # get information through analyzing json
    print(request.body)
    try:
        action = json.loads(request.body.decode()).get('action')
        client_id = json.loads(request.body.decode()).get('client_id')
        ip = json.loads(request.body.decode()).get('ip')
        vhost = json.loads(request.body.decode()).get('vhost')
        app = json.loads(request.body.decode()).get('app')

        if "on_connect" == action:
            tcUrl = json.loads(request.body.decode()).get('tcUrl')
            pageUrl = json.loads(request.body.decode()).get('pageUrl')
            print(action, client_id, ip, vhost, app, tcUrl, pageUrl)

        elif "on_close" == action:
            send_bytes = json.loads(request.body.decode()).get('send_bytes')
            recv_bytes = json.loads(request.body.decode()).get('recv_bytes')
            print(action, client_id, ip, vhost, app, send_bytes, recv_bytes)

        elif "on_publish" == action:
            tcUrl = json.loads(request.body.decode()).get('tcUrl')
            stream = json.loads(request.body.decode()).get('stream')

            if change_streaming_status(request, stream, 1) is True:
                print(action, client_id, ip, vhost, app, tcUrl, stream)
            else:
                print("failed")

        elif "on_unpublish" == action:
            stream = json.loads(request.body.decode()).get('stream')

            if change_streaming_status(request, stream, 0) is True:
                print(action, client_id, ip, vhost, app, stream)
            else:
                print("failed")

        elif "on_play" == action:
            stream = json.loads(request.body.decode()).get('stream')
            pageUrl = json.loads(request.body.decode()).get('pageUrl')
            print(action, client_id, ip, vhost, app, stream, pageUrl)

        elif "on_stop" == action:
            stream = json.loads(request.body.decode()).get('stream')
            print(action, client_id, ip, vhost, app, stream)

        elif "on_dvr" == action:
            stream = json.loads(request.body.decode()).get('stream')
            cwd = json.loads(request.body.decode()).get('cwd')
            file = json.loads(request.body.decode()).get('file')
            print(action, client_id, ip, vhost, app, stream, cwd, file)
            # save file name to database
            '''
            try:
                anchor = models.User.objects.get(userName=stream, isAnchor=1)
                room = models.Room.objects.get(roomId=anchor)
                room.replayURL = file
                room.save()
            except:
                print('save file fail')
            '''
    except json.JSONDecodeError:
        functions_cz.save_fail_log(request.path)
    except:
        print("failed")
    return HttpResponse(0)