def receive(self, mail_message): # We don't bother with the message body, it will be too long for Notifo. sender = mail_message.sender # e.g. "sender <*****@*****.**>" subject = mail_message.subject # e.g. "Hello there..." to = mail_message.to # e.g. "*****@*****.**" to = to[:to.index('@')] notifo.send_notification(config.NOTIFO_SERVICE, config.NOTIFO_KEY, config.NOTIFO_USER, title=to, msg=subject)
def _send_notification(self, name, crash_message): notifo.send_notification( self.api_user, self.api_token, to=self.api_user, title=name, msg=crash_message, label='CrashHound' )
def notifyDrivesOverMaxCapacity(): print('notifyDrivesOverMaxCapacity executed') if getSetting('NotifyOverMaxCapacity') == 'True': if (Drive.objects.all().count() == 0): return for drive in Drive.objects.all(): isOver = checkDriveOverMaxCapacity(drive) overBy = getDriveOverMaxCapacity(drive) print(drive.Name) print(overBy) if isOver: notifo.send_notification(settings.notifoUser,settings.notifoSecret,settings.notifoUser,('FSLM is notifying you that one of your managed drives: %s is over its maximum capacity by %s')%(drive.Name, overBy))
def notifo_webhook(request): if request.method == 'POST': if str(sig(request.POST)) == str(request.POST['notifo_signature']): resp = notifo.send_notification(USER_NAME, API_KEY, to=str(request.POST['notifo_from_username']), msg='boop') else: pass return HttpResponse('done')
def get(self): user = users.get_current_user() if user: q = db.GqlQuery("SELECT * FROM Developer WHERE person = :1", user) dev_user = q.get() if not dev_user: apikey = str(uuid.uuid4()).replace('-', '') dev_user = developer.Developer(person=user, apikey=apikey) dev_user.put() notifo.send_notification(config.NOTIFO_SERVICE, config.NOTIFO_KEY, config.NOTIFO_USER, title='New User', msg=user.email()) q = db.GqlQuery("SELECT * FROM Application WHERE person = :1", user) dev_user_apps = q.fetch(config.WORQ_CONFIG['max_app_user']) values = {'dev_user': dev_user, 'dev_user_apps': dev_user_apps} else: values = {} page = view.Page() page.render(self, 'templates/page/index.html', values)
def moveFolderBackground(moveQueueID): mi = MoveQueueItem.objects.get(id=int(moveQueueID)) if mi: #set start time mi.StartTime = datetime.now() mi.save() #If the folder exists make a copy instead of a move if os.path.exists(mi.DestFolder): shutil.copy2(mi.SourceFolder, mi.DestFolder) shutil.rmtree(mi.SourceFolder) else: shutil.move(mi.SourceFolder,mi.DestFolder) #set the finish time instead of deleting mi.EndTime = datetime.now() mi.save() kbSaved = mi.PotentialSpaceFreed * 1024 k = mi.EndTime - mi.StartTime rate = round(kbSaved / k.seconds) notifo.send_notification(settings.notifoUser,settings.notifoSecret,settings.notifoUser,('%s Moved successfully from %s to %s at an average rate of %s kb/s')%( mi.SourceFolder , mi.StartTime.strftime('%d %b %H:%M'), mi.EndTime.strftime('%d %b %H:%M'), rate.__str__())) return 'Folder Moved' else: return 'No Queue Item Found'
def notify(request, motion_id): done = {'status':'fail'} try: title="Motion detected!" msg=" %s." % motion_id label="rpiMotionTracker" uri= '/admin/motiontracker/motiontracked/%s/' % motion_id done = notifo.send_notification(settings.NOTIFO_LOGIN, settings.NOTIFO_TOKEN, settings.NOTIFO_LOGIN, msg, label, title, uri) return HttpResponse(json.dumps(done),mimetype="application/json") except Exception, e: print e return HttpResponse(json.dumps(done),mimetype="application/json")
def main(): """ main function """ # get options and arguments (parser, options, args) = init_parser() # initialize result variable result = None # check for values which are always needed if not options.user: parser.error("No user given.") if not options.secret: parser.error("No API secret given.") if not options.name: parser.error("No recipient given.") if not options.message_type: options.message_type = "notification" if len(args) < 1: result = notifo.subscribe_user(options.user, options.secret, options.name) else: params = {} params["to"] = options.name m = '' for a in args: m = "%s %s" %(m, a) params["msg"] = m if options.message_type == "message": result = notifo.send_message(options.user, options.secret, **params) elif options.message_type == "notification": if options.label: params["label"] = options.label if options.title: params["title"] = options.title if options.callback: params["uri"] = options.callback result = notifo.send_notification(options.user,options.secret, **params) if result is None: print "Something went wrong. Check parameters and try again."
def main(): """ main function """ # get options and arguments (parser, options, args) = init_parser() # initialize result variable result = None # check for values which are always needed if not options.user: parser.error("No user given.") if not options.secret: parser.error("No API secret given.") if not options.name: parser.error("No recipient given.") # If there is no message, we probably want to subscribe a user if len(args) < 1: result = notifo.subscribe_user(options.user, options.secret, options.name) else: params = {} params["to"] = options.name m = '' for a in args: m = "%s %s" % (m, a) params["msg"] = m if options.message == True: result = notifo.send_message(options.user, options.secret, **params) else: if options.label: params["label"] = options.label if options.title: params["title"] = options.title if options.callback: params["uri"] = options.callback result = notifo.send_notification(options.user, options.secret, **params) if result is None: print "Something went wrong. Check parameters and try again."
def sendAlert(key, usage, date): if not has_pynma and not has_notifo: raise ImportError("No notification modules loaded") global p pkey = None message = "You have used %sGB bandwidth in %s" % (usage,date) if has_pynma: p = PyNMA() p.addkey(key) res = p.push("Comcast Bandwidth Check", 'Daily Update', message, 'http://misfoc.us', batch_mode=False) if has_notifo: if notifo_username == '' or notifo_secret == '': raise SystemExit("No API username/secret specified for Notifo notifications.") res = notifo.send_notification(notifo_username, notifo_secret, notifo_username, message, "Comcast Bandwidth Check", "Daily Update")
#!/usr/bin/env python # Send download notifications from Sabnzbd to iPhone import sys import notifo # Notifo API settings USERNAME = "******" API_KEY = "apikeyhere" # Get NZB info job = dict(name=sys.argv[3], status=int(sys.argv[7])) if job['status'] == 0: job['long_status'] = "OK" elif job['status'] == 1: job['long_status'] = "failed verification" elif job['status'] == 2: job['long_status'] = "failed unpacking" elif job['status'] == 3: job['long_status'] = "failed verification & unpacking" if job['status'] == 0: print notifo.send_notification(USERNAME, API_KEY, USERNAME, "{name} downloaded successfully".format(**job), "Sabnzbd", "Download Complete") else: print notifo.send_notification(USERNAME, API_KEY, USERNAME, "{name} {long_status}".format(**job), "Sabnzbd", "Download Failed")
def test_notify_self(self): res = send_notification(self.user, self.user_token, to=self.user, msg="foo test") self.assertEqual(2201, res["response_code"])
def test_message_with_label(self): res = send_notification(self.user, self.user_token, to=self.user, msg="foo test", label="label") self.assertEqual(2201, res["response_code"])
def test_message_with_plain_args(self): res = send_notification(self.user, self.user_token, self.user, "foo test", "label") self.assertEqual(2201, res["response_code"])
def log(longid): """View or add to a log.""" if request.method == 'POST': # Add to log. message = request.form['message'][:app.config['MAX_MSG_LENGTH']] try: level = request.form['level'] except KeyError: level = app.config['MIN_LEVEL'] try: level = int(level) except ValueError: level = app.config['MIN_LEVEL'] level = max(level, app.config['MIN_LEVEL']) level = min(level, app.config['MAX_LEVEL']) logid, loginfo = _get_log(longid) with g.db: # Add new message. g.db.execute("INSERT INTO messages (logid, message, time, level) " "VALUES (?, ?, ?, ?)", (logid, message, int(time.time()), level)) # Drop old messages. g.db.execute("DELETE FROM messages WHERE id IN (SELECT id FROM " "messages WHERE logid = ? ORDER BY time DESC, id DESC " "LIMIT -1 OFFSET ?)", (logid, app.config['MAX_MESSAGES'])) # Send notifications. if level >= app.config['NOTIFICATION_THRESHOLD']: logname = loginfo['title'] or longid logurl = flask.url_for('log', longid=longid, _external=True) # Notifo. if loginfo['notifoname']: resp = notifo.send_notification( app.config['NOTIFO_USER'], app.config['NOTIFO_SECRET'], loginfo['notifoname'], title=logname, msg=message, uri=logurl ) if resp['status'] != 'success': log.warn('notifo notification failed: %s' % resp) return flask.jsonify(success=1) else: # Show log. try: tzoffset = float(request.args['tzoffset']) except (KeyError, ValueError): tzoffset = 0.0 messages, loginfo = _log_contents(longid) return flask.render_template('log.html', messages=messages, title=loginfo['title'], notifoname=loginfo['notifoname'], longid=longid, tzoffset=tzoffset)
def log(longid): """View or add to a log.""" if request.method == 'POST': # Add to log. message = request.form['message'][:app.config['MAX_MSG_LENGTH']] try: level = request.form['level'] except KeyError: level = app.config['MIN_LEVEL'] try: level = int(level) except ValueError: level = app.config['MIN_LEVEL'] level = max(level, app.config['MIN_LEVEL']) level = min(level, app.config['MAX_LEVEL']) logid, loginfo = _get_log(longid) with g.db: # Add new message. g.db.execute("INSERT INTO messages (logid, message, time, level) " "VALUES (?, ?, ?, ?)", (logid, message, int(time.time()), level)) # Drop old messages. g.db.execute("DELETE FROM messages WHERE id IN (SELECT id FROM " "messages WHERE logid = ? ORDER BY time DESC, id DESC " "LIMIT -1 OFFSET ?)", (logid, app.config['MAX_MESSAGES'])) # Send notifications. if level >= app.config['NOTIFICATION_THRESHOLD']: logname = loginfo['title'] or longid logurl = flask.url_for('log', longid=longid, _external=True) # Notifo. if loginfo['notifoname']: resp = notifo.send_notification( app.config['NOTIFO_USER'], app.config['NOTIFO_SECRET'], loginfo['notifoname'], title=logname, msg=message, uri=logurl ) if resp['status'] != 'success': log.warn('notifo notification failed: %s' % resp) return flask.jsonify(success=1) else: # Show log. try: tzoffset = float(request.args['tzoffset']) except (KeyError, ValueError): tzoffset = 0.0 # Concoct the URL for the reverse-order listing. reversed_args = dict(request.args) if not reversed_args.get('reverse'): reversed_args['reverse'] = '1' elif 'reverse' in reversed_args: del reversed_args['reverse'] reversed_url = url_with_args(request.base_url, reversed_args) # ... and the alternate-format URLs. text_url = url_with_args(flask.url_for('logtxt', longid=longid), request.args) json_url = url_with_args(flask.url_for('logjson', longid=longid), request.args) feed_url = flask.url_for('logfeed', longid=longid) messages, loginfo = _log_contents(longid, request.args.get('reverse', False)) return flask.render_template( 'log.html', messages=messages, title=loginfo['title'], notifoname=loginfo['notifoname'], longid=longid, tzoffset=tzoffset, reversed_url=reversed_url, text_url=text_url, json_url=json_url, feed_url=feed_url, )
def test_message_with_title(self): res = send_notification(self.user, self.user_token, to=self.user, msg="foo test", title="title") self.assertEqual(2201, res["response_code"])
def test_message_with_callback(self): res = send_notification(self.user, self.user_token, to=self.user, msg="foo test", uri="http://example.org") self.assertEqual(2201, res["response_code"])
def test_message_from_provider(self): res = send_notification(self.provider, self.provider_token, to=self.user, msg="foo test") self.assertEqual(2201, res["response_code"])
def post(self, action): self.response.headers['Content-Type'] = 'application/json' key = cgi.escape(self.request.get('key')) arg = cgi.escape(self.request.get('arg')) # Check for 'key'. if key == '': self.response.set_status(400) # Bad Request self.response.out.write('{"error": "Bad Request"}\n') return # Check for 'arg' and 'action' that does not require an argument. if action not in ['refresh_api_key'] and arg == '': self.response.set_status(400) # Bad Request self.response.out.write('{"error": "Bad Request"}\n') return # Get the Developer object. q = db.GqlQuery("SELECT * FROM Developer WHERE apikey = :1", key) dev_user = q.get() if not dev_user: self.response.set_status(401) # Unauthorized self.response.out.write('{"error": "Unauthorized"}\n') return # Check for the account status. if dev_user.enabled == False: self.response.set_status(401) # Unauthorized self.response.out.write('{"error": "Unauthorized"}\n') return # Perform the action. ####################################### # Perform the refresh_api_key action. # ####################################### if action == 'refresh_api_key': apikey = str(uuid.uuid4()).replace('-', '') dev_user.apikey = apikey dev_user.put() result = apikey ######################################### # Perform the change_public_key action. # ######################################### elif action == 'change_public_key': dev_user.publickey = arg dev_user.put() if not APPENGINE_ONLY: form_data = '{"action": "%s", "username": "******", "publickey": "%s"}' % (action, dev_user.person.email(), dev_user.publickey) form_result = urlfetch.fetch(url='http://worqshop.com:8000', payload=form_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}) if form_result.status_code != 200: self.response.set_status(500) # Internal Server Error self.response.out.write('{"error": "Internal Server Error"}\n') result = 'OK' ########################################## # Perform the create_application action. # ########################################## elif action == 'create_application': if arg in ['gitosis-admin']: self.response.set_status(400) # Bad Request self.response.out.write('{"error": "Bad Request"}\n') return q = db.GqlQuery("SELECT * FROM Application WHERE name = :1", arg) app = q.get() if app: self.response.set_status(400) # Bad Request self.response.out.write('{"error": "Bad Request"}\n') return appcount = dev_user.appcount if appcount >= config.WORQ_CONFIG['max_app_user']: self.response.set_status(400) # Bad Request self.response.out.write('{"error": "Bad Request"}\n') return w_conf = configuration.Configuration.get_or_insert(config.WORQ_CONFIG['config_name']) appcount = w_conf.appcount if appcount >= config.WORQ_CONFIG['max_app_site']: self.response.set_status(400) # Bad Request self.response.out.write('{"error": "Bad Request"}\n') return host = config.AWS_HOSTS[appcount % len(config.AWS_HOSTS)] port = str(config.WORQ_CONFIG['port_start'] + appcount) app = application.Application(person=dev_user.person, name=arg, host=host, port=port) app.put() notifo.send_notification(config.NOTIFO_SERVICE, config.NOTIFO_KEY, config.NOTIFO_USER, title='New Application', msg='%s %s' % (arg, dev_user.person.email())) dev_user.appcount += 1 dev_user.put() w_conf.appcount += 1 w_conf.put() if not APPENGINE_ONLY: form_data = '{"action": "%s", "username": "******", "appname": "%s", "host": "%s", "port": "%s"}' % (action, dev_user.person.email(), app.name, host, port) form_result = urlfetch.fetch(url='http://worqshop.com:8000', payload=form_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}) if form_result.status_code != 200: self.response.set_status(500) # Internal Server Error self.response.out.write('{"error": "Internal Server Error"}\n') result = port ########################################### # Perform the destroy_application action. # ########################################### elif action == 'destroy_application': q = db.GqlQuery("SELECT * FROM Application WHERE name = :1", arg) app = q.get() if not app: self.response.set_status(400) # Bad Request self.response.out.write('{"error": "Bad Request"}\n') return if not APPENGINE_ONLY: form_data = '{"action": "%s", "username": "******", "appname": "%s"}' % (action, dev_user.person.email(), app.name) form_result = urlfetch.fetch(url='http://worqshop.com:8000', payload=form_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded'}) if form_result.status_code != 200: self.response.set_status(500) # Internal Server Error self.response.out.write('{"error": "Internal Server Error"}\n') app.delete() result = 'OK' ################################## # Cannot find an action handler. # ################################## else: self.response.set_status(400) # Bad Request self.response.out.write('{"error": "Bad Request"}\n') return self.response.set_status(200) # OK self.response.out.write('{"result": "%s"}\n' % result)
def msg(self,title,msg,uri): notifo.send_notification(self.login, self.secret, self.login, msg, self.label, title, uri)