Package x2go :: Package backends :: Package profiles :: Module _file
[frames] | no frames]

Source Code for Module x2go.backends.profiles._file

  1  # -*- coding: utf-8 -*- 
  2   
  3  # Copyright (C) 2010-2012 by Mike Gabriel <mike.gabriel@das-netzwerkteam.de> 
  4  # 
  5  # Python X2Go is free software; you can redistribute it and/or modify 
  6  # it under the terms of the GNU Affero General Public License as published by 
  7  # the Free Software Foundation; either version 3 of the License, or 
  8  # (at your option) any later version. 
  9  # 
 10  # Python X2Go is distributed in the hope that it will be useful, 
 11  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
 12  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 13  # GNU Affero General Public License for more details. 
 14  # 
 15  # You should have received a copy of the GNU Affero General Public License 
 16  # along with this program; if not, write to the 
 17  # Free Software Foundation, Inc., 
 18  # 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. 
 19   
 20  """\ 
 21  L{X2goSessionProfiles} class - managing x2goclient session profiles. 
 22   
 23  L{X2goSessionProfiles} is a public API class. Use this class in your Python X2Go based  
 24  applications. 
 25   
 26  """ 
 27  __NAME__ = 'x2gosessionprofiles-pylib' 
 28   
 29  import copy 
 30  import types 
 31  import re 
 32   
 33  # Python X2Go modules 
 34  from x2go.defaults import X2GO_SESSIONPROFILES_CONFIGFILES as _X2GO_SESSIONPROFILES_CONFIGFILES 
 35  from x2go.defaults import X2GO_SESSIONPROFILE_DEFAULTS as _X2GO_SESSIONPROFILE_DEFAULTS 
 36  from x2go.defaults import X2GO_DESKTOPSESSIONS as _X2GO_DESKTOPSESSIONS 
 37  import x2go.inifiles as inifiles 
 38  import x2go.log as log 
 39  import x2go.utils as utils 
 40  from x2go.x2go_exceptions import X2goProfileException 
41 42 43 -class X2goSessionProfilesFILE(inifiles.X2goIniFile):
44 45 defaultSessionProfile = _X2GO_SESSIONPROFILE_DEFAULTS 46 _non_profile_sections = ('embedded') 47
48 - def __init__(self, config_files=_X2GO_SESSIONPROFILES_CONFIGFILES, defaults=None, session_profile_defaults=None, logger=None, loglevel=log.loglevel_DEFAULT):
49 """\ 50 Retrieve X2Go session profiles from a file, typically C{~/.x2goclient/sessions}. 51 52 @param config_files: a list of config file locations, the first file name in this list the user has write access to will be the user configuration file 53 @type config_files: C{list} 54 @param defaults: not used for this class 55 @type defaults: C{dict} 56 @param session_profile_defaults: a default session profile 57 @type session_profile_defaults: C{dict} 58 @param logger: you can pass an L{X2goLogger} object to the 59 L{X2goSessionProfilesFILE} constructor 60 @type logger: L{X2goLogger} instance 61 @param loglevel: if no L{X2goLogger} object has been supplied a new one will be 62 constructed with the given loglevel 63 @type loglevel: C{int} 64 65 """ 66 self.defaultValues = {} 67 self._profile_metatypes = {} 68 self._cached_profile_ids = [] 69 self._cached_profile_names = [] 70 71 if logger is None: 72 self.logger = log.X2goLogger(loglevel=loglevel) 73 else: 74 self.logger = copy.deepcopy(logger) 75 self.logger.tag = __NAME__ 76 77 # providing defaults for an X2goSessionProfiles instance will---in the worst case---override your 78 # existing sessions file in your home directory once you write the sessions back to file... 79 inifiles.X2goIniFile.__init__(self, config_files, defaults=defaults, logger=logger, loglevel=loglevel) 80 81 if utils._checkSessionProfileDefaults(session_profile_defaults): 82 self.defaultSessionProfile = session_profile_defaults 83 84 self.session_profiles = [ p for p in self.iniConfig.sections() if p not in self._non_profile_sections ] 85 for session_profile in self.session_profiles: 86 for key, default_value in self.defaultSessionProfile.iteritems(): 87 if not self.iniConfig.has_option(session_profile, key): 88 self._storeValue(session_profile, key, default_value) 89 self.get_profile_metatype(session_profile)
90
91 - def __call__(self, profile_id_or_name):
92 """\ 93 Retrieve the session profile configuration for a given session profile ID (or name) 94 95 @param profile_id_or_name: profile ID or profile name 96 @type profile_id_or_name: C{str} 97 98 @return: the profile ID's / name's profile configuration 99 @rtype: C{dict} 100 101 """ 102 _profile_id = self.check_profile_id_or_name(self, profile_id_or_name) 103 return self.get_profile_config(profile_id=_profile_id)
104
105 - def get_profile_metatype(self, profile_id_or_name, force=False):
106 """\ 107 Detect a human readable session profile type from the session profile configuration. 108 109 @param profile_id_or_name: profile ID or profile name 110 @type profile_id_or_name: C{str} 111 @param force: re-detect the meta type, otherwise use a cached result 112 @type force: C{bool} 113 114 @return: the profile ID's / name's meta type 115 @rtype: C{str} 116 117 """ 118 119 _profile_id = self.check_profile_id_or_name(profile_id_or_name) 120 if not self._profile_metatypes.has_key(_profile_id) or force: 121 _config = self.get_profile_config(_profile_id) 122 if _config['host']: 123 if _config['rdpserver'] and _config['command'] == 'RDP': 124 _metatype = 'RDP/proxy' 125 elif _config['published']: 126 127 if _config['command'] in _X2GO_DESKTOPSESSIONS.keys(): 128 _metatype = '%s + Published Applications' % _config['command'] 129 else: 130 _metatype = 'Published Applications' 131 132 elif _config['rootless']: 133 _metatype = 'Single Applications' 134 elif _config['command'] in _X2GO_DESKTOPSESSIONS.keys(): 135 _metatype = '%s Desktop' % _config['command'] 136 elif _config['command'] in _X2GO_DESKTOPSESSIONS.values(): 137 _metatype = '%s Desktop' % [ s for s in _X2GO_DESKTOPSESSIONS.keys() if _config['command'] == _X2GO_DESKTOPSESSIONS[s] ][0] 138 else: 139 _metatype = 'CUSTOM Desktop' 140 else: 141 if _config['rdpserver'] and _config['command'] == 'RDP': 142 _metatype = 'RDP/direct' 143 else: 144 _metatype = 'not supported' 145 self._profile_metatypes[_profile_id] = _metatype 146 else: 147 return self._profile_metatypes[_profile_id]
148
149 - def get_profile_option_type(self, option):
150 """\ 151 Get the data type for a specific session profile option. 152 153 @param option: the option to get the data type for 154 @type option: will be detected by this method 155 156 @return: the data type of C{option} 157 @rtype: C{type} 158 159 """ 160 try: 161 return type(self.defaultSessionProfile[option]) 162 except KeyError: 163 return types.StringType
164
165 - def get_type(self, section, key):
166 """\ 167 Override the parent class's get_type method due to the special layout of this class. 168 169 @param section: INI file section 170 @type section: C{str} 171 @param key: key in INI file section 172 @type key: C{str} 173 174 @return: the data type of C{key} in C{section} 175 @rtype: C{type} 176 177 """ 178 # we have to handle the get_type method separately... 179 return self.get_profile_option_type(key)
180
181 - def get_profile_config(self, profile_id_or_name=None, parameter=None, profile_id=None):
182 """\ 183 The configuration options for a single session profile. 184 185 @param profile_id_or_name: either profile ID or profile name is accepted 186 @type profile_id_or_name: C{str} 187 @param parameter: if specified, only the value for the given parameter is returned 188 @type parameter: C{str} 189 @param profile_id: profile ID (fast than specifying C{profile_id_or_name}) 190 @type profile_id: C{str} 191 192 @return: the session profile configuration for the given profile ID (or name) 193 @rtype: C{dict} 194 195 """ 196 _profile_id = profile_id or self.check_profile_id_or_name(profile_id_or_name) 197 _profile_config = {} 198 for option in self.iniConfig.options(_profile_id): 199 _profile_config[option] = self.get(_profile_id, option, key_type=self.get_profile_option_type(option)) 200 201 if parameter is not None: 202 if parameter in _profile_config.keys(): 203 204 value = _profile_config[parameter] 205 206 if parameter == 'export': 207 _strvalue = value.replace(',', ';').strip().strip('"').strip().strip(';').strip() 208 value = {} 209 if _strvalue: 210 _export_paths = _strvalue.split(';') 211 for _path in _export_paths: 212 if not re.match('.*:(0|1)$', _path): _path = '%s:1' % _path 213 _auto_export_path = re.match('.*:1$', _path) and True or False 214 _export_path = ':'.join(_path.split(':')[:-1]) 215 value[_export_path] = _auto_export_path 216 217 return value 218 219 else: 220 raise X2goProfileException('no such session profile parameter: %s' % parameter) 221 return _profile_config
222
223 - def default_profile_config(self):
224 """\ 225 Return a default session profile. 226 227 @return: default session profile 228 @rtype: C{dict} 229 230 """ 231 return copy.deepcopy(self.defaultSessionProfile)
232
233 - def has_profile(self, profile_id_or_name):
234 """\ 235 Does a session profile of a given profile ID or profile name exist? 236 237 @param profile_id_or_name: profile ID or profile name 238 @type profile_id_or_name: C{str} 239 240 @return: C{True} if there is such a session profile, C{False} otherwise 241 @rtype: C{bool} 242 243 """ 244 try: 245 self.check_profile_id_or_name(profile_id_or_name) 246 return True 247 except X2goProfileException: 248 return False
249 250 @property
251 - def profile_ids(self):
252 """\ 253 Renders a list of all profile IDs found in the session profile configuration file. 254 255 """ 256 if not self._cached_profile_ids: 257 self._cached_profile_ids = [ s for s in self.iniConfig.sections() if s not in self._non_profile_sections ] 258 return self._cached_profile_ids
259
260 - def has_profile_id(self, profile_id):
261 """\ 262 Does a session profile of a given profile ID exist? (Faster than L{has_profile()}.) 263 264 @param profile_id: profile ID 265 @type profile_id: C{str} 266 267 @return: C{True} if there is such a session profile, C{False} otherwise 268 @rtype: C{bool} 269 270 """ 271 return profile_id in self.profile_ids
272 273 @property
274 - def profile_names(self):
275 """\ 276 Renders a list of all profile names found in the session profile configuration file. 277 278 """ 279 if not self._cached_profile_names: 280 self._cached_profile_names = [ self.to_profile_name(p) for p in self.profile_ids ] 281 return self._cached_profile_names
282
283 - def has_profile_name(self, profile_name):
284 """\ 285 Does a session profile of a given profile name exist? (Faster than L{has_profile()}.) 286 287 @param profile_name: profile name 288 @type profile_name: C{str} 289 290 @return: C{True} if there is such a session profile, C{False} otherwise 291 @rtype: C{bool} 292 293 """ 294 return profile_name in self.profile_names
295
296 - def to_profile_id(self, profile_name):
297 """\ 298 Convert profile name to profile ID. 299 300 @param profile_name: profile name 301 @type profile_name: C{str} 302 303 @return: profile ID 304 @rtype: C{str} 305 306 """ 307 _profile_ids = [ p for p in self.profile_ids if self.to_profile_name(p) == profile_name ] 308 if len(_profile_ids) == 1: 309 return _profile_ids[0] 310 elif len(_profile_ids) == 0: 311 return None 312 else: 313 raise X2goProfileException('The sessions config file contains multiple session profiles with name: %s' % profile_name)
314
315 - def to_profile_name(self, profile_id):
316 """\ 317 Convert profile ID to profile name. 318 319 @param profile_id: profile ID 320 @type profile_id: C{str} 321 322 @return: profile name 323 @rtype: C{str} 324 325 """ 326 _profile_config = self.get_profile_config(profile_id=profile_id) 327 if _profile_config.has_key('name'): 328 return _profile_config['name'] 329 else: 330 return ''
331
332 - def add_profile(self, profile_id=None, **kwargs):
333 """\ 334 Add a new session profile. 335 336 @param profile_id: a custom profile ID--if left empty a profile ID will be auto-generated 337 @type profile_id: C{str} 338 @param kwargs: session profile options for this new session profile 339 @type kwargs: C{dict} 340 341 @return: the (auto-generated) profile ID of the new session profile 342 @rtype: C{str} 343 344 """ 345 if profile_id is None: 346 profile_id = utils._genSessionProfileId() 347 for key, value in kwargs.items(): 348 if key in self.defaultSessionProfile: 349 self.update_value(profile_id, key, value) 350 else: 351 raise X2goProfileException('keyword ,,%s\'\' not supported in X2Go session profile' % key) 352 353 for key, value in self.defaultSessionProfile.items(): 354 if key in kwargs: continue 355 self.update_value(profile_id, key, value) 356 357 self._cached_profile_ids = [] 358 self._cached_profile_names = [] 359 360 return profile_id
361
362 - def delete_profile(self, profile_id_or_name):
363 """\ 364 Delete a session profile from the configuration file. 365 366 @param profile_id_or_name: profile ID or profile name 367 @type profile_id_or_name: C{str} 368 369 """ 370 _profile_id = self.check_profile_id_or_name(profile_id_or_name) 371 self.iniConfig.remove_section(_profile_id) 372 self.write_user_config = True 373 self.write() 374 self._cached_profile_ids = [] 375 self._cached_profile_names = []
376
377 - def update_value(self, section, key, value):
378 """\ 379 Update a value in a session profile. 380 381 @param section: the profile ID 382 @type section: C{str} 383 @param key: the session profile option of the given profile ID 384 @type key: C{str} 385 @param value: the value to update the session profile option with 386 @type value: any type, depends on the session profile option 387 388 """ 389 try: 390 profile_id = self.check_profile_id_or_name(section) 391 except X2goProfileException: 392 profile_id = section 393 if key == 'name': 394 profile_name = value 395 current_profile_name = self.get_value(profile_id, key) 396 if not profile_name: 397 raise X2goProfileException('profile name for profile id %s may not be empty' % profile_id) 398 else: 399 if profile_name != current_profile_name and profile_name in self.profile_names: 400 raise X2goProfileException('a profile of name ,,%s'' already exists' % profile_name) 401 self._cached_profile_names = [] 402 403 if key == 'export' and type(value) == types.DictType: 404 405 _strvalue = '"' 406 for folder in value.keys(): 407 _strvalue += "%s:%s;" % (folder, int(value[folder])) 408 _strvalue += '"' 409 _strvalue = _strvalue.replace('""', '') 410 value = _strvalue 411 412 inifiles.X2goIniFile.update_value(self, profile_id, key, value)
413
414 - def check_profile_id_or_name(self, profile_id_or_name):
415 """\ 416 Detect the profile ID from a given string which maybe profile ID or profile name. 417 418 @param profile_id_or_name: profile ID or profile name 419 @type profile_id_or_name: C{str} 420 421 @return: profile ID 422 @rtype: C{str} 423 424 @raise X2goProfileException: if no such session profile exists 425 426 """ 427 _profile_id = None 428 if self.has_profile_name(profile_id_or_name): 429 # we were given a sesion profile name... 430 _profile_id = self.to_profile_id(profile_id_or_name) 431 elif self.has_profile_id(profile_id_or_name): 432 # we were given a session profile id... 433 _profile_id = profile_id_or_name 434 else: 435 raise X2goProfileException('No session profile with id or name ,,%s\'\' exists.' % profile_id_or_name) 436 return _profile_id
437
438 - def to_session_params(self, profile_id_or_name=None, profile_id=None):
439 """\ 440 Convert session profile options to L{X2goSession} constructor method parameters. 441 442 @param profile_id_or_name: either profile ID or profile name is accepted 443 @type profile_id_or_name: C{str} 444 @param profile_id: profile ID (fast than specifying C{profile_id_or_name}) 445 @type profile_id: C{str} 446 447 @return: a dictionary of L{X2goSession} constructor method parameters 448 @rtype: C{dict} 449 450 """ 451 _profile_id = profile_id or self.check_profile_id_or_name(profile_id_or_name) 452 return utils._convert_SessionProfileOptions_2_SessionParams(self.get_profile_config(_profile_id))
453
454 - def get_session_param(self, profile_id_or_name, param):
455 """\ 456 Get a single L{X2goSession} parameter from a specific session profile. 457 458 @param profile_id_or_name: either profile ID or profile name is accepted 459 @type profile_id_or_name: C{str} 460 @param param: the parameter name in the L{X2goSession} constructor method 461 @type param: C{str} 462 463 @return: the value of the session profile option represented by C{param} 464 @rtype: depends on the session profile option requested 465 466 """ 467 return self.to_session_params(profile_id_or_name)[param]
468