Merge pull request #1063 from micahflee/f-strings

Use python 3.6 f-strings
This commit is contained in:
Micah Lee 2019-10-22 09:58:20 -07:00 committed by GitHub
commit b3d33c0dff
29 changed files with 147 additions and 263 deletions

View file

@ -7,14 +7,13 @@ workflows:
version: 2 version: 2
test: test:
jobs: jobs:
- test-3.5
- test-3.6 - test-3.6
- test-3.7 - test-3.7
jobs: jobs:
test-3.5: &test-template test-3.6: &test-template
docker: docker:
- image: circleci/python:3.5.6 - image: circleci/python:3.6.6
working_directory: ~/repo working_directory: ~/repo
@ -44,11 +43,6 @@ jobs:
command: | command: |
xvfb-run -s "-screen 0 1280x1024x24" pytest --rungui --cov=onionshare --cov=onionshare_gui --cov-report=term-missing -vvv --no-qt-log tests/ xvfb-run -s "-screen 0 1280x1024x24" pytest --rungui --cov=onionshare --cov=onionshare_gui --cov-report=term-missing -vvv --no-qt-log tests/
test-3.6:
<<: *test-template
docker:
- image: circleci/python:3.6.6
test-3.7: test-3.7:
<<: *test-template <<: *test-template
docker: docker:

View file

@ -31,9 +31,9 @@ from .onionshare import OnionShare
def build_url(common, app, web): def build_url(common, app, web):
# Build the URL # Build the URL
if common.settings.get("public_mode"): if common.settings.get("public_mode"):
return "http://{0:s}".format(app.onion_host) return f"http://{app.onion_host}"
else: else:
return "http://onionshare:{0:s}@{1:s}".format(web.password, app.onion_host) return f"http://onionshare:{web.password}@{app.onion_host}"
def main(cwd=None): def main(cwd=None):
@ -44,7 +44,7 @@ def main(cwd=None):
common = Common() common = Common()
# Display OnionShare banner # Display OnionShare banner
print("OnionShare {0:s} | https://onionshare.org/".format(common.version)) print(f"OnionShare {common.version} | https://onionshare.org/")
# OnionShare CLI in OSX needs to change current working directory (#132) # OnionShare CLI in OSX needs to change current working directory (#132)
if common.platform == "Darwin": if common.platform == "Darwin":
@ -160,10 +160,10 @@ def main(cwd=None):
valid = True valid = True
for filename in filenames: for filename in filenames:
if not os.path.isfile(filename) and not os.path.isdir(filename): if not os.path.isfile(filename) and not os.path.isdir(filename):
print("{0:s} is not a valid file.".format(filename)) print(f"{filename} is not a valid file.")
valid = False valid = False
if not os.access(filename, os.R_OK): if not os.access(filename, os.R_OK):
print("{0:s} is not a readable file.".format(filename)) print(f"{filename} is not a readable file.")
valid = False valid = False
if not valid: if not valid:
sys.exit() sys.exit()
@ -217,9 +217,7 @@ def main(cwd=None):
schedule = datetime.now() + timedelta(seconds=autostart_timer) schedule = datetime.now() + timedelta(seconds=autostart_timer)
if mode == "receive": if mode == "receive":
print( print(
"Files sent to you appear in this folder: {}".format( f"Files sent to you appear in this folder: {common.settings.get('data_dir')}"
common.settings.get("data_dir")
)
) )
print("") print("")
print( print(
@ -228,30 +226,22 @@ def main(cwd=None):
print("") print("")
if stealth: if stealth:
print( print(
"Give this address and HidServAuth lineto your sender, and tell them it won't be accessible until: {}".format( f"Give this address and HidServAuth lineto your sender, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}"
schedule.strftime("%I:%M:%S%p, %b %d, %y")
)
) )
print(app.auth_string) print(app.auth_string)
else: else:
print( print(
"Give this address to your sender, and tell them it won't be accessible until: {}".format( f"Give this address to your sender, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}"
schedule.strftime("%I:%M:%S%p, %b %d, %y")
)
) )
else: else:
if stealth: if stealth:
print( print(
"Give this address and HidServAuth line to your recipient, and tell them it won't be accessible until: {}".format( f"Give this address and HidServAuth line to your recipient, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}"
schedule.strftime("%I:%M:%S%p, %b %d, %y")
)
) )
print(app.auth_string) print(app.auth_string)
else: else:
print( print(
"Give this address to your recipient, and tell them it won't be accessible until: {}".format( f"Give this address to your recipient, and tell them it won't be accessible until: {schedule.strftime('%I:%M:%S%p, %b %d, %y')}"
schedule.strftime("%I:%M:%S%p, %b %d, %y")
)
) )
print(url) print(url)
print("") print("")
@ -324,9 +314,7 @@ def main(cwd=None):
else: else:
if mode == "receive": if mode == "receive":
print( print(
"Files sent to you appear in this folder: {}".format( f"Files sent to you appear in this folder: {common.settings.get('data_dir')}"
common.settings.get("data_dir")
)
) )
print("") print("")
print( print(

View file

@ -63,9 +63,9 @@ class Common(object):
if self.verbose: if self.verbose:
timestamp = time.strftime("%b %d %Y %X") timestamp = time.strftime("%b %d %Y %X")
final_msg = "[{}] {}.{}".format(timestamp, module, func) final_msg = f"[{timestamp}] {module}.{func}"
if msg: if msg:
final_msg = "{}: {}".format(final_msg, msg) final_msg = f"{final_msg}: {msg}"
print(final_msg) print(final_msg)
def get_resource_path(self, filename): def get_resource_path(self, filename):
@ -162,7 +162,7 @@ class Common(object):
if self.platform == "Windows": if self.platform == "Windows":
try: try:
appdata = os.environ["APPDATA"] appdata = os.environ["APPDATA"]
onionshare_data_dir = "{}\\OnionShare".format(appdata) onionshare_data_dir = f"{appdata}\\OnionShare"
except: except:
# If for some reason we don't have the 'APPDATA' environment variable # If for some reason we don't have the 'APPDATA' environment variable
# (like running tests in Linux while pretending to be in Windows) # (like running tests in Linux while pretending to be in Windows)
@ -517,7 +517,7 @@ class AutoStopTimer(threading.Thread):
def run(self): def run(self):
self.common.log( self.common.log(
"AutoStopTimer", "Server will shut down after {} seconds".format(self.time) "AutoStopTimer", f"Server will shut down after {self.time} seconds"
) )
time.sleep(self.time) time.sleep(self.time)
return 1 return 1

View file

@ -219,9 +219,7 @@ class Onion(object):
dir=self.common.build_data_dir() dir=self.common.build_data_dir()
) )
self.common.log( self.common.log(
"Onion", "Onion", "connect", f"tor_data_directory={self.tor_data_directory.name}"
"connect",
"tor_data_directory={}".format(self.tor_data_directory.name),
) )
# Create the torrc # Create the torrc
@ -283,9 +281,7 @@ class Onion(object):
# Bridge support # Bridge support
if self.settings.get("tor_bridges_use_obfs4"): if self.settings.get("tor_bridges_use_obfs4"):
f.write( f.write(
"ClientTransportPlugin obfs4 exec {}\n".format( f"ClientTransportPlugin obfs4 exec {self.obfs4proxy_file_path}\n"
self.obfs4proxy_file_path
)
) )
with open( with open(
self.common.get_resource_path("torrc_template-obfs4") self.common.get_resource_path("torrc_template-obfs4")
@ -294,9 +290,7 @@ class Onion(object):
f.write(line) f.write(line)
elif self.settings.get("tor_bridges_use_meek_lite_azure"): elif self.settings.get("tor_bridges_use_meek_lite_azure"):
f.write( f.write(
"ClientTransportPlugin meek_lite exec {}\n".format( f"ClientTransportPlugin meek_lite exec {self.obfs4proxy_file_path}\n"
self.obfs4proxy_file_path
)
) )
with open( with open(
self.common.get_resource_path("torrc_template-meek_lite_azure") self.common.get_resource_path("torrc_template-meek_lite_azure")
@ -307,17 +301,13 @@ class Onion(object):
if self.settings.get("tor_bridges_use_custom_bridges"): if self.settings.get("tor_bridges_use_custom_bridges"):
if "obfs4" in self.settings.get("tor_bridges_use_custom_bridges"): if "obfs4" in self.settings.get("tor_bridges_use_custom_bridges"):
f.write( f.write(
"ClientTransportPlugin obfs4 exec {}\n".format( f"ClientTransportPlugin obfs4 exec {self.obfs4proxy_file_path}\n"
self.obfs4proxy_file_path
)
) )
elif "meek_lite" in self.settings.get( elif "meek_lite" in self.settings.get(
"tor_bridges_use_custom_bridges" "tor_bridges_use_custom_bridges"
): ):
f.write( f.write(
"ClientTransportPlugin meek_lite exec {}\n".format( f"ClientTransportPlugin meek_lite exec {self.obfs4proxy_file_path}\n"
self.obfs4proxy_file_path
)
) )
f.write(self.settings.get("tor_bridges_use_custom_bridges")) f.write(self.settings.get("tor_bridges_use_custom_bridges"))
f.write("\nUseBridges 1") f.write("\nUseBridges 1")
@ -371,12 +361,7 @@ class Onion(object):
summary = res_parts[4].split("=")[1] summary = res_parts[4].split("=")[1]
# "\033[K" clears the rest of the line # "\033[K" clears the rest of the line
print( print(f"Connecting to the Tor network: {progress}% - {summary}\033[K")
"Connecting to the Tor network: {}% - {}{}".format(
progress, summary, "\033[K"
),
end="\r",
)
if callable(tor_status_update_func): if callable(tor_status_update_func):
if not tor_status_update_func(progress, summary): if not tor_status_update_func(progress, summary):
@ -457,12 +442,12 @@ class Onion(object):
if not found_tor: if not found_tor:
try: try:
if self.common.platform == "Linux" or self.common.platform == "BSD": if self.common.platform == "Linux" or self.common.platform == "BSD":
socket_file_path = "/run/user/{}/Tor/control.socket".format( socket_file_path = (
os.geteuid() f"/run/user/{os.geteuid()}/Tor/control.socket"
) )
elif self.common.platform == "Darwin": elif self.common.platform == "Darwin":
socket_file_path = "/run/user/{}/Tor/control.socket".format( socket_file_path = (
os.geteuid() f"/run/user/{os.geteuid()}/Tor/control.socket"
) )
elif self.common.platform == "Windows": elif self.common.platform == "Windows":
# Windows doesn't support unix sockets # Windows doesn't support unix sockets
@ -541,9 +526,7 @@ class Onion(object):
# Get the tor version # Get the tor version
self.tor_version = self.c.get_version().version_str self.tor_version = self.c.get_version().version_str
self.common.log( self.common.log("Onion", "connect", f"Connected to tor {self.tor_version}")
"Onion", "connect", "Connected to tor {}".format(self.tor_version)
)
# Do the versions of stem and tor that I'm using support ephemeral onion services? # Do the versions of stem and tor that I'm using support ephemeral onion services?
list_ephemeral_hidden_services = getattr( list_ephemeral_hidden_services = getattr(
@ -597,7 +580,7 @@ class Onion(object):
raise TorTooOld(strings._("error_stealth_not_supported")) raise TorTooOld(strings._("error_stealth_not_supported"))
if not save_scheduled_key: if not save_scheduled_key:
print("Setting up onion service on port {0:d}.".format(int(port))) print(f"Setting up onion service on port {port}.")
if self.stealth: if self.stealth:
if self.settings.get("hidservauth_string"): if self.settings.get("hidservauth_string"):
@ -648,10 +631,10 @@ class Onion(object):
basic_auth = None basic_auth = None
self.stealth = False self.stealth = False
debug_message = "key_type={}".format(key_type) debug_message = f"key_type={key_type}"
if key_type == "NEW": if key_type == "NEW":
debug_message += ", key_content={}".format(key_content) debug_message += f", key_content={key_content}"
self.common.log("Onion", "start_onion_service", "{}".format(debug_message)) self.common.log("Onion", "start_onion_service", debug_message)
try: try:
if basic_auth != None: if basic_auth != None:
res = self.c.create_ephemeral_hidden_service( res = self.c.create_ephemeral_hidden_service(
@ -700,24 +683,20 @@ class Onion(object):
self.auth_string = self.settings.get("hidservauth_string") self.auth_string = self.settings.get("hidservauth_string")
else: else:
auth_cookie = list(res.client_auth.values())[0] auth_cookie = list(res.client_auth.values())[0]
self.auth_string = "HidServAuth {} {}".format( self.auth_string = f"HidServAuth {onion_host} {auth_cookie}"
onion_host, auth_cookie
)
self.settings.set("hidservauth_string", self.auth_string) self.settings.set("hidservauth_string", self.auth_string)
else: else:
if not self.scheduled_auth_cookie: if not self.scheduled_auth_cookie:
auth_cookie = list(res.client_auth.values())[0] auth_cookie = list(res.client_auth.values())[0]
self.auth_string = "HidServAuth {} {}".format( self.auth_string = f"HidServAuth {onion_host} {auth_cookie}"
onion_host, auth_cookie
)
if save_scheduled_key: if save_scheduled_key:
# Register the HidServAuth for the scheduled share # Register the HidServAuth for the scheduled share
self.scheduled_auth_cookie = auth_cookie self.scheduled_auth_cookie = auth_cookie
else: else:
self.scheduled_auth_cookie = None self.scheduled_auth_cookie = None
else: else:
self.auth_string = "HidServAuth {} {}".format( self.auth_string = (
onion_host, self.scheduled_auth_cookie f"HidServAuth {onion_host} {self.scheduled_auth_cookie}"
) )
if not save_scheduled_key: if not save_scheduled_key:
# We've used the scheduled share's HidServAuth. Reset it to None for future shares # We've used the scheduled share's HidServAuth. Reset it to None for future shares
@ -741,14 +720,14 @@ class Onion(object):
for onion in onions: for onion in onions:
try: try:
self.common.log( self.common.log(
"Onion", "cleanup", "trying to remove onion {}".format(onion) "Onion", "cleanup", f"trying to remove onion {onion}"
) )
self.c.remove_ephemeral_hidden_service(onion) self.c.remove_ephemeral_hidden_service(onion)
except: except:
self.common.log( self.common.log(
"Onion", "Onion",
"cleanup", "cleanup",
"could not remove onion {}.. moving on anyway".format(onion), f"could not remove onion {onion}.. moving on anyway",
) )
pass pass
except: except:

View file

@ -56,7 +56,7 @@ class OnionShare(object):
self.autostop_timer_thread = None self.autostop_timer_thread = None
def set_stealth(self, stealth): def set_stealth(self, stealth):
self.common.log("OnionShare", "set_stealth", "stealth={}".format(stealth)) self.common.log("OnionShare", f"set_stealth", "stealth={stealth}")
self.stealth = stealth self.stealth = stealth
self.onion.stealth = stealth self.onion.stealth = stealth
@ -83,7 +83,7 @@ class OnionShare(object):
self.autostop_timer_thread = AutoStopTimer(self.common, self.autostop_timer) self.autostop_timer_thread = AutoStopTimer(self.common, self.autostop_timer)
if self.local_only: if self.local_only:
self.onion_host = "127.0.0.1:{0:d}".format(self.port) self.onion_host = f"127.0.0.1:{self.port}"
return return
self.onion_host = self.onion.start_onion_service( self.onion_host = self.onion.start_onion_service(

View file

@ -190,9 +190,7 @@ class Settings(object):
# If the settings file exists, load it # If the settings file exists, load it
if os.path.exists(self.filename): if os.path.exists(self.filename):
try: try:
self.common.log( self.common.log("Settings", "load", f"Trying to load {self.filename}")
"Settings", "load", "Trying to load {}".format(self.filename)
)
with open(self.filename, "r") as f: with open(self.filename, "r") as f:
self._settings = json.load(f) self._settings = json.load(f)
self.fill_in_defaults() self.fill_in_defaults()
@ -211,9 +209,7 @@ class Settings(object):
""" """
self.common.log("Settings", "save") self.common.log("Settings", "save")
open(self.filename, "w").write(json.dumps(self._settings, indent=2)) open(self.filename, "w").write(json.dumps(self._settings, indent=2))
self.common.log( self.common.log("Settings", "save", f"Settings saved in {self.filename}")
"Settings", "save", "Settings saved in {}".format(self.filename)
)
def get(self, key): def get(self, key):
return self._settings[key] return self._settings[key]

View file

@ -36,7 +36,7 @@ def load_strings(common):
translations = {} translations = {}
for locale in common.settings.available_locales: for locale in common.settings.available_locales:
locale_dir = common.get_resource_path("locale") locale_dir = common.get_resource_path("locale")
filename = os.path.join(locale_dir, "{}.json".format(locale)) filename = os.path.join(locale_dir, f"{locale}.json")
with open(filename, encoding="utf-8") as f: with open(filename, encoding="utf-8") as f:
translations[locale] = json.load(f) translations[locale] = json.load(f)

View file

@ -38,7 +38,7 @@ class ReceiveModeWeb:
self.cur_history_id += 1 self.cur_history_id += 1
self.web.add_request( self.web.add_request(
self.web.REQUEST_INDIVIDUAL_FILE_STARTED, self.web.REQUEST_INDIVIDUAL_FILE_STARTED,
"{}".format(request.path), request.path,
{"id": history_id, "status_code": 200}, {"id": history_id, "status_code": 200},
) )
@ -79,11 +79,9 @@ class ReceiveModeWeb:
self.common.log( self.common.log(
"ReceiveModeWeb", "ReceiveModeWeb",
"define_routes", "define_routes",
"/upload, uploaded {}, saving to {}".format( f"/upload, uploaded {f.filename}, saving to {local_path}",
f.filename, local_path
),
) )
print("\n" + "Received: {}".format(local_path)) print(f"\nReceived: {local_path}")
if request.upload_error: if request.upload_error:
self.common.log( self.common.log(
@ -98,9 +96,7 @@ class ReceiveModeWeb:
{"receive_mode_dir": request.receive_mode_dir}, {"receive_mode_dir": request.receive_mode_dir},
) )
print( print(
"Could not create OnionShare data folder: {}".format( f"Could not create OnionShare data folder: {request.receive_mode_dir}"
request.receive_mode_dir
)
) )
msg = "Error uploading, please inform the OnionShare user" msg = "Error uploading, please inform the OnionShare user"
@ -124,7 +120,7 @@ class ReceiveModeWeb:
else: else:
msg = "Sent " msg = "Sent "
for filename in filenames: for filename in filenames:
msg += "{}, ".format(filename) msg += f"{filename}, "
msg = msg.rstrip(", ") msg = msg.rstrip(", ")
if ajax: if ajax:
info_flashes.append(msg) info_flashes.append(msg)
@ -191,7 +187,7 @@ class ReceiveModeFile(object):
self.onionshare_close_func = close_func self.onionshare_close_func = close_func
self.filename = os.path.join(self.onionshare_request.receive_mode_dir, filename) self.filename = os.path.join(self.onionshare_request.receive_mode_dir, filename)
self.filename_in_progress = "{}.part".format(self.filename) self.filename_in_progress = f"{self.filename}.part"
# Open the file # Open the file
self.upload_error = False self.upload_error = False
@ -309,7 +305,7 @@ class ReceiveModeRequest(Request):
# Keep going until we find a directory name that's available # Keep going until we find a directory name that's available
i = 1 i = 1
while True: while True:
new_receive_mode_dir = "{}-{}".format(self.receive_mode_dir, i) new_receive_mode_dir = f"{self.receive_mode_dir}-{i}"
try: try:
os.makedirs(new_receive_mode_dir, 0o700, exist_ok=False) os.makedirs(new_receive_mode_dir, 0o700, exist_ok=False)
self.receive_mode_dir = new_receive_mode_dir self.receive_mode_dir = new_receive_mode_dir
@ -333,9 +329,7 @@ class ReceiveModeRequest(Request):
{"receive_mode_dir": self.receive_mode_dir}, {"receive_mode_dir": self.receive_mode_dir},
) )
print( print(
"Could not create OnionShare data folder: {}".format( f"Could not create OnionShare data folder: {self.receive_mode_dir}"
self.receive_mode_dir
)
) )
self.web.common.log( self.web.common.log(
"ReceiveModeRequest", "ReceiveModeRequest",
@ -460,12 +454,7 @@ class ReceiveModeRequest(Request):
self.previous_file = filename self.previous_file = filename
print( print(
"\r=> {:15s} {}".format( f"\r=> {self.web.common.human_readable_filesize(self.progress[filename]['uploaded_bytes'])} {filename}",
self.web.common.human_readable_filesize(
self.progress[filename]["uploaded_bytes"]
),
filename,
),
end="", end="",
) )

View file

@ -95,16 +95,14 @@ class SendBaseModeWeb:
self.cur_history_id += 1 self.cur_history_id += 1
self.web.add_request( self.web.add_request(
self.web.REQUEST_INDIVIDUAL_FILE_STARTED, self.web.REQUEST_INDIVIDUAL_FILE_STARTED,
"/{}".format(path), f"/{path}",
{"id": history_id, "method": request.method, "status_code": 200}, {"id": history_id, "method": request.method, "status_code": 200},
) )
breadcrumbs = [("", "/")] breadcrumbs = [("", "/")]
parts = path.split("/")[:-1] parts = path.split("/")[:-1]
for i in range(len(parts)): for i in range(len(parts)):
breadcrumbs.append( breadcrumbs.append((parts[i], f"/{'/'.join(parts[0 : i + 1])}/"))
("{}".format(parts[i]), "/{}/".format("/".join(parts[0 : i + 1])))
)
breadcrumbs_leaf = breadcrumbs.pop()[0] breadcrumbs_leaf = breadcrumbs.pop()[0]
# If filesystem_path is None, this is the root directory listing # If filesystem_path is None, this is the root directory listing
@ -173,7 +171,6 @@ class SendBaseModeWeb:
{"id": history_id, "filesize": filesize}, {"id": history_id, "filesize": filesize},
) )
def generate(): def generate():
chunk_size = 102400 # 100kb chunk_size = 102400 # 100kb

View file

@ -340,8 +340,8 @@ class ZipWriter(object):
if zip_filename: if zip_filename:
self.zip_filename = zip_filename self.zip_filename = zip_filename
else: else:
self.zip_filename = "{0:s}/onionshare_{1:s}.zip".format( self.zip_filename = (
tempfile.mkdtemp(), self.common.random_string(4, 6) f"{tempfile.mkdtemp()}/onionshare_{self.common.random_string(4, 6)}.zip"
) )
self.z = zipfile.ZipFile(self.zip_filename, "w", allowZip64=True) self.z = zipfile.ZipFile(self.zip_filename, "w", allowZip64=True)

View file

@ -62,15 +62,13 @@ class Web:
def __init__(self, common, is_gui, mode="share"): def __init__(self, common, is_gui, mode="share"):
self.common = common self.common = common
self.common.log("Web", "__init__", "is_gui={}, mode={}".format(is_gui, mode)) self.common.log("Web", "__init__", f"is_gui={is_gui}, mode={mode}")
# The flask app # The flask app
self.app = Flask( self.app = Flask(
__name__, __name__,
static_folder=self.common.get_resource_path("static"), static_folder=self.common.get_resource_path("static"),
static_url_path="/static_".format( static_url_path=f"/static_{self.common.random_string(16)}", # randomize static_url_path to avoid making /static unusable
self.common.random_string(16)
), # randomize static_url_path to avoid making /static unusable
template_folder=self.common.get_resource_path("templates"), template_folder=self.common.get_resource_path("templates"),
) )
self.app.secret_key = self.common.random_string(8) self.app.secret_key = self.common.random_string(8)
@ -154,11 +152,11 @@ class Web:
def generate_static_url_path(self): def generate_static_url_path(self):
# The static URL path has a 128-bit random number in it to avoid having name # The static URL path has a 128-bit random number in it to avoid having name
# collisions with files that might be getting shared # collisions with files that might be getting shared
self.static_url_path = "/static_{}".format(self.common.random_string(16)) self.static_url_path = f"/static_{self.common.random_string(16)}"
self.common.log( self.common.log(
"Web", "Web",
"generate_static_url_path", "generate_static_url_path",
"new static_url_path is {}".format(self.static_url_path), f"new static_url_path is {self.static_url_path}",
) )
# Update the flask route to handle the new static URL path # Update the flask route to handle the new static URL path
@ -218,7 +216,7 @@ class Web:
@self.app.route("/favicon.ico") @self.app.route("/favicon.ico")
def favicon(): def favicon():
return send_file( return send_file(
"{}/img/favicon.ico".format(self.common.get_resource_path("static")) f"{self.common.get_resource_path('static')}/img/favicon.ico"
) )
def error401(self): def error401(self):
@ -228,7 +226,7 @@ class Web:
auth["username"] == "onionshare" auth["username"] == "onionshare"
and auth["password"] not in self.invalid_passwords and auth["password"] not in self.invalid_passwords
): ):
print("Invalid password guess: {}".format(auth["password"])) print(f"Invalid password guess: {auth['password']}")
self.add_request(Web.REQUEST_INVALID_PASSWORD, data=auth["password"]) self.add_request(Web.REQUEST_INVALID_PASSWORD, data=auth["password"])
self.invalid_passwords.append(auth["password"]) self.invalid_passwords.append(auth["password"])
@ -256,7 +254,7 @@ class Web:
def error404(self, history_id): def error404(self, history_id):
self.add_request( self.add_request(
self.REQUEST_INDIVIDUAL_FILE_STARTED, self.REQUEST_INDIVIDUAL_FILE_STARTED,
"{}".format(request.path), request.path,
{"id": history_id, "status_code": 404}, {"id": history_id, "status_code": 404},
) )
@ -269,7 +267,7 @@ class Web:
def error405(self, history_id): def error405(self, history_id):
self.add_request( self.add_request(
self.REQUEST_INDIVIDUAL_FILE_STARTED, self.REQUEST_INDIVIDUAL_FILE_STARTED,
"{}".format(request.path), request.path,
{"id": history_id, "status_code": 405}, {"id": history_id, "status_code": 405},
) )
@ -309,23 +307,19 @@ class Web:
def generate_password(self, persistent_password=None): def generate_password(self, persistent_password=None):
self.common.log( self.common.log(
"Web", "Web", "generate_password", f"persistent_password={persistent_password}"
"generate_password",
"persistent_password={}".format(persistent_password),
) )
if persistent_password != None and persistent_password != "": if persistent_password != None and persistent_password != "":
self.password = persistent_password self.password = persistent_password
self.common.log( self.common.log(
"Web", "Web",
"generate_password", "generate_password",
'persistent_password sent, so password is: "{}"'.format(self.password), f'persistent_password sent, so password is: "{self.password}"',
) )
else: else:
self.password = self.common.build_password() self.password = self.common.build_password()
self.common.log( self.common.log(
"Web", "Web", "generate_password", f'built random password: "{self.password}"'
"generate_password",
'built random password: "{}"'.format(self.password),
) )
def verbose_mode(self): def verbose_mode(self):
@ -362,9 +356,7 @@ class Web:
self.common.log( self.common.log(
"Web", "Web",
"start", "start",
"port={}, stay_open={}, public_mode={}, password={}".format( f"port={port}, stay_open={stay_open}, public_mode={public_mode}, password={password}",
port, stay_open, public_mode, password
),
) )
self.stay_open = stay_open self.stay_open = stay_open
@ -398,7 +390,7 @@ class Web:
# (We're putting the shutdown_password in the path as well to make routing simpler) # (We're putting the shutdown_password in the path as well to make routing simpler)
if self.running: if self.running:
requests.get( requests.get(
"http://127.0.0.1:{}/{}/shutdown".format(port, self.shutdown_password), f"http://127.0.0.1:{port}/{self.shutdown_password}/shutdown",
auth=requests.auth.HTTPBasicAuth("onionshare", self.password), auth=requests.auth.HTTPBasicAuth("onionshare", self.password),
) )

View file

@ -63,7 +63,7 @@ def main():
common.define_css() common.define_css()
# Display OnionShare banner # Display OnionShare banner
print("OnionShare {0:s} | https://onionshare.org/".format(common.version)) print(f"OnionShare {common.version} | https://onionshare.org/")
# Allow Ctrl-C to smoothly quit the program instead of throwing an exception # Allow Ctrl-C to smoothly quit the program instead of throwing an exception
# https://stackoverflow.com/questions/42814093/how-to-handle-ctrlc-in-python-app-with-pyqt # https://stackoverflow.com/questions/42814093/how-to-handle-ctrlc-in-python-app-with-pyqt
@ -124,10 +124,10 @@ def main():
valid = True valid = True
for filename in filenames: for filename in filenames:
if not os.path.isfile(filename) and not os.path.isdir(filename): if not os.path.isfile(filename) and not os.path.isdir(filename):
Alert(common, "{0:s} is not a valid file.".format(filename)) Alert(common, f"{filename} is not a valid file.")
valid = False valid = False
if not os.access(filename, os.R_OK): if not os.access(filename, os.R_OK):
Alert(common, "{0:s} is not a readable file.".format(filename)) Alert(common, f"{filename} is not a readable file.")
valid = False valid = False
if not valid: if not valid:
sys.exit() sys.exit()

View file

@ -119,18 +119,10 @@ class Mode(QtWidgets.QWidget):
if not seconds: if not seconds:
seconds = "0" seconds = "0"
result = ( result = (
("{0}{1}, ".format(days, strings._("days_first_letter")) if days else "") (f"{days}{strings._('days_first_letter')}, " if days else "")
+ ( + (f"{hours}{strings._('hours_first_letter')}, " if hours else "")
"{0}{1}, ".format(hours, strings._("hours_first_letter")) + (f"{minutes}{strings._('minutes_first_letter')}, " if minutes else "")
if hours + f"{seconds}{strings._('seconds_first_letter')}"
else ""
)
+ (
"{0}{1}, ".format(minutes, strings._("minutes_first_letter"))
if minutes
else ""
)
+ "{0}{1}".format(seconds, strings._("seconds_first_letter"))
) )
return result return result

View file

@ -171,7 +171,7 @@ class FileList(QtWidgets.QListWidget):
if event.mimeData().hasUrls: if event.mimeData().hasUrls:
self.setStyleSheet(self.common.css["share_file_list_drag_enter"]) self.setStyleSheet(self.common.css["share_file_list_drag_enter"])
count = len(event.mimeData().urls()) count = len(event.mimeData().urls())
self.drop_count.setText("+{}".format(count)) self.drop_count.setText(f"+{count}")
size_hint = self.drop_count.sizeHint() size_hint = self.drop_count.sizeHint()
self.drop_count.setGeometry( self.drop_count.setGeometry(

View file

@ -181,9 +181,7 @@ class ReceiveHistoryItemFile(QtWidgets.QWidget):
super(ReceiveHistoryItemFile, self).__init__() super(ReceiveHistoryItemFile, self).__init__()
self.common = common self.common = common
self.common.log( self.common.log("ReceiveHistoryItemFile", "__init__", f"filename: {filename}")
"ReceiveHistoryItemFile", "__init__", "filename: {}".format(filename)
)
self.filename = filename self.filename = filename
self.dir = None self.dir = None
@ -265,7 +263,7 @@ class ReceiveHistoryItemFile(QtWidgets.QWidget):
# Windows # Windows
elif self.common.platform == "Windows": elif self.common.platform == "Windows":
subprocess.Popen(["explorer", "/select,{}".format(abs_filename)]) subprocess.Popen(["explorer", f"/select,{abs_filename}"])
class ReceiveHistoryItem(HistoryItem): class ReceiveHistoryItem(HistoryItem):
@ -409,7 +407,7 @@ class IndividualFileHistoryItem(HistoryItem):
self.timestamp_label.setStyleSheet( self.timestamp_label.setStyleSheet(
self.common.css["history_individual_file_timestamp_label"] self.common.css["history_individual_file_timestamp_label"]
) )
self.path_label = QtWidgets.QLabel("{}".format(self.path)) self.path_label = QtWidgets.QLabel(self.path)
self.status_code_label = QtWidgets.QLabel() self.status_code_label = QtWidgets.QLabel()
# Progress bar # Progress bar
@ -437,7 +435,7 @@ class IndividualFileHistoryItem(HistoryItem):
# Is a status code already sent? # Is a status code already sent?
if "status_code" in data: if "status_code" in data:
self.status_code_label.setText("{}".format(data["status_code"])) self.status_code_label.setText(str(data["status_code"]))
if data["status_code"] >= 200 and data["status_code"] < 300: if data["status_code"] >= 200 and data["status_code"] < 300:
self.status_code_label.setStyleSheet( self.status_code_label.setStyleSheet(
self.common.css["history_individual_file_status_code_label_2xx"] self.common.css["history_individual_file_status_code_label_2xx"]
@ -649,7 +647,7 @@ class History(QtWidgets.QWidget):
""" """
Add a new item. Add a new item.
""" """
self.common.log("History", "add", "id: {}, item: {}".format(id, item)) self.common.log("History", "add", f"id: {id}, item: {item}")
# Hide empty, show not empty # Hide empty, show not empty
self.empty.hide() self.empty.hide()
@ -699,9 +697,7 @@ class History(QtWidgets.QWidget):
image = self.common.get_resource_path("images/history_completed_none.png") image = self.common.get_resource_path("images/history_completed_none.png")
else: else:
image = self.common.get_resource_path("images/history_completed.png") image = self.common.get_resource_path("images/history_completed.png")
self.completed_label.setText( self.completed_label.setText(f'<img src="{image}" /> {self.completed_count}')
'<img src="{0:s}" /> {1:d}'.format(image, self.completed_count)
)
self.completed_label.setToolTip( self.completed_label.setToolTip(
strings._("history_completed_tooltip").format(self.completed_count) strings._("history_completed_tooltip").format(self.completed_count)
) )
@ -716,7 +712,7 @@ class History(QtWidgets.QWidget):
image = self.common.get_resource_path("images/history_in_progress.png") image = self.common.get_resource_path("images/history_in_progress.png")
self.in_progress_label.setText( self.in_progress_label.setText(
'<img src="{0:s}" /> {1:d}'.format(image, self.in_progress_count) f'<img src="{image}" /> {self.in_progress_count}'
) )
self.in_progress_label.setToolTip( self.in_progress_label.setToolTip(
strings._("history_in_progress_tooltip").format(self.in_progress_count) strings._("history_in_progress_tooltip").format(self.in_progress_count)
@ -731,9 +727,7 @@ class History(QtWidgets.QWidget):
else: else:
image = self.common.get_resource_path("images/history_requests.png") image = self.common.get_resource_path("images/history_requests.png")
self.requests_label.setText( self.requests_label.setText(f'<img src="{image}" /> {self.requests_count}')
'<img src="{0:s}" /> {1:d}'.format(image, self.requests_count)
)
self.requests_label.setToolTip( self.requests_label.setToolTip(
strings._("history_requests_tooltip").format(self.requests_count) strings._("history_requests_tooltip").format(self.requests_count)
) )
@ -777,7 +771,7 @@ class ToggleHistory(QtWidgets.QPushButton):
if increment and not self.history_widget.isVisible(): if increment and not self.history_widget.isVisible():
self.indicator_count += 1 self.indicator_count += 1
self.indicator_label.setText("{}".format(self.indicator_count)) self.indicator_label.setText(str(self.indicator_count))
if self.indicator_count == 0: if self.indicator_count == 0:
self.indicator_label.hide() self.indicator_label.hide()

View file

@ -655,22 +655,17 @@ class OnionShareGui(QtWidgets.QMainWindow):
) )
if event["type"] == Web.REQUEST_OTHER: if event["type"] == Web.REQUEST_OTHER:
if event["path"] != "/favicon.ico" and event[ if (
"path" event["path"] != "/favicon.ico"
] != "/{}/shutdown".format(mode.web.shutdown_password): and event["path"] != f"/{mode.web.shutdown_password}/shutdown"
):
self.status_bar.showMessage( self.status_bar.showMessage(
"{0:s}: {1:s}".format( f"{strings._('other_page_loaded')}: {event['path']}"
strings._("other_page_loaded"), event["path"]
)
) )
if event["type"] == Web.REQUEST_INVALID_PASSWORD: if event["type"] == Web.REQUEST_INVALID_PASSWORD:
self.status_bar.showMessage( self.status_bar.showMessage(
"[#{0:d}] {1:s}: {2:s}".format( f"[#{mode.web.invalid_passwords_count}] {strings._('incorrect_password')}: {event['data']}"
mode.web.invalid_passwords_count,
strings._("incorrect_password"),
event["data"],
)
) )
mode.timer_callback() mode.timer_callback()

View file

@ -540,9 +540,7 @@ class ServerStatus(QtWidgets.QWidget):
Returns the OnionShare URL. Returns the OnionShare URL.
""" """
if self.common.settings.get("public_mode"): if self.common.settings.get("public_mode"):
url = "http://{0:s}".format(self.app.onion_host) url = f"http://{self.app.onion_host}"
else: else:
url = "http://onionshare:{0:s}@{1:s}".format( url = f"http://onionshare:{self.web.password}@{self.app.onion_host}"
self.web.password, self.app.onion_host
)
return url return url

View file

@ -672,7 +672,7 @@ class SettingsDialog(QtWidgets.QDialog):
strings._("gui_settings_button_cancel") strings._("gui_settings_button_cancel")
) )
self.cancel_button.clicked.connect(self.cancel_clicked) self.cancel_button.clicked.connect(self.cancel_clicked)
version_label = QtWidgets.QLabel("OnionShare {0:s}".format(self.common.version)) version_label = QtWidgets.QLabel(f"OnionShare {self.common.version}")
version_label.setStyleSheet(self.common.css["settings_version"]) version_label.setStyleSheet(self.common.css["settings_version"])
self.help_button = QtWidgets.QPushButton(strings._("gui_settings_button_help")) self.help_button = QtWidgets.QPushButton(strings._("gui_settings_button_help"))
self.help_button.clicked.connect(self.help_clicked) self.help_button.clicked.connect(self.help_clicked)
@ -1040,7 +1040,7 @@ class SettingsDialog(QtWidgets.QDialog):
self.common.log( self.common.log(
"SettingsDialog", "SettingsDialog",
"data_dir_button_clicked", "data_dir_button_clicked",
"selected dir: {}".format(selected_dir), f"selected dir: {selected_dir}",
) )
self.data_dir_lineedit.setText(selected_dir) self.data_dir_lineedit.setText(selected_dir)
@ -1255,9 +1255,7 @@ class SettingsDialog(QtWidgets.QDialog):
self.common.log( self.common.log(
"SettingsDialog", "SettingsDialog",
"save_clicked", "save_clicked",
"Onion done rebooting, connected to Tor: {}".format( f"Onion done rebooting, connected to Tor: {self.onion.connected_to_tor}",
self.onion.connected_to_tor
),
) )
if self.onion.is_authenticated() and not tor_con.wasCanceled(): if self.onion.is_authenticated() and not tor_con.wasCanceled():
@ -1473,9 +1471,7 @@ class SettingsDialog(QtWidgets.QDialog):
def _tor_status_update(self, progress, summary): def _tor_status_update(self, progress, summary):
self.tor_status.setText( self.tor_status.setText(
"<strong>{}</strong><br>{}% {}".format( f"<strong>{strings._('connecting_to_tor')}</strong><br>{progress}% {summary}"
strings._("connecting_to_tor"), progress, summary
)
) )
self.qtapp.processEvents() self.qtapp.processEvents()
if "Done" in summary: if "Done" in summary:

View file

@ -86,7 +86,7 @@ class TorConnectionDialog(QtWidgets.QProgressDialog):
def _tor_status_update(self, progress, summary): def _tor_status_update(self, progress, summary):
self.setValue(int(progress)) self.setValue(int(progress))
self.setLabelText( self.setLabelText(
"<strong>{}</strong><br>{}".format(strings._("connecting_to_tor"), summary) f"<strong>{strings._('connecting_to_tor')}</strong><br>{summary}"
) )
def _connected_to_tor(self): def _connected_to_tor(self):
@ -112,7 +112,7 @@ class TorConnectionDialog(QtWidgets.QProgressDialog):
# Display the exception in an alert box # Display the exception in an alert box
Alert( Alert(
self.common, self.common,
"{}\n\n{}".format(msg, strings._("gui_tor_connection_error_settings")), f"{msg}\n\n{strings._('gui_tor_connection_error_settings')}",
QtWidgets.QMessageBox.Warning, QtWidgets.QMessageBox.Warning,
) )
@ -162,7 +162,7 @@ class TorConnectionThread(QtCore.QThread):
except Exception as e: except Exception as e:
self.common.log( self.common.log(
"TorConnectionThread", "run", "caught exception: {}".format(e.args[0]) "TorConnectionThread", "run", f"caught exception: {e.args[0]}"
) )
self.error_connecting_to_tor.emit(str(e.args[0])) self.error_connecting_to_tor.emit(str(e.args[0]))

View file

@ -71,7 +71,7 @@ class UpdateChecker(QtCore.QObject):
self.config = config self.config = config
def check(self, force=False, config=False): def check(self, force=False, config=False):
self.common.log("UpdateChecker", "check", "force={}".format(force)) self.common.log("UpdateChecker", "check", f"force={force}")
# Load the settings # Load the settings
settings = Settings(self.common, config) settings = Settings(self.common, config)
settings.load() settings.load()
@ -100,9 +100,7 @@ class UpdateChecker(QtCore.QObject):
# Download the latest-version file over Tor # Download the latest-version file over Tor
try: try:
# User agent string includes OnionShare version and platform # User agent string includes OnionShare version and platform
user_agent = "OnionShare {}, {}".format( user_agent = f"OnionShare {self.common.version}, {self.common.platform}"
self.common.version, self.common.platform
)
# If the update is forced, add '?force=1' to the URL, to more # If the update is forced, add '?force=1' to the URL, to more
# accurately measure daily users # accurately measure daily users
@ -118,9 +116,7 @@ class UpdateChecker(QtCore.QObject):
onion_domain = "elx57ue5uyfplgva.onion" onion_domain = "elx57ue5uyfplgva.onion"
self.common.log( self.common.log(
"UpdateChecker", "UpdateChecker", "check", f"loading http://{onion_domain}{path}"
"check",
"loading http://{}{}".format(onion_domain, path),
) )
(socks_address, socks_port) = self.onion.get_tor_socks_port() (socks_address, socks_port) = self.onion.get_tor_socks_port()
@ -130,9 +126,9 @@ class UpdateChecker(QtCore.QObject):
s.settimeout(15) # 15 second timeout s.settimeout(15) # 15 second timeout
s.connect((onion_domain, 80)) s.connect((onion_domain, 80))
http_request = "GET {} HTTP/1.0\r\n".format(path) http_request = f"GET {path} HTTP/1.0\r\n"
http_request += "Host: {}\r\n".format(onion_domain) http_request += f"Host: {onion_domain}\r\n"
http_request += "User-Agent: {}\r\n".format(user_agent) http_request += f"User-Agent: {user_agent}\r\n"
http_request += "\r\n" http_request += "\r\n"
s.sendall(http_request.encode("utf-8")) s.sendall(http_request.encode("utf-8"))
@ -146,11 +142,11 @@ class UpdateChecker(QtCore.QObject):
self.common.log( self.common.log(
"UpdateChecker", "UpdateChecker",
"check", "check",
"latest OnionShare version: {}".format(latest_version), f"latest OnionShare version: {latest_version}",
) )
except Exception as e: except Exception as e:
self.common.log("UpdateChecker", "check", "{}".format(e)) self.common.log("UpdateChecker", "check", str(e))
self.update_error.emit() self.update_error.emit()
raise UpdateCheckerCheckError raise UpdateCheckerCheckError
@ -174,9 +170,7 @@ class UpdateChecker(QtCore.QObject):
settings.save() settings.save()
# Do we need to update? # Do we need to update?
update_url = "https://github.com/micahflee/onionshare/releases/tag/v{}".format( update_url = f"https://github.com/micahflee/onionshare/releases/tag/v{latest_version}"
latest_version
)
installed_version = self.common.version installed_version = self.common.version
if installed_version < latest_version: if installed_version < latest_version:
self.update_available.emit( self.update_available.emit(
@ -217,7 +211,7 @@ class UpdateThread(QtCore.QThread):
u.check(config=self.config, force=self.force) u.check(config=self.config, force=self.force)
except Exception as e: except Exception as e:
# If update check fails, silently ignore # If update check fails, silently ignore
self.common.log("UpdateThread", "run", "{}".format(e)) self.common.log("UpdateThread", "run", str(e))
pass pass
def _update_available(self, update_url, installed_version, latest_version): def _update_available(self, update_url, installed_version, latest_version):

View file

@ -3,4 +3,4 @@ Package3: onionshare
Depends3: python3, python3-flask, python3-flask-httpauth, python3-stem, python3-pyqt5, python3-crypto, python3-socks, python3-distutils, python-nautilus, tor, obfs4proxy Depends3: python3, python3-flask, python3-flask-httpauth, python3-stem, python3-pyqt5, python3-crypto, python3-socks, python3-distutils, python-nautilus, tor, obfs4proxy
Build-Depends: python3, python3-all, python3-pytest, python3-requests, python3-flask, python3-flask-httpauth, python3-stem, python3-pyqt5, python3-crypto, python3-socks, python3-distutils Build-Depends: python3, python3-all, python3-pytest, python3-requests, python3-flask, python3-flask-httpauth, python3-stem, python3-pyqt5, python3-crypto, python3-socks, python3-distutils
Suite: disco Suite: disco
X-Python3-Version: >= 3.5.3 X-Python3-Version: >= 3.6

View file

@ -129,7 +129,7 @@ class GuiBaseTest(object):
if type(mode) == ReceiveMode: if type(mode) == ReceiveMode:
# Upload a file # Upload a file
files = {"file[]": open("/tmp/test.txt", "rb")} files = {"file[]": open("/tmp/test.txt", "rb")}
url = "http://127.0.0.1:{}/upload".format(self.gui.app.port) url = f"http://127.0.0.1:{self.gui.app.port}/upload"
if public_mode: if public_mode:
r = requests.post(url, files=files) r = requests.post(url, files=files)
else: else:
@ -142,7 +142,7 @@ class GuiBaseTest(object):
if type(mode) == ShareMode: if type(mode) == ShareMode:
# Download files # Download files
url = "http://127.0.0.1:{}/download".format(self.gui.app.port) url = f"http://127.0.0.1:{self.gui.app.port}/download"
if public_mode: if public_mode:
r = requests.get(url) r = requests.get(url)
else: else:
@ -201,7 +201,7 @@ class GuiBaseTest(object):
def web_server_is_running(self): def web_server_is_running(self):
"""Test that the web server has started""" """Test that the web server has started"""
try: try:
r = requests.get("http://127.0.0.1:{}/".format(self.gui.app.port)) r = requests.get(f"http://127.0.0.1:{self.gui.app.port}/")
self.assertTrue(True) self.assertTrue(True)
except requests.exceptions.ConnectionError: except requests.exceptions.ConnectionError:
self.assertTrue(False) self.assertTrue(False)
@ -230,15 +230,11 @@ class GuiBaseTest(object):
) )
clipboard = self.gui.qtapp.clipboard() clipboard = self.gui.qtapp.clipboard()
if public_mode: if public_mode:
self.assertEqual( self.assertEqual(clipboard.text(), f"http://127.0.0.1:{self.gui.app.port}")
clipboard.text(), "http://127.0.0.1:{}".format(self.gui.app.port)
)
else: else:
self.assertEqual( self.assertEqual(
clipboard.text(), clipboard.text(),
"http://onionshare:{}@127.0.0.1:{}".format( f"http://onionshare:{mode.server_status.web.password}@127.0.0.1:{self.gui.app.port}",
mode.server_status.web.password, self.gui.app.port
),
) )
def server_status_indicator_says_started(self, mode): def server_status_indicator_says_started(self, mode):
@ -257,7 +253,7 @@ class GuiBaseTest(object):
def web_page(self, mode, string, public_mode): def web_page(self, mode, string, public_mode):
"""Test that the web page contains a string""" """Test that the web page contains a string"""
url = "http://127.0.0.1:{}/".format(self.gui.app.port) url = f"http://127.0.0.1:{self.gui.app.port}/"
if public_mode: if public_mode:
r = requests.get(url) r = requests.get(url)
else: else:
@ -293,7 +289,7 @@ class GuiBaseTest(object):
QtTest.QTest.qWait(2000) QtTest.QTest.qWait(2000)
try: try:
r = requests.get("http://127.0.0.1:{}/".format(self.gui.app.port)) r = requests.get(f"http://127.0.0.1:{self.gui.app.port}/")
self.assertTrue(False) self.assertTrue(False)
except requests.exceptions.ConnectionError: except requests.exceptions.ConnectionError:
self.assertTrue(True) self.assertTrue(True)

View file

@ -19,7 +19,7 @@ class GuiReceiveTest(GuiBaseTest):
QtTest.QTest.qWait(2000) QtTest.QTest.qWait(2000)
files = {"file[]": open(file_to_upload, "rb")} files = {"file[]": open(file_to_upload, "rb")}
url = "http://127.0.0.1:{}/upload".format(self.gui.app.port) url = f"http://127.0.0.1:{self.gui.app.port}/upload"
if public_mode: if public_mode:
r = requests.post(url, files=files) r = requests.post(url, files=files)
if identical_files_at_once: if identical_files_at_once:
@ -68,7 +68,7 @@ class GuiReceiveTest(GuiBaseTest):
def upload_file_should_fail(self, public_mode): def upload_file_should_fail(self, public_mode):
"""Test that we can't upload the file when permissions are wrong, and expected content is shown""" """Test that we can't upload the file when permissions are wrong, and expected content is shown"""
files = {"file[]": open("/tmp/test.txt", "rb")} files = {"file[]": open("/tmp/test.txt", "rb")}
url = "http://127.0.0.1:{}/upload".format(self.gui.app.port) url = f"http://127.0.0.1:{self.gui.app.port}/upload"
if public_mode: if public_mode:
r = requests.post(url, files=files) r = requests.post(url, files=files)
else: else:
@ -88,9 +88,9 @@ class GuiReceiveTest(GuiBaseTest):
os.chmod("/tmp/OnionShare", mode) os.chmod("/tmp/OnionShare", mode)
def try_without_auth_in_non_public_mode(self): def try_without_auth_in_non_public_mode(self):
r = requests.post("http://127.0.0.1:{}/upload".format(self.gui.app.port)) r = requests.post(f"http://127.0.0.1:{self.gui.app.port}/upload")
self.assertEqual(r.status_code, 401) self.assertEqual(r.status_code, 401)
r = requests.get("http://127.0.0.1:{}/close".format(self.gui.app.port)) r = requests.get(f"http://127.0.0.1:{self.gui.app.port}/close")
self.assertEqual(r.status_code, 401) self.assertEqual(r.status_code, 401)
# 'Grouped' tests follow from here # 'Grouped' tests follow from here

View file

@ -105,7 +105,7 @@ class GuiShareTest(GuiBaseTest):
def download_share(self, public_mode): def download_share(self, public_mode):
"""Test that we can download the share""" """Test that we can download the share"""
url = "http://127.0.0.1:{}/download".format(self.gui.app.port) url = f"http://127.0.0.1:{self.gui.app.port}/download"
if public_mode: if public_mode:
r = requests.get(url) r = requests.get(url)
else: else:
@ -126,8 +126,8 @@ class GuiShareTest(GuiBaseTest):
def individual_file_is_viewable_or_not(self, public_mode, stay_open): def individual_file_is_viewable_or_not(self, public_mode, stay_open):
"""Test whether an individual file is viewable (when in stay_open mode) and that it isn't (when not in stay_open mode)""" """Test whether an individual file is viewable (when in stay_open mode) and that it isn't (when not in stay_open mode)"""
url = "http://127.0.0.1:{}".format(self.gui.app.port) url = f"http://127.0.0.1:{self.gui.app.port}"
download_file_url = "http://127.0.0.1:{}/test.txt".format(self.gui.app.port) download_file_url = f"http://127.0.0.1:{self.gui.app.port}/test.txt"
if public_mode: if public_mode:
r = requests.get(url) r = requests.get(url)
else: else:
@ -175,7 +175,7 @@ class GuiShareTest(GuiBaseTest):
def hit_401(self, public_mode): def hit_401(self, public_mode):
"""Test that the server stops after too many 401s, or doesn't when in public_mode""" """Test that the server stops after too many 401s, or doesn't when in public_mode"""
url = "http://127.0.0.1:{}/".format(self.gui.app.port) url = f"http://127.0.0.1:{self.gui.app.port}/"
for _ in range(20): for _ in range(20):
password_guess = self.gui.common.build_password() password_guess = self.gui.common.build_password()

View file

@ -67,7 +67,7 @@ class GuiWebsiteTest(GuiShareTest):
def view_website(self, public_mode): def view_website(self, public_mode):
"""Test that we can download the share""" """Test that we can download the share"""
url = "http://127.0.0.1:{}/".format(self.gui.app.port) url = f"http://127.0.0.1:{self.gui.app.port}/"
if public_mode: if public_mode:
r = requests.get(url) r = requests.get(url)
else: else:
@ -83,7 +83,7 @@ class GuiWebsiteTest(GuiShareTest):
def check_csp_header(self, public_mode, csp_header_disabled): def check_csp_header(self, public_mode, csp_header_disabled):
"""Test that the CSP header is present when enabled or vice versa""" """Test that the CSP header is present when enabled or vice versa"""
url = "http://127.0.0.1:{}/".format(self.gui.app.port) url = f"http://127.0.0.1:{self.gui.app.port}/"
if public_mode: if public_mode:
r = requests.get(url) r = requests.get(url)
else: else:

View file

@ -79,28 +79,24 @@ class TorGuiBaseTest(GuiBaseTest):
(socks_address, socks_port) = self.gui.app.onion.get_tor_socks_port() (socks_address, socks_port) = self.gui.app.onion.get_tor_socks_port()
session = requests.session() session = requests.session()
session.proxies = {} session.proxies = {}
session.proxies["http"] = "socks5h://{}:{}".format(socks_address, socks_port) session.proxies["http"] = f"socks5h://{socks_address}:{socks_port}"
if type(mode) == ReceiveMode: if type(mode) == ReceiveMode:
# Upload a file # Upload a file
files = {"file[]": open("/tmp/test.txt", "rb")} files = {"file[]": open("/tmp/test.txt", "rb")}
if not public_mode: if not public_mode:
path = "http://{}/{}/upload".format( path = f"http://{self.gui.app.onion_host}/{mode.web.password}/upload"
self.gui.app.onion_host, mode.web.password
)
else: else:
path = "http://{}/upload".format(self.gui.app.onion_host) path = f"http://{self.gui.app.onion_host}/upload"
response = session.post(path, files=files) response = session.post(path, files=files)
QtTest.QTest.qWait(4000) QtTest.QTest.qWait(4000)
if type(mode) == ShareMode: if type(mode) == ShareMode:
# Download files # Download files
if public_mode: if public_mode:
path = "http://{}/download".format(self.gui.app.onion_host) path = f"http://{self.gui.app.onion_host}/download"
else: else:
path = "http://{}/{}/download".format( path = f"http://{self.gui.app.onion_host}/{mode.web.password}/download"
self.gui.app.onion_host, mode.web.password
)
response = session.get(path) response = session.get(path)
QtTest.QTest.qWait(4000) QtTest.QTest.qWait(4000)
@ -124,11 +120,11 @@ class TorGuiBaseTest(GuiBaseTest):
s.settimeout(60) s.settimeout(60)
s.connect((self.gui.app.onion_host, 80)) s.connect((self.gui.app.onion_host, 80))
if not public_mode: if not public_mode:
path = "/{}".format(mode.server_status.web.password) path = f"/{mode.server_status.web.password}"
else: else:
path = "/" path = "/"
http_request = "GET {} HTTP/1.0\r\n".format(path) http_request = f"GET {path} HTTP/1.0\r\n"
http_request += "Host: {}\r\n".format(self.gui.app.onion_host) http_request += f"Host: {self.gui.app.onion_host}\r\n"
http_request += "\r\n" http_request += "\r\n"
s.sendall(http_request.encode("utf-8")) s.sendall(http_request.encode("utf-8"))
with open("/tmp/webpage", "wb") as file_to_write: with open("/tmp/webpage", "wb") as file_to_write:
@ -151,15 +147,11 @@ class TorGuiBaseTest(GuiBaseTest):
) )
clipboard = self.gui.qtapp.clipboard() clipboard = self.gui.qtapp.clipboard()
if public_mode: if public_mode:
self.assertEqual( self.assertEqual(clipboard.text(), f"http://{self.gui.app.onion_host}")
clipboard.text(), "http://{}".format(self.gui.app.onion_host)
)
else: else:
self.assertEqual( self.assertEqual(
clipboard.text(), clipboard.text(),
"http://{}/{}".format( f"http://{self.gui.app.onion_host}/{mode.server_status.web.password}",
self.gui.app.onion_host, mode.server_status.web.password
),
) )
# Stealth tests # Stealth tests

View file

@ -10,14 +10,12 @@ class TorGuiReceiveTest(TorGuiBaseTest):
(socks_address, socks_port) = self.gui.app.onion.get_tor_socks_port() (socks_address, socks_port) = self.gui.app.onion.get_tor_socks_port()
session = requests.session() session = requests.session()
session.proxies = {} session.proxies = {}
session.proxies["http"] = "socks5h://{}:{}".format(socks_address, socks_port) session.proxies["http"] = f"socks5h://{socks_address}:{socks_port}"
files = {"file[]": open(file_to_upload, "rb")} files = {"file[]": open(file_to_upload, "rb")}
if not public_mode: if not public_mode:
path = "http://{}/{}/upload".format( path = f"http://{self.gui.app.onion_host}/{self.gui.receive_mode.web.password}/upload"
self.gui.app.onion_host, self.gui.receive_mode.web.password
)
else: else:
path = "http://{}/upload".format(self.gui.app.onion_host) path = f"http://{self.gui.app.onion_host}/upload"
response = session.post(path, files=files) response = session.post(path, files=files)
QtTest.QTest.qWait(4000) QtTest.QTest.qWait(4000)
self.assertTrue(os.path.isfile(expected_file)) self.assertTrue(os.path.isfile(expected_file))

View file

@ -12,15 +12,13 @@ class TorGuiShareTest(TorGuiBaseTest, GuiShareTest):
(socks_address, socks_port) = self.gui.app.onion.get_tor_socks_port() (socks_address, socks_port) = self.gui.app.onion.get_tor_socks_port()
session = requests.session() session = requests.session()
session.proxies = {} session.proxies = {}
session.proxies["http"] = "socks5h://{}:{}".format(socks_address, socks_port) session.proxies["http"] = f"socks5h://{socks_address}:{socks_port}"
# Download files # Download files
if public_mode: if public_mode:
path = "http://{}/download".format(self.gui.app.onion_host) path = f"http://{self.gui.app.onion_host}/download"
else: else:
path = "http://{}/{}/download".format( path = f"http://{self.gui.app.onion_host}/{self.gui.share_mode.web.password}/download"
self.gui.app.onion_host, self.gui.share_mode.web.password
)
response = session.get(path, stream=True) response = session.get(path, stream=True)
QtTest.QTest.qWait(4000) QtTest.QTest.qWait(4000)

View file

@ -166,7 +166,7 @@ class TestWeb:
assert res.status_code == 401 assert res.status_code == 401
# But static resources should work without auth # But static resources should work without auth
res = c.get("{}/css/style.css".format(web.static_url_path)) res = c.get(f"{web.static_url_path}/css/style.css")
res.get_data() res.get_data()
assert res.status_code == 200 assert res.status_code == 200
@ -186,11 +186,7 @@ class TestZipWriterDefault:
@pytest.mark.parametrize( @pytest.mark.parametrize(
"test_input", "test_input",
( (
"onionshare_{}.zip".format( f"onionshare_{''.join(random.choice('abcdefghijklmnopqrstuvwxyz234567') for _ in range(6))}.zip"
"".join(
random.choice("abcdefghijklmnopqrstuvwxyz234567") for _ in range(6)
)
)
for _ in range(50) for _ in range(50)
), ),
) )