added initial profiles switch implementation
[stack/code/dboxswitch.git] / profhandler.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 """
5 Dboxswitch dropbox profile switcher
6
7 license: Modified BSD License
8
9 Copyright (c) 2012,  <stack@inventati.org>
10 All rights reserved.
11
12 Redistribution and use in source and binary forms, with or without
13 modification, are permitted provided that the following conditions are met:
14     * Redistributions of source code must retain the above copyright
15       notice, this list of conditions and the following disclaimer.
16     * Redistributions in binary form must reproduce the above copyright
17       notice, this list of conditions and the following disclaimer in the
18       documentation and/or other materials provided with the distribution.
19     * Neither the name of the <organization> nor the
20       names of its contributors may be used to endorse or promote products
21       derived from this software without specific prior written permission.
22
23 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
24 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
27 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
28 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
30 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
32 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
34 """
35 import platform
36 import re
37 import shutil
38 import os
39 import errno
40
41 from apperror import AppError
42 from settings import appconf
43
44 class ProfHandler():
45
46     def __init__(self):
47
48         #create profile directory if not exists
49         try:
50             os.makedirs(self.getProfileFolder())
51         except OSError, e:
52             if e.errno != errno.EEXIST:
53                 raise
54
55         #compile regular expression for validating profile names
56         self.reg = re.compile("[a-zA-Z0-9_-]+")
57
58         #patch symlink on windows
59         if platform.system() is 'Windows':
60             os.symlink = winsymlink
61
62     def getProfilesList(self):
63         """ Generate and returns the profiles 
64             it assumes that self.pdir is defined """
65         #this is generated every time to handle the case of the user renaming the directories by hand
66         return [os.path.join(self.pdir, f) for f in os.listdir(self.pdir)]
67
68     def getProfileFolder(self):
69         """ Generates, in a os dependant way, the local folder where all profiles are stored """
70         try:
71             #directory path is cached
72             return self.pdir
73         except AttributeError:
74             pl = platform.system()
75             if pl == "Linux":
76                 try:
77                     from xdg.BaseDirectory import xdf_data_home
78                     self.pdir = os.path.join(xdg_data_home, appconf.appname)
79                 except:
80                     self.pdir = os.path.join(os.path.expanduser('~'),".local/share",appconf.appname)
81             elif pl == 'Windows':
82                 self.pdir = os.path.join(os.getenv("APPDATA"), appconf.appname)
83             elif pl == 'Darwin':
84                 self.pdir =  os.path.join(os.path.expanduser('~'),"."+appconf.appname)
85             elif pl == None:
86                 raise AppError('Operative system NOT supported.')
87
88             return self.pdir
89
90     def addProfile(self, profileName):
91         """ Create a profile """
92
93         print("Creating a new profile")
94         if self.isValidProfileName(profileName):
95             os.makedirs(os.path.join(self.getProfileFolder(), profileName)) 
96         else:
97             raise AppError('Profile Name not valid.\nAllowed only ascii characters.')
98         print("Profile "+profileName+" created.")
99
100     def delProfile(self, profileName):
101         """ Delete a profile """
102
103         print("Deleting profile")
104         if self.isValidProfileName(profileName):
105             try:
106                 #recursively delete the profile directory
107                 shutil.rmtree(os.path.join(self.pdir, profileName))
108             except:
109                 raise AppError('Profile Name does not exists')
110         else:
111             raise AppError('Profile Name not valid')
112         print("Profile "+profileName+" created.")
113
114     def isValidProfileName(self, pname):
115         if self.reg.match(pname) is not None:
116             return True
117         else:
118             return False
119
120     def activateProfile(self, pname):
121         if pname in self.getProfilesList():
122             self.stopDropbox()
123             try:
124                 with open(os.path.join(self.getProfileFolder(), pname)) as pdir:
125                     os.unlink(self.getDropboxDirectory())
126                     os.symlink(os.path.join(self.getProfileFolder(), pname), self.getDropboxDirectory())
127             except IOError as e:
128                 raise AppError('Error on activating Profile: '+pname)
129             self.startDropbox()
130         else:
131             raise AppError("Trying to acrivate non existant profile")
132
133     def getDropboxDirectory(self):
134         pl = platform.system()
135         if pl == 'Linux':
136             return os.path.join(os.path.expanduser('~'),".dropbox")
137         elif pl == 'Windows':
138             raise NotImplementedError, "Not implemented yet."
139         elif pl == 'Darwin':
140             raise NotImplementedError, "Not implemented yet."
141
142             
143 __CSL = None
144 def winsymlink(source, link_name):
145     '''symlink(source, link_name)
146        Creates a symbolic link pointing to source named link_name.
147         Used to patch the nonexistant version on windows for python 2.6'''
148     global __CSL
149     if __CSL is None:
150         import ctypes
151         csl = ctypes.windll.kernel32.CreateSymbolicLinkW
152         csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)
153         csl.restype = ctypes.c_ubyte
154         __CSL = csl
155     flags = 0
156     if source is not None and os.path.isdir(source):
157         flags = 1
158     if __CSL(link_name, source, flags) == 0:
159         raise ctypes.WinError()
160