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 27107d8992
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
29 changed files with 147 additions and 263 deletions

View File

@ -7,14 +7,13 @@ workflows:
version: 2
test:
jobs:
- test-3.5
- test-3.6
- test-3.7
jobs:
test-3.5: &test-template
test-3.6: &test-template
docker:
- image: circleci/python:3.5.6
- image: circleci/python:3.6.6
working_directory: ~/repo
@ -44,11 +43,6 @@ jobs:
command: |
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-template
docker:

View File

@ -31,9 +31,9 @@ from .onionshare import OnionShare
def build_url(common, app, web):
# Build the URL
if common.settings.get("public_mode"):
return "http://{0:s}".format(app.onion_host)
return f"http://{app.onion_host}"
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):
@ -44,7 +44,7 @@ def main(cwd=None):
common = Common()
# 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)
if common.platform == "Darwin":
@ -160,10 +160,10 @@ def main(cwd=None):
valid = True
for filename in filenames:
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
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
if not valid:
sys.exit()
@ -217,9 +217,7 @@ def main(cwd=None):
schedule = datetime.now() + timedelta(seconds=autostart_timer)
if mode == "receive":
print(
"Files sent to you appear in this folder: {}".format(
common.settings.get("data_dir")
)
f"Files sent to you appear in this folder: {common.settings.get('data_dir')}"
)
print("")
print(
@ -228,30 +226,22 @@ def main(cwd=None):
print("")
if stealth:
print(
"Give this address and HidServAuth lineto your sender, and tell them it won't be accessible until: {}".format(
schedule.strftime("%I:%M:%S%p, %b %d, %y")
)
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')}"
)
print(app.auth_string)
else:
print(
"Give this address to your sender, and tell them it won't be accessible until: {}".format(
schedule.strftime("%I:%M:%S%p, %b %d, %y")
)
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')}"
)
else:
if stealth:
print(
"Give this address and HidServAuth line to your recipient, and tell them it won't be accessible until: {}".format(
schedule.strftime("%I:%M:%S%p, %b %d, %y")
)
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')}"
)
print(app.auth_string)
else:
print(
"Give this address to your recipient, and tell them it won't be accessible until: {}".format(
schedule.strftime("%I:%M:%S%p, %b %d, %y")
)
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')}"
)
print(url)
print("")
@ -324,9 +314,7 @@ def main(cwd=None):
else:
if mode == "receive":
print(
"Files sent to you appear in this folder: {}".format(
common.settings.get("data_dir")
)
f"Files sent to you appear in this folder: {common.settings.get('data_dir')}"
)
print("")
print(

View File

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

View File

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

View File

@ -56,7 +56,7 @@ class OnionShare(object):
self.autostop_timer_thread = None
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.onion.stealth = stealth
@ -83,7 +83,7 @@ class OnionShare(object):
self.autostop_timer_thread = AutoStopTimer(self.common, self.autostop_timer)
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
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 os.path.exists(self.filename):
try:
self.common.log(
"Settings", "load", "Trying to load {}".format(self.filename)
)
self.common.log("Settings", "load", f"Trying to load {self.filename}")
with open(self.filename, "r") as f:
self._settings = json.load(f)
self.fill_in_defaults()
@ -211,9 +209,7 @@ class Settings(object):
"""
self.common.log("Settings", "save")
open(self.filename, "w").write(json.dumps(self._settings, indent=2))
self.common.log(
"Settings", "save", "Settings saved in {}".format(self.filename)
)
self.common.log("Settings", "save", f"Settings saved in {self.filename}")
def get(self, key):
return self._settings[key]

View File

@ -36,7 +36,7 @@ def load_strings(common):
translations = {}
for locale in common.settings.available_locales:
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:
translations[locale] = json.load(f)

View File

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

View File

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

View File

@ -340,8 +340,8 @@ class ZipWriter(object):
if zip_filename:
self.zip_filename = zip_filename
else:
self.zip_filename = "{0:s}/onionshare_{1:s}.zip".format(
tempfile.mkdtemp(), self.common.random_string(4, 6)
self.zip_filename = (
f"{tempfile.mkdtemp()}/onionshare_{self.common.random_string(4, 6)}.zip"
)
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"):
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
self.app = Flask(
__name__,
static_folder=self.common.get_resource_path("static"),
static_url_path="/static_".format(
self.common.random_string(16)
), # randomize static_url_path to avoid making /static unusable
static_url_path=f"/static_{self.common.random_string(16)}", # randomize static_url_path to avoid making /static unusable
template_folder=self.common.get_resource_path("templates"),
)
self.app.secret_key = self.common.random_string(8)
@ -154,11 +152,11 @@ class Web:
def generate_static_url_path(self):
# The static URL path has a 128-bit random number in it to avoid having name
# 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(
"Web",
"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
@ -218,7 +216,7 @@ class Web:
@self.app.route("/favicon.ico")
def favicon():
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):
@ -228,7 +226,7 @@ class Web:
auth["username"] == "onionshare"
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.invalid_passwords.append(auth["password"])
@ -256,7 +254,7 @@ class Web:
def error404(self, history_id):
self.add_request(
self.REQUEST_INDIVIDUAL_FILE_STARTED,
"{}".format(request.path),
request.path,
{"id": history_id, "status_code": 404},
)
@ -269,7 +267,7 @@ class Web:
def error405(self, history_id):
self.add_request(
self.REQUEST_INDIVIDUAL_FILE_STARTED,
"{}".format(request.path),
request.path,
{"id": history_id, "status_code": 405},
)
@ -309,23 +307,19 @@ class Web:
def generate_password(self, persistent_password=None):
self.common.log(
"Web",
"generate_password",
"persistent_password={}".format(persistent_password),
"Web", "generate_password", f"persistent_password={persistent_password}"
)
if persistent_password != None and persistent_password != "":
self.password = persistent_password
self.common.log(
"Web",
"generate_password",
'persistent_password sent, so password is: "{}"'.format(self.password),
f'persistent_password sent, so password is: "{self.password}"',
)
else:
self.password = self.common.build_password()
self.common.log(
"Web",
"generate_password",
'built random password: "{}"'.format(self.password),
"Web", "generate_password", f'built random password: "{self.password}"'
)
def verbose_mode(self):
@ -362,9 +356,7 @@ class Web:
self.common.log(
"Web",
"start",
"port={}, stay_open={}, public_mode={}, password={}".format(
port, stay_open, public_mode, password
),
f"port={port}, stay_open={stay_open}, public_mode={public_mode}, password={password}",
)
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)
if self.running:
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),
)

View File

@ -63,7 +63,7 @@ def main():
common.define_css()
# 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
# https://stackoverflow.com/questions/42814093/how-to-handle-ctrlc-in-python-app-with-pyqt
@ -124,10 +124,10 @@ def main():
valid = True
for filename in filenames:
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
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
if not valid:
sys.exit()

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -672,7 +672,7 @@ class SettingsDialog(QtWidgets.QDialog):
strings._("gui_settings_button_cancel")
)
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"])
self.help_button = QtWidgets.QPushButton(strings._("gui_settings_button_help"))
self.help_button.clicked.connect(self.help_clicked)
@ -1040,7 +1040,7 @@ class SettingsDialog(QtWidgets.QDialog):
self.common.log(
"SettingsDialog",
"data_dir_button_clicked",
"selected dir: {}".format(selected_dir),
f"selected dir: {selected_dir}",
)
self.data_dir_lineedit.setText(selected_dir)
@ -1255,9 +1255,7 @@ class SettingsDialog(QtWidgets.QDialog):
self.common.log(
"SettingsDialog",
"save_clicked",
"Onion done rebooting, connected to Tor: {}".format(
self.onion.connected_to_tor
),
f"Onion done rebooting, connected to Tor: {self.onion.connected_to_tor}",
)
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):
self.tor_status.setText(
"<strong>{}</strong><br>{}% {}".format(
strings._("connecting_to_tor"), progress, summary
)
f"<strong>{strings._('connecting_to_tor')}</strong><br>{progress}% {summary}"
)
self.qtapp.processEvents()
if "Done" in summary:

View File

@ -86,7 +86,7 @@ class TorConnectionDialog(QtWidgets.QProgressDialog):
def _tor_status_update(self, progress, summary):
self.setValue(int(progress))
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):
@ -112,7 +112,7 @@ class TorConnectionDialog(QtWidgets.QProgressDialog):
# Display the exception in an alert box
Alert(
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,
)
@ -162,7 +162,7 @@ class TorConnectionThread(QtCore.QThread):
except Exception as e:
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]))

View File

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

View File

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

View File

@ -19,7 +19,7 @@ class GuiReceiveTest(GuiBaseTest):
QtTest.QTest.qWait(2000)
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:
r = requests.post(url, files=files)
if identical_files_at_once:
@ -68,7 +68,7 @@ class GuiReceiveTest(GuiBaseTest):
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"""
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:
r = requests.post(url, files=files)
else:
@ -88,9 +88,9 @@ class GuiReceiveTest(GuiBaseTest):
os.chmod("/tmp/OnionShare", mode)
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)
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)
# 'Grouped' tests follow from here

View File

@ -105,7 +105,7 @@ class GuiShareTest(GuiBaseTest):
def download_share(self, public_mode):
"""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:
r = requests.get(url)
else:
@ -126,8 +126,8 @@ class GuiShareTest(GuiBaseTest):
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)"""
url = "http://127.0.0.1:{}".format(self.gui.app.port)
download_file_url = "http://127.0.0.1:{}/test.txt".format(self.gui.app.port)
url = f"http://127.0.0.1:{self.gui.app.port}"
download_file_url = f"http://127.0.0.1:{self.gui.app.port}/test.txt"
if public_mode:
r = requests.get(url)
else:
@ -175,7 +175,7 @@ class GuiShareTest(GuiBaseTest):
def hit_401(self, 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):
password_guess = self.gui.common.build_password()

View File

@ -67,7 +67,7 @@ class GuiWebsiteTest(GuiShareTest):
def view_website(self, public_mode):
"""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:
r = requests.get(url)
else:
@ -83,7 +83,7 @@ class GuiWebsiteTest(GuiShareTest):
def check_csp_header(self, public_mode, csp_header_disabled):
"""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:
r = requests.get(url)
else:

View File

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

View File

@ -10,14 +10,12 @@ class TorGuiReceiveTest(TorGuiBaseTest):
(socks_address, socks_port) = self.gui.app.onion.get_tor_socks_port()
session = requests.session()
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")}
if not public_mode:
path = "http://{}/{}/upload".format(
self.gui.app.onion_host, self.gui.receive_mode.web.password
)
path = f"http://{self.gui.app.onion_host}/{self.gui.receive_mode.web.password}/upload"
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)
QtTest.QTest.qWait(4000)
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()
session = requests.session()
session.proxies = {}
session.proxies["http"] = "socks5h://{}:{}".format(socks_address, socks_port)
session.proxies["http"] = f"socks5h://{socks_address}:{socks_port}"
# Download files
if public_mode:
path = "http://{}/download".format(self.gui.app.onion_host)
path = f"http://{self.gui.app.onion_host}/download"
else:
path = "http://{}/{}/download".format(
self.gui.app.onion_host, self.gui.share_mode.web.password
)
path = f"http://{self.gui.app.onion_host}/{self.gui.share_mode.web.password}/download"
response = session.get(path, stream=True)
QtTest.QTest.qWait(4000)

View File

@ -166,7 +166,7 @@ class TestWeb:
assert res.status_code == 401
# 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()
assert res.status_code == 200
@ -186,11 +186,7 @@ class TestZipWriterDefault:
@pytest.mark.parametrize(
"test_input",
(
"onionshare_{}.zip".format(
"".join(
random.choice("abcdefghijklmnopqrstuvwxyz234567") for _ in range(6)
)
)
f"onionshare_{''.join(random.choice('abcdefghijklmnopqrstuvwxyz234567') for _ in range(6))}.zip"
for _ in range(50)
),
)