Replace .format with python 3.6 f-strings in onionshare_gui module

This commit is contained in:
Micah Lee 2019-10-20 10:30:16 -07:00
parent b9a7361d9c
commit 3a2cc8bdee
No known key found for this signature in database
GPG Key ID: 403C2657CD994F73
9 changed files with 42 additions and 75 deletions

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,15 @@ 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( ):
"{0:s}: {1:s}".format( self.status_bar.showMessage(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):