diff --git a/kitchen_counter/Blockchain2/web3User.py b/kitchen_counter/Blockchain2/web3User.py index 404b383..35a3005 100755 --- a/kitchen_counter/Blockchain2/web3User.py +++ b/kitchen_counter/Blockchain2/web3User.py @@ -1,8 +1,10 @@ - from web3 import Web3 +from web3.middleware import geth_poa_middleware + web3 = Web3(Web3.HTTPProvider("https://rpc-amoy.polygon.technology/")) # CAddress = '0x953113427cdCA32e360727d1298f9B83f06c23a6' +web3.middleware_onion.inject(geth_poa_middleware, layer=0) def get_user_Balance(public_key): # Get the balance of the Ethereum address @@ -14,14 +16,16 @@ def get_user_Balance(public_key): def get_transction_recipt(tx): - print(tx,"txx") response = web3.eth.get_transaction_receipt(tx) - print(response) - return response + timestamp = web3.eth.get_block(response.blockNumber).timestamp + return response,timestamp +# get_transction_recipt("0xfacda3343495205bf1de5cfe096290c82c6fafcf319844935139b883e00c47c8") - - +def mypublickey(key): + acc1 = web3.eth.account.from_key(key).address + return acc1 + diff --git a/kitchen_counter/auto_email/email/EMAILSheet39.xlsx b/kitchen_counter/auto_email/email/EMAILSheet39.xlsx index 87c596c..ea5b7d5 100644 Binary files a/kitchen_counter/auto_email/email/EMAILSheet39.xlsx and b/kitchen_counter/auto_email/email/EMAILSheet39.xlsx differ diff --git a/kitchen_counter/conversion/management/commands/custom_runserver.py b/kitchen_counter/conversion/management/commands/custom_runserver.py index 4281afc..18ba5ec 100755 --- a/kitchen_counter/conversion/management/commands/custom_runserver.py +++ b/kitchen_counter/conversion/management/commands/custom_runserver.py @@ -11,12 +11,7 @@ from django.core.management import call_command from mnfapp.models import ScriptTranslations from MNF.settings import BasePath from conversion.translation.external_conversion import Conversion -from centralisedFileSystem.models import Script, File -from scriptAudit.models import ScriptAuditModel -from scriptAudit.models import States -from utils import filesystem, utilities -from scriptAudit.utils import update_audit_status -from scriptAudit.mnf_script_audit import NeutralAudit +from scriptAudit.views import run_audit_in_counter from django.core.files.base import ContentFile from django.contrib.auth import get_user_model from users.models import UserCredentialsForBlockchain @@ -74,12 +69,6 @@ def run_conversion(msg): def run_audit(msg): - from Blockchain2.decryption import decryptionOfPrivate, decryptionOfUrl, download_file_System,decryptionOflocalUrl,hash_decrypation - from Blockchain2.DataStorage import uploadDataToIPFSNode - from Blockchain2.scriptAudit import getUserprojectIds,UploadScriptAuditData,getScriptAudit - from Blockchain2.blockchainsetting import OWNER_KEY - - print("Hello World inside ") body_dict = json.loads(msg.body) msg.delete() user = body_dict.get("user") @@ -100,453 +89,17 @@ def run_audit(msg): ) print(object_key, local_file_path) s3_client.download_file("conversion-kitchen", object_key, local_file_path) - print("113") - - with open(local_file_path, 'rb') as file: - file_content = file.read() - - file = ContentFile( - file_content, - script_file_name, - ) - - user = User.objects.get(username=user) - - result = filesystem.new_screenplay_without_audit_in_background( - user, - author, - screenplay_name, - file, - "script-original", - language, - ) - - - script_id = result.get("script", {}).get("id") - - file_to_original = File.objects.get( - script=script_id, - type="script-original" - - ) - try: - update_audit_status(script_id, States.STARTED) - except: - update_audit_status(script_id, States.FAILURE) - - - try: - - audit = NeutralAudit(script_id) - audit.audit_in_background() - ScriptAuditModel.objects.update_or_create( - script = Script.objects.get( - id = script_id - ), - defaults={"status" : "SUCCESS"} - ) - - - - except: - ScriptAuditModel.objects.update_or_create( - script = Script.objects.get( - id = script_id - ), - defaults={"status" : "FAILURE"} - ) - - status = ScriptAuditModel.objects.get( - script = Script.objects.get( - id = script_id - )) - print("STATUS AUDIT",status) - status.only_audit = True - # Blockchain - # if UserCredentialsForBlockchain.objects.filter(user=request.user).exists(): - blockchain_obj = UserCredentialsForBlockchain.objects.get(user=user) - script_original= {} - audit_data={} - script_original["status"] = "STARTED" - script_original["script_id"] = script_id - with open(file_to_original.file.path, 'rb') as file: - hash = uploadDataToIPFSNode(file) - script_original["script_file"] = hash - script_original["type"] = "script-original" - script_original["script_file_path"] = file_to_original.file.path - audit_data["script-original"] = script_original - userkey= decryptionOfPrivate(blockchain_obj.privateKey) - print("userkey = ", str(userkey)) - print("blockchain_obj.publicKey",blockchain_obj.publicKey) - print("blockchain_obj.privateKey",blockchain_obj.privateKey) - if status.status == "SUCCESS": - - if script_ext == "fdx": - - file_to_audit = File.objects.get( - script=script_id, - type="script-csv" - ) - hash2 = "" - hash2_docx = "" - try: - file_to_audit_docx = File.objects.get( - script=script_id, - type="script-docx" - ) - script_docx = {} - script_path1 = file_to_audit_docx.file.path - with open(script_path1, 'rb') as _file: - hash2_docx = uploadDataToIPFSNode(_file) - script_docx["script_file_path"] = script_path1 - script_docx["script_file"] = hash2_docx - script_docx["type"] = "script-docx" - audit_data["script-docx"] = script_docx - except: - csv_script_path = file_to_audit.file.path - df = pd.read_csv(csv_script_path) - docx = utilities.csv_to_docx(df) - - temp_file_stream = BytesIO() - docx.save(temp_file_stream) - temp_file_stream.seek(0) - - docx_file = ContentFile( - temp_file_stream.getvalue(), - "from_audited_csv_to_document.docx", - ) - - query_file = File.objects.create( - script= file_to_audit.script, - file=docx_file, - type="script-docx", - ) - file_to_audit_docx = File.objects.get( - script=script_id, - type="script-docx" - ) - script_docx = {} - script_path1 = file_to_audit_docx.file.path - script_size = file_to_audit_docx.file.size - with open(script_path1, 'rb') as _file: - hash2_docx = uploadDataToIPFSNode(_file) - script_docx["script_file_path"] = script_path1 - script_docx["script_file"] = hash2_docx - script_docx["type"] = "script-docx" - audit_data["script-docx"] = script_docx - - ## code for pdf also - try: - temp_dir = tempfile.TemporaryDirectory() - pdf_file_path = utilities.docx_to_pdf( - script_path1, temp_dir.name) - - with open(pdf_file_path, "rb") as temp_pdf: - - pdf_file = DjangoFile(temp_pdf,pdf_file_path.rsplit('/', 1)[1],) - - query_file = File.objects.create( - script = file_to_audit.script, - file = pdf_file, - type="script-pdf", - ) - script_pdf = {} - script_path1 = pdf_file_path - # script_size = file_to_audit_docx.file.size - with open(script_path1, 'rb') as _file: - hash2 = uploadDataToIPFSNode(_file) - script_pdf["script_file_path"] = script_path1 - script_pdf["script_file"] = hash2 - script_pdf["type"] = "script-pdf" - audit_data["script-pdf"] = script_pdf - except: - pass - # convert csv to json and store JSON - try: - csv_script_path = file_to_audit.file.path - print("csv_path fetched",csv_script_path) - df = pd.read_csv(csv_script_path) - df = df.loc[:, ["content", "script_element"]] - script_json: dict = json.loads(utilities.csv_to_json(df)) - with tempfile.TemporaryDirectory() as temp_dir: - print("Temporary directory created:", temp_dir) - temp_filename = os.path.join(temp_dir, 'script_json_file.json') - print("temp file name ----------------?>",temp_filename) - with open(temp_filename, 'w') as json_file: - json.dump(script_json, json_file, indent=4) - script_json = {} - script_path1 = temp_filename - # script_size = file_to_audit_docx.file.size - with open(script_path1, 'rb') as _file: - hash2 = uploadDataToIPFSNode(_file) - script_json["script_file_path"] = script_path1 - script_json["script_file"] = hash2 - script_json["type"] = "script-json" - audit_data["script-json"] = script_json - print("data_uploaded") - except Exception as exp: - print("###ERROR:",exp) - print("######Error from JSON CREATION############") - try: - script_csv = {} - script_path = file_to_audit.file.path - print("script_file_path_is_here",script_path) - with open(script_path, 'rb') as _file: - hash1 = uploadDataToIPFSNode(_file) - script_csv["script_file"] = hash1 - script_csv["script_file_path"] = script_path - script_csv["type"] = "script-csv" - audit_data["script-csv"]= script_csv - except Exception as exp: - print(exp) - Response,gasprice = UploadScriptAuditData(OWNER_KEY,blockchain_obj.publicKey,blockchain_obj.user_id,script_id,str(audit_data)) - print("tx_hash",Response) - transactioni_id = str(Response) - status.transaction_hash =str(transactioni_id) - status.save() - to_email = [user.email] - print("####### #### to_email",to_email) - key_value_aud = { "script_name" : str(screenplay_name) } - email_code = 'SB1' - sendmail(to_email=to_email , email_code=email_code, key_value = key_value_aud ) - print("$$$$### after sendmail") - # user_infos = user_info(tx_hash=Response,service="Script Audit",gas_fee=gasprice) - # addition_result = user_infos.update_info(request) - hash2_docx = hash_decrypation(hash2_docx) - tx_id = Response - certificate = certificateGenrate(user.username,"script audit",tx_id,projectname=script_file_name,matic=gasprice) - to_email = [user.email] - email_code = 'BL1' - key_value = { - "service":"Audited Script", - "hash": hash2_docx, - "public key":blockchain_obj.publicKey, - "Transaction Hash": tx_id, - } - print("userkey = ", userkey) - sendmail(to_email=to_email , email_code=email_code, key_value=key_value, filePath=certificate) - print("mail send sucessfully:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::") - data = {"message": "Success"} - - else: - - file_to_audit = File.objects.get( - script=script_id, - type="script-csv" - ) - file_to_audit_report = File.objects.get( - script=script_id, - type="audit-report" - ) - hash2 = "" - hash2_docx = "" - try: - file_to_audit_docx = File.objects.get( - script=script_id, - type="script-docx" - ) - script_docx = {} - script_path1 = file_to_audit_docx.file.path - with open(script_path1, 'rb') as _file: - hash2_docx = uploadDataToIPFSNode(_file) - script_docx["script_file_path"] = script_path1 - script_docx["script_file"] = hash2_docx - script_docx["type"] = "script-docx" - audit_data["script-docx"] = script_docx - except: - csv_script_path = file_to_audit.file.path - df = pd.read_csv(csv_script_path) - docx = utilities.csv_to_docx(df) - - temp_file_stream = BytesIO() - docx.save(temp_file_stream) - temp_file_stream.seek(0) - - docx_file = ContentFile( - temp_file_stream.getvalue(), - "from_audited_csv_to_document.docx", - ) - - query_file = File.objects.create( - script= file_to_audit.script, - file=docx_file, - type="script-docx", - ) - file_to_audit_docx = File.objects.get( - script=script_id, - type="script-docx" - ) - script_docx = {} - script_path1 = file_to_audit_docx.file.path - script_size = file_to_audit_docx.file.size - with open(script_path1, 'rb') as _file: - hash2_docx = uploadDataToIPFSNode(_file) - script_docx["script_file_path"] = script_path1 - script_docx["script_file"] = hash2_docx - script_docx["type"] = "script-docx" - audit_data["script-docx"] = script_docx - - ## code for pdf also - try: - temp_dir = tempfile.TemporaryDirectory() - pdf_file_path = utilities.docx_to_pdf( - script_path1, temp_dir.name) - - with open(pdf_file_path, "rb") as temp_pdf: - - pdf_file = DjangoFile(temp_pdf,pdf_file_path.rsplit('/', 1)[1],) - - query_file = File.objects.create( - script = file_to_audit.script, - file = pdf_file, - type="script-pdf", - ) - script_pdf = {} - script_path1 = pdf_file_path - # script_size = file_to_audit_docx.file.size - with open(script_path1, 'rb') as _file: - hash2 = uploadDataToIPFSNode(_file) - script_pdf["script_file_path"] = script_path1 - script_pdf["script_file"] = hash2 - script_pdf["type"] = "script-pdf" - audit_data["script-pdf"] = script_pdf - except: - pass - # convert csv to json and store JSON - try: - csv_script_path = file_to_audit.file.path - df = pd.read_csv(csv_script_path) - df = df.loc[:, ["content", "script_element"]] - script_json: dict = json.loads(utilities.csv_to_json(df)) - with tempfile.TemporaryDirectory() as temp_dir: - print("Temporary directory created:", temp_dir) - temp_filename = os.path.join(temp_dir, 'script_json_file.json') - print("temp file name ----------------?>",temp_filename) - with open(temp_filename, 'w') as json_file: - json.dump(script_json, json_file, indent=4) - script_json = {} - script_path1 = temp_filename - # script_size = file_to_audit_docx.file.size - with open(script_path1, 'rb') as _file: - hash2 = uploadDataToIPFSNode(_file) - script_json["script_file_path"] = script_path1 - script_json["script_file"] = hash2 - script_json["type"] = "script-json" - audit_data["script-json"] = script_json - print("data_uploaded") - except Exception as exp: - print("###ERROR:",exp) - print("######Error from JSON CREATION############") - pass - - script_csv = {} - audit_report ={} - audit_report_path = file_to_audit_report.file.path - script_path = file_to_audit.file.path - script_size = file_to_audit.file.size - - print("script_file_path_is_here",script_path) - with open(script_path, 'rb') as _file: - hash1 = uploadDataToIPFSNode(_file) - script_csv["script_file"] = hash1 - script_csv["script_file_path"] = script_path - script_csv["type"] = "script-csv" - with open(audit_report_path, 'rb') as file1: - hash2 = uploadDataToIPFSNode(file1) - audit_report["script_file"] = hash2 - audit_report["script_file_path"] = audit_report_path - audit_report["type"] = "audit-report" - audit_data["script-csv"]= script_csv - audit_data["audit-report"]= audit_report - - - Response,gasprice = UploadScriptAuditData(OWNER_KEY,blockchain_obj.publicKey,blockchain_obj.user_id,script_id,str(audit_data)) - print("tx_hash",Response) - transactioni_id = str(Response) - status.transaction_hash =str(transactioni_id) - status.save() - - to_email = [user.email] - email_code = 'SB1' - key_value_aud = { "script_name" : str(screenplay_name)} - sendmail(to_email=to_email , email_code=email_code, key_value = key_value_aud) - - # user_infos = user_info(tx_hash=Response,service="Script Audit",gas_fee=gasprice) - # addition_result = user_infos.update_info(request) - hash2_docx = hash_decrypation(hash2_docx) - tx_id = Response - certificate = certificateGenrate(user.username,"script audit",tx_id,projectname=script_file_name,matic=gasprice) - to_email = [user.email] - email_code = 'BL1' - key_value = { - "service":"Audited Script", - "hash": hash2_docx, - "public key":blockchain_obj.publicKey, - "Transaction Hash": tx_id, - } - print("userkey = ", userkey) - sendmail(to_email=to_email , email_code=email_code, key_value=key_value, filePath=certificate) - print("mail send sucessfully:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::") - data = {"message": "Success"} - # deleting the folder and files - - # Delete a file - media_path = os.path.join(settings.MEDIA_ROOT, "audit_counter_files", script_file_name) - if os.path.exists(media_path): - os.remove(media_path) - print(f"File '{media_path}' deleted successfully.") - else: - print(f"File '{media_path}' does not exist.") - - # Delete a folder and its contents - folder1_path = os.path.join(settings.MEDIA_ROOT, "scripts_folder", script_id) - if os.path.exists(folder1_path): - shutil.rmtree(folder1_path) - print(f"Folder '{folder1_path}' and its contents deleted successfully.") - else: - print(f"Folder '{folder1_path}' does not exist.") - - folder2_path = os.path.join(settings.MEDIA_ROOT, "audit_folder", script_id) - if os.path.exists(folder2_path): - shutil.rmtree(folder2_path) - print(f"Folder '{folder2_path}' and its contents deleted successfully.") - else: - print(f"Folder '{folder2_path}' does not exist.") - return JsonResponse(data, status=200) - # return Response("Success", status=200) - - - else: - - to_email = [user.email] - email_code = 'SB2' - key_value_aud = { "script_name" : str(screenplay_name)} - sendmail(to_email=to_email , email_code=email_code, key_value = key_value_aud ) - - Response = UploadScriptAuditData(OWNER_KEY,blockchain_obj.publicKey,blockchain_obj.user_id,script_id,str(audit_data)) - print("tx_hash",Response) - hash = hash_decrypation(hash) - #certificate = certificateGenrate(request.user.username,"script audit",hash) - tx_id = Response - - # certificate = certificateGenrate(request.user.username,"script audit",tx_id,projectname=script_file_name,matic=gasprice) - - to_email = [user.email] - email_code = 'BL1' - key_value = { - "service":"Orginal Script Audit", - "hash": hash, - "public key":blockchain_obj.publicKey, - "private key":userkey, - "Transaction Hash": tx_id, + audit_parameters = { + "service_type" : "audit", + "user":user, + "s3-file-path": local_file_path, + "screenplay_name": screenplay_name, + "author": author, + "language": language, + "script_ext": script_ext, + "script_file_name": script_file_name } - certificate = certificateGenrate(user.username,"script audit",tx_id,projectname=script_file_name,matic=gasprice) - sendmail(to_email=to_email , email_code=email_code, key_value=key_value, filePath=certificate) - - print("::::::::::::::",key_value) - print("userkey = ", userkey) - - + run_audit_in_counter(audit_parameters) diff --git a/kitchen_counter/scriptAudit/admin.py b/kitchen_counter/scriptAudit/admin.py index d299c5a..21e3e13 100755 --- a/kitchen_counter/scriptAudit/admin.py +++ b/kitchen_counter/scriptAudit/admin.py @@ -23,7 +23,7 @@ class ScriptAuditModelAdmin(admin.ModelAdmin): list_display = ( "script", "status", - "pre_audit_run", + "results", "last_call", - "celery_id", + "error_msg", ) diff --git a/kitchen_counter/scriptAudit/mnf_script_audit.py b/kitchen_counter/scriptAudit/mnf_script_audit.py index 477c2f9..42f91cb 100755 --- a/kitchen_counter/scriptAudit/mnf_script_audit.py +++ b/kitchen_counter/scriptAudit/mnf_script_audit.py @@ -2,39 +2,27 @@ import os import re import sys from pathlib import Path -# import time import datetime -# from utils import filesystem,utilities import pandas as pd from django.core.files.base import ContentFile import time -# from users.models import UserCredentialsForBlockchain -# from utils.scripts_functions import countPages -# import page_script.models as ps_models -# from mnfapp.views import update_juggernaut from centralisedFileSystem.models import File, Script, ScreenPlay -# from utils import filesystem -# from conversion.translation.detection import script_det, language_detector -# from conversion.translation.translation_variables import get_language_script_code, language_code -# from page_script.views import _file_path -# from page_script import views as page_script from scriptAudit import sa_functions as sf from scriptAudit import sa_functions_english as sf_eng from scriptAudit.models import ScriptAuditModel, States -# from mnfapp.views import update_juggernaut from io import BytesIO import datetime import pytz import subprocess -#from django_q.tasks import async_task +# from django_q.tasks import async_task # from django_q.brokers import Broker class NeutralAudit: def __init__( self, script_id: str = None, - log: bool = False, + log: bool = True, ) -> None: """ To Audit a Script already uploded. @@ -2712,7 +2700,7 @@ class NeutralAudit: return character_scripts_dict def audit_in_background(self): - # # commenting os.fork to make code run in foreground + # if os.fork() != 0: # return @@ -2736,76 +2724,10 @@ class NeutralAudit: except Exception as exp: self.audit_model_obj.status = States.FAILURE self.audit_model_obj.results = exp + self.audit_model_obj.error_msg = "FAILED" self.audit_model_obj.save() print(end_time) - - # def _audit(self): - # try: - # extension = self.input_script.rsplit(".", 1)[-1] - # if extension == 'fdx': - # self.audit_fdx() - # else: - # self.audit() - # self.audit_model_obj.status = States.SUCCESS - # self.audit_model_obj.save() - # print("Audit Success!!!!!!!!!!!!!!!!!!!!!!!") - # with open(self.base_file_path + "time_taken.txt", "a") as file007: - # file007.write("\n\n****AUDITING IS SUCCESSFUL****\n") - # except Exception as exp: - # self.audit_model_obj.status = States.FAILURE - # self.audit_model_obj.results = exp - # self.audit_model_obj.save() - - # def audit_in_background(self): - # print("Running in background") - # async_task(self._audit) - - - # def audit_in_background(self): - # print("Running in background") - # async_task(self._audit) - # print("Task enqueued successfully") - - # def _audit(self): - # try: - # extension = self.input_script.rsplit(".", 1)[-1] - # if extension == 'fdx': - # self.audit_fdx() - # else: - # self.audit() - # self.audit_model_obj.status = States.SUCCESS - # self.audit_model_obj.save() - # print("Audit Success!!!!!!!!!!!!!!!!!!!!!!!") - # with open(self.base_file_path + "time_taken.txt", "a") as file007: - # file007.write("\n\n****AUDITING IS SUCCESSFUL****\n") - # except Exception as exp: - # self.audit_model_obj.status = States.FAILURE - # self.audit_model_obj.results = exp - # self.audit_model_obj.save() - # print("Audit Failed:", exp) - - - - - - - - if __name__ == "__main__": naudit = NeutralAudit("123", True) - ## audit run - # naudit.__call__() - - ## character subset check - # character_list = [] - # character_list = naudit.get_character_list() - - # try: - # print("characters of script are",character_list) - # except: - # pass - - # naudit.quick_audit() - naudit.get_character_subset() diff --git a/kitchen_counter/scriptAudit/models.py b/kitchen_counter/scriptAudit/models.py index 4e1b1c3..3edda78 100755 --- a/kitchen_counter/scriptAudit/models.py +++ b/kitchen_counter/scriptAudit/models.py @@ -1,64 +1,65 @@ -import uuid - -from django.db import models - -from centralisedFileSystem.models import Script - - -class States: - """ - All the possible states of the audit. - """ - - PENDING = "PENDING" - STARTED = "STARTED" - SUCCESS = "SUCCESS" - FAILURE = "FAILURE" - RETRY = "RETRY" - REVOKED = "REVOKED" - -# class AuditStatus(models.Model): -# STATUS = ( -# ("N", "notstarted"), -# ("R", "running"), -# ("S", "success"), -# ("F", "failed"), -# ) - -# id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) -# script = models.ForeignKey( -# Script, on_delete=models.CASCADE, related_name="audit_scripts_files" -# ) -# script_audit_status = models.CharField(choices=STATUS, default="N", max_length=20) - - -class ScriptAuditModel(models.Model): - - _STATES = tuple(((v, v) for k, v in States.__dict__.items() if k[:2] != "__")) - """ - PENDING (waiting for execution or unknown task id) - STARTED (task has been started) - SUCCESS (task executed successfully) - FAILURE (task execution resulted in exception) - RETRY (task is being retried) - REVOKED (task has been revoked) - """ - - id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) - script = models.OneToOneField( - Script, on_delete=models.CASCADE, blank=False, null=False, related_name="script_audit" - ) - celery_id = models.CharField(max_length=50, blank=False, null=True, editable=False) - last_call = models.DateTimeField(auto_now=True) - pre_audit_run = models.BooleanField(default=False) - status = models.CharField(max_length=10, blank=True, null=True, choices=_STATES) - results = models.CharField(max_length=200, blank=True, null=True) - retries = models.IntegerField(default=0) - expected_duration = models.CharField(max_length=30, blank=True, null=True) - number_of_pages = models.IntegerField(blank=True, null=True) - screenplay_language = models.CharField(max_length=50, blank=False, null=True) - dialogue_language = models.CharField(max_length=50, blank=False, null=True) - transaction_hash = models.CharField(max_length=200, blank=False, null=True) - bchain_privatekey = models.CharField(max_length=200, blank=False, null=True) - isfdx = models.BooleanField(default=False) - only_audit = models.BooleanField(null=True, blank=True) +import uuid + +from django.db import models + +from centralisedFileSystem.models import Script + + +class States: + """ + All the possible states of the audit. + """ + + PENDING = "PENDING" + STARTED = "STARTED" + SUCCESS = "SUCCESS" + FAILURE = "FAILURE" + RETRY = "RETRY" + REVOKED = "REVOKED" + +# class AuditStatus(models.Model): +# STATUS = ( +# ("N", "notstarted"), +# ("R", "running"), +# ("S", "success"), +# ("F", "failed"), +# ) + +# id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) +# script = models.ForeignKey( +# Script, on_delete=models.CASCADE, related_name="audit_scripts_files" +# ) +# script_audit_status = models.CharField(choices=STATUS, default="N", max_length=20) + + +class ScriptAuditModel(models.Model): + + _STATES = tuple(((v, v) for k, v in States.__dict__.items() if k[:2] != "__")) + """ + PENDING (waiting for execution or unknown task id) + STARTED (task has been started) + SUCCESS (task executed successfully) + FAILURE (task execution resulted in exception) + RETRY (task is being retried) + REVOKED (task has been revoked) + """ + + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + script = models.OneToOneField( + Script, on_delete=models.CASCADE, blank=False, null=False, related_name="script_audit" + ) + celery_id = models.CharField(max_length=50, blank=False, null=True, editable=False) + last_call = models.DateTimeField(auto_now=True) + pre_audit_run = models.BooleanField(default=False) + status = models.CharField(max_length=10, blank=True, null=True, choices=_STATES) + results = models.CharField(max_length=200, blank=True, null=True) + retries = models.IntegerField(default=0) + expected_duration = models.CharField(max_length=30, blank=True, null=True) + number_of_pages = models.IntegerField(blank=True, null=True) + screenplay_language = models.CharField(max_length=50, blank=False, null=True) + dialogue_language = models.CharField(max_length=50, blank=False, null=True) + transaction_hash = models.CharField(max_length=200, blank=False, null=True) + bchain_privatekey = models.CharField(max_length=200, blank=False, null=True) + isfdx = models.BooleanField(default=False) + only_audit = models.BooleanField(null=True, blank=True) + error_msg = models.TimeField(null=True,blank=True) \ No newline at end of file diff --git a/kitchen_counter/scriptAudit/urls.py b/kitchen_counter/scriptAudit/urls.py index 5305671..0883d1a 100755 --- a/kitchen_counter/scriptAudit/urls.py +++ b/kitchen_counter/scriptAudit/urls.py @@ -3,24 +3,16 @@ from scriptAudit import views from django.views.generic import TemplateView urlpatterns = [ - path("home", views.AuditHomeView.as_view(), name="upload_audit"), + # path("home", views.AuditHomeView.as_view(), name="upload_audit"),#fetch from backup path("counter_run", views.Get_Counter.as_view(), name="counter_run"), - path("fetch_in_counter", views.Fetch_in_Counter.as_view(), name="fetch_in_counter"), - path("facade", views.AuditFacadeView.as_view(), name="upload_audit_facade"), - path("facade/status_update", views.AuditStatusUpdate.as_view(), name="audit_facade_status_update"), - path("facade/file_update", views.AuditedFileUpdate.as_view(), name="audit_facade_file_update"), - path("facade/report_update", views.AuditedReportUpdate.as_view(), name="audit_facade_report_update"), - # path("audited", views.AuditedScriptsView.as_view(), name="my_audited_scripts"), - path("audits", views.AuditedScriptsView_kunal.as_view(), name="new_audited_page"), #new audited page - path("audits1", views.AuditedScriptsView_kunal1.as_view(), name="new_audited_page1"), #new audited page - # path("audit/", views.AuditView.as_view()), - # path("charlst/", views.CharacterListView.as_view()), + # path("fetch_in_counter", views.Fetch_in_Counter.as_view(), name="fetch_in_counter"), + path("audit-blockchain_", views.AuditedScriptsView_Without_blockchain.as_view(), name="new_audited_page"), #new audited page + path("audits1", views.AuditedScriptsView_With_Blockchain.as_view(), name="new_audited_page1"), #new audited page path("download",views.DownloadScript.as_view()), - path("checkdomain",views.CheckDomain.as_view()), path("delete_scripts/", views.DeleteScriptAPIView.as_view(),name="delete_script"), - path("processing", TemplateView.as_view(template_name="audit/audit_processing.html"), name="audit_processing_page"), path("audit_tutorial",TemplateView.as_view(template_name = "audit/audit_tutorial.html"),name="audit_tutorial"), path("scriptAuditDemo", TemplateView.as_view(template_name = "audit/audit_demo.html"), name="scriptAuditDemo"), path("downloadScriptFromBlockchain",views.DownloadScriptFromBlockchain.as_view()), ] +# path('view/',login_required(ViewSpaceIndex.as_view(..)), \ No newline at end of file diff --git a/kitchen_counter/scriptAudit/views.py b/kitchen_counter/scriptAudit/views.py index 112c78a..e2a65ba 100755 --- a/kitchen_counter/scriptAudit/views.py +++ b/kitchen_counter/scriptAudit/views.py @@ -1,218 +1,73 @@ -# from .models import AuditStatus -import time,pytz -import mimetypes -from rest_framework_simplejwt.authentication import JWTAuthentication -import tempfile -import requests +import pytz,mimetypes,tempfile,requests import pandas as pd -import boto3 +import boto3 , json , shutil, os from io import BytesIO -from django.contrib.auth.models import User -import json -import shutil from users.models import UserCredentialsForBlockchain -from Blockchain2.block_user_info import * -from Blockchain2.decryption import decryptionOfPrivate, decryptionOfUrl, download_file_System,decryptionOflocalUrl,hash_decrypation +from Blockchain2.decryption import decryptionOfPrivate,decryptionOflocalUrl,hash_decrypation from Blockchain2.DataStorage import uploadDataToIPFSNode from Blockchain2.scriptAudit import getUserprojectIds,UploadScriptAuditData,getScriptAudit +from Blockchain2.web3User import mypublickey from Blockchain2.blockchainsetting import OWNER_KEY from django.core import exceptions as django_exception -from django.http import FileResponse, HttpResponseBadRequest,HttpResponse,JsonResponse +from django.http import FileResponse, JsonResponse from django.core.files.base import File as DjangoFile from django.core.files.base import ContentFile from django.shortcuts import redirect, render from rest_framework import status from rest_framework.authentication import BasicAuthentication, SessionAuthentication -from rest_framework.decorators import authentication_classes, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView -from .utils import audit_in_background, update_audit_status +from .utils import update_audit_status from utils.scripts_functions import script_id_generator -# from centralisedFileSystem.models import BeatSheet from centralisedFileSystem.models import Script,File, ScreenPlay from scriptAudit.mnf_script_audit import NeutralAudit from utils import filesystem,utilities from datetime import datetime from .forms import AuditForm from .models import ScriptAuditModel, States -from .utils import audit_in_background,send_email_to_user from scriptAudit import exceptions as spex -import os from django.contrib.sites.shortcuts import get_current_site -from rest_framework_simplejwt.authentication import JWTAuthentication -import threading -# from rest_framework.permissions import IsAuthenticated -from datetime import timedelta from lpp.certificate.createCertificate import certificateGenrate -# url = "http://115.245.192.138" -# url = "http://1.6.141.104:4000" -# url = "http://1.6.141.108" -from django.views import View -# url = "https://mynextfilm.ai" -from utils.filesystem import get_file,get_file_path, get_script_data -# from utils.utilities import send_email_to_user -# from narration.vectorcode.code import vector_generation from auto_email.views import sendmail from MNF import settings +from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.models import User -# from mnfapp.views import update_juggernaut -# from mnfapp.views import check_juggernaut -# from Pitchdeck.views import multilingual_render -# from centralizePayment.views import callback, create_indent - -#api_gateway_url = "https://diybbp-main-ed89647.d2.zuplo.dev" -api_gateway_url = "https://mnf-apigateway-main-6268011.d2.zuplo.dev" -gateway_audit_url = api_gateway_url +"/sify/audit/headless/taj" # /aws for aws -class AuditFacadeView(APIView): + +class Get_Counter(LoginRequiredMixin,APIView): + login_url = "/personal-login" authentication_classes = [BasicAuthentication,SessionAuthentication] permission_classes = [IsAuthenticated] - def get(self, request): - form = AuditForm() - return render(request, "audit/audit_facade.html", {"form": form}) - - def post(self, request): - form = AuditForm(request.POST, request.FILES) - if form.is_valid(): - screenplay_name = form.cleaned_data["screenplay_name"] - author = form.cleaned_data["author_name"] - language = form.cleaned_data["language"] - script_file = form.cleaned_data["script_file"] - - script_ext = script_file.name.split(".")[-1] - script_file_name = screenplay_name + "." + script_ext - - - file = ContentFile( - script_file.read(), - script_file_name, - ) - - result = filesystem.new_screenplay_without_audit_in_background( - request.user, - author, - screenplay_name, - file, - "script-original", - language, - ) - - script_id = result.get("script", {}).get("id") - - update_audit_status(script_id,"PENDING") - - file_to_original = File.objects.get( - script=script_id, - type="script-original" - - ) - - ## call audit gateway url - form_data = {'author_name':'taj_audit', - 'screenplay_name':screenplay_name+"_facade", - 'language':language, - 'facade_script_id': str(script_id)} - with open(file_to_original.file.path, 'rb') as file: - files = {'script_file':file} - res = requests.post(gateway_audit_url, files=files, data= form_data) - print("Facade=============>>>>>>>>>",script_id) - print("Response",res.text) - - status = ScriptAuditModel.objects.get( - script = Script.objects.get( - id = script_id - )) - print("STATUS AUDIT",status) - # return redirect("new_audited_page") - if status.status == "SUCCESS": - try: - script = Script.objects.get(id=script_id) - no_of_pages = script.no_of_pages - user_id = script.screenplay.user.id - except Script.DoesNotExist: - print(f"Script with ID {script_id} does not exist.") - - to_email = [request.user.email] - email_code = 'SB1' - # sendmail(to_email=to_email , email_code=email_code - elif status.status == "FAILURE": - to_email = [request.user.email] - email_code = 'SB2' - return redirect("audit_processing_page") - # return multilingual_render(request, "audit/audit_processing.html", None) - else : - # return HttpResponseBadRequest(multilingual_render(request, "audit/audit.html", {"form": form,"errors": form.errors})) - return HttpResponseBadRequest(render(request, "audit/audit_facade.html", {"form": form,"errors": form.errors})) - - -# class AuditFacadeView(APIView): -# #authentication_classes = [BasicAuthentication,SessionAuthentication] -# #permission_classes = [IsAuthenticated] -# def get(self, request): -# form = AuditForm() -# return render(request, "audit/audit.html", {"form": form}) - -# def post(self, request): -# form = AuditForm(request.POST, request.FILES) -# if form.is_valid(): -# print("form valid") -# screenplay_name = form.cleaned_data["screenplay_name"] -# author = form.cleaned_data["author_name"] -# language = form.cleaned_data["language"] -# script_file = form.cleaned_data["script_file"] - -# script_ext = script_file.name.split(".")[-1] -# script_file_name = screenplay_name + "." + script_ext -# file = ContentFile( -# script_file.read(), -# script_file_name, -# ) - -# result = filesystem.new_screenplay_without_audit_in_background( -# request.user, -# author, -# screenplay_name, -# file, -# "script-original", -# language, -# ) -# print("getting script id") -# script_id = result.get("script", {}).get("id") -# print("scriptid", script_id) - -# ## call the sify headless view -# sify_audit_url = "http://1.6.141.103/audit/headless" -# files = {'script_file':file} -# form_data = {'author_name':'taj_audit', -# 'screenplay_name':screenplay_name+"_facade", -# 'language':language, -# 'facade_script_id': str(script_id)} -# res = requests.post(sify_audit_url, files=files, data= form_data) -# print("Facade=============>>>>>>>>>",script_id) -# print("Response",res.text) -# message = 'facade_script_id' + res.text + '\n script_id ' + str(script_id) -# return render(request, "audit/audit.html",{'message': message}) -# else : -# return HttpResponseBadRequest(render(request, "audit/audit.html", {"form": form,"errors": form.errors})) - - -class Get_Counter(APIView): - authentication_classes = [BasicAuthentication,SessionAuthentication] - permission_classes = [IsAuthenticated] - - def get(self, request): return render(request, "audit/audit_AWS_home.html") def post(self, request): - # session = boto3.Session( - # aws_access_key_id='AKIAQVLBBGCB45RMLKVW', # replace with your key - # aws_secret_access_key='ZWc6KOc5LuBLuCEBDDfQTor+Q7rp3fFH74gVt+AA', # replace with your key - # ) - # sqs = session.resource('sqs', region_name='ap-south-1') - # queue = sqs.get_queue_by_name(QueueName="mnfqueue") + current_site = str(get_current_site(request).domain) + print("CURREENT DOMAIN :-----") + print(current_site) + running_in_production = True + if current_site in ["http://1.6.141.108", + "http://1.6.141.104", + "http://1.6.141.103", + "http://1.6.141.106", + "https://taj.mynextfilm.in", + "1.6.141.108", + "1.6.141.104", + "1.6.141.103", + "1.6.141.106", + "taj.mynextfilm.in", + "qa.mynextfilm.net", + "https://qa.mynextfilm.net", + ]: + running_in_production = False + session = boto3.Session( + aws_access_key_id='AKIAQVLBBGCB45RMLKVW', + aws_secret_access_key='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', + ) + sqs = session.resource('sqs', region_name='ap-south-1') + queue = sqs.get_queue_by_name(QueueName="mnfqueue") user = str(request.user) @@ -228,167 +83,152 @@ class Get_Counter(APIView): for chunk in script_file.chunks(): destination.write(chunk) - # object_name = "INPUT/" + script_file_name - # filee = media_path - # bucket = "conversion-kitchen" - # s3_client = boto3.client('s3', - # aws_access_key_id="AKIAQVLBBGCB45RMLKVW", - # aws_secret_access_key="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", - # region_name="ap-south-1" - # ) - # try: - # response = s3_client.upload_file(filee, bucket, object_name) - # print(response) - # except Exception as e: - # print("Error is", e) + object_name = "INPUT/" + script_file_name + filee = media_path + bucket = "conversion-kitchen" + s3_client = boto3.client('s3', + aws_access_key_id="AKIAQVLBBGCB45RMLKVW", + aws_secret_access_key="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", + region_name="ap-south-1" + ) + if running_in_production == True: + try: + response = s3_client.upload_file(filee, bucket, object_name) + print(response) + except Exception as e: + print("Error is", e) + - - # s3_url = f"https://{bucket}.s3.ap-south-1.amazonaws.com/{object_name}" - + s3_url = f"https://{bucket}.s3.ap-south-1.amazonaws.com/{object_name}" + else: + s3_url = media_path audit_parameters = { "service_type" : "audit", "user":user, - # "s3-file-path": s3_url, - "s3-file-path": media_path, + "s3-file-path": s3_url, "screenplay_name": screenplay_name, "author": author, "language": language, "script_ext": script_ext, "script_file_name": script_file_name } - print("################ AUDIT PARAMETER", audit_parameters) - # response = queue.send_message( - # MessageBody=json.dumps(audit_parameters),) - - return JsonResponse({"response": audit_parameters}) - # return redirect("new_audited_page") + key_value = {"script_name" : screenplay_name} + to_email = [request.user.email] + email_code = 'SB14' + sendmail(to_email=to_email, email_code=email_code ,key_value = key_value) + if running_in_production != True: + print("RUNNING AUDIT LOCALLY") + print(audit_parameters) + run_audit_in_counter(audit_parameters) + return JsonResponse({"response": audit_parameters}) + else: + response = queue.send_message(MessageBody=json.dumps(audit_parameters),) + return JsonResponse({"response": response}) -class Fetch_in_Counter(APIView): - authentication_classes = [BasicAuthentication,SessionAuthentication] - permission_classes = [IsAuthenticated] - def post(self, request): - audit_parameters = request.data - print(audit_parameters) - # time.sleep(7) - user = audit_parameters.get("user") - s3_url = audit_parameters.get("s3-file-path") - screenplay_name = audit_parameters.get("screenplay_name") - author = audit_parameters.get("author") - language = audit_parameters.get("language") - script_ext = audit_parameters.get("script_ext") - script_file_name = audit_parameters.get("script_file_name") - language = "en" # main language - - if script_ext == "docx": - pass - - elif script_ext == "pdf": - pass - - elif script_ext == "fdx": - estimatedtime = None - - else: #txt - pass - with open(s3_url, 'rb') as file: - file_content = file.read() - - file = ContentFile( +def run_audit_in_counter(msg): + user = msg["user"] + s3_url = msg["s3-file-path"] + screenplay_name = msg["screenplay_name"] + author = msg["author"] + language = msg["language"] + script_ext = msg["script_ext"] + script_file_name = msg["script_file_name"] + language = "en" + local_file_path = s3_url + + + with open(local_file_path, 'rb') as file: + file_content = file.read() + + file = ContentFile( file_content, script_file_name, - ) - # user = User.objects.get(username=user) - # user_id = user.id + ) + + user = User.objects.get(username=user) - result = filesystem.new_screenplay_without_audit_in_background( - request.user, - author, - screenplay_name, - file, - "script-original", - language, - ) + result = filesystem.new_screenplay_without_audit_in_background( + user, + author, + screenplay_name, + file, + "script-original", + language, + ) + + + script_id = result.get("script", {}).get("id") + file_to_original = File.objects.get( + script=script_id, + type="script-original" - script_id = result.get("script", {}).get("id") - - file_to_original = File.objects.get( - script=script_id, - type="script-original" + ) + try: + update_audit_status(script_id, States.STARTED) + except: + update_audit_status(script_id, States.FAILURE) + #update_only_audit + audit_only = ScriptAuditModel.objects.get( + script = Script.objects.get( + id = script_id + )) + audit_only.only_audit = True + audit_only.save() - ) - try: - update_audit_status(script_id, States.STARTED) - except: - update_audit_status(script_id, States.FAILURE) + try: + + audit = NeutralAudit(script_id) + audit.audit_in_background() + ScriptAuditModel.objects.update_or_create( + script = Script.objects.get( + id = script_id + ), + defaults={"status" : "SUCCESS"} + ) + + + + except Exception as exp: + ScriptAuditModel.objects.update_or_create(script = Script.objects.get(id = script_id), + defaults={"status" : "FAILURE", + "results" : exp}) + key_value = {"script_name" : screenplay_name,} + to_email = [user.email] + email_code = 'SB2' + sendmail(to_email=to_email, email_code=email_code ,key_value = key_value) + + status = ScriptAuditModel.objects.get( + script = Script.objects.get( + id = script_id + )) + blockchain_obj = UserCredentialsForBlockchain.objects.get(user=user) + script_original= {} + audit_data={} + script_original["status"] = "STARTED" + script_original["script_id"] = script_id + with open(file_to_original.file.path, 'rb') as file: + hash = uploadDataToIPFSNode(file) + script_original["script_file"] = hash + script_original["type"] = "script-original" + script_original["script_file_path"] = file_to_original.file.path + audit_data["script-original"] = script_original + userkey= decryptionOfPrivate(blockchain_obj.privateKey) + print("userkey = ", str(userkey)) + print("blockchain_obj.publicKey",blockchain_obj.publicKey) + print("blockchain_obj.privateKey",blockchain_obj.privateKey) + if status.status == "SUCCESS": + + if script_ext == "fdx": - try: - # audit_in_background(script_id) - audit = NeutralAudit(script_id) - audit.audit_in_background() - ScriptAuditModel.objects.update_or_create( - script = Script.objects.get( - id = script_id - ), - defaults={"status" : "SUCCESS"} - ) - #script_id will be present here as well - # blockchain code to upload files, - #1. csv - #2. Audit Orginal - #3. Audit Report - #4. Audit Docx - #5. Audit PDF - - - - except: - ScriptAuditModel.objects.update_or_create( - script = Script.objects.get( - id = script_id - ), - defaults={"status" : "FAILURE"} - ) - - status = ScriptAuditModel.objects.get( - script = Script.objects.get( - id = script_id - )) - print("STATUS AUDIT",status) - # Blockchain - # if UserCredentialsForBlockchain.objects.filter(user=request.user).exists(): - blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user) - script_original= {} - audit_data={} - script_original["status"] = "STARTED" - script_original["script_id"] = script_id - with open(file_to_original.file.path, 'rb') as file: - hash = uploadDataToIPFSNode(file) - script_original["script_file"] = hash - script_original["type"] = "script-original" - script_original["script_file_path"] = file_to_original.file.path - audit_data["script-original"] = script_original - userkey= decryptionOfPrivate(blockchain_obj.privateKey) - print("userkey = ", str(userkey)) - # status,getData = getScriptAudit(userkey.decode('utf-8'),user_id,str(script_id)) - # privatekeyfordb = userkey.decode('utf-8') - # print(privatekeyfordb) - # status.bchain_privatekey = privatekeyfordb - # status.save() - print("blockchain_obj.publicKey",blockchain_obj.publicKey) - print("blockchain_obj.privateKey",blockchain_obj.privateKey) - if status.status == "SUCCESS": file_to_audit = File.objects.get( script=script_id, type="script-csv" ) - file_to_audit_report = File.objects.get( - script=script_id, - type="audit-report" - ) hash2 = "" + hash2_docx = "" try: file_to_audit_docx = File.objects.get( script=script_id, @@ -397,9 +237,9 @@ class Fetch_in_Counter(APIView): script_docx = {} script_path1 = file_to_audit_docx.file.path with open(script_path1, 'rb') as _file: - hash2 = uploadDataToIPFSNode(_file) + hash2_docx = uploadDataToIPFSNode(_file) script_docx["script_file_path"] = script_path1 - script_docx["script_file"] = hash2 + script_docx["script_file"] = hash2_docx script_docx["type"] = "script-docx" audit_data["script-docx"] = script_docx except: @@ -429,9 +269,160 @@ class Fetch_in_Counter(APIView): script_path1 = file_to_audit_docx.file.path script_size = file_to_audit_docx.file.size with open(script_path1, 'rb') as _file: - hash2 = uploadDataToIPFSNode(_file) + hash2_docx = uploadDataToIPFSNode(_file) script_docx["script_file_path"] = script_path1 - script_docx["script_file"] = hash2 + script_docx["script_file"] = hash2_docx + script_docx["type"] = "script-docx" + audit_data["script-docx"] = script_docx + + ## code for pdf also + try: + temp_dir = tempfile.TemporaryDirectory() + pdf_file_path = utilities.docx_to_pdf( + script_path1, temp_dir.name) + + with open(pdf_file_path, "rb") as temp_pdf: + + pdf_file = DjangoFile(temp_pdf,pdf_file_path.rsplit('/', 1)[1],) + + query_file = File.objects.create( + script = file_to_audit.script, + file = pdf_file, + type="script-pdf", + ) + script_pdf = {} + script_path1 = pdf_file_path + # script_size = file_to_audit_docx.file.size + with open(script_path1, 'rb') as _file: + hash2 = uploadDataToIPFSNode(_file) + script_pdf["script_file_path"] = script_path1 + script_pdf["script_file"] = hash2 + script_pdf["type"] = "script-pdf" + audit_data["script-pdf"] = script_pdf + except: + pass + # convert csv to json and store JSON + try: + csv_script_path = file_to_audit.file.path + print("csv_path fetched",csv_script_path) + df = pd.read_csv(csv_script_path) + df = df.loc[:, ["content", "script_element"]] + script_json: dict = json.loads(utilities.csv_to_json(df)) + with tempfile.TemporaryDirectory() as temp_dir: + print("Temporary directory created:", temp_dir) + temp_filename = os.path.join(temp_dir, 'script_json_file.json') + print("temp file name ----------------?>",temp_filename) + with open(temp_filename, 'w') as json_file: + json.dump(script_json, json_file, indent=4) + script_json = {} + script_path1 = temp_filename + # script_size = file_to_audit_docx.file.size + with open(script_path1, 'rb') as _file: + hash2 = uploadDataToIPFSNode(_file) + script_json["script_file_path"] = script_path1 + script_json["script_file"] = hash2 + script_json["type"] = "script-json" + audit_data["script-json"] = script_json + print("data_uploaded") + except Exception as exp: + print("###ERROR:",exp) + print("######Error from JSON CREATION############") + try: + script_csv = {} + script_path = file_to_audit.file.path + print("script_file_path_is_here",script_path) + with open(script_path, 'rb') as _file: + hash1 = uploadDataToIPFSNode(_file) + script_csv["script_file"] = hash1 + script_csv["script_file_path"] = script_path + script_csv["type"] = "script-csv" + audit_data["script-csv"]= script_csv + except Exception as exp: + print(exp) + Response,gasprice = UploadScriptAuditData(OWNER_KEY,blockchain_obj.publicKey,blockchain_obj.user_id,script_id,str(audit_data)) + print("tx_hash",Response) + transactioni_id = str(Response) + status.transaction_hash =str(transactioni_id) + status.save() + to_email = [user.email] + print("####### #### to_email",to_email) + key_value_aud = { "script_name" : str(screenplay_name) } + email_code = 'SB1' + sendmail(to_email=to_email , email_code=email_code, key_value = key_value_aud ) + print("$$$$### after sendmail") + # user_infos = user_info(tx_hash=Response,service="Script Audit",gas_fee=gasprice) + # addition_result = user_infos.update_info(request) + hash2_docx = hash_decrypation(hash2_docx) + tx_id = Response + certificate = certificateGenrate(user.username,"script audit",tx_id,projectname=script_file_name,matic=gasprice) + to_email = [user.email] + email_code = 'BL1' + key_value = { + "service":"Audited Script", + "hash": hash2_docx, + "public key":blockchain_obj.publicKey, + "Transaction Hash": tx_id, + } + print("userkey = ", userkey) + sendmail(to_email=to_email , email_code=email_code, key_value=key_value, filePath=certificate) + print("mail send sucessfully:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::") + data = {"message": "Success"} + + else: + + file_to_audit = File.objects.get( + script=script_id, + type="script-csv" + ) + file_to_audit_report = File.objects.get( + script=script_id, + type="audit-report" + ) + hash2 = "" + hash2_docx = "" + try: + file_to_audit_docx = File.objects.get( + script=script_id, + type="script-docx" + ) + script_docx = {} + script_path1 = file_to_audit_docx.file.path + with open(script_path1, 'rb') as _file: + hash2_docx = uploadDataToIPFSNode(_file) + script_docx["script_file_path"] = script_path1 + script_docx["script_file"] = hash2_docx + script_docx["type"] = "script-docx" + audit_data["script-docx"] = script_docx + except: + csv_script_path = file_to_audit.file.path + df = pd.read_csv(csv_script_path) + docx = utilities.csv_to_docx(df) + + temp_file_stream = BytesIO() + docx.save(temp_file_stream) + temp_file_stream.seek(0) + + docx_file = ContentFile( + temp_file_stream.getvalue(), + "from_audited_csv_to_document.docx", + ) + + query_file = File.objects.create( + script= file_to_audit.script, + file=docx_file, + type="script-docx", + ) + file_to_audit_docx = File.objects.get( + script=script_id, + type="script-docx" + ) + script_docx = {} + script_path1 = file_to_audit_docx.file.path + script_size = file_to_audit_docx.file.size + with open(script_path1, 'rb') as _file: + hash2_docx = uploadDataToIPFSNode(_file) + script_docx["script_file_path"] = script_path1 + script_docx["script_file"] = hash2_docx script_docx["type"] = "script-docx" audit_data["script-docx"] = script_docx @@ -470,7 +461,7 @@ class Fetch_in_Counter(APIView): with tempfile.TemporaryDirectory() as temp_dir: print("Temporary directory created:", temp_dir) temp_filename = os.path.join(temp_dir, 'script_json_file.json') - print(temp_filename) + print("temp file name ----------------?>",temp_filename) with open(temp_filename, 'w') as json_file: json.dump(script_json, json_file, indent=4) script_json = {} @@ -482,7 +473,10 @@ class Fetch_in_Counter(APIView): script_json["script_file"] = hash2 script_json["type"] = "script-json" audit_data["script-json"] = script_json - except: + print("data_uploaded") + except Exception as exp: + print("###ERROR:",exp) + print("######Error from JSON CREATION############") pass script_csv = {} @@ -505,36 +499,28 @@ class Fetch_in_Counter(APIView): audit_data["script-csv"]= script_csv audit_data["audit-report"]= audit_report - with open("/home/mnftaj/mnf_march22/MNF/app/Blockchain2/file_stroge.txt","a") as file01: - file01.write("audit userkey------------------SUCCESS1 IN_COUNTER\n" + str(audit_data) + "\n") + Response,gasprice = UploadScriptAuditData(OWNER_KEY,blockchain_obj.publicKey,blockchain_obj.user_id,script_id,str(audit_data)) print("tx_hash",Response) - with open("/home/mnftaj/mnf_march22/MNF/app/Blockchain2/file_stroge.txt","a") as file01: - file01.write("audit userkey------------------SUCCESS\n"+str(Response)) transactioni_id = str(Response) - # with open("/home/mnfbeta/mnf/app/Blockchain2/file_stroge.txt","a") as file01: - # file01.write(f"Transaction hash for audit is {str(transactioni_id)}\n") - # current_time = datetime.now() - # formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S") - # file01.write(f"Transaction hash for audit is {str(type(transactioni_id))}\n") - # file01.write(f" time for the above transaction id {str(formatted_time)}\n") - # audit_model_obj = ScriptAuditModel.objects.get( - # script = Script.objects.get(id = script_id)) status.transaction_hash =str(transactioni_id) - # audit_model_obj.transaction_hash = str(transactioni_id) - # audit_model_obj.save() status.save() + to_email = [user.email] + email_code = 'SB1' + key_value_aud = { "script_name" : str(screenplay_name)} + sendmail(to_email=to_email , email_code=email_code, key_value = key_value_aud) + # user_infos = user_info(tx_hash=Response,service="Script Audit",gas_fee=gasprice) # addition_result = user_infos.update_info(request) - hash2 = hash_decrypation(hash2) + hash2_docx = hash_decrypation(hash2_docx) tx_id = Response - certificate = certificateGenrate(request.user.username,"script audit",tx_id,projectname=script_file_name,matic=gasprice) - to_email = [request.user.email] + certificate = certificateGenrate(user.username,"script audit",tx_id,projectname=script_file_name,matic=gasprice) + to_email = [user.email] email_code = 'BL1' key_value = { "service":"Audited Script", - "hash": hash2, + "hash": hash2_docx, "public key":blockchain_obj.publicKey, "Transaction Hash": tx_id, } @@ -568,525 +554,78 @@ class Fetch_in_Counter(APIView): print(f"Folder '{folder2_path}' does not exist.") return JsonResponse(data, status=200) # return Response("Success", status=200) - - - else: - with open("/home/mnftaj/mnf_march22/MNF/app/Blockchain2/file_stroge.txt","a") as file01: - file01.write("audit userkey------------------else\n") - Response = UploadScriptAuditData(OWNER_KEY,blockchain_obj.publicKey,blockchain_obj.user_id,script_id,str(audit_data)) - print("tx_hash",Response) - hash = hash_decrypation(hash) - #certificate = certificateGenrate(request.user.username,"script audit",hash) - tx_id = Response - - # certificate = certificateGenrate(request.user.username,"script audit",tx_id,projectname=script_file_name,matic=gasprice) - - to_email = [request.user.email] - email_code = 'BL1' - key_value = { - "service":"Orginal Script Audit", - "hash": hash, - "public key":blockchain_obj.publicKey, - "private key":userkey, - "Transaction Hash": tx_id, - } - - print("::::::::::::::",key_value) - print("userkey = ", userkey) - # sendmail(to_email=to_email , email_code=email_code,key_value=key_value,filePath=certificate) - return JsonResponse({"script_id": script_id}, status=200) -class AuditStatusUpdate(APIView): - def post(self,request): - facade_script_id = request.data['facade_script_id'] - status = request.data['status'] - try: - update_audit_status(facade_script_id,status) - return Response("ok") - except : - return Response("nok") - -## to update audited csv via api -class AuditedFileUpdate(APIView): - def post(self,request): - facade_script_id = request.data['facade_script_id'] - script_file = request.data['script_file'] - audited_file_name = str(facade_script_id) + ".csv" - req_file = ContentFile(script_file.read(),audited_file_name) - try: - File.objects.create( - script= Script.objects.get(id=facade_script_id), - type="script-csv", - file=req_file, - ) - return Response("ok") - except : - return Response("nok") - - -## to update audited report via api -class AuditedReportUpdate(APIView): - def post(self,request): - facade_script_id = request.data['facade_script_id'] - script_file = request.data['script_file'] - audited_file_name = str(facade_script_id) + "_report.docx" - req_file = ContentFile(script_file.read(),audited_file_name) - try: - File.objects.create( - script= Script.objects.get(id=facade_script_id), - type="audit-report", - file=req_file, - ) - return Response("ok") - except : - return Response("nok") + else: + to_email = [user.email] + email_code = 'SB2' + key_value_aud = { "script_name" : str(screenplay_name)} + sendmail(to_email=to_email , email_code=email_code, key_value = key_value_aud ) + + Response = UploadScriptAuditData(OWNER_KEY,blockchain_obj.publicKey,blockchain_obj.user_id,script_id,str(audit_data)) + print("tx_hash",Response) + hash = hash_decrypation(hash) + #certificate = certificateGenrate(request.user.username,"script audit",hash) + tx_id = Response + + # certificate = certificateGenrate(request.user.username,"script audit",tx_id,projectname=script_file_name,matic=gasprice) + + to_email = [user.email] + email_code = 'BL1' + key_value = { + "service":"Orginal Script Audit", + "hash": hash, + "public key":blockchain_obj.publicKey, + "private key":userkey, + "Transaction Hash": tx_id, + } + certificate = certificateGenrate(user.username,"script audit",tx_id,projectname=script_file_name,matic=gasprice) + sendmail(to_email=to_email , email_code=email_code, key_value=key_value, filePath=certificate) + + print("::::::::::::::",key_value) + print("userkey = ", userkey) -def audit_thread_one(request, author, screenplay_name, file, language): - result = filesystem.new_screenplay( - request.user, - author, - screenplay_name, - file, - "script-original", - language, - ) - script_id = result.get("script", {}).get("id") +""" +# # KITCHEN ACCEPT CODE - try: - file_to_original = File.objects.get( - script=script_id, - type="script-original" - ) - status = ScriptAuditModel.objects.get( - script_id=script_id - ) - key_value = {"script_name" : screenplay_name} - if status.status == "SUCCESS": - script = Script.objects.get(id=script_id) - user_id = script.screenplay.user.id - to_email = [request.user.email] - email_code = 'SB1' - sendmail(to_email=to_email, email_code=email_code ,key_value = key_value) - elif status.status == "FAILURE": - to_email = [request.user.email] - email_code = 'SB2' - sendmail(to_email=to_email, email_code=email_code ,key_value = key_value) - except Script.DoesNotExist: - print(f"Script with ID {script_id} does not exist.") +def run_audit(msg): + body_dict = json.loads(msg.body) + msg.delete() + user = body_dict.get("user") + s3_url = body_dict.get("s3-file-path") + screenplay_name = body_dict.get("screenplay_name") + author = body_dict.get("author") + language = body_dict.get("language") + script_ext = body_dict.get("script_ext") + script_file_name = body_dict.get("script_file_name") + language = "en" + print("112") + object_key = "INPUT/" + str(script_file_name) + local_file_path = "/home/ubuntu/Conversion_Kitchen_Code/kitchen_counter/media/audit_counter_files/" + script_file_name + s3_client = boto3.client('s3', + aws_access_key_id="AKIAQVLBBGCB45RMLKVW", + aws_secret_access_key="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", + region_name="ap-south-1" + ) + print(object_key, local_file_path) + s3_client.download_file("conversion-kitchen", object_key, local_file_path) + audit_parameters = { + "service_type" : "audit", + "user":user, + "s3-file-path": local_file_path, + "screenplay_name": screenplay_name, + "author": author, + "language": language, + "script_ext": script_ext, + "script_file_name": script_file_name + } + run_audit_in_counter(audit_parameters) +""" - print("script id is", script_id) - -def audit_thread_two(): - # return redirect("audit_processing_page") - return redirect("new_audited_page") - - - -# class AuditHomeView(APIView): -# authentication_classes = [BasicAuthentication,SessionAuthentication] -# permission_classes = [IsAuthenticated] -# def get(self, request): -# form = AuditForm() -# return render(request, "audit/audit.html", {"form": form}) - -# def post(self, request): -# form = AuditForm(request.POST, request.FILES) -# if form.is_valid(): -# screenplay_name = form.cleaned_data["screenplay_name"] -# author = form.cleaned_data["author_name"] -# language = form.cleaned_data["language"] -# script_file = form.cleaned_data["script_file"] - -# script_ext = script_file.name.split(".")[-1] -# script_file_name = screenplay_name + "." + script_ext -# file = ContentFile( -# script_file.read(), -# script_file_name, -# ) -# print("############AUDIT THREAD$$$$$$$$$$") - -# thread1 = threading.Thread(target=audit_thread_one, args=(request, author, screenplay_name, file, language)) -# thread2 = threading.Thread(target=audit_thread_two) - -# # Start threads -# thread1.start() -# thread2.start() - -# # Wait for threads to complete -# # thread1.join() -# # thread2.join() - - -# print("All tasks completed") -# # return redirect("audit_processing_page") -# return redirect("new_audited_page") -# else : - -# return HttpResponseBadRequest(render(request, "audit/audit.html", {"form": form,"errors": form.errors})) - - -# class AuditHomeView(APIView): -# authentication_classes = [BasicAuthentication,SessionAuthentication] -# permission_classes = [IsAuthenticated] -# def get(self, request): -# form = AuditForm() -# return render(request, "audit/audit.html", {"form": form}) - -# def post(self, request): -# form = AuditForm(request.POST, request.FILES) -# if form.is_valid(): -# screenplay_name = form.cleaned_data["screenplay_name"] -# author = form.cleaned_data["author_name"] -# language = form.cleaned_data["language"] -# script_file = form.cleaned_data["script_file"] - -# script_ext = script_file.name.split(".")[-1] -# script_file_name = screenplay_name + "." + script_ext -# # Blockchain_script_id = int(time.time()) -# # request.session["Blockchain_script_id"] = Blockchain_script_id - -# file = ContentFile( -# script_file.read(), -# script_file_name, -# ) - -# result = filesystem.new_screenplay( -# request.user, -# author, -# screenplay_name, -# file, -# "script-original", -# language, -# ) - -# script_id = result.get("script", {}).get("id") -# # print("calling blockchain function") -# file_to_original = File.objects.get( -# script=script_id, -# type="script-original" - -# ) -# status = ScriptAuditModel.objects.get( -# script = Script.objects.get( -# id = script_id -# )) -# if status.status == "SUCCESS": -# try: -# script = Script.objects.get(id=script_id) -# #no_of_pages = script.no_of_pages -# user_id = script.screenplay.user.id -# except Script.DoesNotExist: -# print(f"Script with ID {script_id} does not exist.") -# # Handle the case when the script is not found -# to_email = [request.user.email] -# email_code = 'SB1' -# sendmail(to_email=to_email , email_code=email_code ) - -# elif status.status == "FAILURE": -# email_code = 'SB2' -# sendmail(to_email=to_email , email_code=email_code ) -# pass - -# print("script id is", script_id) -# return redirect("audit_processing_page") - -# else : - -# return HttpResponseBadRequest(render(request, "audit/audit.html", {"form": form,"errors": form.errors})) - - -class AuditHomeView(APIView): - authentication_classes = [BasicAuthentication,SessionAuthentication] - permission_classes = [IsAuthenticated] - def get(self, request): - - # context = create_indent(request) - - form = AuditForm() - # return multilingual_render(request, "audit/audit.html", {"form": form}) - return render(request, "audit/audit.html", {"form": form}) - - def post(self, request): - form = AuditForm(request.POST, request.FILES) - if form.is_valid(): - screenplay_name = form.cleaned_data["screenplay_name"] - author = form.cleaned_data["author_name"] - language = form.cleaned_data["language"] - script_file = form.cleaned_data["script_file"] - - script_ext = script_file.name.split(".")[-1] - script_file_name = screenplay_name + "." + script_ext - Blockchain_script_id = int(time.time()) - request.session["Blockchain_script_id"] = Blockchain_script_id - - file = ContentFile( - script_file.read(), - script_file_name, - ) - - result = filesystem.new_screenplay( - request.user, - author, - screenplay_name, - file, - "script-original", - language, - ) - - script_id = result.get("script", {}).get("id") - - print("calling blockchain function") - file_to_original = File.objects.get( - script=script_id, - type="script-original" - - ) - status = ScriptAuditModel.objects.get( - script = Script.objects.get( - id = script_id - )) - print("STATUS AUDIT",status) - - # Blockchain - # if UserCredentialsForBlockchain.objects.filter(user=request.user).exists(): - blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user) - script_original= {} - audit_data={} - script_original["status"] = "STARTED" - script_original["script_id"] = script_id - with open(file_to_original.file.path, 'rb') as file: - hash = uploadDataToIPFSNode(file) - script_original["script_file"] = hash - script_original["type"] = "script-original" - script_original["script_file_path"] = file_to_original.file.path - audit_data["script-original"] = script_original - userkey= decryptionOfPrivate(blockchain_obj.privateKey) - print("userkey = ", str(userkey)) - # status,getData = getScriptAudit(userkey.decode('utf-8'),user_id,str(script_id)) - privatekeyfordb = userkey.decode('utf-8') - print(privatekeyfordb) - status.bchain_privatekey = privatekeyfordb - status.save() - print("blockchain_obj.publicKey",blockchain_obj.publicKey) - print("blockchain_obj.privateKey",blockchain_obj.privateKey) - if status.status == "SUCCESS": - file_to_audit = File.objects.get( - script=script_id, - type="script-csv" - ) - file_to_audit_report = File.objects.get( - script=script_id, - type="audit-report" - ) - hash2 = "" - try: - file_to_audit_docx = File.objects.get( - script=script_id, - type="script-docx" - ) - script_docx = {} - script_path1 = file_to_audit_docx.file.path - script_size = file_to_audit_docx.file.size - with open(script_path1, 'rb') as _file: - hash2 = uploadDataToIPFSNode(_file) - script_docx["script_file_path"] = script_path1 - script_docx["script_file"] = hash2 - script_docx["type"] = "script-docx" - audit_data["script-docx"] = script_docx - except: - pass - script_csv = {} - audit_report ={} - audit_report_path = file_to_audit_report.file.path - script_path = file_to_audit.file.path - script_size = file_to_audit.file.size - - print("script_file_path_is_here",script_path) - with open(script_path, 'rb') as _file: - hash1 = uploadDataToIPFSNode(_file) - script_csv["script_file"] = hash1 - script_csv["script_file_path"] = script_path - script_csv["type"] = "script-csv" - with open(audit_report_path, 'rb') as file1: - hash2 = uploadDataToIPFSNode(file1) - audit_report["script_file"] = hash2 - audit_report["script_file_path"] = audit_report_path - audit_report["type"] = "audit-report" - audit_data["script-csv"]= script_csv - audit_data["audit-report"]= audit_report - with open("/home/mnftaj/mnf_march22/MNF/app/Blockchain2/file_stroge.txt","a") as file01: - file01.write("audit userkey------------------SUCCESS1 HOME AUDIT\n") - Response,gasprice = UploadScriptAuditData(OWNER_KEY,blockchain_obj.publicKey,blockchain_obj.user_id,script_id,str(audit_data)) - print("tx_hash",Response) - with open("/home/mnftaj/mnf_march22/MNF/app/Blockchain2/file_stroge.txt","a") as file01: - file01.write("audit userkey------------------SUCCESS\n"+str(Response)) - transactioni_id = str(Response) - # with open("/home/mnfbeta/mnf/app/Blockchain2/file_stroge.txt","a") as file01: - # file01.write(f"Transaction hash for audit is {str(transactioni_id)}\n") - # current_time = datetime.now() - # formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S") - # file01.write(f"Transaction hash for audit is {str(type(transactioni_id))}\n") - # file01.write(f" time for the above transaction id {str(formatted_time)}\n") - # audit_model_obj = ScriptAuditModel.objects.get( - # script = Script.objects.get(id = script_id)) - status.transaction_hash =str(transactioni_id) - # audit_model_obj.transaction_hash = str(transactioni_id) - # audit_model_obj.save() - status.save() - - # user_infos = user_info(tx_hash=Response,service="Script Audit",gas_fee=gasprice) - # addition_result = user_infos.update_info(request) - hash2 = hash_decrypation(hash2) - tx_id = Response - certificate = certificateGenrate(request.user.username,"script audit",tx_id,projectname=script_file_name,matic=gasprice) - to_email = [request.user.email] - email_code = 'BL1' - key_value = { - "service":"Audited Script", - "hash": hash2, - "public key":blockchain_obj.publicKey, - "Transaction Hash": tx_id, - } - print("userkey = ", userkey) - sendmail(to_email=to_email , email_code=email_code, key_value=key_value, filePath=certificate) - - print("mail send sucessfully:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::") - else: - with open("/home/mnftaj/mnf_march22/MNF/app/Blockchain2/file_stroge.txt","a") as file01: - file01.write("audit userkey------------------else\n") - Response = UploadScriptAuditData(OWNER_KEY,blockchain_obj.publicKey,blockchain_obj.user_id,script_id,str(audit_data)) - print("tx_hash",Response) - hash = hash_decrypation(hash) - #certificate = certificateGenrate(request.user.username,"script audit",hash) - tx_id = Response - - # certificate = certificateGenrate(request.user.username,"script audit",tx_id,projectname=script_file_name,matic=gasprice) - - to_email = [request.user.email] - email_code = 'BL1' - key_value = { - "service":"Orginal Script Audit", - "hash": hash, - "public key":blockchain_obj.publicKey, - "private key":userkey, - "Transaction Hash": tx_id, - } - - print("::::::::::::::",key_value) - print("userkey = ", userkey) - # sendmail(to_email=to_email , email_code=email_code,key_value=key_value,filePath=certificate) - - - if status.status == "SUCCESS": - try: - script = Script.objects.get(id=script_id) - no_of_pages = script.no_of_pages - user_id = script.screenplay.user.id - except Script.DoesNotExist: - print(f"Script with ID {script_id} does not exist.") - # Handle the case when the script is not found - # You might want to return an error response or raise an exception. - - try: - update_juggernaut(request, service_name='audit', audit_pages=int(no_of_pages)) - except Exception as e: - print("Failed to update Juggernaut:", e) - # Handle the case when the update_juggernaut function fails. - to_email = [request.user.email] - email_code = 'SB1' - - - sendmail(to_email=to_email , email_code=email_code ) - - # send_email_to_user(request.user,screenplay_name,"MyNextFilm: Successfully Audited Your Script ","Woohoo ! Your Script is Audited SuccessFully ") - - elif status.status == "FAILURE": - to_email = [request.user.email] - email_code = 'SB2' - - sendmail(to_email=to_email , email_code=email_code ) - # send_email_to_user(request.user,screenplay_name,"MyNextFilm: Auditing was Unsuccessfull ","Oops! Something went wrong and Your Script is Not Audited ") - # ## to be run via scriptpage - print("script id is", script_id) - # run_service(script_id,'audit') - # audit_in_background(script_id) - # time.sleep(3) - # return redirect("my_audited_scripts") - return redirect("new_audited_page1") - # return multilingual_render(request, "audit/audit_processing.html", None) - else : - # return HttpResponseBadRequest(multilingual_render(request, "audit/audit.html", {"form": form,"errors": form.errors})) - return HttpResponseBadRequest(render(request, "audit/audit.html", {"form": form,"errors": form.errors})) - -def audit_processing_view(request): - # multilingual_render the HTML template and return it as a response - # return multilingual_render(request, 'audit/audit_processing.html') - print("<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>") - print(get_current_site(request).domain) - return render(request, 'audit/audit_processing.html') - - -# class AuditedScriptsView(APIView): -# authentication_classes = [BasicAuthentication,SessionAuthentication] -# permission_classes = [IsAuthenticated] -# def get(self, request): -# display_list = [] -# scripts = Script.objects.filter(screenplay__user=request.user).order_by('-created_on') -# # try: -# # print("scripts list:",scripts) -# # except: -# # pass - -# for script in scripts: - -# if ScriptAuditModel.objects.filter(script=script).exists(): -# # audit_status_objects = AuditStatus.objects.filter(script=str(script.id)) -# audit_status_objects = ScriptAuditModel.objects.filter(script=script) -# for audit_status_object in audit_status_objects: -# script_audit_status = audit_status_object.status -# if script_audit_status == States.SUCCESS: -# display_list.append( -# { -# "scriptid": str(script.id), -# "scriptName": str(script.screenplay.name), -# "author": str(script.screenplay.author), -# "iscomplete": "S", -# "created_on" : str(script.created_on.astimezone(pytz.timezone('Asia/Kolkata')).strftime("%B %d, %Y %I:%M %p")), -# } -# ) -# elif script_audit_status == States.FAILURE: -# display_list.append( -# { -# "scriptid": str(script.id), -# "scriptName": str(script.screenplay.name), -# "author": str(script.screenplay.author), -# "iscomplete": "F", -# "created_on" : str(script.created_on.astimezone(pytz.timezone('Asia/Kolkata')).strftime("%B %d, %Y %I:%M %p")), -# } -# ) -# elif script_audit_status == States.STARTED: -# display_list.append( -# { -# "scriptid": str(script.id), -# "scriptName": str(script.screenplay.name), -# "author": str(script.screenplay.author), -# "iscomplete": "R", -# "created_on" : str(script.created_on.astimezone(pytz.timezone('Asia/Kolkata')).strftime("%B %d, %Y %I:%M %p")), -# } -# ) -# elif script_audit_status == States.PENDING: -# continue -# print(get_current_site(request).domain) -# return render( -# request, -# "audit/audited.html", -# {"i": display_list, "url": url}, -# ) - -class AuditedScriptsView_kunal(APIView): +class AuditedScriptsView_Without_blockchain(LoginRequiredMixin, APIView): + login_url = "/personal-login" authentication_classes = [BasicAuthentication,SessionAuthentication] permission_classes = [IsAuthenticated] def get(self, request): @@ -1165,7 +704,10 @@ class AuditedScriptsView_kunal(APIView): "audit/audited_copy.html", {"i": display_list, "url": url}, ) -class AuditedScriptsView_kunal1(APIView): + + +class AuditedScriptsView_With_Blockchain(LoginRequiredMixin, APIView): + login_url = "/personal-login" authentication_classes = [BasicAuthentication,SessionAuthentication] permission_classes = [IsAuthenticated] def get(self, request): @@ -1180,7 +722,7 @@ class AuditedScriptsView_kunal1(APIView): audit_status_objects = ScriptAuditModel.objects.filter(script=script) for audit_status_object in audit_status_objects: script_audit_status = audit_status_object.status - if script_audit_status == States.SUCCESS: + if script_audit_status == States.SUCCESS and audit_status_object.only_audit == True: extimated_time = audit_status_object.expected_duration no_of_pages = audit_status_object.number_of_pages screenplay_language = audit_status_object.screenplay_language @@ -1213,7 +755,7 @@ class AuditedScriptsView_kunal1(APIView): "isfdx" : str(isfdx) } ) - elif script_audit_status == States.FAILURE: + elif script_audit_status == States.FAILURE and audit_status_object.only_audit == True: display_list.append( { "scriptid": str(script.id), @@ -1223,7 +765,7 @@ class AuditedScriptsView_kunal1(APIView): "created_on" : str(script.created_on.astimezone(pytz.timezone('Asia/Kolkata')).strftime("%B %d, %Y %I:%M %p")), } ) - elif script_audit_status == States.STARTED: + elif script_audit_status == States.STARTED and audit_status_object.only_audit == True: extimated_time = audit_status_object.expected_duration no_of_pages = audit_status_object.number_of_pages display_list.append( @@ -1236,7 +778,7 @@ class AuditedScriptsView_kunal1(APIView): "extimated_time": str(extimated_time), } ) - elif script_audit_status == States.PENDING: + elif script_audit_status == States.PENDING and audit_status_object.only_audit == True: continue url = get_current_site(request).domain return render( @@ -1245,95 +787,9 @@ class AuditedScriptsView_kunal1(APIView): {"i": display_list, "url": url}, ) -class CheckDomain(APIView): - authentication_classes = [JWTAuthentication] - permission_classes = [IsAuthenticated] - def get(self, request): - domain_name = (get_current_site(request).domain) - return Response(f"Audit started {domain_name}") - -class AuditView(APIView): - authentication_classes = [JWTAuthentication] - permission_classes = [IsAuthenticated] - def get(self, request, script_id): - audit_in_background(script_id) - return Response("Audit started") - - - -class CharacterListView(APIView): - authentication_classes = [JWTAuthentication] - permission_classes = [IsAuthenticated] - def get(self, request, script_id): - audit = NeutralAudit(script_id) - char_lst = audit.get_character_list() - # char_sub = audit.get_character_subset(char_lst) - char_sub = audit.get_character_subset(char_lst) - return Response([char_lst, char_sub]) - - -def generate_script_id(path,request): - input_file = os.path.basename(path) - input_file1 = os.path.splitext(input_file)[0] - now = datetime.now() - screenplay_name = input_file1 +"_"+ now.strftime("%d-%m-%Y_%H-%M-%S_") - author = "SELF_DEFINED" - language = "en" - script_file = path - script_ext = script_file.split(".")[-1] - script_file_name = screenplay_name + "." + script_ext - print(script_file_name) - with open(path, "rb") as script_file: - file = ContentFile(script_file.read(), - script_file_name, - ) - result = filesystem.new_screenplay( - request.user, - author, - screenplay_name, - file, - "script-original", - language, - ) - script_id = result.get("script", {}).get("id") - print("\n\n\n\nSCRIPT____ID :",script_id,"\n\n\n\n") - return script_id - -def check_audit_status(request): - scripts = Script.objects.filter(screenplay__user=request.user) - for script in scripts: - # audit_exists = File.objects.filter(script=str(script.id),type='script-csv').exists() - # if AuditStatus.objects.filter(script=str(script.id)).exists(): - if ScriptAuditModel.objects.filter(script=script).exists(): - # audit_status_objects = AuditStatus.objects.filter(script=str(script.id)) - audit_status_objects = ScriptAuditModel.objects.filter(script=script) - for audit_status_object in audit_status_objects: - script_audit_status = audit_status_object.status - while script_audit_status != States.SUCCESS: - if script_audit_status == States.SUCCESS: - return "SUCCESS" - - if script_audit_status == States.FAILURE: - return "FAILURE" - - -def write_dict_to_file(file_path, dictionary): - try: - with open(file_path, 'w') as file: - json.dump(dictionary, file) - print("Dictionary successfully written to the file.") - except IOError: - print("Error: Unable to open the file.") - -def audit_vector_gen(request,path,mnf_db_id): - filesystem_id = generate_script_id(path,request) - audit_in_background(filesystem_id) - - pass class DownloadScriptFromBlockchain(APIView): - #authentication_classes = [JWTAuthentication] authentication_classes = [BasicAuthentication,SessionAuthentication] permission_classes = [IsAuthenticated] """ @@ -1370,512 +826,63 @@ class DownloadScriptFromBlockchain(APIView): if UserCredentialsForBlockchain.objects.filter(user=request.user).exists(): blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user) userkeys = decryptionOfPrivate(blockchain_obj.privateKey) - UserId = blockchain_obj.user_id - with open("/home/mnftaj/mnf_march22/MNF/app/Blockchain2/file_stroge.txt","a") as file01: - file01.write("1.user private key-------------------" + str(userkeys) + "\n") - with open("/home/mnftaj/mnf_march22/MNF/app/Blockchain2/file_stroge.txt","a") as file01: - file01.write("1.user script_id -------------------" + str(script_id) + "\n") - status,getdata = getScriptAudit(privatekey1,UserId,str(script_id)) - print(status,">>>>>>>>>>>>>>>>>>>>") - if status == True: - self.auditData = eval(getdata[1]) - else: - return HttpResponse(f'External API returned a non-200 status code.{getdata}', status=500) - except: - pass - - self.file_model_objects = File.objects.filter(script=script_id) - print(">><<>><<") - print(">><<>><<",self.file_model_objects) - - - if not self.file_model_objects.exists(): - raise spex.ScriptDoesNotExist() - if file_type == "script-json": - try: - # self.query_file = self.file_model_objects.get(type=file_type) - try: - query_file1 = self.auditData.get(file_type) - print("###########", str(self.auditData)) - file_hash = query_file1.get('script_file') - file_name = str((str(query_file1['script_file_path']).split("/"))[-1]) - geting_files = str(decryptionOflocalUrl(file_hash)) - print("########GETTING",geting_files ) - print(type(geting_files)) - # Fetch the JSON data from the URL - response = requests.get(str(geting_files)) - print("#####RESPONSE####", response) - if response.status_code == 200: - # Parse the JSON data - json_data = response.json() - print("##########JSON DATA #######") - print(json_data) - # Return the JSON data as a response - return JsonResponse({"script-json": json_data}, status=200) - return JsonResponse({"response didnt work": str(geting_files), "message": "File type is script-json"}, status=200) - except Exception as exp: - # err = repr(exp) - return JsonResponse({"fail": repr(exp), "message": "File type is script-json"}, status=400) - except: - pass - - return JsonResponse({"failing": "not----", "message": "File type is script-json"}, status=400) - - try: - self.query_file = self.file_model_objects.get(type=file_type) - try: - query_file1 = self.auditData.get(file_type, {}) - except: - pass - - except django_exception.ObjectDoesNotExist: - try: - query_file2 = self.auditData.get("script-csv", {}) - file_hash1 = query_file2.get('script_file') - file_path1 = query_file2.get('script_file_path') - download_file_System(file_hash1,file_path1) - self.auditData.get("script-docx",{}) - if file_type == "script-docx": - self._check_docx() - - elif file_type == "script-pdf": - self._check_pdf() - - if UserCredentialsForBlockchain.objects.filter(user=request.user).exists(): - blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user) - userkeys = decryptionOfPrivate(blockchain_obj.privateKey) + publickey = mypublickey(privatekey1) + if publickey == blockchain_obj.publicKey: UserId = blockchain_obj.user_id - status,getdata = getScriptAudit(userkeys.decode('utf-8'),UserId,str(script_id)) + status,getdata = getScriptAudit(privatekey1,UserId,str(script_id)) + print(status,">>>>>>>>>>>>>>>>>>>>") if status == True: self.auditData = eval(getdata[1]) - query_file1 = self.auditData[file_type] - except: - if file_type == "script-docx": - self._check_docx() + else: + return JsonResponse({"status":False, "error": "This Transcation Is Not Found On The Blockchain.",},status=500) + else: + return JsonResponse({"status":False, "error": "Your Private Key Is Worng", "key": str(userkeys)},status=500) + else: + return JsonResponse({"status":False, "error": "Your Wallet is Not Created",},status=500) + except Exception as e: + return JsonResponse({"status":False, "error": "Private key Format Wrong",},status=500) + + if file_type == "script-json": + # self.query_file = self.file_model_objects.get(type=file_type) + try: + query_file1 = self.auditData.get(file_type) + file_hash = query_file1.get('script_file') + file_name = str((str(query_file1['script_file_path']).split("/"))[-1]) + geting_files = str(decryptionOflocalUrl(file_hash)) + # Fetch the JSON data from the URL + response = requests.get(str(geting_files)) + if response.status_code == 200: + # Parse the JSON data + json_data = response.json() + # Return the JSON data as a response + return JsonResponse({"script-json": json_data}, status=200) + return JsonResponse({"response didnt work": str(geting_files), "message": "File type is script-json"}, status=200) + except Exception as exp: + # err = repr(exp) + return JsonResponse({"fail": repr(exp), "message": "File type is script-json"}, status=400) + + try: + query_file1 = self.auditData[file_type] + except Exception as exp: + return JsonResponse({"status":False, "error": "The File Does Not Exist On The Blockchain",},status=500) - elif file_type == "script-pdf": - self._check_pdf() + file_path = query_file1.get('script_file_path') - file_path = self.query_file.file.path - file_size = self.query_file.file.size - - # file_path = query_file1.get('script_file_path') - # file_size = query_file1.get('script_file_size') try: file_hash = query_file1.get('script_file') file_name = str((str(query_file1['script_file_path']).split("/"))[-1]) except: pass - - - # file_path = self.latest_file.file.path - # file_size = self.latest_file.file.size try: print("file_path") print(file_path) geting_files = decryptionOflocalUrl(file_hash) - # response = requests.get(geting_files, stream=True) - # if response.status_code == 200: - # content_type = response.headers['Content-Type'] # Change to the appropriate format - # response = HttpResponse(response.iter_content(chunk_size=8192), content_type=content_type) - # response[ - # 'Content-Disposition'] = f"attachment; filename={self.query_file.script.screenplay.name + '_' + str(self.query_file)}.{file_path.rsplit('.',1)[1]}" - # return response - # else: - # return HttpResponse('External API returned a non-200 status code.', status=500) return JsonResponse({"status":True, "download_link": geting_files, "file_name": str(file_name)}) - - except: - mimetype, _ = mimetypes.guess_type(file_path) - - response = FileResponse(self.query_file.file, content_type=mimetype) - response['Content-Length'] = file_size - response[ - 'Content-Disposition'] = f"attachment; filename={self.query_file.script.screenplay.name + '_' + str(self.query_file)}.{file_path.rsplit('.',1)[1]}" - return response - - - - def _check_docx(self) -> None: - """ - When docx not found this function can create docx of script for available formats. - """ - try: - audit_file_object = self.file_model_objects.get(type="script-csv") - except django_exception.ObjectDoesNotExist: - self._download_original() - return - - df = pd.read_csv(audit_file_object.file) - docx = utilities.csv_to_docx(df) - - temp_file_stream = BytesIO() - docx.save(temp_file_stream) - temp_file_stream.seek(0) - - docx_file = ContentFile( - temp_file_stream.getvalue(), - "from_audited_csv_to_document.docx", - ) - - self.query_file = File.objects.create( - script=audit_file_object.script, - file=docx_file, - type="script-docx", - ) - try: - if UserCredentialsForBlockchain.objects.filter(user=self.user).exists(): - blockchain_obj = UserCredentialsForBlockchain.objects.get(user=self.user) - userkeys = decryptionOfPrivate(blockchain_obj.privateKey) - UserId = blockchain_obj.user_id - status,getdata = getScriptAudit(self.privatekey1,UserId,str(self.Blockchain_script)) - if status == True: - audit_data = eval(getdata[1]) - file_to_audit = File.objects.get( - script=self.Blockchain_script, - type="script-docx" - ) - script_docx = {} - script_path = file_to_audit.file.path - script_size = file_to_audit.file.size - with open(script_path, 'rb') as _file: - hash = uploadDataToIPFSNode(_file) - script_docx["script_file_path"] = script_path - script_docx["script_file"] = hash - script_docx["type"] = "script-docx" - script_docx["script_file_size"] = script_size - audit_data["script-docx"] = script_docx - Response = UploadScriptAuditData(OWNER_KEY,blockchain_obj.publicKey,blockchain_obj.user_id,self.Blockchain_script,str(audit_data)) - print("tx_hash",Response) - except: - pass - - temp_file_stream.close() - - def _check_pdf(self) -> None: - """ - When pdf not found this function can create docx of script for available formats. - """ - print("I am printing in _check_pdf method") - if not self.file_model_objects.filter(type="script-docx").exists(): - self._check_docx() - - try: - docx_file_object = self.file_model_objects.get(type="script-docx") - except django_exception.ObjectDoesNotExist: - self._download_original() - return - - temp_dir = tempfile.TemporaryDirectory() - pdf_file_path = utilities.docx_to_pdf( - docx_file_object.file.path, temp_dir.name) - - with open(pdf_file_path, "rb") as temp_pdf: - - pdf_file = DjangoFile( - temp_pdf, - pdf_file_path.rsplit('/', 1)[1], - ) - - self.query_file = File.objects.create( - script=docx_file_object.script, - file=pdf_file, - type="script-pdf", - ) - - try: - if UserCredentialsForBlockchain.objects.filter(user=self.user).exists(): - blockchain_obj = UserCredentialsForBlockchain.objects.get(user=self.user) - userkeys = decryptionOfPrivate(blockchain_obj.privateKey) - UserId = blockchain_obj.user_id - status,getdata = getScriptAudit(self.privatekey1,UserId,str(self.Blockchain_script)) - if status == True: - audit_data = eval(getdata[1]) - file_to_audit = File.objects.get( - script=self.Blockchain_script, - type="script-pdf" - ) - script_pdf = {} - script_path = file_to_audit.file.path - script_size = file_to_audit.file.size - with open(script_path, 'rb') as _file: - hash = uploadDataToIPFSNode(_file) - script_pdf["script_file_path"] = script_path - script_pdf["script_file"] = hash - script_pdf["type"] = "script-pdf" - script_pdf["script_file_size"] = script_size - audit_data["script-pdf"] = script_pdf - Response = UploadScriptAuditData(OWNER_KEY,blockchain_obj.publicKey,blockchain_obj.user_id,self.Blockchain_script,str(audit_data)) - print("tx_hash",Response) - - except: - pass - self.latest_file = self.query_file - - def _download_original(self) -> None: - """ - used for downloafing the script-original when no other type of scripts are found. - This downloads the unaudited file. - """ - self.query_file = self.file_model_objects.get(type="script-original") - - - - -#download Audited Script - - -# class DownloadScript(APIView): - -# #authentication_classes = [JWTAuthentication] -# authentication_classes = [BasicAuthentication,SessionAuthentication] -# permission_classes = [IsAuthenticated] -# """ -# View for downloding scripts of desired type eg- docx, pdf -# """ - -# VALID_FILE_TYPES = ("script-docx", "script-pdf","script-original","audit-report") -# """ -# Files of only above types are allwed to be downloaded. -# """ - - -# def get(self, request) -> FileResponse: - -# if not "script_id" in request.query_params: -# raise spex.ScriptIdNotFound("script_id must be provided in body.") - -# if not "type" in request.query_params: -# raise spex.ScriptAuditException( -# "type(i.e. type of file) must be provided in body.") - -# script_id = request.query_params.get("script_id") -# file_type = request.query_params.get("type") - -# self.user = request.user -# self.Blockchain_script = script_id -# if not request.query_params.get("type") in self.VALID_FILE_TYPES: -# raise spex.IllegalFiletype(file_type, self.VALID_FILE_TYPES) - -# try: -# if UserCredentialsForBlockchain.objects.filter(user=request.user).exists(): -# blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user) -# userkeys = decryptionOfPrivate(blockchain_obj.privateKey) -# UserId = blockchain_obj.user_id -# status,getdata = getScriptAudit(userkeys.decode('utf-8'),UserId,str(script_id)) -# print(status,">>>>>>>>>>>>>>>>>>>>") -# if status == True: -# self.auditData = eval(getdata[1]) -# except: -# pass - -# self.file_model_objects = File.objects.filter(script=script_id) -# print(">><<>><<") -# print(">><<>><<",self.file_model_objects) - - -# if not self.file_model_objects.exists(): -# raise spex.ScriptDoesNotExist() - -# try: -# self.query_file = self.file_model_objects.get(type=file_type) -# try: -# query_file1 = self.auditData.get(file_type, {}) -# except: -# pass - -# except django_exception.ObjectDoesNotExist: -# try: -# query_file2 = self.auditData.get("script-csv", {}) -# file_hash1 = query_file2.get('script_file') -# file_path1 = query_file2.get('script_file_path') -# download_file_System(file_hash1,file_path1) -# self.auditData.get("script-docx",{}) -# if file_type == "script-docx": -# self._check_docx() - -# elif file_type == "script-pdf": -# self._check_pdf() - -# if UserCredentialsForBlockchain.objects.filter(user=request.user).exists(): -# blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user) -# userkeys = decryptionOfPrivate(blockchain_obj.privateKey) -# UserId = blockchain_obj.user_id -# status,getdata = getScriptAudit(userkeys.decode('utf-8'),UserId,str(script_id)) -# if status == True: -# self.auditData = eval(getdata[1]) -# query_file1 = self.auditData[file_type] -# except: -# if file_type == "script-docx": -# self._check_docx() - -# elif file_type == "script-pdf": -# self._check_pdf() - -# file_path = self.query_file.file.path -# file_size = self.query_file.file.size - -# # file_path = query_file1.get('script_file_path') -# # file_size = query_file1.get('script_file_size') -# try: -# file_hash = query_file1.get('script_file') -# except: -# pass - - -# # file_path = self.latest_file.file.path -# # file_size = self.latest_file.file.size -# try: -# print("file_path") -# print(file_path) -# geting_files = decryptionOflocalUrl(file_hash) -# response = requests.get(geting_files, stream=True) -# if response.status_code == 200: -# content_type = response.headers['Content-Type'] # Change to the appropriate format -# response = HttpResponse(response.iter_content(chunk_size=8192), content_type=content_type) -# response[ -# 'Content-Disposition'] = f"attachment; filename={self.query_file.script.screenplay.name + '_' + str(self.query_file)}.{file_path.rsplit('.',1)[1]}" -# return response -# else: -# return HttpResponse('External API returned a non-200 status code.', status=500) -# except: -# mimetype, _ = mimetypes.guess_type(file_path) - -# response = FileResponse(self.query_file.file, content_type=mimetype) -# response['Content-Length'] = file_size -# response[ -# 'Content-Disposition'] = f"attachment; filename={self.query_file.script.screenplay.name + '_' + str(self.query_file)}.{file_path.rsplit('.',1)[1]}" -# return response - - - -# def _check_docx(self) -> None: -# """ -# When docx not found this function can create docx of script for available formats. -# """ -# try: -# audit_file_object = self.file_model_objects.get(type="script-csv") -# except django_exception.ObjectDoesNotExist: -# self._download_original() -# return - -# df = pd.read_csv(audit_file_object.file) -# docx = utilities.csv_to_docx(df) - -# temp_file_stream = BytesIO() -# docx.save(temp_file_stream) -# temp_file_stream.seek(0) - -# docx_file = ContentFile( -# temp_file_stream.getvalue(), -# "from_audited_csv_to_document.docx", -# ) - -# self.query_file = File.objects.create( -# script=audit_file_object.script, -# file=docx_file, -# type="script-docx", -# ) -# try: -# if UserCredentialsForBlockchain.objects.filter(user=self.user).exists(): -# blockchain_obj = UserCredentialsForBlockchain.objects.get(user=self.user) -# userkeys = decryptionOfPrivate(blockchain_obj.privateKey) -# UserId = blockchain_obj.user_id -# status,getdata = getScriptAudit(userkeys.decode('utf-8'),UserId,str(self.Blockchain_script)) -# if status == True: -# audit_data = eval(getdata[1]) -# file_to_audit = File.objects.get( -# script=self.Blockchain_script, -# type="script-docx" -# ) -# script_docx = {} -# script_path = file_to_audit.file.path -# script_size = file_to_audit.file.size -# with open(script_path, 'rb') as _file: -# hash = uploadDataToIPFSNode(_file) -# script_docx["script_file_path"] = script_path -# script_docx["script_file"] = hash -# script_docx["type"] = "script-docx" -# script_docx["script_file_size"] = script_size -# audit_data["script-docx"] = script_docx -# Response = UploadScriptAuditData(OWNER_KEY,blockchain_obj.publicKey,blockchain_obj.user_id,self.Blockchain_script,str(audit_data)) -# print("tx_hash",Response) -# except: -# pass - -# temp_file_stream.close() - -# def _check_pdf(self) -> None: -# """ -# When pdf not found this function can create docx of script for available formats. -# """ -# print("I am printing in _check_pdf method") -# if not self.file_model_objects.filter(type="script-docx").exists(): -# self._check_docx() - -# try: -# docx_file_object = self.file_model_objects.get(type="script-docx") -# except django_exception.ObjectDoesNotExist: -# self._download_original() -# return - -# temp_dir = tempfile.TemporaryDirectory() -# pdf_file_path = utilities.docx_to_pdf( -# docx_file_object.file.path, temp_dir.name) - -# with open(pdf_file_path, "rb") as temp_pdf: - -# pdf_file = DjangoFile( -# temp_pdf, -# pdf_file_path.rsplit('/', 1)[1], -# ) - -# self.query_file = File.objects.create( -# script=docx_file_object.script, -# file=pdf_file, -# type="script-pdf", -# ) - -# try: -# if UserCredentialsForBlockchain.objects.filter(user=self.user).exists(): -# blockchain_obj = UserCredentialsForBlockchain.objects.get(user=self.user) -# userkeys = decryptionOfPrivate(blockchain_obj.privateKey) -# UserId = blockchain_obj.user_id -# status,getdata = getScriptAudit(userkeys.decode('utf-8'),UserId,str(self.Blockchain_script)) -# if status == True: -# audit_data = eval(getdata[1]) -# file_to_audit = File.objects.get( -# script=self.Blockchain_script, -# type="script-pdf" -# ) -# script_pdf = {} -# script_path = file_to_audit.file.path -# script_size = file_to_audit.file.size -# with open(script_path, 'rb') as _file: -# hash = uploadDataToIPFSNode(_file) -# script_pdf["script_file_path"] = script_path -# script_pdf["script_file"] = hash -# script_pdf["type"] = "script-pdf" -# script_pdf["script_file_size"] = script_size -# audit_data["script-pdf"] = script_pdf -# Response = UploadScriptAuditData(OWNER_KEY,blockchain_obj.publicKey,blockchain_obj.user_id,self.Blockchain_script,str(audit_data)) -# print("tx_hash",Response) - -# except: -# pass -# self.latest_file = self.query_file - -# def _download_original(self) -> None: -# """ -# used for downloafing the script-original when no other type of scripts are found. -# This downloads the unaudited file. -# """ -# self.query_file = self.file_model_objects.get(type="script-original") - + except: + return JsonResponse({"status":False, "error": "The File Does Not Exist On IPFS Node"},status=500) class DownloadScript(APIView): - #authentication_classes = [JWTAuthentication] authentication_classes = [BasicAuthentication,SessionAuthentication] permission_classes = [IsAuthenticated] """ @@ -1999,28 +1006,18 @@ class DownloadScript(APIView): self.query_file = self.file_model_objects.get(type="script-original") - -# @authentication_classes([SessionAuthentication, BasicAuthentication]) -# @permission_classes([IsAuthenticated]) class DeleteScriptAPIView(APIView): - # authentication_classes = [JWTAuthentication] - # permission_classes = [IsAuthenticated] authentication_classes = [BasicAuthentication,SessionAuthentication] permission_classes = [IsAuthenticated] def delete(self,request,screen_play): try: screenplay = ScreenPlay.objects.get(name=screen_play) - # scripts = Script.objects.filter(screenplay=screenplay) - # scripts.delete() screenplay.delete() return Response("Scripts deleted successfully.", status=status.HTTP_204_NO_CONTENT) except ScreenPlay.DoesNotExist: return Response(f"Screenplay with name '{screen_play}' does not exist.", status=status.HTTP_404_NOT_FOUND) - - - def string_to_audit(request,path): """ @@ -2081,4 +1078,31 @@ def string_to_audit(request,path): return script_id +def generate_script_id(path,request): + input_file = os.path.basename(path) + input_file1 = os.path.splitext(input_file)[0] + now = datetime.now() + screenplay_name = input_file1 +"_"+ now.strftime("%d-%m-%Y_%H-%M-%S_") + author = "SELF_DEFINED" + language = "en" + script_file = path + script_ext = script_file.split(".")[-1] + script_file_name = screenplay_name + "." + script_ext + print(script_file_name) + with open(path, "rb") as script_file: + file = ContentFile(script_file.read(), + script_file_name, + ) + result = filesystem.new_screenplay( + request.user, + author, + screenplay_name, + file, + "script-original", + language, + ) + script_id = result.get("script", {}).get("id") + print("\n\n\n\nSCRIPT____ID :",script_id,"\n\n\n\n") + return script_id +