Skip to content

Commit

Permalink
Improvements
Browse files Browse the repository at this point in the history
- Activate rocketchat using other_course_settings
- include create user in create token
- docstrings
- improve code
- Add docstrings
  • Loading branch information
andrey-canon committed Apr 9, 2019
1 parent 54e352b commit a7c8507
Show file tree
Hide file tree
Showing 31 changed files with 406 additions and 254 deletions.
22 changes: 22 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
###############################################
#
# Openedx Rocketchat commands.
#
###############################################

.DEFAULT_GOAL := help

help: ## display this help message
@echo "Please use \`make <target>' where <target> is one of"
@grep '^[a-zA-Z]' $(MAKEFILE_LIST) | sort | awk -F ':.*?## ' 'NF==2 {printf "\033[36m %-25s\033[0m %s\n", $$1, $$2}'

clean: ## delete most git-ignored files
find . -name '__pycache__' -exec rm -rf {} +
find . -name '*.pyc' -exec rm -f {} +

requirements: ## install environment requirements
pip install -r requirements.txt

run-quality-test: clean ## Run quality test.
pycodestyle ./openedx_rocketchat
pylint ./openedx_rocketchat --rcfile=./setup.cfg
2 changes: 1 addition & 1 deletion manage.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import sys

if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "openedx_rocketchat.settings")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "openedx_rocketchat.settings.common")

from django.core.management import execute_from_command_line

Expand Down
3 changes: 0 additions & 3 deletions openedx_rocketchat/admin.py

This file was deleted.

2 changes: 1 addition & 1 deletion openedx_rocketchat/api/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
"""
from django.conf.urls import include, url

urlpatterns = [
urlpatterns = [ # pylint: disable=invalid-name
url(r'^v0/', include('openedx_rocketchat.api.v0.urls', namespace='v0')),
]
16 changes: 15 additions & 1 deletion openedx_rocketchat/api/v0/serializers.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,27 @@
""" RocketChat Serializers """
from rest_framework import serializers


# pylint: disable=abstract-method
class RocketChatCredentialsSerializer(serializers.Serializer):
"""
Serializer for RocketChatCredentials view.
"""
url_service = serializers.CharField()
auth_token = serializers.CharField()
user_id = serializers.CharField()
room_ids = serializers.ListField(child=serializers.CharField())


class RocketChatSubscriptionsIdSerializer(serializers.Serializer):
"""
Serializer for RocketChatSubscriptionsId view.
"""
subscriptions_id = serializers.ListField(child=serializers.CharField())


class RocketChatChangeRoleSerializer(serializers.Serializer):
"""
Serializer for RocketChatChangeRole view.
"""
username = serializers.CharField()
role = serializers.CharField()
2 changes: 1 addition & 1 deletion openedx_rocketchat/api/v0/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from . import views


urlpatterns = [
urlpatterns = [ # pylint: disable=invalid-name
url(r'^credentials', views.RocketChatCredentials.as_view(), name='rocket_chat_credentials'),
url(r'^subscriptions-id', views.RocketChatSubscriptionsId.as_view(), name='rocket_chat_subscriptions'),
url(r'^change-role', views.RocketChatChangeRole.as_view(), name='rocket_chat_change_role'),
Expand Down
72 changes: 47 additions & 25 deletions openedx_rocketchat/api/v0/views.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,48 @@
"""
Openedx RocketChat Api Views.
"""
import logging

from django.core.cache import cache

from openedx_rocketchat.utils import (
create_token, get_rocket_chat_settings,
get_course_from_string,
get_subscriptions_rids,
initialize_api_rocket_chat,
logout,
)
from rest_framework import permissions, status
from rest_framework.authentication import SessionAuthentication
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import permissions
from rest_framework import status

from openedx_rocketchat.edxapp_wrapper.get_opaque_keys import get_course_from_string

from openedx_rocketchat.utils import (
get_rocket_chat_settings,
initialize_api_rocket_chat,
get_subscriptions_rids,
logout,
create_token,
from .serializers import (
RocketChatChangeRoleSerializer,
RocketChatCredentialsSerializer,
RocketChatSubscriptionsIdSerializer
)
from .serializers import *

LOG = logging.getLogger(__name__)


class RocketChatCredentials(APIView):
"""
This class allows to get rocketchat credentials based on the edx user.
"""

authentication_classes = (
SessionAuthentication,
)
permission_classes = (permissions.IsAuthenticated,)

def get(self, request):
def get(self, request): # pylint: disable=no-self-use
"""
Get rocketchat user credentials in order to use rocketchat methods outside the server.
**Query params**
courseId: Unique identifier for every course
**Example Requests**:
GET /rocketchat/api/v0/credentials?courseId=course-v1:ExampleX+Subject101+2015
Expand Down Expand Up @@ -88,13 +98,16 @@ def get(self, request):


class RocketChatSubscriptionsId(APIView):
"""
Class that allows to get the id for every subscription.
"""

authentication_classes = (
SessionAuthentication,
)
permission_classes = (permissions.IsAuthenticated,)

def get(self, request):
def get(self, request): # pylint: disable=no-self-use
"""
Retrieve the rooms' id for every user subscription.
Expand Down Expand Up @@ -126,19 +139,21 @@ def get(self, request):

except Exception as error:
LOG.error("Rocketchat Subscriptions couldn't be got due to %s", error)
pass

return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)
return Response(status=status.HTTP_400_BAD_REQUEST)


class RocketChatChangeRole(APIView):
"""
Class that allows to change the role for a given user.
"""

authentication_classes = (
SessionAuthentication,
)
permission_classes = (permissions.IsAuthenticated,)

def post(self, request):
def post(self, request): # pylint: disable=no-self-use
"""
This methods allows to change the rocketchat role for a specific user
Expand All @@ -153,16 +168,18 @@ def post(self, request):
**Response Values**:
* It doesn't return data
* It doesn't return data on successful.
* {"error": "error reason"} on fail by 400.
"""
if not request.user.is_staff:
return Response(status=status.HTTP_401_UNAUTHORIZED)
return Response(status=status.HTTP_403_FORBIDDEN)

serializer = RocketChatChangeRoleSerializer(data=request.data)

if not serializer.is_valid():
return Response("Data is not valid", status=status.HTTP_400_BAD_REQUEST)
error_message = {"error": "Data is not valid"}
return Response(error_message, status=status.HTTP_400_BAD_REQUEST)

username = serializer.data["username"]
role = serializer.data["role"]
Expand All @@ -178,31 +195,36 @@ def post(self, request):
try:
user_info = user_info.json()
if not user_info.get('success', False):
return Response(user_info.get("error"), status=status.HTTP_400_BAD_REQUEST)
error_message = {"error": user_info.get("error")}
return Response(error_message, status=status.HTTP_400_BAD_REQUEST)

user = user_info.get("user")
data = {"roles": [role]}
response = api_rocket_chat.users_update(user.get("_id"), **data)
if response.status_code == 200:
return Response(status=status.HTTP_204_NO_CONTENT)
return Response(response.json().get("error"), status=status.HTTP_400_BAD_REQUEST)

error_message = {"error": response.json().get("error")}
return Response(error_message, status=status.HTTP_400_BAD_REQUEST)

except AttributeError:
LOG.error("Rocketchat API can not get the user information")
return Response(status=status.HTTP_503_SERVICE_UNAVAILABLE)

LOG.error("Rocketchat API object can not be initialized")
return Response(status=status.HTTP_503_SERVICE_UNAVAILABLE)


class RocketChatCleanToken(APIView):
"""
Clean cache and invalidates the stored token.
"""

authentication_classes = (
SessionAuthentication,
)
permission_classes = (permissions.IsAuthenticated,)

def get(self, request):
def get(self, request): # pylint: disable=no-self-use
"""
Invalidate the rocketchat user data store on the server.
Expand Down Expand Up @@ -230,4 +252,4 @@ def get(self, request):
cache.delete(key)
return Response(status=status.HTTP_202_ACCEPTED)

return Response(status=status.HTTP_401_UNAUTHORIZED)
return Response(status=status.HTTP_400_BAD_REQUEST)
1 change: 1 addition & 0 deletions openedx_rocketchat/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class OpenEdxRocketChatExtensionConfig(AppConfig):
'lms.djangoapp': {
'common': {'relative_path': 'settings.common'},
'aws': {'relative_path': 'settings.aws'},
'production': {'relative_path': 'settings.production'},
},
},
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
""" Backend abstraction """
import os

import edxmako # pylint: disable=import-error
import openedx_rocketchat

Expand Down
10 changes: 4 additions & 6 deletions openedx_rocketchat/edxapp_wrapper/backends/get_courseware.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
""" Backend abstraction """
from courseware.access import has_access
from courseware.courses import get_course_with_access
from courseware.access import has_access # pylint: disable=import-error
from courseware.courses import get_course_with_access # pylint: disable=import-error


def get_has_access(*args, **kwargs):
"""
"""
""" Backend to has_access """
return has_access(*args, **kwargs)


def course_with_access(*args, **kwargs):
"""
"""
""" Backend to get_course_with_acces """
return get_course_with_access(*args, **kwargs)
8 changes: 0 additions & 8 deletions openedx_rocketchat/edxapp_wrapper/backends/get_opaque_keys.py

This file was deleted.

21 changes: 11 additions & 10 deletions openedx_rocketchat/edxapp_wrapper/backends/get_student_models.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,27 @@
""" Backend abstraction """
from student.models import CourseEnrollment, CourseEnrollmentManager, anonymous_id_for_user, get_user
from student.models import ( # pylint: disable=import-error
CourseEnrollment,
CourseEnrollmentManager,
anonymous_id_for_user,
get_user
)


def get_course_enrollment():
"""
"""
""" Backend to CourseEnrollment """
return CourseEnrollment


def get_course_enrollment_manager():
"""
"""
""" Backend to CourseEnrollmentManager """
return CourseEnrollmentManager


def get_anonymous_id_for_edxapp_user(*args, **kwargs):
"""
"""
def get_anonymous_id_for_edxapp_user(*args, **kwargs): # pylint: disable=invalid-name
""" Backend to get anonymous_id_for_user """
return anonymous_id_for_user(*args, **kwargs)


def get_edxapp_user(*args, **kwargs):
"""
"""
""" Backend to get_user """
return get_user(*args, **kwargs)
6 changes: 2 additions & 4 deletions openedx_rocketchat/edxapp_wrapper/get_courseware.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,15 @@


def has_access(*args, **kwargs):
"""
"""
""" Backend to has_access """
backend_function = settings.ROCKETCHAT_COURSEWARE
backend = import_module(backend_function)

return backend.get_has_access(*args, **kwargs)


def get_course_with_access(*args, **kwargs):
"""
"""
""" Backend to get_course_with_acces """
backend_function = settings.ROCKETCHAT_COURSEWARE
backend = import_module(backend_function)

Expand Down
12 changes: 0 additions & 12 deletions openedx_rocketchat/edxapp_wrapper/get_opaque_keys.py

This file was deleted.

Loading

0 comments on commit a7c8507

Please sign in to comment.