Пример #1
0
    def __init__(self):
        self.util = Utility()
        self.globaL = Global()

        self.myClass = self.__class__.__name__
        self.myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                                '.' + self.myClass)
Пример #2
0
    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.member = Member()
        self.activity = Activity()

        self.myClass = self.__class__.__name__
        self.myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                                '.' + self.myClass)
Пример #3
0
    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)
Пример #4
0
    def __init__(self):
        ''' Intialization method -- Private
        Instantiating all methods & logger needed for this module
        '''

        myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                           '.MongoDB')
        myModuleLogger.debug("initializing ...")

        self.connBuild = ConnectionBuilder()
        self.util = Utility()
        self.globaL = Global()

        self.myPageSize = self.util.getMaxPageSize()
        self.myExclColl4Id = self.util.getExclColl4Id()

        self.conn = self.connBuild.buildConnection("MongoDB")
        self.myClass = self.__class__.__name__
        self.myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                                '.' + self.myClass)
Пример #5
0
class MongoDbConnection(object, metaclass=Singleton):
    '''
     MongoDbConnection class
   '''
    def __init__(self):
        myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                           '.MongoDbConnection')
        self.env = Environment()
        self.util = Utility()

    def getConnection(self):
        try:
            myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                               '.MongoDbConnection')
            myModuleLogger.debug("Reading MONGO_URI details ...")
            myEnvironment = self.env.getCurrentEnvironment()
            mongoDbEnvDetail = self.env.getEnvironmentDetails(myEnvironment)
            mongoDbMongoURI = mongoDbEnvDetail['MongoUri']
            mongoDbDBName = mongoDbEnvDetail['MongoDBName']

            myModuleLogger.debug(" MONGO_URI details [{mongoUri}]".format(
                mongoUri=mongoDbMongoURI))
            myModuleLogger.debug(
                " MongoDb Name [{mongoDB}]".format(mongoDB=mongoDbDBName))

            myMongoClient = MongoClient(mongoDbMongoURI)
            myMongoConn = myMongoClient.get_database(mongoDbDBName)

            myModuleLogger.debug(" MongoDb Connection [{mongoConn}]".format(
                mongoConn=myMongoConn))

            myLogger.info(myMongoConn)
            return myMongoConn

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            raise
Пример #6
0
class Group(object, metaclass=Singleton):
    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.member = Member()
        self.activity = Activity()

        self.myClass = self.__class__.__name__
        self.myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                                '.' + self.myClass)

    def __buildInitGroupData(self, argRequestDict):

        #argMainDict,argAddressDict,argContactDict
        try:
            # Preparing document:

            #self.myModuleLogger = logging.getLogger('uConnect.' +str(__name__) + '.' + self.myClass)
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=argRequestDict))

            myMainArgData = self.util.getCopy(argRequestDict)
            ''' validating arguments '''
            myArgKey = ['GroupName', 'OwnerMemberId']
            myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg(
                myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi

            myInitGroupData = self.util.getTemplateCopy(
                self.globaL._Global__group)
            myInitGroupData['Main']['GroupName'] = myMainArgData['GroupName']
            myInitGroupData['Main']['OwnerMemberId'] = myMainArgData[
                'OwnerMemberId']
            myGroupId = self.mongo.genKeyForCollection(
                self.globaL._Global__groupColl)
            myInitGroupData['_id'] = myGroupId
            ''' build initial history data '''
            myInitGroupData[
                self.globaL.
                _Global__HistoryColumn] = self.util.buildInitHistData()
            self.myModuleLogger.info(
                'Data [{arg}] returned'.format(arg=myInitGroupData))

            return myInitGroupData

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            raise

    #__buildInitGroupData Ends here

    def __buildGetAllGroupMemberPipeline(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 = ['GroupId']
            ''' validating arguments '''
            myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg(
                myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)

            myGroupId = myMainArgData['GroupId']

            self.myModuleLogger.debug(
                'Building pipeline for aggregate function, for retrieving group member information'
            )

            myFromCollection = self.globaL._Global__memberColl
            myPipeLine = [{
                "$match": {
                    "_id": myGroupId
                }
            }, {
                "$unwind": {
                    "path": "$Participants",
                    "preserveNullAndEmptyArrays": True
                }
            }, {
                "$lookup": {
                    "from": "Member",
                    "localField": "Participants.MemberId",
                    "foreignField": "_id",
                    "as": "Participants"
                }
            }, {
                "$project": {
                    "_id": 1,
                    "Main": 1,
                    "Participants._id": 1,
                    "Participants.Main": 1
                }
            }, {
                "$sort": {
                    "Participants.Main.LastName": 1
                }
            }]
            #fi
            myRequestStatus = self.util.getRequestStatus(
                self.globaL._Global__Success)
            myRequestStatus.update({'Data': myPipeLine})
            #print(myRequestStatus)
            return myRequestStatus

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            return myRequestStatus

    #__buildGetAllConnPipeline Ends here

    def __formatParticipantsData(self, argRequestDict):
        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)

            myAllParticipantsData = []
            for myParticipant in myMainArgData:
                # we need to make sure Participants array is not empty
                if len(myParticipant['Participants']) > 0:
                    myAllParticipantsData.append(\
                        {'MemberId':myParticipant['Participants'][0]['_id'],'Main':myParticipant['Participants'][0]['Main']})
                #fi
            myResponse = {
                '_id': myMainArgData[0]['_id'],
                'Main': myMainArgData[0]['Main'],
                'Participants': myAllParticipantsData
            }
            return myResponse
        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            # we would return error in main
            return {'Main': myRequestStatus}

    def __isValidGroupForMember(self, argRequestDict):
        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)

            myArgKey = ['MemberId', 'GroupId']
            myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg(
                myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi
            myCriteria = {
                '_id': myMainArgData['GroupId'],
                'Main.OwnerMemberId': myMainArgData['MemberId']
            }
            myGroupCount = self.mongo.findTotDocuments(
                self.globaL._Global__groupColl, myCriteria)
            if myGroupCount == 0:
                return self.globaL._Global__False
            else:
                return self.globaL._Global__True
            return myResponse
        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            # we would return error in main
            return self.globaL._Global__Error

    def __createAMemGroup(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']
            myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg(
                myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi

            myArgKey = ['GroupName', 'OwnerMemberId']
            myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg(
                myMainArgData['Main'], myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi

            # validating memberid (owner of this group)
            myMemberValArg = {
                '_id': myMainArgData['Main']['OwnerMemberId'],
                'ResponseMode': self.globaL._Global__InternalRequest
            }
            self.myModuleLogger.debug(myMemberValArg)
            if not (self.member._Member__isAValidMember(myMemberValArg)):
                raise com.uconnect.core.error.MissingArgumentValues(\
                    'Invalid member [{member}]'.format(member=myParticipant['_id']))

            # validating group name, if its already in use by this member
            myGroupNameValArg = myMainArgData['Main']
            if self.__isAMemberGroupInUse(myGroupNameValArg):
                raise com.uconnect.core.error.DuplicateGroup('Duplicate group [{group}]'.\
                    format(group=myMainArgData['Main']['GroupName']))
            #fi

            # Preparing document:
            myGroupData = self.__buildInitGroupData(myMainArgData['Main'])
            self.myModuleLogger.info(
                'Creating new Group, data [{doc}]'.format(doc=myGroupData))

            #persisting group data
            #print(myGroupData)
            myDbResult = self.mongo.InsertOneDoc(
                self.globaL._Global__groupColl, myGroupData)
            myGroupId = myDbResult['_id']
            myGroupResultStatus = self.util.getCreateStatus(myDbResult)
            self.myModuleLogger.debug(
                'Group id [{id}] created, status[{status}] '.format(
                    id=myGroupId, status=myGroupResultStatus))

            # we need to add owner of this group as a 1st participant
            if myGroupResultStatus == self.globaL._Global__Success:
                myParticipantArgData = \
                    {'_id': myGroupId, 'ResponseMode': self.globaL._Global__InternalRequest,\
                     'Participants':[{'MemberId': myMainArgData['Main']['OwnerMemberId'], 'Action': 'Add'}]}
                myDbStatus = self.__updateGroupParticipants(
                    myParticipantArgData)
                #print('Db Status',myDbStatus, myDbStatus)
                if myDbStatus['Status'] == self.globaL._Global__Success:
                    #print('Status is Success')
                    myRequestStatus = self.util.getRequestStatus(
                        self.globaL._Global__Success)
                    myRequestStatus['Data'] = {'_id': myGroupId}
                else:
                    # removing newly created group
                    self.mongo.DeleteDoc(self.globaL._Global__groupColl,
                                         {'_id': myGroupId}, False)
                    myRequestStatus = self.util.getRequestStatus(
                        self.globaL._Global__UnSuccess,
                        myDbStatus.get('Message'))
                #fi
            else:
                myRequestStatus = self.util.getRequestStatus(
                    self.globaL._Global__UnSuccess)
            #fi

            return myRequestStatus
        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            return myRequestStatus

    #end

    def __updateGroupMain(self, argRequestDict):
        '''
            Update Group attribute; only Group Name can be changed
        '''
        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=myMainArgData))

            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            myArgKey = ['_id', 'GroupName']
            ''' validating arguments '''
            myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg(
                myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi
            myCriteria = {'_id': myMainArgData['_id']}
            myGroupData = {'Main.GroupName': myMainArgData['GroupName']}
            myDbResult = self.mongo.UpdateDoc(self.globaL._Global__groupColl,
                                              myCriteria, myGroupData, 'set',
                                              False)
            if self.util.getUpdateStatus(
                    myDbResult) == self.globaL._Global__Success:
                myRequestStatus = self.util.getUpdateStatus(
                    self.globaL._Global__Success)
            else:
                myRequestStatus = self.util.getUpdateStatus(self.globaL._Global__UnSuccess,\
                    ' DB result [{result}]'.format(result=myDbResult))
            #fi
            return myRequestStatus

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            return myRequestStatus

    def __updateGroupParticipants(self, argRequestDict):
        ''' 
            Description:    updating Group participants (Add/Remove)
            argRequestDict: Json/Dict; Following key name is expected in this dict/json object
                            {'_id':'','Participants':['MemberId']}}
            usage:          <createAMemGroup(<argRequestDict>)
            Return:         Json object
            Collection:     Group: add a participant to group
        '''
        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)
            myArgKey = ['_id', 'Participants']
            ''' validating arguments '''
            myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg(
                myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi

            # Participants validation and adding to group
            if self.util.isList(myMainArgData['Participants']):
                myAllParticipantsList = myMainArgData['Participants']
            else:
                myAllParticipantsList = [myMainArgData['Participants']]
            #fi

            # adding participant to group
            myArgKey = ['MemberId', 'Action']
            myCriteria = {'_id': myMainArgData['_id']}
            # need to get the group owner information to ensure group owner is not removed from participants

            myGrouResult = self.mongo.findDocument(\
                self.globaL._Global__groupColl, myCriteria, {'Main.OwnerMemberId':1,'_id':0}, False)

            myGroupOwnerId = self.util.extr1stDocFromResultSets(
                myGrouResult)['Main']['OwnerMemberId']

            #print(myAllParticipantsList)

            for myParticipant in myAllParticipantsList:
                ''' validating Participant arguments '''
                myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg(
                    myParticipant, myArgKey)
                if not (myArgValidation):
                    raise com.uconnect.core.error.MissingArgumentValues(
                        myArgValMessage)
                #fi
                myParticipantsData = {
                    'Participants': {
                        'MemberId': myParticipant['MemberId']
                    }
                }
                myMemberValidationArg = {
                    '_id': myParticipant['MemberId'],
                    'ResponseMode': self.globaL._Global__InternalRequest
                }
                myExecuteOperation = False

                if (myParticipant['Action']
                        == 'Add') and (self.member._Member__isAValidMember(
                            myMemberValidationArg)):
                    myOperation = 'addToSet'
                    myIncrementValue = 1
                    myExecuteOperation = True
                elif (myParticipant['Action'] == 'Remove') and (
                        not (myParticipant['MemberId'] == myGroupOwnerId)):
                    myOperation = 'pull'
                    myIncrementValue = -1
                    myExecuteOperation = True
                #fi
                if myExecuteOperation:
                    myDbResult = self.mongo.UpdateDoc(
                        self.globaL._Global__groupColl, myCriteria,
                        myParticipantsData, myOperation, False)
                    if self.util.getUpdateStatus(
                            myDbResult) == self.globaL._Global__Success:
                        self.mongo.UpdateDoc(
                            self.globaL._Global__groupColl, myCriteria,
                            {'Main.TotalParticipants': myIncrementValue},
                            'inc', False)
                    #
                #
            #end for

            #building response
            myRequestStatus = self.util.getRequestStatus(
                self.globaL._Global__Success)
            return myRequestStatus
        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            return myRequestStatus

    #end

    def __isAMemberGroupInUse(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
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=myMainArgData))
            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            isGroupNameInUse = self.globaL._Global__False

            # validating arguments
            myArgKey = ['GroupName', 'OwnerMemberId']
            myArgValidation, myMissingKeys, myArgValMessage = self.util.valRequiredArg(
                myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi

            myCriteria = {
                'Main.GroupName': myMainArgData['GroupName'],
                'Main.OwnerMemberId': myMainArgData['OwnerMemberId']
            }

            if self.mongo.findTotDocuments(self.globaL._Global__groupColl,
                                           myCriteria) > 0:
                #print('group found',self.globaL._Global__groupColl,myCriteria)
                return self.globaL._Global__True
            else:
                return self.globaL._Global__False
            #fi

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            raise
Пример #7
0
class Connections(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.activity = Activity()
        self.member = Member()

        self.myClass = self.__class__.__name__
        self.myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                                '.' + self.myClass)

    def __AddAConnection(self, argRequestDict):
        ''' This mehtod is for building a fresh new connection
            usage:          <__AddMember2MemberConnection(<argReqJsonDict>)
                            MainArg['MemberId','ConnectMemberId','Auth']
            Return:         Success/UnSuccess
        '''
        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))
            ''' declaring/initializing variables '''
            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            isReqConnectionAdded = self.globaL._Global__False
            isInvConnectionAdded = self.globaL._Global__False
            isCleanUpDone = self.globaL._Global__False
            myArgKey = ['_id', 'Type', 'ConnectionId', 'ConnectionType']
            ''' validating arguments '''
            myArgValidation, myMissingKeys, myArgValMessage = \
                    self.util.valRequiredArg(myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi
            ''' validating Requestor entity
            must be a valid id and its connection can not be same '''
            if myMainArgData['Type'] == self.globaL._Global__member:
                #validating
                if myMainArgData['_id'] == myMainArgData['ConnectionId']:
                    raise com.uconnect.core.error.MissingArgumentValues(
                        'Arg validation error, Member [{member}] and it\'s Connection[{connect}] can not be same'
                        .format(member=myMainArgData['_id'],
                                connect=myMainArgData['ConnectMemberId']))
                #fi
                myMemberValidationData = {
                    '_id': myMainArgData['ConnectionId'],
                    'ResponseMode': self.globaL._Global__InternalRequest
                }
                if (not self.member._Member__isAValidMember(
                        myMemberValidationData)):
                    raise com.uconnect.core.error.MissingArgumentValues(
                        'Arg validation error, Invalid MemberId [{member}]'.
                        format(member=myMainArgData['ConnectionId']))
                #fi
                myRequestorCollection = self.globaL._Global__memberColl
                # requestor is Member and it has been validated, preparing Invitee (revese)connection which will be a member
                # connection
                myInviteeCriteria = {'_id': myMainArgData['ConnectionId']}
                myInviteeConn = self.util.getConnTemplateCopy(
                    self.globaL._Global__member)
                myInviteeConn['Id'] = myMainArgData['_id']
                myInviteeConn['Status'] = self.util.getConnStatus4Action(
                    'New Connection', 'Invitee')
                myInviteeConnData = {'Connections': myInviteeConn}

                self.myModuleLogger.debug(
                    'Invitee [{invitee}] connection document [{doc}] prepared'.
                    format(invitee=myMainArgData['ConnectionId'],
                           doc=myInviteeConn))

            elif myMainArgData['Type'] == 'Agent':
                pass
            #fi

            #validating connection id
            if myMainArgData['ConnectionType'] == self.globaL._Global__member:
                # this is a member 2 member connection
                myMemberValidationData = {
                    '_id': myMainArgData['ConnectionId'],
                    'ResponseMode': self.globaL._Global__InternalRequest
                }
                if (not self.member._Member__isAValidMember(
                        myMemberValidationData)):
                    raise com.uconnect.core.error.MissingArgumentValues(\
                        'Arg validation error, Invalid Connect MemberId [{member}]'.format(member=myMainArgData['ConnectionId'] ))
                #fi
                myInviteeCollection = self.globaL._Global__memberColl
                # Preparing Requestor connection
                myRequestorCriteria = {'_id': myMainArgData['_id']}
                myRequestorConn = self.util.getConnTemplateCopy(
                    self.globaL._Global__member)
                myRequestorConn['Id'] = myMainArgData['ConnectionId']
                myRequestorConn['Status'] = self.util.getConnStatus4Action(
                    'New Connection', 'Requestor')
                myRequestorConnData = {'Connections': myRequestorConn}

                self.myModuleLogger.debug(
                    'Requestor [{requestor}] connection document [{doc}] prepared'
                    .format(requestor=myMainArgData['_id'],
                            doc=myRequestorConn))

            elif myMainArgData['ConnectionType'] == 'Agent':
                pass
            #fi

            #persisiting requestor connection data
            myReqConnectionResult = self.mongo.UpdateDoc(
                myRequestorCollection, myRequestorCriteria,
                myRequestorConnData, 'addToSet', False)
            if self.util.getUpdateStatus(
                    myReqConnectionResult) == self.globaL._Global__Success:
                # Requestor connection created successfully
                self.myModuleLogger.debug('Requestor connection [{conn}] created successfully, result [{result}]'.
                    format(conn = myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])  + ' -> ' + myMainArgData['ConnectionType']\
                            + ' ' + str(myMainArgData['ConnectionId']), result=myReqConnectionResult))

                isReqConnectionAdded = self.globaL._Global__True

                #building invitee connection (revese of requestor)
                myInvConnectionResult = self.mongo.UpdateDoc(
                    myInviteeCollection, myInviteeCriteria, myInviteeConnData,
                    'addToSet', False)
                if self.util.getUpdateStatus(
                        myInvConnectionResult) == self.globaL._Global__Success:
                    #invitee connection created successful
                    isInvConnectionAdded = self.globaL._Global__True
                    myRequestStatus = self.util.getRequestStatus(
                        self.globaL._Global__Success)

                    # recording this successful activity; requestor
                    self.activity._Activity__logActivity(self.util.buildActivityArg( \
                        myMainArgData['_id'], myRequestorCollection,self.globaL._Global__Internal,\
                        'Requestor Connection [{conn}] created successfully'.format(conn=myMainArgData['Type'] + ' ' + \
                        str(myMainArgData['_id']) + ' --> ' + myMainArgData['ConnectionType'] + ' ' + \
                        str(myMainArgData['ConnectionId'])) ))
                    #recording this successful activity; invitee
                    self.activity._Activity__logActivity(self.util.buildActivityArg(\
                        myMainArgData['_id'],myInviteeCollection,self.globaL._Global__Internal,\
                        'Invitee Connection [{conn}] created successfully'.format(conn=myMainArgData['ConnectionType'] + ' ' + \
                        str(myMainArgData['ConnectionId']) + ' --> ' + myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])) ))
                else:
                    ''' invitee connection is not successful, remvoving requestor connection to maintain the data integrity '''
                    self.myModuleLogger.debug('Invitee connection [{conn}] creation unsuccessful, result [{result}]'.
                        format(conn = myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId'])  + ' -> ' + \
                                myMainArgData['Type'] + ' ' + str(myMainArgData['_id']), result=myInvConnectionResult))
                    ''' rolling back previous Requestor connection'''
                    self.mongo.UpdateDoc(myInviteeCollection,
                                         myRequestorCriteria,
                                         myRequestorConnData, 'pull', False)
                    isCleanUpDone = self.globaL._Global__True
                    myRequestStatus = self.util.getRequestStatus(
                        self.globaL._Global__UnSuccess,
                        'Could not build Invitee [{inv}] while performing "Add Connection" task'
                        .format(inv=myMainArgData['ConnectionId']))
                #fi
            else:
                self.myModuleLogger.debug('Requestor connection [{conn}] creation unsuccesful, result [{result}]'.
                    format(conn = myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])  + ' -> ' + myMainArgData['ConnectionType']\
                            + ' ' + str(myMainArgData['ConnectionId']), result=myReqConnectionResult))
                myRequestStatus = self.util.getRequestStatus(
                    self.globaL._Global__UnSuccess,
                    'Could not build Requestor [{req}] while performing "Add Connection" task'
                    .format(req=myMainArgData['_id']))
            #fi

            return myRequestStatus

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            if isReqConnectionAdded and (not isInvConnectionAdded) and (
                    not isCleanUpDone):
                #print(isReqConnectionAdded,isInvConnectionAdded,isCleanUpDone)
                self.mongo.UpdateDoc(self.globaL._Global__memberColl,
                                     myRequestorCriteria, myRequestorConnData,
                                     'pull', False)
            #fi
            return myRequestStatus

    #__AddMember2MemberConnection Ends here

    def __acceptInvitation(self, argRequestDict):
        ''' This method is invoked by Invitee; update the status of connection status in each other (Requestor/Invitee)'s connection list 
            usage:          <__AcceptInvitation(<argReqJsonDict>)
                            MainArg['_id','Type','ConnectionId','ConnectionType','Auth']
            Return:         Success/UnSuccess
        '''
        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))
            ''' declaring/initializing variables '''
            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            isReqConnectionAdded = self.globaL._Global__False
            isInvConnectionAdded = self.globaL._Global__False
            isCleanUpDone = self.globaL._Global__False

            if myMainArgData['Type'] == self.globaL._Global__member:
                myInviteeCollection = self.globaL._Global__memberColl
            elif myMainArgData['Type'] == self.globaL._Global__agent:
                myInviteeCollection = self.globaL._Global__agentColl
            #fi

            if myMainArgData['ConnectionType'] == self.globaL._Global__member:
                myRequestorCollection = self.globaL._Global__memberColl
            elif myMainArgData['ConnectionType'] == self.globaL._Global__agent:
                myRequestorCollection = self.globaL._Global__agentColl
            #fi
            ''' validating arguments '''
            myArgKey = ['_id', 'Type', 'ConnectionId', 'ConnectionType']
            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 (we dont need auth val since it has been already performed by BPS process,
            we need to ensure that any call to this process is from BPS process '''
            ''' we need to check if this is a valid request; is this invitation pending for this id (id is invitee)'''
            myInviValCriteria = {'_id':myMainArgData['_id'],'Connections.Id':myMainArgData['ConnectionId'],\
                                'Connections.Type': myMainArgData['ConnectionType'],\
                                'Connections.Status':self.util.getConnStatus4Action('New Connection','Invitee')}
            #print('Invitee validation',myInviValCriteria)
            if self.mongo.findTotDocuments(myInviteeCollection,
                                           myInviValCriteria) == 0:
                raise com.uconnect.core.error.MissingArgumentValues(\
                    'Invalid Request, Invitee [{invitee}] does not have any connection pending from [{requestor}]'.\
                            format( invitee=myMainArgData['Type'] + str(myMainArgData['_id']),\
                                    requestor= myMainArgData['ConnectionType'] + str(myMainArgData['ConnectionId']) ))
            #fi
            # need to validate if this connectin is in wait state
            ''' Building Invitee connection data'''
            myInviteeCriteria = {
                '_id': myMainArgData['_id'],
                'Connections.Id': myMainArgData['ConnectionId']
            }
            #                     'Connections.Type': myMainArgData['ConnectionType'],\
            #                     'Connections.Status': self.util.getConnStatus4Action('New Connection','Invitee')}
            myInviteeConnData = {
                'Connections.$.Status':
                self.util.getConnStatus4Action('Accept Connection', 'Invitee')
            }
            ''' Building Requestor connection data '''
            myRequestorCriteria = {
                '_id': myMainArgData['ConnectionId'],
                'Connections.Id': myMainArgData['_id']
            }
            #                       'Connections.Type':myMainArgData['Type'],\
            #                       'Connections.Status': self.util.getConnStatus4Action('New Connection','Requestor')}
            myRequestorConnData = {
                'Connections.$.Status':
                self.util.getConnStatus4Action('Accept Connection',
                                               'Requestor')
            }
            ''' persisitng changes in database, Updating invitee's connection status '''
            myConnectionResult = self.mongo.UpdateDoc(myInviteeCollection,
                                                      myInviteeCriteria,
                                                      myInviteeConnData, 'set',
                                                      False)
            self.myModuleLogger.debug('Invitee connection status updated, [{conn}], result [{result}] '.
                format(conn = myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])  + ' -> ' + \
                              myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId']),\
                              result=myConnectionResult))

            if self.util.getUpdateStatus(
                    myConnectionResult) == self.globaL._Global__Success:
                # Invitee connection update is successful, persisiting Requestor's connection status update
                isInvConnStatusUpdated = self.globaL._Global__True
                myConnectionResult = self.mongo.UpdateDoc(
                    myRequestorCollection, myRequestorCriteria,
                    myRequestorConnData, 'set', False)
                self.myModuleLogger.debug('Requestor connection status updated, [{conn}], result [{result}] '.
                format(conn = myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId'])  + ' -> ' + \
                              myMainArgData['Type'] + ' ' + str(myMainArgData['_id']),\
                              result=myConnectionResult))

                if self.util.getUpdateStatus(
                        myConnectionResult) == self.globaL._Global__Success:
                    ''' Requestor connection update is successful, undo Invitee connection change '''
                    isInvConnStatusUpdated = self.globaL._Global__True
                    myRequestStatus = self.util.getRequestStatus(
                        self.globaL._Global__Success)
                    # recording this successful activity; Invitee
                    self.activity._Activity__logActivity(self.util.buildActivityArg( \
                        myMainArgData['_id'], myRequestorCollection,self.globaL._Global__Internal,\
                        'Invitee accepted connection [{conn}] '.format(conn=myMainArgData['Type'] + ' ' + str(myMainArgData['_id']) + \
                        ' --> ' + myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId'])) ))
                    #recording this successful activity; invitee
                    self.activity._Activity__logActivity(self.util.buildActivityArg(\
                        myMainArgData['_id'],myInviteeCollection,self.globaL._Global__Internal,\
                        'Requestor connection [{conn}] status updated'.format(conn=myMainArgData['ConnectionType'] + ' ' + \
                        str(myMainArgData['ConnectionId']) + ' --> ' + myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])) ))

                else:
                    ''' Requestor connection update is not successful, undo Invitee connection change '''
                    self.myModuleLogger.debug(
                        'Requestor [{req}] connection update unsuccessful, results [{result}]'
                        .format(req=myMainArgData['Connectiontype'] + ' ' +
                                str(myMainArgData['ConnectionId']),
                                result=myReqConnResults))

                    myInviteeConnData = {
                        'Connections.$.Status':
                        self.util.getConnStatus4Action('New Connection',
                                                       'Invitee')
                    }
                    self.mongo.UpdateDoc(myInviteeCollection,
                                         myInviteeCriteria, myInviteeConnData,
                                         'set', False)
                    isCleanUpDone = self.globaL._Global__True
                    myRequestStatus = self.util.getRequestStatus(self.globaL._Global__UnSuccess,\
                        'Requestor [{req}] connection status [{status}] update unsuccessful'.\
                        format(req=myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId']), \
                               status=self.globaL._Global__Accepted_Req_ConnectionStatus))
                    self.myModuleLogger.debug('undo changes to Invitee\'s connection successful, result [{result}]'.\
                        format(result=myReqConnResults))
                #fi
            else:
                myRequestStatus = self.util.getRequestStatus(self.globaL._Global__UnSuccess,\
                    'Invitee [{inv}] connection status [{status}] update unsuccessful'. \
                    format(inv= myMainArgData['Type'] + ' ' + str(myMainArgData['_id']),
                            status=self.globaL._Global__Accepted_Inv_ConnectionStatus))
            #fi
            return myRequestStatus
        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            ''' we need to ensure if cleanup is required should there be an issue during failure of Invitee connection '''
            if isInvConnStatusUpdated and (not isReqConnStatusUpdated) and (
                    not isCleanUpDone):
                myInviteeConnData = {
                    'Connections.$.Status':
                    self.util.getConnStatus4Action('New Connection', 'Invitee')
                }
                self.mongo.UpdateDoc(myInviteeCollection, myInviteeCriteria,
                                     myInviteeConnData, 'set', False)
            #fi
            return myRequestStatus

    #__AcceptInvitation Ends here

    def __rejectInvitation(self, argRequestDict):
        ''' This method is invoked by Invitee; remove the connection from each other (Requestor/Invitee)'s connection list 
            usage:          <__rejectInvitation(<argReqJsonDict>)
                            MainArg['_id','Type','ConnectionId','ConnectionType','Auth']
            Return:         Success/UnSuccess
        '''
        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))
            ''' declaring/initializing variables '''
            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            isInvConnStatusRemoved = self.globaL._Global__False
            isCleanUpDone = self.globaL._Global__False

            if myMainArgData['Type'] == self.globaL._Global__member:
                myInviteeCollection = self.globaL._Global__memberColl
            elif myMainArgData['Type'] == self.globaL._Global__agent:
                myInviteeCollection = self.globaL._Global__agentColl
            #fi

            if myMainArgData['ConnectionType'] == self.globaL._Global__member:
                myRequestorCollection = self.globaL._Global__memberColl
            elif myMainArgData['ConnectionType'] == self.globaL._Global__agent:
                myRequestorCollection = self.globaL._Global__agentColl
            #fi
            ''' validating arguments '''
            myArgKey = ['_id', 'Type', 'ConnectionId', 'ConnectionType']
            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 (we dont need auth val since it has been already performed by BPS process,
            we need to ensure that any call to this process is from BPS process '''
            ''' we need to check if this is a valid request; is this invitation pending for this id (id is invitee)'''
            myInviValCriteria = {'_id':myMainArgData['_id'],'Connections.Id':myMainArgData['ConnectionId'],\
                                'Connections.Type': myMainArgData['ConnectionType'],\
                                'Connections.Status':self.util.getConnStatus4Action('New Connection','Invitee')}

            #print('Invitee validation',myInviValCriteria)
            if self.mongo.findTotDocuments(myInviteeCollection,
                                           myInviValCriteria) == 0:
                raise com.uconnect.core.error.MissingArgumentValues(\
                    'Invalid Request, Invitee [{invitee}] does not have pending connection from [{requestor}]'.\
                            format( invitee=myMainArgData['Type'] + str(myMainArgData['_id']),\
                                    requestor= myMainArgData['ConnectionType'] + str(myMainArgData['ConnectionId']) ))
            #fi
            ''' Building Invitee connection data to be removed'''
            myInviteeCriteria = {'_id':myMainArgData['_id'],'Connections.Id':myMainArgData['ConnectionId'], \
                                 'Connections.Type': myMainArgData['ConnectionType'],\
                                 'Connections.Status': self.util.getConnStatus4Action('New Connection','Invitee')}
            myInviteeConnData = {'Connections':{'Id': myMainArgData['ConnectionId'],'Type': myMainArgData['ConnectionType'],\
                                                'Status' : self.util.getConnStatus4Action('New Connection','Invitee')}}
            ''' Building Requestor connection data to be removed'''
            myRequestorCriteria = {'_id':myMainArgData['ConnectionId'], 'Connections.Id':myMainArgData['_id'],\
                                   'Connections.Type':myMainArgData['Type'],\
                                   'Connections.Status': self.util.getConnStatus4Action('New Connection','Requestor')}
            myRequestorConnData = {'Connections':\
                                        {'Id': myMainArgData['_id'],'Type': myMainArgData['Type'],\
                                         'Status' : self.util.getConnStatus4Action('New Connection','Requestor')}}
            ''' building backup data '''
            myInviteeConnBkupData = self.util.extr1stDocFromResultSets(\
                self.mongo.findDocument(myInviteeCollection,myInviteeCriteria,{'_id':1,'Connections':1},True))
            myRequestorConnBkupData = self.util.extr1stDocFromResultSets(\
                self.mongo.findDocument(myRequestorCollection,myRequestorCriteria,{'_id':1,'Connections':1},True))
            ''' persisitng changes in database, removing invitee's connection '''
            myConnectionResult = self.mongo.UpdateDoc(myInviteeCollection,
                                                      myInviteeCriteria,
                                                      myInviteeConnData,
                                                      'pull', False)

            self.myModuleLogger.debug('Invitee rejected request, connection [{conn}] removed, result [{result}] '.
                format(conn = myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])  + ' -> ' + \
                          myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId']),\
                          result=myConnectionResult))

            if self.util.getUpdateStatus(
                    myConnectionResult) == self.globaL._Global__Success:

                # Invitee's connection removed.  removing Requestor's connection
                isInvConnStatusRemoved = self.globaL._Global__True
                myConnectionResult = self.mongo.UpdateDoc(
                    myRequestorCollection, myRequestorCriteria,
                    myRequestorConnData, 'pull', False)
                self.myModuleLogger.debug('Invitee rejected request, Requestor connection [{conn}] removed, result [{result}] '.
                    format(conn = myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])  + ' -> ' + \
                              myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId']),\
                              result=myConnectionResult))

                if self.util.getUpdateStatus(
                        myConnectionResult) == self.globaL._Global__Success:

                    # Requestor connection update is successful, undo Invitee connection change
                    isInvConnStatusRemoved = self.globaL._Global__True
                    myRequestStatus = self.util.getRequestStatus(
                        self.globaL._Global__Success)

                    # recording this successful activity; Invitee
                    self.activity._Activity__logActivity(self.util.buildActivityArg( \
                        myMainArgData['_id'], myRequestorCollection,self.globaL._Global__Internal,\
                        'Invitee rejected connection [{conn}], removing this connection '.format(conn=myMainArgData['Type'] + ' ' + str(myMainArgData['_id']) + \
                        ' --> ' + myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId'])) ))

                    #recording this successful activity; invitee
                    self.activity._Activity__logActivity(self.util.buildActivityArg(\
                        myMainArgData['_id'],myInviteeCollection,self.globaL._Global__Internal,\
                        'Invitee rejected connection [{conn}], removing this connection'.format(conn=myMainArgData['ConnectionType'] + ' ' + \
                        str(myMainArgData['ConnectionId']) + ' --> ' + myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])) ))
                else:
                    ''' Requestor connection update is not successful, undo Invitee connection change '''
                    self.myModuleLogger.debug(
                        'Requestor [{req}] connection update unsuccessful, results [{result}]'
                        .format(req=myMainArgData['Connectiontype'] + ' ' +
                                str(myMainArgData['ConnectionId']),
                                result=myReqConnResults))

                    self.mongo.UpdateDoc(myInviteeCollection, myInviteeCriteria, \
                        {'Connections':{myInviteeConnBkupData['Connections'][0]}}, 'addToSet',False)

                    isCleanUpDone = self.globaL._Global__True
                    myRequestStatus = self.util.getRequestStatus(self.globaL._Global__UnSuccess,\
                        'Requestor [{req}] connection restored'.format(req=myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId']) ))

                    self.myModuleLogger.debug('undo changes to Invitee\'s connection successful, result [{result}]'.\
                        format(result=myReqConnResults))
                #fi
            else:
                myRequestStatus = self.util.getRequestStatus(self.globaL._Global__UnSuccess,\
                    'Invitee [{inv}] connection status [{status}] update unsuccessful'. \
                    format(inv= myMainArgData['Type'] + ' ' + str(myMainArgData['_id']),
                            status=self.globaL._Global__Accepted_Inv_ConnectionStatus ))
            #fi

            return myRequestStatus

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            ''' we need to ensure if cleanup is required should there be an issue during failure of Invitee connection '''
            if isInvConnStatusRemoved and (not isReqConnStatusUpdated) and (
                    not isCleanUpDone):
                myInviteeConnData = {
                    'Connections.$.Status':
                    self.util.getConnStatus4Action('New Connection', 'Invitee')
                }
                self.mongo.UpdateDoc(myInviteeCollection, myInviteeCriteria,
                                     myInviteeConnData, 'set', False)
            #fi
            return myRequestStatus

    #__rejectInvitation end here

    def __removeConnection(self, argRequestDict):
        ''' Removes the connection from each other (Requestor/Requestee)'s connection list 
            usage:          <__rejectInvitation(<argReqJsonDict>)
                            MainArg['_id','Type','ConnectionId','ConnectionType','Auth']
            Return:         Success/UnSuccess
            Requestor   --> who initiated the removal of a connection
            Requestee   --> whose connection to be removed from requestor
            Connection will be removed from Requestor/Requstee's conneciton list for each other 
        '''
        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))
            ''' declaring/initializing variables '''
            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            isRequestorConnRemoved = self.globaL._Global__False
            isRequesteeConnRemoved = self.globaL._Global__False
            isCleanUpDone = self.globaL._Global__False

            if myMainArgData['Type'] == self.globaL._Global__member:
                myRequestorCollection = self.globaL._Global__memberColl
            elif myMainArgData['Type'] == self.globaL._Global__agent:
                myRequestorCollection = self.globaL._Global__agentColl
            #fi

            if myMainArgData['ConnectionType'] == self.globaL._Global__member:
                myRequesteeCollection = self.globaL._Global__memberColl
            elif myMainArgData['ConnectionType'] == self.globaL._Global__agent:
                myRequesteeCollection = self.globaL._Global__agentColl
            #fi
            ''' validating arguments '''
            myArgKey = ['_id', 'Type', 'ConnectionId', 'ConnectionType']
            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 (we dont need auth val since it has been already performed by BPS process,
            we need to ensure that any call to this process is from BPS process '''
            ''' we need to check if this is a valid request; is this invitation pending for this id (id is invitee)'''
            myRequestorValCriteria = {'_id':myMainArgData['_id'],'Connections.Id':myMainArgData['ConnectionId'],\
                                'Connections.Type': myMainArgData['ConnectionType']}

            if self.mongo.findTotDocuments(myRequestorCollection,
                                           myRequestorValCriteria) == 0:
                raise com.uconnect.core.error.MissingArgumentValues(\
                    'Invalid Request, Requestor [{requestor}] does not have any connection from [{requestee}] to be removed'.\
                            format( requestor=myMainArgData['Type'] + str(myMainArgData['_id']),\
                                    requestee= myMainArgData['ConnectionType'] + str(myMainArgData['ConnectionId']) ))
            #fi
            ''' Building Invitee connection data to be removed'''
            myRequestorCriteria = {'_id':myMainArgData['_id'],'Connections.Id':myMainArgData['ConnectionId'], \
                                 'Connections.Type': myMainArgData['ConnectionType']}
            myRequestorConnData = {
                'Connections': {
                    'Id': myMainArgData['ConnectionId'],
                    'Type': myMainArgData['ConnectionType']
                }
            }
            ''' Building Requestor connection data to be removed'''
            myRequesteeCriteria = {'_id':myMainArgData['ConnectionId'], 'Connections.Id':myMainArgData['_id'],\
                                   'Connections.Type':myMainArgData['Type']}
            myRequesteeConnData = {
                'Connections': {
                    'Id': myMainArgData['_id'],
                    'Type': myMainArgData['Type']
                }
            }
            ''' building backup data '''
            myRequestorConnBkupData = self.util.extr1stDocFromResultSets(\
                self.mongo.findDocument(myRequestorCollection,myRequestorCriteria,{'_id':1,'Connections':1},True))
            myRequesteeConnBkupData = self.util.extr1stDocFromResultSets(\
                self.mongo.findDocument(myRequesteeCollection,myRequesteeCriteria,{'_id':1,'Connections':1},True))
            ''' persisitng changes in database, removing invitee's connection '''
            myConnectionResult = self.mongo.UpdateDoc(myRequestorCollection,
                                                      myRequestorCriteria,
                                                      myRequestorConnData,
                                                      'pull', False)

            self.myModuleLogger.debug('Requestor connection [{conn}] removed, result [{result}] '.
                format(conn = myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])  + ' -> ' + \
                          myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId']),\
                          result=myConnectionResult))

            if self.util.getUpdateStatus(
                    myConnectionResult) == self.globaL._Global__Success:

                # Requestor's connection removed.  removing Requestor's connection
                isRequestorConnRemoved = self.globaL._Global__True
                myConnectionResult = self.mongo.UpdateDoc(
                    myRequesteeCollection, myRequesteeCriteria,
                    myRequesteeConnData, 'pull', False)

                self.myModuleLogger.debug('Requestee connection [{conn}] removed, result [{result}] '.
                    format(conn = myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])  + ' -> ' + \
                              myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId']),\
                              result=myConnectionResult))

                if self.util.getUpdateStatus(
                        myConnectionResult) == self.globaL._Global__Success:
                    ''' Requestor connection update is successful, undo Requestor connection change '''
                    isRequesteeConnRemoved = self.globaL._Global__True
                    myRequestStatus = self.util.getRequestStatus(
                        self.globaL._Global__Success)

                    # recording this successful activity; Requestor
                    self.activity._Activity__logActivity(self.util.buildActivityArg( \
                        myMainArgData['_id'], myRequestorCollection,self.globaL._Global__Internal,\
                        'Requestor [{req}] removed connection [{conn}]'.\
                            format(req=myMainArgData['Type'] + ' ' + str(myMainArgData['_id']),\
                                    conn=myMainArgData['Type'] + ' ' + str(myMainArgData['_id']) + ' --> ' + \
                                    myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId'])) ))

                    #recording this successful activity; Requestee
                    self.activity._Activity__logActivity(self.util.buildActivityArg(\
                        myMainArgData['_id'],myRequesteeCollection,self.globaL._Global__Internal,\
                        'Requestor [{req}] removed connection, removing connection [{conn}] from requestee'.\
                            format(req=myMainArgData['Type'] + ' ' + str(myMainArgData['_id']), \
                                conn=myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId']) + ' --> ' + \
                                myMainArgData['Type'] + ' ' + str(myMainArgData['_id'])) ))
                else:
                    ''' Requestee connection update is not successful, undo Requestor connection change '''
                    self.myModuleLogger.debug(
                        'Requestee [{req}] connection update unsuccessful, results [{result}]'
                        .format(req=myMainArgData['Connectiontype'] + ' ' +
                                str(myMainArgData['ConnectionId']),
                                result=myReqConnResults))

                    self.mongo.UpdateDoc(myRequestorCollection, myRequestorCriteria, \
                        {'Connections':{myRequestorConnBkupData['Connections'][0]}}, 'addToSet',False)

                    isCleanUpDone = self.globaL._Global__True
                    myRequestStatus = self.util.getRequestStatus(self.globaL._Global__UnSuccess,\
                        'Requestor [{req}] connection restored'.format(req=myMainArgData['ConnectionType'] + ' ' + str(myMainArgData['ConnectionId']) ))
                    self.myModuleLogger.debug('undo changes to Requestor\'s connection successful, result [{result}]'.\
                        format(result=myReqConnResults))
                #fi
            else:
                myRequestStatus = self.util.getRequestStatus(self.globaL._Global__UnSuccess,\
                    'Requestor [{req}] connection status [{status}] update unsuccessful'. \
                    format(req= myMainArgData['Type'] + ' ' + str(myMainArgData['_id']),
                            status=self.globaL._Global__Accepted_Inv_ConnectionStatus ))
            #fi

            return myRequestStatus

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            ''' we need to ensure if cleanup is required should there be an issue during failure of Invitee connection '''
            if isRequestorConnRemoved and (not isRequesteeConnRemoved) and (
                    not isCleanUpDone):
                self.mongo.UpdateDoc(myRequestorCollection, myRequestorCriteria, \
                    {'Connections':{myRequestorConnBkupData['Connections'][0]}}, 'addToSet',False)
            #fi
            return myRequestStatus
        #__reoveConnection Ends here

    def __favoriteConnection(self, argRequestDict):
        ''' 
            Description:    Change favorite of a connection
            argRequestDict: Json/Dict; Following key name is expected in this dict/json object
            usage:          <__MarkConnectionFavorite(<argReqJsonDict>)
                            MainArg{'_id','Type','ConnectionId','ConnectionType','Favorite'}
            Return:         Json object
        '''
        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))

            # validating arguments
            myArgKey = [
                '_id', 'Type', 'ConnectionId', 'ConnectionType', 'Favorite'
            ]
            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            myArgValidationResults = self.util.valRequiredArg(
                myMainArgData, myArgKey)

            myArgValidation, myMissingKeys, myArgValMessage = \
                    self.util.valRequiredArg(myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi

            if myMainArgData['Favorite'] not in ["0", "1"]:
                raise com.uconnect.core.error.MissingArgumentValues(\
                    'Expecting favorite value in ["0","1"], got [{favorite}]'.format(favorite=myMainArgData['Favorite']))
            #fi

            if myMainArgData['Type'] == self.globaL._Global__member:
                myCollection = self.globaL._Global__memberColl
            elif myMainArgData['Type'] == self.globaL._Global__agent:
                myCollection = self.globaL._Global__agentColl
            #fi

            # validating this connection
            myValidConnectionArg = {'_id':myMainArgData['_id'], 'Connections.Id':myMainArgData['ConnectionId'], \
                                    'Connections.Type': myMainArgData['ConnectionType'],\
                                    'Connections.Status' :{'$in':['Accepted','Valid']}}
            if self.mongo.findTotDocuments(myCollection,
                                           myValidConnectionArg) == 0:
                raise com.uconnect.core.error.MissingArgumentValues('No connection found for this request [{request}]'.\
                    format( request=myMainArgData['Type'] + str(myMainArgData['_id']) + ': Connection(' + \
                        myMainArgData['ConnectionType'] + str(myMainArgData['ConnectionId']) + ')' ))
            #fi
            ''' Preparing document:    '''
            #myCriteria = {'_id':myMainArgData['_id'],'Connections.Id': myMainArgData['ConnectionId'], \
            #                'Connections.Type':myMainArgData['ConnectionType']}
            myCriteria = {
                '_id': myMainArgData['_id'],
                'Connections.Id': myMainArgData['ConnectionId']
            }
            myFavoriteData = {
                "Connections.$.Favorite": int(myMainArgData['Favorite'])
            }

            ##db.Member.update({'_id':313848,'LinkedBy.MemberId':313850},{ $set : {'LinkedBy.$.Favorite':1}})
            myMarkFavoriteStatus = self.mongo.UpdateDoc(
                myCollection, myCriteria, myFavoriteData, 'set', False)
            #print('Favorite Status:',myMarkFavoriteStatus)
            if self.util.getUpdateStatus(
                    myMarkFavoriteStatus) == self.globaL._Global__Success:
                myRequestStatus = self.util.getRequestStatus(
                    self.globaL._Global__Success)
            else:
                myRequestStatus = self.util.getRequestStatus(self.globaL._Global__UnSuccess,\
                    myMarkFavoriteStatus.get('Message'))
            #fi

            return myRequestStatus

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            return myRequestStatus
            #fi
        #__favoriteConnection Ends here

    def __blockConnection(self, argRequestDict):
        ''' 
            Description:    Change block of a connection
            argRequestDict: Json/Dict; Following key name is expected in this dict/json object
            usage:          <__blockConnection(<argReqJsonDict>)
                            MainArg{'_id','Type','ConnectionId','ConnectionType','Favorite'}
            Return:         Json object
        '''
        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))

            # validating arguments
            myArgKey = [
                '_id', 'Type', 'ConnectionId', 'ConnectionType', 'Blocked'
            ]
            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['Blocked'] not in ["0", "1"]:
                raise com.uconnect.core.error.MissingArgumentValues(\
                    'Expecting blocked value in ["0","1"], got [{block}]'.format(block=myMainArgData['Blocked']))
            #fi

            if myMainArgData['Type'] == self.globaL._Global__member:
                myCollection = self.globaL._Global__memberColl
            elif myMainArgData['Type'] == self.globaL._Global__agent:
                myCollection = self.globaL._Global__agentColl
            #fi

            # validating this connection
            myValidConnectionArg = {'_id':myMainArgData['_id'], 'Connections.Id':myMainArgData['ConnectionId'], \
                                    'Connections.Type': myMainArgData['ConnectionType'],\
                                    'Connections.Status' :{'$in':['Accepted','Valid']}}

            if self.mongo.findTotDocuments(myCollection,
                                           myValidConnectionArg) == 0:
                raise com.uconnect.core.error.MissingArgumentValues('No connection found for this request [{request}]'.\
                    format( request=myMainArgData['Type'] + str(myMainArgData['_id']) + ': Connection(' + \
                        myMainArgData['ConnectionType'] + str(myMainArgData['ConnectionId']) + ')' ))
            #fi
            ''' Preparing document:    '''
            myCriteria = {
                '_id': myMainArgData['_id'],
                'Connections.Id': myMainArgData['ConnectionId']
            }
            myFavoriteData = {
                "Connections.$.Blocked": int(myMainArgData['Blocked'])
            }

            ##db.Member.update({'_id':313848,'LinkedBy.MemberId':313850},{ $set : {'LinkedBy.$.Favorite':1}})
            myBlockedStatus = self.mongo.UpdateDoc(myCollection, myCriteria,
                                                   myFavoriteData, 'set',
                                                   False)
            #print('Blocked Status:',myBlockedStatus)
            if self.util.getUpdateStatus(
                    myBlockedStatus) == self.globaL._Global__Success:
                myRequestStatus = self.util.getRequestStatus(
                    self.globaL._Global__Success)
            else:
                myRequestStatus = self.util.getRequestStatus(self.globaL._Global__UnSuccess,\
                    myBlockStatus.get('Message'))
            #fi

            return myRequestStatus

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            return myRequestStatus
Пример #8
0
class MongoDB(object, metaclass=Singleton):
    def __init__(self):
        ''' Intialization method -- Private
        Instantiating all methods & logger needed for this module
        '''

        myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                           '.MongoDB')
        myModuleLogger.debug("initializing ...")

        self.connBuild = ConnectionBuilder()
        self.util = Utility()
        self.globaL = Global()

        self.myPageSize = self.util.getMaxPageSize()
        self.myExclColl4Id = self.util.getExclColl4Id()

        self.conn = self.connBuild.buildConnection("MongoDB")
        self.myClass = self.__class__.__name__
        self.myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                                '.' + self.myClass)

        #myModuleLogger.debug("Initialization details: conn[{myConn}], myPageSize[{myPageSize}]".format(myConn=self.conn, myPageSize=self.myPageSize))
        #myModuleLogger.debug("initialization completed")

        ## validate all the collections

    def __getRequestSummary(self, argCollection, argCriteria, argCurPage=None):
        ''' 
            Description:    This method is called internally in conjunction with other method in this class
            argCollection:  Collection name
            argCriteria:    Criteria to retrieve document(s)
            argCurPage:     Current page (optional)
            usage:          <__findDocument(<coll>,<criteria>,<curPage (optional)>)
            Return:         Dict object as request summary
        '''
        try:
            if not (self.util.isAllArgumentsValid(argCollection)):
                raise com.uconnect.core.error.MissingArgumentValues(
                    'One/All of the argument(s) [{arg}] is missing or contains null value'
                    .format(arg='(' + argCollection + ',' + str(argCriteria) +
                            ')'))

            myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                               '.MongoDB')
            myModuleLogger.debug(
                "arg(s) received: collection[{col}], criteria[{criteria}], curPage[{curPage}]"
                .format(col=argCollection,
                        criteria=argCriteria,
                        curPage=argCurPage))

            myConnectionInst = self.conn
            try:
                myDb = myConnectionInst[argCollection]
            except Exception as error:
                raise com.uconnect.core.error.InvalidCollection(
                    "Can not set collection to [{coll}], error[{error}]".
                    format(coll=argCollection, err=error.message))

            myModuleLogger.debug(
                "myDb value after assigning collection [{col}]: [{mydb}]".
                format(col=argCollection, mydb=myDb))

            myTotDocuments = myDb.find(argCriteria).count()

            if argCurPage == None:
                argCurPage = 0

            myReturnValues = self.util.findPagingValue(myTotDocuments,
                                                       self.myPageSize,
                                                       argCurPage)
            myStatus = myReturnValues[0]
            myTotPages = myReturnValues[1]
            #myDisplay = myReturnValues[2]
            ''' if total documents is 1 then total page is 1 regardless of pagesize
            if myTotDocuments <=  self.myPageSize:
                myTotPages = 1
            else:
                myTotPages = myTotDocuments / self.myPageSize 
             
            #if requested page is out of bound display message "out of bound"
            if argCurPage > myTotPages:
                myStatus = "ERROR: Out of bound page request"
                myDisplay = "0"
            else:
                myStatus = "OK"
                myDisplay = str( (argCurPage * self.myPageSize) +1 ) + " to " + str(((argCurPage * self.myPageSize) + 1) + self.myPageSize)
            '''

            # we need to reset the curpage to 1 if it was passed 0 or None

            if argCurPage == 0: argCurPage = 1

            summaryResult = {
                "TotalDocuments": myTotDocuments,
                "TotalPages": myTotPages,
                "RequestedPage": int(argCurPage),
                "PageSize": self.myPageSize,
                "Status": myStatus
            }

            myModuleLogger.debug(
                "TotDoc [{totdoc}], TotPages [{totpage}]".format(
                    totdoc=myTotDocuments, totpage=myTotPages))
            myModuleLogger.debug(
                "Summary Result [{summary}]".format(summary=summaryResult))

        except com.uconnect.core.error.MissingArgumentValues as error:
            myModuleLogger.exception(
                "MissingArgumentValues: error [{error}]".format(
                    error=error.errorMsg))
            raise error
        except com.uconnect.core.error.InvalidCollection as error:
            myModuleLogger.exception(
                "InvalidCollection: error [{error}]".format(
                    error=error.errorMsg))
            raise error
        '''
        except Exception as error:
            myModuleLogger.error("Error [{error}]".format(error=error.message))
            raise error
        '''
        return summaryResult

    def __updateKeyValue(self, argCollection, argDictDocument):
        ''' 
            Description:    Update key in dictDocument for a given collection, this is a private method
            argCollection:  Collection name
            argDictDocument:Dict documents
            usage:          <__updateKeyValue(<coll>,<DictDocument>)
            Return:         Dictionary object
        '''
        try:
            myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                               '.MongoDB')

            myModuleLogger.debug(
                "arg(s) received: collection[{col}], dictDoc[{dictDoc}]".
                format(col=argCollection, dictDoc=argDictDocument))

            ##myDb = self.conn

            myModuleLogger.debug(
                "Connection to be used [{conn}]".format(conn=self.conn))

            if not (self.util.isAllArgumentsValid(argCollection,
                                                  argDictDocument)):
                raise com.uconnect.core.error.MissingArgumentValues(
                    'One/All of the argument(s) [{arg}] is missing or contains null value'
                    .format(arg='(' + argCollection + ',' +
                            str(argDictDocument) + ')'))
            '''
            calling mongodb JS function to get the next sequence
            '''
            try:
                myKeyValue = int(
                    self.conn.system_js.getNextSequence(argCollection))
            except Exception as error:
                raise com.uconnect.core.error.MongoDBError(
                    'Error executing ({conn}).system_js.getNextSequence({col})'
                    .format(conn=self.conn, col=argCollection))
            ''' we dont need to generate the id for collection which is marked for exclusion'''
            if not (myKeyValue == None):
                # we need to use repr() for a value to be appeared as string character
                argDictDocument.update({"_id": repr(myKeyValue)})
            elif myKeyValue == None and (argCollection
                                         not in self.util.getExclColl4Id()):
                raise NullKeyValue(
                    "Null Key Value found for collection [{coll}]".format(
                        coll=argCollection))

            myModuleLogger.debug(
                "Results: dictionary document, after updating key value [{dict}]"
                .format(dict=argDictDocument))
            return argDictDocument

        except com.uconnect.core.error.MissingArgumentValues as error:
            myModuleLogger.exception(
                "MissingArgumentValues: error [{error}]".format(
                    error=error.errorMsg))
            raise error
        except com.uconnect.core.error.NullKeyValue as error:
            myModuleLogger.exception(
                "NullKeyValue: error [{error}]".format(error=error.errorMsg))
            raise error
        except com.uconnect.core.error.MongoDBError as error:
            myModuleLogger.exception(
                "c: error [{error}]".format(error=error.errorMsg))
            raise error
        except Exception as error:
            myModuleLogger.exception(
                "Error [{error}]".format(error=error.message))
            raise error

    def genKeyForCollection(self, argCollection):
        ''' 
            Description:    Generate keyId for a given collection
            argCollection:  Collection name
            usage:          <genKeyForCollection(<coll>)
            Return:         Keyid for passed collection
        '''
        try:
            myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                               '.MongoDB')

            myModuleLogger.debug(
                "arg(s) received: collection[{col}]".format(col=argCollection))

            ##myDb = self.conn

            myModuleLogger.debug(
                "Connection to be used [{conn}]".format(conn=self.conn))

            if not (self.util.isAllArgumentsValid(argCollection)):
                raise com.uconnect.core.error.MissingArgumentValues(
                    'Argument [{arg}] is missing or contains null value'.
                    format(arg='(' + argCollection + ')'))
            '''
            calling mongodb JS function to get the next sequence
            '''
            try:
                myKeyValue = int(
                    self.conn.system_js.getNextSequence(argCollection))
            except Exception as error:
                raise com.uconnect.core.error.MongoDBError(
                    'Error executing ({conn}).system_js.getNextSequence({col})'
                    .format(conn=self.conn, col=argCollection))

            if myKeyValue == None:
                raise NullKeyValue(
                    "Null Key Value found for collection [{coll}]".format(
                        coll=argCollection))

            myModuleLogger.debug(
                "Results: keyId for [{keyVal}] for collection {col}".format(
                    keyVal=myKeyValue, col=argCollection))

        except com.uconnect.core.error.MissingArgumentValues as error:
            myModuleLogger.exception(
                "MissingArgumentValues: error [{error}]".format(
                    error=error.errorMsg))
            raise error
        except com.uconnect.core.error.NullKeyValue as error:
            myModuleLogger.exception(
                "NullKeyValue: error [{error}]".format(error=error.errorMsg))
            raise error
        except com.uconnect.core.error.MongoDBError as error:
            myModuleLogger.exception(
                "c: error [{error}]".format(error=error.errorMsg))
            raise error
        except Exception as error:
            myModuleLogger.exception(
                "Error [{error}]".format(error=error.message))
            raise error

        return myKeyValue

    def findTotDocuments(self, argCollection, argCriteria=None):
        ''' 
            Description:    Find document from a collection
            argCollection:  Collection name
            argCriteria:    Criteria in dict {'criteria1' : 'value'}
            usage:          <findDocument(<coll>,<criteria (optional)>
            Return:         Number (total documents)
        '''
        try:

            myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                               '.MongoDB')
            myModuleLogger.debug(
                "arg(s) received: collection[{col}], criteria[{criteria}]".
                format(col=argCollection, criteria=argCriteria))
            myTotDocuments = 0

            if not (self.util.isAllArgumentsValid(argCollection)):
                raise com.uconnect.core.error.MissingArgumentValues(
                    'One/All of the argument(s) [{arg}] is missing or contains null value'
                    .format(arg='(' + argCollection + ')'))

            #myModuleLogger.debug("checking if collection [{coll}] exists in db [{db}]".format(coll=argCollection))

            myConnectionInst = self.conn
            try:
                myDb = myConnectionInst[argCollection]
            except Exception as error:
                raise com.uconnect.core.error.InvalidCollection(
                    "Can not set collection to [{coll}], error[{error}]".
                    format(coll=argCollection, err=error.message))

            #myModuleLogger.debug("myDb value after assigning collection [{col}]: [{mydb}]".format(col=argCollection,mydb=myDb))
            myModuleLogger.debug(
                "using connection [{conn}] to find the document criteria [{criteroa}]"
                .format(conn=myDb, criteria=argCriteria))

            myTotDocuments = myDb.find(argCriteria).count()

            myModuleLogger.debug("Total Documents [{totDocuments}]".format(
                totDocuments=myTotDocuments))
            ## need to find type of data retunned and then use for x in to put it in dict
            myModuleLogger.debug("completed, returning value")

        except com.uconnect.core.error.MissingArgumentValues as error:
            myModuleLogger.exception(
                "MissingArgumentValues: error [{error}]".format(
                    error=error.errorMsg))
            #raise error
        except com.uconnect.core.error.InvalidCollection as error:
            myModuleLogger.exception(
                "InvalidCollection: error [{error}]".format(
                    error=error.errorMsg))
            #raise error
        except Exception as error:
            myModuleLogger.exception(
                "Error [{error}]".format(error=error.message))
            #raise error
        finally:
            return myTotDocuments

    def findDocument(self,
                     argCollection,
                     argCriteria,
                     argProjection=None,
                     argFindOne=False,
                     argSort=None):
        ''' 
            Description:    Find document from a collection without any paging and sort
            argCollection:  Collection name
            argCriteria:    Criteria to retrieve document(s)
            argProjection:  Column which need to be projected/returned
            argFindOne:     Find only one document 
            usage:          <findDocument(<coll>,<criteria>,<projection>, <True/False>)
            Return:         List
        '''

        try:
            myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                               '.MongoDB')
            myModuleLogger.debug(
                "arg(s) received: collection[{col}], criteria[{criteria}], projection[{proj}], findOne[{findone}]"
                .format(col=argCollection,
                        criteria=argCriteria,
                        proj=argProjection,
                        findone=argFindOne))

            if not (self.util.isAllArgumentsValid(argCollection, argCriteria)):
                raise com.uconnect.core.error.MissingArgumentValues(
                    'One/All of the argument(s) [{arg}] is missing or contains null value'
                    .format(arg='(' + argCollection + ',' + str(argCriteria) +
                            ')'))

            myConnectionInst = self.conn
            try:
                myDb = myConnectionInst[argCollection]
            except Exception as error:
                raise com.uconnect.core.error.InvalidCollection(
                    "Can not set collection to [{coll}], error[{error}]".
                    format(coll=argCollection, err=error.message))

            myData = []

            if not argProjection: argProjection = None

            if (argSort == None) or (not isinstance(argSort, list)):
                argSort = [("_id", 1)]

            #print('in mongodb, sort:', argSort)
            #myModuleLogger.debug("arg(s) used for finding document: collection[{col}], criteria[{criteria}], projection[{proj}], findOne[{findone}], sort[{sort}]".
            #    format(col=argCollection,criteria=argCriteria, proj=argProjection,findone=argFindOne, sort=argSort))

            myModuleLogger.debug("Arguments [{arg}] will be used for fetching data".\
                format(arg= ''.join([str(myDb), '-', argCollection, '-', str(argCriteria), '-', str(argProjection), '-', str(argFindOne), '-', str(argSort)] )))

            mySummary = (self.__getRequestSummary(argCollection, argCriteria))

            if argFindOne:
                myData = myDb.find_one(argCriteria, argProjection)
                if (myData == None):
                    myData = []
                else:
                    myData = [myData]
            else:
                for data in myDb.find(argCriteria,
                                      argProjection).sort(argSort):
                    myData.append(data)

            myResults = {"Summary": mySummary, "Data": myData}

            myModuleLogger.debug("Document [{data}] type[{type}] ".format(
                data=myResults, type=type(myResults)))
            myModuleLogger.debug("completed, returning document")

            return myResults

        except com.uconnect.core.error.MissingArgumentValues as error:
            myModuleLogger.exception(
                "MissingArgumentValues: error [{error}]".format(
                    error=error.errorMsg))
            raise error
        except com.uconnect.core.error.InvalidCollection as error:
            myModuleLogger.exception(
                "InvalidCollection: error [{error}]".format(
                    error=error.errorMsg))
            raise error
        except Exception as error:
            myErrorMessage = self.util.extractLogError()
            myModuleLogger.exception(
                "Error [{error}]".format(error=error.message))
            raise error

    def findAllDocuments4Page(self,
                              argCollection,
                              argCriteria=None,
                              argProjection=None,
                              argPage=None,
                              argSort=None):
        ''' 
            Description:    Find all documents from a collection with paging and sort
            argCollection:  Collection name
            argCriteria:    Criteria to retrieve document(s)
            argProjection:  Column which need to be projected/returned
            argPage:        Page# which need to be returned            
            argSort:        Sort arguments, defaults to none 
            usage:          <findDocument(<coll>,<criteria>,<projection>, <True/False>)
            Return:         List
        '''

        try:
            #print ("Collection",argCollection)
            myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                               '.MongoDB')
            myModuleLogger.debug(
                "args received: collection[{coll}], page[{page}], sort[{sort}]"
                .format(coll=argCollection, page=argPage, sort=argSort))

            if not (self.util.isAllArgumentsValid(argCollection)):
                raise com.uconnect.core.error.MissingArgumentValues(
                    'One/All of the argument(s) [{arg}] is missing or contains null value'
                    .format(arg='(' + argCollection + ')'))

            myConnectionInst = self.conn
            try:
                myDb = myConnectionInst[argCollection]
            except Exception as error:
                raise com.uconnect.core.error.InvalidCollection(
                    "Can not set collection to [{coll}], error[{error}]".
                    format(coll=argCollection, err=error.message))

            myData = []

            if argProjection:
                if len(argProjection) == 0: argProjection = None
            ''' 
                Sort value in pymongo should be in list not dictionary 
                .sort([('field',1),('field',-1)])
            '''
            if (argPage == None): argPage = 0
            if (argSort == None) or (not isinstance(argSort, list)):
                argSort = [("_id", 1)]

            if not (self.util.isList(argSort)):
                raise com.uconnect.core.error.NotListValue(
                    "Sort argument passed [{sort}] is not list value (expecting list)"
                    .format(sort=argSort))

            skipPage = int(argPage) * (self.myPageSize)
            mySummary = (self.__getRequestSummary(argCollection, argCriteria,
                                                  int(argPage)))

            myModuleLogger.debug(
                "arg passed to MongoDB: db[{db}].({criteria}).skip({skipPage}).limit({limit}).sort({sort})]"
                .format(db=myDb,
                        criteria=argCriteria,
                        skipPage=skipPage,
                        limit=self.myPageSize,
                        sort=argSort))

            for data in myDb.find(argCriteria,
                                  argProjection).sort(argSort).limit(
                                      self.myPageSize).skip(skipPage):
                myData.append(data)

            myResults = {"Summary": mySummary, "Data": myData}
            myModuleLogger.debug("completed, returning document(s)")

            return myResults

        except com.uconnect.core.error.MissingArgumentValues as error:
            myModuleLogger.error(
                "MissingArgumentValues: error [{error}]".format(
                    error=error.errorMsg))
            raise error
        except com.uconnect.core.error.InvalidCollection as error:
            myModuleLogger.error("InvalidCollection: error [{error}]".format(
                error=error.errorMsg))
            raise error
        except com.uconnect.core.error.NotListValue as error:
            myModuleLogger.error(
                "NotListValue: error [{error}]".format(error=error.errorMsg))
            raise error
        '''
        except Exception as error:
            myModuleLogger.error("Error [{error}]".format(error=error.message))
            raise error
        '''

    def InsertOneDoc(self, argCollection, argDocument):
        ''' 
            Description:    Insert a document in a given collection, _ID value will be overwritten
            argCollection:  Collection name
            argDocument:    Document as dict need to be inserted
            usage:          ( InsertOneDoc(<coll><document as dict>)
            <<
                we should incorporate insert many and one in single method
                need to check if multiple doc is passed
                if mutliptle doc is passed we need to generate the key for each document
                may be for future? not right now
            >>
            Return:         Dictionary (_id, status)
        '''

        try:
            myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                               '.MongoDB')
            myModuleLogger.debug(
                "args received: collection[{coll}], document[{docdict}]".
                format(coll=argCollection, docdict=argDocument))
            ''' call validation method to see if passed collection is a valid collection '''

            myConnectionInst = self.conn
            try:
                myDb = myConnectionInst[argCollection]
            except Exception as error:
                raise com.uconnect.core.error.InvalidCollection(
                    "Can not set collection to [{coll}], error[{error}]".
                    format(coll=argCollection, err=error.message))

            if not (self.util.isAllArgumentsValid(argCollection, argDocument)):
                raise com.uconnect.core.error.MissingArgumentValues(
                    'One/All of the argument(s) [{arg}] is missing or contains null value'
                    .format(arg='(' + argCollection + ',' + str(argDocument) +
                            ')'))
            ''' we need key to be generated for this collection, if not passed as argument dict '''

            myArgDocument = argDocument

            if (self.util.isKeyInDict(myArgDocument, '_id')):
                myKeyValue = myArgDocument['_id']
                #print( myKeyValue )
                if (not myKeyValue):
                    myArgDocument = self.__updateKeyValue(
                        argCollection, myArgDocument)

            myInsertOneResult = myDb.insert_one(myArgDocument)

            myModuleLogger.debug(
                "requested document inserted with [{_id}, {status}]".format(
                    _id=myInsertOneResult.inserted_id,
                    status=myInsertOneResult.acknowledged))
            myresult = {
                "_id": myInsertOneResult.inserted_id,
                "Status": myInsertOneResult.acknowledged
            }

            return myresult

        except com.uconnect.core.error.MissingArgumentValues as error:
            myModuleLogger.exception(
                "MissingArgumentValues: error [{error}]".format(
                    error=error.errorMsg))
            raise error
        except com.uconnect.core.error.InvalidCollection as error:
            myModuleLogger.exception(
                "InvalidCollection: error [{error}]".format(
                    error=error.errorMsg))
            raise error
        except Exception as error:
            myModuleLogger.exception(
                "Error [{error}]".format(error=error.message))
            raise error

    def InsertManyDoc(self, argCollection, argDocument):
        ''' 
            Description:    Insert a document in a given collection, _ID value will be overwritten
            argCollection:  Collection name
            argDocument:    Document as dict need to be inserted
            usage:          ( InsertOneDoc(<coll><document as dict>)
            Return:         (_id,status)
        '''
        try:
            myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                               '.MongoDB')
            myModuleLogger.debug(
                "args received: collection[{coll}], document[{docdict}]".
                format(coll=argCollection, docdict=argDocument))

            if not (self.util.isAllArgumentsValid(argCollection, argDocument)):
                raise com.uconnect.core.error.MissingArgumentValues(
                    'One/All of the argument(s) [{arg}] is missing or contains null value'
                    .format(arg='(' + argCollection + ',' + str(argDocument) +
                            ')'))

            myConnectionInst = self.conn
            try:
                myDb = myConnectionInst[argCollection]
            except Exception as error:
                raise com.uconnect.core.error.InvalidCollection(
                    "Can not set collection to [{coll}], error[{error}]".
                    format(coll=argCollection, err=error.message))
            ''' we need key to be generated for this collection '''
            myDictDocument = self.__updateKeyValue(argCollection, argDocument)
            ''' check how many documents are passed, if only one document passed, route the call to Insert one'''

            myInsertManyResult = myDb.insert_one(myDictDocument)

            myModuleLogger.debug(
                "requested document inserted with [{_id}, {status}]".format(
                    _id=myInsertManyResult.inserted_id,
                    status=myInsertOneResult.acknowledged))

            myresult = {
                "_id": myInsertManyResult.inserted_id,
                "status": myInsertManyResult.acknowledged
            }
            return myresult

        except com.uconnect.core.error.MissingArgumentValues as error:
            myModuleLogger.exception(
                "MissingArgumentValues: error [{error}]".format(
                    error=error.errorMsg))
            raise error
        except Exception as error:
            myModuleLogger.exception(
                "Error [{error}]".format(error=error.message))
            raise error

    def UpdateDoc(self,
                  argCollection,
                  argCriteria,
                  argUpdateValue,
                  argUpdateOperator='set',
                  argUpdateMany=False):
        ''' 
            Description:    Update document(s) in a given collection
            argCollection:  Collection name
            argCriteria:    valid criteria for documents to be updated
            argUpdateValue: Value as dict to be updated
            argUpdateOper:  Updated operator to be used ('set','inc')            
            argUpdateMany:  Update all matching documents (True/False)            
            usage:          ( UpdateDoc(<coll><criteria>,<update_value>,<update_oper>,<update_many>)
            Return:         (_id,status)
        '''
        try:

            myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                               '.MongoDB')
            myModuleLogger.debug(
                "args received: collection[{coll}], data[{data}]".format(
                    coll=argCollection, data=argUpdateValue))

            if not (self.util.isAllArgumentsValid(argCollection, argCriteria,
                                                  argUpdateValue)):
                raise com.uconnect.core.error.MissingArgumentValues(
                    'One/All of the argument(s) [{arg}] is missing or contains null value'
                    .format(arg='(' + argCollection + ',' + str(argCriteria) +
                            ',' + str(argUpdateValue) + ')'))

            myConnectionInst = self.conn

            try:
                myDb = myConnectionInst[argCollection]
            except Exception as error:
                raise com.uconnect.core.error.InvalidCollection(
                    "Can not set collection to [{coll}], error[{error}]".
                    format(coll=argCollection, err=error.message))

            if (argUpdateMany):
                myDbUpdate = myDb.update_one
            else:
                myDbUpdate = myDb.update_many

            if (argUpdateOperator == 'set'):
                updOperator = '$set'
            elif (argUpdateOperator == 'inc'):
                updOperator = '$inc'
            elif (argUpdateOperator == 'addToSet'):
                updOperator = '$addToSet'
            elif (argUpdateOperator == 'pull'):
                updOperator = '$pull'
            else:
                raise com.uconnect.core.error.InvalidOperator(
                    "Invalid operator [{oper}] passed during update".format(
                        oper=argUpdateOperator))

            myUpdateClause = {updOperator: argUpdateValue}

            myModuleLogger.debug(
                "Performing update: coll[{coll}], criteria[{criteria}], updateClause[{data}]"
                .format(coll=argCollection,
                        criteria=argCriteria,
                        data=myUpdateClause))
            try:
                myUpdatedResult = myDbUpdate(argCriteria,
                                             myUpdateClause,
                                             upsert=True)
                ## History
            except Exception as error:
                myModuleLogger.error(
                    "could not perform update request, error stack[{errStack}]"
                    .format(errStack=error))
                raise error

            myModuleLogger.debug(
                "requested document updated, matched [{matched}, modified[{modified}], acknowledged{acknowledged}]"
                .format(matched=myUpdatedResult.matched_count,
                        modified=myUpdatedResult.modified_count,
                        acknowledged=myUpdatedResult.acknowledged))
            myresult = {
                "matched": myUpdatedResult.matched_count,
                "modified": myUpdatedResult.modified_count,
                "status": myUpdatedResult.acknowledged
            }
            #print ('in mongodb',myresult)
            return myresult

        except com.uconnect.core.error.MissingArgumentValues as error:
            myModuleLogger.exception(
                "MissingArgumentValues: error [{error}]".format(
                    error=error.errorMsg))
            raise error
        except com.uconnect.core.error.InvalidCollection as error:
            myModuleLogger.exception(
                "InvalidCollection: error [{error}]".format(
                    error=error.errorMsg))
            raise error
        except Exception as error:
            myModuleLogger.exception(
                "Error [{error}]".format(error=error.message))
            raise error

    def DeleteDoc(self, argCollection, argCriteria, argDeleteMany=False):
        ''' 
            Description:    Delete document(s) in a given collection
            argCollection:  Collection name
            argCriteria:    valid criteria for documents to be updated
            argUpdateMany:  Update all matching documents (True/False)            
            usage:          ( DeleteDoc(<coll><criteria><update_many>)
            Return:         (_id,status)
        '''
        try:

            myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                               '.MongoDB')
            myModuleLogger.debug(
                "args received: collection[{coll}], document[{doc}]".format(
                    coll=argCollection, doc=argCriteria))

            if not (self.util.isAllArgumentsValid(argCollection, argCriteria)):
                raise com.uconnect.core.error.MissingArgumentValues(
                    'One/All of the argument(s) [{arg}] is missing or contains null value'
                    .format(arg='(' + argCollection + ',' + str(argCriteria) +
                            ')'))

            myConnectionInst = self.conn

            try:
                myDb = myConnectionInst[argCollection]
            except Exception as error:
                raise com.uconnect.core.error.InvalidCollection(
                    "Can not set collection to [{coll}], error[{error}]".
                    format(coll=argCollection, err=error.message))

            if (argDeleteMany):
                myDbDelete = myDb.delete_one
            else:
                myDbDelete = myDb.delete_many

            myModuleLogger.debug(
                "Deleteing document: coll[{coll}], criteria[{criteria}]".
                format(coll=argCollection, criteria=argCriteria))
            try:
                myDeletedResult = myDbDelete(argCriteria)
                ## History
            except Exception as error:
                myModuleLogger.error(
                    "could not perform delete request, error stack[{errStack}]"
                    .format(errStack=error))
                raise error

            myModuleLogger.debug(
                "requested document deleted, deleted[{deleted}], acknowledged{acknowledged}]"
                .format(deleted=myDeletedResult.deleted_count,
                        acknowledged=myDeletedResult.acknowledged))
            myresult = {
                "deleted": myDeletedResult.deleted_count,
                "status": myDeletedResult.acknowledged
            }

            return myresult

        except com.uconnect.core.error.MissingArgumentValues as error:
            myModuleLogger.exception(
                "MissingArgumentValues: error [{error}]".format(
                    error=error.errorMsg))
            raise error
        except com.uconnect.core.error.InvalidCollection as error:
            myModuleLogger.exception(
                "InvalidCollection: error [{error}]".format(
                    error=error.errorMsg))
            raise error
        except Exception as error:
            myModuleLogger.exception(
                "Error [{error}]".format(error=error.message))
            raise error

    #db.command('aggregate','member',pipeline=pipeLine, allowDiskUse=True)

    def ExecCommand(self, argCommandDict):
        ''' 
            Description:    Executes command passed as argument defined in argCommandDict
            argCollection:  argCommandDict
            usage:          ( ExecCommand(<argCommandDict>)
            Return:         (_id,status)
        '''
        try:

            myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                               '.MongoDB')
            myModuleLogger.debug(
                "args received: [{arg}]".format(arg=argCommandDict))

            if not (self.util.isAllArgumentsValid(argCommandDict)):
                raise com.uconnect.core.error.MissingArgumentValues(
                    'Argument(s) [{arg}] is missing or contains null value'.
                    format(arg='(' + argCommandDict + ')'))

            myConnectionInst = self.conn
            myDb = myConnectionInst
            '''
            try:
                myDb = myConnectionInst[argCollection]
            except Exception as error:
                raise com.uconnect.core.error.InvalidCollection("Can not set collection to [{coll}], error[{error}]".format(coll=argCollection,err=error.message))
            '''
            myModuleLogger.debug(
                "Executing document: arg[{arg}]".format(arg=argCommandDict))

            try:
                myResult = myDb.command(argCommandDict)
            except Exception as error:
                myModuleLogger.error(
                    "could not perform execute db command, error stack[{errStack}]"
                    .format(errStack=error))
                raise error

            myModuleLogger.debug(
                "db command executed, result[{result}]".format(
                    result=myResult))

            return myResult

        except com.uconnect.core.error.MissingArgumentValues as error:
            myModuleLogger.exception(
                "MissingArgumentValues: error [{error}]".format(
                    error=error.errorMsg))
            raise error
        except Exception as error:
            myModuleLogger.exception(
                "Error [{error}]".format(error=error.message))
            raise error

    def SearchText(
        self,
        argRequestDict,
    ):
        ''' 
            Description:    Executes command passed as argument defined in argCommandDict
            argCollection:  argCommandDict
            usage:          ( SearchText(<argRequestDict>)
            Return:         json
        '''
        try:

            myMainArgData = self.util.getCopy(argRequestDict)
            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)
            self.myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=myMainArgData))
            ''' validating arguments '''
            myArgKey = ['Collection', 'Search', 'Projection', 'Limit']
            myArgValidationResults = self.util.valRequiredArg(
                myMainArgData, 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=myMainArgData.keys(),
                            key=self.util.extractValFromTuple(
                                myArgValidationResults, 1)))
            #fi

            myConnectionInst = self.conn
            myDb = myConnectionInst
            if "score" not in myMainArgData["Projection"]:
                myMainArgData["Projection"].update(
                    {"score": {
                        "$meta": "textScore"
                    }})
            #find
            try:
                myDb = myConnectionInst[myMainArgData['Collection']]
            except Exception as error:
                raise com.uconnect.core.error.InvalidCollection(
                    "Can not set collection to [{coll}], error[{error}]".
                    format(coll=argCollection, err=error.message))
            #end

            self.myModuleLogger.debug(
                'Argument [{arg}] used'.format(arg=myMainArgData))
            myResult = []
            try:
                for doc in myDb.find(\
                    {"$text":{"$search":myMainArgData["Search"] }}, myMainArgData["Projection"] ).\
                        sort([('score', {'$meta': 'textScore'})]).\
                        limit(myMainArgData["Limit"]).skip(int(myMainArgData['Skip'])):
                    #myDb.find (\
                    #    {"$text": {"$search": "Anil" }}, {"_id":1,"Main":1,"score": { "$meta": "textScore" }}).\
                    #    sort([('score', {'$meta': 'textScore'})]).limit(10).skip(0):
                    myResult.append(doc)
            except Exception as error:
                self.myModuleLogger.error(
                    "could not perform execute db command, error stack[{errStack}]"
                    .format(errStack=error))
                raise error

            self.myModuleLogger.debug(
                "db command executed, result[{result}]".format(
                    result=myResult))

            return myResult

        except com.uconnect.core.error.MissingArgumentValues as error:
            self.myModuleLogger.exception(
                "MissingArgumentValues: error [{error}]".format(
                    error=error.errorMsg))
            raise error
        except Exception as error:
            self.myModuleLogger.exception(
                "Error [{error}]".format(error=error.message))
            raise error
Пример #9
0
class Activity(object, metaclass=Singleton):
    def __init__(self):
        self.util = Utility()
        self.mongo = MongoDB()
        self.globaL = Global()

        self.myClass = self.__class__.__name__

    def __buildInitActivityData(self, argRequestDict):

        try:

            myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                               '.' + self.myClass)
            myMainArgData = self.util.getCopy(argRequestDict)
            myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=myMainArgData))

            myArgKey = ['EntityId', 'EntityType', 'ActivityType', 'Activity']

            myArgValidation, myMissingKeys, myArgValMessage = \
                    self.util.valRequiredArg(myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi

            # deleting the password from Auth
            self.util.removeKeyFromDict(myMainArgData, 'Password')

            # retrieve the template
            myInitActivityLogData = self.util.getTemplateCopy(
                self.globaL._Global__activityLogColl)
            myModuleLogger.debug('ActivityLog template [{template}]'.format(
                template=myInitActivityLogData))

            myInitActivityLogData['EntityId'] = myMainArgData['EntityId']
            myInitActivityLogData['EntityType'] = myMainArgData['EntityType']
            #myInitActivityLogData['ActivityType'] = myMainArgData['ActivityType']
            myInitActivityLogData['Activity'] = myMainArgData['Activity']
            myInitActivityLogData['ActivityDate'] = datetime.datetime.utcnow()
            myInitActivityLogData['Acknowledged'] = self.globaL._Global__False
            if 'Auth' in myMainArgData:
                myInitActivityLogData['Auth'] = myMainArgData['Auth']

            #myInitActivityLogData.update({'_History' : self.util.buildInitHistData()})

            myModuleLogger.info(
                'Data [{arg}] returned'.format(arg=myInitActivityLogData))

            return myInitActivityLogData

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            raise

    def __logActivity(self, argRequestDict):
        '''
        Desccription: Log all activity for an entity
        Arguments:  [EntityId, EntityType, ActivityDetails, 'Auth']
        '''
        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

            myModuleLogger.debug(
                'Argument [{arg}] received'.format(arg=myMainArgData))

            myArgKey = ['EntityId', 'EntityType', 'ActivityType', 'Activity']
            myRequestStatus = self.util.getCopy(
                self.globaL._Global__RequestStatus)

            #print('activitylog',myMainArgData.keys(), myArgKey)
            myArgValidation, myMissingKeys, myArgValMessage = \
                    self.util.valRequiredArg(myMainArgData, myArgKey)
            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    myArgValMessage)
            #fi
            ''' valdiating authorization '''
            ''' we dont need Auth validation
            if not (self.securityInstance._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
            '''

            myActivityLogData = self.__buildInitActivityData(myMainArgData)
            myDbResult = self.mongo.InsertOneDoc(
                self.globaL._Global__activityLogColl, myActivityLogData)

            #print('Activity',myDbResult)
            ''' we need to make sure if "Data" key is in Result set, it must not be empty and must have "_id" key in it'''
            if myDbResult[
                    self.globaL.
                    _Global__StatusKey] == self.globaL._Global__TrueStatus:
                myRequestStatus = self.util.getRequestStatus(
                    self.globaL._Global__Success, None, myDbResult['_id'])
            else:
                myRequestStatus = self.util.getRequestStatus(
                    self.globaL._Global__UnSuccess,
                    'could not create acitvity log')
            #fi
            return myRequestStatus

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            raise

    def acknowledgeActivity(self, argRequesDict):
        pass

    def getActivity(self, argRequesDict):
        pass
Пример #10
0
class Factory(object):
    '''
    This is Factory class, this will execute a BO process as mapped in config/FactoryMetadata.json
    '''
    def __init__(self):
        self.util = Utility()
        self.globaL = Global()

        self.myClass = self.__class__.__name__
        self.myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                                '.' + self.myClass)

    def processRequest(self, argRequestDict):
        ''' 
            Description:    Update key in dictDocument for a given collection, this is a private method
            argCollection:  Collection name
            argDictDocument:Dict documents
            usage:          <processRequest(argRequestDict)
        '''
        try:

            self.myModuleLogger.debug(
                "arg received [{args}]".format(args=argRequestDict))
            myMainArgData = self.util.getCopy(argRequestDict)
            ''' Validating argumemt received '''
            #self.util.valBPSArguments(myMainArgData)
            myArgValidation = self.util.valBPSArguments(myMainArgData)

            if not (myArgValidation):
                raise com.uconnect.core.error.MissingArgumentValues(
                    "Arg validation error {arg}".format(arg=myMainArgData))
            #fi

            myScreenId = myMainArgData['Request']['Header']['ScreenId']
            myActionId = myMainArgData['Request']['Header']['ActionId']

            bpsProcessVal = self.__findBPSProcess(myScreenId, myActionId)

            # extracting tuple value returned from above method

            myLibrary, myClass, myMethod = bpsProcessVal
            if myLibrary and myClass and myMethod:
                self.myModuleLogger.debug(
                    "found, bps process [{bpsprocVal}]".format(
                        bpsprocVal=bpsProcessVal))
                #print('found [{lib}]'.format(lib=(myLibrary, myClass, myMethod)))
                myResponse = self.__executeBPSPRocess(myLibrary, myClass,
                                                      myMethod, myMainArgData)
                myRquestStatus = self.util.getRequestStatus(
                    self.globaL._Global__Success)
            else:
                self.myModuleLogger.debug(
                    "did not find mapped bps process, value from navigating factoty data [{bpsprocVal}]"
                    .format(bpsprocVal=bpsProcessVal))
                myRquestStatus = self.util.getRequestStatus(
                    self.globaL._Global__UnSuccess,
                    'Invalid Screen [{screen}] Action [{action}]'.format(
                        screen=myScreenId, action=myActionId))
                myResponse = self.util.buildResponseData(
                    'E', myRquestStatus, 'Error')
            #fi

            #self.myModuleLogger.debug("return value from bps process [{responseVal}]".format(responseVal=myResponse))

            return myResponse

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            myResponse = self.util.buildResponseData('E', myRequestStatus,
                                                     'Error')
            return myResponse

    def __findBPSProcess(self, argScreenId, argActionId):
        ''' 
            Description:    Update key in dictDocument for a given collection, this is a private method
            argCollection:  Collection name
            argDictDocument:Dict documents
            usage:          <__updateKeyValue(<coll>,<DictDocument>)
            Return:         library, class, method
        '''
        try:

            self.myModuleLogger.debug(
                "arg received [{screen},{action}]".format(screen=argScreenId,
                                                          action=argActionId))

            myLibrary = myClass = myMethod = ''

            myLibClassMethod = self.util.getModuleClassMethod(
                argScreenId, argActionId)
            if not (myLibClassMethod[0] == None):
                myLibrary = myLibClassMethod[0]
                myClass = myLibClassMethod[1]
                myMethod = myLibClassMethod[2]
            else:
                return None
            #fi
            return myLibrary, myClass, myMethod

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            #myResponse = self.util.buildResponseData(myMainArgData['ResponseMode'], myRequestStatus, 'Error')
            raise

    def __executeBPSPRocess(self, argLibrary, argClass, argMethod,
                            argReqJsonDict):
        ''' 
            Description:    Update key in dictDocument for a given collection, this is a private method
            argCollection:  Collection name
            argDictDocument:Dict documents
            usage:          <__updateKeyValue(<coll>,<DictDocument>)
            Return:         Return value from called objects
        '''
        try:

            self.myModuleLogger.debug(
                "arg received [{lib},{cls},{method},{args}]".format(
                    lib=argLibrary,
                    cls=argClass,
                    method=argMethod,
                    args=argReqJsonDict))
            #print('Library/Module',argLibrary,argClass, argMethod)
            myModule = importlib.import_module(argLibrary)
            myClass = getattr(myModule, argClass)
            # if singleton, get an instance else instantiate the class
            if hasattr(myModule, 'Singleton') and hasattr(myClass, 'Instance'):
                myCallableClass = myClass.Instance()
            else:
                myCallableClass = myClass()

            #print('imported')
            # get the method from this class
            myMethod = getattr(myCallableClass, argMethod)
            ''' Only MainArg need to be passed  '''
            myMainArg = {
                'MainArg': self.util.extMainArgFromReq(argReqJsonDict)
            }
            ''' need to mark that this response is external '''
            myMainArg['MainArg'].update(
                {'ResponseMode': self.globaL._Global__ExternalRequest})
            #print('Factory executing param',myMainArg)
            # execute the method
            myResults = myMethod(myMainArg)

            return (myResults)

        except Exception as err:
            myRequestStatus = self.util.extractLogError()
            #myResponse = self.util.buildResponseData(myMainArgData['ResponseMode'], myRequestStatus, 'Error')
            raise
Пример #11
0
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
Пример #12
0
 def __init__(self):
     self.util = Utility()
     self.mongo = MongoDbConnection()
Пример #13
0
 def __init__(self):
     myModuleLogger = logging.getLogger('uConnect.' + str(__name__) +
                                        '.MongoDbConnection')
     self.env = Environment()
     self.util = Utility()
Пример #14
0
 def __init__(self):
     self.util = Utility()
Пример #15
0
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
Пример #16
0
from flask import Flask, flash, session, redirect, url_for, escape, request, jsonify, json
from datetime import timedelta
from com.uconnect.core.singleton import Singleton
from com.uconnect.bps.factory import Factory
from com.uconnect.core.infra import Environment
from com.uconnect.db.mongodb import MongoDB
from com.uconnect.utility.ucUtility import Utility
from flask_cors import CORS

import logging, com.uconnect.utility.ucLogging

#'\x95\x8d\xe3\xab\x18\xc2\xc6\xeb\xd4+\x11H<\xdc\xd8m\xaf\xae0\xcfb\xdc\x84\x92\xc5\xb2\xado\x98\xc5\x08\xa9\xbb/\x95\xe9/\xda\x10\xaa\x1f\xb7k\x956SLCIj\r7v\xdbm\\\x1e\xdc\xf3M&$\xb0\xce\xdb\x18\xd6\xa3\x13\x85\xd0m\r\x1a]\xbe\xf8\xd8Q\xcf\xed\xaf\x0b\x827TB\xb7'
myLogger = logging.getLogger('uConnect')
util = Utility()
factory = Factory()

app = Flask(__name__)
CORS(app)
app.secret_key = '\x95\x8d\xe3\xab\x18\xc2\xc6\xeb\xd4+\x11H<\xdc\xd8m\xaf\xae0\xcfb\xdc\x84\x92\xc5\xb2\xado\x98\xc5\x08\xa9\xbb/\x95\xe9/\xda\x10\xaa\x1f\xb7k\x956SLCIj\r7v\xdbm\\\x1e\xdc\xf3M&$\xb0\xce\xdb\x18\xd6\xa3\x13\x85\xd0m\r\x1a]\xbe\xf8\xd8Q\xcf\xed\xaf\x0b\x827TB\xb7'
#session = {}


@app.before_request
def make_session_permanent():
    myModuleLogger = logging.getLogger('uConnect.' + str(__name__))
    myModuleLogger.debug("initializing session information ...")
    session.permanent = True
    app.permanent_session_lifetime = timedelta(minutes=5)


@app.route('/uConnect', methods=['GET', 'POST'])
Пример #17
0
import json
from com.uconnect.bps.factory import Factory
from com.uconnect.core.infra import Environment
from com.uconnect.utility.ucUtility import Utility
from com.uconnect.db.mongodb import MongoDB

myFactory = Factory.Instance()
utilityInstance = Utility.Instance()
mongodbInstance = MongoDB.Instance()

# load Member test data, you might consider emptying Member collection: db.Member.remov({})
MemberData = json.loads(
    open("c:\\app\\uconnect\\MongoDb\\json\\MemberTestData.json").read())
#MemberData = json.loads(open("c:\\app\\uconnect\\MongoDb\\json\\Temp.json").read())
for line in MemberData:
    #print (line['Main'],line['Address'],['Contact'])
    myRequest = {
        "Request": {
            "Header": {
                "ScreenId": "Registration",
                "ActionId": "RegisterEntity",
                "Page": None
            },
            "MainArg": {
                "Main": line['Main'],
                "Address": {
                    'ZipCode': str(line['Address']['ZipCode'])
                },
                "Contact": {
                    'Mobile':
                    line['Contact']['Mobile'],
Пример #18
0
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
Пример #19
0
    def __init__(self):
        self.util = Utility()
        self.mongo = MongoDB()
        self.globaL = Global()

        self.myClass = self.__class__.__name__