auto_remove_played_episodes -> auto.cleanup.played
[gpodder.git] / src / gpodder / config.py
bloba49d2376b995645d3fcb8284209dca33b8b2e311
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
27 import atexit
28 import logging
29 import os
30 import time
32 import gpodder
33 from gpodder import jsonconfig, util
35 _ = gpodder.gettext
37 defaults = {
38 # External applications used for playback
39 'player': {
40 'audio': 'default',
41 'video': 'default',
44 # gpodder.net settings
45 'mygpo': {
46 'enabled': False,
47 'server': 'gpodder.net',
48 'username': '',
49 'password': '',
50 'device': {
51 'uid': util.get_hostname(),
52 'type': 'desktop',
53 'caption': _('gPodder on %s') % util.get_hostname(),
57 # Various limits (downloading, updating, etc..)
58 'limit': {
59 'bandwidth': {
60 'enabled': False,
61 'kbps': 500.0, # maximum kB/s per download
63 'downloads': {
64 'enabled': True,
65 'concurrent': 1,
66 'concurrent_max': 16,
68 'episodes': 200, # max episodes per feed
71 # Behavior of downloads
72 'downloads': {
73 'chronological_order': True, # download older episodes first
76 # Automatic feed updates, download removal and retry on download timeout
77 'auto': {
78 'update': {
79 'enabled': False,
80 'frequency': 20, # minutes
83 'cleanup': {
84 'days': 7,
85 'played': False,
86 'unplayed': False,
87 'unfinished': True,
90 'retries': 3, # number of retries when downloads time out
93 'check_connection': True,
95 # Software updates from gpodder.org
96 'software_update': {
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
102 'ui': {
103 # Settings for the Command-Line Interface
104 'cli': {
105 'colors': True,
108 # Settings for the Gtk UI
109 'gtk': {
110 'state': {
111 'main_window': {
112 'width': 700,
113 'height': 500,
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': [],
123 'preferences': {
124 'width': -1,
125 'height': -1,
126 'x': -1, 'y': -1, 'maximized': False,
128 'config_editor': {
129 'width': -1,
130 'height': -1,
131 'x': -1, 'y': -1, 'maximized': False,
133 'channel_editor': {
134 'width': -1,
135 'height': -1,
136 'x': -1, 'y': -1, 'maximized': False,
138 'episode_selector': {
139 'width': 600,
140 'height': 400,
141 'x': -1, 'y': -1, 'maximized': False,
143 'episode_window': {
144 'width': 500,
145 'height': 400,
146 'x': -1, 'y': -1, 'maximized': False,
148 'export_to_local_folder': {
149 'width': 500,
150 'height': 400,
151 'x': -1, 'y': -1, 'maximized': False,
155 'toolbar': 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,
161 'podcast_list': {
162 'all_episodes': True,
163 'sections': True,
164 'view_mode': 1,
165 'hide_empty': False,
168 'episode_list': {
169 'descriptions': True,
170 'view_mode': 1,
171 'columns': int('110', 2), # bitfield of visible columns
172 'always_show_new': True,
173 'ctrl_click_to_sort': False,
176 'download_list': {
177 'remove_finished': True,
180 'html_shownotes': True, # enable webkit renderer
184 # Synchronization with portable devices (MP3 players, etc..)
185 'device_sync': {
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,
199 'after_sync': {
200 'mark_episodes_played': False,
201 'delete_episodes': False,
202 'sync_disks': False,
204 'playlists': {
205 'create': True,
206 'two_way_sync': False,
207 'use_absolute_path': True,
208 'folder': 'Playlists',
213 'youtube': {
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)
220 'vimeo': {
221 'fileformat': '720p', # preferred file format (see vimeo.py)
224 'extensions': {
225 'enabled': [],
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):
257 return config_value
258 else:
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'))
269 else:
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 = []
284 self.load()
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):
289 self.save()
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
307 have this signature:
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)
316 else:
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)
325 else:
326 logger.warning('Observer not added: %s', repr(callback))
328 def all_keys(self):
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:
338 self.save()
340 def __atexit(self):
341 if self.__save_thread is not None:
342 self.save()
344 def save(self, filename=None):
345 if filename is None:
346 filename = self.__filename
348 logger.info('Flushing settings to disk')
350 try:
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)
356 except:
357 logger.error('Cannot write settings to %s', filename)
358 util.delete_file(filename + '.tmp')
359 raise
360 finally:
361 os.umask(umask)
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):
370 try:
371 with open(self.__filename, 'rt') as f:
372 data = f.read()
373 new_keys_added = self.__json_config._restore(data)
374 except:
375 logger.warning('Cannot parse config file: %s',
376 self.__filename, exc_info=True)
377 new_keys_added = False
379 if new_keys_added:
380 logger.info('New default keys added - saving config.')
381 self.save()
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)
391 return True
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:
398 try:
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)
404 self.schedule_save()
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)
415 return
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)
431 if value < min:
432 setattr(self, name, min)
433 return True
434 if value > max:
435 setattr(self, name, max)
436 return True
437 return False