def __init__(self): ''' Description: Initialization internal method, called internally usage: Called internally Return: N/A ''' self.env = Environment() self.util = Utility() self.mongo = MongoDB() self.dbutil = DBUtility() self.globaL = Global() self.sec = Security() self.myClass = self.__class__.__name__ self.myModuleLogger = logging.getLogger('uConnect.' + str(__name__) + '.' + self.myClass)
def __init__(self): ''' Description: Initialization internal method, called internally usage: Called internally Return: N/A ''' self.factory = Factory() self.util = Utility() self.mongo = MongoDB() self.globaL = Global() self.sec = Security() self.member = Member() self.activity = Activity() self.conn = Connections() self.myClass = self.__class__.__name__ self.myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
class Member(object, metaclass=Singleton): def __init__(self): ''' Description: Initialization internal method, called internally usage: Called internally Return: N/A ''' self.env = Environment() self.util = Utility() self.mongo = MongoDB() self.dbutil = DBUtility() self.globaL = Global() self.sec = Security() self.myClass = self.__class__.__name__ self.myModuleLogger = logging.getLogger('uConnect.' + str(__name__) + '.' + self.myClass) def __buildArg4IsAValidMember(self, argMemberId, argAuthKey, argEntityId, argEntityType): return { 'MemberId': argMemberId, 'EntityId': argEntityId, 'EntityType': argEntityType, 'AuthKey': argAuthKey } def __updateMemberTag(self, argRequestDict): try: #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass) self.myModuleLogger.debug( 'Argument [{arg}] received'.format(arg=argRequestDict)) myRequestStatus = self.util.getCopy( self.globaL._Global__RequestStatus) myMainArgData = self.util.getCopy(argRequestDict) myArgKey = ['_id'] ''' validating arguments ''' myArgValidation, myMissingKeys, myArgValMessage = \ self.util.valRequiredArg(myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues( myArgValMessage) #fi ''' preparing pipeline for aggregate function ''' myAggregateColl = self.globaL._Global__memberColl #myPipeLine=[{"$match":{"_id":myMainArgData['_id']}},{"$unwind":"$Contact"},{"$addFields": { "Tag": { "$concat":["$Main.LastName", " , ", "$Main.FirstName"," , ","$Address.City"," ", "$Address.State", " , ", "$Contact.Value"] }}},{"$project": { "Tag":1, "_id":0 }}] # tag filed is Main.LastName, Main.FirstName, Address.City/State, Contact.Email myPipeLine = [{ "$match": { "_id": myMainArgData['_id'] } }, { "$addFields": { "Tag": { "$concat": [ "$Main.LastName", " , ", "$Main.FirstName", " , ", "$Address.City", " ", "$Address.State", " , ", "$Contact.Email" ] } } }, { "$project": { "Tag": 1, "_id": 0 } }] myAggregateCommand = { "aggregate": myAggregateColl, "pipeline": myPipeLine } self.myModuleLogger.debug( 'pipeline [{pipeline}] will be used to build Tag for member [{member}]' .format(pipeline=myPipeLine, member=myMainArgData['_id'])) ''' executing aggregate command to get Tag information ''' myTagResult = self.mongo.ExecCommand(myAggregateCommand) self.myModuleLogger.debug( 'Tag [{tag}] built'.format(tag=myTagResult)) #print('tag result:',myTagResult) if 'result' in myTagResult: myTagData = [ tag.upper() for tag in [myTagResult['result'][0]['Tag']] ] #print('tag:',myTagData[0],tuple(myTagData)) myTagUpdateData = {'Tag': myTagData} myTagUpdateResult = self.mongo.UpdateDoc( self.globaL._Global__memberColl, myMainArgData, myTagUpdateData, 'set') if self.util.getUpdateStatus( myTagUpdateResult) == self.globaL._Global__Success: myRequestStatus = self.util.getRequestStatus( self.globaL._Global__Success) else: myRequestStatus = self.util.getRequestStatus( self.globaL._Global__UnSuccess) #fi else: myRequestStatus = self.util.getRequestStatus( self.globaL._Global__UnSuccess) self.myModuleLogger.exception( 'Could not build tag for this member, Error [{myerror}]'. format(myerror='result key is missing' + myTagResult)) #fi return myRequestStatus except Exception as err: myRequestStatus = self.util.extractLogError() return myRequestStatus def __buildInitMembderData(self, argRequestDict): #argMainDict,argAddressDict,argContactDict try: #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass) self.myModuleLogger.debug( 'Argument [{arg}] received'.format(arg=argRequestDict)) myMainArgData = self.util.getCopy(argRequestDict) myArgKey = ['Main', 'Address', 'Contact'] ''' validating arguments ''' myArgValidation, myMissingKeys, myArgValMessage = \ self.util.valRequiredArg(myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues( myArgValMessage) #fi myMainDict = myMainArgData['Main'] myAddressDict = myMainArgData['Address'] myContactDict = myMainArgData['Contact'] myZipCode = myAddressDict['ZipCode'] myCityNState = self.util.getAddressCityState(myZipCode) myCity = myCityNState[0] myState = myCityNState[1] myMemberTag = [] myInitMemberData = self.util.getTemplateCopy( self.globaL._Global__member) #myModuleLogger.debug('Member template [{template}]'.format(template=myInitMemberData)) ''' Main ''' if ('LastName' in myMainDict): myInitMemberData['Main']['LastName'] = myMainDict['LastName'] myMemberTag.append(myMainDict['LastName']) #fi if ('FirstName' in myMainDict): myInitMemberData['Main']['FirstName'] = myMainDict['FirstName'] myMemberTag.append(myMainDict['FirstName']) #fi if ('NickName' in myMainDict): myInitMemberData['Main']['NickName'] = myMainDict['NickName'] myMemberTag.append(myMainDict['NickName']) #fi if ('Type' in myMainDict): myInitMemberData['Main']['Type'] = myMainDict['Type'] else: myInitMemberData['Main'][ 'Type'] = self.globaL._Global__Participant #fi ''' Address ''' if ('Street' in myAddressDict): myInitMemberData['Address']['Street'] = myAddressDict['Street'] #myMemberTag.append(myAddressDict['Street']) #fi if (not (myCity == None)) and (not (myState == None)): myInitMemberData['Address']['City'] = myCity myInitMemberData['Address']['State'] = myState myInitMemberData['Address']['ZipCode'] = myZipCode #myMemberTag.extend([myCity,myState]) else: myInitMemberData['Address']['ZipCode'] = myZipCode #fi ''' Contact, ''' if ('Mobile' in myContactDict): ''' commenting following code, will go back to original way to store the contact data myInitMemberData['Contact'].append({'Method':'Mobile','Value': myContactDict['Mobile']}) ''' myInitMemberData['Contact']['Mobile'] = myContactDict['Mobile'] #myMemberTag.append(myContactDict['Mobile']) #fi if ('Email' in myContactDict): ''' commenting following code, will go back to original way to store the contact data myInitMemberData['Contact'].append({'Method':'Email','Value': myContactDict['Email']}) ''' myInitMemberData['Contact']['Email'] = myContactDict['Email'] #myMemberTag.append(myContactDict['Email']) #fi # building tag #myMemberTag = self.util.removeEmptyValueFromList(myMemberTag) #myInitMemberData['Tag'].extend(myMemberTag) ''' lets get the memberid for this member ''' myMemberId = self.mongo.genKeyForCollection( self.globaL._Global__memberColl) myInitMemberData['_id'] = myMemberId ''' build initial history data ''' myInitMemberData[ self.globaL. _Global__HistoryColumn] = self.util.buildInitHistData() self.myModuleLogger.info( 'Data [{arg}] returned'.format(arg=myInitMemberData)) return myInitMemberData except Exception as err: myRequestStatus = self.util.extractLogError() raise #__buildInitMembderData Ends here def __createAMember(self, argRequestDict): ''' Description: Create a member argRequestDict: Json/Dict; Following key name is expected in this dict/json object {'Request': {'Header':{ScreenId':'','ActionId':'',Page:}, {'MainArg': {<Member data 'Main','Address','Contact'>}} } We will add 'BusyHours', BusyDays' block from default value usage: <createAMember(<argReqJsonDict>) Return: Json object Collection: Member: Insert a record in Member collection ''' try: ## we need to check who called this function, must be from register #print(self.util.whoAmi()) #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass) myMainArgData = self.util.getCopy(argRequestDict) self.myModuleLogger.debug( 'Argument [{arg}] received'.format(arg=argRequestDict)) myArgKey = ['Main', 'Address', 'Contact'] myArgValidation, myMissingKeys, myArgValMessage = \ self.util.valRequiredArg(myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues( myArgValMessage) #fi ''' Preparing value to create a new member build initial data ''' myMemberData = self.__buildInitMembderData({ 'Main': myMainArgData['Main'], 'Address': myMainArgData['Address'], 'Contact': myMainArgData['Contact'] }) myMemberId = myMemberData['_id'] ''' Creating a member ''' self.myModuleLogger.info( 'Creating new member, data [{doc}]'.format(doc=myMemberData)) myMemberResult = self.mongo.InsertOneDoc( self.globaL._Global__memberColl, myMemberData) myTagUpdateResult = self.__updateMemberTag({'_id': myMemberId}) self.myModuleLogger.info( 'Member [{id}] created, result[{result}]'.format( id=myMemberId, result=myMemberResult)) self.myModuleLogger.info('Tag updated, result[{result}]'.format( result=myTagUpdateResult)) ''' Building response data, we can not retrieve member information because we dont have Auth ket yet, will return member id created''' ''' myRequestDict = self.util.builInternalRequestDict({'Data':{'_id':myMemberId}}) myRequestDict = self.getAMemberDetail(myResponseDataDict) myResponse = self.util.buildResponseData(self.globaL._Global__InternalRequest,myMemberResult,'Insert',myResponseData) ''' myResponse = myMemberResult['_id'] return myResponse except Exception as err: myRequestStatus = self.util.extractLogError() raise def __buildGetAllConnPipeline(self, argRequestDict): #argMemberId, argConnectionType try: #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass) self.myModuleLogger.debug( 'Argument [{arg}] received'.format(arg=argRequestDict)) myMainArgData = self.util.getCopy(argRequestDict) myArgKey = ['MemberId', 'ConnectionType'] ''' validating arguments ''' myArgValidation, myMissingKeys, myArgValMessage = \ self.util.valRequiredArg(myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues( myArgValMessage) #fi myConnectionType = myMainArgData['ConnectionType'] myMemberId = myMainArgData['MemberId'] self.myModuleLogger.debug( 'Building pipeline for aggregate function') if myConnectionType == self.globaL._Global__memberColl: myFromCollection = self.globaL._Global__memberColl myPipeLine = [{ "$match": { "_id": myMemberId } }, { "$unwind": { "path": "$Connections", "preserveNullAndEmptyArrays": True } }, { "$match": { "$and": [{ "Connections.Type": myConnectionType }] } }, { "$lookup": { "from": myFromCollection, "localField": "Connections.Id", "foreignField": "_id", "as": "MyMemberConnections" } }, { "$project": { "_id": 1, "Connections": 1, "MyMemberConnections.Id": 1, "MyMemberConnections.Main": 1, "MyMemberConnections.Address": 1, "MyMemberConnections.Contact": 1 } }, { "$sort": { "MyMemberConnections.Main.LastName": 1 } }] #fi return myPipeLine except Exception as err: myRequestStatus = self.util.extractLogError() raise #__buildGetAllConnPipeline Ends here def __buildMyConnection(self, argRequestDict): #argConnectionType, argConnectionRawData): #argMemberId, argConnectionType try: #self.myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass) #self.myModuleLogger.debug('Argument [{arg}] received'.format(arg=argRequestDict)) myMainArgData = self.util.getCopy(argRequestDict) myArgKey = ['ConnectionType', 'ConnectionRawData'] ''' validating arguments ''' myArgValidation, myMissingKeys, myArgValMessage = \ self.util.valRequiredArg(myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues( myArgValMessage) #fi myConnectionType = myMainArgData['ConnectionType'] myConnectionRawData = myMainArgData['ConnectionRawData'] self.myModuleLogger.debug( 'Building [{conn}] Connection '.format(conn=myConnectionType)) if myConnectionType == self.globaL._Global__memberColl: myResultStatus = {"Success": myConnectionRawData['ok']} myMemberConnRawData = myConnectionRawData['result'] if (myMemberConnRawData): myMemberConnections = { "_id": myMemberConnRawData[0]['_id'] } myMemberConnections['Connections'] = [] for x in myMemberConnRawData: x['MyMemberConnections'][0].update( {'Favorite': x['Connections']['Favorite']}) x['MyMemberConnections'][0].update( {'Blocked': x['Connections']['Blocked']}) x['MyMemberConnections'][0].update( {'Id': x['Connections']['Id']}) x['MyMemberConnections'][0].update( {'Type': x['Connections']['Type']}) x['MyMemberConnections'][0].update( {'Status': x['Connections']['Status']}) myMemberConnections['Connections'].append( x['MyMemberConnections'][0]) # sorting now #myConnection = json.dumps(myMemberConnections, sort_keys=True) myConnection = myMemberConnections else: myConnection = {} #fi #print json.dumps(myMemberConnections, sort_keys=True) #print myMemberConnections return myConnection except Exception as err: myRequestStatus = self.util.extractLogError() raise #__buildMyConnection Ends here def __getMemberConnectionInfo(self, argRequestDict): ''' Returns current Member connection status MemberId, ConnectMemberId, Auth ''' try: #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass) myMainArgData = self.util.getCopy(argRequestDict) self.myModuleLogger.debug( 'Argument [{arg}] received'.format(arg=argRequestDict)) myArgKey = ['MemberId', 'ConnectMemberId', 'Auth'] ''' validating arguments ''' myArgValidation, myMissingKeys, myArgValMessage = \ self.util.valRequiredArg(myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues( myArgValMessage) #fi ''' Validate auth key for this request''' if not (self.sec._Security__isValAuthKeyInternal( myMainArgData['Auth'])): raise com.uconnect.core.error.InvalidAuthKey( 'Invalid Auth Key [{auth}] for this request [{me}]'.format( auth=myMainArgData['Auth'], me=self.util.whoAmI())) #fi ''' Preparing ''' myCriteria = { '_id': myMainArgData['MemberId'], 'Connections.Id': myMainArgData['ConnectMemberId'], 'Connections.Type': 'Member' } myProjection = {'_id': 1, 'Connections': 1} #print(myCriteria,myProjection) ''' Finding document ''' myResult = self.mongo.findDocument(self.globaL._Global__memberColl, myCriteria, myProjection, True) #print(myResult) myMemberConnection = self.util.extr1stDocFromResultSets(myResult) return myMemberConnection except Exception as err: myRequestStatus = self.util.extractLogError() raise #__getMemberConnectionInfo Ends here def __updateMemberMain(self, argRequestDict): ''' We need to combine all update of a Member Description: Update Member's Main information (LastName,FirstName,NickName,Sex) argRequestDict: Json/Dict; Following key name is expected in this dict/json object {'Request': {'Header':{ScreenId':'','ActionId':'',Page:}, {'MainArg': {'MemberId':'','Main':[{'Key':'Value'},...] } usage: <addMember2Favorite(<argReqJsonDict>) MainArg{'MemberId':'','Main':[{Key':'', 'Value':''}]} Return: Json object ''' try: #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass) if 'MainArg' in argRequestDict: myMainArgData = self.util.getCopy(argRequestDict)['MainArg'] else: myMainArgData = self.util.getCopy(argRequestDict) #fi myRequestStatus = self.util.getCopy( self.globaL._Global__RequestStatus) self.myModuleLogger.debug( 'Argument [{arg}] received'.format(arg=myMainArgData)) ''' validating arguments ''' myArgKey = ['Auth', 'Main'] myArgValidation, myMissingKeys, myArgValMessage = \ self.util.valRequiredArg(myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues( myArgValMessage) #fi # validating security, this has already been validated by BPS process ??? ''' if not (self.sec._Security__isValAuthKeyInternal(myMainArgData['Auth'])): raise com.uconnect.core.error.InvalidAuthKey('Invalid Auth Key [{auth}] for this request [{me}]'. format(auth=myMainArgData['Auth'], me=self.util.whoAmI())) #fi ''' ''' Preparing document: ''' # removing key(s) if it has any empty values myMainUpdateData = self.util.removeEmptyValueKeyFromDict( {'Main': myMainArgData['Main']}) # building update data, find all key informarion which need to be changed myAllMainKey = self.util.getAllKeysFromDict( myMainUpdateData['Main']) myMainUpdateData = {} for key in myAllMainKey: myMainUpdateData.update( {'Main.' + key: myMainArgData['Main'][key]}) # myMemberId = myMainArgData['Auth']['EntityId'] myCriteria = {'_id': myMemberId} self.myModuleLogger.info( 'Updating Member [{member}]\'s [{main}]'.format( member=myMemberId, main=myMainUpdateData)) ''' Executing document update ''' myResult = self.mongo.UpdateDoc(self.globaL._Global__memberColl, myCriteria, myMainUpdateData, 'set', False) ''' build response data ''' myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myRequestStatus, 'Update', myResult) #return myResponse except Exception as err: myRequestStatus = self.util.extractLogError() myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myRequestStatus, 'Error') return myResponse def __updateMemberAddress(self, argRequestDict): ''' Description: Update Member's Address argRequestDict: Json/Dict; Following key name is expected in this dict/json object {'Request': {'Header':{ScreenId':'','ActionId':'',Page:}, {'MainArg': {'MemberId':'','Address':[{'Key':'Value'},...] } usage: <addMember2Favorite(<argReqJsonDict>) MainArg{'MemberId':'','Contact':[{Key':'', 'Value':''}]} Return: Json object ''' try: #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass) if 'MainArg' in argRequestDict: myMainArgData = self.util.getCopy(argRequestDict)['MainArg'] else: myMainArgData = self.util.getCopy(argRequestDict) #fi myRequestStatus = self.util.getCopy( self.globaL._Global__RequestStatus) self.myModuleLogger.debug( 'Argument [{arg}] received'.format(arg=myMainArgData)) ''' validating arguments ''' myArgKey = ['Auth', 'Address'] myArgValidation, myMissingKeys, myArgValMessage = \ self.util.valRequiredArg(myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues( myArgValMessage) #fi ''' preparing document ''' myMemberId = myMainArgData['Auth']['EntityId'] myCriteria = {'_id': myMemberId} myAddressUpdateData = {} # removing key(s) if it has any empty values myAddressData = self.util.removeEmptyValueKeyFromDict( {'Address': myMainArgData['Address']}) #print('AddressData',myAddressData) # building update data, find all key informarion which need to be changed myAllAddressKey = self.util.getAllKeysFromDict( myAddressData['Address']) # would not change city/state, this shold be change by changing the ZipCode if 'City' in myAllAddressKey: myAllAddressKey.remove('City') #fi if 'State' in myAllAddressKey: myAllAddressKey.remove('State') #fi #print('Removed City/State,addressData:',myAddressData, myAllAddressKey) for key in myAllAddressKey: myAddressUpdateData.update( {'Address.' + key: myAddressData['Address'][key]}) # #print('Created address update data', myAddressUpdateData) # will add matching the City/State, if ZipCode is passed if 'ZipCode' in myAllAddressKey: myCityNState = self.util.getAddressCityState( myAddressData['Address']['ZipCode']) myAddressUpdateData.update({'Address.City': myCityNState[0]}) myAddressUpdateData.update({'Address.State': myCityNState[1]}) #fi self.myModuleLogger.info( 'Updating Member [{member}]\'s address [{address}]'.format( member=myMemberId, address=myAddressUpdateData)) ''' Executing document update ''' myResult = self.mongo.UpdateDoc(self.globaL._Global__memberColl, myCriteria, myAddressUpdateData, 'set', False) ''' build response data ''' myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myRequestStatus, 'Update', myResult) #return myResponse except Exception as err: myRequestStatus = self.util.extractLogError() myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myRequestStatus, 'Error') return myResponse def __updateMemberContact(self, argRequestDict): ''' Description: Update Member's contact argRequestDict: Json/Dict; Following key name is expected in this dict/json object {'Request': {'Header':{ScreenId':'','ActionId':'',Page:}, {'MainArg': {'MemberId':'','Contact':[{'Key':'Value'},...] } usage: <addMember2Favorite(<argReqJsonDict>) MainArg{'MemberId':'','Contact':[{Key':'', 'Value':''}]} Return: Json object ''' try: #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass) if 'MainArg' in argRequestDict: myMainArgData = self.util.getCopy(argRequestDict)['MainArg'] else: myMainArgData = self.util.getCopy(argRequestDict) #fi myRequestStatus = self.util.getCopy( self.globaL._Global__RequestStatus) self.myModuleLogger.debug( 'Argument [{arg}] received'.format(arg=myMainArgData)) ''' validating arguments ''' myArgKey = ['Auth', 'Contact'] myArgValidation, myMissingKeys, myArgValMessage = \ self.util.valRequiredArg(myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues( myArgValMessage) #fi ''' preparing document ''' # removing key(s) if it has any empty values myContactData = self.util.removeEmptyValueKeyFromDict( {'Contact': myMainArgData['Contact']}) myMemberId = myMainArgData['Auth']['EntityId'] myCriteria = {'_id': myMemberId} # building update data, find all key informarion which need to be changed myAllContactKey = self.util.getAllKeysFromDict( myContactData['Contact']) myContactUpdateData = {} for key in myAllContactKey: myContactUpdateData.update( {'Contact.' + key: myMainArgData['Contact'][key]}) # self.myModuleLogger.info( 'Updating Member [{member}]\'s Contact [{contact}]'.format( member=myMemberId, contact=myContactUpdateData)) ''' Executing document update ''' myResult = self.mongo.UpdateDoc(self.globaL._Global__memberColl, myCriteria, myContactUpdateData, 'set', False) ''' build response data ''' myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myRequestStatus, 'Update', myResult) #return myResponse except Exception as err: myRequestStatus = self.util.extractLogError() myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myRequestStatus, 'Error') return myResponse #fi def __getAMemberConnections(self, argRequestDict): ''' Description: Find a member's all connections argRequestDict: Json/Dict; Following key name is expected in this dict/json object {'_id':'','ResponseMode':''} usage: <__getAMemberConnections(<argReqJsonDict>) Return: Json object ''' try: #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass) if 'MainArg' in argRequestDict: myMainArgData = self.util.getCopy(argRequestDict)['MainArg'] else: myMainArgData = self.util.getCopy(argRequestDict) #fi myRequestStatus = self.util.getCopy( self.globaL._Global__RequestStatus) self.myModuleLogger.debug( 'Argument [{arg}] received'.format(arg=myMainArgData)) ''' validating arguments ''' myArgKey = ['MemberId', 'ConnectionType', 'ResponseMode'] myArgValidation, myMissingKeys, myArgValMessage = \ self.util.valRequiredArg(myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues( myArgValMessage) #fi ''' build aggregate pipeline ''' myAggregatePipeLine = self.__buildGetAllConnPipeline(\ {'MemberId':myMainArgData['MemberId'],'ConnectionType':myMainArgData['ConnectionType']}) self.myModuleLogger.debug( "Pipeline [{pipeline}] will be used to execute the aggregate function" ) # execute aggregate pipeline myAggregateDict = { "aggregate": self.globaL._Global__memberColl, "pipeline": myAggregatePipeLine, "allowDiskUse": True } myConnectionRawData = self.mongo.ExecCommand(myAggregateDict) if self.util.isAllArgumentsValid(myConnectionRawData): myMemberConnection = { "Data": self.__buildMyConnection({ 'ConnectionType': self.globaL._Global__member, 'ConnectionRawData': myConnectionRawData }) } else: myMemberConnection = {} #fi myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myRequestStatus, 'Find', myMemberConnection) return myResponse except Exception as err: myRequestStatus = self.util.extractLogError() myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myRequestStatus, 'Error') return myResponse def __isAValidMember(self, argRequestDict): ''' Description: Find a member details argRequestDict: Json/Dict; Following key name is expected in this dict/json object {'_id':'','ResponseMode':''} usage: <__isAValidMember(<argReqJsonDict>) Return: Json object ''' try: #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass) if 'MainArg' in argRequestDict: myMainArgData = self.util.getCopy(argRequestDict)['MainArg'] else: myMainArgData = self.util.getCopy(argRequestDict) #fi myRequestStatus = self.util.getCopy( self.globaL._Global__RequestStatus) self.myModuleLogger.debug( 'Argument [{arg}] received'.format(arg=myMainArgData)) isValidMember = self.globaL._Global__False #myArgKey = ['Member','Auth'] ''' validating arguments ''' myArgKey = ['_id', 'ResponseMode'] myArgValidation, myMissingKeys, myArgValMessage = \ self.util.valRequiredArg(myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues( myArgValMessage) #fi myCriteria = { '_id': myMainArgData['_id'], 'Main.Type': self.globaL._Global__member } myMemberDataCount = self.mongo.findTotDocuments( self.globaL._Global__memberColl, myCriteria) #print(myCriteria,myProjection,myMemberData) if myMemberDataCount > 0: isValidMember = self.globaL._Global__True myRequestStatus = self.util.getRequestStatus( self.globaL._Global__Success) else: isValidMember = self.globaL._Global__False myRequestStatus = self.util.getRequestStatus( self.globaL._Global__UnSuccess, 'MemberID [{member}] does not exist'.format( member=str(myMainArgData['_id']))) #fi ''' build response data ''' myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myRequestStatus, 'Find', isValidMember) return myResponse except Exception as err: myRequestStatus = self.util.extractLogError() myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myRequestStatus, 'Error', isValidMember) return myResponse
class GroupBPS(object): def __init__(self): ''' Description: Initialization internal method, called internally usage: Called internally Return: N/A ''' self.util = Utility() self.mongo = MongoDB() self.globaL = Global() self.activity = Activity() self.group = Group() self.sec = Security() self.myClass = self.__class__.__name__ self.myModuleLogger = logging.getLogger('uConnect.' + str(__name__) + '.' + self.myClass) ''' +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ GGGGGGGGGGGGG RRRRRRRRRRR OOOOOOOOOOOO UU UU PPPPPPPPPPPP GG RR RR OO OO UU UU PP PP GG RR RR OO OO UU UU PP PP GG GGGGGGG RRRRRRRRRRR OO OO UU UU PPPPPPPPPPPP GG GG RR RR OO OO UU UU PP GG GG RR RR OO OO UU UU PP GGGGGGGGGGGGG RR RR OOOOOOOOOOOO UUUUUUUUUUUUUU PP +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ''' def isAMemberGroupNameInUse(self, argRequestDict): ''' check if the group name is already in use for this member''' try: if 'MainArg' in argRequestDict: myMainArgData = self.util.getCopy(argRequestDict)['MainArg'] else: myMainArgData = self.util.getCopy(argRequestDict) #fi myRequestStatus = self.util.getCopy( self.globaL._Global__RequestStatus) self.myModuleLogger.debug( 'Argument [{arg}] received'.format(arg=myMainArgData)) isGroupNameInUse = self.globaL._Global__False ''' validating arguments ''' myArgKey = ['Main', 'Auth', 'ResponseMode'] myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg( myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues( myArgValMessage) #fi myArgKey = ['GroupName'] myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg( myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues( myArgValMessage) #fi ''' Validate auth key for this request''' if not (self.sec._Security__isValAuthKeyInternal( myMainArgData['Auth'])): raise com.uconnect.core.error.InvalidAuthKey( 'Invalid Auth Key [{auth}] for this request [{me}]'.format( auth=myMainArgData['AuthKey'], me=self.util.whoAmI())) #fi myGroupValidationData = { 'GroupName': myMainArgData['Main']['GroupName'], 'OwnerMemberId': myMainArgData['Auth']['EntityId'] } isGroupNameInUse = self.group._Group__isAMemberGroupInUse( myGroupValidationData) myRequestStatus = self.util.getRequestStatus( self.globaL._Global__Success) myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myRequestStatus, 'Find', isGroupNameInUse) return myResponse except Exception as err: myRequestStatus = self.util.extractLogError() myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myRequestStatus, 'Error') return myResponse # end def createAMemberGroup(self, argRequestDict): ''' Description: Create a Member's group argRequestDict: Json/Dict; Following key name is expected in this dict/json object {'MainArg': {'GroupName':'<GroupName>','MeberId':'<owner of group>'}} usage: <createAMemGroup(<argRequestDict>) Return: Json object Collection: Group: Insert a record in Group collection ''' try: #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass) if 'MainArg' in argRequestDict: myMainArgData = self.util.getCopy(argRequestDict['MainArg']) else: myMainArgData = self.util.getCopy(argRequestDict) #fi self.myModuleLogger.debug( 'Argument [{arg}] received'.format(arg=myMainArgData)) myRequestStatus = self.util.getCopy( self.globaL._Global__RequestStatus) ''' validating arguments ''' myArgKey = ['Main', 'Auth', 'ResponseMode', 'Participants'] myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg( myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues( myArgValMessage) #fi myArgKey = ['GroupName'] myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg( myMainArgData['Main'], myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues( myArgValMessage) #fi ''' Validate auth key for this request''' if not (self.sec._Security__isValAuthKeyInternal( myMainArgData['Auth'])): raise com.uconnect.core.error.InvalidAuthKey( 'Invalid Auth Key [{auth}] for this request [{me}]'.format( auth=myMainArgData['AuthKey'], me=self.util.whoAmI())) #fi # create Member Group myGroupData = { 'Main': myMainArgData['Main'], 'ResponseMode': self.globaL._Global__InternalRequest } myGroupData['Main'].update( {'OwnerMemberId': myMainArgData['Auth']['EntityId']}) myGroupDbResult = self.group._Group__createAMemGroup(myGroupData) if myGroupDbResult['Status'] == self.globaL._Global__Success: myGroupId = myGroupDbResult['Data']['_id'] self.myModuleLogger.info('New group [{group}] craeted for member [{member}]'\ .format(group=myGroupData['Main']['GroupName'] + ':' + str(myGroupId), member=myGroupData['Main']['OwnerMemberId'])) # add allparticipants to this group myAllParticipantLists = myMainArgData['Participants'] if not (self.util.isList(myAllParticipantLists)): myAllParticipantLists = [myAllParticipantLists] #fi myParticipantData = {'_id':myGroupId,'ResponseMode':self.globaL._Global__InternalRequest,\ 'Participants':myAllParticipantLists} self.group._Group__updateGroupParticipants(myParticipantData) # Building response data myRequestStatus = self.util.getRequestStatus( self.globaL._Global__Success) myGroupArg = { '_id': myGroupId, 'ResponseMode': self.globaL._Global__InternalRequest, 'Auth': myMainArgData['Auth'] } myGroupFindResult = self.getAGroupDetail(myGroupArg) if myGroupFindResult[ 'Status'] == self.globaL._Global__UnSuccess: myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myGroupFindResult, 'Error') else: myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myRequestStatus, 'Find', myGroupFindResult) #fi else: #myRequestStatus = self.util.getRequestStatus(self.global._Global__UnSuccess,myGroupDbResult['Message'] ) myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myGroupDbResult, 'Error') #fi return myResponse except Exception as err: myRequestStatus = self.util.extractLogError() #print('In Error',myRequestStatus) myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myRequestStatus, 'Error') return myResponse #end def getAllGroupOfAMember(self, argRequestDict): ''' Description: Find all group member participates and all participating member argRequestDict: Json/Dict; Following key name is expected in this dict/json object usage: <getGroupDetails4AMember(<argReqJsonDict>) Return: Json object ''' try: #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass) if 'MainArg' in argRequestDict: myMainArgData = self.util.getCopy(argRequestDict['MainArg']) else: myMainArgData = self.util.getCopy(argRequestDict) #fi self.myModuleLogger.debug( 'Argument [{arg}] received'.format(arg=myMainArgData)) myRequestStatus = self.util.getCopy( self.globaL._Global__RequestStatus) ''' validating arguments ''' myArgKey = ['Auth', 'ResponseMode'] myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg( myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues( myArgValMessage) #fi ''' Validate auth key for this request''' if not (self.sec._Security__isValAuthKeyInternal( myMainArgData['Auth'])): raise com.uconnect.core.error.InvalidAuthKey( 'Invalid Auth Key [{auth}] for this request [{me}]'.format( auth=myMainArgData['AuthKey'], me=self.util.whoAmI())) #fi myMemberId = myMainArgData['Auth']['EntityId'] self.myModuleLogger.info( 'Finding all group for this member [{member}]'.format( member=myMemberId)) myCriteria = {'Participants.MemberId': myMemberId} myProjection = {'_id': 1, 'Main': 1} myFindOne = True myGroupData = self.mongo.findDocument( self.globaL._Global__groupColl, myCriteria, myProjection, myFindOne) myRequestStatus = self.util.getRequestStatus( self.globaL._Global__Success) ''' build response data ''' myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myRequestStatus, 'Find', myGroupData) return myResponse except Exception as err: myRequestStatus = self.util.extractLogError() myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myRequestStatus, 'Error') return myResponse def getAGroupDetail(self, argRequestDict): ''' Description: Find a member's all connections details argRequestDict: Json/Dict; Following key name is expected in this dict/json object {'Request': {'Header':{ScreenId':'','ActionId':'',Page:}, {'MainArg': {}} } usage: <getsAMemberDetail(<argReqJsonDict>) http://www.jsoneditoronline.org/?id=ae36cfdc68b1255530150d286d14bab8 ''' # we need to check which arguments are passed; valid argument is Phone/Email/LastName + FirstName try: if 'MainArg' in argRequestDict: myMainArgData = self.util.getCopy(argRequestDict)['MainArg'] else: myMainArgData = self.util.getCopy(argRequestDict) #fi self.myModuleLogger.debug( 'Argument [{arg}] received'.format(arg=argRequestDict)) myRequestStatus = self.util.getCopy( self.globaL._Global__RequestStatus) ''' validating arguments ''' myArgKey = ['_id', 'ResponseMode', 'Auth'] myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg( myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues( myArgValMessage) #fi if (myMainArgData['Auth']['EntityType'] != self.globaL._Global__member): raise com.uconnect.core.error.MissingArgumentValues( 'Auth Arg validation error; entitytype key must be "Member"' ) #fi ''' Validate auth key for this request''' if not (self.sec._Security__isValidAuthentication( myMainArgData['Auth'])): raise com.uconnect.core.error.InvalidAuthKey( 'Invalid Auth Key [{auth}] for this request [{me}]'.format( auth=myMainArgData['Auth'], me=self.util.whoAmI())) #fi ''' preparing value needed to find member connections''' self.myModuleLogger.info( 'Finding all member participants for a group [{arg}]'.format( arg=myMainArgData)) ''' we need threading for following request using threading of python ''' myGroupId = myMainArgData['_id'] ''' build aggregate pipeline ''' myAggregatePipeLine = self.group._Group__buildGetAllGroupMemberPipeline( {'GroupId': myGroupId})['Data'] self.myModuleLogger.debug( "Pipeline [{pipeline}] will be used to execute the aggregate function" ) myAggregateDict = { "aggregate": self.globaL._Global__groupColl, "pipeline": myAggregatePipeLine, "allowDiskUse": True } myAllParticipantsRawData = self.mongo.ExecCommand( myAggregateDict)['result'] #print('Participants',myAllParticipantsRawData) myAllPArticipants = self.group._Group__formatParticipantsData( myAllParticipantsRawData) myRequestStatus = self.util.getRequestStatus( self.globaL._Global__Success) myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myRequestStatus, 'Find', myAllPArticipants) return myResponse except Exception as err: myRequestStatus = self.util.extractLogError() myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myRequestStatus, 'Error') return myResponse def UpdateGroupDetails(self, argRequestDict): ''' Description: Update group participants (Add/Remove [participants]) argRequestDict: Json/Dict; Following key name is expected in this dict/json object {'Main':{'GroupName':''},'Participants':[{'MemberId':'','Action':''}]} usage: <UpdateGroupDetails(<argReqJsonDict>) Return: Status of the operation ''' try: if 'MainArg' in argRequestDict: myMainArgData = self.util.getCopy(argRequestDict)['MainArg'] else: myMainArgData = self.util.getCopy(argRequestDict) #fi self.myModuleLogger.debug( 'Argument [{arg}] received'.format(arg=argRequestDict)) myRequestStatus = self.util.getCopy( self.globaL._Global__RequestStatus) ''' validating arguments ''' myArgKey = ['_id', 'ResponseMode', 'Auth'] myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg( myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues( myArgValMessage) #fi if not (self.util.isAnyKeyInDict(['Main', 'Participants'], myMainArgData)): raise com.uconnect.core.error.MissingArgumentValues( 'Either Main/Participants key is required ') #fi # validating if this member is associated with this group if not (self.group._Group__isValidGroupForMember( { 'GroupId': myMainArgData['_id'], 'MemberId': myMainArgData['Auth']['EntityId'] })): raise com.uconnect.core.error.MissingArgumentValues(\ 'Member {member} is not associated with group {group}'.\ format(member=myMainArgData['Auth']['EntityId'], group=myMainArgData['_id'])) #fi if (myMainArgData['Auth']['EntityType'] != self.globaL._Global__member): raise com.uconnect.core.error.MissingArgumentValues( 'Auth Arg validation error; entitytype key must be "Member"' ) #fi ''' Validate auth key for this request''' if not (self.sec._Security__isValidAuthentication( myMainArgData['Auth'])): raise com.uconnect.core.error.InvalidAuthKey( 'Invalid Auth Key [{auth}] for this request [{me}]'.format( auth=myMainArgData['Auth'], me=self.util.whoAmI())) #fi ''' Performing update ''' # see if an update is requested in Main if 'Main' in myMainArgData and myMainArgData['Main']: myGroupName = myMainArgData['Main']['GroupName'] myGroupUpdateStatus = self.group._Group__updateGroupMain(\ {'_id':myMainArgData['_id'], 'GroupName':myGroupName}) # if 'Participants' in myMainArgData and myMainArgData[ 'Participants']: myAllPArticipants = myMainArgData['Participants'] myGroupUpdateStatus = self.group._Group__updateGroupParticipants(\ {'_id':myMainArgData['_id'],'Participants':myAllPArticipants}) # myRequestStatus = self.util.getRequestStatus( self.globaL._Global__Success) myGroupDetail = self.getAGroupDetail(\ {'_id':myMainArgData['_id'],'ResponseMode':self.globaL._Global__InternalRequest,'Auth':myMainArgData['Auth']}) myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myRequestStatus, 'Find', myGroupDetail) return myResponse except Exception as err: myRequestStatus = self.util.extractLogError() myResponse = self.util.buildResponseData( myMainArgData['ResponseMode'], myRequestStatus, 'Error') return myRequestStatus
class MemberBPS(object): ''' Member BPS class, called from factory method ''' def __init__(self): ''' Description: Initialization internal method, called internally usage: Called internally Return: N/A ''' self.factory = Factory() self.util = Utility() self.mongo = MongoDB() self.globaL = Global() self.sec = Security() self.member = Member() self.activity = Activity() self.conn = Connections() self.myClass = self.__class__.__name__ self.myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass) ''' +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ MMM MMM EEEEEEEEEE MMM MMM BBBBBBBBBBB EEEEEEEEEE RRRRRRRRRRRR MMMM MMMM EE MMMM MMMM BB BB EE RR RR MM MM MM MM EE MM MM MM MM BB BB EE RR RR MM MM MM MM EEEEEEEEEE MM MM MM MM BBBBBBBBBBBB EEEEEEEEEE RRRRRRRRRRRR MM MMM MM EE MM MMM MM BB BB EE RR RR MM MM EE MM MM BB BB EE RR RR MM MM EEEEEEEEEE MM MM BBBBBBBBBBB EEEEEEEEEE RR RR +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ''' def ____createAMember(self,argRequestDict): ''' Description: Create a member argRequestDict: Json/Dict; Following key name is expected in this dict/json object {'Request': {'Header':{ScreenId':'','ActionId':'',Page:}, {'MainArg': {<Member data 'Main','Address','Contact'>}} } We will add 'BusyHours', BusyDays' block from default value usage: <createAMember(<argReqJsonDict>) Return: Json object Collection: Member: Insert a record in Member collection ''' #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass) try: ## we need to check who called this function, must be from register #print(self.util.whoAmi()) myMainArgData = self.util.getCopy(argRequestDict) self.myModuleLogger.debug('Argument [{arg}] received'.format(arg = argRequestDict)) myArgKey = ['Main','Address','Contact'] myArgValidation, myMissingKeys, myArgValMessage = \ self.util.valRequiredArg(myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues(myArgValMessage) #fi ''' Preparing value to create a new member build initial data ''' myMemberData = self.member._Member__buildInitMembderData({'Main':myMainArgData['Main'],'Address':myMainArgData['Address'],'Contact':myMainArgData['Contact']}) myMemberId = myMemberData['_id'] ''' Creating a member ''' self.myModuleLogger.info('Creating new member, data [{doc}]'.format(doc=myMemberData)) myMemberResult = self.mongo.InsertOneDoc(self.globaL._Global__memberColl, myMemberData) self.myModuleLogger.info('Member [{id}] created, result[{result}]'.format(id=myMemberId, result=myMemberResult)) ''' Building response data, we can not retrieve member information because we dont have Auth ket yet, will return member id created''' ''' myRequestDict = self.util.builInternalRequestDict({'Data':{'_id':myMemberId}}) myRequestDict = self.getAMemberDetail(myResponseDataDict) myResponse = self.util.buildResponseData(self.global._Global__InternalRequest,myMemberResult,'Insert',myResponseData) ''' myResponse = myMemberResult['_id'] return myResponse except Exception as err: myRequestStatus = self.util.extractLogError() raise def getAllInformation4Member(self,argRequestDict): # wip ''' We need to combine all update of a Member Description: Update Member's Main information (LastName,FirstName,NickName,Sex) argRequestDict: Json/Dict; Following key name is expected in this dict/json object {'Request': {'Header':{ScreenId':'','ActionId':'',Page:}, {'MainArg': {'MemberId':'','Main':[{'Key':'Value'},...] } usage: <getAllInformation4Member(<argReqJsonDict>) MainArg{'MemberId':'','Main':[{Key':'', 'Value':''}]} Return: Json object ''' try: ''' Initialization & Validation ''' if 'MainArg' in argRequestDict: myMainArgData = self.util.getCopy(argRequestDict)['MainArg'] else: myMainArgData = self.util.getCopy(argRequestDict) #fi self.myModuleLogger.debug('Argument [{arg}] received'.format(arg = argRequestDict)) myArgKey = ['Auth','ResponseMode'] myArgValidation, myMissingKeys, myArgValMessage = \ self.util.valRequiredArg(myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues(myArgValMessage) #fi ''' validating Auth arg ''' if (myMainArgData['Auth']['EntityType'] != self.globaL._Global__member): raise com.uconnect.core.error.MissingArgumentValues('Auth Arg validation error; entitytype key must be "Member"') #fi if not (self.sec._Security__isValidAuthentication(myMainArgData['Auth'])): #print(self.util.whoAmI()) raise com.uconnect.core.error.InvalidAuthKey('Invalid Auth Key [{auth}] for this request [{me}]'. format(auth=myMainArgData['Auth'], me=self.myClass+'.'+self.util.whoAmI())) #fi ''' Preparing document: ''' myMemberId = myMainArgData['Auth']['EntityId'] myCriteria = {'_id':myMemberId} # get Member Details myMemberDetails = self.getAMemberDetail({'ResponseMode':self.globaL._Global__InternalRequest,'Auth':myMainArgData['Auth']}) # get All Connections (Member) myConnectionArgData = {'ConnectionType':'Member','ResponseMode': self.globaL._Global__InternalRequest,'Auth':myMainArgData['Auth']} myMemberConnections = self.getAMemberConnections(myResponseArgData) # Get All Group this member participates to (owner of a group is also member) # we need to combine all results in one result sets return myResponse except Exception as err: myRequestStatus = self.util.extractLogError() raise error def updateMemberDetail(self, argRequestDict): ''' Description: Update member information Main --> Member's Main information Address --> Member's Address information Contact --> Member's Contact information argRequestDict: Json/Dict; Following key name is expected in this dict/json object {'Main','Address','Contact','Auth',ResponseMode'} usage: <updateMemberDetail(<argRequestDict>) Return: Json object ''' try: #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass) if 'MainArg' in argRequestDict: myMainArgData = self.util.getCopy(argRequestDict)['MainArg'] else: myMainArgData = self.util.getCopy(argRequestDict) #fi myRequestStatus = self.util.getCopy(self.globaL._Global__RequestStatus) self.myModuleLogger.debug('Argument [{arg}] received'.format(arg=myMainArgData)) ''' validating arguments ''' myArgKey = ['Auth'] myArgValidation, myMissingKeys, myArgValMessage = \ self.util.valRequiredArg(myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues(myArgValMessage) #fi # will check either Main/Address/Contact/Settings information is passed for update #{'a','d'} <= set(a), need to fix this if not(any (block in myMainArgData.keys() for block in ['Main','Address','Contact','Settings'])): raise com.uconnect.core.error.MissingArgumentValues(\ 'Mainarg validation error; main arg(s)[{arg}], expecting Main/Address/Contact/Settings'.\ format(arg=myMainArgData.keys())) ''' commenting below code, we will get the entityid from AUTH will overwrite EntityType and EntityId if passed in Auth dictionary. This is to ensure that Auth key must belong to this Member myMainArgData['Auth'] = self.sec._Security__updateAuthEntity( {'Auth':myMainArgData['Auth'],'EntityType':self.global._Global__member,'EntityId':myMainArgData['_id']}) ''' ''' validating auth args ''' if (myMainArgData['Auth']['EntityType'] != self.globaL._Global__member): raise com.uconnect.core.error.MissingArgumentValues('Auth Arg validation error; entitytype key must be "Member"') #fi ''' Validate auth key for this request''' if not (self.sec._Security__isValidAuthentication(myMainArgData['Auth'])): #print(self.util.whoAmI()) raise com.uconnect.core.error.InvalidAuthKey('Invalid Auth Key [{auth}] for this request [{me}]'. format(auth=myMainArgData['Auth'], me=self.myClass+'.'+self.util.whoAmI())) #fi #we need to find the block which is beieng changed in Member collection dcoument if 'Main' in myMainArgData and myMainArgData['Main']: self.myModuleLogger.debug('Got Main[{main}] information which changed'.format(main=myMainArgData['Main'])) myUpdateResult = self.member._Member__updateMemberMain(myMainArgData) #print('MainUpdateResult',myUpdateResult,myMainArgData) #fi if 'Address' in myMainArgData and myMainArgData['Address']: #print('In Address') self.myModuleLogger.debug('Got Address[{address}] information which changed'.format(address=myMainArgData['Address'])) myUpdateResult = self.member._Member__updateMemberAddress(myMainArgData) #fi if 'Contact' in myMainArgData and myMainArgData['Contact']: #print('In Contact') self.myModuleLogger.debug('Got Contact[{contact}] information which changed'.format(contact=myMainArgData['Contact'])) myUpdateResult = self.member._Member__updateMemberContact(myMainArgData) #fi # rebuilding tag and recording this activity self.myModuleLogger.info('Updating Tag for member [{member}]' .format(member=myMainArgData['Auth']['EntityId'])) myTagUpdateResult = self.member._Member__updateMemberTag({'_id':myMainArgData['Auth']['EntityId']}) #record this activity self.activity._Activity__logActivity(self.util.buildActivityArg( myMainArgData['Auth']['EntityId'],self.globaL._Global__member,self.globaL._Global__External,'Member [{member}] detail [{change}] changed'. format(member=myMainArgData['Auth']['EntityId'], change=myMainArgData), myMainArgData['Auth'])) myRequestStatus = self.util.getRequestStatus(self.globaL._Global__Success) ''' get all the information of a member ''' myMemberDetailResults = self.getAMemberDetail({'ResponseMode':self.globaL._Global__InternalRequest,'Auth':myMainArgData['Auth']}) #print(myMemberDetailResults) myResponse = self.util.buildResponseData(myMainArgData['ResponseMode'], myRequestStatus, 'Find', myMemberDetailResults) return myResponse except Exception as err: myRequestStatus = self.util.extractLogError() myResponse = self.util.buildResponseData(myMainArgData['ResponseMode'], myRequestStatus, 'Error') return myResponse def updateMemberSettings(self,argRequestDict): pass def UpdateConnectionDetails(self, argRequestDict): ''' Description: UpdateConnectionDetails (Only Invitee can accept the connection) Requestor --> _id Invitee --> []) Action --> Invite/Remove/Accept/Reject/Remove Requestor: Invite/Remove Invitee: Accept/Reject/Remove argRequestDict: Json/Dict; Following key name is expected in this dict/json object {'MainArg': {'_id':'','Connections':[{'MemberId':'','Actions':''}],'Auth':'','ResponseMode'}} usage: <UpdateConnectionDetails(<argReqJsonDict>) Return: Json object ''' try: myMainArgData = self.util.getCopy(argRequestDict)['MainArg'] self.myModuleLogger.debug('Argument [{arg}] received'.format(arg=argRequestDict)) myConnectionResult = self.globaL._Global__False myActivityDetails = '' myRequestStatus = self.util.getCopy(self.globaL._Global__RequestStatus) # validating arguments myArgKey = ['UpdateConnections','Auth','ResponseMode'] myConnectionArgs = myMainArgData['UpdateConnections'] myArgValidation, myMissingKeys, myArgValMessage = \ self.util.valRequiredArg(myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues(myArgValMessage) #fi # if connection is passed as dict, converting to list if not(self.util.isList(myConnectionArgs)): myConnectionArgs = [myConnectionArgs] # we might get more than one connection request for myConnections in myConnectionArgs: myArgKey = ['Id','Type','Action'] if myConnections['Action'] not in self.globaL._Global__Connection_Action: raise com.uconnect.core.error.MissingArgumentValues('Arg validation error, Action must be one of the value in[{action}]'.format(action=self.globaL._Global__Connection_Action)) #fi myArgValidationResults = self.util.valRequiredArg(myConnections, myArgKey) myArgValidation = self.util.extractValFromTuple(myArgValidationResults,0) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues(\ 'Mainarg validation error; main arg(s)[{arg}], missing/empty key(s)[{key}]'.\ format(arg=myConnections.keys(), key=self.util.extractValFromTuple(myArgValidationResults,1))) #fi if (myConnections['Action'] == 'Favorite') and ('Favorite' not in myConnections): raise com.uconnect.core.error.MissingArgumentValues(\ 'Mainarg validation error; missing "Favorite" key') #fi if (myConnections['Action'] == 'Blocked') and ('Blocked' not in myConnections): raise com.uconnect.core.error.MissingArgumentValues(\ 'Mainarg validation error; missing "Blocked" key') #fi #end for loop ''' commenting out below code as its not needed, we will pick entity id from AUTH will overwrite EntityType and EntityId if passed in Auth dictionary. This is to ensure that Auth key must belong to this Member myMainArgData['Auth'] = self.sec._Security__updateAuthEntity( {'Auth':myMainArgData['Auth'],'EntityType':self.global._Global__member,'EntityId':myMainArgData['_id']}) ''' if (myMainArgData['Auth']['EntityType'] != self.globaL._Global__member): raise com.uconnect.core.error.MissingArgumentValues('Auth Arg validation error; entitytype key must be "Member"') #fi ''' Validate auth key for this request''' if not (self.sec._Security__isValidAuthentication(myMainArgData['Auth'])): raise com.uconnect.core.error.InvalidAuthKey('Invalid Auth Key [{auth}] for this request [{me}]'. format(auth=myMainArgData['Auth'], me=self.myClass+'.'+self.util.whoAmI())) #fi # lets perform action for myConnections in myConnectionArgs: myConnectionArgData = {'_id':myMainArgData['Auth']['EntityId'],'Type':self.globaL._Global__member, 'ConnectionId': myConnections['Id'], 'ConnectionType': myConnections['Type']} # we need to populate favorite and block dict as well #print('processing connection request [{request}]'.format(request=myConnectionArgData)) if myConnections['Action'] == self.globaL._Global__Connection_Action_Invite: myConnectionResults = self.conn._Connections__AddAConnection(myConnectionArgData) myActivityDetails = 'Member [{member}] added [{conn}] as a connection '.\ format(member=myMainArgData['Auth']['EntityId'], conn=myConnectionArgData['ConnectionType'] + ' ' + \ str(myConnectionArgData['ConnectionId'])) elif myConnections['Action'] == self.globaL._Global__Connection_Action_Accepted: myConnectionResults = self.conn._Connections__acceptInvitation(myConnectionArgData) myActivityDetails = 'Member [{member}] accepted connection request from [{conn}]'.\ format(member=myMainArgData['Auth']['EntityId'], conn=myConnectionArgData['ConnectionType'] + ' ' + \ str(myConnectionArgData['ConnectionId'])) elif myConnections['Action'] == self.globaL._Global__Connection_Action_Rejected: myConnectionResults = self.conn._Connections__rejectInvitation(myConnectionArgData) myActivityDetails = 'Member [{member}] rejected connection request from [{conn}]'.\ format(member=myMainArgData['Auth']['EntityId'], conn=myConnectionArgData['ConnectionType'] + ' ' + \ str(myConnectionArgData['ConnectionId'])) elif myConnections['Action'] == self.globaL._Global__Connection_Action_Removed: myConnectionResults = self.conn._Connections__removeConnection(myConnectionArgData) myActivityDetails = 'Member [{member}] removed connection from [{conn}]'.\ format(member=myMainArgData['Auth']['EntityId'], conn=myConnectionArgData['ConnectionType'] + ' ' + \ str(myConnectionArgData['ConnectionId'])) elif myConnections['Action'] == self.globaL._Global__Connection_Action_Favorite: #print('Fav',myConnections) myConnectionArgData.update({'Favorite':myConnections['Favorite']}) myConnectionResults = self.conn._Connections__favoriteConnection(myConnectionArgData) myActivityDetails = 'Member [{member}] updated favorite attribute of connection [{conn}]'.\ format(member=myMainArgData['Auth']['EntityId'], conn=myConnectionArgData['ConnectionType'] + ' ' + \ str(myConnectionArgData['ConnectionId'])) elif myConnections['Action'] == self.globaL._Global__Connection_Action_Block: myConnectionArgData.update({'Blocked':myConnections['Blocked']}) myConnectionResults = self.conn._Connections__blockConnection(myConnectionArgData) myActivityDetails = 'Member [{member}] updated block attribute of connection [{conn}]'.\ format(member=myMainArgData['Auth']['EntityId'], conn=myConnectionArgData['ConnectionType'] + ' ' + \ str(myConnectionArgData['ConnectionId'])) #fi #print('in BPS result',myConnectionResults) if myConnectionResults.get('Status') == self.globaL._Global__Success: ''' recording activity ''' myActivityDetails = 'Success,' + myActivityDetails myRequestStatus = self.util.getRequestStatus(self.globaL._Global__Success) else: myActivityDetails = 'UnSuccess: ' + myActivityDetails myRequestStatus = self.util.getRequestStatus(self.globaL._Global__UnSuccess,myConnectionResults.get('Message')) #print('reqStatus',myRequestStatus) #fi self.myModuleLogger.info(myActivityDetails) # end for loop ''' preparing response; get all connection member details for this member ''' myResponseArgData = {'ConnectionType':'Member','ResponseMode': self.globaL._Global__InternalRequest,'Auth':myMainArgData['Auth']} myResponseData = self.getAMemberConnections(myResponseArgData) myResponse = self.util.buildResponseData(myMainArgData['ResponseMode'],myRequestStatus,'Find',myResponseData) return myResponse except Exception as err: myRequestStatus = self.util.extractLogError() myResponse = self.util.buildResponseData(myMainArgData['ResponseMode'], myRequestStatus, 'Error') return myResponse # ends ExecConnectionAction def getAMemberDetail(self,argRequestDict): ''' Description: Find a member details argRequestDict: Json/Dict; Following key name is expected in this dict/json object {'MemberId','Auth','ResponseMode'} usage: <getAMemberDetail(<argReqJsonDict>) Return: Json object ''' # we need to check which arguments are passed; valid argument is Phone/Email/LastName + FirstName #print (argRequestDict) ''' frollowing import is placed here; this is to avoid error while import module in each other ''' try: #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass) self.myModuleLogger.debug('Argument [{arg}] received'.format(arg=argRequestDict)) if 'MainArg' in argRequestDict: myMainArgData = self.util.getCopy(argRequestDict)['MainArg'] else: myMainArgData = self.util.getCopy(argRequestDict) #fi myArgKey = ['Auth','ResponseMode'] myRequestStatus = self.util.getCopy(self.globaL._Global__RequestStatus) myArgValidation, myMissingKeys, myArgValMessage = \ self.util.valRequiredArg(myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues(myArgValMessage) #fi if (myMainArgData['Auth']['EntityType'] != self.globaL._Global__member): raise com.uconnect.core.error.MissingArgumentValues('Auth Arg validation error; entitytype key must be "Member"') #fi ''' Validate auth key for this request''' if myMainArgData['ResponseMode'] == self.globaL._Global__InternalRequest: if not (self.sec._Security__isValAuthKeyInternal(myMainArgData['Auth'])): raise com.uconnect.core.error.InvalidAuthKey('Invalid Auth [{auth}] for this request [{me}]'. format(auth=myMainArgData['Auth'], me=self.util.whoAmI())) #fi else: if not (self.sec._Security__isValidAuthentication(myMainArgData['Auth'])): raise com.uconnect.core.error.InvalidAuthKey('Invalid Auth [{auth}] for this request [{me}]'. format(auth=myMainArgData['Auth'], me=self.util.whoAmI())) #fi #fi ''' preparing value needed to find member details''' myCriteria = {'_id':myMainArgData['Auth']['EntityId']} myFindOne = self.globaL._Global__True myProjection={"Main":1,"Address":1,"Contact":1,"Tag":1} self.myModuleLogger.info('Finding member [{member}] details'.format (member=myMainArgData['Auth']['EntityId'])) myMemberData = self.mongo.findDocument(self.globaL._Global__memberColl, myCriteria,myProjection,myFindOne) # get the connection information myConnectionArgs = {'MemberId': myMainArgData['Auth']['EntityId'], 'ConnectionType':self.globaL._Global__member,\ 'ResponseMode':self.globaL._Global__InternalRequest} myMemberConnections = self.member._Member__getAMemberConnections(myConnectionArgs) # will update connection information to current result sets, there are only one document in 'Data' if 'Data' in myMemberConnections and 'Connections' in myMemberConnections['Data']: myMemberData['Data'][0].update({'Connections':myMemberConnections['Data']['Connections']}) else: myMemberData['Data'][0].update({'Connections':[]}) #fi myRequestStatus = self.util.getRequestStatus(self.globaL._Global__Success) ''' Building response ''' myResponse = self.util.buildResponseData(myMainArgData['ResponseMode'],myRequestStatus,'Find',myMemberData) return myResponse except Exception as err: myRequestStatus = self.util.extractLogError() myResponse = self.util.buildResponseData(myMainArgData['ResponseMode'], myRequestStatus, 'Error') return myResponse def getAMemberConnections(self,argRequestDict): ''' Description: Find a member's all connections details argRequestDict: Json/Dict; Following key name is expected in this dict/json object {'Request': {'Header':{ScreenId':'','ActionId':'',Page:}, {'MainArg': {}} } usage: <getsAMemberDetail(<argReqJsonDict>) http://www.jsoneditoronline.org/?id=ae36cfdc68b1255530150d286d14bab8 ''' # we need to check which arguments are passed; valid argument is Phone/Email/LastName + FirstName #print (argRequestDict) # raise an user defined exception here try: #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass) if 'MainArg' in argRequestDict: myMainArgData = self.util.getCopy(argRequestDict)['MainArg'] else: myMainArgData = self.util.getCopy(argRequestDict) #fi self.myModuleLogger.debug('Argument [{arg}] received'.format(arg=argRequestDict)) myArgKey = ['ConnectionType','Auth','ResponseMode'] myRequestStatus = self.util.getCopy(self.globaL._Global__RequestStatus) ''' validating arguments ''' myArgValidation, myMissingKeys, myArgValMessage = \ self.util.valRequiredArg(myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues(myArgValMessage) #fi if (myMainArgData['Auth']['EntityType'] != self.globaL._Global__member): raise com.uconnect.core.error.MissingArgumentValues('Auth Arg validation error; entitytype key must be "Member"') #fi ''' Validate auth key for this request''' if myMainArgData['ResponseMode'] == self.globaL._Global__InternalRequest: if not (self.sec._Security__isValAuthKeyInternal(myMainArgData['Auth'])): raise com.uconnect.core.error.InvalidAuthKey('Invalid Auth Key [{auth}] for this request [{me}]'. format(auth=myMainArgData['Auth'], me=self.util.whoAmI())) #fi else: if not (self.sec._Security__isValidAuthentication(myMainArgData['Auth'])): raise com.uconnect.core.error.InvalidAuthKey('Invalid Auth Key [{auth}] for this request [{me}]'. format(auth=myMainArgData['Auth'], me=self.util.whoAmI())) #fi #fi ''' preparing value needed to find member connections''' self.myModuleLogger.info('Finding a members connection [{arg}]'.format(arg=myMainArgData)) ''' we need threading for following request using threading of python ''' myMemberId = myMainArgData['Auth']['EntityId'] myConnectionType = myMainArgData['ConnectionType'] ''' commenting below, this has been moved to Memebr build aggregate pipeline myAggregatePipeLine = self.member._Member__buildGetAllConnPipeline({'MemberId':myMemberId,'ConnectionType':myConnectionType}) self.myModuleLogger.debug("Pipeline [{pipeline}] will be used to execute the aggregate function") #myAggregateDict = {"aggregate":self.memberColl,"pipeline":myAggregatePipeLine,"allowDiskUse":True} #myConnectionRawData = self.mongo.ExecCommand(self.memberColl, myAggregateDict) myAggregateDict = {"aggregate":self.global._Global__memberColl,"pipeline":myAggregatePipeLine,"allowDiskUse":True} myConnectionRawData = self.mongo.ExecCommand(myAggregateDict) if self.util.isAllArgumentsValid(myConnectionRawData): myMemberConnection = {"Data":self.member._Member__buildMyConnection({'ConnectionType':self.global._Global__member,'ConnectionRawData':myConnectionRawData})} else: myMemberConnection = {} #fi ''' myMemberConnectionsArg = {'MemberId':myMemberId,'ConnectionType':myConnectionType,\ 'ResponseMode':self.globaL._Global__InternalRequest} myMemberConnection = self.member._Member__getAMemberConnections(myMemberConnectionsArg) myRequestStatus = self.util.getRequestStatus(self.globaL._Global__Success) myResponse = self.util.buildResponseData(myMainArgData['ResponseMode'], myRequestStatus, 'Find', myMemberConnection) return myResponse except Exception as err: myRequestStatus = self.util.extractLogError() myResponse = self.util.buildResponseData(myMainArgData['ResponseMode'], myRequestStatus, 'Error') return myResponse def SearchMember(self,argRequestDict): ''' Description: Search memebr based of argument passed argRequestDict: Json/Dict; Following key name is expected in this dict/json object {'SearchCriteria','Page',Auth','ResponseMode'} usage: <SearchMember(<argReqJsonDict>) Return: Json object ''' try: #myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass) if 'MainArg' in argRequestDict: myMainArgData = self.util.getCopy(argRequestDict)['MainArg'] else: myMainArgData = self.util.getCopy(argRequestDict) #fi self.myModuleLogger.debug('Argument [{arg}] received'.format(arg=argRequestDict)) myArgKey = ['SearchCriteria','Page','Auth','ResponseMode'] myRequestStatus = self.util.getCopy(self.globaL._Global__RequestStatus) ''' validating arguments ''' myArgValidation, myMissingKeys, myArgValMessage = \ self.util.valRequiredArg(myMainArgData, myArgKey) if not (myArgValidation): raise com.uconnect.core.error.MissingArgumentValues(myArgValMessage) #fi if (myMainArgData['Auth']['EntityType'] != self.globaL._Global__member): raise com.uconnect.core.error.MissingArgumentValues('Auth Arg validation error; entitytype key must be "Member"') #fi ''' Validate auth key for this request''' if not (self.sec._Security__isValidAuthentication(myMainArgData['Auth'])): raise com.uconnect.core.error.InvalidAuthKey('Invalid Auth Key [{auth}] for this request [{me}]'. format(auth=myMainArgData['Auth'], me=self.util.whoAmI())) #fi # preparing documemt for search mySearchCriteria = myMainArgData['SearchCriteria'].upper() #print('Search',mySearchCriteria) myTextSearhDocArgDict = \ {'Collection':'Member', 'Search':"\"mySearchCriteria\"",'Projection':{'_id':1,'Main':1}, 'Limit':10, 'Skip':"0"} mySearchResults = self.mongo.SearchText(myTextSearhDocArgDict) myRequestStatus = self.util.getRequestStatus(self.globaL._Global__Success) # building response myResponse = self.util.buildResponseData(myMainArgData['ResponseMode'], myRequestStatus, 'Find', mySearchResults) return myResponse except Exception as err: myRequestStatus = self.util.extractLogError() myResponse = self.util.buildResponseData(myMainArgData['ResponseMode'], myRequestStatus, 'Error') return myResponse