Skip to content

Commit

Permalink
Clean up unused code and improve readability
Browse files Browse the repository at this point in the history
  • Loading branch information
justin025 committed Dec 4, 2024
1 parent 23b63c7 commit c702805
Show file tree
Hide file tree
Showing 13 changed files with 66 additions and 63 deletions.
1 change: 1 addition & 0 deletions src/onthespot/accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ def __init__(self, gui=False):
self.gui = gui
super().__init__()


def run(self):
accounts = config.get('accounts')
for account in accounts:
Expand Down
4 changes: 3 additions & 1 deletion src/onthespot/casualsnek.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ def start_snake_game(win):
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_YELLOW, curses.COLOR_BLACK)


while True:
snake = [(4, 10), (4, 9), (4, 8)]
food = (random.randint(3, win.getmaxyx()[0] - 2), random.randint(1, win.getmaxyx()[1] - 3))
Expand Down Expand Up @@ -65,6 +64,7 @@ def start_snake_game(win):
elif key == ord('q'):
return


def draw_borders(win):
height, width = win.getmaxyx()
if width < 2 or height < 2:
Expand All @@ -79,6 +79,7 @@ def draw_borders(win):
if height > 1 and width > 2:
win.addstr(height - 1, 0, '┗' + '━' * (width - 3) + '┛', curses.color_pair(1))


def update_header(win, score):
win.addstr(1, 2, f'Score: {score}', curses.A_BOLD)
if not download_queue:
Expand All @@ -89,6 +90,7 @@ def update_header(win, score):

win.addstr(1, 15, item_label, curses.A_BOLD)


def display_game_over(win, score):
win.clear()
if score > config.get('snake_high_score', 0):
Expand Down
6 changes: 0 additions & 6 deletions src/onthespot/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ class CLI(Cmd):
intro = '\033[32mWelcome to OnTheSpot. Type help or ? to list commands.\033[0m'
prompt = '(OTS) '


def do_help(self, arg):
print("\033[32mAvailable commands:\033[0m")
print(" help - Show this help message")
Expand Down Expand Up @@ -141,7 +140,6 @@ def add_spotify_account_worker():
deezer_add_account(parts[2])

elif len(parts) == 2 and parts[0] == "select_account":

try:
account_number = int(parts[1])
config.set_('parsing_acc_sn', account_number)
Expand All @@ -151,7 +149,6 @@ def add_spotify_account_worker():
print("\033[32mInvalid account number. Please enter a valid integer.\033[0m")

elif len(parts) == 2 and parts[0] == "delete_account":

try:
account_number = int(parts[1])
accounts = config.get('accounts').copy()
Expand All @@ -162,7 +159,6 @@ def add_spotify_account_worker():
print(f"\033[32mDeleted account number: {account_number}\033[0m")
except ValueError:
print("\033[32mInvalid account number. Please enter a valid integer.\033[0m")

else:
print("\033[32mConfiguration options:\033[0m")
print(" list_accounts")
Expand Down Expand Up @@ -300,13 +296,11 @@ def refresh_queue():
stdscr.refresh()



def do_exit(self, arg):
"""Exit the CLI application."""
print("Exiting the CLI application.")
os._exit(0)



if __name__ == '__main__':
main()
14 changes: 10 additions & 4 deletions src/onthespot/gui/dl_progressbtn.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def __init__(self, local_id, item_metadata, pbar, copy_btn, cancel_btn, retry_bt
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
layout.addWidget(pbar)
if copy_btn != None:
if copy_btn is not None:
self.copy_btn = copy_btn
copy_btn.clicked.connect(self.copy_link)
layout.addWidget(copy_btn)
Expand All @@ -27,47 +27,53 @@ def __init__(self, local_id, item_metadata, pbar, copy_btn, cancel_btn, retry_bt
self.retry_btn = retry_btn
retry_btn.clicked.connect(self.retry_item)
layout.addWidget(retry_btn)
if open_btn != None:
if open_btn is not None:
self.open_btn = open_btn
open_btn.clicked.connect(self.open_file)
layout.addWidget(open_btn)
if locate_btn != None:
if locate_btn is not None:
self.locate_btn = locate_btn
locate_btn.clicked.connect(self.locate_file)
layout.addWidget(locate_btn)
if delete_btn != None:
if delete_btn is not None:
self.delete_btn = delete_btn
delete_btn.clicked.connect(self.delete_file)
layout.addWidget(delete_btn)
self.setLayout(layout)


def copy_link(self):
pyperclip.copy(self.item_metadata['item_url'])


def cancel_item(self):
download_queue[self.local_id]['item_status'] = "Cancelled"
download_queue[self.local_id]['gui']['status_label'].setText(self.tr("Cancelled"))
download_queue[self.local_id]['gui']['progress_bar'].setValue(0)
self.cancel_btn.hide()
self.retry_btn.show()


def retry_item(self):
download_queue[self.local_id]['item_status'] = "Waiting"
download_queue[self.local_id]['gui']['status_label'].setText(self.tr("Waiting"))
download_queue[self.local_id]['gui']['progress_bar'].setValue(0)
self.retry_btn.hide()
self.cancel_btn.show()


def open_file(self):
file_path = download_queue[self.local_id]['file_path']
file = os.path.abspath(file_path)
open_item(file)


def locate_file(self):
file_path = download_queue[self.local_id]['file_path']
file_dir = os.path.dirname(file_path)
open_item(file_dir)


def delete_file(self):
file_path = download_queue[self.local_id]['file_path']
file = os.path.abspath(file_path)
Expand Down
71 changes: 20 additions & 51 deletions src/onthespot/gui/mainui.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,11 @@ def stop(self):


class MainWindow(QMainWindow):
def closeEvent(self, event):
if config.get('close_to_tray') and get_init_tray():
event.ignore()
self.hide()


# Remove Later
def contribute(self):
Expand All @@ -74,12 +79,6 @@ def contribute(self):
open_item(url)


def closeEvent(self, event):
if config.get('close_to_tray') and get_init_tray():
event.ignore()
self.hide()


def __init__(self, _dialog, start_url=''):
super(MainWindow, self).__init__()
self.path = os.path.dirname(os.path.realpath(__file__))
Expand Down Expand Up @@ -123,9 +122,6 @@ def __init__(self, _dialog, start_url=''):
# Bind button click
self.bind_button_inputs()

self.__users = []
self.last_search = None

# Set application theme
self.toggle_theme_button.clicked.connect(self.toggle_theme)
self.theme = config.get("theme")
Expand Down Expand Up @@ -219,8 +215,6 @@ def bind_button_inputs(self):


def set_table_props(self):
window_width = self.width()
logger.info(f"Setting table item properties {window_width}")
# Sessions table
#self.tbl_sessions.setSortingEnabled(True)
self.tbl_sessions.horizontalHeader().setSectionsMovable(True)
Expand Down Expand Up @@ -305,7 +299,6 @@ def session_load_done(self):


def fill_account_table(self):

# Clear the table
while self.tbl_sessions.rowCount() > 0:
self.tbl_sessions.removeRow(0)
Expand Down Expand Up @@ -418,7 +411,7 @@ def add_item_to_download_list(self, item, item_metadata):

rows = self.tbl_dl_progress.rowCount()
self.tbl_dl_progress.insertRow(rows)
if item_metadata.get('explicit', ''): # Check if the item is explicit
if item_metadata.get('explicit', ''):
title = config.get('explicit_label', '') + ' ' + item_metadata['title']
else:
title = item_metadata['title']
Expand Down Expand Up @@ -521,34 +514,12 @@ def remove_completed_from_download_list(self):
"Already Exists"
):
logger.info(f'Removing Row: {check_row} and mediaid: {local_id}')

# Clear the widget in the last column before removing the row
widget = self.tbl_dl_progress.cellWidget(check_row, 0)
if widget:
widget.deleteLater() # Schedule the widget for deletion
widget = self.tbl_dl_progress.cellWidget(check_row, 1)
if widget:
widget.deleteLater() # Schedule the widget for deletion
widget = self.tbl_dl_progress.cellWidget(check_row, 2)
if widget:
widget.deleteLater() # Schedule the widget for deletion
widget = self.tbl_dl_progress.cellWidget(check_row, 3)
if widget:
widget.deleteLater() # Schedule the widget for deletion
widget = self.tbl_dl_progress.cellWidget(check_row, 4)
if widget:
widget.deleteLater() # Schedule the widget for deletion
widget = self.tbl_dl_progress.cellWidget(check_row, 5)
if widget:
widget.deleteLater() # Schedule the widget for deletion

# Remove the row from the table
self.tbl_dl_progress.removeRow(check_row)
download_queue.pop(local_id)
else:
check_row += 1 # Move to the next row
check_row += 1
else:
check_row += 1 # Move to the next row
check_row += 1


def cancel_all_downloads(self):
Expand Down Expand Up @@ -732,31 +703,29 @@ def fill_search_table(self):
self.inp_search_term.setText('')
return

def download_btn_clicked(item_name, item_url, item_service, item_type, item_id, ):
parsing[item_id] = {
'item_url': item_url,
'item_service': item_service,
'item_type': item_type,
'item_id': item_id
}
self.__show_popup_dialog(self.tr("{0} is being parsed and will be added to the download queue shortly.").format(f"{item_type.title()}: {item_name}"), download=True)

for result in results:
btn = QPushButton(self.tbl_search_results)
#btn.setText(btn_text.strip())
btn.setIcon(self.get_icon('download'))

item_url = result['item_url']

def download_btn_clicked(item_name, item_url, item_service, item_type, item_id, ):
parsing[item_id] = {
'item_url': item_url,
'item_service': item_service,
'item_type': item_type,
'item_id': item_id
}
self.__show_popup_dialog(self.tr("{0} is being parsed and will be added to the download queue shortly.").format(f"{item_type.title()}: {item_name}"), download=True)

btn.setMinimumHeight(30)
btn.clicked.connect(lambda x,
item_name=result['item_name'],
item_url=result['item_url'],
item_type=result['item_type'],
item_id=result['item_id'],
item_service=result['item_service']:
download_btn_clicked(item_name, item_url, item_service, item_type, item_id))
download_btn_clicked(item_name, item_url, item_service, item_type, item_id)
)

btn.setMinimumHeight(30)
service = QTableWidgetItem(result['item_service'].title())
service.setIcon(self.get_icon(result["item_service"]))

Expand Down
3 changes: 3 additions & 0 deletions src/onthespot/gui/minidialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

logger = get_logger('gui.minidialog')


class MiniDialog(QDialog):
def __init__(self, parent=None):
super(MiniDialog, self).__init__(parent)
Expand All @@ -31,6 +32,7 @@ def __init__(self, parent=None):

self.lb_main.mousePressEvent = self.on_label_click


def on_label_click(self, event):
if event.button() == Qt.MouseButton.LeftButton:
match = re.search(r"href='(https?://[^']+)'", self.lb_main.text())
Expand All @@ -40,6 +42,7 @@ def on_label_click(self, event):
logger.info(f"Update URL Clicked, {match.group(1)}")
open_item(match.group(1))
except Exception:
# No url in label
pass

def run(self, content, btn_hidden=False):
Expand Down
4 changes: 3 additions & 1 deletion src/onthespot/gui/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def wheelEvent(self, event):


def load_config(self):
# Hide Popups
# Hide Popup Settings
self.group_search_items.hide()
self.group_download_items.hide()

Expand All @@ -32,6 +32,7 @@ def load_config(self):
self.inp_login_service.insertItem(3, self.get_icon('youtube'), "")
self.inp_login_service.setCurrentIndex(2)

#self.btn_reset_config.setIcon(self.get_icon('trash'))
self.btn_save_config.setIcon(self.get_icon('save'))
self.btn_download_root_browse.setIcon(self.get_icon('folder'))
self.btn_download_tmp_browse.setIcon(self.get_icon('folder'))
Expand Down Expand Up @@ -176,6 +177,7 @@ def load_config(self):
# Store the newly created widget in the previous instance variable
setattr(self, name, new_widget)


def save_config(self):
# Missing Theme
config.set_('language_index', self.inp_language.currentIndex())
Expand Down
1 change: 1 addition & 0 deletions src/onthespot/gui/thumb_listitem.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ def __init__(self, label, thumb_url):

self.setLayout(layout)


def on_finished(self, reply: QNetworkReply):
# This method is called when the network request is completed
if reply.error() == QNetworkReply.NetworkError.NoError: # Correct error checking
Expand Down
5 changes: 5 additions & 0 deletions src/onthespot/otsconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ def config_dir():
else:
return os.path.join(os.path.expanduser("~"), ".config")


def cache_dir():
if os.name == "nt":
if 'TEMP' in os.environ:
Expand Down Expand Up @@ -223,6 +224,7 @@ def __init__(self, cfg_path=None):
os.path.dirname(self.get("_log_file")), exist_ok=True
)


def get(self, key, default=None):
if key in self.__config:
return self.__config[key]
Expand All @@ -231,13 +233,15 @@ def get(self, key, default=None):
else:
return default


def set_(self, key, value):
if type(value) in [list, dict]:
self.__config[key] = value.copy()
else:
self.__config[key] = value
return value


def update(self):
os.makedirs(os.path.dirname(self.__cfg_path), exist_ok=True)
for key in list(set(self.__template_data).difference(set(self.__config))):
Expand All @@ -246,6 +250,7 @@ def update(self):
with open(self.__cfg_path, "w") as cf:
cf.write(json.dumps(self.__config, indent=4))


def rollback(self):
with open(self.__cfg_path, "w") as cf:
cf.write(json.dumps(self.__template_data, indent=4))
Expand Down
1 change: 1 addition & 0 deletions src/onthespot/parse_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ def parse_url(url):
'item_id': item_id
}


def parsingworker():
while True:
if parsing:
Expand Down
Loading

0 comments on commit c702805

Please sign in to comment.