Filters for Podcasts and Episodes on Maemo 5
[gpodder.git] / src / gpodder / config.py
blob50e345a88bbd01712d227b0762b423bdebd39f1d
1 # -*- coding: utf-8 -*-
3 # gPodder - A media aggregator and podcast client
4 # Copyright (c) 2005-2009 Thomas Perl and 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 gpodder
28 from gpodder import util
29 from gpodder.liblogger import log
31 import atexit
32 import os
33 import time
34 import threading
35 import ConfigParser
37 _ = gpodder.gettext
39 if gpodder.ui.fremantle:
40 default_download_dir = os.path.join(os.path.expanduser('~'), 'MyDocs/Podcasts')
41 elif gpodder.ui.diablo:
42 default_download_dir = '/media/mmc2/gpodder'
43 else:
44 default_download_dir = os.path.join(os.path.expanduser('~'), 'gpodder-downloads')
46 gPodderSettings = {
47 # General settings
48 'player': (str, 'default',
49 ("The default player for all media, if set to 'default' this will "
50 "attempt to use xdg-open on linux or the built-in media player on maemo.")),
51 'videoplayer': (str, 'default',
52 ("The default player for video")),
53 'opml_url': (str, 'http://gpodder.org/directory.opml',
54 ("A URL pointing to an OPML file which can be used to bulk-add podcasts.")),
55 'toplist_url': (str, 'http://gpodder.org/toplist.opml',
56 ("A URL pointing to a gPodder web services top podcasts list")),
57 'custom_sync_name': ( str, '{episode.basename}',
58 ("The name used when copying a file to a FS-based device. Available "
59 "options are: episode.basename, episode.title, episode.published")),
60 'custom_sync_name_enabled': ( bool, True,
61 ("Enables renaming files when transfered to an FS-based device with "
62 "respect to the 'custom_sync_name'.")),
63 'max_downloads': ( int, 1,
64 ("The maximum number of simultaneous downloads allowed at a single "
65 "time. Requires 'max_downloads_enabled'.")),
66 'max_downloads_enabled': ( bool, True,
67 ("The 'max_downloads' setting will only work if this is set to 'True'.")),
68 'limit_rate': ( bool, False,
69 ("The 'limit_rate_value' setting will only work if this is set to 'True'.")),
70 'limit_rate_value': ( float, 500.0,
71 ("Set a global speed limit (in KB/s) when downloading files. "
72 "Requires 'limit_rate'.")),
73 'episode_old_age': ( int, 7,
74 ("The number of days before an episode is considered old. "
75 "Must be used in conjunction with 'auto_remove_old_episodes'.")),
77 # Boolean config flags
78 'update_on_startup': ( bool, False,
79 ("Update the feed cache on startup.")),
80 'only_sync_not_played': ( bool, False,
81 ("Only sync episodes to a device that have not been marked played in gPodder.")),
82 'fssync_channel_subfolders': ( bool, True,
83 ("Create a directory for every feed when syncing to an FS-based device "
84 "instead of putting all the episodes in a single directory.")),
85 'on_sync_mark_played': ( bool, False,
86 ("After syncing an episode, mark it as played in gPodder.")),
87 'on_sync_delete': ( bool, False,
88 ("After syncing an episode, delete it from gPodder.")),
89 'auto_remove_old_episodes': ( bool, False,
90 ("Remove episodes older than 'episode_old_age' days on startup.")),
91 'auto_update_feeds': (bool, False,
92 ("Automatically update feeds when gPodder is minimized. "
93 "See 'auto_update_frequency' and 'auto_download'.")),
94 'auto_update_frequency': (int, 20,
95 ("The frequency (in minutes) at which gPodder will update all feeds "
96 "if 'auto_update_feeds' is enabled.")),
97 'episode_list_descriptions': (bool, True,
98 ("Display the episode's description under the episode title in the GUI.")),
99 'show_toolbar': (bool, True,
100 ("Show the toolbar in the GUI's main window.")),
101 'ipod_purge_old_episodes': (bool, False,
102 ("Remove episodes from an iPod device if they've been marked as played "
103 "on the device and they have no rating set (the rating can be set on "
104 "the device by the user to prevent deletion).")),
105 'ipod_delete_played_from_db': (bool, False,
106 ("Remove episodes from gPodder if they've been marked as played "
107 "on the device and they have no rating set (the rating can be set on "
108 "the device by the user to prevent deletion).")),
109 'mp3_player_delete_played': (bool, False,
110 ("Removes episodes from an FS-based device that have been marked as "
111 "played in gPodder. Note: only works if 'only_sync_not_played' is "
112 "also enabled.")),
113 'disable_pre_sync_conversion': (bool, False,
114 ("Disable pre-synchronization conversion of OGG files. This should be "
115 "enabled for deviced that natively support OGG. Eg. Rockbox, iAudio")),
117 # Tray icon and notification settings
118 'display_tray_icon': (bool, False,
119 ("Whether or not gPodder should display an icon in the system tray.")),
120 'minimize_to_tray': (bool, False,
121 ("If 'display_tray_icon' is enabled, when gPodder is minimized it will "
122 "not be visible in the window list.")),
123 'start_iconified': (bool, False,
124 ("When gPodder starts, send it to the tray immediately.")),
125 'enable_notifications': (bool, True,
126 ("Let gPodder use notification bubbles when it can completed certain "
127 "tasks like downloading an episode or finishing syncing to a device.")),
128 'on_quit_ask': (bool, True,
129 ("Ask the user to confirm quitting the application.")),
130 'auto_download': (str, 'never',
131 ("Auto download episodes (never, minimized, always)")),
132 'do_not_show_new_episodes_dialog': (bool, False,
133 ("Do not show the new episodes dialog after updating feed cache when "
134 "gPodder is not minimized")),
137 # Settings that are updated directly in code
138 'ipod_mount': ( str, '/media/ipod',
139 ("The moint point for an iPod Device.")),
140 'mp3_player_folder': ( str, '/media/usbdisk',
141 ("The moint point for an FS-based device.")),
142 'device_type': ( str, 'none',
143 ("The device type: 'mtp', 'filesystem' or 'ipod'")),
144 'download_dir': (str, default_download_dir,
145 ("The default directory that podcast episodes are downloaded to.")),
147 # Playlist Management settings
148 'mp3_player_playlist_file': (str, 'PLAYLISTS/gpodder.m3u',
149 ("The relative path to where the playlist is stored on an FS-based device.")),
150 'mp3_player_playlist_absolute_path': (bool, True,
151 ("Whether or not the the playlist should contain relative or absolute "
152 "paths; this is dependent on the player.")),
153 'mp3_player_playlist_win_path': (bool, True,
154 ("Whether or not the player requires Windows-style paths in the playlist.")),
156 # Special settings (not in preferences)
157 'on_quit_systray': (bool, False,
158 ("When the 'X' button is clicked do not quit, send gPodder to the tray.")),
159 'max_episodes_per_feed': (int, 200,
160 ("The maximum number of episodes that gPodder will display in the episode "
161 "list. Note: Set this to a lower value on slower hardware to speed up "
162 "rendering of the episode list.")),
163 'mp3_player_use_scrobbler_log': (bool, False,
164 ("Attempt to use a Device's scrobbler.log to mark episodes as played in "
165 "gPodder. Useful for Rockbox players.")),
166 'mp3_player_max_filename_length': (int, 100,
167 ("The maximum filename length for FS-based devices.")),
168 'rockbox_copy_coverart' : (bool, False,
169 ("Create rockbox-compatible coverart and copy it to the device when "
170 "syncing. See: 'rockbox_coverart_size'.")),
171 'rockbox_coverart_size' : (int, 100,
172 ("The width of the coverart for the user's Rockbox player/skin.")),
173 'custom_player_copy_coverart' : (bool, False,
174 ("Create custom coverart for FS-based players.")),
175 'custom_player_coverart_size' : (int, 176,
176 ("The width of the coverart for the user's FS-based player.")),
177 'custom_player_coverart_name' : (str, 'folder.jpg',
178 ("The name of the coverart file accepted by the user's FS-based player.")),
179 'custom_player_coverart_format' : (str, 'JPEG',
180 ("The image format accepted by the user's FS-based player.")),
181 'podcast_list_icon_size': (int, 32,
182 ("The width of the icon used in the podcast channel list.")),
183 'cmd_all_downloads_complete': (str, '',
184 ("The path to a command that gets run after all downloads are completed.")),
185 'cmd_download_complete': (str, '',
186 ("The path to a command that gets run after a single download completes. "
187 "See http://wiki.gpodder.org/wiki/Time_stretching for more info.")),
188 'enable_html_shownotes': (bool, True,
189 ("Allow HTML to be rendered in the episode information dialog.")),
190 'maemo_enable_gestures': (bool, False,
191 ("Enable fancy gestures on Maemo.")),
192 'sync_disks_after_transfer': (bool, True,
193 ("Call 'sync' after tranfering episodes to a device.")),
194 'resume_ask_every_episode': (bool, False,
195 ("If there are episode downloads that can be resumed, ask whether or "
196 "not to resume every single one.")),
197 'enable_fingerscroll': (bool, False,
198 ("Enable the use of finger-scrollable widgets on Maemo.")),
199 'double_click_episode_action': (str, 'shownotes',
200 ("Episode double-click/enter action handler (shownotes, download, stream)")),
202 'feed_update_skipping': (bool, True,
203 ('Skip podcasts that are unlikely to have new episodes when updating feeds.')),
205 'episode_list_view_mode': (int, 1, # "Hide deleted episodes" (see gtkui/model.py)
206 ('Internally used (current view mode)')),
207 'podcast_list_view_mode': (int, 1, # Only on Fremantle
208 ('Internally used (current view mode)')),
209 'podcast_list_hide_boring': (bool, False,
210 ('Hide podcasts in the main window for which the episode list is empty')),
212 'audio_played_dbus': (bool, False,
213 ('Set to True if the audio player notifies gPodder about played episodes')),
214 'video_played_dbus': (bool, False,
215 ('Set to True if the video player notifies gPodder about played episodes')),
217 # Settings for my.gpodder.org
218 'my_gpodder_username': (str, '',
219 ("The user's gPodder web services username.")),
220 'my_gpodder_password': (str, '',
221 ("The user's gPodder web services password.")),
222 'my_gpodder_autoupload': (bool, False,
223 ("Upload the user's podcast list to the gPodder web services when "
224 "gPodder is closed.")),
226 # Paned position
227 'paned_position': ( int, 200,
228 ("The width of the channel list.")),
231 # Helper function to add window-specific properties (position and size)
232 def window_props(config_prefix, x=-1, y=-1, width=700, height=500):
233 return {
234 config_prefix+'_x': (int, x),
235 config_prefix+'_y': (int, y),
236 config_prefix+'_width': (int, width),
237 config_prefix+'_height': (int, height),
238 config_prefix+'_maximized': (bool, False),
241 # Register window-specific properties
242 gPodderSettings.update(window_props('main_window', width=700, height=500))
243 gPodderSettings.update(window_props('episode_selector', width=600, height=400))
244 gPodderSettings.update(window_props('episode_window', width=500, height=400))
247 class Config(dict):
248 Settings = gPodderSettings
250 # Number of seconds after which settings are auto-saved
251 WRITE_TO_DISK_TIMEOUT = 60
253 def __init__(self, filename='gpodder.conf'):
254 dict.__init__(self)
255 self.__save_thread = None
256 self.__filename = filename
257 self.__section = 'gpodder-conf-1'
258 self.__observers = []
260 self.load()
261 self.apply_fixes()
263 atexit.register( self.__atexit)
265 def apply_fixes(self):
266 # Here you can add fixes in case syntax changes. These will be
267 # applied whenever a configuration file is loaded.
268 if '{channel' in self.custom_sync_name:
269 log('Fixing OLD syntax {channel.*} => {podcast.*} in custom_sync_name.', sender=self)
270 self.custom_sync_name = self.custom_sync_name.replace('{channel.', '{podcast.')
272 def __getattr__(self, name):
273 if name in self.Settings:
274 return self[name]
275 else:
276 raise AttributeError('%s is not a setting' % name)
278 def get_description(self, option_name):
279 description = _('No description available.')
281 if self.Settings.get(option_name) is not None:
282 row = self.Settings[option_name]
283 if len(row) >= 3:
284 description = row[2]
286 return description
288 def add_observer(self, callback):
290 Add a callback function as observer. This callback
291 will be called when a setting changes. It should
292 have this signature:
294 observer(name, old_value, new_value)
296 The "name" is the setting name, the "old_value" is
297 the value that has been overwritten with "new_value".
299 if callback not in self.__observers:
300 self.__observers.append(callback)
301 else:
302 log('Observer already added: %s', repr(callback), sender=self)
304 def remove_observer(self, callback):
306 Remove an observer previously added to this object.
308 if callback in self.__observers:
309 self.__observers.remove(callback)
310 else:
311 log('Observer not added :%s', repr(callback), sender=self)
313 def schedule_save(self):
314 if self.__save_thread is None:
315 self.__save_thread = threading.Thread(target=self.save_thread_proc)
316 self.__save_thread.setDaemon(True)
317 self.__save_thread.start()
319 def save_thread_proc(self):
320 time.sleep(self.WRITE_TO_DISK_TIMEOUT)
321 if self.__save_thread is not None:
322 self.save()
324 def __atexit(self):
325 if self.__save_thread is not None:
326 self.save()
328 def save(self, filename=None):
329 if filename is None:
330 filename = self.__filename
332 log('Flushing settings to disk', sender=self)
334 parser = ConfigParser.RawConfigParser()
335 parser.add_section(self.__section)
337 for key, value in self.Settings.items():
338 fieldtype, default = value[:2]
339 parser.set(self.__section, key, getattr(self, key, default))
341 try:
342 parser.write(open(filename, 'w'))
343 except:
344 log('Cannot write settings to %s', filename, sender=self)
345 raise IOError('Cannot write to file: %s' % filename)
347 self.__save_thread = None
349 def load(self, filename=None):
350 if filename is not None:
351 self.__filename = filename
353 parser = ConfigParser.RawConfigParser()
355 if os.path.exists(self.__filename):
356 try:
357 parser.read(self.__filename)
358 except:
359 log('Cannot parse config file: %s', self.__filename,
360 sender=self, traceback=True)
362 for key, value in self.Settings.items():
363 fieldtype, default = value[:2]
364 try:
365 if not parser.has_section(self.__section):
366 value = default
367 elif fieldtype == int:
368 value = parser.getint(self.__section, key)
369 elif fieldtype == float:
370 value = parser.getfloat(self.__section, key)
371 elif fieldtype == bool:
372 value = parser.getboolean(self.__section, key)
373 else:
374 value = fieldtype(parser.get(self.__section, key))
375 except:
376 log('Invalid value in %s for %s: %s', self.__filename,
377 key, value, sender=self, traceback=True)
378 value = default
380 self[key] = value
382 def toggle_flag(self, name):
383 if name in self.Settings:
384 (fieldtype, default) = self.Settings[name][:2]
385 if fieldtype == bool:
386 setattr(self, name, not getattr(self, name))
387 else:
388 log('Cannot toggle value: %s (not boolean)', name, sender=self)
389 else:
390 log('Invalid setting name: %s', name, sender=self)
392 def update_field(self, name, new_value):
393 if name in self.Settings:
394 (fieldtype, default) = self.Settings[name][:2]
395 try:
396 new_value = fieldtype(new_value)
397 except:
398 log('Cannot convert "%s" to %s. Ignoring.', str(new_value), fieldtype.__name__, sender=self)
399 return False
400 setattr(self, name, new_value)
401 return True
402 else:
403 log('Invalid setting name: %s', name, sender=self)
404 return False
406 def __setattr__(self, name, value):
407 if name in self.Settings:
408 fieldtype, default = self.Settings[name][:2]
409 try:
410 if self[name] != fieldtype(value):
411 old_value = self[name]
412 log('Update %s: %s => %s', name, old_value, value, sender=self)
413 self[name] = fieldtype(value)
414 for observer in self.__observers:
415 try:
416 # Notify observer about config change
417 observer(name, old_value, self[name])
418 except:
419 log('Error while calling observer: %s',
420 repr(observer), sender=self,
421 traceback=True)
422 self.schedule_save()
423 except:
424 raise ValueError('%s has to be of type %s' % (name, fieldtype.__name__))
425 else:
426 object.__setattr__(self, name, value)