コード例 #1
0
ファイル: views.py プロジェクト: jadensiow/File_Sharing_Web
def edit_video_details(request, **kwargs):
    if request.method != 'PUT':
        return send_message(False,
                            f"{request.method} not supported on this route")

    body = json.loads(request.body.decode())

    user = kwargs.get('user')
    video_id = kwargs.get('videoId')

    user_model = User.objects.filter(pk=user['id']).first()
    video_model = Video.objects.filter(pk=video_id).first()

    if video_model.user.id != user_model.id:
        return send_message(False, "You can only edit your own videos")

    new_title = body.get('title')
    new_description = body.get('description')

    if new_title:
        video_model.title = new_title

    if new_description:
        video_model.description = new_description

    video_model.save()

    return HttpResponse(
        json.dumps({
            "success": True,
            "message": "Video details edited Successfully",
            "video": video_model.get_dict()
        }))
コード例 #2
0
ファイル: views.py プロジェクト: jadensiow/File_Sharing_Web
def profile_pic_upload(request, *args, **kwargs):
    if request.method == 'POST':
        user = kwargs.get('user')

        user_model = User.objects.filter(pk=user['id']).first()
        file_to_upload = request.FILES.get('myFile')

        # picture_type can be either profilePicture or channelBanner
        picture_type = request.GET.get('pictureType')

        if not picture_type:
            return send_message(False, "Bad Request")

        try:
            s3_url = upload_file(file_to_upload, user_model.username)

            if picture_type == 'profilePicture':
                user_model.profilePictureUrl = s3_url

            elif picture_type == 'channelBanner':
                user_model.channelBannerUrl = s3_url

            user_model.save()

        except:
            return send_message(
                False, "Sorry something went wrong while uploading the file")

        return send_message(
            True, "It might take some time for the change to show up")
コード例 #3
0
ファイル: views.py プロジェクト: jadensiow/File_Sharing_Web
def delete_video(request, **kwargs):
    if request.method != 'DELETE':
        return send_message(False,
                            f"{request.method} not supported on this route")

    video_id = kwargs.get('videoId')
    user = kwargs.get('user')

    user_model = User.objects.filter(pk=user['id']).first()
    video_model = Video.objects.filter(pk=video_id).first()

    if video_model.user.id != user_model.id:
        return send_message(False, "You can only delete your own videos")

    video_s3_urls = [video_model.videoUrl, video_model.videoThumbnailUrl]

    video_s3_keys = get_s3_key_from_s3_url(video_s3_urls)

    try:
        delete_from_s3(video_s3_keys)

    except:
        return send_message(False,
                            "Something went wrong while deleting the video")

    video_model.delete()

    return send_message(True, "Video Deleted")
コード例 #4
0
ファイル: views.py プロジェクト: jadensiow/File_Sharing_Web
def get_post_comments(request, **kwargs):
    if request.method == 'POST':
        user = kwargs.get('user')
        video_id = kwargs.get('videoId')
        body = json.loads(request.body.decode())

        user_model = User.objects.filter(pk=user['id']).first()
        video_model = Video.objects.filter(pk=video_id).first()

        if not user_model or not video_model:
            return send_message(False, "Either user of video not found")

        try:
            new_comment = Comment(comment=body.get('comment'),
                                  user=user_model,
                                  video=video_model)

            new_comment.save()

        except Exception as e:
            return send_message(
                False, "Something went wrong while saving the comment")

        return HttpResponse(
            json.dumps({
                'success': True,
                "comment": new_comment.get_dict()
            }))
コード例 #5
0
ファイル: views.py プロジェクト: jadensiow/File_Sharing_Web
def add_view_count(request, *args, **kwargs):

    if request.method != 'PUT':
        return send_message(False,
                            f"{request.method} not supported on this route")

    video_Id = kwargs.get("videoId")
    video_model = Video.objects.filter(pk=video_Id).first()
    video_model.views += 1

    user = kwargs.get('user')
    user_id = user['id']
    print('user', user)
    viewers_json = json.loads(video_model.viewers)

    viewers_json.append(user_id)
    video_model.viewers = json.dumps(viewers_json)

    video_model.save()

    return HttpResponse(json.dumps({
        "success": True,
        "watchVideo": video_model.get_dict()
    }),
                        content_type="text/json-comment-filtered")
コード例 #6
0
ファイル: views.py プロジェクト: jadensiow/File_Sharing_Web
def channel_page(request, *args, **kwargs):

    user_id = kwargs['id']

    user_model_object = User.objects.filter(pk=user_id).first()

    if not user_model_object:
        return send_message(False, f"User with id {user_id} does not exist")

    channel = Channel.objects.filter(user=user_model_object).first()

    if channel:
        obj_to_return = {}
        obj_to_return['user_id'] = user_id
        obj_to_return['channel_name'] = channel.channel_name
        obj_to_return['channel_description'] = channel.channel_description
        obj_to_return['subscribers'] = channel.subscribers

        all_videos = Video.objects.filter(user=user_model_object)

        videos_list = []

        for video in all_videos:
            v_obj = {**video.get_dict()}

            videos_list.append(v_obj)
        obj_to_return["videos"] = videos_list

    else:
        obj_to_return = {[]}

    return HttpResponse(json.dumps(obj_to_return),
                        content_type='application/json')
コード例 #7
0
ファイル: views.py プロジェクト: jadensiow/File_Sharing_Web
def video_upload(request, *args, **kwargs):
    if request.method == 'POST':
        user = kwargs.get('user')
        video_id = kwargs.get('videoId')

        user_model = User.objects.filter(pk=user['id']).first()

        file_to_upload1 = request.FILES.get('myVid')
        file_to_upload2 = request.FILES.get('myThumbnail')

        try:
            s3_url1 = upload_file(file_to_upload1, user_model.username)
            s3_url2 = upload_file(file_to_upload2, user_model.username)
            print("s3", s3_url1)
        except:
            return send_message(False, "Sorry something went wrong")

        video_data = Video.objects.filter(pk=video_id, user=user_model).first()

        if video_data:
            video_data.videoUrl = s3_url1

            video_data.videoThumbnailUrl = s3_url2

            video_data.save()

        return HttpResponse(
            json.dumps({
                "success": True,
                "message": "File Uploaded Successfully",
                "videoUrl": video_data.videoUrl,
                "videoThumbnailUrl": video_data.videoThumbnailUrl,
            }))
コード例 #8
0
ファイル: views.py プロジェクト: jadensiow/File_Sharing_Web
def user_login(request) -> HttpResponse:
    if request.method != 'POST':
        return HttpResponse(
            json.dumps({
                "success": False,
                "message": f"{request.method} not allowed on this route"
            }),
            content_type="application/json",
        )

    data = json.loads(request.body.decode('utf-8'))
    if not data.get('username') or not data.get('password'):
        return send_message(
            False, "Either username or password not present. Login failed")

    username: str = data['username']
    password: str = data['password']

    user: User = User.objects.filter(username=username).first()

    if not user:
        return send_message(False,
                            f"User with username '{username}' not found")
    '''
    take the user input password and hash it with the same salt use used to 
    hash the original password. Then we compare hashes to see if they're equal
    '''
    password_new = password.encode('utf-8')
    hashed_input_password: bytes = bcrypt.hashpw(password_new,
                                                 user.salt.tobytes())

    if not hashed_input_password == user.password.tobytes():
        return send_message(False, 'Invalid Password')

    jw_token = jwt.encode({
        'username': user.username,
        'id': user.pk
    },
                          key=Config.JWT_SECRET,
                          algorithm=Config.JWT_HASH_ALGO)

    return HttpResponse(json.dumps({
        'success': True,
        'token': jw_token,
        "user": user.get_dict()
    }),
                        status=200)
コード例 #9
0
ファイル: views.py プロジェクト: jadensiow/File_Sharing_Web
def search_videos_channels(request, **kwargs):
    search_for = request.GET.get('searchFor')
    search_query = request.GET.get('searchQuery')

    if len(search_for) == 0 or len(search_query) == 0:
        send_message(False, "Search Query cannot be empty")

    print('\n\nrequest.GET = ', search_for, search_query)

    list_to_return = []
    search_for = search_for.lower()

    if search_for == 'videos':
        videos = Video.objects.filter(
            Q(title__icontains=search_query)
            | Q(description__icontains=search_query))

        if videos:
            for v in videos:
                list_to_return.append(v.get_dict())

        else:
            return send_message(False, "Sorry nothing found")

    elif search_for == 'channels':
        channels = Channel.objects.filter(
            Q(channel_name__icontains=search_query)
            | Q(channel_description__icontains=search_query))

        if channels:
            for c in channels:
                list_to_return.append(c.get_dict())

        else:
            return send_message(False, "Sorry nothing found")

    else:
        return send_message(False, "Invalid Search")

    return HttpResponse(
        json.dumps({
            "results": list_to_return,
            "success": True
        }))
コード例 #10
0
ファイル: views.py プロジェクト: jadensiow/File_Sharing_Web
def edit_post_comments(request, **kwargs):
    if request.method != 'PUT':
        return send_message(False,
                            f"{request.method} not supported on this route")

    # body = (request.body.decode())
    # print(type(body))
    # print("@@BODY@a@", body)
    print(f"\n\n {request.body} \n\n")

    body = json.loads(request.body.decode())

    new_comment = body.get('newComment')

    if not new_comment:
        return send_message(False, "Bad request. No comment found")

    user = kwargs.get('user')
    comment_Id = kwargs.get('commentId')
    user_model = User.objects.filter(pk=user['id']).first()

    # sorry again for this. keep forgetting the .first()

    comment_model = Comment.objects.filter(pk=comment_Id,
                                           user=user_model).first()

    if not comment_model:
        return send_message(False,
                            "Sorry no comment found in database with that id")

    comment_model.comment = new_comment

    # print('comment',comment_model)

    comment_model.save()

    return HttpResponse(
        json.dumps({
            "success": True,
            "message": "Comment details edited Successfully",
            "comment": comment_model.get_dict()
        }))
コード例 #11
0
ファイル: views.py プロジェクト: jadensiow/File_Sharing_Web
def change_video_thumbnail(request, **kwargs):
    if request.method != 'POST':
        return send_message(False,
                            f"{request.method} not supported on this route")

    user = kwargs.get('user')
    video_id = kwargs.get('videoId')

    user_model = User.objects.filter(pk=user['id']).first()
    video_model = Video.objects.filter(pk=video_id).first()

    if video_model.user.id != user_model.id:
        return send_message(False, "You can only edit your own videos")

    new_thumbnail = request.FILES.get('newThumbnail')

    print(f'\n\n file = {new_thumbnail}, files = {request.FILES} \n\n')

    try:
        new_thumbnail_s3_url = upload_file(new_thumbnail, user_model.username)

    except Exception as e:
        print(f'\n\n Exception = {e} \n\n')
        return send_message(
            False, "Something went wrong while uploading the thumbnail")

    urls = get_s3_key_from_s3_url([video_model.videoThumbnailUrl])

    delete_from_s3(urls)

    video_model.videoThumbnailUrl = new_thumbnail_s3_url
    video_model.save()

    return HttpResponse(
        json.dumps({
            "success": True,
            "message": "Successfully uploaded the new thumbnail",
            "video": video_model.get_dict()
        }))
コード例 #12
0
ファイル: views.py プロジェクト: jadensiow/File_Sharing_Web
def get_video(request, **kwargs):
    video_id = kwargs.get('videoId')

    video_model = Video.objects.filter(pk=video_id).first()
    if not video_model:
        return send_message(False, "Video not found")

    video_comments = Comment.objects.filter(
        video=video_model).order_by('-commented_on')

    #print(f"\n\n {request.GET} \n\n")

    user_id = request.GET.get('userId')

    obj_to_return = {
        'video': {},
        'comments': [],
    }

    obj_to_return['video'] = video_model.get_dict()

    user_model = None

    if user_id is not None:
        user_model = User.objects.filter(pk=int(user_id)).first()
        obj_to_return['video']['userLikesVideo'] = user_model.has_liked_video(
            int(video_id))
        obj_to_return['video'][
            'userDislikesVideo'] = user_model.has_disliked_video(int(video_id))

    for comment in video_comments:
        comment_dict = comment.get_dict()

        if user_model:
            comment_dict['userLikesComment'] = user_model.has_liked_comment(
                comment.id)
            comment_dict[
                'userDislikesComment'] = user_model.has_disliked_comment(
                    comment.id)

        else:
            comment_dict['userLikesComment'] = False
            comment_dict['userDislikesComment'] = False

        obj_to_return['comments'].append(comment_dict)

    obj_to_return['success'] = True

    return HttpResponse(json.dumps(obj_to_return),
                        content_type='application/json')
コード例 #13
0
ファイル: views.py プロジェクト: jadensiow/File_Sharing_Web
def get_user_profile_by_id(request, *args, **kwargs) -> HttpResponse:
    user_id: int = kwargs['id']

    user_model: User = User.objects.filter(pk=user_id).first()

    if not user_model:
        return send_message(False, f"User with id '{user_id}' not found")

    response = user_model.get_dict()

    return HttpResponse(json.dumps({
        "success": True,
        'profileInfo': response
    }),
                        content_type="text/json-comment-filtered")
コード例 #14
0
ファイル: views.py プロジェクト: jadensiow/File_Sharing_Web
def user_register(request) -> HttpResponse:
    # request.body is a bytes string so convert it to utf-8
    body = request.body.decode('utf-8')
    data: dict = json.loads(body)

    if not data.get('username') or not data.get('password'):
        return send_message(
            False,
            "Either username or password not present. User creation failed")

    user_exists = User.objects.filter(username=data.get('username')).first()

    if user_exists:
        return send_message(False,
                            f"Username '{user_exists.username}' is taken")

    user = User(username=data.get('username'),
                password=data.get('password'),
                firstName=data.get('firstName'),
                lastName=data.get('lastName'),
                email=data.get('email'))
    user.save(hash_password=True)

    return send_message(True, "User Created successfully")
コード例 #15
0
ファイル: views.py プロジェクト: jadensiow/File_Sharing_Web
def edit_profile_info(request, **kwargs):
    user = kwargs.get('user')
    user_id = kwargs.get('userId')

    if not user['id'] == user_id:
        return send_message(False, "Token mismatch")

    user_model = User.objects.filter(pk=user_id).first()

    new_data = json.loads(request.body.decode())

    new_username = new_data.get('username')
    new_firstName = new_data.get('firstName')
    new_lastName = new_data.get('lastName')
    new_email = new_data.get('email')

    if new_username != user_model.username:
        user_model.username = new_username

    if new_email != user_model.email:
        user_model.email = new_email

    if new_lastName != user_model.lastName:
        user_model.lastName = new_lastName

    if new_firstName != user_model.firstName:
        user_model.firstName = new_firstName

    user_model.save()

    return HttpResponse(
        json.dumps({
            "success": True,
            "message": "Edited Successfully",
            "profileInfo": user_model.get_dict()
        }))