stop sync in linux before killing daemon
[stack/code/dboxswitch.git] / 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 [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 isCurrentProfile(self, ppath):
115         """ Returns true if the current profile path is currently activated """
116         
117         pl = platform.system()
118         if pl in ('Linux','Darwin'):
119             if os.path.exists(self.getDropboxDirectory()):
120                 return True if os.readlink(self.getDropboxDirectory()) == ppath else False
121             else:
122                 return False
123
124     def isValidProfileName(self, pname):
125
126         if self.reg.match(pname) is not None:
127             return True
128         else:
129             return False
130
131     def activateProfile(self, ppath):
132         pl = platform.system()
133         if ppath in self.getProfilesList():
134             self.stopDropbox()
135             try:
136                 print self.getDropboxDirectory()
137                 print ppath 
138                 if pl in ('Linux','Darwin'):
139                     if os.path.exists(self.getDropboxDirectory()):
140                         os.unlink(self.getDropboxDirectory())
141                     os.symlink(ppath, self.getDropboxDirectory())
142                 else:
143                     raise NotImplementedError, "Not implemented yet."
144             except IOError as e:
145                 raise AppError('Error on activating Profile: '+ os.path.basename(ppath))
146             self.startDropbox()
147         else:
148             raise AppError("Trying to acrivate non existant profile")
149
150     def getDropboxDirectory(self):
151         pl = platform.system()
152         if pl in ('Linux', 'Darwin'):
153             return os.path.join(os.path.expanduser('~'),".dropbox")
154         elif pl == 'Windows':
155             assert os.environ.has_key('APPDATA'), Exception('APPDATA env variable not found')
156             return os.path.join(os.environ['APPDATA'],'Dropbox')
157         else:
158             raise NotImplementedError, "Not implemented yet."
159
160     def stopDropbox(self):
161         """ Stop dropbox Daemon """
162         pl = platform.system()
163         if pl == 'Linux':
164             os.system("dropbox stop")
165         if pl in ('Linux','Darwin'):
166             pidfile = os.path.expanduser("~/.dropbox/dropbox.pid")                    
167             try:                                                                      
168                 with open(pidfile, "r") as f:                                         
169                     pid = int(f.read())                                               
170                     os.kill(pid, signal.SIGTERM)
171             except:                                                                   
172                 pass
173
174     def startDropbox(self):
175         """ Sart dropbox Daemon """
176
177         pl = platform.system()
178         if pl == 'Linux':
179             try:
180                 os.system("dropbox start -i")
181             except:
182                 raise AppError(u"Could not start dropbox.")
183         elif pl == 'Darwin':
184             os.system("/Applications/Dropbox.app/Contents/MacOS/Dropbox &")
185
186             
187 __CSL = None
188 def winsymlink(source, link_name):
189     '''symlink(source, link_name)
190        Creates a symbolic link pointing to source named link_name.
191         Used to patch the nonexistant version on windows for python 2.6'''
192     global __CSL
193     if __CSL is None:
194         import ctypes
195         csl = ctypes.windll.kernel32.CreateSymbolicLinkW
196         csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32)
197         csl.restype = ctypes.c_ubyte
198         __CSL = csl
199     flags = 0
200     if source is not None and os.path.isdir(source):
201         flags = 1
202     if __CSL(link_name, source, flags) == 0:
203         raise ctypes.WinError()
204