Coverage for sfkit/auth/setup_networking.py: 100%

37 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-10-19 13:42 -0400

1import socket 

2 

3from requests import get 

4 

5from sfkit.api import get_doc_ref_dict, get_username, update_firestore 

6from sfkit.utils.helper_functions import authenticate_user 

7 

8 

9def setup_networking(ports_str: str, ip_address: str = "") -> None: 

10 print("Setting up networking...") 

11 print( 

12 "NOTE: this step should be run after all participants have joined the study. If you run this step before all participants have joined, you will need to re-run this step after all participants have joined." 

13 ) 

14 

15 authenticate_user() 

16 doc_ref_dict: dict = get_doc_ref_dict() 

17 

18 if not ip_address: 

19 if doc_ref_dict["setup_configuration"] == "website": 

20 ip_address = socket.gethostbyname(socket.gethostname()) # internal ip address 

21 print("Using internal ip address:", ip_address) 

22 else: 

23 ip_address = get("https://api.ipify.org").content.decode("utf-8") # external ip address 

24 print("Using external ip address:", ip_address) 

25 

26 print("Processing...") 

27 update_firestore(f"update_firestore::IP_ADDRESS={ip_address}") 

28 

29 username: str = get_username() 

30 role: str = str(doc_ref_dict["participants"].index(username)) 

31 

32 if ports_str: 

33 [validate_port(port) for port in ports_str.split(",")] 

34 # pad ports_str with nulls if necessary 

35 pad_length = len(doc_ref_dict["participants"]) - len(ports_str.split(",")) 

36 if pad_length < 0: 

37 print( 

38 "WARNING: You have provided more ports than there are participants. The extra ports will be ignored." 

39 ) 

40 ports_str = ",".join(ports_str.split(",")[: len(doc_ref_dict["participants"])]) 

41 ports_str = "null," * pad_length + ports_str 

42 else: 

43 ports = ["null" for _ in range(len(doc_ref_dict["participants"]))] 

44 for r in range(int(role) + 1, len(doc_ref_dict["participants"])): # for each other participant 

45 ports[r] = validate_port(input(f"Enter port you would like to use to conenct with participant #{r}: ")) 

46 ports_str = ",".join(ports) 

47 

48 update_firestore(f"update_firestore::PORTS={ports_str}") 

49 print("Successfully communicated networking information!") 

50 

51 

52def validate_port(port: str) -> str: 

53 if port.isdigit() and 1024 <= int(port) <= 65535: 

54 return port 

55 print(f"{port} is an invalid port number. Please enter a number between 1024 and 65535.") 

56 exit(1)