Commits

Guillermo Szeliga committed 6af9684 Draft

- Accounts management being defined

  • Participants
  • Parent commits 5951b8d

Comments (0)

Files changed (6)

api/shelf/configuration/accounts.py

+from api.shelf.registry.clients import StorageClientsRegistry
+
+__author__ = 'guillermo'
+
+
+class AccountsManager():
+
+    def __init__(self, client_class):
+        self.__client_class = client_class
+        self.__account_type_class = self.__client_class.registry_metadata().account_type_class()
+
+    def get_descriptor(self):
+        return self.__account_type_class.get_descriptor()
+
+    def create(self, account_config_values):
+        print 'Instantiates a new account data object'
+
+    def authorize(self, account_data):
+        print 'Connects using account info and expected adapter in order to authorize our application and return new account data'
+
+    def load(self, id=None):
+        pass
+
+    def save(self, account_data, unique_account_name):
+        print 'Save file into home'
+
+    def delete(self, id=None):
+        pass

api/shelf/console/shell.py

 import cmd
 
 from functools import wraps
+from api.shelf.configuration.accounts import AccountsManager
 from api.shelf.registry.clients import StorageClientsRegistry
 
 __author__ = 'guillermo'
 
 #http://alex.kavanagh.name/2011/05/exploring-python-decorators/
 #http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
-def single_client_command(requires_session=False):
-	def factory(f):
-		def wrapped(*args,**kwds):
-
+def single_client_command(f):
+	@wraps(f)
+	def wrapped(*args,**kwds):
 #
 #			for arg in args:
 #				print "another arg:", dir(arg)
 
-			if args[0]._CloudsterShell__client_class is None:
-				print 'Non client has been selected'
-				return
+		if args[0]._CloudsterShell__client_class is None:
+			print 'Non client has been selected'
+			return
 
-			return f(*args,**kwds)
+		return f(*args,**kwds)
 
-		return wraps(f)(wrapped)
-	return factory
+	return wrapped
 
 def global_command(requires_session=False):
 	pass
 	intro = "\nCloudster administration console\n"
 
 	CMD_REGISTRY_OPTIONS = ['list', 'use', 'dismiss']
+	CMD_ACCOUNT_OPTIONS = ['connect', 'create', 'list', 'delete']
 
 	def __init__(self):
 		cmd.Cmd.__init__(self)
 		return True
 
 	@single_client_command
-	def do_connect(self, operation):
-		print 'Connecting....'
+	def do_account(self, operation):
+
+		account_manager = AccountsManager(self.__client_class)
+
+		operation_parts = operation.rsplit(" ")
+
+		if operation_parts[0] == 'create':
+			descriptor = account_manager.get_descriptor()
+
+			#1- Asks for all values
+			values = {}
+
+			#2- Creates new account data
+			account_data = account_manager.create(values)
+
+			#3- If account needs authorization
+			account_data = account_manager.authorize(account_data)
+
+			#4- Save data into a file
+			account_manager.save(account_data, 'UNIQUE_ACCOUNT_NAME')
+
 
 	@single_client_command
 	def do_disconnect(self, operation):
 
 		elif operation_parts[0] == 'dismiss':
 
-            #TODO Close session
+			#TODO Close session
 			self.__client_class = None
 			self.__update_prompt()
 
 			]
 		return completions
 
+	def complete_account(self, text, line, begidx, endidx):
+		if not text:
+			completions = self.CMD_ACCOUNT_OPTIONS[:]
+		else:
+			completions = [ f
+							for f in self.CMD_ACCOUNT_OPTIONS
+							if f.startswith(text)
+			]
+		return completions
+
 	def __update_prompt(self):
 
 		prompt_string = None

api/shelf/registry/metadata.py

 
 class ClientRegistryMetadata():
 
-    def __init__(self, unique_id):
+    def __init__(self, unique_id, account_type_class):
         self.__unique_id = unique_id
+        self.__account_type_class = account_type_class
 
     def unique_id(self):
         return self.__unique_id
 
+    def account_type_class(self):
+        return self.__account_type_class
+
     def __str__(self):
 
         return 'id:%(unique_id)s' % {"unique_id": self.__unique_id}

api/storages/adapters/box/adapter.py

     @staticmethod
     def registry_metadata():
 
-        metadata = ClientRegistryMetadata('box')
+        metadata = ClientRegistryMetadata('box', BoxAccountData)
 
         return metadata
 
-	def __init__(self, account_data):
+    def __init__(self, account_data):
 
-		StorageAdapter.__init__(self)
+        StorageAdapter.__init__(self)
 
-		self._account_data = account_data
+        self.__account_data = account_data
 
-	def obtainAccessToken(self, sess):
+    def obtainAccessToken(self, sess):
 
-		auth_page = sess.get_authorization_page()
+        auth_page = sess.get_authorization_page()
 
-		print 'You should redirect user to ' + auth_page
+        print 'You should redirect user to ' + auth_page
 
-		raw_input()
+        raw_input()
 
-		return sess.get_auth_token()
+        return sess.get_auth_token()
 
-	def connect(self):
+    def connect(self):
 
-		boxSession = session.BoxSession(self._account_data.appKey())
+        boxSession = session.BoxSession(self.__account_data.appKey())
 
-		if not self._account_data.isAccessGranted():
-			self._account_data.assignAccessToken(self.obtainAccessToken(boxSession))
-		else:
-			boxSession.set_auth_token(self._account_data.oauthTokenSecret())
+        if not self.__account_data.isAccessGranted():
+            self.__account_data.assignAccessToken(self.obtainAccessToken(boxSession))
+        else:
+            boxSession.set_auth_token(self.__account_data.oauthTokenSecret())
 
-		self._client = client.BoxClient(boxSession)
+        self._client = client.BoxClient(boxSession)
 
-	def write(self, target_full_path, source_file, overwrite=True):
-		self._client.upload(target_full_path, source_file)
+    def write(self, target_full_path, source_file, overwrite=True):
+        self._client.upload(target_full_path, source_file)
 
-	def read(self, full_remote_path, target_file_path=None):
+    def read(self, full_remote_path, target_file_path=None):
 
-		remote_file = self._client.download(full_remote_path)
+        remote_file = self._client.download(full_remote_path)
 
-		if target_file_path is not None:
+        if target_file_path is not None:
 
-			f = open(target_file_path,'wb')
+            f = open(target_file_path,'wb')
 
-			meta = remote_file.info()
-			file_size = int(meta.getheaders("Content-Length")[0])
+            meta = remote_file.info()
+            file_size = int(meta.getheaders("Content-Length")[0])
 
-			print "Downloading: %s Bytes: %s" % (target_file_path, file_size)
+            print "Downloading: %s Bytes: %s" % (target_file_path, file_size)
 
-			file_size_dl = 0
-			block_sz = 1024*1024
+            file_size_dl = 0
+            block_sz = 1024*1024
 
-			while True:
-				buffer = remote_file.read(block_sz)
+            while True:
+                buffer = remote_file.read(block_sz)
 
-				if not buffer:
-					break
+                if not buffer:
+                    break
 
-				file_size_dl += len(buffer)
-				f.write(buffer)
+                file_size_dl += len(buffer)
+                f.write(buffer)
 
-				status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
-				status += chr(8)*(len(status)+1)
+                status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
+                status += chr(8)*(len(status)+1)
 
-				print status
+                print status
 
-			f.close()
-		else:
-			return remote_file
+            f.close()
+        else:
+            return remote_file
 
-	def list(self, full_element_path):
-		remote_info = self._client.get_metadata(full_element_path)
+    def list(self, full_element_path):
+        remote_info = self._client.get_metadata(full_element_path)
 
-		content = []
+        content = []
 
-		if remote_info['type'] == client.BoxClient.ELEMENT_TYPE_FOLDER:
-			for item in remote_info['item_collection']['entries']:
-				if item['type'] == client.BoxClient.ELEMENT_TYPE_FOLDER:
-					content.append(elements.StorageFolder(remote_info['name'], None, remote_info['id']))
-				elif item['type'] == client.BoxClient.ELEMENT_TYPE_FILE:
-					content.append(elements.StorageFile(remote_info['name'],None,remote_info['id']))
-		else:
-			content.append(elements.StorageFile(remote_info['path'],remote_info['modified_at'],remote_info['id']))
+        if remote_info['type'] == client.BoxClient.ELEMENT_TYPE_FOLDER:
+            for item in remote_info['item_collection']['entries']:
+                if item['type'] == client.BoxClient.ELEMENT_TYPE_FOLDER:
+                    content.append(elements.StorageFolder(remote_info['name'], None, remote_info['id']))
+                elif item['type'] == client.BoxClient.ELEMENT_TYPE_FILE:
+                    content.append(elements.StorageFile(remote_info['name'],None,remote_info['id']))
+        else:
+            content.append(elements.StorageFile(remote_info['path'],remote_info['modified_at'],remote_info['id']))
 
-		return content
+        return content
 
-	def remove(self, full_path):
-		self._client.delete(full_path)
+    def remove(self, full_path):
+        self._client.delete(full_path)
 
-	def events(self, history_pointer=client.BoxClient.DEFAULT_STREAM_POSITION):
-		iterator = events.BoxEventsIterator(self._client, history_pointer)
-		translator = events.BoxEventTranslator()
+    def events(self, history_pointer=client.BoxClient.DEFAULT_STREAM_POSITION):
+        iterator = events.BoxEventsIterator(self._client, history_pointer)
+        translator = events.BoxEventTranslator()
 
-		return events.BoxEventsBrowser(iterator, translator)
+        return events.BoxEventsBrowser(iterator, translator)
 
 
 class BoxAccountData(StorageAccountData):
 
-	def __init__(self, account_data):
+    def __init__(self, account_data):
 
-		parsed_data = StorageAccountData.parse(self, account_data)
+        parsed_data = StorageAccountData.parse(self, account_data)
 
-		self._appKey = parsed_data["appKey"]
-		self._oauth_token = None
-		self._oauth_token_secret = None
+        self._appKey = parsed_data["appKey"]
+        self._oauth_token = None
+        self._oauth_token_secret = None
 
-		if "OAuthToken" in parsed_data:
-			self._oauth_token = parsed_data["OAuthToken"]
+        if "OAuthToken" in parsed_data:
+            self._oauth_token = parsed_data["OAuthToken"]
 
-		if "OAuthTokenSecret" in parsed_data:
-			self._oauth_token_secret = parsed_data["OAuthTokenSecret"]
+        if "OAuthTokenSecret" in parsed_data:
+            self._oauth_token_secret = parsed_data["OAuthTokenSecret"]
 
 
-	def appKey(self):
-		return self._appKey
+    def appKey(self):
+        return self._appKey
 
-	def assignAccessToken(self, access_token):
-		self._oauth_token = access_token.key
-		self._oauth_token_secret = access_token.secret
+    def assignAccessToken(self, access_token):
+        self._oauth_token = access_token.key
+        self._oauth_token_secret = access_token.secret
 
-	def oauthToken(self):
-		return self._oauth_token
+    def oauthToken(self):
+        return self._oauth_token
 
-	def oauthTokenSecret(self):
-		return self._oauth_token_secret
+    def oauthTokenSecret(self):
+        return self._oauth_token_secret
 
-	def isAccessGranted(self):
-		return (self._oauth_token_secret != None and self._oauth_token != None)
+    def isAccessGranted(self):
+        return (self._oauth_token_secret != None and self._oauth_token != None)
 
-	def jsonize(self):
-		return dict({'appKey': self._appKey, 'OAuthToken' : self._oauth_token, 'OAuthTokenSecret': self._oauth_token_secret})
+    @staticmethod
+    def get_descriptor():
+        print 'Return account description fields, needs_authorization, etc'
+
+    @staticmethod
+    def create_descriptor(properties=None,interactiveMode=False):
+        print 'Interactive creation ....'
+
+    def jsonize(self):
+        return dict({'appKey': self._appKey, 'OAuthToken' : self._oauth_token, 'OAuthTokenSecret': self._oauth_token_secret})

api/storages/adapters/dropbox/adapter.py

 	@staticmethod
 	def registry_metadata():
 
-		metadata = ClientRegistryMetadata('dropbox')
+		metadata = ClientRegistryMetadata('dropbox', DropboxAccountData)
 
 		return metadata
 

api/storages/adapters/skeleton.py

 		return json_types.JSonizable.fromJSON(self,account_data)
 
 	def save(self,target):
+		pass
+
+	@staticmethod
+	def get_descriptor():
+		pass
+
+	@staticmethod
+	@abc.abstractmethod
+	def create_descriptor(properties=None,interactive=False):
 		pass