fix profile switching
[stack/code/dboxswitch.git] / dboxswitch / profhandler.py
1 # -*- coding: utf-8 -*-
2
3 """
4 Dboxswitch dropbox profile switcher
5
6 license: Modified BSD License
7
8 Copyright (c) 2012,  <stack@inventati.org>
9 All rights reserved.
10
11 Redistribution and use in source and binary forms, with or without
12 modification, are permitted provided that the following conditions are met:
13     * Redistributions of source code must retain the above copyright
14       notice, this list of conditions and the following disclaimer.
15     * Redistributions in binary form must reproduce the above copyright
16       notice, this list of conditions and the following disclaimer in the
17       documentation and/or other materials provided with the distribution.
18     * Neither the name of the <organization> nor the
19       names of its contributors may be used to endorse or promote products
20       derived from this software without specific prior written permission.
21
22 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
23 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
24 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
25 DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
26 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
27 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
29 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32
33 """
34 import platform
35 import re
36 import shutil
37 import os
38 import errno
39 import signal
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 sorted([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             try:
96                 os.makedirs(os.path.join(self.getProfileFolder(), profileName)) 
97             except OSError,e:
98                 if e.errno == errno.EEXIST:
99                     raise AppError("Profile exists.")
100                 else:
101                     raise AppError(str(e))
102         else:
103             raise AppError('Profile Name not valid.\nAllowed only ascii characters.')
104         print("Profile "+profileName+" created.")
105
106     def delProfile(self, profileName):
107         """ Delete a profile """
108
109         print("Deleting profile")
110         if self.isValidProfileName(profileName):
111             try:
112                 #recursively delete the profile directory
113                 shutil.rmtree(os.path.join(self.pdir, profileName))
114             except:
115                 raise AppError('Profile Name does not exists')
116         else:
117             raise AppError('Profile Name not valid')
118         print("Profile "+profileName+" deleted.")
119
120     def isCurrentProfile(self, ppath):
121         """ Returns true if the current profile path is currently activated """
122         
123         pl = platform.system()
124         if pl in ('Linux','Darwin'):
125             if os.path.exists(self.getDropboxDirectory()):
126                 return True if os.readlink(self.getDropboxDirectory()) == ppath else False
127             else:
128                 return False
129
130     def isValidProfileName(self, pname):
131
132         if self.reg.match(pname) is not None:
133             return True
134         else:
135             return False
136
137     def activateProfile(self, ppath):
138         pl = platform.system()
139         if ppath in self.getProfilesList():
140             self.stopDropbox()
141             try:
142                 if pl in ('Linux','Darwin'):
143                     dbdir = self.getDropboxDirectory()
144                     if os.path.exists(dbdir):
145                         os.unlink(dbdir)
146                     os.symlink(ppath, dbdir)
147                 else:
148                     raise NotImplementedError, "Not implemented yet."
149             except IOError as e:
150                 raise AppError('Error on activating Profile: '+ self.getBaseProfileName(ppath))
151             self.startDropbox()
152         else:
153             raise AppError("Trying to acrivate non existant profile")
154
155     def getBaseProfileName(self, ppath):
156         """ Returns the base name given a profile returned by getProfilesList """
157
158         return os.path.basename(ppath)
159
160     def getDropboxDirectory(self):
161         pl = platform.system()
162         if pl in ('Linux', 'Darwin'):
163             basepath = os.path.join(os.path.expanduser("~"), ".dropbox")
164             for path in [os.path.join(basepath, "instance1"), basepath]:
165                 if os.path.exists(path) and os.path.islink(path):
166                     return path 
167             raise NotImplementedError("Path not found " + basepath + "[instance1]")
168         elif pl == 'Windows':
169             assert os.environ.has_key('APPDATA'), Exception('APPDATA env variable not found')
170             return os.path.join(os.environ['APPDATA'],'Dropbox')
171         else:
172             raise NotImplementedError, "Not implemented yet."
173
174     def stopDropbox(self):
175         """ Stop dropbox Daemon """
176         pl = platform.system()
177         if pl == 'Linux':
178             os.system("dropbox stop")
179         if pl in ('Linux','Darwin'):
180             pidfile = os.path.expanduser("~/.dropbox/dropbox.pid")                    
181             try:                                                                      
182                 with open(pidfile, "r") as f:                                         
183                     pid = int(f.read())                                               
184                     os.kill(pid, signal.SIGTERM)
185             except:                                                                   
186                 pass
187
188     def startDropbox(self):
189         """ Sart dropbox Daemon """
190
191         pl = platform.system()
192         if pl == 'Linux':
193             try:
194                 os.system("dropbox start -i")
195             except:
196                 raise AppError(u"Could not start dropbox.")
197         elif pl == 'Darwin':
198             os.system("/Applications/Dropbox.app/Contents/MacOS/Dropbox &")
199
200             
201 __CSL = None
202 def winsymlink(source, link_name):
203     '''symlink(source, link_name)
204        Creates a symbolic link pointing to source named link_name.
205         Used to patch the nonexistant version on windows for python 2.6'''
206     global __CSL
207     if __CSL is None:
208         import ctypes
209         csl = ctypes.windll.kernel32.CreateSymbolicLinkW
210         csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)
211         csl.restype = ctypes.c_ubyte
212         __CSL = csl
213     flags = 0
214     if source is not None and os.path.isdir(source):
215         flags = 1
216     if __CSL(link_name, source, flags) == 0:
217         raise ctypes.WinError()
218