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 '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):
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'))
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
= []
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
):
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
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
)
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
)
313 logger
.warning('Observer not added: %s', repr(callback
))
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:
328 if self
.__save
_thread
is not None:
331 def save(self
, filename
=None):
333 filename
= self
.__filename
335 logger
.info('Flushing settings to disk')
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
)
344 logger
.error('Cannot write settings to %s', filename
)
345 util
.delete_file(filename
+ '.tmp')
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
):
358 with
open(self
.__filename
, 'rt') as f
:
360 new_keys_added
= self
.__json
_config
._restore
(data
)
362 logger
.warning('Cannot parse config file: %s',
363 self
.__filename
, exc_info
=True)
364 new_keys_added
= False
367 logger
.info('New default keys added - saving config.')
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
)
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
:
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)
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
)
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
)
419 setattr(self
, name
, min)
422 setattr(self
, name
, max)