def user_list(request):
    """
    List all users.
    """
    if request.method == GET:
        try:
            return getUsers()
        except Exception as e:
            return returnExceptionResult(e, logger)

    elif request.method == POST:
        try:
            return createUser(request)
        except Exception as e:
            return returnExceptionResult(e, logger)
def updateDocumentStart(request, docId, userId):
    try:
        doc = Document(documentId=docId)
        user = DocUser(userId=userId)

        if request.method == POST:
            try:
                try:
                    document = Document.objects.get(pk=docId)
                except Document.DoesNotExist:
                    response_data = {RESULT: FAILURE, MESSAGE: 'Document not found'}
                    return JsonResponse(response_data, status=404)
                # Check if document has permissions for edit and if the owner is performing any edits
                if isDocumentPermissionForUser(document, userId) and not isOwnerUpdatingDocument(document):
                    # create a record stating that the user has started editing the file
                    documentEdit = DocumentEdits(userId=user, documentId=doc)
                    documentEdit.save()
                    response_data = {RESULT: SUCCESS}
                    return JsonResponse(response_data, status=201)
                else:
                    # Unauthorize
                    response_data = {RESULT: FAILURE, MESSAGE: 'Access denied'}
                    return JsonResponse(response_data, status=401)

            except IntegrityError:
                logger.error("Error while fetching user and/or documents")
                response_data = {RESULT: FAILURE, MESSAGE: 'Document/User not found'}
                return JsonResponse(response_data, status=404)
    except Exception as e:
        return returnExceptionResult(e, logger)
def downloadDocument(request, docId, userId):
    """
    downlaod document specified by @docId for the user with userId @userId
    """
    try:
        try:
            document = Document.objects.get(pk=docId)
        except Document.DoesNotExist:
            response_data = {RESULT: FAILURE, MESSAGE: 'Document not found'}
            return JsonResponse(response_data, status=404)

        # Assuming that permissions are required for downloading: check for permissions
        if userId != document.ownerId.userId and not isDocumentPermissionForUser(document, userId):
            response_data = {RESULT: FAILURE, MESSAGE: 'User not authorised'}
            return JsonResponse(response_data, status=401)

        if request.method == GET:
            # check if owner is updating the document
            if not isOwnerUpdatingDocument(document):
                try:
                    return downloadFile(document.docPath, document.docName, userId == document.ownerId.userId)
                    # response_data = {RESULT: SUCCESS}
                    # return JsonResponse(response_data, status=201)
                except Exception:
                    response_data = {RESULT: FAILURE, MESSAGE: ERROR_MESSAGE}
                    return JsonResponse(response_data, status=500)
            else:
                response_data = {RESULT: FAILURE, MESSAGE: 'Owner is performing edits. Access denied'}
                return JsonResponse(response_data, status=401)
    except Exception as e:
        return returnExceptionResult(e, logger)
def document_control(request):
    #
    # """
    # List all users.
    # """
    if request.method == GET:
        try:
            return getDocument()
        except Exception as e:
            return returnExceptionResult(e, logger)

    elif request.method == POST:
        try:
            return createDocument(request)
        except Exception as e:
            return returnExceptionResult(e, logger)
def grantDocumentPermission(request):
    """
    grant permission to a user by the owner of the document
    """

    try:
        data = JSONParser().parse(request)
        ownerId = data["ownerId"]
        docId = data["documentId"]
        userId = data["userId"]

        try:
            document = Document.objects.get(pk=docId)
        except Document.DoesNotExist:
            logger.warning("Document with docId: " + str(docId) + " not found")
            response_data = {RESULT: FAILURE, MESSAGE: 'Document not found'}
            return JsonResponse(response_data, status=404)

        # if the requesting user is not the owner, then deny access
        if document.ownerId.userId != ownerId:
            response_data = {RESULT: FAILURE, MESSAGE: 'Not enough permissions to grant access'}
            return JsonResponse(response_data, status=401)

        # try:
        #     user = DocUser.objects.get(pk=userId)
        # except DocUser.DoesNotExist:
        #     logger.warning("User with userId: " + userId + " not found")
        #     response_data = {RESULT: FAILURE, MESSAGE: 'User not found'}
        #     return JsonResponse(response_data, status=404)

        # if owner is requesting access for itself then state that user already has access
        if ownerId == userId:
            response_data = {RESULT: SUCCESS, MESSAGE: 'Already an owner'}
            return JsonResponse(response_data, status=200)

        try:
            # add permissions to DB
            documentPermission = DocumentPermissions(documentId=Document(documentId=data["documentId"]),
                                                     userId=DocUser(userId=data["userId"]))
            documentPermission.save()

            response_data = {RESULT: SUCCESS, MESSAGE: 'Succesfully saved in DB'}
            return JsonResponse(response_data, status=201)

        # in case of permissions being already present, state that permission exists
        except IntegrityError:
            response_data = {RESULT: SUCCESS, MESSAGE: 'Already has permissions'}
            return JsonResponse(response_data, status=200)

    except Exception as e:
        return returnExceptionResult(e, logger)
def getUserById(request, userId):
    # """
    # Retrieve a user with userId PK.
    # """
    try:
        try:
            user = DocUser.objects.get(pk=userId)
        except DocUser.DoesNotExist:
            return HttpResponse(status=404)
        if request.method == GET:
            serializer = DocUserSerializer(user)
            return JsonResponse(serializer.data, status=200)
    except Exception as e:
        return returnExceptionResult(e, logger)
def updateDocumentEnd(request, docId, userId):
    """
    finish updating the file
    """

    try:
        document = Document(documentId=docId)
        user = DocUser(userId=userId)
        docEdit=isUserUpdatingDocument(document, userId)
        if not docEdit:
            response_data = {RESULT: FAILURE, MESSAGE: 'User is not permforming edits yet.'}
            return JsonResponse(response_data, status=401)
        if request.method == POST:
            try:
                try:
                    doc = Document.objects.get(pk=docId)
                except Document.DoesNotExist:
                    response_data = {RESULT: FAILURE, MESSAGE: 'Document not found'}
                    return JsonResponse(response_data, status=404)
                if userId == doc.ownerId.userId or not isOwnerUpdatingDocument(doc):
                    # TODO: if the edit has been cancelled then remove the edit and ask user to reload
                    if docEdit.editIsValid:
                        uploadFile(request, doc.docPath, doc.docName)
                    # TODO: if file has been opened for other edits then cancel those edits
                        invalidateEdits(document)
                        response_data = {RESULT: SUCCESS}
                        status=200
                    else:
                        response_data = {RESULT: FAILURE, MESSAGE: "Reload the document"}
                        status=406
                    docEdit.delete()

                    return JsonResponse(response_data, status=status)
                else:
                    response_data = {RESULT: FAILURE, MESSAGE: 'Owner is performing edits. Access denied'}
                    return JsonResponse(response_data, status=401)

            except IntegrityError:
                logger.error("Error while fetching user and/or documents")
                response_data = {RESULT: FAILURE, MESSAGE: 'Document/User not found'}
                return JsonResponse(response_data, status=404)
    except Exception as e:
        return returnExceptionResult(e, logger)