From 094a8d763fa81e36535fa5abc0136b9a8750660f Mon Sep 17 00:00:00 2001 From: Aman Tahiliani <65684756+AmanTahiliani@users.noreply.github.com> Date: Mon, 22 Apr 2024 00:42:08 -0400 Subject: [PATCH] Peer to Peer code along with test script (#18) * Initial Peer service code * Updated peer service * Updated peer service * Updated file service * Updated User Ip registration * Updated File moving function * test * test1 again * new --------- Co-authored-by: Sahej Panag --- backend/api/user_login.py | 8 ++- backend/api/utils/get_client_ip.py | 8 ++- backend/peer_notes/settings.py | 2 +- file_peer/peer_service.py | 111 +++++++++++++++++++++++++++++ file_peer/uploads/1_abcd.txt | 2 + file_peer/uploads/2_bcdef.txt | 2 + test1.py | 40 +++++++++++ 7 files changed, 170 insertions(+), 3 deletions(-) create mode 100644 file_peer/peer_service.py create mode 100644 file_peer/uploads/1_abcd.txt create mode 100644 file_peer/uploads/2_bcdef.txt create mode 100644 test1.py diff --git a/backend/api/user_login.py b/backend/api/user_login.py index c88a84d..588d159 100644 --- a/backend/api/user_login.py +++ b/backend/api/user_login.py @@ -66,7 +66,13 @@ class PollOnlineView(APIView): def post(self, request): try: user = request.user - ip_address = get_client_ip(request) + try: + data = request.data + ip_address = data['ip'] + print("Local IP found in request") + except Exception as e: + ip_address = get_client_ip(request) + print("Using public IP") user.ip_address = ip_address user.last_poll = timezone.now() user.save() diff --git a/backend/api/utils/get_client_ip.py b/backend/api/utils/get_client_ip.py index 739a1e7..172b5a7 100644 --- a/backend/api/utils/get_client_ip.py +++ b/backend/api/utils/get_client_ip.py @@ -13,7 +13,13 @@ def get_client_ip(request): def update_user_ip(request): user = request.user - ip_address = get_client_ip(request) + try: + data = request.data + ip_address = data['ip'] + print("Local IP found in request") + except Exception as e: + ip_address = get_client_ip(request) + print("Using public IP") user.ip_address = ip_address user.last_poll = timezone.now() user.save() diff --git a/backend/peer_notes/settings.py b/backend/peer_notes/settings.py index cbaefc6..2b2c292 100644 --- a/backend/peer_notes/settings.py +++ b/backend/peer_notes/settings.py @@ -25,7 +25,7 @@ SECRET_KEY = "django-insecure-rh0s*u8$uugtt10cxbifjriaz%@&p1w!)c2=y^undd2*nx5 # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True -ALLOWED_HOSTS = ["10.20.4.109", "73.7.29.136", "localhost", "127.0.0.1", "http://localhost:5173"] +ALLOWED_HOSTS = ["*"] # ALLOWED_HOSTS = [] diff --git a/file_peer/peer_service.py b/file_peer/peer_service.py new file mode 100644 index 0000000..20d75b6 --- /dev/null +++ b/file_peer/peer_service.py @@ -0,0 +1,111 @@ +from flask import Flask, send_file, request +import requests +import socket +import shutil +import os + +app = Flask(__name__) + + +@app.route('/copy-file', methods = ['POST']) +def copy_file(): + try: + data = request.json + source_file = data['file_path'] + id = data['file_id'] + if not os.path.exists(source_file): + return f"Source file does not exist at {source_file}", 400 + filename = os.path.basename(source_file) + destination_path = os.path.join('./uploads/', str(id) +'_' + filename) + shutil.copyfile(source_file, destination_path) + return "File Moved successfully", 200 + except Exception as e: + print(f'An error occured: {e}') + return "An error occured", 400 + + +@app.route('/ip', methods=["GET"]) +def get_internal_ip(): + internal_ip = None + try: + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + s.connect(("8.8.8.8", 80)) + internal_ip = s.getsockname()[0] + s.close() + except Exception as e: + print("Error:", e) + return internal_ip, 200 + +@app.route('/send', methods=['GET']) +def send(): + file_id = request.args.get('id') + filename = request.args.get('filename') + + file_path = './uploads/' + file_id + '_' + filename + + return send_file(file_path, as_attachment=True, download_name = str(file_id)+'_'+filename) + +@app.route('/request', methods=['GET']) +def request_file(): + data = request.json + file_id = data['id'] + filename = data['filename'] + ip = data['ip'] + + + url = f"http://{ip}:8080/send" + params = { + 'id': file_id, + 'filename': filename, + } + + response = requests.get(url, params=params) + file_path = './uploads/' + str(file_id) + '_' + filename + + if response.status_code == 200: + if os.path.exists(file_path): + return "File with name already exists", 200 + + with open(file_path, 'wb') as f: + f.write(response.content) + print("File downloaded successfully") + return f'File Downloaded to location to location {file_path}', 200 + else: + error = response.text + print("Error:", error) + return error, response.status_code + +@app.route('/request-tests', methods=['GET']) +def request_test_(): + data = request.json + file_id = data['id'] + filename = data['filename'] + ip = data['ip'] + new_filename = data['new_filename'] + + + url = f"http://{ip}:8080/send" + params = { + 'id': file_id, + 'filename': filename, + } + + response = requests.get(url, params=params) + file_path = './uploads/' + str(file_id) + '_' + new_filename + + if response.status_code == 200: + if os.path.exists(file_path): + return "File with name already exists", 200 + + with open(file_path, 'wb') as f: + f.write(response.content) + print("File downloaded successfully") + return f'File Downloaded to location to location {file_path}', 200 + else: + error = response.text + print("Error:", error) + return error, response.status_code + + +if __name__ == '__main__': + app.run(debug=True, host= '0.0.0.0', port=8080) diff --git a/file_peer/uploads/1_abcd.txt b/file_peer/uploads/1_abcd.txt new file mode 100644 index 0000000..7b37538 --- /dev/null +++ b/file_peer/uploads/1_abcd.txt @@ -0,0 +1,2 @@ +Hello World! +Flask Notes Transfer Test \ No newline at end of file diff --git a/file_peer/uploads/2_bcdef.txt b/file_peer/uploads/2_bcdef.txt new file mode 100644 index 0000000..447472f --- /dev/null +++ b/file_peer/uploads/2_bcdef.txt @@ -0,0 +1,2 @@ +Hello World! +Flask Notes Transfer Test 2 \ No newline at end of file diff --git a/test1.py b/test1.py new file mode 100644 index 0000000..a27e756 --- /dev/null +++ b/test1.py @@ -0,0 +1,40 @@ +import requests +import json +import os + +def request_tests(): + url = "http://localhost:8080/request-tests" + downloaded_files = [] + print("past url") + for i in range(100): + filename = f"TestFileTransfer.pdf" + + payload = json.dumps({ + "id": 5, + "filename": filename, + "ip": "143.215.87.54", + "new_filename":f"TestFileTransfer_{i}.pdf" + }) + + headers = { + 'Content-Type': 'application/json', + } + + response = requests.get(url, headers=headers, data=payload) + print("response received") + print(payload) + print(response) + + if response.status_code == 200: + print(f"Request {i+1} successful") + downloaded_files.append(f"bcdef_{i}.txt") + else: + print(f"Request {i+1} failed with status code {response.status_code}") + + if downloaded_files: + file_paths = ', '.join(['./uploads/' + file for file in downloaded_files]) + return f"1000 files have been downloaded to {file_paths}", 200 + else: + return "No files downloaded", 200 + +request_tests() \ No newline at end of file