podcast_list_view_mode -> ui.gtk.podcast_list.view_mode
[gpodder.git] / src / gpodder / config.py
blobd4617a78968e79aeceb509566a0f2c0f0060d6d7
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 'podcast_list_hide_boring': 'ui.gtk.podcast_list.hide_empty',
232 'episode_list_columns': 'ui.gtk.episode_list.columns',
235 logger = logging.getLogger(__name__)
238 def config_value_to_string(config_value):
239 config_type = type(config_value)
241 if config_type == list:
242 return ','.join(map(config_value_to_string, config_value))
243 elif config_type in (str, str):
244 return config_value
245 else:
246 return str(config_value)
249 def string_to_config_value(new_value, old_value):
250 config_type = type(old_value)
252 if config_type == list:
253 return [_f for _f in [x.strip() for x in new_value.split(',')] if _f]
254 elif config_type == bool:
255 return (new_value.strip().lower() in ('1', 'true'))
256 else:
257 return config_type(new_value)
260 class Config(object):
261 # Number of seconds after which settings are auto-saved
262 WRITE_TO_DISK_TIMEOUT = 60
264 def __init__(self, filename='gpodder.json'):
265 self.__json_config = jsonconfig.JsonConfig(default=defaults,
266 on_key_changed=self._on_key_changed)
267 self.__save_thread = None
268 self.__filename = filename
269 self.__observers = []
271 self.load()
272 self.migrate_defaults()
274 # If there is no configuration file, we create one here (bug 1511)
275 if not os.path.exists(self.__filename):
276 self.save()
278 atexit.register(self.__atexit)
280 def register_defaults(self, defaults):
282 Register default configuration options (e.g. for extensions)
284 This function takes a dictionary that will be merged into the
285 current configuration if the keys don't yet exist. This can
286 be used to add a default configuration for extension modules.
288 self.__json_config._merge_keys(defaults)
290 def add_observer(self, callback):
292 Add a callback function as observer. This callback
293 will be called when a setting changes. It should
294 have this signature:
296 observer(name, old_value, new_value)
298 The "name" is the setting name, the "old_value" is
299 the value that has been overwritten with "new_value".
301 if callback not in self.__observers:
302 self.__observers.append(callback)
303 else:
304 logger.warning('Observer already added: %s', repr(callback))
306 def remove_observer(self, callback):
308 Remove an observer previously added to this object.
310 if callback in self.__observers:
311 self.__observers.remove(callback)
312 else:
313 logger.warning('Observer not added: %s', repr(callback))
315 def all_keys(self):
316 return self.__json_config._keys_iter()
318 def schedule_save(self):
319 if self.__save_thread is None:
320 self.__save_thread = util.run_in_background(self.save_thread_proc, True)
322 def save_thread_proc(self):
323 time.sleep(self.WRITE_TO_DISK_TIMEOUT)
324 if self.__save_thread is not None:
325 self.save()
327 def __atexit(self):
328 if self.__save_thread is not None:
329 self.save()
331 def save(self, filename=None):
332 if filename is None:
333 filename = self.__filename
335 logger.info('Flushing settings to disk')
337 try:
338 # revoke unix group/world permissions (this has no effect under windows)
339 umask = os.umask(0o077)
340 with open(filename + '.tmp', 'wt') as fp:
341 fp.write(repr(self.__json_config))
342 util.atomic_rename(filename + '.tmp', filename)
343 except:
344 logger.error('Cannot write settings to %s', filename)
345 util.delete_file(filename + '.tmp')
346 raise
347 finally:
348 os.umask(umask)
350 self.__save_thread = None
352 def load(self, filename=None):
353 if filename is not None:
354 self.__filename = filename
356 if os.path.exists(self.__filename):
357 try:
358 with open(self.__filename, 'rt') as f:
359 data = f.read()
360 new_keys_added = self.__json_config._restore(data)
361 except:
362 logger.warning('Cannot parse config file: %s',
363 self.__filename, exc_info=True)
364 new_keys_added = False
366 if new_keys_added:
367 logger.info('New default keys added - saving config.')
368 self.save()
370 def toggle_flag(self, name):
371 setattr(self, name, not getattr(self, name))
373 def update_field(self, name, new_value):
374 """Update a config field, converting strings to the right types"""
375 old_value = self._lookup(name)
376 new_value = string_to_config_value(new_value, old_value)
377 setattr(self, name, new_value)
378 return True
380 def _on_key_changed(self, name, old_value, value):
381 if 'ui.gtk.state' not in name:
382 # Only log non-UI state changes
383 logger.debug('%s: %s -> %s', name, old_value, value)
384 for observer in self.__observers:
385 try:
386 observer(name, old_value, value)
387 except Exception as exception:
388 logger.error('Error while calling observer %r: %s',
389 observer, exception, exc_info=True)
391 self.schedule_save()
393 def __getattr__(self, name):
394 if name in gPodderSettings_LegacySupport:
395 name = gPodderSettings_LegacySupport[name]
397 return getattr(self.__json_config, name)
399 def __setattr__(self, name, value):
400 if name.startswith('_'):
401 object.__setattr__(self, name, value)
402 return
404 if name in gPodderSettings_LegacySupport:
405 name = gPodderSettings_LegacySupport[name]
407 setattr(self.__json_config, name, value)
409 def migrate_defaults(self):
410 """ change default values in config """
411 if self.device_sync.max_filename_length == 999:
412 logger.debug("setting config.device_sync.max_filename_length=120"
413 " (999 is bad for NTFS and ext{2-4})")
414 self.device_sync.max_filename_length = 120
416 def clamp_range(self, name, min, max):
417 value = getattr(self, name)
418 if value < min:
419 setattr(self, name, min)
420 return True
421 if value > max:
422 setattr(self, name, max)
423 return True
424 return False