Skip to content

Commit

Permalink
- adding resource_opener config parameter
Browse files Browse the repository at this point in the history
- fixing issue #236
  • Loading branch information
s-n-g committed Apr 15, 2024
1 parent a87d409 commit 998bc55
Show file tree
Hide file tree
Showing 11 changed files with 73 additions and 29 deletions.
7 changes: 4 additions & 3 deletions .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,19 @@ A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Press '....'
3. Select '....'
3. Select '....'
4. See error

**Expected behavior**
A clear and concise description of what you expected to happen.

**System (please complete the following information):**
- OS: [e.g. Dabian, macOS, Windows]
- **Python** version:
- `pipx` version (if applicable):
- **Python** version:
- `pipx` version (if applicable):
- `pipx` installation method: System dependent / Fully isolated
- **PyRadio** Version:
- Player used: [e.g mpv, mplayer, vlc]

**Additional context**
Add any other context about the problem here.
17 changes: 16 additions & 1 deletion pyradio/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
import io
import csv
from sys import version as sys_version
from os import rename, remove
from os import rename, remove, access, X_OK
from os.path import exists, dirname, join
from shutil import which
from copy import deepcopy
from rich import print
import logging
Expand Down Expand Up @@ -478,3 +479,17 @@ def update_stations_csv(self, print_messages=True):
# for n in self._stations:
# print(n)

def validate_resource_opener_path(a_file):
# Check if the file exists
if not exists(a_file):
# If the file doesn't exist, try to find it using shutil.which
full_path = which(a_file)
if full_path is None:
return None
else:
a_file = full_path
# Check if the file is executable
if not access(a_file, X_OK):
return None
# Return the validated path
return a_file
11 changes: 11 additions & 0 deletions pyradio/config
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,17 @@ enable_mouse = False
# Default value: default
recording_dir = default

# Resource Opener
# This is a Linux (et al) only parameter. It has no effect on Windows or MacOS.
# A Resource Opener is a program used to open files passed to it as arguments.
# PyRadio will use it to open either directories or HTML files.
# Default value is "auto", in which case, PyRadio will try to use xdg-open,
# gio, mimeopen, mimeo or handlr, in that order of detection. If none if found,
# the requested file will simply not open.
# To set a custom Opener, insert the absolute path to its executable, followed
# by any parameter required, for example: "/usr/bin/gio open".
resource_opener = auto

# Desktop notifications
# If this option is enabled, a Desktop notification will be displayed using the
# notification daemon / service. If enabled but no notification is displayed,
Expand Down
23 changes: 17 additions & 6 deletions pyradio/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,14 @@
from os import getuid
from pyradio import version, stations_updated

from .common import validate_resource_opener_path
from .browser import PyRadioStationsBrowser, probeBrowsers
from .install import get_github_long_description
from .common import is_rasberrypi
from .player import pywhich
from .server import IPsWithNumbers
from .xdg import XdgDirs, XdgMigrate, CheckDir
from .install import run_tool
from .install import get_a_linux_resource_opener
HAS_REQUESTS = True

try:
Expand Down Expand Up @@ -1285,6 +1286,7 @@ class PyRadioConfig(PyRadioStations):
opts['enable_notifications'] = ['Enable notifications: ', '-1']
opts['use_station_icon'] = [' Use station icon: ', True]
opts['recording_dir'] = ['Recordings dir: ', '']
opts['resource_opener'] = ['Resource Opener: ', 'auto']
opts['conn_title'] = ['Connection Options: ', '']
opts['connection_timeout'] = ['Connection timeout: ', '10']
opts['force_http'] = ['Force http connections: ', False]
Expand Down Expand Up @@ -1368,7 +1370,7 @@ class PyRadioConfig(PyRadioStations):

_fixed_recording_dir = None

_linux_run_tool = None
_linux_resource_opener = None

def __init__(self, user_config_dir=None, headless=False):
# keep old recording / new recording dir
Expand Down Expand Up @@ -1426,8 +1428,8 @@ def __init__(self, user_config_dir=None, headless=False):
player_instance = None

@property
def linux_run_tool(self):
return self._linux_run_tool
def linux_resource_opener(self):
return self._linux_resource_opener

@property
def xdg_compliant(self):
Expand Down Expand Up @@ -1832,7 +1834,7 @@ def open_a_dir(self, a_dir):
elif system().lower() == 'darwin':
Popen([which('open'), a_dir])
else:
xdg_open_path = self._linux_run_tool if self._linux_run_tool else run_tool()
xdg_open_path = self._linux_resource_opener if self._linux_resource_opener else get_a_linux_resource_opener()
if xdg_open_path:
try:
Popen(
Expand All @@ -1850,7 +1852,7 @@ def open_config_dir(self, recording=0):
elif system().lower() == 'darwin':
Popen([which('open'), a_dir])
else:
xdg_open_path = self._linux_run_tool if self._linux_run_tool else run_tool()
xdg_open_path = self._linux_resource_opener if self._linux_resource_opener else get_a_linux_resource_opener()
if xdg_open_path:
try:
Popen(
Expand Down Expand Up @@ -2052,6 +2054,7 @@ def _read_config(self, distro_config=False):
self._make_sure_dirs_exist()
self._first_read = False
return
self._linux_resource_opener = None
lines = []
try:
with open(file_to_read, 'r', encoding='utf-8') as cfgfile:
Expand Down Expand Up @@ -2224,6 +2227,14 @@ def _read_config(self, distro_config=False):
not platform.startswith('win') and \
sp[1].lower() == 'true':
self.xdg_compliant = True
elif sp[0] == 'resource_opener' and \
not platform.startswith('win'):
if self.opts['resource_opener'][1] != 'auto':
tmp = self.opts['resource_opener'][1].split(' ')
prog = validate_resource_opener_path(tmp[0])
if prog is not None:
tmp[0] = prog
self._linux_resource_opener = ' '.join(tmp)

# logger.error('\n\nself.params{}\n\n'.format(self.params))
''' read distro from package config file '''
Expand Down
6 changes: 6 additions & 0 deletions pyradio/config_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ def set_global_functions(global_functions):
del ret[ord('t')]
return ret


class PyRadioConfigWindow(object):
n_u = Window_Stack_Constants

Expand Down Expand Up @@ -68,6 +69,10 @@ class PyRadioConfigWindow(object):
_help_text.append(['If this options is enabled, a Desktop Notification will be displayed using the notification daemon / service.', '|', 'If enabled but no notification is displayed, please refer to', 'https://github.com/coderholic/pyradio/desktop-notification.md', '|', 'Valid values are:', ' -1: disabled ', ' 0: enabled (no repetition) ', ' x: repeat every x seconds ', '|', 'Default value: -1'])
_help_text.append(['Notice: Not applicable on Windows!', '|', 'Online Radio Directory Services (like RadioBrowser) will usually provide an icon for the stations they advertise.', '|', 'PyRadio can use this icon (provided that one exists and is of JPG or PNG format) while displaying Desktop Notifications.', '|', 'Setting this option to True, will enable the behavior above.', '|', 'If this option is False, the default icon will be used.', '|', 'Default value: True'])
_help_text.append([ 'This is the folder where recorded files will be saved', '|', 'Tip: When you open the window "h" will display HTML help about this parameter (not in Line Editor).', '|', 'Default value: "pyradio-recordings" in home dir' ])
_help_text.append(['This is a Linux (et al) only parameter. It has no effect on Windows or MacOS.', '|',
'A Resource Opener is a program used to open files passed to it as arguments. PyRadio will use it to open either directories or HTML files.', '|',
'Default value is "auto", in which case, PyRadio will try to use xdg-open, gio, mimeopen, mimeo or handlr, in that order of detection. If none if found, the requested file will simply not open.'
])
_help_text.append(None)
_help_text.append(['PyRadio will wait for this number of seconds to get a station/server message indicating that playback has actually started.', '|',
'If this does not happen within this number of seconds after the connection is initiated, PyRadio will consider the station unreachable, and display the "Failed to connect to: station" message.', '|', 'Press "h"/Left or "l"/Right to change value.',
Expand Down Expand Up @@ -519,6 +524,7 @@ def _load_default_values(self):
self._config_options['enable_notifications'][1] = '-1'
self._config_options['use_station_icon'][1] = 'True'
self._config_options['recording_dir'][1] = path.join(path.expanduser('~'), 'pyradio-recordings')
opts['resource_opener'] = ['Resource Opener: ', 'auto']
self._config_options['connection_timeout'][1] = '10'
self._config_options['theme_title'][1] = ''
''' Transparency '''
Expand Down
18 changes: 9 additions & 9 deletions pyradio/html_help.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from sys import platform
from os import path
from shutil import which
from .install import run_tool
from .install import get_a_linux_resource_opener

logger = logging.getLogger(__name__)

Expand All @@ -30,14 +30,14 @@ def __init__(self):
self._path = a_path
break

def open_file(self, linux_run_tool=None, browser=False):
def open_file(self, linux_resource_opener=None, browser=False):
a_file = self._files[1] if browser else self._files[0]
self._open_file(a_file, linux_run_tool=linux_run_tool)
self._open_file(a_file, linux_resource_opener=linux_resource_opener)

def open_filename(self,a_file, linux_run_tool=None):
self._open_file(a_file, linux_run_tool=linux_run_tool)
def open_filename(self,a_file, linux_resource_opener=None):
self._open_file(a_file, linux_resource_opener=linux_resource_opener)

def _open_file(self, a_file, linux_run_tool=None):
def _open_file(self, a_file, linux_resource_opener=None):
if logger.isEnabledFor(logging.DEBUG):
logger.debug('HtmlHelp: opening "{}"'.format(path.join(self._path, a_file)))
this_platform = platform.lower()
Expand All @@ -48,10 +48,10 @@ def _open_file(self, a_file, linux_run_tool=None):
if this_platform.startswith('darwin'):
cmd = [which('open'), path.join(self._path, a_file)]
else:
if linux_run_tool is None:
tool = run_tool()
if linux_resource_opener is None:
tool = get_a_linux_resource_opener()
else:
tool = linux_run_tool
tool = linux_resource_opener
if tool is None:
if logger.isEnabledFor(logging.INFO):
logger.info('HtmlHelp: Cannot find a run tool for Linux!')
Expand Down
4 changes: 2 additions & 2 deletions pyradio/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,7 @@ def WindowExists(title):
else:
return True

def run_tool():
def get_a_linux_resource_opener():
''' return an resource open tool from a list
the list comes from "Resource openers"
https://wiki.archlinux.org/title/default_applications
Expand Down Expand Up @@ -455,7 +455,7 @@ def open_cache_dir():
elif platform.system().lower() == 'darwin':
subprocess.Popen([which('open'), c.cache_dir])
else:
prog = run_tool()
prog = get_a_linux_resource_opener()
if prog:
try:
subprocess.Popen(
Expand Down
4 changes: 2 additions & 2 deletions pyradio/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from .log import Log
from .common import StationsChanges
from .schedule import PyRadioScheduleList
from .install import run_tool
from .install import get_a_linux_resource_opener
import locale
locale.setlocale(locale.LC_ALL, "")

Expand Down Expand Up @@ -1049,7 +1049,7 @@ def open_conf_dir(cnf, msg=None, a_dir=None):
elif platform.system().lower() == 'darwin':
subprocess.Popen([shutil.which('open'), op_dir])
else:
prog = cnf.linux_run_tool if cnf.linux_run_tool else run_tool()
prog = cnf.linux_resource_opener if cnf.linux_resource_opener else get_a_linux_resource_opener()
if prog:
try:
subprocess.Popen(
Expand Down
8 changes: 4 additions & 4 deletions pyradio/messages_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -1119,16 +1119,16 @@ def set_text(self, parent, *args):
When a new directory is specified, |PyRadio| will try to |move| the
existing directory to the new location.
If the new directory
If the new directory...
1. |does not exist|
___|PyRadio| will move the original directory to the new location
___and optionally rename it.
2. |already exists and it is empty|
2. |already exists and is empty|
___|PyRadio| will |delete| the new directory and |move| the original
___directory to the new location and optionally rename it.
3. |PyRadio| will |move| the original directory |inside| the new
3. |already exists and is not empty|
___|PyRadio| will |move| the original directory |inside| the new
___directory and optionally rename it.
'''
),

Expand Down
2 changes: 1 addition & 1 deletion pyradio/player.py
Original file line number Diff line number Diff line change
Expand Up @@ -678,7 +678,7 @@ def get_info_string(self, a_station, max_width, win_width):
# logger.debug('\n\n\n')

if 'Codec:' not in a_list[-1]:
a_list[n] = '|' + a_list[n]
a_list.append(' Codec:')

# if a_list[1].startswith('_'):
# a_list[1] = '|' + a_list[1]
Expand Down
2 changes: 1 addition & 1 deletion pyradio/radio.py
Original file line number Diff line number Diff line change
Expand Up @@ -6133,7 +6133,7 @@ def keypress(self, char):
self._update_status_bar_right(status_suffix='')
html = HtmlHelp()
html.open_file(
linux_run_tool=self._cnf.linux_run_tool,
linux_resource_opener=self._cnf.linux_resource_opener,
browser=self._cnf.browsing_station_service
)

Expand Down

0 comments on commit 998bc55

Please sign in to comment.