def sendCommentNotificationEmail(self, userToEmail, authorUser, vision, comment): '''Takes dictionary inputs''' visionUser = User.getById(vision[Vision.Key.USER_ID]) if visionUser: visionUser = visionUser.toDictionary() emailAddress = userToEmail[User.Key.EMAIL] if authorUser[User.Key.ID] == visionUser[User.Key.ID]: emailSubject = authorUser[User.Key.FULL_NAME] + \ " responded on their vision" else: emailSubject = authorUser[User.Key.FULL_NAME] + \ " responded on " + \ visionUser[User.Key.FULL_NAME] + "\'s vision" emailText = emailSubject emailHtml = render_template("email/commentNotification.html", userToEmail=userToEmail, authorUser=authorUser, visionUser=visionUser, vision=vision, comment=comment) email = { Constant.EMAIL_TO_KEY : emailAddress, Constant.EMAIL_SUBJECT_KEY : emailSubject, Constant.EMAIL_BODY_TEXT_KEY : emailText, Constant.EMAIL_BODY_HTML_KEY : emailHtml, } emailer = Emailer() emailer.sendBatch([email])
def email_loop(): threading.Timer(config.EMAIL_LOOP_INTERVAL, email_loop).start() emails = generate_email.generate_all_email() print(datetime.now().strftime("%d/%m/%Y - %H:%M:%S")) print("Emails Generated -", len(emails)) if len(emails) > 0: EmailSystem = Emailer() for email in emails: EmailSystem.send_email(email) print() else: print()
def sendWelcomeEmail(self, user): '''Takes dictionaries as input''' emailAddress = user[User.Key.EMAIL] emailSubject = "Welcome to Project Awesome!" emailText = emailSubject emailHtml = render_template("email/welcome.html", user=user) email = { Constant.EMAIL_TO_KEY : emailAddress, Constant.EMAIL_SUBJECT_KEY : emailSubject, Constant.EMAIL_BODY_TEXT_KEY : emailText, Constant.EMAIL_BODY_HTML_KEY : emailHtml, } emailer = Emailer() emailer.sendBatch([email])
def sendDailyEmails(self): ''' Send daily motivational emails, and return number of emails sent ''' #Get motivatinal picture for each user userInfo = self.__getMotivationContent() #Render Templates emailInfo = self.__generateEmails(userInfo) #Send Email emailer = Emailer() emailer.sendBatch(emailInfo) #Write to log return len(emailInfo)
def run(self): outputs = {} for handle in self.handles: if '(类型)' not in handle.keys(): raise RuntimeError('not find (类型)') handle_type: str = handle['(类型)'] if handle_type == '(输出)': outputer = GioOutputer(self.projects, self.dashboards, handle, outputs) outputer.run() elif handle_type == '(邮件)': emailer = Emailer(self.mailbox, handle, outputs) emailer.run()
def sendFollowEmail(self, follower, user): '''Takes dictionary inputs''' emailAddress = user[User.Key.EMAIL] emailSubject = follower[User.Key.FULL_NAME] + " is following you!" emailText = emailSubject emailHtml = render_template("email/follow.html", follower = follower, user = user) email = { Constant.EMAIL_TO_KEY : emailAddress, Constant.EMAIL_SUBJECT_KEY : emailSubject, Constant.EMAIL_BODY_TEXT_KEY : emailText, Constant.EMAIL_BODY_HTML_KEY : emailHtml, } emailer = Emailer() emailer.sendBatch([email])
def fetch( self ): # Get bookname and author name and send it to the scrapy module for searching and scraping global download_path bookName = self.bookNameTextbox.text() authorName = self.authorNameTextbox.text() authorName = re.split( ';|,| ', authorName) #Get the different words in the author name list authorName = [ x.lower() for x in authorName if x ] # Convert it to lower case and filter out empty strings authorName = set(authorName) # Add to set if bookName == '': self.show_error('Please provide atleast one book name') else: linkScraper = BookLinkScraper() linkScraper.begin(bookName, authorName) if linkScraper.get_list_length() == 0: self.show_error("No matches found") return prioritizer = Prioritizer() prioritizer.prioritize() downloader = DownloadLinkScraper(download_path) status = downloader.begin() status = "Success" if status == "Limit Reached": self.show_error('Download cannot be completed due to limits') elif status == "Success": Converter().convert(book_name=bookName, download_dir=download_path) Emailer().send(bookName, download_dir=download_path) Remover().remove(download_dir=download_path) self.show_message("Process Complete")
def sendVisionLikeEmail(self, user, liker, vision): '''Takes dictionary inputs''' emailAddress = user[User.Key.EMAIL] emailSubject = liker[User.Key.FULL_NAME] + " liked your vision" emailText = emailSubject emailHtml = render_template("email/vision_like.html", user = user, liker = liker, vision = vision) email = { Constant.EMAIL_TO_KEY : emailAddress, Constant.EMAIL_SUBJECT_KEY : emailSubject, Constant.EMAIL_BODY_TEXT_KEY : emailText, Constant.EMAIL_BODY_HTML_KEY : emailHtml, } emailer = Emailer() emailer.sendBatch([email])
def onRadianButton(self, event): self.spreadsheet = 0 #send spreadsheet path to Merge class myMerge = Merge(self.tc_files) #myMerge.hello() for i, v in enumerate(self.dropped_files): if self.dropped_files[i].endswith('.xlsx' or '.XLSX'): self.spreadsheet = v self.tc_files.WriteText("\n Processing Spreadsheet...") propertyList = myMerge.openFile(self.spreadsheet) #self.tc_files.WriteText("\n Creating PDFs...") myMerge.rename_files() self.tc_files.WriteText("\n Creating Emails...") myEmail = Emailer() myEmail.create_mail(propertyList) self.tc_files.WriteText("\n You're done! Don't forget to hit the clear button!")
def run(self): if len(self.handles) is 0: raise RuntimeError('未找到任务处理') for handle in self.handles: # print(handle) if len(handle) is 0: raise RuntimeError('未找到操作片段') results = {} for segment in handle: key = list(segment.keys())[0] value = list(segment.values())[0] if key == '(SELECT)': selecter = Selecter(self.databases, results, value) selecter.run() print(results) elif key == '(JOIN)': joiner = Joiner(results, value) joiner.run() print(results) elif key == '(UNION)': unioner = Unioner(results, value) unioner.run() print(results) elif key == '(ADD)': adder = Adder(results, value) minuser.run() print(results) elif key == '(MINUS)': minuser = Minuser(results, value) minuser.run() print(results) elif key == '(GROUP)': grouper = Grouper(results, value) grouper.run() print(results) elif key == '(输出)': outputer = Outputer(results, value) outputer.run() print(results) elif key == '(邮件)': emailer = Emailer(self.email, value[0], results) emailer.run()
def __init__(self, parameters=None, emailer=None): if parameters is None: parameters = TestRunnerParameters(self.cfgParser) if emailer is None: emailerParameters = EmailerParameters(self.cfgParser) emailer = Emailer(emailerParameters) self.emailer = emailer self.parameters = parameters self.experiments = []
def run(self): """ Calls everything. Execution starts here :return: -1 or 1 """ raw_json_data = QueryCowin("294").get_json_data() receiver_config = self.get_receivers_configs() for vaccine in receiver_config: responsecombiner = CombinedResponse(raw_json_data, vaccine, "Karnataka") combined_data = responsecombiner.get_combined_response() Emailer(combined_data, vaccine, receiver_config[vaccine]).send_vaccine_info()
def main(self): scrape = Scraper(self.from_ct, self.date, self.time) data = scrape.fetch_full() nj = NJParser(data[0]).parse_data() ct = CTParser(data[1]).parse_data() if self.from_ct: schedule = Scheduler(ct, nj, self.low, self.high).generate() else: schedule = Scheduler(nj, ct, self.low, self.high).generate() message = "Train schedules for " + self.date.strftime('%Y-%m-%d') Emailer(self.password, self.email, self.file).send_email(message + ":\n" + schedule, message)
def sendCommentEmail(self, authorUser, vision, comment): '''Takes dictionary inputs''' visionUser = User.getById(vision[Vision.Key.USER_ID]) if visionUser: visionUser = visionUser.toDictionaryFull() emailAddress = visionUser[User.Key.EMAIL] emailSubject = authorUser[User.Key.FULL_NAME] + " wrote on your vision" emailText = emailSubject emailHtml = render_template("email/comment.html", author = authorUser, user = visionUser, vision = vision, comment = comment) email = { Constant.EMAIL_TO_KEY : emailAddress, Constant.EMAIL_SUBJECT_KEY : emailSubject, Constant.EMAIL_BODY_TEXT_KEY : emailText, Constant.EMAIL_BODY_HTML_KEY : emailHtml, } emailer = Emailer() emailer.sendBatch([email])
def sendRepostEmail(self, user, origVision, newVision): '''Takes dictionaries as input''' origUser = User.getById(origVision['userId']) if origUser: origUser = origUser.toDictionaryFull() emailAddress = origUser[User.Key.EMAIL] emailSubject = user[User.Key.FULL_NAME] + " reposted your vision" emailText = emailSubject emailHtml = render_template("email/repost.html", origUser = origUser, origVision = origVision, user = user, vision = newVision) email = { Constant.EMAIL_TO_KEY : emailAddress, Constant.EMAIL_SUBJECT_KEY : emailSubject, Constant.EMAIL_BODY_TEXT_KEY : emailText, Constant.EMAIL_BODY_HTML_KEY : emailHtml, } emailer = Emailer() emailer.sendBatch([email])
def CheckFace(valid_output, vid_image, graph, frame_name, match_count): # run a single inference on the image and overwrite the # boxes and labels test_output = run_inference(vid_image, graph) matched_face = face_match(valid_output, test_output) if (matched_face != False): print('PASS! File ' + matched_face + ' matches ') match_count += 1 if (match_count >= 5 and match_count <= 7): print('User Checked In!') found_match = 2 if (match_count == 7): match_count = 0 Requestor().start() excemptions = ['Michael', 'Chris L'] if matched_face not in excemptions: fileName = '/home/tme/Desktop/Log/' + matched_face + str( datetime.now()) + '.png' cv2.imwrite(fileName, vid_image) emailMessage = Emailer(fileName, matched_face) emailMessage.start() else: found_match = 1 else: found_match = 3 # print('FAIL! File ' + frame_name + ' does not match ') match_count = 0 # Uncomment next line to view the image sent to the graph # vid_image = preprocess_image(vid_image) overlay_on_image(vid_image, frame_name, found_match, matched_face) return match_count
def test(): from ConfigParser import ConfigParser from ParametersParsing import EmailerParameters, GeneralParameters, Tools configFile = "Parameters.conf" parentDir = os.path.abspath( os.path.join(os.path.dirname(__file__), os.pardir)) configFile = os.path.join(parentDir, configFile) cfgParser = ConfigParser() cfgParser.read(configFile) tools = Tools(cfgParser) emailerParameters = EmailerParameters(cfgParser) generalParameters = GeneralParameters(cfgParser) solutionBuilder = SolutionBuilder(Emailer(emailerParameters)) solutionBuilder.BuildSln(generalParameters, tools)
class testSend(unittest.TestCase): def setUp(self): self.gmail_service = authenticate() self.emailer = Emailer() self.match_xls = '/Users/jjw036/Dropbox/GSA/LinkLunch/matches_04212015.xlsx' self.address_xls = '/Users/jjw036/Dropbox/GSA/LinkLunch/individual_info.xlsx' def test_template(self): template_txt = self.emailer.get_template() pdb.set_trace() test_dict = { 'match1': 'Jia Awesomepants', 'match2': 'Bruce Wayne', 'match1_email': '*****@*****.**', 'match2_email': '*****@*****.**', 'match1_dept': 'Magic', 'match2_dept': 'Crime Fighting', 'based_on': 'cheese', 'chicago': 'Y', 'which_person_chicago': 'Bruce', 'notified':'N', 'additional':'Take note that Bruce\'s batcave is located on the Chicago campus.'} new_body = self.emailer.replace_text(test_dict,template_txt) message, body = self.emailer.get_welcome_email(test_dict, new_body) message = (self.gmail_service.users().messages().send(userId="me", body=body).execute()) def test_get_matches(self): match_list = self.emailer.get_matches(self.match_xls, self.address_xls) def test_get_email(self): match_list = self.emailer.get_matches(self.match_xls, self.address_xls) email_add = self.emailer.get_email('Ivy') self.assertEquals(email_add, '*****@*****.**') def test_send(self): pass
from Emailer import Emailer from authenticate import authenticate import pdb # send it try: match_xls = '/Users/jjw036/Dropbox/GSA/LinkLunch/matches_04212015.xlsx' address_xls = '/Users/jjw036/Dropbox/GSA/LinkLunch/individual_info.xlsx' gmail_service = authenticate() emailer = Emailer() matches = emailer.get_matches(match_xls, address_xls) #parse the list of matches #matches is a list of dicts for match in matches: template = emailer.get_template() new_body = emailer.replace_text(match,template) message, body = emailer.get_welcome_email(match,new_body) print(new_body) user_confirmation = raw_input('Send this email? (1 Y/ 2 n/ 3s) ') if float(user_confirmation) == 1: message = (gmail_service.users().messages().send(userId="me", body=body).execute()) print('Message Id: %s' % message['id']) print(message) elif float(user_confirmation) == 2: break elif float(user_confirmation) == 3:
return anchorLinks if __name__ == '__main__': rr = BlueRidge() rr.goSlow = True if len(sys.argv) > 1: url = sys.argv[1] else: url = 'http://sfbay.craigslist.org/search/sfc/fuo?sort=date&query=sofa%7Ccouch' listingsPage = rr.requestPage(url) rr.parse(listingsPage) listings = rr.getListingsLessThan(1000) if listings: content = rr.getAnchorLinksFromPids(listings) #with open('couches1.html', 'w') as htmlFile: # htmlFile.write(content) emailer = Emailer() emailer.sendEmail("New Craigslist Couch/Sofa Listings", content) else: pass #emailer = Emailer() #emailer.sendEmail("Blue Ridge Heartbeat", str(datetime.datetime.now()))
from authenticate import authenticate from Emailer import Emailer gmail_service = authenticate() emailer = Emailer() message, body = emailer.get_welcome_msg("blah", "blah", "blah") message = (gmail_service.users().messages().send(userId="me", body=body).execute())
command = r'"C:\Program Files (x86)\CollabNet\Subversion Client\svn.exe" co%s %s %s' \ % (rev, url, to) return command def CheckOut(self): self.logger = Logger() self.logger.CoolLog("Delete sources and Checkout") self.DeleteSources() command = self.FormCommand() self.doCheckOut(command) if __name__ == "__main__": from ConfigParser import ConfigParser from ParametersParsing import EmailerParameters, GeneralParameters, RepoParameters configFile = "Parameters.conf" parentDir = os.path.abspath( os.path.join(os.path.dirname(__file__), os.pardir)) configFile = os.path.join(parentDir, configFile) cfgParser = ConfigParser() cfgParser.read(configFile) emailerParameters = EmailerParameters(cfgParser) repoParameters = RepoParameters(cfgParser) generalParameters = GeneralParameters(cfgParser) svnWorker = SvnWorker(Emailer(emailerParameters), generalParameters, repoParameters) svnWorker.CheckOut()
def CreateSocket(q): # Read the IP address of the door with open(r'/home/tme/door.txt') as file: host = file.readline() port = 8686 q.put(False) doorOpenedTime = None sendEmail = True # Create a socket item mySocket = socket.socket() # Try to connect to the socket server running on the Pi try: mySocket.connect((host, port)) except socket.error as e: print(e) # Loop forever checking the socket for messages while True: if doorOpenedTime is not None: if (datetime.now() - doorOpenedTime).total_seconds() > 1800 and sendEmail: sendEmail = False emailMessage = Emailer() emailMessage.start() # Check the Queue to see if it has information, if it does check to see if it says exit. # If the Queue says exit then break the loop if not q.empty(): qData = q.get() if qData == "exit": break else: q.put(qData) # Set receive listen timeout to 1/10 of a second so it doesn't hang forever waiting for a message mySocket.settimeout(0.1) # Try to receive data from the socket, if it times out pass and run loop again try: data = mySocket.recv(1024).decode() # If data is None then the socket server isn't running and break the loop if not data: break print("from connected user: "******"opened": if q.empty(): q.put(True) else: qData = q.get() if qData == "exit": break q.put(True) doorOpenedTime = datetime.now() print("Door opened at " + str(doorOpenedTime)) elif data == "closed": if q.empty(): q.put(False) else: qData = q.get() if qData == "exit": print("quitting") break q.put(False) sendEmail = True doorOpenedTime = None print("Door closed") except KeyboardInterrupt: print("Keyboard interrupt detected. Closing Socket.") mySocket.close() except socket.timeout: pass mySocket.close() print("Socket Closed")
def emailWithPdf(self, emailList, sms_list, subjectLine, emailContent, pfile, cfile): sender = Emailer(emailList, sms_list, subjectLine, emailContent) sender.sendPdf(pfile, cfile)
class PortalBoxApplication: ''' wrap code as a class to allow for clean sharing of objects between states ''' def __init__(self, settings): ''' Setup the bare minimun, defering as much as poosible to the run method so signal handlers can be configured in __main__ ''' self.exceeded_time = False self.running = False self.equipment_id = False self.box = PortalBox() self.settings = settings def __del__(self): ''' free resources after run ''' self.box.cleanup() def run(self): ''' Actually get ready to run... we defered initialization in order to configure signal handlers in __main__ but they should now be in place This corresponds to the transition from Start in FSM.odg see docs ''' # Step 1 Do a bit of a dance to show we are running self.box.set_display_color_wipe(RED, 10) # Set 2 Figure out our identity mac_address = format(get_mac_address(), 'x') logging.debug("Discovered Mac Address: %s", mac_address) # connect to backend database logging.debug("Connecting to database on host %s", self.settings['db']['host']) try: self.db = Database(self.settings['db']) logging.debug("Connected to Database") except Exception as e: logging.error("{}".format(e)) sys.exit(1) # be prepared to send emails try: self.emailer = Emailer(self.settings['email']) logging.debug("Cached email settings") except Exception as e: # should be unreachable logging.error("{}".format(e)) sys.exit(1) # give user hint we are makeing progress self.box.set_display_color_wipe(ORANGE, 10) # determine what we are profile = (-1, ) self.running = True while self.running and 0 > profile[0]: profile = self.db.get_equipment_profile(mac_address) if 0 > profile[0]: sleep(5) # only run if we have role, which we might not if systemd asked us to # shutdown before we discovered a role if 0 < profile[0]: # profile: # (int) equipment id # (int) equipment type id # (str) equipment type # (int) location id # (str) location # (int) time limit in minutes self.equipment_id = profile[0] self.equipment_type_id = profile[1] self.equipment_type = profile[2] self.location = profile[4] self.timeout_period = profile[5] logging.info( "Discovered identity. Type: %s(%s) Timeout period: %s", profile[2], self.equipment_type_id, self.timeout_period) self.db.log_started_status(self.equipment_id) self.box.set_display_color_wipe(GREEN, 10) self.timeout_period *= 60 # python threading wants seconds, DB has minutes self.proxy_uid = -1 self.training_mode = False self.wait_for_access_card() else: logging.info( "Running ending abnormally. Did not discover identity.") def wait_for_access_card(self): ''' Wait for a card and if we read a card decide what to do ''' self.box.set_display_color_wipe(BLUE, 15) # Run... loop endlessly waiting for RFID cards while self.running: # Scan for card uid = self.box.read_RFID_card() if -1 < uid: # we read a card... decide what to do card_type = self.db.get_card_type(uid) logging.debug("Card of type: %s was presented", card_type) if Database.SHUTDOWN_CARD == card_type: logging.info( "Shutdown Card: %s detected, triggering box shutdown", uid) self.db.log_shutdown_status(self.equipment_id, uid) self.box.set_display_color() os.system("shutdown -h now") elif Database.TRAINING_CARD == card_type: if self.db.is_training_card_for_equipment_type( uid, self.equipment_type_id): logging.info( "Trainer identitfied by card: %s is authorized to use equipment", uid) self.training_mode = True self.run_session(uid) self.training_mode = False else: self.wait_for_unauthorized_card_removal(uid) elif Database.USER_CARD == card_type: if self.db.is_user_authorized_for_equipment_type( uid, self.equipment_type_id): logging.info( "User identitfied by card: %s is authorized to use equipment", uid) self.run_session(uid) else: self.wait_for_unauthorized_card_removal(uid) else: self.wait_for_unauthorized_card_removal(uid) self.box.set_display_color_wipe(BLUE, 15) sleep(0.2) def run_session(self, user_id): ''' Allow user to use the equipment ''' logging.info( "Logging successful activation of equipment to backend database") self.db.log_access_attempt(user_id, self.equipment_id, True) self.authorized_uid = user_id self.box.set_display_color(GREEN) self.box.set_equipment_power_on(True) if 0 < self.timeout_period: self.exceeded_time = False self.activation_timeout = threading.Timer(self.timeout_period, self.timeout) self.activation_timeout.start() self.wait_for_authorized_card_removal() if not self.exceeded_time and 0 < self.timeout_period: self.activation_timeout.cancel() self.box.set_equipment_power_on(False) logging.info( "Logging completion of equipment access to backend database") self.db.log_access_completion(user_id, self.equipment_id) self.authorized_uid = -1 def timeout(self): ''' Called by timer thread when usage time is exceeeded ''' self.exceeded_time = True def wait_for_unauthorized_card_removal(self, uid): ''' Wait for card to be removed ''' logging.info("Card: %s is NOT authorized to use equipment", uid) self.db.log_access_attempt(uid, self.equipment_id, False) # We have to have a grace_counter because consecutive card reads currently fail grace_count = 0 #loop endlessly waiting for shutdown or card to be removed while self.running and grace_count < 2: # Scan for card uid = self.box.read_RFID_card() if -1 < uid: # we read a card grace_count = 0 else: # we did not read a card grace_count += 1 self.box.flash_display(RED, 100, 1, RED) def wait_for_authorized_card_removal(self): ''' Wait for card to be removed ''' self.card_present = True self.proxy_uid = -1 # We have to have a grace_counter because consecutive card reads currently fail grace_count = 0 #loop endlessly waiting for shutdown or card to be removed while self.running and self.card_present: # check for timeout if self.exceeded_time: self.wait_for_timeout_grace_period_to_expire() if self.card_present: # User pressed the button return to running self.exceeded_time = False if self.card_present: grace_count = 0 if -1 < self.proxy_uid: self.box.set_display_color(ORANGE) else: self.box.set_display_color(GREEN) self.activation_timeout = threading.Timer( self.timeout_period, self.timeout) self.activation_timeout.start() else: break # Scan for card uid = self.box.read_RFID_card() if -1 < uid and (uid == self.authorized_uid or uid == self.proxy_uid): # we read an authorized card grace_count = 0 else: # we did not read a card or we read the wrong card grace_count += 1 if grace_count > 2: self.wait_for_user_card_return() if self.card_present: grace_count = 0 if -1 < self.proxy_uid: self.box.set_display_color(ORANGE) else: self.box.set_display_color(GREEN) sleep(0.1) def wait_for_user_card_return(self): ''' Wait for a time for card to return before shutting down, button press shuts down immediately. We accomplish this using the card_present flag. By setting the flag to False immeditely we just return and the outer loop in wait_for_authorized_card_removal will also end. If we get the authorized card back we can toggle the flag back and return which will cause the outer loop to continue ''' self.card_present = False self.proxy_uid = -1 self.box.set_display_color(YELLOW) grace_count = 0 logging.info("Card Removed") self.box.has_button_been_pressed() # clear pending events while self.running and grace_count < 16: # Check for button press if self.box.has_button_been_pressed(): break # Scan for card uid = self.box.read_RFID_card() if -1 < uid: # we read a card if uid == self.authorized_uid: # card returned self.card_present = True break elif not self.training_mode: # trainers may not use proxy cards # check if proxy card if Database.PROXY_CARD == self.db.get_card_type(uid): self.card_present = True self.proxy_uid = uid break grace_count += 1 self.box.set_buzzer(True) self.box.flash_display(YELLOW, 100, 1, YELLOW) self.box.set_buzzer(False) if self.running and not self.card_present: logging.debug( "Grace period following card removal expired; shutting down equipment" ) def wait_for_timeout_grace_period_to_expire(self): """ Four posibilities: 1) user presses button with card in to renew session 2) user removes card and presses button to end session 3) user removes card but does not press button to end session 4) user forgot their card """ logging.info("Equipment usage timeout") grace_count = 0 self.box.has_button_been_pressed() # clear pending events self.box.set_display_color(ORANGE) while self.running and grace_count < 600: #check for button press if self.box.has_button_been_pressed(): logging.info("Button was pressed, extending time out period") uid = self.box.read_RFID_card() uid2 = self.box.read_RFID_card( ) #try twice since reader fails consecutive reads if -1 < uid or -1 < uid2: # Card is still present session renewed return else: # Card removed end session self.card_present = False return else: grace_count += 1 if 1 > (grace_count % 2): self.box.flash_display(ORANGE, 100, 1, ORANGE) if 1 > (grace_count % 20): self.box.set_buzzer(True) else: self.box.set_buzzer(False) sleep(0.1) # grace period expired # stop the buzzer self.box.set_buzzer(False) # shutdown now, do not wait for email or card removal self.box.set_equipment_power_on(False) # was forgotten card? uid = self.box.read_RFID_card() uid2 = self.box.read_RFID_card( ) #try twice since reader fails consecutive reads if -1 < uid or -1 < uid2: # Card is still present logging.info( "User card was left in portal box. Sending user an email.") self.box.set_display_color_wipe(BLUE, 50) user = self.db.get_user(self.authorized_uid) try: self.emailer.send( user[1], "Access Card left in PortalBox", "{} it appears you left your access card in a badge box for the {} in the {}" .format(user[0], self.equipment_type, self.location)) except Exception as e: logging.error("{}".format(e)) self.box.set_display_color(RED) while self.running and self.card_present: # wait for card to be removed... we need to make sure we don't have consecutive read failure uid = self.box.read_RFID_card() uid2 = self.box.read_RFID_card( ) #try twice since reader fails consecutive reads if 0 > uid and 0 > uid2: self.card_present = False else: # Card removed end session self.card_present = False def exit(self): ''' Stop looping in all run states ''' logging.info("Service Exiting") if self.running: if self.equipment_id: self.db.log_shutdown_status(self.equipment_id, False) self.running = False else: # never made it to the run state sys.exit() def handle_interupt(self, signum, frame): ''' Stop the service from a signal''' logging.debug("Interupted") self.exit()
class PortalBoxApplication: ''' wrap code as a class to allow for clean sharing of objects between states ''' def __init__(self, settings): ''' Setup the bare minimun, defering as much as poosible to the run method so signal handlers can be configured in __main__ ''' self.running = False self.equipment_id = False self.box = PortalBox() self.settings = settings self.start_time = 0.0 feed_watchdog("portalbox_init") def __del__(self): ''' free resources after run ''' self.box.cleanup() def run(self): ''' Actually get ready to run... we defered initialization in order to configure signal handlers in __main__ but they should now be in place This corresponds to the transition from Start in FSM.odg see docs ''' # Step 1 Do a bit of a dance to show we are running logging.info("Setting display color to wipe red") self.box.set_display_color_wipe(RED, 10) logging.info("Started PortalBoxApplication.run()") # Set 2 Figure out our identity mac_address = format(get_mac_address(), 'x') logging.info("Discovered Mac Address: %s", mac_address) # connect to backend database logging.info("Connecting to database on host %s", self.settings['db']['host']) try: logging.debug("Creating database instance") self.db = Database(self.settings['db']) logging.info("Connected to Database") except Exception as e: logging.error("{}".format(e)) sys.exit(1) # be prepared to send emails try: logging.info("Creating emailer instance") self.emailer = Emailer(self.settings['email']) logging.info("Cached email settings") except Exception as e: # should be unreachable logging.error("{}".format(e)) sys.exit(1) # give user hint we are makeing progress logging.debug("Setting display color to wipe orange") self.box.set_display_color_wipe(ORANGE, 10) # determine what we are profile = (-1,) self.running = True while self.running and 0 > profile[0]: feed_watchdog("equipment_profile") logging.info("Trying to get equipment profile") profile = self.db.get_equipment_profile(mac_address) if 0 > profile[0]: sleep(5) # only run if we have role, which we might not if systemd asked us to # shutdown before we discovered a role if 0 < profile[0]: # profile: # (int) equipment id # (int) equipment type id # (str) equipment type # (int) location id # (str) location # (int) time limit in minutes self.equipment_id = profile[0] self.equipment_type_id = profile[1] self.equipment_type = profile[2] self.location = profile[4] self.timeout_period = profile[5] logging.info("Discovered identity. Type: %s(%s) Timeout: %s m", self.equipment_type, self.equipment_type_id, self.timeout_period) self.db.log_started_status(self.equipment_id) logging.info("Setting display to wipe green") self.box.set_display_color_wipe(GREEN, 10) self.timeout_period *= 60 # python threading wants seconds, DB has minutes self.proxy_uid = -1 self.training_mode = False logging.info("Starting to wait for access card") self.wait_for_access_card() else: logging.info("Running ending; did not discover identity.") sys.exit(1) def wait_for_access_card(self): ''' Wait for a card and if we read a card decide what to do ''' logging.debug("Setting display to sleep") self.box.sleep_display() # Run... loop endlessly waiting for RFID cards logging.debug("Waiting for an access card") while self.running: feed_watchdog("wait_for_a_card") # Scan for card uid = self.box.read_RFID_card() if -1 < uid: logging.debug("Detected a card") # we read a card... decide what to do card_type = self.db.get_card_type(uid) logging.debug("Card of type: %s was presented", card_type) if Database.SHUTDOWN_CARD == card_type: logging.info("Shutdown Card: %s detected, triggering box shutdown", uid) self.db.log_shutdown_status(self.equipment_id, uid) logging.debug("Blanking display") self.box.set_display_color() logging.debug("Telling OS to shut down") os.system("sync; shutdown -h now") elif Database.USER_CARD == card_type: logging.info("User card %s detected, authorized?", uid) if self.db.is_user_authorized_for_equipment_type(uid, self.equipment_type_id): logging.info("User %s authorized for %s", uid, self.equipment_type) self.run_session(uid) else: self.wait_for_unauthorized_card_removal(uid) logging.debug("Done with user card, start sleep display") self.box.sleep_display() else: logging.info("Unauthorized card %s detected", uid) self.wait_for_unauthorized_card_removal(uid) logging.debug("Done with unauthorized card, start sleep display") self.box.sleep_display() self.box.sleep_display() sleep(0.1) def run_session(self, user_id): ''' Allow user to use the equipment ''' self.authorized_uid = user_id self.proxy_uid = -1 self.training_mode = False self.user_is_trainer = False logging.debug("Setting display to green") self.box.set_display_color(AUTH_COLOR) self.box.set_buzzer(True) self.box.set_equipment_power_on(True) sleep(0.05) logging.info("Logging activation of %s to DB", self.equipment_type) self.db.log_access_attempt(user_id, self.equipment_id, True) self.box.set_buzzer(False) logging.debug("Setting display to green") self.box.set_display_color(AUTH_COLOR) logging.debug("Checking if user is a trainer or admin") self.user_is_trainer = self.db.is_user_trainer(user_id) if 0 < self.timeout_period: self.start_time = time() logging.debug("Starting timeout") self.wait_for_authorized_card_removal() self.box.set_equipment_power_on(False) logging.info("Logging end of %s access to DB", self.equipment_type) self.db.log_access_completion(user_id, self.equipment_id) self.authorized_uid = -1 logging.debug("run_session() ends") def wait_for_unauthorized_card_removal(self, uid): ''' Wait for card to be removed ''' logging.info("Card %s NOT authorized for %s", uid, self.equipment_type) self.db.log_access_attempt(uid, self.equipment_id, False) #loop endlessly waiting for shutdown or card to be removed logging.debug("Looping until not running or card removed") self.box.flash_display(RED, 100, 1000, RED) while self.running: feed_watchdog("wait_unauth_remove") # Scan for card uid = self.box.read_RFID_card() if uid < 0: # card removed break sleep(0.1) logging.debug("wait_for_unauthorized_card_removal() ends") def wait_for_authorized_card_removal(self): ''' Wait for card to be removed ''' self.card_present = True self.proxy_uid = -1 if self.training_mode: color_now = TRAINER_COLOR else: color_now = AUTH_COLOR #loop endlessly waiting for shutdown or card to be removed logging.debug("Waiting for card removal or timeout") while self.running and self.card_present: feed_watchdog("wait_auth_remove_timeout") # check for timeout if (self.timeout_period > 0 and (time() - self.start_time) > self.timeout_period): logging.debug("Time exceeded, wait for timeout grace") self.wait_for_timeout_grace_period_to_expire() logging.debug("Timeout grace period expired") if self.card_present: # User pressed the button return to running logging.debug("Button pressed, restart timeout") self.start_time = time() if self.proxy_uid > -1: color_now = PROXY_COLOR elif self.training_mode: color_now = TRAINER_COLOR else: color_now = AUTH_COLOR else: logging.debug("Card removed") break # Scan for card uid = self.box.read_RFID_card() # FIXME Accept training card also? if -1 < uid and (uid == self.authorized_uid or uid == self.proxy_uid): pass else: # we did not read a card or we read the wrong card self.wait_for_user_card_return() if -1 < self.proxy_uid: color_now = PROXY_COLOR elif self.training_mode: color_now = TRAINER_COLOR else: color_now = AUTH_COLOR self.box.set_display_color(color_now) sleep(0.1) self.box.set_display_color(color_now) logging.debug("Finished waiting for card removal or timeout") def wait_for_user_card_return(self): ''' Wait for a time for card to return before shutting down, button press shuts down immediately. We accomplish this using the card_present flag. By setting the flag to False immeditely we just return and the outer loop in wait_for_authorized_card_removal will also end. If we get the authorized card back we can toggle the flag back and return which will cause the outer loop to continue ''' logging.info("User card removed") self.card_present = False self.proxy_uid = -1 grace_seconds = 10 grace_start_time = time() logging.debug("Setting display to yellow") #self.box.set_display_color(YELLOW) self.box.flash_display(YELLOW, 200, (grace_seconds * 5000), YELLOW) self.box.has_button_been_pressed() # clear pending events logging.debug("Waiting for card to return") previous_uid = -1 loop_count = 0 while (self.running and (time() - grace_start_time) < grace_seconds): feed_watchdog("wait_auth_card_return") # Check for button press if self.box.has_button_been_pressed(): logging.debug("Button pressed") break # Scan for card uid = self.box.read_RFID_card() if uid > -1 and uid != previous_uid: # we read a card previous_uid = uid if uid == self.authorized_uid: # card returned self.card_present = True logging.debug("Authorized card returned") break elif not self.training_mode: # trainers may not use proxy cards logging.debug("Checking database for card type") card_type = self.db.get_card_type(uid) if Database.PROXY_CARD == card_type: self.card_present = True self.proxy_uid = uid self.user_is_trainer = False logging.debug("Authorized user -> proxy card") break if Database.TRAINING_CARD == card_type: logging.info("Training card %s detected, authorized?", uid) if self.proxy_uid > -1: logging.info("Training card disallowed with proxy") elif not self.user_is_trainer: logging.info("User is not a trainer") elif self.db.is_training_card_for_equipment_type(uid, self.equipment_type_id): logging.info("Training card %s authorized", uid) self.db.log_access_attempt(uid, self.equipment_id, True) self.card_present = True self.training_mode = True self.user_is_trainer = False self.authorized_uid = uid break else: logging.info("Training card NOT authorized for %s", uid, self.equipment_type) if (loop_count % 20) == 0: self.box.set_buzzer(True) else: self.box.set_buzzer(False) loop_count = loop_count + 1 sleep(0.1) if self.running and not self.card_present: logging.info("Grace period following card removal expired; shutting down equipment") logging.debug("wait_for_user_card_return() ends") def wait_for_timeout_grace_period_to_expire(self): """ Four posibilities: 1) user presses button with card in to renew session 2) user removes card and presses button to end session 3) user removes card but does not press button to end session 4) user forgot their card """ logging.info("Equipment usage timeout") self.box.has_button_been_pressed() # clear pending events logging.debug("Setting display to orange") self.box.set_display_color(ORANGE) # FIXME Does this really work? self.box.flash_display(ORANGE, 100, 1, ORANGE) logging.debug("Starting grace period") grace_seconds = 10 grace_start_time = time() loop_count = 0 while (self.running and (time() - grace_start_time) < grace_seconds): feed_watchdog("grace_timeout") #check for button press if self.box.has_button_been_pressed(): logging.info("Button was pressed, extending time out period") uid = self.box.read_RFID_card() if -1 < uid: # Card is still present session renewed logging.debug("Card still present, renew session") return else: # Card removed end session logging.debug("Card removed, end session") self.card_present = False return if (loop_count % 20) == 0: self.box.set_buzzer(True) else: self.box.set_buzzer(False) loop_count = loop_count + 1 sleep(0.1) # grace period expired # stop the buzzer logging.debug("Grace period expired") self.box.set_buzzer(False) # shutdown now, do not wait for email or card removal self.box.set_equipment_power_on(False) # was forgotten card? logging.debug("Checking for forgotten card") uid = self.box.read_RFID_card() if -1 < uid: # Card is still present logging.info("User card left in portal box. Sending user email.") logging.debug("Setting display to wipe blue") self.box.set_display_color_wipe(BLUE, 50) logging.debug("Getting user email ID from DB") user = self.db.get_user(self.authorized_uid) try: logging.debug("Mailing user") self.emailer.send(user[1], "Access Card left in PortalBox", "{} it appears you left your access card in a badge box for the {} in the {}".format(user[0], self.equipment_type, self.location)) except Exception as e: logging.error("{}".format(e)) logging.debug("Setting display to red") self.box.set_display_color(RED) while self.running and self.card_present: feed_watchdog("user_left_card") # wait for card to be removed uid = self.box.read_RFID_card() if 0 > uid: self.card_present = False logging.debug("Stopped running or card removed") else: # Card removed end session logging.debug("Card removed, session ends") self.card_present = False logging.debug("wait_for_timeout_grace_period_to_expire() ends") def exit(self): ''' Stop looping in all run states ''' logging.info("Service Exiting") feed_watchdog("service_exit") self.box.set_equipment_power_on(False) if self.running: if self.equipment_id: logging.debug("Logging exit-while-running to DB") self.db.log_shutdown_status(self.equipment_id, False) self.running = False else: # never made it to the run state logging.debug("Not running, just exit") sys.exit() def handle_interupt(self, signum, frame): ''' Stop the service from a signal''' logging.debug("Interrupted") feed_watchdog("service_interrupt") self.exit()
def run(self): ''' Actually get ready to run... we defered initialization in order to configure signal handlers in __main__ but they should now be in place This corresponds to the transition from Start in FSM.odg see docs ''' # Step 1 Do a bit of a dance to show we are running logging.info("Setting display color to wipe red") self.box.set_display_color_wipe(RED, 10) logging.info("Started PortalBoxApplication.run()") # Set 2 Figure out our identity mac_address = format(get_mac_address(), 'x') logging.info("Discovered Mac Address: %s", mac_address) # connect to backend database logging.info("Connecting to database on host %s", self.settings['db']['host']) try: logging.debug("Creating database instance") self.db = Database(self.settings['db']) logging.info("Connected to Database") except Exception as e: logging.error("{}".format(e)) sys.exit(1) # be prepared to send emails try: logging.info("Creating emailer instance") self.emailer = Emailer(self.settings['email']) logging.info("Cached email settings") except Exception as e: # should be unreachable logging.error("{}".format(e)) sys.exit(1) # give user hint we are makeing progress logging.debug("Setting display color to wipe orange") self.box.set_display_color_wipe(ORANGE, 10) # determine what we are profile = (-1,) self.running = True while self.running and 0 > profile[0]: feed_watchdog("equipment_profile") logging.info("Trying to get equipment profile") profile = self.db.get_equipment_profile(mac_address) if 0 > profile[0]: sleep(5) # only run if we have role, which we might not if systemd asked us to # shutdown before we discovered a role if 0 < profile[0]: # profile: # (int) equipment id # (int) equipment type id # (str) equipment type # (int) location id # (str) location # (int) time limit in minutes self.equipment_id = profile[0] self.equipment_type_id = profile[1] self.equipment_type = profile[2] self.location = profile[4] self.timeout_period = profile[5] logging.info("Discovered identity. Type: %s(%s) Timeout: %s m", self.equipment_type, self.equipment_type_id, self.timeout_period) self.db.log_started_status(self.equipment_id) logging.info("Setting display to wipe green") self.box.set_display_color_wipe(GREEN, 10) self.timeout_period *= 60 # python threading wants seconds, DB has minutes self.proxy_uid = -1 self.training_mode = False logging.info("Starting to wait for access card") self.wait_for_access_card() else: logging.info("Running ending; did not discover identity.") sys.exit(1)
from Emailer import Emailer from time import sleep notes = [["test", "123"], ["jest","124"]] my_emailer = Emailer() for i in range(20): my_emailer.send_email(notes)
from Emailer import Emailer if __name__ == "__main__": email = Emailer() receiver = "*****@*****.**" dealDetail = { "brand": "kate spade", "description": "kate spade surprise sale", "hashcode": hash("kate spade surprise sale"), "link": "https://dealsea.com/view-deal/827333 ", } email.sendemail(dealDetail, receiver)
def email(self, emailList, sms_list, subjectLine, emailContent): sender = Emailer(emailList, sms_list, subjectLine, emailContent) sender.alert()
def setUp(self): self.gmail_service = authenticate() self.emailer = Emailer() self.match_xls = '/Users/jjw036/Dropbox/GSA/LinkLunch/matches_04212015.xlsx' self.address_xls = '/Users/jjw036/Dropbox/GSA/LinkLunch/individual_info.xlsx'
def emailRecovery(self, emailList, sms_list, subjectLine, emailContent, pfile, cfile): sender = Emailer(emailList, sms_list, subjectLine, emailContent) sender.sendPdfOnly(pfile, cfile)
def run_camera(valid_output, graph): camera_device = cv2.VideoCapture(CAMERA_INDEX) camera_device.set(cv2.CAP_PROP_FRAME_WIDTH, REQUEST_CAMERA_WIDTH) camera_device.set(cv2.CAP_PROP_FRAME_HEIGHT, REQUEST_CAMERA_HEIGHT) camera_device.set(cv2.CAP_PROP_FPS, REQUEST_CAMERA_FPS) actual_camera_width = camera_device.get(cv2.CAP_PROP_FRAME_WIDTH) actual_camera_height = camera_device.get(cv2.CAP_PROP_FRAME_HEIGHT) print ('actual camera resolution: ' + str(actual_camera_width) + ' x ' + str(actual_camera_height)) if ((camera_device == None) or (not camera_device.isOpened())): print ('Could not open camera. Make sure it is plugged in.') print ('Also, if you installed python opencv via pip or pip3 you') print ('need to uninstall it and install from source with -D WITH_V4L=ON') print ('Use the provided script: install-opencv-from_source.sh') return frame_count = 0 match_count = 0 #entrant = 0 cv2.namedWindow(CV_WINDOW_NAME) found_match = 0 Faked = False while True : # Read image from camera, ret_val, vid_image = camera_device.read() if (not ret_val): print("No image from camera, exiting") break frame_count += 1 frame_name = 'camera frame ' + str(frame_count) if (not Faked): # run a single inference on the image and overwrite the # boxes and labels test_output = run_inference(vid_image, graph) matched_face = face_match(valid_output, test_output) if (matched_face != False): print('PASS! File ' + matched_face + ' matches ') match_count += 1 if (match_count >= 5 and match_count <= 7): print('User Checked In!') found_match = 2 if (match_count == 7): #return match_count = 0 Requestor().start() excemptions = ['Michael', 'Chris L'] if matched_face not in excemptions: fileName = '/home/tme/Desktop/Log/' + matched_face + str(datetime.datetime.now()) + '.png' cv2.imwrite(fileName, vid_image) emailMessage = Emailer(fileName, matched_face) emailMessage.start() else: found_match = 1 else: found_match = 3 print('FAIL! File ' + frame_name + ' does not match ') match_count = 0 #Uncomment next line to view the image sent to the graph #vid_image = preprocess_image(vid_image) overlay_on_image(vid_image, frame_name, found_match, matched_face) # check if the window is visible, this means the user hasn't closed # the window via the X button prop_val = cv2.getWindowProperty(CV_WINDOW_NAME, cv2.WND_PROP_ASPECT_RATIO) if (prop_val < 0.0): print('window closed') break # display the results and wait for user to hit a key cv2.imshow(CV_WINDOW_NAME, vid_image) raw_key = cv2.waitKey(1) if (raw_key != -1): if (handle_keys(raw_key) == False): print('user pressed Q') break if (handle_keys(raw_key) == 2): Faked = True print('PASS! File ' + frame_name + ' matches ') match_count += 1 if (match_count == 2): print('User Checked In!') found_match = 2 elif (match_count == 3): Faked = False match_count = 0 else: found_match = 1 if (found_match): cv2.imshow(CV_WINDOW_NAME, vid_image) cv2.waitKey(0)