Exemple #1
0
 def logout(self):
     try:
         NotificationManager.removeInstance(flask.session['sessionID'])
         flask.session.clear()
         flask.flash("You have been logged out!")
         return flask.redirect(flask.url_for('login_page'))
     except Exception as e:
         self.flasklogger.error("Logout Failed:Exception:{0}".format(e))
         return flask.render_template('wrong.html', error = "{}".format(e))
Exemple #2
0
class PTMHub(BaseManager):
	def __init__(self, *args, **kw):
		super(PTMHub, self).__init__(*args, **kw)
		self.__shadow_manager = ShadowManager(client = self)
		self.__subscription_manager = SubscriptionManager()
		self.__notification_manager = NotificationManager(registry = self.registry)
		
	def get_method_dispatcher(self):
		return HubMethodDispatcher(self)
		
	def __check_resolvable(self, owner):
		self.get_adapter(owner)
		
	def __mangle_notify_args(self, condition, owner, reference):
		if not owner:
			raise InternalIllegalArgumentError(owner)
		return (NotificationId(condition), Identifier(owner, need_abs = True), Identifier(reference, need_abs = True))
		
	def do_subscribe(self, condition, owner, reference):
		self.__check_resolvable(owner)
		self.__subscription_manager.add_subscription(*self.__mangle_notify_args(condition, owner, reference))
		
	def do_unsubscribe(self, condition, owner, reference):
		self.__subscription_manager.remove_subscription(*self.__mangle_notify_args(condition, owner, reference))
		
	def do_notify(self, condition, owner, reference):
		(condition, owner, reference) = self.__mangle_notify_args(condition, owner, reference)
		self.__do_notify(condition, owner, reference)
		
	def __do_notify(self, condition, owner, reference):
		if DELETED in condition:
			condition = DELETED
		self.__notification_manager.notify(condition, owner, reference)
		
	def do_signal(self, condition, reference):
		(condition, _, reference) = self.__mangle_notify_args(condition, "/", reference)
		subscribers = self.__subscription_manager.get_subscribers(condition, reference)
		for s in subscribers:
			try:
				self.do_notify(condition, s, reference)
			except:
				logger.exception("notify failed")
	
	def do_register(self, identifier, payload):
		payload = self.__shadow_manager.get_shadow(payload)
		super(PTMHub, self).do_register(identifier, payload)
		
	def register_adapter(self, identifier, adapter):
		if not isinstance(adapter, AbstractResourceAdapter):
			raise TypeError("Need an instance of ResourceAdapter here. Got: " + str(adapter))
		super(PTMHub, self).do_register(identifier, adapter)
    def performAudioAnalysis(self, userID, expectedStr):

        try:
            ac = AccuracyChecker()
            ac.record("recordings_audio/" + self.username + '/' +
                      self.filename + ".wav")
            accuracy, wpm = ac.performAnalysis(expectedStr)
            afa = AudioFeatureAnalyzer("recordings_audio/" + self.username +
                                       '/' + self.filename + ".wav")
            variance = afa.calcFrequencyVariance()
            mFrequency = afa.calcModalFrequency()
            breathTime = afa.calcTimeSpentBreathing()
            avgAmp = afa.calcAverageAmplitude()
            self.logger.info("userID is {}".format(userID))
            aS = AnalysisSingletonSwitch.getInstance(userID)

            while not aS.userChecked:
                self.logger.debug('waiting for recognzizer')
                time.sleep(5)
                self.logger.info("userID is {}".format(userID))
                aS = AnalysisSingletonSwitch.getInstance(userID)

            if aS.isUser:
                self.dbh.insert_audiorecordings(userID, accuracy,
                                                self.filename, wpm, variance,
                                                mFrequency, breathTime, avgAmp,
                                                "INSERT")
                self.logger.debug('Inserted Audio')
                count = 0
                while not aS.facialFinished:
                    if count == 6:
                        break
                    self.logger.debug('waiting for face analyzer')
                    time.sleep(5)
                    count += 1
                    aS = AnalysisSingletonSwitch.getInstance(userID)
                nm = NotificationManager.getInstance(userID)
                nm.addNotification("Your results are ready for display",
                                   "results", "Analysis Team")
                self.logger.debug('Added Notification')
                aS.removeInstance(userID)
            else:
                nm = NotificationManager.getInstance(userID)
                nm.addNotification(
                    "We're sorry but we couldn't recognize you from your recording, please try again later.",
                    "info", "Analysis Team")
        except Exception as e:
            self.logger.error('Error: {}'.format(e))
Exemple #4
0
 def pref_func(self):
     try:
         userID = flask.session['sessionID']
         pref1  = flask.request.form.get('irishindependent')
         pref2  = flask.request.form.get('irishtimes')
         pref3  = flask.request.form.get('rte')
         pref4  = flask.request.form.get('rtesport')
         pref5  = flask.request.form.get('guardian')
         pref6  = flask.request.form.get('skysports')
         
         self.dbh.insert_text_pref(userID,
                                   dict(p1=('irishindependent' if pref1 == 'true' else "NULL"))['p1'],
                                   dict(p2=('irishtimes' if pref2 == 'true' else "NULL"))['p2'],
                                   dict(p3=('rte' if pref3 == 'true' else "NULL"))['p3'],
                                   dict(p4=('rtesport' if pref4 == 'true' else "NULL"))['p4'],
                                   dict(p5=('guardian' if pref5 == 'true' else "NULL"))['p5'],
                                   dict(p6=('skysports' if pref6 == 'true' else "NULL"))['p6'],
                                   "INSERT")
         
         nm = NotificationManager.getInstance(flask.session['sessionID'])
         nm.addNotification("Your changes have been saved", "preferences", "System")
         return flask.redirect('/menu')
     except Exception as e:
         self.flasklogger.error("Preferences function failed:{0}".format(e))
         return flask.render_template('wrong.html',error="{}".format(e))
Exemple #5
0
 def menu(self):
     try:
         nm = NotificationManager.getInstance(flask.session['sessionID'])
         return flask.render_template('menu.html', message=nm.getUserNotifications(), days=json.dumps(self.dbh.getTakenDays(flask.session['sessionID'])))
     except Exception as e:
         self.flasklogger.error("Menu Page Failed:Exception:{0}".format(e))
         return flask.render_template('wrong.html', error = "{}".format(e))
Exemple #6
0
 def updateNotifications(self):
     try:
         nm = NotificationManager.getInstance(flask.session['sessionID'])
         self.flasklogger.debug("CurrList:{}".format(self.registeredUsers))
         return nm.getUserNotifications()
     except Exception as e:
         self.flasklogger.error("Update Notification Function:Exception:{0}".format(e))
         return flask.render_template('wrong.html', error = "{}".format(e))
Exemple #7
0
 def wrap(*args,**kwargs):
     if 'user' in flask.session:
         flask.flash("You need to log out first")
         dbh = DatabaseHelper.getInstance()
         nm = NotificationManager.getInstance(flask.session['sessionID'])
         return flask.render_template('menu.html', message=nm.getUserNotifications(), days=json.dumps(dbh.getTakenDays(flask.session['sessionID'])))
     else:
         return f(*args,**kwargs)
Exemple #8
0
 def wrap(*args,**kwargs):
     nm = NotificationManager.getInstance(flask.session['sessionID'])
     dbh = DatabaseHelper.getInstance()
     acc,filename,wpm,var,mFreq,brTime,avgAmp = dbh.return_audiorecordings(flask.session['sessionID'])
     if len(filename) == 0:
         if not nm.newStartGiven:
             nm.addNotification("Hi " + flask.session['user'] + ', and welcome to PAPA! It seems to be your first time using this app. Please click the help button to get started.', "help", "PAPA Team")
             nm.newStartGiven = True
     return f(*args,**kwargs)
Exemple #9
0
def main():

    mqtt_manager = MBPclient()
    mqtt_manager.connect()
    notification_manager = NotificationManager()
    token_validation_manager = TokenValidationManager()

    handler = partial(CommandReceiverServer, mqtt_manager,
                      notification_manager, token_validation_manager)
    server = HTTPServer(('', 8084), handler)
    print("Starting web server on http://localhost:8084/")
    server.serve_forever()
Exemple #10
0
 def config_func(self):
     try:
         userId = flask.session['sessionID']
         time = flask.request.form['time']
         ch_acc = flask.request.form['ch_acc']
         ch_wpm = flask.request.form['ch_wpm']
         ch_freq = flask.request.form['ch_freq']
         ch_mod_freq = flask.request.form['ch_mod_freq']
         ch_avg_amp = flask.request.form['ch_avg_amp']
         ch_breath = flask.request.form['ch_breath']
         ch_blink = flask.request.form['ch_blink']
         ch_jvib = flask.request.form['ch_jvib']
         self.dbh.insert_config(userId,time,ch_acc,ch_wpm,ch_freq,ch_mod_freq,ch_breath,ch_avg_amp,ch_blink,ch_jvib,"save")
         nm = NotificationManager.getInstance(flask.session['sessionID'])
         nm.addNotification("Your changes have been saved.", "config", "SYSTEM")
         return flask.render_template("menu.html",message = nm.getUserNotifications(), days=json.dumps(self.dbh.getTakenDays(flask.session['sessionID'])))
     except Exception as e:
         self.flasklogger.error("Configuration Function Failed:Exception:{0}".format(e))
         return flask.render_template('wrong.html', error = "{}".format(e))
Exemple #11
0
 def wrap(*args,**kwargs):
     nm = NotificationManager.getInstance(flask.session['sessionID'])
     dbh = DatabaseHelper.getInstance()
     acc,filename,wpm,var,mFreq,brTime,avgAmp = dbh.return_audiorecordings(flask.session['sessionID'])
     ch_acc,ch_wpm,ch_var,ch_mFreq,ch_breath,ch_avgAmp,ch_blink,ch_jvib = dbh.return_config(flask.session['sessionID'])   
     filename,total_blinks,total_peaks,total_troughs,blinkspermin,peakspermin,troughspermin,video_duration = dbh.return_videoRecordings(flask.session['sessionID'])
     try:
          if len(acc) >5:
              avg_acc = (sum(acc) - acc[-1])/(len(acc) - 1)
              avg_wpm = (sum(wpm) - wpm[-1])/(len(wpm) - 1)
              avg_var = (sum(var) - var[-1])/(len(var) - 1)
              avg_mFreq = (sum(mFreq) - mFreq[-1])/(len(mFreq) - 1)
              avg_brTime = (sum(brTime) - brTime[-1])/(len(brTime) - 1)
              avg_avgAmp = (sum(avgAmp) - avgAmp[-1])/(len(avgAmp) - 1)
              avg_blinkspermin = (sum(blinkspermin) - blinkspermin[-1])/(len(blinkspermin) - 1)
              avg_peakspermin = (sum(peakspermin) - peakspermin[-1])/(len(peakspermin) - 1)
         
          if (((acc[-1]/avg_acc)-100) <= -ch_acc) or (((wpm[-1]/avg_wpm)-100) <= -ch_wpm) or (((var[-1]/avg_var)-100) <= -ch_var) or (((brTime[-1]/avg_brTime)-100) <= ch_breath) or (((avg_avgAmp[-1]/avg_avgAmp)-100) <= -ch_avgAmp) or (((mFreq[-1]/avg_mFreq)-100) <= -ch_mFreq or (((blinkspermin[-1]/avg_blinkspermin)-100) <= -ch_blink) or (((peakspermin[-1]/avg_peakspermin)-100) <= ch_jvib)):
              nm.addNotification('We have noticed some changes in your results, your doctor has been notified, but you may wish to book an appointment',"deterioration","Analysis Team")
              nm.sendDoctorNotifications("Hello", "*****@*****.**")
              return flask.render_template('menu.html', message=nm.getUserNotifications(), days=json.dumps(dbh.getTakenDays(flask.session['sessionID'])))
     except:
          return flask.render_template('menu.html', message=nm.getUserNotifications(), days=json.dumps(dbh.getTakenDays(flask.session['sessionID'])))
     return f(*args,**kwargs)
    def __init__(self):

        self.send_next_image = False
        self.is_active = False
        self.notification_manager = NotificationManager()
Exemple #13
0
def startup(args: argparse.Namespace, **kwargs: Dict[str, Any]) -> None:
    global announce, dispatcher, group, httpServer, notification, validator
    global registration, remote, security, statistics, storage, event
    global rootDirectory
    global aeStatistics

    rootDirectory = os.getcwd()  # get the root directory
    os.environ[
        "FLASK_ENV"] = "development"  # get rid if the warning message from flask.
    # Hopefully it is clear at this point that this is not a production CSE

    # Handle command line arguments and load the configuration
    if args is None:
        args = argparse.Namespace(
        )  # In case args is None create a new args object and populate it
        args.configfile = None
        args.resetdb = False
        args.loglevel = None
        for key, value in kwargs.items():
            args.__setattr__(key, value)

    if not Configuration.init(args):
        return

    # init Logging
    Logging.init()
    Logging.log('============')
    Logging.log('Starting CSE')
    Logging.log('CSE-Type: %s' % C.cseTypes[Configuration.get('cse.type')])
    Logging.log(Configuration.print())

    # Initiatlize the resource storage
    storage = Storage()

    # Initialize the event manager
    event = EventManager()

    # Initialize the statistics system
    statistics = Statistics()

    # Initialize the registration manager
    registration = RegistrationManager()

    # Initialize the resource validator
    validator = Validator()

    # Initialize the resource dispatcher
    dispatcher = Dispatcher()

    # Initialize the security manager
    security = SecurityManager()

    # Initialize the HTTP server
    httpServer = HttpServer()

    # Initialize the notification manager
    notification = NotificationManager()

    # Initialize the announcement manager
    announce = AnnouncementManager()

    # Initialize the group manager
    group = GroupManager()

    # Import a default set of resources, e.g. the CSE, first ACP or resource structure
    importer = Importer()
    if not importer.importResources():
        return

    # Initialize the remote CSE manager
    remote = RemoteCSEManager()
    remote.start()

    # Start AEs
    startAppsDelayed(
    )  # the Apps are actually started after the CSE finished the startup

    # Start the HTTP server
    event.cseStartup()  # type: ignore
    Logging.log('CSE started')
    httpServer.run()  # This does NOT return
Exemple #14
0
	def __init__(self, *args, **kw):
		super(PTMHub, self).__init__(*args, **kw)
		self.__shadow_manager = ShadowManager(client = self)
		self.__subscription_manager = SubscriptionManager()
		self.__notification_manager = NotificationManager(registry = self.registry)
Exemple #15
0
def startup(args: argparse.Namespace, **kwargs: Dict[str, Any]) -> None:
    global announce, dispatcher, group, httpServer, notification, validator
    global registration, remote, request, security, statistics, storage, event
    global rootDirectory
    global aeStatistics
    global supportedReleaseVersions, cseType, defaultSerialization, cseCsi, cseRi, cseRn
    global cseOriginator
    global isHeadless

    rootDirectory = os.getcwd()  # get the root directory
    os.environ[
        "FLASK_ENV"] = "development"  # get rid if the warning message from flask.
    # Hopefully it is clear at this point that this is not a production CSE

    # Handle command line arguments and load the configuration
    if args is None:
        args = argparse.Namespace(
        )  # In case args is None create a new args object and populate it
        args.configfile = None
        args.resetdb = False
        args.loglevel = None
        args.headless = False
        for key, value in kwargs.items():
            args.__setattr__(key, value)
    isHeadless = args.headless

    if not Configuration.init(args):
        return

    # Initialize configurable constants
    supportedReleaseVersions = Configuration.get(
        'cse.supportedReleaseVersions')
    cseType = Configuration.get('cse.type')
    cseCsi = Configuration.get('cse.csi')
    cseRi = Configuration.get('cse.ri')
    cseRn = Configuration.get('cse.rn')
    cseOriginator = Configuration.get('cse.originator')

    defaultSerialization = Configuration.get('cse.defaultSerialization')

    # init Logging
    Logging.init()
    if not args.headless:
        Logging.console('Press ? for help')
    Logging.log('============')
    Logging.log('Starting CSE')
    Logging.log(f'CSE-Type: {cseType.name}')
    Logging.log('Configuration:')
    Logging.log(Configuration.print())

    # Initiatlize the resource storage
    storage = Storage()

    # Initialize the event manager
    event = EventManager()

    # Initialize the statistics system
    statistics = Statistics()

    # Initialize the registration manager
    registration = RegistrationManager()

    # Initialize the resource validator
    validator = Validator()

    # Initialize the resource dispatcher
    dispatcher = Dispatcher()

    # Initialize the request manager
    request = RequestManager()

    # Initialize the security manager
    security = SecurityManager()

    # Initialize the HTTP server
    httpServer = HttpServer()

    # Initialize the notification manager
    notification = NotificationManager()

    # Initialize the group manager
    group = GroupManager()

    # Import a default set of resources, e.g. the CSE, first ACP or resource structure
    # Import extra attribute policies for specializations first
    importer = Importer()
    if not importer.importAttributePolicies() or not importer.importResources(
    ):
        return

    # Initialize the remote CSE manager
    remote = RemoteCSEManager()

    # Initialize the announcement manager
    announce = AnnouncementManager()

    # Start AEs
    startAppsDelayed(
    )  # the Apps are actually started after the CSE finished the startup

    # Start the HTTP server
    event.cseStartup()  # type: ignore
    httpServer.run()  # This does return (!)

    Logging.log('CSE started')
    if isHeadless:
        # when in headless mode give the CSE a moment (2s) to experience fatal errors before printing the start message
        BackgroundWorkerPool.newActor(
            delay=2,
            workerCallback=lambda: Logging.console('CSE started')
            if not shuttingDown else None).start()

    #
    #	Enter an endless loop.
    #	Execute keyboard commands in the keyboardHandler's loop() function.
    #
    commands = {
        '?': _keyHelp,
        'h': _keyHelp,
        '\n': lambda c: print(),  # 1 empty line
        '\x03': _keyShutdownCSE,  # See handler below
        'c': _keyConfiguration,
        'C': _keyClearScreen,
        'D': _keyDeleteResource,
        'i': _keyInspectResource,
        'l': _keyToggleLogging,
        'Q': _keyShutdownCSE,  # See handler below
        'r': _keyCSERegistrations,
        's': _keyStatistics,
        't': _keyResourceTree,
        'T': _keyChildResourceTree,
        'w': _keyWorkers,
    }

    #	Endless runtime loop. This handles key input & commands
    #	The CSE's shutdown happens in one of the key handlers below
    loop(commands, catchKeyboardInterrupt=True, headless=args.headless)
    shutdown()
Exemple #16
0
    def __init__(self, url=None):

        self.loadConfiguration()

        self.logger.info('Starting Radio Tray...')

        # load configuration

        # load bookmarks data provider and initializes it
        self.provider = XmlDataProvider(self.filename)
        self.provider.loadFromFile()

        # load config data provider and initializes it
        self.cfg_provider = XmlConfigProvider(self.cfg_filename)
        self.cfg_provider.loadFromFile()

        # load default config data provider and initializes it
        self.default_cfg_provider = XmlConfigProvider(
            self.default_cfg_filename)
        self.default_cfg_provider.loadFromFile()

        # load Event Manager
        eventManager = EventManager()
        eventManagerWrapper = EventMngNotificationWrapper(eventManager)

        # mediator
        self.mediator = StateMediator(self.provider, self.cfg_provider,
                                      eventManager)

        # load audio player
        self.audio = AudioPlayerGStreamer(self.mediator, self.cfg_provider,
                                          eventManager)

        # tooltip manager
        tooltipManager = TooltipManager()
        self.logger.debug("Tooltip manager initialized.")

        # chooser
        if (url == '--config'):
            chooser = GuiChooserConfiguration()
            gui_engine = chooser.run()
            self.cfg_provider.setConfigValue("gui_engine", gui_engine)
            url = None
        # load gui
        self.systray = SysTray(self.mediator, self.provider, self.cfg_provider,
                               self.default_cfg_provider, eventManager,
                               tooltipManager)
        self.logger.debug("GUI initialized")

        # notification manager
        self.notifManager = NotificationManager(eventManagerWrapper)

        # bind events
        eventSubscriber = EventSubscriber(eventManager)
        eventSubscriber.bind(EventManager.STATE_CHANGED,
                             self.mediator.on_state_changed)
        eventSubscriber.bind(EventManager.STATE_CHANGED,
                             self.systray.on_state_changed)
        eventSubscriber.bind(EventManager.STATE_CHANGED,
                             self.notifManager.on_state_changed)
        eventSubscriber.bind(EventManager.SONG_CHANGED,
                             self.notifManager.on_song_changed)
        eventSubscriber.bind(EventManager.SONG_CHANGED,
                             self.mediator.on_song_changed)
        eventSubscriber.bind(EventManager.SONG_CHANGED,
                             self.systray.on_song_changed)
        eventSubscriber.bind(EventManager.STATION_ERROR,
                             self.notifManager.on_station_error)
        eventSubscriber.bind(EventManager.VOLUME_CHANGED,
                             self.systray.on_volume_changed)
        eventSubscriber.bind(EventManager.BOOKMARKS_RELOADED,
                             self.notifManager.on_bookmarks_reloaded)

        # config mediator
        self.mediator.init(self.audio)

        # start dbus facade
        dbus = DbusFacade(self.provider, self.mediator)
        #dbus_mpris = mpris.RadioTrayMpris(self.provider, self.mediator)

        #load plugin manager
        self.pluginManager = PluginManager(eventManagerWrapper,
                                           eventSubscriber, self.provider,
                                           self.cfg_provider, self.mediator,
                                           tooltipManager,
                                           self.systray.getPluginMenu())
        self.systray.setPluginManager(self.pluginManager)
        self.pluginManager.discoverPlugins()
        self.pluginManager.activatePlugins()

        if (url != None):
            if (url == "--resume"):
                self.mediator.playLast()
            else:
                self.mediator.playUrl(url)
        # start app
        self.systray.run()
Exemple #17
0
# Uses the requests library to get the HTML from Billboard Top100 on the specified date
response = requests.get(BASE_URL + date)
response.raise_for_status()

# Uses Beautiful Soup to scrap song title from the HTML page and compile them as a list
soup = BeautifulSoup(response.text, "html.parser")
# song_title_tags = soup.find_all(name="span", class_="chart-element__information__song")
song_title_tags = soup.find_all(name="h3", class_="a-font-primary-bold-s")
songs = [tag.getText() for tag in song_title_tags]

# Initialises the custom class SpotifyManager with the date (see description in the class itself)
sm = SpotifyManager(date)

# Gets the list of users from the subscribers Google Sheet
um = UserManager()
users = um.get_users()

# Uses list comprehension to make a list of song URIs ("if" statement checks if the element in the list exists -
# method get_song_uri car return None if there is no such song on Spotify)
track_URIs = [sm.get_song_uri(song) for song in songs if sm.get_song_uri(song)]
# Creates the playlist with songs from previous step
playlist = sm.create_playlist(tracks=track_URIs)

# Initialize Nmtification Manager with the current playlist
nm = NotificationManager(playlist)

# Send e-mails to all subscribed users
for user in users:
    nm.send_email(user)
class ServerMQTTMessageManager(object):
    def __init__(self):

        self.send_next_image = False
        self.is_active = False
        self.notification_manager = NotificationManager()

    def message_handler(self, message):

        if message.topic.startswith("IMAGE_REC"):
            self.handle_person_image(message.payload)

        #person recognition by raspberry
        else:
            new_value_command, new_value_rec = self.get_value_from_payload(
                message.payload)
            if new_value_command is not None:
                if new_value_command == 1.0:
                    self.is_active = True
                elif new_value_command == 0.0:
                    PersonRecStatusFileManager.save_last_person_rec_status(
                        "0.0")
                    self.is_active = False
            if new_value_rec is not None:
                self.handle_person_rec_update(new_value_rec)

    def get_value_from_payload(self, payload):

        message_string = payload.decode(encoding='UTF-8')
        msg_json = json.loads(message_string)

        new_value_command = None
        new_value_rec = None

        if "cep_output" in msg_json:
            if "event_0" in msg_json["cep_output"] and "value" in msg_json[
                    "cep_output"]["event_0"]:
                new_value_rec = float(
                    msg_json["cep_output"]["event_0"]["value"])
            if "event_1" in msg_json["cep_output"] and "value" in msg_json[
                    "cep_output"]["event_1"]:
                new_value_command = float(
                    msg_json["cep_output"]["event_1"]["value"])
        else:
            print("improper message format")
            return
        return new_value_command, new_value_rec

    def handle_person_rec_update(self, new_value):

        if not self.is_active:
            return

        last_value = PersonRecStatusFileManager.get_last_person_rec_status()
        PersonRecStatusFileManager.save_last_person_rec_status(new_value)

        if self.notification_manager.should_notify(float(last_value),
                                                   new_value):
            self.send_next_image = True

    def handle_person_image(self, image_data):

        if self.send_next_image:
            now = datetime.now()
            filename = now.strftime("%d-%m-%Y-%H-%M") + ".jpeg"
            target = os.path.join(APP_ROOT, 'images/')
            if not os.path.isdir(target):
                os.mkdir(target)
            destination = "/".join([target, filename])
            f = open(destination, "wb")
            f.write(image_data)
            self.notification_manager.send_notification(filename)
            self.send_next_image = False