1 # -*- coding: utf-8 -*-
3 # gPodder - A media aggregator and podcast client
4 # Copyright (c) 2005-2018 The gPodder Team
6 # gPodder is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
11 # gPodder is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
22 # config.py -- gPodder Configuration Manager
23 # Thomas Perl <thp@perli.net> 2007-11-02
33 from gpodder
import jsonconfig
, util
38 # External applications used for playback
44 # gpodder.net settings
47 'server': 'gpodder.net',
51 'uid': util
.get_hostname(),
53 'caption': _('gPodder on %s') % util
.get_hostname(),
57 # Various limits (downloading, updating, etc..)
61 'kbps': 500.0, # maximum kB/s per download
68 'episodes': 200, # max episodes per feed
71 # Behavior of downloads
73 'chronological_order': True, # download older episodes first
76 # Automatic feed updates, download removal and retry on download timeout
80 'frequency': 20, # minutes
90 'retries': 3, # number of retries when downloads time out
93 'check_connection': True,
95 # Software updates from gpodder.org
97 'check_on_startup': True, # check for updates on start
98 'last_check': 0, # unix timestamp of last update check
99 'interval': 5, # interval (in days) to check for updates
103 # Settings for the Command-Line Interface
108 # Settings for the Gtk UI
114 'x': -1, 'y': -1, 'maximized': False,
116 'paned_position': 200,
117 'episode_list_size': 200,
119 'episode_column_sort_id': 0,
120 'episode_column_sort_order': False,
121 'episode_column_order': [],
126 'x': -1, 'y': -1, 'maximized': False,
131 'x': -1, 'y': -1, 'maximized': False,
136 'x': -1, 'y': -1, 'maximized': False,
138 'episode_selector': {
141 'x': -1, 'y': -1, 'maximized': False,
146 'x': -1, 'y': -1, 'maximized': False,
148 'export_to_local_folder': {
151 'x': -1, 'y': -1, 'maximized': False,
156 'new_episodes': 'show', # ignore, show, queue, download
157 'live_search_delay': 200,
158 'search_always_visible': False,
159 'find_as_you_type': True,
162 'all_episodes': True,
169 'descriptions': True,
171 'columns': int('110', 2), # bitfield of visible columns
172 'always_show_new': True,
173 'ctrl_click_to_sort': False,
177 'remove_finished': True,
180 'html_shownotes': True, # enable webkit renderer
184 # Synchronization with portable devices (MP3 players, etc..)
186 'device_type': 'none', # Possible values: 'none', 'filesystem', 'ipod'
187 'device_folder': '/media',
189 'one_folder_per_podcast': True,
190 'skip_played_episodes': True,
191 'delete_played_episodes': False,
192 'delete_deleted_episodes': False,
194 'max_filename_length': 120,
196 'custom_sync_name': '{episode.sortdate}_{episode.title}',
197 'custom_sync_name_enabled': False,
200 'mark_episodes_played': False,
201 'delete_episodes': False,
206 'two_way_sync': False,
207 'use_absolute_path': True,
208 'folder': 'Playlists',
214 'preferred_fmt_id': 18, # default fmt_id (see fallbacks in youtube.py)
215 'preferred_fmt_ids': [], # for advanced uses (custom fallback sequence)
216 'preferred_hls_fmt_id': 93, # default fmt_id (see fallbacks in youtube.py)
217 'preferred_hls_fmt_ids': [], # for advanced uses (custom fallback sequence)
221 'fileformat': '720p', # preferred file format (see vimeo.py)
229 # The sooner this goes away, the better
230 gPodderSettings_LegacySupport
= {
231 'auto_remove_unfinished_episodes': 'auto.cleanup.unfinished',
232 'auto_remove_unplayed_episodes': 'auto.cleanup.unplayed',
233 'max_episodes_per_feed': 'limit.episodes',
234 'show_toolbar': 'ui.gtk.toolbar',
235 'episode_list_descriptions': 'ui.gtk.episode_list.descriptions',
236 'podcast_list_view_all': 'ui.gtk.podcast_list.all_episodes',
237 'podcast_list_sections': 'ui.gtk.podcast_list.sections',
238 'episode_list_view_mode': 'ui.gtk.episode_list.view_mode',
239 'podcast_list_view_mode': 'ui.gtk.podcast_list.view_mode',
240 'podcast_list_hide_boring': 'ui.gtk.podcast_list.hide_empty',
241 'episode_list_columns': 'ui.gtk.episode_list.columns',
242 'auto_cleanup_downloads': 'ui.gtk.download_list.remove_finished',
243 'auto_update_feeds': 'auto.update.enabled',
244 'auto_update_frequency': 'auto.update.frequency',
245 'auto_download': 'ui.gtk.new_episodes',
248 logger
= logging
.getLogger(__name__
)
251 def config_value_to_string(config_value
):
252 config_type
= type(config_value
)
254 if config_type
== list:
255 return ','.join(map(config_value_to_string
, config_value
))
256 elif config_type
in (str, str):
259 return str(config_value
)
262 def string_to_config_value(new_value
, old_value
):
263 config_type
= type(old_value
)
265 if config_type
== list:
266 return [_f
for _f
in [x
.strip() for x
in new_value
.split(',')] if _f
]
267 elif config_type
== bool:
268 return (new_value
.strip().lower() in ('1', 'true'))
270 return config_type(new_value
)
273 class Config(object):
274 # Number of seconds after which settings are auto-saved
275 WRITE_TO_DISK_TIMEOUT
= 60
277 def __init__(self
, filename
='gpodder.json'):
278 self
.__json
_config
= jsonconfig
.JsonConfig(default
=defaults
,
279 on_key_changed
=self
._on
_key
_changed
)
280 self
.__save
_thread
= None
281 self
.__filename
= filename
282 self
.__observers
= []
285 self
.migrate_defaults()
287 # If there is no configuration file, we create one here (bug 1511)
288 if not os
.path
.exists(self
.__filename
):
291 atexit
.register(self
.__atexit
)
293 def register_defaults(self
, defaults
):
295 Register default configuration options (e.g. for extensions)
297 This function takes a dictionary that will be merged into the
298 current configuration if the keys don't yet exist. This can
299 be used to add a default configuration for extension modules.
301 self
.__json
_config
._merge
_keys
(defaults
)
303 def add_observer(self
, callback
):
305 Add a callback function as observer. This callback
306 will be called when a setting changes. It should
309 observer(name, old_value, new_value)
311 The "name" is the setting name, the "old_value" is
312 the value that has been overwritten with "new_value".
314 if callback
not in self
.__observers
:
315 self
.__observers
.append(callback
)
317 logger
.warning('Observer already added: %s', repr(callback
))
319 def remove_observer(self
, callback
):
321 Remove an observer previously added to this object.
323 if callback
in self
.__observers
:
324 self
.__observers
.remove(callback
)
326 logger
.warning('Observer not added: %s', repr(callback
))
329 return self
.__json
_config
._keys
_iter
()
331 def schedule_save(self
):
332 if self
.__save
_thread
is None:
333 self
.__save
_thread
= util
.run_in_background(self
.save_thread_proc
, True)
335 def save_thread_proc(self
):
336 time
.sleep(self
.WRITE_TO_DISK_TIMEOUT
)
337 if self
.__save
_thread
is not None:
341 if self
.__save
_thread
is not None:
344 def save(self
, filename
=None):
346 filename
= self
.__filename
348 logger
.info('Flushing settings to disk')
351 # revoke unix group/world permissions (this has no effect under windows)
352 umask
= os
.umask(0o077)
353 with
open(filename
+ '.tmp', 'wt') as fp
:
354 fp
.write(repr(self
.__json
_config
))
355 util
.atomic_rename(filename
+ '.tmp', filename
)
357 logger
.error('Cannot write settings to %s', filename
)
358 util
.delete_file(filename
+ '.tmp')
363 self
.__save
_thread
= None
365 def load(self
, filename
=None):
366 if filename
is not None:
367 self
.__filename
= filename
369 if os
.path
.exists(self
.__filename
):
371 with
open(self
.__filename
, 'rt') as f
:
373 new_keys_added
= self
.__json
_config
._restore
(data
)
375 logger
.warning('Cannot parse config file: %s',
376 self
.__filename
, exc_info
=True)
377 new_keys_added
= False
380 logger
.info('New default keys added - saving config.')
383 def toggle_flag(self
, name
):
384 setattr(self
, name
, not getattr(self
, name
))
386 def update_field(self
, name
, new_value
):
387 """Update a config field, converting strings to the right types"""
388 old_value
= self
._lookup
(name
)
389 new_value
= string_to_config_value(new_value
, old_value
)
390 setattr(self
, name
, new_value
)
393 def _on_key_changed(self
, name
, old_value
, value
):
394 if 'ui.gtk.state' not in name
:
395 # Only log non-UI state changes
396 logger
.debug('%s: %s -> %s', name
, old_value
, value
)
397 for observer
in self
.__observers
:
399 observer(name
, old_value
, value
)
400 except Exception as exception
:
401 logger
.error('Error while calling observer %r: %s',
402 observer
, exception
, exc_info
=True)
406 def __getattr__(self
, name
):
407 if name
in gPodderSettings_LegacySupport
:
408 name
= gPodderSettings_LegacySupport
[name
]
410 return getattr(self
.__json
_config
, name
)
412 def __setattr__(self
, name
, value
):
413 if name
.startswith('_'):
414 object.__setattr
__(self
, name
, value
)
417 if name
in gPodderSettings_LegacySupport
:
418 name
= gPodderSettings_LegacySupport
[name
]
420 setattr(self
.__json
_config
, name
, value
)
422 def migrate_defaults(self
):
423 """ change default values in config """
424 if self
.device_sync
.max_filename_length
== 999:
425 logger
.debug("setting config.device_sync.max_filename_length=120"
426 " (999 is bad for NTFS and ext{2-4})")
427 self
.device_sync
.max_filename_length
= 120
429 def clamp_range(self
, name
, min, max):
430 value
= getattr(self
, name
)
432 setattr(self
, name
, min)
435 setattr(self
, name
, max)