fixed guy indend typo
[stack/code/dboxswitch.git] / profhandler.py
old mode 100755 (executable)
new mode 100644 (file)
index d0e16f2..f2be538
@@ -1,4 +1,3 @@
-#!/usr/bin/python
 # -*- coding: utf-8 -*-
 
 """
@@ -37,6 +36,7 @@ import re
 import shutil
 import os
 import errno
+import signal
 
 from apperror import AppError
 from settings import appconf
@@ -63,7 +63,7 @@ class ProfHandler():
         """ Generate and returns the profiles 
             it assumes that self.pdir is defined """
         #this is generated every time to handle the case of the user renaming the directories by hand
-        return [os.path.join(self.pdir, f) for f in os.listdir(self.pdir)]
+        return sorted([os.path.join(self.pdir, f) for f in os.listdir(self.pdir)])
 
     def getProfileFolder(self):
         """ Generates, in a os dependant way, the local folder where all profiles are stored """
@@ -87,14 +87,20 @@ class ProfHandler():
 
             return self.pdir
 
-    def newProfile(self, profileName):
+    def addProfile(self, profileName):
         """ Create a profile """
 
         print("Creating a new profile")
         if self.isValidProfileName(profileName):
-            os.makedirs(os.path.join(self.getProfileFolder(), profileName)) 
+            try:
+                os.makedirs(os.path.join(self.getProfileFolder(), profileName)) 
+            except OSError,e:
+                if e.errno == errno.EEXIST:
+                    raise AppError("Profile exists.")
+                else:
+                    raise AppError(str(e))
         else:
-            raise AppError('Profile Name not valid')
+            raise AppError('Profile Name not valid.\nAllowed only ascii characters.')
         print("Profile "+profileName+" created.")
 
     def delProfile(self, profileName):
@@ -109,35 +115,82 @@ class ProfHandler():
                 raise AppError('Profile Name does not exists')
         else:
             raise AppError('Profile Name not valid')
-        print("Profile "+profileName+" created.")
+        print("Profile "+profileName+" deleted.")
+
+    def isCurrentProfile(self, ppath):
+        """ Returns true if the current profile path is currently activated """
+        
+        pl = platform.system()
+        if pl in ('Linux','Darwin'):
+            if os.path.exists(self.getDropboxDirectory()):
+                return True if os.readlink(self.getDropboxDirectory()) == ppath else False
+            else:
+                return False
 
     def isValidProfileName(self, pname):
+
         if self.reg.match(pname) is not None:
             return True
         else:
             return False
 
-    def activateProfile(self, pname):
-        if pname in self.getProfilesList():
+    def activateProfile(self, ppath):
+        pl = platform.system()
+        if ppath in self.getProfilesList():
             self.stopDropbox()
             try:
-                with open(os.path.join(self.getProfileFolder(), pname)) as pdir:
-                    os.unlink(self.getDropboxDirectory())
-                    os.symlink(os.path.join(self.getProfileFolder(), pname), self.getDropboxDirectory())
+                if pl in ('Linux','Darwin'):
+                    if os.path.exists(self.getDropboxDirectory()):
+                        os.unlink(self.getDropboxDirectory())
+                    os.symlink(ppath, self.getDropboxDirectory())
+                else:
+                    raise NotImplementedError, "Not implemented yet."
             except IOError as e:
-                raise AppError('Error on activating Profile: '+pname)
+                raise AppError('Error on activating Profile: '+ self.getBaseProfileName(ppath))
             self.startDropbox()
         else:
             raise AppError("Trying to acrivate non existant profile")
 
+    def getBaseProfileName(self, ppath):
+        """ Returns the base name given a profile returned by getProfilesList """
+
+        return os.path.basename(ppath)
+
     def getDropboxDirectory(self):
         pl = platform.system()
-        if pl == 'Linux':
+        if pl in ('Linux', 'Darwin'):
             return os.path.join(os.path.expanduser('~'),".dropbox")
         elif pl == 'Windows':
+            assert os.environ.has_key('APPDATA'), Exception('APPDATA env variable not found')
+            return os.path.join(os.environ['APPDATA'],'Dropbox')
+        else:
             raise NotImplementedError, "Not implemented yet."
+
+    def stopDropbox(self):
+        """ Stop dropbox Daemon """
+        pl = platform.system()
+        if pl == 'Linux':
+            os.system("dropbox stop")
+        if pl in ('Linux','Darwin'):
+            pidfile = os.path.expanduser("~/.dropbox/dropbox.pid")                    
+            try:                                                                      
+                with open(pidfile, "r") as f:                                         
+                    pid = int(f.read())                                               
+                    os.kill(pid, signal.SIGTERM)
+            except:                                                                   
+                pass
+
+    def startDropbox(self):
+        """ Sart dropbox Daemon """
+
+        pl = platform.system()
+        if pl == 'Linux':
+            try:
+                os.system("dropbox start -i")
+            except:
+                raise AppError(u"Could not start dropbox.")
         elif pl == 'Darwin':
-            raise NotImplementedError, "Not implemented yet."
+            os.system("/Applications/Dropbox.app/Contents/MacOS/Dropbox &")
 
             
 __CSL = None