Commits

Guillermo Szeliga committed cf1fe10 Draft

-Dropbox account creation works now.\n-Working on connecting to an account with existing profile data

  • Participants
  • Parent commits 8704c53

Comments (0)

Files changed (5)

api/shelf/configuration/accounts.py

+__author__ = 'guillermo'
+
 import os
+import sys
+import simplejson as json
+
 from api.shelf.registry.clients import StorageClientsRegistry
-
-import simplejson as json
 from api.shelf.configuration import config
 
-__author__ = 'guillermo'
-
 
 
 class AccountsManager():
         client = self.__client_class(account_data)
         client.grant_client_access()
 
-        return account_data
+        return client,account_data
 
-    def load(self, id=None):
+    def load(self, unique_account_id):
+
+        filename = self.__build_account_filename(unique_account_id)
+        full_account_file_path = os.path.join(config.ConfigurationManager.APP_INSTANCES_PATH, filename)
+
+        if os.path.exists(full_account_file_path):
+            account_file = open(full_account_file_path,'r')
+            account_file_content = account_file.read()
+
+            account_file.close()
+
+            return self.__account_type_class(account_file_content)
+        else:
+            #TODO Use a more specific exception
+            raise RuntimeError('Account file %s not found' % filename)
+
+    def connect(self, account_data):
         pass
 
+    def __build_account_filename(self, unique_account_id):
+        return self.__client_class.registry_metadata().unique_id() + "_" + unique_account_id + ".json"
+
     def save(self, account_data):
 
-        filename= self.__client_class.registry_metadata().unique_id() + "_" + account_data.unique_id() + ".json"
+        filename= self.__build_account_filename(account_data.unique_id())
         account_data.save(os.path.join(config.ConfigurationManager.APP_INSTANCES_PATH, filename))
 
     def delete(self, id=None):

api/shelf/console/shell.py

 			account_data = account_manager.create(field_values)
 
 			#3- If account needs authorization
-			account_data = account_manager.authorize(account_data)
+			client,account_data = account_manager.authorize(account_data)
 
 			#4- Save data into a file
 			account_manager.save(account_data)
 
 			print 'Account created successfully'
 
+		elif operation_parts[0] == 'connect':
+
+			account_unique_id = None
+
+			if len(operation_parts) > 1:
+				account_unique_id = operation_parts[1]
+
+			if account_unique_id is None:
+				account_unique_id=raw_input(">> Account name: ")
+
+			if account_unique_id is not None and len(account_unique_id) > 0:
+
+				try:
+					account_data = account_manager.load(account_unique_id)
+
+					print account_data
+
+				except RuntimeError, e:
+					print 'Account information could not be loaded. Reason: %s' % e
+
+			else:
+				print 'Account id cannot be empty'
+
 
 	@single_client_command
 	def do_disconnect(self, operation):

api/storages/adapters/box/adapter.py

+__author__ = 'guillermo'
+
 import webbrowser
 
-__author__ = 'guillermo'
-
 from api.storages.adapters.box import events
 from api.storages.clients.box import session, client
 from api.storages.adapters import skeleton

api/storages/adapters/dropbox/adapter.py

+import webbrowser
+
 from api.shelf.registry.metadata import ClientRegistryMetadata
 from api.storages.adapters import skeleton
 from api.storages.adapters.dropbox import events
 
 class DropboxClient(skeleton.StorageAdapter):
 
-	@staticmethod
-	def registry_metadata():
+    @staticmethod
+    def registry_metadata():
 
-		metadata = ClientRegistryMetadata('dropbox', DropboxAccountData)
+        metadata = ClientRegistryMetadata('dropbox', DropboxAccountData)
 
-		return metadata
+        return metadata
 
-	def __init__(self, account_data):
+    def __init__(self, account_data):
 
-		skeleton.StorageAdapter.__init__(self)
-		self._account_data = account_data
+        skeleton.StorageAdapter.__init__(self)
+        self._account_data = account_data
 
-	def obtain_access_token(self, sess):
+    def move(self):
+        pass
 
-		request_token =  sess.obtain_request_token()
+    def obtain_access_token(self, session_handler):
 
-		print 'You should redirect user to ' + sess.build_authorize_url(request_token)
+        request_token =  session_handler.obtain_request_token()
 
-		raw_input()
+        auth_page = session_handler.build_authorize_url(request_token)
 
-		return sess.obtain_access_token(request_token)
+        print 'You should redirect user to ' + auth_page
 
-	#Mirar el metodo session.obtain_request_token(self) para mas informacion de como hacerlo en el futuro
-	def connect(self):
+        webbrowser.open_new_tab(auth_page)
 
-		#TODO account should be type safe
+        raw_input()
 
-		sess = session.DropboxSession(self._account_data.appKey(), self._account_data.appSecret(), self._account_data.accessType())		
+        return session_handler.obtain_access_token(request_token)
 
-		if not self._account_data.isAccessGranted():
-			self._account_data.assignAccessToken(self.obtain_access_token(sess))
-		else:
-			sess.set_token(self._account_data.oauthToken(), self._account_data.oauthTokenSecret())
-			print 'We are already granted ' + str(sess.token)
+    def __create_session_handler(self):
+        return session.DropboxSession(self._account_data.appKey(), self._account_data.appSecret(), self._account_data.accessType())
 
-		self._client = client.DropboxClient(sess)
+    def grant_client_access(self, session_handler=None):
 
+        if session_handler is None:
+            handler = self.__create_session_handler()
+        else:
+            handler = session_handler
 
-	#TODO We need to check if we actually have an active session opened
+        access_token = self.obtain_access_token(handler)
 
-	def list(self, path):
+        self._account_data.assignAccessToken(access_token)
 
-		#This is not a recursive call, only returns those elements that belong to the specified path
-		remote_info = self._client.metadata(path)
+        return access_token
 
-		content = []
+    #Mirar el metodo session.obtain_request_token(self) para mas informacion de como hacerlo en el futuro
+    def connect(self):
 
-		for remote_element in remote_info['contents']:
-			if remote_element['is_dir']:
-				content.append(self._toStorageFolder(remote_element))
-			else:
-				content.append(self._toStorageFile(remote_element))
+        sess = self.__create_session_handler()
 
-		return content
+        if not self._account_data.isAccessGranted():
+            self.grant_client_access(sess)
+        else:
+            sess.set_token(self._account_data.oauthToken(), self._account_data.oauthTokenSecret())
 
+        self._client = client.DropboxClient(sess)
 
-	def _toStorageFile(self,source):
-		return elements.StorageFile(source['path'],source['modified'],source['rev'])
 
-	def _toStorageFolder(self, source):
-		return elements.StorageFolder(source['path'],source['modified'],source['rev'])
+    #TODO We need to check if we actually have an active session opened
 
-	def about(self):return self._client.account_info()
+    def list(self, path):
 
-	def write(self, target_full_path, source_file, overwrite=True):
-		self._client.put_file(target_full_path, source_file, overwrite)
+        #This is not a recursive call, only returns those elements that belong to the specified path
+        remote_info = self._client.metadata(path)
 
-	def read(self, full_remote_path, target_file_path=None):
+        content = []
 
-		remote_file = self._client.get_file(full_remote_path)
+        for remote_element in remote_info['contents']:
+            if remote_element['is_dir']:
+                content.append(self._toStorageFolder(remote_element))
+            else:
+                content.append(self._toStorageFile(remote_element))
 
-		if target_file_path is not None:
+        return content
 
-			f = open(target_file_path,'wb')
 
-			file_size = 0
+    def _toStorageFile(self,source):
+        return elements.StorageFile(source['path'],source['modified'],source['rev'])
 
-			for header_name, header_value in [(header_content.split(":")[0],header_content.split(":")[1]) for header_content in remote_file.msg.headers]:
-				if header_name.lower() == 'content-length':
-					file_size = int(header_value)
-					break
+    def _toStorageFolder(self, source):
+        return elements.StorageFolder(source['path'],source['modified'],source['rev'])
 
+    def about(self):return self._client.account_info()
 
-			print "Downloading: %s Bytes: %s" % (target_file_path, file_size)
+    def write(self, target_full_path, source_file, overwrite=True):
+        self._client.put_file(target_full_path, source_file, overwrite)
 
-			file_size_dl = 0
-			block_sz = 1024*1024
+    def read(self, full_remote_path, target_file_path=None):
 
-			while True:
-				buffer = remote_file.read(block_sz)
+        remote_file = self._client.get_file(full_remote_path)
 
-				if not buffer:
-					break
+        if target_file_path is not None:
 
-				file_size_dl += len(buffer)
-				f.write(buffer)
+            f = open(target_file_path,'wb')
 
-				status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
-				status += chr(8)*(len(status)+1)
+            file_size = 0
 
-				print status
+            for header_name, header_value in [(header_content.split(":")[0],header_content.split(":")[1]) for header_content in remote_file.msg.headers]:
+                if header_name.lower() == 'content-length':
+                    file_size = int(header_value)
+                    break
 
-			f.close()
-		else:
-			return remote_file
 
+            print "Downloading: %s Bytes: %s" % (target_file_path, file_size)
 
-	def remove(self, full_path):
-		self._client.file_delete(full_path)
+            file_size_dl = 0
+            block_sz = 1024*1024
 
-	def events(self, history_pointer = None):
+            while True:
+                buffer = remote_file.read(block_sz)
 
-		iterator = events.DropboxEventsIterator(self._client, history_pointer)
-		translator = events.DropboxEventTranslator()
+                if not buffer:
+                    break
 
-		return events.DropboxEventsBrowser(iterator, translator)
+                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)
+
+                print status
+
+            f.close()
+        else:
+            return remote_file
+
+
+    def remove(self, full_path):
+        self._client.file_delete(full_path)
+
+    def events(self, history_pointer = None):
+
+        iterator = events.DropboxEventsIterator(self._client, history_pointer)
+        translator = events.DropboxEventTranslator()
+
+        return events.DropboxEventsBrowser(iterator, translator)
 
 
 class DropboxAccountData(skeleton.StorageAccountData):
 
-	def __init__(self, account_data):
+    def __init__(self, account_data):
 
-		parsed_data = skeleton.StorageAccountData.parse(self, account_data)
+        parsed_data = skeleton.StorageAccountData.parse(self, account_data)
 
-		skeleton.StorageAccountData.__init__(self, parsed_data)
+        skeleton.StorageAccountData.__init__(self, parsed_data)
 
-		self._appKey = parsed_data["appKey"]
-		self._appSecret = parsed_data["appSecret"]
-		self._accessType = parsed_data["accessType"]
+        self._appKey = parsed_data["appKey"]
+        self._appSecret = parsed_data["appSecret"]
+        self._accessType = parsed_data["accessType"]
 
-		if "OAuthToken" in parsed_data:
-			self._oauth_token = parsed_data["OAuthToken"]
-		else:
-			self._oauth_token=None
+        if "OAuthToken" in parsed_data:
+            self._oauth_token = parsed_data["OAuthToken"]
+        else:
+            self._oauth_token=None
 
-		if "OAuthTokenSecret" in parsed_data:
-			self._oauth_token_secret = parsed_data["OAuthTokenSecret"]
-		else:
-			self._oauth_token_secret = None
+        if "OAuthTokenSecret" in parsed_data:
+            self._oauth_token_secret = parsed_data["OAuthTokenSecret"]
+        else:
+            self._oauth_token_secret = None
 
-	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
 
-	@skeleton.account_field('dropbox','appKey', 'Application key', skeleton.AccountFieldDescriptor.FIELD_TYPE_STRING)
-	def appKey(self):
-		return self._appKey
+    @skeleton.account_field('dropbox','appKey', 'Application key', skeleton.AccountFieldDescriptor.FIELD_TYPE_STRING)
+    def appKey(self):
+        return self._appKey
 
-	def appSecret(self):
-		return self._appSecret
+    @skeleton.account_field('dropbox','appSecret', 'Application secret', skeleton.AccountFieldDescriptor.FIELD_TYPE_STRING)
+    def appSecret(self):
+        return self._appSecret
 
-	def accessType(self):
-		return self._accessType
+    @skeleton.account_field('dropbox','accessType', 'Access type', skeleton.AccountFieldDescriptor.FIELD_TYPE_STRING)    
+    def accessType(self):
+        return self._accessType
 
-	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 is not None and self._oauth_token is not None
+    def isAccessGranted(self):
+        return self._oauth_token_secret is not None and self._oauth_token is not None
 
-	def jsonize(self):
-		return dict({'appKey': self._appKey, 'appSecret': self._appSecret, 'accessType': self._accessType, 'OAuthToken' : self._oauth_token, 'OAuthTokenSecret': self._oauth_token_secret, 'unique_id': self.unique_id()})
+    @staticmethod
+    def get_configuration_fields():
+        return skeleton.StorageAccountData._list_account_field('dropbox')
 
+    def jsonize(self):
+        return dict({'appKey': self._appKey, 'appSecret': self._appSecret, 'accessType': self._accessType, 'OAuthToken' : self._oauth_token, 'OAuthTokenSecret': self._oauth_token_secret, 'unique_id': self.unique_id()})
+

api/storages/adapters/skeleton.py

 	def unique_id(self):
 		return self.__unique_id
 
-	@staticmethod
 	@abc.abstractmethod
 	def get_configuration_fields():
 		pass