def _jsonParser(data): keymap = KeyMap() for key, value in data: if isinstance(value, list): value = tuple(value) keymap.setValue(key, value) return keymap
def _getMetaData(self, contenttype): metadata = KeyMap() if not self.User.isValid(): # Uri with Scheme but without a Path generate invalid user but we need # to return an Identifier, and raise an 'IllegalIdentifierException' # when ContentProvider try to get the Content... # (ie: ContentProvider.queryContent() -> Identifier.getContent()) return metadata uripath = self._uri.getPath().strip('/.') itemid, parentid, path = self.User.DataBase.getIdentifier( self.User.Id, self.User.RootId, uripath) if itemid is not None: if self.IsNew: # New Identifier are created by the parent folder... metadata.setValue('ParentId', itemid) itemid = self._getNewIdentifier() parenturi = self._uri.getUriReference() data = self._getNewContent(itemid, contenttype) else: metadata.setValue('ParentId', parentid) parenturi = '%s://%s/%s' % (self._uri.getScheme(), self._uri.getAuthority(), path) data = self.User.DataBase.getItem(self.User.Id, itemid, parentid) metadata.setValue('Id', itemid) metadata.setValue('ParentURI', parenturi) if data is not None: metadata += data self._propertySetInfo = self._getPropertySetInfo() return metadata
def MetaData(self): metadata = KeyMap() metadata.insertValue('AccessToken', self.AccessToken) metadata.insertValue('RefreshToken', self.RefreshToken) metadata.insertValue('NeverExpires', self.NeverExpires) metadata.insertValue('TimeStamp', self._TimeStamp) metadata.insertValue('Scopes', self.Scopes) return metadata
def __init__(self, ctx): msg = "User loading" self.ctx = ctx self.MetaData = KeyMap() self._Error = '' self.Request = self._getRequest() msg += " ... Done" logMessage(self.ctx, INFO, msg, "User", "__init__()")
def __init__(self, ctx, datasource, url, contenttype=''): level = INFO msg = "Identifier loading" self.ctx = ctx self.DataSource = datasource self.User = None self._Url = self._getUrl(url) self._ContentType = contenttype self._Error = '' self.MetaData = KeyMap() msg += " ... Done" logMessage(self.ctx, level, msg, "Identifier", "__init__()")
def insertItem(self, user, item): timestamp = parseDateTime() rootid = user.getValue('RootId') c1 = self._getDataSourceCall('deleteParent') c2 = self._getDataSourceCall('insertParent') if not self._prepareItemCall('update', c1, c2, user, item, timestamp): self._prepareItemCall('insert', c1, c2, user, item, timestamp) c1.close() c2.close() id = self.Provider.getItemId(item) identifier = KeyMap() identifier.insertValue('Id', id) return self.selectItem(user, identifier)
def getKeyMapFromResult(result, keymap=None, provider=None): keymap = KeyMap() if keymap is None else keymap for i in range(1, result.MetaData.ColumnCount + 1): name = result.MetaData.getColumnName(i) value = getValueFromResult(result, i) if value is None: continue if result.wasNull(): value = None if provider: value = provider.transform(name, value) keymap.insertValue(name, value) return keymap
def MetaData(self): metadata = KeyMap() metadata.insertValue('ClientSecret', self.ClientSecret) metadata.insertValue('ClientId', self.ClientId) metadata.insertValue('TokenUrl', self.TokenUrl) metadata.insertValue('TokenParameters', self.TokenParameters) return metadata
class User(unohelper.Base, XRestUser): def __init__(self, ctx, source=None, name=None, database=None): self.ctx = ctx self.DataBase = database # Uri with Scheme but without a Path generate invalid user but we need # to return an Identifier, and raise an 'IllegalIdentifierException' # when ContentProvider try to get the Content... # (ie: ContentProvider.queryContent() -> Identifier.getContent()) if source is None: self.Provider = None self.Request = None self.MetaData = KeyMap() else: self.Provider = source.Provider self.Request = getRequest(self.ctx, self.Provider.Scheme, name) self.MetaData = source.DataBase.selectUser(name) self.CanAddChild = not self.Provider.GenerateIds msg = getMessage(self.ctx, g_message, 101) logMessage(self.ctx, INFO, msg, "User", "__init__()") @property def Id(self): return self.MetaData.getDefaultValue('UserId', None) @property def Name(self): return self.MetaData.getDefaultValue('UserName', None) @property def RootId(self): return self.MetaData.getDefaultValue('RootId', None) @property def RootName(self): return self.MetaData.getDefaultValue('RootName', None) @property def Token(self): return self.MetaData.getDefaultValue('Token', '') # XRestUser def isValid(self): return self.Id is not None def setDataBase(self, datasource, password, sync): name, password = self.getCredential(password) self.DataBase = DataBase(self.ctx, datasource, name, password, sync) def getCredential(self, password): return self.Name, password
def getKeyMapSequenceFromResult(result, provider=None): sequence = [] count = result.MetaData.ColumnCount + 1 while result.next(): keymap = KeyMap() for i in range(1, count): name = result.MetaData.getColumnName(i) value = getValueFromResult(result, i) if value is None: continue if result.wasNull(): value = None if provider: value = provider.transform(name, value) keymap.insertValue(name, value) sequence.append(keymap) return sequence
def __init__(self, ctx, source=None, name=None, database=None): self.ctx = ctx self.DataBase = database # Uri with Scheme but without a Path generate invalid user but we need # to return an Identifier, and raise an 'IllegalIdentifierException' # when ContentProvider try to get the Content... # (ie: ContentProvider.queryContent() -> Identifier.getContent()) if source is None: self.Provider = None self.Request = None self.MetaData = KeyMap() else: self.Provider = source.Provider self.Request = getRequest(self.ctx, self.Provider.Scheme, name) self.MetaData = source.DataBase.selectUser(name) self.CanAddChild = not self.Provider.GenerateIds msg = getMessage(self.ctx, g_message, 101) logMessage(self.ctx, INFO, msg, "User", "__init__()")
def __init__(self, ctx): self.ctx = ctx self.configuration = getConfiguration(self.ctx, g_identifier, True) self.Setting = OAuth2Setting(self.ctx) version = self._getSSLVersion() self.Session = self._getSession(version) self._Url = '' self._Provider = KeyMap() self._Users = None self._UserName = '' self._User = KeyMap() self._parent = None self._Warnings = [] self._Error = None self.Error = '' self.stringResource = getStringResource(self.ctx, g_identifier, 'OAuth2OOo') self._SessionMode = OFFLINE
def selectItem(self, user, identifier): item = None select = self._getDataSourceCall('getItem') select.setString(1, user.getValue('UserId')) select.setString(2, identifier.getValue('Id')) result = select.executeQuery() if result.next(): item = getKeyMapFromResult(result, KeyMap()) select.close() return item
def _parseResponse(response): try: content = response.headers.get('Content-Type', '') if content.startswith('application/json'): result = response.json(object_pairs_hook=_jsonParser) else: result = KeyMap(**response.headers) return result except Exception as e: print("request._parseResponse() ERROR: %s - %s" % (e, traceback.print_exc()))
def getKeyMapKeyMapFromResult(result): sequence = KeyMap() count = result.MetaData.ColumnCount + 1 while result.next(): keymap = KeyMap() name = getValueFromResult(result, 1) for i in range(2, count): v = getValueFromResult(result, i) n = result.MetaData.getColumnName(i) keymap.insertValue(n, v) sequence.insertValue(name, keymap) return sequence
def _getMetaData(self, id): metadata = None providers = self.configuration.getByName('Providers') if providers.hasByName(id): provider = providers.getByName(id) metadata = KeyMap() metadata.insertValue('ClientSecret', provider.getByName('ClientSecret')) metadata.insertValue('ClientId', provider.getByName('ClientId')) metadata.insertValue('TokenUrl', provider.getByName('TokenUrl')) metadata.insertValue('TokenParameters', provider.getByName('TokenParameters')) return metadata
def insertUser(self, user, root): userid = self.Provider.getUserId(user) username = self.Provider.getUserName(user) displayname = self.Provider.getUserDisplayName(user) rootid = self.Provider.getRootId(root) timestamp = parseDateTime() insert = self._getDataSourceCall('insertUser') insert.setString(1, username) insert.setString(2, displayname) insert.setString(3, rootid) insert.setTimestamp(4, timestamp) insert.setString(5, userid) insert.execute() insert.close() if not self._executeRootCall('update', userid, root, timestamp): self._executeRootCall('insert', userid, root, timestamp) data = KeyMap() data.insertValue('UserId', userid) data.insertValue('UserName', username) data.insertValue('RootId', rootid) data.insertValue('RootName', self.Provider.getRootTitle(root)) return data
def getRoot(self, request, user): id = user.getValue('root_info').getValue('root_namespace_id') root = KeyMap() root.insertValue('id', id) root.insertValue('name', 'Homework') response = uno.createUnoStruct( 'com.sun.star.beans.Optional<com.sun.star.auth.XRestKeyMap>') response.IsPresent = True response.Value = root return response
def getTokenFromResponse(response, token): token.Value = KeyMap() refresh = response.get('refresh_token', None) expires = response.get('expires_in', None) access = response.get('access_token', None) if refresh: token.Value.insertValue('RefreshToken', refresh) if expires: timestamp = int(time.time()) + expires token.Value.insertValue('ExpiresIn', expires) token.Value.insertValue('TimeStamp', timestamp) if access: token.Value.insertValue('AccessToken', access) token.Value.insertValue('NeverExpires', expires is None) token.IsPresent = any((refresh, expires, access)) return token
def _getIdentifier(self): identifier = KeyMap() if not self.User.isValid(): # Uri with Scheme but without a Path generate invalid user but we need # to return an Identifier, and raise an 'IllegalIdentifierException' # when ContentProvider try to get the Content... # (ie: ContentProvider.queryContent() -> Identifier.getContent()) return identifier userid = self.User.Id rootid = self.User.RootId uripath = self._uri.getPath().strip('/.') itemid, parentid, path = self.User.DataBase.getIdentifier( userid, rootid, uripath) if self.isNew(): # New Identifier are created by the parent folder... identifier.setValue('Id', self._getNewIdentifier()) identifier.setValue('ParentId', itemid) else: identifier.setValue('Id', itemid) identifier.setValue('ParentId', parentid) baseuri = '%s://%s/%s' % (self._uri.getScheme(), self._uri.getAuthority(), path) identifier.setValue('BaseURI', baseuri) print("Identifier._getIdentifier() %s - %s - %s" % (itemid, parentid, baseuri)) return identifier
def Json(self): if self._parser is not None and self._parser.DataType.lower() == 'json': keymap = KeyMap(self._response.json(object_pairs_hook=self._parser.parseResponse)) else: keymap = KeyMap(self._response.json()) return keymap
def insertUser(self, provider, user, root): userid = provider.getUserId(user) username = provider.getUserName(user) displayname = provider.getUserDisplayName(user) rootid = provider.getRootId(root) rootname = provider.getRootTitle(root) timestamp = parseDateTime() insert = self._getCall('insertUser') insert.setString(1, username) insert.setString(2, displayname) insert.setString(3, rootid) insert.setTimestamp(4, timestamp) insert.setString(5, userid) insert.execute() insert.close() self._mergeRoot(provider, userid, rootid, rootname, root, timestamp) data = KeyMap() data.insertValue('UserId', userid) data.insertValue('UserName', username) data.insertValue('RootId', rootid) data.insertValue('RootName', rootname) data.insertValue('Token', '') return data
def getKeyMap(self): return KeyMap()
def _getNewContent(self): try: print("Identifier._getNewContent() 1") timestamp = parseDateTime() isfolder = self.User.Provider.isFolder(self._contenttype) isdocument = self.User.Provider.isDocument(self._contenttype) data = KeyMap() data.insertValue('Id', self.Id) data.insertValue('ObjectId', self.Id) data.insertValue('Title', '') data.insertValue('TitleOnServer', '') data.insertValue('DateCreated', timestamp) data.insertValue('DateModified', timestamp) data.insertValue('ContentType', self._contenttype) mediatype = self._contenttype if isfolder else '' data.insertValue('MediaType', mediatype) data.insertValue('Size', 0) data.insertValue('Trashed', False) data.insertValue('IsRoot', self.isRoot()) data.insertValue('IsFolder', isfolder) data.insertValue('IsDocument', isdocument) data.insertValue('CanAddChild', isfolder) data.insertValue('CanRename', True) data.insertValue('IsReadOnly', False) data.insertValue('IsVersionable', isdocument) data.insertValue('Loaded', True) data.insertValue('BaseURI', self.getContentIdentifier()) print("Identifier._getNewContent() 2 %s - %s" % (self.Id, self.getContentIdentifier())) return data except Exception as e: print("Identifier._getNewContent() ERROR: %s - %s" % (e, traceback.print_exc()))
def getResponseTitle(self, response, default): title = response.getDefaultValue('metadata', KeyMap()).getDefaultValue( 'name', None) if title is None: title = default return title
class User(unohelper.Base, XRestUser): def __init__(self, ctx): msg = "User loading" self.ctx = ctx self.MetaData = KeyMap() self._Error = '' self.Request = self._getRequest() msg += " ... Done" logMessage(self.ctx, INFO, msg, "User", "__init__()") @property def Id(self): return self.MetaData.getDefaultValue('UserId', None) @property def Name(self): return self.MetaData.getDefaultValue('UserName', None) @property def RootId(self): return self.MetaData.getDefaultValue('RootId', None) @property def RootName(self): return self.MetaData.getDefaultValue('RootName', None) @property def IsValid(self): return all( (self.Id, self.Name, self.RootId, self.RootName, not self.Error)) @property def Error(self): return self.Request.Error if self.Request and self.Request.Error else self._Error def _getRequest(self): request = self.ctx.ServiceManager.createInstanceWithContext( g_oauth2, self.ctx) if not request: error = "ERROR: service: %s is not available... Check your installed extensions" self._Error = error % g_oauth2 return request def _setSessionMode(self, provider): provider.SessionMode = self.Request.getSessionMode(provider.Host) def initialize(self, datasource, name): print("User.initialize() 1") init = False provider = datasource.Provider self.Request.initializeSession(provider.Scheme, name) self._setSessionMode(provider) user = datasource.selectUser(name) if user is not None: self.MetaData = user init = True elif provider.isOnLine(): user = provider.getUser(self.Request, name) if user.IsPresent: root = provider.getRoot(self.Request, user.Value) if root.IsPresent: self.MetaData = datasource.insertUser( user.Value, root.Value) init = True else: self._Error = "ERROR: Can't retrieve User: %s from provider network is OffLine" % name print("User.initialize() 2 %s" % self.MetaData) return init def getItem(self, datasource, identifier): item = datasource.selectItem(self.MetaData, identifier) provider = datasource.Provider if not item and provider.isOnLine(): data = provider.getItem(self.Request, identifier) if data.IsPresent: item = datasource.insertItem(self.MetaData, data.Value) return item def insertNewDocument(self, datasource, itemid, parentid, content): inserted = datasource.insertNewDocument(self.Id, itemid, parentid, content) return self.synchronize(datasource, inserted) def insertNewFolder(self, datasource, itemid, parentid, content): inserted = datasource.insertNewFolder(self.Id, itemid, parentid, content) return self.synchronize(datasource, inserted) # XRestUser def updateTitle(self, datasource, itemid, parentid, value, default): result = datasource.updateTitle(self.Id, itemid, parentid, value, default) return self.synchronize(datasource, result) def updateSize(self, datasource, itemid, parentid, size): print("User.updateSize() ***********************") result = datasource.updateSize(self.Id, itemid, parentid, size) return self.synchronize(datasource, result) def updateTrashed(self, datasource, itemid, parentid, value, default): result = datasource.updateTrashed(self.Id, itemid, parentid, value, default) return self.synchronize(datasource, result) def getInputStream(self, url): sf = self.ctx.ServiceManager.createInstance( 'com.sun.star.ucb.SimpleFileAccess') if sf.exists(url): return sf.getSize(url), sf.openFileRead(url) return 0, None def synchronize(self, datasource, result): provider = datasource.Provider if provider.isOffLine(): self._setSessionMode(provider) if provider.isOnLine(): datasource.synchronize() return result
def getItemParent(self, item, rootid): ref = item.getDefaultValue('parentReference', KeyMap()) parent = ref.getDefaultValue('id', rootid) return (parent, )
def getUser(self, request, name): data = KeyMap() data.insertValue('Id', name) parameter = self.getRequestParameter('getUser', data) return request.execute(parameter)
def _getTablesAndStatements(statement, version=g_version): tables = [] statements = [] call = getDataSourceCall(statement.getConnection(), 'getTables') for table in getSequenceFromResult(statement.executeQuery(getSqlQuery('getTableName'))): view = False versioned = False columns = [] primary = [] unique = [] constraint = [] call.setString(1, table) result = call.executeQuery() while result.next(): data = getKeyMapFromResult(result, KeyMap()) view = data.getValue('View') versioned = data.getValue('Versioned') column = data.getValue('Column') definition = '"%s"' % column definition += ' %s' % data.getValue('Type') lenght = data.getValue('Lenght') definition += '(%s)' % lenght if lenght else '' default = data.getValue('Default') definition += ' DEFAULT %s' % default if default else '' options = data.getValue('Options') definition += ' %s' % options if options else '' columns.append(definition) if data.getValue('Primary'): primary.append('"%s"' % column) if data.getValue('Unique'): unique.append({'Table': table, 'Column': column}) if data.getValue('ForeignTable') and data.getValue('ForeignColumn'): constraint.append({'Table': table, 'Column': column, 'ForeignTable': data.getValue('ForeignTable'), 'ForeignColumn': data.getValue('ForeignColumn')}) if primary: columns.append(getSqlQuery('getPrimayKey', primary)) for format in unique: columns.append(getSqlQuery('getUniqueConstraint', format)) for format in constraint: columns.append(getSqlQuery('getForeignConstraint', format)) if version >= '2.5.0' and versioned: columns.append(getSqlQuery('getPeriodColumns')) format = (table, ','.join(columns)) query = getSqlQuery('createTable', format) if version >= '2.5.0' and versioned: query += getSqlQuery('getSystemVersioning') tables.append(query) if view: typed = False for format in constraint: if format['Column'] == 'Type': typed = True break format = {'Table': table} if typed: merge = getSqlQuery('createTypedDataMerge', format) else: merge = getSqlQuery('createUnTypedDataMerge', format) statements.append(merge) call.close() return tables, statements
def getResponseId(self, response, default): id = response.getDefaultValue('metadata', KeyMap()).getDefaultValue('id', None) if id is None: id = default return id