Ejemplo n.º 1
0
 def manageFormData(self, formData: dict):
     """
         \n@Brief: Helper function that parses ui form for relevant data
         \n@Param: formData - data from the ui's form: {
             firstName: str,
             lastName: str,
             emailAddress: str,
             password: str,
             carrier: str,
             phoneNumber: str,
             message: str,
             task: str
         }
         \n@Note: Not all expected data in `formData` will actually exist
         \n@Returns: Processed version of `formData` (has same keys)
         With values being empty strings ("") if does not exist
     """
     # collect all form information
     expectedDict = {
         "firstName": "",
         "lastName": "",
         "emailAddress": "",
         "password": "",
         "carrier": "",
         "phoneNumber": "",
         "message": "",
         "task": ""
     }
     for key in expectedDict.keys():
         expectedDict[key] = formData[key] if utils.keyExists(
             formData, key) else ""
     return expectedDict
Ejemplo n.º 2
0
 def getPasswordFromId(self, myId: str) -> str():
     """
         \n@Param: myId - The password to find's id
         \n@Returns: The matching password (or "" if not yet set)
     """
     match = list(self.usersColl.find({"id": myId}))[0]
     actualPassword = match["password"] if utils.keyExists(
         match, "password") else ""
     return actualPassword
Ejemplo n.º 3
0
 def getUsernameById(self, myId: str) -> str():
     """
         \n@Brief: Gets the username in the database for the user with 'myId'
         \n@Param: myId - The id of the user whose username you want to set
         \n@Returns: The username belonging to the ID (empty string if not set)
     """
     match = self._getDocById(self.usersColl, myId)
     username = match["username"] if utils.keyExists(match,
                                                     "username") else ""
     return username
Ejemplo n.º 4
0
 def __checkIfUserValid(self, userDoc: dict):
     """
         \n@Brief: Helper function that checks if the 'User' obj within the document has been set and is valid
         \n@Param: userDoc - The dictionary containing the information belonging to a specific user
         \n@Return: The User object 
     """
     if utils.keyExists(userDoc, "User") and userDoc["User"] != None:
         serializedUserObj = userDoc["User"]
         userObj = self._deserializeData(serializedUserObj)
     else:
         userObj = None
     return userObj
    def getServiceType(self):
        """Helps to determine what user wants to do via terminal inputs"""
        createPrompt = lambda currKey, nextKey: f"{currKey} or {nextKey}"
        keysString = reduce(createPrompt, list(serviceTypes.keys()))
        prompt = "Type {0}".format(keysString)

        isValidType = False
        while not isValidType:
            serviceType = input(prompt).lower()
            isValidType = utils.keyExists(cls.serviceTypes, serviceType)
            # return or print error based on if entered value is valid
            if (not isValidType):   print("Please Enter a Valid Option!")
            else:                   return serviceType
    def __init__(self):
        """
            \n@Brief: This class is responsible for spinning off the email agent via it's CLI Flags4
            \n@Param: EmailAgent - Reference to EmailAgent class (cannot directly import or else get circular chain)
        """
        # prevent magic numbers for service types
        # map class functions for sending & getting emails to a dictionary's keys
        self.serviceTypes = {
            "send": self.sendText,
            "receive": self.getText,
            "None": self.sendText # if non-entered, default to sending
        }
    
        parser = argparse.ArgumentParser(description="Emailing & Texting Application CLI")
    
        ##################################################################################################################
        # contact managing group - should be exclusive (should not add & update contacts at same time)
        ##################################################################################################################
        contactManagerGroup = parser.add_argument_group(
            title="Contacts Managers",
            description="Helps to add, update, & remove contacts"
        )
        contactManagerGroup.add_argument(
            "-a", "--add-contact",
            action="store_true", # defaults to false
            required=False,
            dest="addContact",
            help="Add a contact to the contact list",
        )
        contactManagerGroup.add_argument(
            "-u", "--update-contact",
            action="store_true", # defaults to false
            required=False,
            dest="updateContact",
            help="Update a contact in the contact list",
        )

        ##################################################################################################################
        # Login Group
        # TODO: eventually add flags to specific username & password
        ##################################################################################################################
        contactManagerGroup = parser.add_argument_group(
            title="Login Helpers",
            description="Helps log in to your email account (or use default)"
        )
        # check if using default email account
        contactManagerGroup.add_argument(
            "-d", "--use-default-sender",
            action="store_true", # defaults to false
            required=False,
            dest="useDefault",
            help="If used, will login to default account that does not require user interaction",
        )

        ##################################################################################################################
        # Service Types (Send & Receiving)
        ##################################################################################################################
        serviceDest = "serviceType" # Both send & receive set their value in the args['serviceType']
        serviceGroup = parser.add_argument_group(
            title="Services",
            description="Helps to choose what you want to do",
        )
        serviceGroup.add_argument(
            "-s", "--send",
            action="store_const",
            const="send",
            dest=serviceDest,
            required=False,
            help="Send an email/text messages",
        )
        serviceGroup.add_argument(
            "-r", "--receive",
            action="store_const",
            const="receive",
            dest=serviceDest,
            required=False,
            help="Receive email/text messages",
        )

        ##################################################################################################################
        # Receipient Managers (First & Last Name)
        # If first or last name not entered, stored as None
        ##################################################################################################################
        nameMetaVar="<name>"
        receipientManagerGroup = parser.add_argument_group(
            title="Receipient",
            description="Helps choose who to send the email to",
        )
        receipientManagerGroup.add_argument(
            "-f", "--firstname",
            metavar=nameMetaVar,
            default=None,
            dest="fname",
            required=False,
            help="The receipient's firstname",
        )
        receipientManagerGroup.add_argument(
            "-l", "--lastname",
            metavar=nameMetaVar,
            default=None,
            dest="lname",
            required=False,
            help="The receipient's lastname",
        )

        ##################################################################################################################
        # Login Managers
        ##################################################################################################################
        loginManagersGroup = parser.add_argument_group(
            title="Login",
            description="Helps update login information",
        )
        loginManagersGroup.add_argument(
            "-x", "--username",
            action="store_true",
            dest="setUsername",
            required=False,
            help="Set what username (display name) when sending text messages and exit",
        )
        loginManagersGroup.add_argument(
            "-p", "--password",
            action="store_true",
            dest="setPassword",
            required=False,
            help="Set your password when logging in and exit",
        )

        # Actually Parse Flags (turn into dictionary)
        args = vars(parser.parse_args()) # converts all '-' after '--' to '_' (--add-contact -> 'add_contact')

        # use this phrase to easily add more contacts to the contact list
        # trigger EmailAgent init based on the situation (this point forward, 'self' will contain EmailAgent attributes)
        if args["addContact"]:
            super().__init__(displayContacts=True, isCommandLine=True)
            self.simpleAddContact()
            sys.exit(0)
        
        elif args["updateContact"]:
            super().__init__(displayContacts=True, isCommandLine=True)
            self.updateContactInfo()
            sys.exit(0)
        elif args["setUsername"] or args["setPassword"]:
            super().__init__(displayContacts=False, isCommandLine=True)
            self.configureLogin(overrideUsername=args["setUsername"], overridePassword=args["setPassword"])
            sys.exit(0)

        # Create a class obj for this file
        super().__init__(displayContacts=False, isCommandLine=True)

        # based on if CLI flag is used, set the default's state
        self.setDefaultState(args["useDefault"])

        # determine what the user wants to use the emailing agent for
        # dont ask if user already specified via CLI flags
        serviceType = args[serviceDest] if utils.keyExists(args, serviceDest) else self.getServiceType()

        # each function takes the email agent as first arg, and have optional for the rest
        # firstname, lastname, etc...
        selectedFn = self.serviceTypes[str(serviceType)]
        selectedFn(firstname=args['fname'], lastname=args['lname'])

        # logout
        self.logoutEmail()

        print("Closing Program")
Ejemplo n.º 7
0

if __name__ == "__main__":
    # Create all CLI Flags
    # https://docs.python.org/3/library/argparse.html
    parser = argparse.ArgumentParser(
        description="Start up a web app GUI for the emailing agent")
    parser.add_argument(
        "-p",
        "--port",
        type=str,
        required=False,
        help="The port to run the emailing web app from",
    )

    # defaults debugMode to false (only true if flag exists)
    parser.add_argument(
        "--debugMode",
        action="store_true",
        required=False,
        help="Use debug mode for development environments",
    )

    # Actually Parse Flags (turn into dictionary)
    args = vars(parser.parse_args())
    port = args["port"] if utils.keyExists(args, "port") else None
    debugMode = args["debugMode"] if utils.keyExists(args,
                                                     "debugMode") else False

    ui = WebApp(port=port, isDebug=debugMode)