def edit_problem(server_data): config = handle_config.read_config_json() problem_no = config["Code"][server_data["Problem Code"]] print('./Problems/Problem_' + problem_no[-1:-2:-1] + '.json') try: with open('./Problems/Problem_' + problem_no[-1:-2:-1] + '.json', 'r') as write: problem_file = json.load(write) problem_file = handle_config.encryptDecrypt( problem_file, config["Problem Key"]) problem_file = eval(problem_file) except Exception as Error: print(str(Error)) problem_file[server_data["Type"]] = server_data["Data"] try: problem_file = str(problem_file) problem_file = handle_config.encryptDecrypt( problem_file, config["Problem Key"]) with open('./Problems/Problem_' + problem_no[-1:-2:-1] + '.json', 'w') as write: json.dump(problem_file, write, indent=4) except Exception as Error: print(str(Error)) start_listening.queue.put(problem_no) start_listening.data_changed_flags[7] = 1
def sending(self, data_changed_flag): if data_changed_flag[0] == 0: QMessageBox.warning(self, 'Message', 'Contest not yet started.\nPlease wait.') elif data_changed_flag[0] == 4: QMessageBox.warning(self, 'Message', 'Contest has been ENDED') elif data_changed_flag[0] == 3: QMessageBox.warning( self, 'Message', 'Your Time Up.\n Now you cannot submit any query') else: config = handle_config.read_config_json() client_id = config["client_id"] client_key = config["client_key"] query = ui_widgets.ask_query.text() if (query == ''): QMessageBox.warning(self, 'Message', "Query Cannot be empty") # print("Don't be stupid") elif (len(query) > 499): QMessageBox.warning(self, 'Message', "Length of query cannot exceed 500 words") # print('Length of query cannot exceed 500 words') else: query_management.insert_query(query, 'Waiting for response') data_changed_flag[2] = 1 send_code.query_request(client_id, client_key, query, config["Username"], config["IP"]) QMessageBox.warning(self, 'Message', 'Your Query has been successfully send') return
def listen_server(rabbitmq_username, rabbitmq_password, host, data_changed_flags2, queue, scoreboard, channel): print('[ LISTEN ] Start listening...') start_listening.authenticate_login = handle_config.read_config_json() conn, cursor = manage_database.initialize_table() manage_local_ids.initialize_local_id(cursor) start_listening.cursor = cursor try: # creds = pika.PlainCredentials(rabbitmq_username, rabbitmq_password) # params = pika.ConnectionParameters(host = host, credentials = creds, heartbeat=0, blocked_connection_timeout=0) # connection = pika.BlockingConnection(params) # channel = connection.channel() start_listening.channel = channel # start_listening.connection = connection start_listening.host = host start_listening.data_changed_flags = data_changed_flags2 start_listening.queue = queue start_listening.scoreboard = scoreboard start_listening.channel.basic_consume( queue=start_listening.authenticate_login["Username"], on_message_callback=start_listening.server_response_handler, auto_ack=True) start_listening.channel.start_consuming() except (KeyboardInterrupt, SystemExit): print('[ DELETE ] Queue ' + start_listening.authenticate_login["Username"] + ' deleted...') print("[ STOP ] Keyboard interrupt") start_listening.channel.stop_consuming() start_listening.channel.queue_delete( start_listening.authenticate_login["Username"]) return except Exception as error: print('[ ERROR ] Shit ', error)
def show_problem(self, i, data_changed_flags): config = handle_config.read_config_json() if "Problem Key" in config: if data_changed_flags[0] == 0: QMessageBox.warning(self, 'Message', 'Contest not yet started.\nPlease wait.') else: try: with open('.\\Problems\\Problem_' + str(i) + '.json') as read: problem = json.load(read) problem = handle_config.encryptDecrypt( problem, config["Problem Key"]) problem = eval(problem) except Exception as Error: print(str(Error)) try: self.problem_window = view_problem_ui( str(i), data_changed_flags, problem) self.problem_window.show() except Exception as Error: print(str(Error)) else: QMessageBox.warning( self, 'Message', 'This incident has been reported.\n Contact Admin.') return
def server_response_handler(ch,method,properties,body): # Decoding the data json_data = str(body.decode('utf-8')) server_data = json.loads(json_data) # Extracting the status whether valid or invalid status = server_data['Code'] print("[ STATUS ] " + status) print(server_data) # If authentication is valid if (status == 'VALID'): print('[ ClientID ] receiving ......') # read config file config.json config = handle_config.read_config_json() # Add client id in the config file received by the server config["client_id"] = str(server_data["Client ID"]) config["Username"] = authenticate_login.username # update data in config file handle_config.write_config_json(config) # insert user detail for future use user_detail.insert_detail(server_data["Client ID"], authenticate_login.username) print("[ Status ] " + status + "\n[ ClientID ] : " + str(server_data["Client ID"]) + "\n[ Server ] : " + server_data["Message"]) # Changing login status to valid authenticate_login.login_status = 'VALID' authenticate_login.client_id = server_data["Client ID"] # authenticate_login.channel.basic_ack(True) authenticate_login.channel.stop_consuming() # authenticate_login.channel.basic_ack(True) # If login is rejected by the server elif (status == 'LRJCT'): authenticate_login.queue.put(server_data["Message"]) # Changing login status to rejected print('[ Authentication ] REJECTED ......') authenticate_login.login_status = 'LRJCT' # Delete the queue try: authenticate_login.channel.queue_delete( queue = authenticate_login.username ) except Exception as Error: print(str(Error)) authenticate_login.channel.basic_ack(True) # If login authentication is not valid else: print("Invalid Login!!!!") authenticate_login.login_status = 'INVLD' # Deleting the queue on which the client is listening try: authenticate_login.channel.queue_delete( queue = authenticate_login.username ) except Exception as Error: print(str(Error)) authenticate_login.channel.basic_ack(True)
def submit_call(self, data_changed_flag, ui_widgets): if data_changed_flag[0] == 0: QMessageBox.warning(self, 'Message', 'Contest not yet started.\nPlease wait.') elif data_changed_flag[0] == 4: QMessageBox.warning(self, 'Message', 'Contest has been ENDED') elif data_changed_flag[0] == 3: QMessageBox.warning( self, 'Message', 'Your Time Up.\n Now you cannot submit solution') else: try: config = handle_config.read_config_json() local_time = time.localtime() time_stamp = time.strftime("%H:%M:%S", local_time) textbox_value = ui_widgets.text_area.toPlainText() selected_language = str(ui_widgets.language_box.currentText()) problem_number = str(ui_widgets.problem_box.currentText()) print(problem_number) problem_code = config["Problems"][str( ui_widgets.problem_box.currentText())] problem_code = problem_code[1] if (selected_language == 'C'): extention = '.c' language_code = 'GCC' elif (selected_language == 'C++'): extention = '.cpp' language_code = 'CPP' elif (selected_language == 'JAVA'): extention = '.java' language_code = 'JVA' elif (selected_language == 'PYTHON-3'): extention = '.py' language_code = 'PY3' else: extention = '.py' language_code = 'PY2' local_id = manage_local_ids.get_new_id() client_id = config["client_id"] client_key = config["client_key"] username = config["Username"] print(local_id) submission_management.insert_verdict( local_id, client_id, 0, 'Queued', selected_language, language_code, problem_code, problem_number, time_stamp, textbox_value, extention) data_changed_flag[1] = 1 send_code.solution_request(problem_code, selected_language, time_stamp, textbox_value, local_id, client_key, username, config["IP"]) ui_widgets.text_area.setPlainText('') except Exception as Error: print(str(Error)) self.submission_counter = 0 return
def disconnect(server_data): print(server_data) if server_data["Client"] == 'All': start_listening.channel.stop_consuming() start_listening.data_changed_flags[5] = 2 else: config = handle_config.read_config_json() if config["Username"] == server_data["Client"]: start_listening.channel.stop_consuming() start_listening.data_changed_flags[5] = 1
def start_contest(self): global current_status global Timer data = handle_config.read_config_json() current_status = 'RUNNING' Timer = data["Duration"] # decrypt.decrypting() QMessageBox.warning( self, 'Info', 'Contest has been STARTED.\nNow you can view problems.')
def decrypting(): # read config file data = handle_config.read_config_json() psswd = handle_config.read_config_json() # read contest config file # with open('config.json', 'r') as contest: # psswd = json.load(contest) # loop to traverse every problem for i in range(data["No_of_Problems"]): try: with open('Problems/Problem_' + str(i + 1) + '.pdf', mode='rb') as problem: reader = PyPDF2.PdfFileReader(problem) # command to decrypt problem command = ("cp " + "Problems/Problem_" + str(i + 1) + ".pdf temp.pdf; qpdf --password="******"Problem Key"] + " --decrypt temp.pdf Problems/Problem_" + str(i + 1) + ".pdf; rm temp.pdf") os.system(command) except Exception as Error: print(str(Error))
def update_query(client_id, query, response, Type): # with open('config.json', 'r') as read_file: # config = json.load(read_file) config = handle_config.read_config_json() # if type will be broadcast the query wil be updated in every client's table if Type == 'Broadcast': # Query to check whether that query exist in the table or not manage_database.cur.execute( "SELECT exists(SELECT * FROM my_query WHERE Query = ?)", (query, )) existence_result = manage_database.cur.fetchall() # if exist then just update the table with the response if (existence_result[0][0]): # Update Query to update the table manage_database.cur.execute( "UPDATE my_query SET Response = ? WHERE Query = ?", ( response, query, )) manage_database.conn.commit() else: # Else insert it as a new query manage_database.cur.execute("INSERT into my_query values(?,?)", (query, response)) manage_database.conn.commit() # Else it will be updated in only the client's table who have raised that query else: # if client id matches then update the table if (str(client_id) == config["client_id"]): try: # Query to update the table manage_database.cur.execute( "UPDATE my_query SET Response = ? WHERE Query = ?", ( response, query, )) manage_database.conn.commit() except Exception as Error: print( "[ ERROR ] Could not update submission submission : " + str(error)) else: pass return #################################################################### ####################################################################
def closeEvent(self, event): message = "Pressing 'Yes' will SHUT the Client.\nAre you sure you want to exit?" detail_message = "Any active contest might end prematurely. " custom_close_box = QMessageBox() custom_close_box.setIcon(QMessageBox.Critical) custom_close_box.setWindowTitle('Warning!') custom_close_box.setText(message) custom_close_box.setInformativeText(detail_message) custom_close_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) custom_close_box.setDefaultButton(QMessageBox.No) button_yes = custom_close_box.button(QMessageBox.Yes) button_yes.setText('Yes') button_no = custom_close_box.button(QMessageBox.No) button_no.setText('No') button_yes.setObjectName("close_button_yes") button_no.setObjectName("close_button_no") button_yes.setStyleSheet(open('Elements/style.qss', "r").read()) button_no.setStyleSheet(open('Elements/style.qss', "r").read()) custom_close_box.exec_() if custom_close_box.clickedButton() == button_yes: try: config = handle_config.read_config_json() data = { "Code": "DSCNT", "IP": config["IP"], "Client Key": config["client_key"], "Username": config["Username"], "ID": config["client_id"], "Type": "CLIENT" } data = json.dumps(data) self.channel.basic_publish( exchange='connection_manager', routing_key='client_requests', body=data, ) except Exception as Error: print(str(Error)) event.accept() elif custom_close_box.clickedButton() == button_no: event.ignore()
def start_status(server_data): print(server_data) contest_start_time = time.time() # start_time = start_listening.convert_time_format(server_data["Start Time"]) config = handle_config.read_config_json() config["Duration"] = server_data["Duration"] config["Contest"] = "RUNNING" config["Problem Key"] = server_data["Problem Key"] # contest_start_time = start_time config["Start Time"] = contest_start_time initialize_contest.set_duration(config["Duration"]) contest_duration_seconds = initialize_contest.convert_to_seconds( initialize_contest.get_duration()) config["End Time"] = contest_duration_seconds + contest_start_time handle_config.write_config_json(config) start_listening.data_changed_flags[0] = 1 start_listening.data_changed_flags[4] = 2 print("[START] Signal received") print("Contest Duration : " + server_data["Duration"])
def __init__(self, channel, data_changed_flag2, queue, score): super().__init__() global current_status current_status = "STOPPED" global Timer # Set app icon self.setWindowIcon(QIcon('Elements/logo.png')) # Set window title self.setWindowTitle('BitsOJ v1.0.1 [ Client ]') # self.setFixedSize(1200,700) self.resize(1200, 700) self.timer = QTimer() self.change_flag = True self.timer.timeout.connect(self.update_data) self.timer.start(1000) self.score_timer = QTimer() self.change_flag_1 = True self.score_timer.timeout.connect(self.update_scoreboard) self.score_timer.start(1000) self.channel = channel # self.rows = 0 # self.columns = 5 # self.scoreboard = QTableWidget() # self.scoreboard.setEditTriggers(QAbstractItemView.NoEditTriggers) # self.scoreboard.setFixedHeight(650) # self.scoreboard.verticalHeader().setVisible(False) # self.scoreboard.setRowCount(self.rows) # self.scoreboard.setColumnCount(self.columns) # self.scoreboard.setHorizontalHeaderLabels(('Rank', 'Username', 'Score', 'Problems Solved', 'Time')) # self.scoreboard.horizontalHeader().setStretchLastSection(True) # self.scoreboard.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) config = handle_config.read_config_json() # score_data = handle_config.read_score_json() # if score_data != None: # score_data = eval(score_data["Data"]) # row_data = len(score_data) # self.scoreboard.setRowCount(row_data) # for i in range(row_data): # for j in range(5): # if j == 0: # self.scoreboard.setItem(i,j, QTableWidgetItem(str(i+1))) # self.scoreboard.item(i,j).setTextAlignment(Qt.AlignCenter) # else: # self.scoreboard.setItem(i,j, QTableWidgetItem(str(score_data[i][j-1]))) # self.scoreboard.item(i,j).setTextAlignment(Qt.AlignCenter) # if i == 0: # self.scoreboard.item(i,j).setForeground(QColor('#B29700')) # elif i == 1: # # self.scoreboard.item(i,j).setForeground(QColor('#AAA9AD')) # self.scoreboard.item(i,j).setForeground(QColor('#777777')) # elif i == 2: # self.scoreboard.item(i,j).setForeground(QColor('#CD7F32')) # elif score_data[i][0] == config["Username"]: # self.scoreboard.item(i,j).setForeground(QColor('#4B8B3B')) # else: # self.scoreboard.item(i,j).setForeground(QColor('#FFFFFF')) # Make data_changed_flag accessible from the class methods self.data_changed_flag = data_changed_flag2 if config["Contest"] == "RUNNING": self.setWindowTitle('BitsOJ v1.0.1 [ CLIENT ][ RUNNING ]') current_status = "RUNNING" Timer = config["Duration"] self.data_changed_flag[0] = 2 self.data_changed_flag[4] = 2 self.queue = queue self.scoreboard = score # Initialize status bar self.status = self.statusBar() #################################################################### self.db = self.init_qt_database() #################################################################### # Define Sidebar buttons and their actions button_width = 200 button_height = 50 self.button_1 = QPushButton('Problems', self) self.button_1.setFixedSize(button_width, button_height) self.button_1.clicked.connect(self.view_problems) self.button_1.setObjectName('sidebar_button') self.button_2 = QPushButton('Submissions', self) self.button_2.setFixedSize(button_width, button_height) self.button_2.clicked.connect(self.view_submissions) self.button_2.setObjectName('sidebar_button') self.button_3 = QPushButton('Submit Solution', self) self.button_3.setFixedSize(button_width, button_height) self.button_3.clicked.connect(self.submit_solution) self.button_3.setObjectName('sidebar_button') self.button_4 = QPushButton('Query', self) self.button_4.setFixedSize(button_width, button_height) self.button_4.clicked.connect(self.send_query) self.button_4.setObjectName('sidebar_button') self.button_5 = QPushButton('Leaderboard', self) self.button_5.setFixedSize(button_width, button_height) self.button_5.clicked.connect(self.ranklist) self.button_5.setObjectName('sidebar_button') self.button_6 = QPushButton('About', self) self.button_6.setFixedSize(button_width, button_height) self.button_6.clicked.connect(self.show_about) self.button_6.setObjectName('sidebar_button') ##################################################################### ##################################################################### # Manage tabs o the right window # Each tab is an object returned by the respective function associated with its UI # Tab UI are managed by interface_package/ui_classes.py file self.tab1 = ui_widgets.problems_ui(self) self.tab2, self.sub_model = ui_widgets.submissions_ui(self) self.tab3 = ui_widgets.submit_ui(self) self.tab4, self.query_model = ui_widgets.query_ui(self) self.tab5, self.score_model = ui_widgets.leaderboard_ui(self) self.tab6 = ui_widgets.about_ui(self) ##################################################################### # Add widgets to our main window client_window.init_UI(self, config) return
from PyQt5.QtWidgets import * from PyQt5.QtGui import QIcon, QPixmap, QTextCursor, QCursor, QFont, QColor from PyQt5.QtSql import QSqlTableModel, QSqlDatabase from PyQt5.QtCore import pyqtSlot, pyqtSignal, QObject, QTimer, Qt, QModelIndex, qInstallMessageHandler, QSize, QRect import os import time import json import webbrowser from functools import partial from manage_code import send_code from database_management import submission_management, query_management, manage_local_ids from init_client import handle_config config = handle_config.read_config_json() class ui_widgets(): ############################################################################# # Handle UI for various button presses var = {} def problems_ui(self): main_layout = QVBoxLayout() heading = QLabel('Problems') heading.setObjectName('main_screen_heading') column = 0 row = 0 number_of_buttons = 1
def extended_time(server_data): config = handle_config.read_config_json() time = server_data["Time"] config["End Time"] = config["End Time"] + time * 60 handle_config.write_config_json(config) start_listening.data_changed_flags[4] = 3
def __init__(self, channel, data_changed_flag2, queue, score): super().__init__() global current_status current_status = "STOPPED" global Timer # Set app icon self.setWindowIcon(QIcon("Elements\\logo.png")) # Set window title self.setWindowTitle('BitsOJ v1.33.5 [ Client ]') # self.setFixedSize(1200,700) self.resize(1200, 700) self.timer = QTimer() self.change_flag = True self.timer.timeout.connect(self.update_data) self.timer.start(1000) self.score_timer = QTimer() self.change_flag_1 = True self.score_timer.timeout.connect(self.update_scoreboard) self.score_timer.start(1000) self.channel = channel config = handle_config.read_config_json() # Make data_changed_flag accessible from the class methods self.data_changed_flag = data_changed_flag2 if config["Contest"] == "RUNNING": self.setWindowTitle('BitsOJ v1.33.5 [ CLIENT ][ RUNNING ]') current_status = "RUNNING" Timer = config["Duration"] self.data_changed_flag[0] = 2 self.data_changed_flag[4] = 2 self.queue = queue self.scoreboard = score # Initialize status bar self.status = self.statusBar() #################################################################### self.db = self.init_qt_database() #################################################################### # Define Sidebar buttons and their actions button_width = 200 button_height = 50 self.button_1 = QPushButton('Problems', self) self.button_1.setFixedSize(button_width, button_height) self.button_1.clicked.connect(self.view_problems) self.button_1.setObjectName('sidebar_button') self.button_2 = QPushButton('Submissions', self) self.button_2.setFixedSize(button_width, button_height) self.button_2.clicked.connect(self.view_submissions) self.button_2.setObjectName('sidebar_button') self.button_3 = QPushButton('Submit Solution', self) self.button_3.setFixedSize(button_width, button_height) self.button_3.clicked.connect(self.submit_solution) self.button_3.setObjectName('sidebar_button') self.button_4 = QPushButton('Query', self) self.button_4.setFixedSize(button_width, button_height) self.button_4.clicked.connect(self.send_query) self.button_4.setObjectName('sidebar_button') self.button_5 = QPushButton('Leaderboard', self) self.button_5.setFixedSize(button_width, button_height) self.button_5.clicked.connect(self.ranklist) self.button_5.setObjectName('sidebar_button') self.button_6 = QPushButton('About', self) self.button_6.setFixedSize(button_width, button_height) self.button_6.clicked.connect(self.show_about) self.button_6.setObjectName('sidebar_button') ##################################################################### # Manage tabs o the right window # Each tab is an object returned by the respective function associated with its UI # Tab UI are managed by interface_package/ui_classes.py file self.tab1 = ui_widgets.problems_ui(self) self.tab2, self.sub_model = ui_widgets.submissions_ui(self) self.tab3 = ui_widgets.submit_ui(self) self.tab4, self.query_model = ui_widgets.query_ui(self) self.tab5, self.score_model = ui_widgets.leaderboard_ui(self) self.tab6 = ui_widgets.about_ui(self) ##################################################################### # Add widgets to our main window client_window.init_UI(self, config) return
def login(username, password,queue): authenticate_login.channel = manage_connection.channel authenticate_login.host = manage_connection.host authenticate_login.username = username password = password authenticate_login.queue = queue print("[ Validating ] : " + authenticate_login.username + "@" + password) config = handle_config.read_config_json() if config["client_id"] != 'Null': authenticate_login.client_id = config["client_id"] final_data = { 'Code' : 'LOGIN', 'Client Key' : config["client_key"], 'IP' : config["IP"], 'Username' : username, 'Password' : password, 'ID' : authenticate_login.client_id, 'Type' : 'CLIENT' } final_data = json.dumps(final_data) try: authenticate_login.channel.queue_delete( queue = authenticate_login.username ) except: channel = connection.channel() authenticate_login.channel = channel # authenticate_login.channel.basic_qos(prefetch_count = 1) # Declaring queue for the new client authenticate_login.channel.queue_declare( queue = authenticate_login.username, # virtual_host = "Client", durable = True, ) # Binding the queue for listening from the server authenticate_login.channel.queue_bind( exchange = 'connection_manager', # virtual_host = "Client", queue = authenticate_login.username ) # Publishing the message ( Username and Password ) authenticate_login.channel.basic_publish( exchange = 'connection_manager', routing_key = 'client_requests', body = final_data ) # Listening from the server whether the credentials are valid or not authenticate_login.channel.basic_consume( queue = username, on_message_callback = authenticate_login.server_response_handler, # auto_ack = True ) print("[ Listening ] @ " + authenticate_login.host) # authenticate_login.channel.start_consuming() try: authenticate_login.channel.start_consuming() except(KeyboardInterrupt, SystemExit): authenticate_login.channel.stop_consuming()