From d99be8795a16a8db2fe7eacf1319f2adee63b251 Mon Sep 17 00:00:00 2001 From: Fernando Date: Mon, 9 Oct 2023 16:00:00 -0400 Subject: [PATCH] fix: handlers refactor and format --- .../0002_alter_turnitinsubmission_user.py | 13 +- platform_plugin_turnitin/models.py | 6 +- .../static/html/turnitin.html | 2 +- .../static/js/src/turnitin.js | 2 +- platform_plugin_turnitin/turnitin.py | 37 +-- .../turnitin_client/handlers.py | 280 ------------------ .../turnitin_client/handlers/__init__.py | 21 ++ .../turnitin_client/handlers/api_handler.py | 82 +++++ .../turnitin_client/handlers/eula.py | 38 +++ .../handlers/similarity_reports.py | 69 +++++ .../turnitin_client/handlers/submissions.py | 62 ++++ .../turnitin_client/handlers/utils.py | 13 + setup.py | 3 + 13 files changed, 318 insertions(+), 310 deletions(-) delete mode 100644 platform_plugin_turnitin/turnitin_client/handlers.py create mode 100644 platform_plugin_turnitin/turnitin_client/handlers/__init__.py create mode 100644 platform_plugin_turnitin/turnitin_client/handlers/api_handler.py create mode 100644 platform_plugin_turnitin/turnitin_client/handlers/eula.py create mode 100644 platform_plugin_turnitin/turnitin_client/handlers/similarity_reports.py create mode 100644 platform_plugin_turnitin/turnitin_client/handlers/submissions.py create mode 100644 platform_plugin_turnitin/turnitin_client/handlers/utils.py diff --git a/platform_plugin_turnitin/migrations/0002_alter_turnitinsubmission_user.py b/platform_plugin_turnitin/migrations/0002_alter_turnitinsubmission_user.py index 8ab7e80..1c76869 100644 --- a/platform_plugin_turnitin/migrations/0002_alter_turnitinsubmission_user.py +++ b/platform_plugin_turnitin/migrations/0002_alter_turnitinsubmission_user.py @@ -6,16 +6,19 @@ class Migration(migrations.Migration): - dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), - ('platform_plugin_turnitin', '0001_initial'), + ("platform_plugin_turnitin", "0001_initial"), ] operations = [ migrations.AlterField( - model_name='turnitinsubmission', - name='user', - field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='turnitin_submissions', to=settings.AUTH_USER_MODEL), + model_name="turnitinsubmission", + name="user", + field=models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="turnitin_submissions", + to=settings.AUTH_USER_MODEL, + ), ), ] diff --git a/platform_plugin_turnitin/models.py b/platform_plugin_turnitin/models.py index c499c83..779f20e 100644 --- a/platform_plugin_turnitin/models.py +++ b/platform_plugin_turnitin/models.py @@ -7,6 +7,7 @@ User = get_user_model() + class TurnitinSubmission(models.Model): """ Represents a submission to Turnitin. @@ -20,7 +21,10 @@ class TurnitinSubmission(models.Model): Methods: - __str__: Returns a string representation of the submission, showing its ID and creation date. """ - user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="turnitin_submissions") + + user = models.ForeignKey( + User, on_delete=models.CASCADE, related_name="turnitin_submissions" + ) turnitin_submission_id = models.CharField(max_length=255, blank=True, null=True) turnitin_submission_pdf_id = models.CharField(max_length=255, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) diff --git a/platform_plugin_turnitin/static/html/turnitin.html b/platform_plugin_turnitin/static/html/turnitin.html index 86eb180..db1053c 100644 --- a/platform_plugin_turnitin/static/html/turnitin.html +++ b/platform_plugin_turnitin/static/html/turnitin.html @@ -19,7 +19,7 @@

End User License Agreement (EULA)

File Upload

- + No file selected
diff --git a/platform_plugin_turnitin/static/js/src/turnitin.js b/platform_plugin_turnitin/static/js/src/turnitin.js index acedbd4..13ab409 100644 --- a/platform_plugin_turnitin/static/js/src/turnitin.js +++ b/platform_plugin_turnitin/static/js/src/turnitin.js @@ -81,7 +81,7 @@ function TurnitinXBlock(runtime, element) { } var formData = new FormData(); - formData.append('myfile', file); + formData.append('uploaded_file', file); $.ajax({ type: 'POST', diff --git a/platform_plugin_turnitin/turnitin.py b/platform_plugin_turnitin/turnitin.py index ba2704b..adc2702 100644 --- a/platform_plugin_turnitin/turnitin.py +++ b/platform_plugin_turnitin/turnitin.py @@ -2,6 +2,7 @@ import json from datetime import datetime +from http import HTTPStatus import pkg_resources from django.contrib.auth.models import User @@ -96,10 +97,14 @@ def get_user_data(self): """ user_service = self.runtime.service(self, "user") current_user = user_service.get_current_user() + user_full_name = current_user.full_name.split() return { "user_id": current_user.opt_attrs["edx-platform.user_id"], "user_email": current_user.emails[0], - "user_name": current_user.full_name.split(), + "user_name": user_full_name[0] if user_full_name else "no_name", + "user_last_name": " ".join(user_full_name[1:]) + if len(user_full_name) > 1 + else "no_last_name", } @XBlock.json_handler @@ -147,7 +152,6 @@ def create_turnitin_submission_object(self): Response: The response from the Turnitin submission API. """ user_data = self.get_user_data() - user_name = user_data["user_name"] date_now = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ") payload = { @@ -161,19 +165,15 @@ def create_turnitin_submission_object(self): "owners": [ { "id": user_data["user_id"], - "given_name": user_name[0] if user_name else "no_name", - "family_name": " ".join(user_name[1:]) - if len(user_name) > 1 - else "no_last_name", + "given_name": user_data["user_name"], + "family_name": user_data["user_last_name"], "email": user_data["user_email"], } ], "submitter": { "id": user_data["user_id"], - "given_name": user_name[0] if user_name else "no_name", - "family_name": " ".join(user_name[1:]) - if len(user_name) > 1 - else "no_last_name", + "given_name": user_data["user_name"], + "family_name": user_data["user_last_name"], "email": user_data["user_email"], }, "original_submitted_time": date_now, @@ -194,7 +194,7 @@ def upload_turnitin_submission_file(self, data, suffix=""): Response: The response after uploading the file to Turnitin. """ turnitin_submission = self.create_turnitin_submission_object() - if turnitin_submission.status_code == 201: + if turnitin_submission.status_code == HTTPStatus.CREATED: turnitin_submission_id = turnitin_submission.json()["id"] current_user_id = self.get_user_data()["user_id"] current_user = User.objects.get(id=current_user_id) @@ -202,10 +202,9 @@ def upload_turnitin_submission_file(self, data, suffix=""): user=current_user, turnitin_submission_id=turnitin_submission_id ) submission.save() - myfile = data.params["myfile"].file - # turnitin_submission_id='0a966646-83f9-4ce6-aa47-71e07baf4e30' + uploaded_file = data.params["uploaded_file"].file response = put_upload_submission_file_content( - turnitin_submission_id, myfile + turnitin_submission_id, uploaded_file ) return Response( json.dumps(response.json()), @@ -238,7 +237,6 @@ def get_submission_status(self, data, suffix=""): ).latest("created_at") except TurnitinSubmission.DoesNotExist: return {"success": False} - # last_submission = 'de6784c5-471f-4220-aff1-16b6b44dffcf' response = get_submission_info(last_submission.turnitin_submission_id) return response.json() @@ -296,7 +294,6 @@ def generate_similarity_report(self, data, suffix=""): ).latest("created_at") except TurnitinSubmission.DoesNotExist: return {"success": False} - # last_submission = 'de6784c5-471f-4220-aff1-16b6b44dffcf' response = put_generate_similarity_report( last_submission.turnitin_submission_id, payload ) @@ -322,7 +319,6 @@ def get_similarity_report_status(self, data, suffix=""): ).latest("created_at") except TurnitinSubmission.DoesNotExist: return {"success": False} - # last_submission = 'de6784c5-471f-4220-aff1-16b6b44dffcf' response = get_similarity_report_info(last_submission.turnitin_submission_id) return response.json() @@ -355,10 +351,8 @@ def create_similarity_viewer(self, data, suffix=""): "view_settings": {"save_changes": True}, }, "author_metadata_override": { - "family_name": " ".join(user_name[1:]) - if len(user_name) > 1 - else "no_last_name", - "given_name": user_name[0] if user_name else "no_name", + "family_name": user_data["user_last_name"], + "given_name": user_data["user_name"], }, "sidebar": {"default_mode": "similarity"}, } @@ -369,7 +363,6 @@ def create_similarity_viewer(self, data, suffix=""): ).latest("created_at") except TurnitinSubmission.DoesNotExist: return {"success": False} - # last_submission = 'de6784c5-471f-4220-aff1-16b6b44dffcf' response = post_create_viewer_launch_url( last_submission.turnitin_submission_id, payload ) diff --git a/platform_plugin_turnitin/turnitin_client/handlers.py b/platform_plugin_turnitin/turnitin_client/handlers.py deleted file mode 100644 index f1e674b..0000000 --- a/platform_plugin_turnitin/turnitin_client/handlers.py +++ /dev/null @@ -1,280 +0,0 @@ -import json -from typing import Dict, Optional - -import requests - -from django.conf import settings - - -def turnitin_api_handler( - request_method: str, - url_prefix: str = "", - data: Optional[Dict] = None, - is_upload: bool = False, - uploaded_file=None, -): - """ - Handles API requests to the Turnitin service. - - Parameters: - - request_method (str): The HTTP method (e.g., 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'). - - data (dict): The payload to be sent in the request. Use None for methods that don't require a payload. - - url_prefix (str): The endpoint suffix for the API URL. - - Returns: - - Response: A requests.Response object containing the server's response to the request. - - Raises: - - ValueError: If an unsupported request method is provided. - """ - - # Configuration variables - TII_API_URL = getattr(settings, "TURNITIN_TII_API_URL", None) - TCA_INTEGRATION_FAMILY = getattr(settings, "TURNITIN_TCA_INTEGRATION_FAMILY", None) - TCA_INTEGRATION_VERSION = getattr(settings, "TURNITIN_TCA_INTEGRATION_VERSION", None) - TCA_API_KEY = getattr(settings, "TURNITIN_TCA_API_KEY", None) - - # Headers configuration - headers = { - "X-Turnitin-Integration-Name": TCA_INTEGRATION_FAMILY, - "X-Turnitin-Integration-Version": TCA_INTEGRATION_VERSION, - "Authorization": f"Bearer {TCA_API_KEY}", - } - - # Add Content-Type for methods that typically send JSON payload - if request_method.lower() in ["post", "put", "patch"]: - headers["Content-Type"] = "application/json" - - if is_upload: - headers["Content-Type"] = "binary/octet-stream" - headers["Content-Disposition"] = f'inline; filename="{uploaded_file.name}"' - response = requests.put( - f"{TII_API_URL}/api/v1/{url_prefix}", headers=headers, data=uploaded_file - ) - return response - - # Mapping of methods to corresponding functions in the requests library - method_map = { - "get": requests.get, - "post": requests.post, - "put": requests.put, - "delete": requests.delete, - "patch": requests.patch, - } - - # Retrieving the correct function - method_func = method_map.get(request_method.lower()) - - if not method_func: - raise ValueError(f"Unsupported request method: {request_method}") - - # Calling the appropriate method - if request_method.lower() in ["post", "put", "patch"]: - response = method_func( - f"{TII_API_URL}/api/v1/{url_prefix}", headers=headers, json=data - ) - else: - response = method_func( - f"{TII_API_URL}/api/v1/{url_prefix}", headers=headers, params=data - ) - - return response - - -def pretty_print_response(response, type_of=""): - """debug helper function""" - content = response.json() - print("\n\n") - print(f"------{type_of}------") - print("\n\n") - print(json.dumps(content, indent=4)) - print("\n\n") - print("------------") - print("\n\n") - - -# Returns all the features enabled in Turnitin account. -def get_features_enabled(): - """ - Returns all the features enabled in the Turnitin account. - """ - response = turnitin_api_handler("get", "features-enabled") - pretty_print_response(response) - - -# *---EULA endpoints ---* -# The EULA is a page of terms and conditions that the owner and the -# submiter has to accept in order to send a file to Turnitin. - - -def get_eula_version_info(version: str = "latest", language: str = "EN"): - """ - Returns Turnitin's EULA (End User License Agreement) version information. - The EULA is a page of terms and conditions that both the owner and the submitter - have to accept in order to send a file to Turnitin. - """ - response = turnitin_api_handler("get", f"eula/{version}?lang={language}") - pretty_print_response(response) - - -def get_eula_page(version: str = "v1beta", language: str = "en-US"): - """ - Returns the HTML content for a specified EULA version. - """ - response = turnitin_api_handler("get", f"/eula/{version}/view?lang={language}") - return response - - -def post_accept_eula_version(payload, version: str = "v1beta"): - """ - Accepts a specific EULA version. - This method should be invoked after the user has viewed the EULA content. - """ - response = turnitin_api_handler("post", f"eula/{version}/accept", payload) - pretty_print_response(response, "ACCEPT EULA") - return response - - -def get_eula_acceptance_by_user(user_id): - """ - Checks if a specific user has accepted a particular EULA version. - """ - response = turnitin_api_handler("get", f"eula/v1beta/accept/{user_id}") - pretty_print_response(response) - - -# *---Submissions endpoints ---* -# Submissions is a Turnithin model that has all relative info to a Assessment send by -# an student. - - -def post_create_submission(payload): - """ - Creates a submission object in Turnitin and returns an associated ID. - This relates to the Turnitin model which contains all information - related to an assessment sent by a student. - """ - response = turnitin_api_handler("post", "submissions", payload) - pretty_print_response(response, "CREATE SUBMISSION") - return response - - -def put_upload_submission_file_content(submission_id, file): - """ - Attaches a document to a student's submission. - """ - response = turnitin_api_handler( - "put", - f"submissions/{submission_id}/original", - is_upload=True, - uploaded_file=file, - ) - pretty_print_response(response, "UPLOAD FILE") - return response - - -def get_submission_info(submission_id): - """ - Fetches all the information related to a specific submission. - - Status: - CREATED Submission has been created but no file has been uploaded - PROCESSING File contents have been uploaded and the submission is being processed - COMPLETE Submission processing is complete - ERROR An error occurred during submission processing; see error_code for details - - """ - response = turnitin_api_handler("get", f"submissions/{submission_id}") - pretty_print_response(response, "SUBMISSION STATUS") - return response - - -def delete_submission(submission_id, is_hard_delete="false"): - """ - Deletes a submission by its ID. - The deletion can either be a hard delete or a soft delete based on the parameter provided. - """ - response = turnitin_api_handler( - "delete", f"submissions/{submission_id}/?hard={is_hard_delete}" - ) - pretty_print_response(response) - - -def put_recover_submission(submission_id): - """ - Recovers a submission that has been soft deleted - """ - response = turnitin_api_handler("put", f"submissions/{submission_id}/recover") - pretty_print_response(response) - - -# *---Similarity endpoints ---* -# Similarity is a Turnithin report with an internet similarity detection -# score of the student submissions. - - -def put_generate_similarity_report(submission_id, payload): - """ - Turnitin begin to process the doc to generate the report. - """ - response = turnitin_api_handler( - "put", f"submissions/{submission_id}/similarity", payload - ) - pretty_print_response(response, "REPORT GENERATION") - return response - - -def get_similarity_report_info(submission_id): - """ - Returns summary information about the requested Similarity Report. - Status: - PROCESSING - COMPLETE - """ - response = turnitin_api_handler("get", f"submissions/{submission_id}/similarity") - pretty_print_response(response, "REPORT STATUS") - return response - - -def post_create_viewer_launch_url(submission_id, payload): - """ - So that users can interact with the details of a submission and Similarity Report, - Turnitin provides a purpose-built viewer to enable smooth interaction with the - report details and submitted document. - """ - response = turnitin_api_handler( - "post", f"submissions/{submission_id}/viewer-url", payload - ) - pretty_print_response(response, "URL VIEWER") - return response - - -def post_generate_similarity_report_pdf(submission_id): - """ - This endpoint generates Similarty Report pdf and returns an ID that can be used in - a subsequent API call to download a pdf file. - """ - response = turnitin_api_handler( - "post", f"submissions/{submission_id}/similarity/pdf" - ) - pretty_print_response(response) - - -def get_similarity_report_pdf(submission_id, pdf_id): - """ - This endpoint returns the Similarity Report pdf file as stream of bytes. - """ - response = turnitin_api_handler( - "get", f"submissions/{submission_id}/similarity/pdf/{pdf_id}" - ) - pretty_print_response(response) - - -def get_similarity_report_pdf_status(submission_id, pdf_id): - """ - This endpoint returns the requested Similarity Report pdf status. - """ - response = turnitin_api_handler( - "get", f"submissions/{submission_id}/similarity/pdf/{pdf_id}/status" - ) - pretty_print_response(response) diff --git a/platform_plugin_turnitin/turnitin_client/handlers/__init__.py b/platform_plugin_turnitin/turnitin_client/handlers/__init__.py new file mode 100644 index 0000000..16e2230 --- /dev/null +++ b/platform_plugin_turnitin/turnitin_client/handlers/__init__.py @@ -0,0 +1,21 @@ +from .eula import ( + get_eula_acceptance_by_user, + get_eula_page, + get_eula_version_info, + post_accept_eula_version, +) +from .similarity_reports import ( + get_similarity_report_info, + get_similarity_report_pdf, + get_similarity_report_pdf_status, + post_create_viewer_launch_url, + post_generate_similarity_report_pdf, + put_generate_similarity_report, +) +from .submissions import ( + delete_submission, + get_submission_info, + post_create_submission, + put_recover_submission, + put_upload_submission_file_content, +) diff --git a/platform_plugin_turnitin/turnitin_client/handlers/api_handler.py b/platform_plugin_turnitin/turnitin_client/handlers/api_handler.py new file mode 100644 index 0000000..5cbd94f --- /dev/null +++ b/platform_plugin_turnitin/turnitin_client/handlers/api_handler.py @@ -0,0 +1,82 @@ +from typing import Dict, Optional + +import requests +from django.conf import settings + +from .utils import pretty_print_response + +TII_API_URL = getattr(settings, "TURNITIN_TII_API_URL", None) +TCA_INTEGRATION_FAMILY = getattr(settings, "TURNITIN_TCA_INTEGRATION_FAMILY", None) +TCA_INTEGRATION_VERSION = getattr(settings, "TURNITIN_TCA_INTEGRATION_VERSION", None) +TCA_API_KEY = getattr(settings, "TURNITIN_TCA_API_KEY", None) + + +def turnitin_api_handler( + request_method: str, + url_prefix: str = "", + data: Optional[Dict] = None, + is_upload: bool = False, + uploaded_file=None, +): + """ + Handles API requests to the Turnitin service. + + Parameters: + - request_method (str): The HTTP method (e.g., 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'). + - data (dict): The payload to be sent in the request. Use None for methods that don't require a payload. + - url_prefix (str): The endpoint suffix for the API URL. + + Returns: + - Response: A requests.Response object containing the server's response to the request. + + Raises: + - ValueError: If an unsupported request method is provided. + """ + headers = { + "X-Turnitin-Integration-Name": TCA_INTEGRATION_FAMILY, + "X-Turnitin-Integration-Version": TCA_INTEGRATION_VERSION, + "Authorization": f"Bearer {TCA_API_KEY}", + } + + if request_method.lower() in ["post", "put", "patch"]: + headers["Content-Type"] = "application/json" + + if is_upload: + headers["Content-Type"] = "binary/octet-stream" + headers["Content-Disposition"] = f'inline; filename="{uploaded_file.name}"' + response = requests.put( + f"{TII_API_URL}/api/v1/{url_prefix}", headers=headers, data=uploaded_file + ) + return response + + method_map = { + "get": requests.get, + "post": requests.post, + "put": requests.put, + "delete": requests.delete, + "patch": requests.patch, + } + + method_func = method_map.get(request_method.lower()) + + if not method_func: + raise ValueError(f"Unsupported request method: {request_method}") + + if request_method.lower() in ["post", "put", "patch"]: + response = method_func( + f"{TII_API_URL}/api/v1/{url_prefix}", headers=headers, json=data + ) + else: + response = method_func( + f"{TII_API_URL}/api/v1/{url_prefix}", headers=headers, params=data + ) + + return response + + +def get_features_enabled(): + """ + Returns all the features enabled in the Turnitin account. + """ + response = turnitin_api_handler("get", "features-enabled") + pretty_print_response(response) diff --git a/platform_plugin_turnitin/turnitin_client/handlers/eula.py b/platform_plugin_turnitin/turnitin_client/handlers/eula.py new file mode 100644 index 0000000..25e79d1 --- /dev/null +++ b/platform_plugin_turnitin/turnitin_client/handlers/eula.py @@ -0,0 +1,38 @@ +from .api_handler import turnitin_api_handler +from .utils import pretty_print_response + + +def get_eula_version_info(version: str = "latest", language: str = "EN"): + """ + Returns Turnitin's EULA (End User License Agreement) version information. + The EULA is a page of terms and conditions that both the owner and the submitter + have to accept in order to send a file to Turnitin. + """ + response = turnitin_api_handler("get", f"eula/{version}?lang={language}") + pretty_print_response(response) + + +def get_eula_page(version: str = "v1beta", language: str = "en-US"): + """ + Returns the HTML content for a specified EULA version. + """ + response = turnitin_api_handler("get", f"/eula/{version}/view?lang={language}") + return response + + +def post_accept_eula_version(payload, version: str = "v1beta"): + """ + Accepts a specific EULA version. + This method should be invoked after the user has viewed the EULA content. + """ + response = turnitin_api_handler("post", f"eula/{version}/accept", payload) + pretty_print_response(response, "ACCEPT EULA") + return response + + +def get_eula_acceptance_by_user(user_id): + """ + Checks if a specific user has accepted a particular EULA version. + """ + response = turnitin_api_handler("get", f"eula/v1beta/accept/{user_id}") + pretty_print_response(response) diff --git a/platform_plugin_turnitin/turnitin_client/handlers/similarity_reports.py b/platform_plugin_turnitin/turnitin_client/handlers/similarity_reports.py new file mode 100644 index 0000000..2f61ef3 --- /dev/null +++ b/platform_plugin_turnitin/turnitin_client/handlers/similarity_reports.py @@ -0,0 +1,69 @@ +from .api_handler import turnitin_api_handler +from .utils import pretty_print_response + + +def put_generate_similarity_report(submission_id, payload): + """ + Turnitin begin to process the doc to generate the report. + """ + response = turnitin_api_handler( + "put", f"submissions/{submission_id}/similarity", payload + ) + pretty_print_response(response, "REPORT GENERATION") + return response + + +def get_similarity_report_info(submission_id): + """ + Returns summary information about the requested Similarity Report. + Status: + PROCESSING + COMPLETE + """ + response = turnitin_api_handler("get", f"submissions/{submission_id}/similarity") + pretty_print_response(response, "REPORT STATUS") + return response + + +def post_create_viewer_launch_url(submission_id, payload): + """ + So that users can interact with the details of a submission and Similarity Report, + Turnitin provides a purpose-built viewer to enable smooth interaction with the + report details and submitted document. + """ + response = turnitin_api_handler( + "post", f"submissions/{submission_id}/viewer-url", payload + ) + pretty_print_response(response, "URL VIEWER") + return response + + +def post_generate_similarity_report_pdf(submission_id): + """ + This endpoint generates Similarty Report pdf and returns an ID that can be used in + a subsequent API call to download a pdf file. + """ + response = turnitin_api_handler( + "post", f"submissions/{submission_id}/similarity/pdf" + ) + pretty_print_response(response) + + +def get_similarity_report_pdf(submission_id, pdf_id): + """ + This endpoint returns the Similarity Report pdf file as stream of bytes. + """ + response = turnitin_api_handler( + "get", f"submissions/{submission_id}/similarity/pdf/{pdf_id}" + ) + pretty_print_response(response) + + +def get_similarity_report_pdf_status(submission_id, pdf_id): + """ + This endpoint returns the requested Similarity Report pdf status. + """ + response = turnitin_api_handler( + "get", f"submissions/{submission_id}/similarity/pdf/{pdf_id}/status" + ) + pretty_print_response(response) diff --git a/platform_plugin_turnitin/turnitin_client/handlers/submissions.py b/platform_plugin_turnitin/turnitin_client/handlers/submissions.py new file mode 100644 index 0000000..369b68c --- /dev/null +++ b/platform_plugin_turnitin/turnitin_client/handlers/submissions.py @@ -0,0 +1,62 @@ +from .api_handler import turnitin_api_handler +from .utils import pretty_print_response + + +def post_create_submission(payload): + """ + Creates a submission object in Turnitin and returns an associated ID. + This relates to the Turnitin model which contains all information + related to an assessment sent by a student. + """ + response = turnitin_api_handler("post", "submissions", payload) + pretty_print_response(response, "CREATE SUBMISSION") + return response + + +def put_upload_submission_file_content(submission_id, file): + """ + Attaches a document to a student's submission. + """ + response = turnitin_api_handler( + "put", + f"submissions/{submission_id}/original", + is_upload=True, + uploaded_file=file, + ) + pretty_print_response(response, "UPLOAD FILE") + return response + + +def get_submission_info(submission_id): + """ + Fetches all the information related to a specific submission. + + Status: + CREATED Submission has been created but no file has been uploaded + PROCESSING File contents have been uploaded and the submission is being processed + COMPLETE Submission processing is complete + ERROR An error occurred during submission processing; see error_code for details + + """ + response = turnitin_api_handler("get", f"submissions/{submission_id}") + pretty_print_response(response, "SUBMISSION STATUS") + return response + + +def delete_submission(submission_id, is_hard_delete="false"): + """ + Deletes a submission by its ID. + The deletion can either be a hard delete or a soft delete based on the parameter provided. + """ + response = turnitin_api_handler( + "delete", f"submissions/{submission_id}/?hard={is_hard_delete}" + ) + pretty_print_response(response) + + +def put_recover_submission(submission_id): + """ + Recovers a submission that has been soft deleted + """ + response = turnitin_api_handler("put", f"submissions/{submission_id}/recover") + pretty_print_response(response) diff --git a/platform_plugin_turnitin/turnitin_client/handlers/utils.py b/platform_plugin_turnitin/turnitin_client/handlers/utils.py new file mode 100644 index 0000000..8da4971 --- /dev/null +++ b/platform_plugin_turnitin/turnitin_client/handlers/utils.py @@ -0,0 +1,13 @@ +import json + + +def pretty_print_response(response, type_of=""): + """debug helper function""" + content = response.json() + print("\n\n") + print(f"------{type_of}------") + print("\n\n") + print(json.dumps(content, indent=4)) + print("\n\n") + print("------------") + print("\n\n") diff --git a/setup.py b/setup.py index db68a7e..12578a7 100755 --- a/setup.py +++ b/setup.py @@ -150,6 +150,9 @@ def is_requirement(line): "lms.djangoapp": [ "platform_plugin_turnitin = platform_plugin_turnitin.apps:PlatformPluginTurnitinConfig" ], + "cms.djangoapp": [ + "platform_plugin_turnitin = platform_plugin_turnitin.apps:PlatformPluginTurnitinConfig" + ], "xblock.v1": [ "turnitin = platform_plugin_turnitin.turnitin:TurnitinXBlock", ],