Skip to content

Commit

Permalink
Fix tray bug and add the ability to download from multiple services a…
Browse files Browse the repository at this point in the history
…t once
  • Loading branch information
justin025 committed Dec 3, 2024
1 parent d4e98cb commit 918ec0f
Show file tree
Hide file tree
Showing 13 changed files with 141 additions and 61 deletions.
3 changes: 2 additions & 1 deletion src/onthespot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from PyQt6.QtGui import QIcon
from .gui.mainui import MainWindow
from .gui.minidialog import MiniDialog
from .runtimedata import get_logger
from .runtimedata import get_logger, set_init_tray
from .otsconfig import config
from .parse_item import parsingworker

Expand Down Expand Up @@ -87,6 +87,7 @@ def main():
window = MainWindow(_dialog, start_url)

if config.get('close_to_tray'):
set_init_tray(True)
tray_app = TrayApp(window)

app.setDesktopFileName('org.onthespot.OnTheSpot')
Expand Down
23 changes: 11 additions & 12 deletions src/onthespot/accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,19 +84,18 @@ def run(self):



def get_account_token():
def get_account_token(item_service):
if item_service == 'youtube':
return
parsing_index = config.get('parsing_acc_sn')
service = account_pool[parsing_index]['service']

if service == 'youtube':
return

if config.get("rotate_acc_sn") is True:
if item_service == service and not config.get("rotate_acc_sn"):
return globals()[f"{item_service}_get_token"](parsing_index)
else:
for i in range(parsing_index + 1, parsing_index + len(account_pool) + 1):
index = i % len(account_pool)
if account_pool[index]['service'] == service:
config.set_('parsing_acc_sn', index)
config.update
return globals()[f"{service}_get_token"](index)
else:
return globals()[f"{service}_get_token"](parsing_index)
if account_pool[index]['service'] == item_service:
if config.get("rotate_acc_sn"):
config.set_('parsing_acc_sn', index)
config.update
return globals()[f"{item_service}_get_token"](index)
31 changes: 16 additions & 15 deletions src/onthespot/api/spotify.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,21 +64,22 @@ def run(self):
parent_category = 'track'
playlist_name = ''
playlist_by = ''
if data['context']['type'] == 'playlist':
match = re.search(r'spotify:playlist:(\w+)', data['context']['uri'])
if match:
playlist_id = match.group(1)
else:
continue
token = account_pool[parsing_index]['login']['session'].tokens().get("user-read-email")
playlist_name, playlist_by = spotify_get_playlist_data(token, playlist_id)
parent_category = 'playlist'
elif data['context']['type'] == 'collection':
playlist_name = 'Liked Songs'
playlist_by = 'me'
parent_category = 'playlist'
elif data['context']['type'] in ('album', 'artist'):
parent_category = 'album'
if data['context'] is not None:
if data['context'].get('type', '') == 'playlist':
match = re.search(r'spotify:playlist:(\w+)', data['context']['uri'])
if match:
playlist_id = match.group(1)
else:
continue
token = account_pool[parsing_index]['login']['session'].tokens().get("user-read-email")
playlist_name, playlist_by = spotify_get_playlist_data(token, playlist_id)
parent_category = 'playlist'
elif data['context'].get('type', '') == 'collection':
playlist_name = 'Liked Songs'
playlist_by = 'me'
parent_category = 'playlist'
elif data['context'].get('type', '') in ('album', 'artist'):
parent_category = 'album'
# Use item id to prevent duplicates
#local_id = format_local_id(item_id)
with pending_lock:
Expand Down
3 changes: 1 addition & 2 deletions src/onthespot/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,8 @@ def run(self):
local_id = next(iter(pending))
with pending_lock:
item = pending.pop(local_id)
token = get_account_token()
token = get_account_token(item['item_service'])
item_metadata = globals()[f"{item['item_service']}_get_{item['item_type']}_metadata"](token, item['item_id'])

with download_queue_lock:
download_queue[local_id] = {
'local_id': local_id,
Expand Down
26 changes: 19 additions & 7 deletions src/onthespot/downloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,9 @@ def run(self):
while self.is_running:
try:
try:
with download_queue_lock:
if download_queue:
if download_queue:
with download_queue_lock:

# Mark item as unavailable for other download workers
iterator = iter(download_queue)
while True:
Expand All @@ -61,9 +62,9 @@ def run(self):
download_queue[local_id]['available'] = False
item = download_queue[local_id]
break
else:
time.sleep(0.2)
continue
else:
time.sleep(0.2)
continue

item_service = item['item_service']
item_type = item['item_type']
Expand All @@ -88,7 +89,7 @@ def run(self):
if self.gui:
self.progress.emit(item, self.tr("Downloading"), 1)

token = get_account_token()
token = get_account_token(item_service)

try:
item_metadata = globals()[f"{item_service}_get_{item_type}_metadata"](token, item_id)
Expand Down Expand Up @@ -181,7 +182,18 @@ def run(self):
# item['gui']['progressbar'] and self.gui into a download_track function.
try:
if item_service == "spotify":
account = account_pool[config.get('parsing_acc_sn')]['login']['session']
# Check if selected account is the same item service and if not find one
parsing_index = config.get('parsing_acc_sn')
if account_pool[parsing_index]['service'] == item_service:
account = account_pool[parsing_index]['login']['session']
else:
for i in range(len(account_pool)):
index = (parsing_index + i + 1) % len(account_pool)
account = account_pool[index]
if account['service'] == item_service:
account = account_pool[index]['login']['session']
break

default_format = ".ogg"
temp_file_path += default_format
if item_type == "track":
Expand Down
11 changes: 6 additions & 5 deletions src/onthespot/gui/mainui.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from .dl_progressbtn import DownloadActionsButtons
from .settings import load_config, save_config
from ..otsconfig import config
from ..runtimedata import get_logger, parsing, pending, download_queue, account_pool, download_queue_lock, pending_lock
from ..runtimedata import get_logger, parsing, pending, download_queue, account_pool, download_queue_lock, pending_lock, get_init_tray
from .thumb_listitem import LabelWithThumb
from ..api.spotify import spotify_get_token, spotify_get_track_metadata, spotify_get_episode_metadata, spotify_new_session, MirrorSpotifyPlayback
from ..api.soundcloud import soundcloud_get_token, soundcloud_get_track_metadata, soundcloud_add_account
Expand All @@ -36,7 +36,7 @@ def run(self):
local_id = next(iter(pending))
with pending_lock:
item = pending.pop(local_id)
token = get_account_token()
token = get_account_token(item['item_service'])
item_metadata = globals()[f"{item['item_service']}_get_{item['item_type']}_metadata"](token, item['item_id'])
self.add_item_to_download_list.emit(item, item_metadata)
continue
Expand All @@ -57,7 +57,7 @@ def contribute(self):
open_item(url)

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

Expand Down Expand Up @@ -373,8 +373,8 @@ def add_item_to_download_list(self, item, item_metadata):
playlist_by = ''
if item['parent_category'] == 'playlist':
item_category = f'Playlist: {item["playlist_name"]}'
playlist_name = item['playlist_name']
playlist_by = item['playlist_by']
playlist_name = item.get('playlist_name', '')
playlist_by = item.get('playlist_by', '')
elif item['parent_category'] in ('album', 'show', 'audiobook'):
item_category = f'{item["parent_category"].title()}: {item_metadata["album_name"]}'
else:
Expand Down Expand Up @@ -485,6 +485,7 @@ def remove_completed_from_download_list(self):
if local_id in download_queue:
if download_queue[local_id]['item_status'] in (
"Cancelled",
"Deleted",
"Downloaded",
"Already Exists"
):
Expand Down
5 changes: 4 additions & 1 deletion src/onthespot/gui/qtui/main.ui
Original file line number Diff line number Diff line change
Expand Up @@ -656,7 +656,7 @@
<property name="geometry">
<rect>
<x>0</x>
<y>-1483</y>
<y>0</y>
<width>660</width>
<height>3154</height>
</rect>
Expand Down Expand Up @@ -884,6 +884,9 @@
</item>
<item>
<widget class="QComboBox" name="inp_language">
<property name="focusPolicy">
<enum>Qt::WheelFocus</enum>
</property>
<property name="frame">
<bool>true</bool>
</property>
Expand Down
55 changes: 55 additions & 0 deletions src/onthespot/gui/settings.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
import os
from PyQt6.QtGui import QIcon
from PyQt6.QtWidgets import QSpinBox, QComboBox, QWidget
from ..otsconfig import config


class NonScrollableSpinBox(QSpinBox):
def wheelEvent(self, event):
event.ignore()


class NonScrollableComboBox(QComboBox):
def wheelEvent(self, event):
event.ignore()


def load_config(self):
# Hide Popups
self.group_search_items.hide()
Expand Down Expand Up @@ -136,6 +147,50 @@ def load_config(self):
self.inp_embed_valence.setChecked(config.get('embed_valence'))
self.inp_mirror_spotify_playback.setChecked(config.get('mirror_spotify_playback'))

# Disable scrolling to change values of QSpinBoxes and QComboBoxes
do_not_scroll = [
"inp_login_service",
"inp_language",
"inp_max_search_results",
"inp_search_thumb_height",
"inp_file_hertz",
"inp_download_delay",
"inp_chunk_size",
"inp_maximum_download_workers"
]

for name in do_not_scroll:
widget = self.findChild(QWidget, name)
if isinstance(widget, QSpinBox):
# Create new NonScrollableSpinBox
new_widget = NonScrollableSpinBox()
new_widget.setRange(widget.minimum(), widget.maximum())
new_widget.setValue(widget.value())
new_widget.setGeometry(widget.geometry())
new_widget.setMinimumSize(widget.minimumSize())
new_widget.setMaximumSize(widget.maximumSize())
elif isinstance(widget, QComboBox):
# Create new NonScrollableComboBox
new_widget = NonScrollableComboBox()
new_widget.addItems([widget.itemText(i) for i in range(widget.count())])
new_widget.setCurrentIndex(widget.currentIndex())
new_widget.setGeometry(widget.geometry())
new_widget.setMinimumSize(widget.minimumSize())
new_widget.setMaximumSize(widget.maximumSize())
# Copy icons
for i in range(widget.count()):
icon = widget.itemIcon(i)
if not icon.isNull():
new_widget.setItemIcon(i, icon)

# Replace the widget in the layout
widget.parent().layout().replaceWidget(widget, new_widget)
# Delete the original widget
widget.deleteLater()

# 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
18 changes: 8 additions & 10 deletions src/onthespot/parse_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,34 +17,32 @@
#QOBUZ_INTERPRETER_URL_REGEX = re.compile(r"https?://www\.qobuz\.com/\w\w-\w\w/interpreter/[-\w]+/([-\w]+)")

def parse_url(url):
account_service = account_pool[config.get('parsing_acc_sn')]['service']

if account_service == 'deezer' and re.match(DEEZER_URL_REGEX, url):
if re.match(DEEZER_URL_REGEX, url):
match = re.search(DEEZER_URL_REGEX, url)
item_id = match.group("id")
item_type = match.group("type")
item_service = 'deezer'

elif account_service == 'soundcloud' and re.match(SOUNDCLOUD_URL_REGEX, url):
token = get_account_token()
elif re.match(SOUNDCLOUD_URL_REGEX, url):
token = get_account_token('soundcloud')
item_type, item_id = soundcloud_parse_url(url, token)
item_service = "soundcloud"

elif account_service == 'spotify' and re.match(SPOTIFY_URL_REGEX, url):
elif re.match(SPOTIFY_URL_REGEX, url):
match = re.search(SPOTIFY_URL_REGEX, url)
item_id = match.group("id")
item_type = match.group("type")
item_service = "spotify"
elif account_service == 'spotify' and url == 'https://open.spotify.com/collection/tracks':
elif url == 'https://open.spotify.com/collection/tracks':
item_id = None
item_type = 'liked_songs'
item_service = "spotify"
elif account_service == 'spotify' and url == 'https://open.spotify.com/collection/your-episodes':
elif url == 'https://open.spotify.com/collection/your-episodes':
item_id = None
item_type = 'your_episodes'
item_service = "spotify"

elif account_service == 'youtube' and re.match(YOUTUBE_URL_REGEX, url):
elif re.match(YOUTUBE_URL_REGEX, url):
match = re.search(YOUTUBE_URL_REGEX, url)
if match:
item_service = 'youtube'
Expand Down Expand Up @@ -80,7 +78,7 @@ def parsingworker():
current_service = item['item_service']
current_type = item['item_type']
current_id = item['item_id']
token = get_account_token()
token = get_account_token(current_service)

if current_service == "spotify":
if current_type == "track":
Expand Down
12 changes: 12 additions & 0 deletions src/onthespot/runtimedata.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,18 @@
pending_lock = threading.Lock()
download_queue_lock = threading.Lock()

init_tray = False


def set_init_tray(value):
global init_tray
init_tray = value


def get_init_tray():
return init_tray


loglevel = int(os.environ.get("LOG_LEVEL", 20))


Expand Down
2 changes: 1 addition & 1 deletion src/onthespot/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,6 @@ def get_search_results(search_term, content_types=None):

logger.info(f"Search clicked with value term {search_term}")
if search_term != "":
token = get_account_token()
account_type = config.get('accounts')[config.get('parsing_acc_sn')]['service']
token = get_account_token(account_type)
return globals()[f"{account_type}_get_search_results"](token, search_term, content_types)
10 changes: 5 additions & 5 deletions src/onthespot/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,13 +535,13 @@ def add_to_m3u_file(item, item_metadata):
album_type=item_metadata.get('album_type', 'single').title(),
name=item_metadata.get('title', ''),
year=item_metadata.get('release_year', ''),
disc_number=item_metadata.get('disc_number', ''),
track_number=item_metadata.get('track_number', ''),
disc_number=item_metadata.get('disc_number', 1),
track_number=item_metadata.get('track_number', 1),
genre=item_metadata.get('genre', ''),
label=item_metadata.get('label', ''),
explicit=str(config.get('explicit_label')) if item_metadata.get('explicit') else '',
trackcount=item_metadata.get('total_tracks', ''),
disccount=item_metadata.get('total_discs', ''),
explicit=str(config.get('explicit_label')) if item_metadata.get('explicit', '') else '',
trackcount=item_metadata.get('total_tracks', 1),
disccount=item_metadata.get('total_discs', 1),
playlist_name=item.get('playlist_name', ''),
playlist_owner=item.get('playlist_by', ''),
playlist_number=item.get('playlist_number', ''),
Expand Down
3 changes: 1 addition & 2 deletions src/onthespot/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,8 @@ def run(self):
local_id = next(iter(pending))
with pending_lock:
item = pending.pop(local_id)
token = get_account_token()
token = get_account_token(item['item_service'])
item_metadata = globals()[f"{item['item_service']}_get_{item['item_type']}_metadata"](token, item['item_id'])

with download_queue_lock:
download_queue[local_id] = {
'local_id': local_id,
Expand Down

0 comments on commit 918ec0f

Please sign in to comment.