예제 #1
0
 def read(self, mac):
     global result
     result = {}
     try:
         if mac in globals.KEEPED_CONNECTION:
             logging.debug('Already a connection for ' + mac + ' use it')
             conn = globals.KEEPED_CONNECTION[mac]
         else:
             logging.debug('Creating a new connection for ' + mac)
             conn = Connector(mac)
             globals.KEEPED_CONNECTION[mac] = conn
             conn.connect()
         if not conn.isconnected:
             conn.connect()
             if not conn.isconnected:
                 return
         notification = Notification(conn, Smartplug)
         conn.writeCharacteristic('0x2b', '0f050400000005ffff')
         notification.subscribe(2)
         return
     except Exception as e:
         try:
             conn.disconnect()
         except Exception as e:
             pass
         logging.error(str(e))
     return
예제 #2
0
    def read(self, mac):
        result = {}
        try:
            conn = Connector(mac)
            conn.connect()
            if not conn.isconnected:
                conn.connect()
                if not conn.isconnected:
                    return

            logging.debug('read batteryFirm')
            batteryFirm = bytearray(conn.readCharacteristic('0x18'))
            battery = batteryFirm[0]
            firmware = "".join(map(chr, batteryFirm[2:]))
            notification = Notification(conn, Mithermaff)
            logging.debug('write 0x10 0100 to get sensor values')
            conn.writeCharacteristic('0x10', '0100', response=True)
            notification.subscribe(2)
            result['battery'] = battery
            result['firmware'] = firmware
            result['id'] = mac
            logging.debug(str(result))
            return result
        except Exception, e:
            logging.error(str(e))
예제 #3
0
    def get_notifications(self, old_stars, old_watchers, old_forks):
        new_stars, new_watchers, new_forks = self.stars, self.watchers, self.forks

        delta_stars = new_stars - old_stars
        delta_watchers = new_watchers - old_watchers
        delta_forks = new_forks - old_forks

        notifications = []
        if delta_stars != 0:
            context = 'starr'
            if delta_stars < 0:
                context = 'un' + context # not a typo

            notifications.append(Notification.generate_message('{} users'.format(delta_stars), context, self.name))

        if delta_watchers != 0:
            context = 'watch'
            if delta_watchers < 0:
                context = 'un' + context

            notifications.append(Notification.generate_message('{} users'.format(delta_watchers), context, self.name))

        if delta_forks != 0:
            context = 'fork'
            if delta_forks < 0:
                context = 'un' + context

            notifications.append(Notification.generate_message('{} users'.format(delta_watchers), context, self.name))

        return notifications
예제 #4
0
def lambda_handler(event, context):
    # This is the function that is called by Lambda (like a Main function)

    # Fetch all records from the last week
    dynamoService = database.DynamoService()
    now = int(time.time())
    oneWeekAgo = now - (7 * 24 * 60 * 60)
    print("Getting items")
    identifierList = dynamoService.getItemIdentifiersAfterTimestamp(oneWeekAgo)

    # Get nutrition data on all food
    nutritionService = NutritionService()
    nutrition = nutritionService.getMockNutritionData()
    print("Querying for nutrition")
    for identifiers in identifierList:
        n = nutritionService.getNutritionByIdentifiers(identifiers)
        if n is not None:
            nutrition.append(n)

    # Generate HTML report
    nutritionReport = NutrtritionReport()
    url = nutritionReport.getHTML(nutrition)

    # Send user notification
    notificationService = Notification()
    message = "Your weekly Nutrition Report is ready. Download here: " + str(
        url)
    notificationService.sendNotification(message)
    return message
예제 #5
0
    def start_video_stream(self, stream_source):
        """
        Starts a video stream using a camera source
        :param stream_source: Sets the stream source (camera source) of the stream.
                                stream_source = 0 stream using system webcam,
                                stream_source = 1, 2, 3 .. : stream using connected camera/camera's.
        """
        vs = cv2.VideoCapture(stream_source)
        time.sleep(2.0)
        Interface.update_progress_bar(100)
        Interface.update_info_text(
            "Press 'q' to quit window | press 's' to send email of last detection"
        )
        while True:
            frame_exist, frame = vs.read()
            frame = imutils.resize(frame, width=400)
            self.start_mask_detection(frame=frame)
            key = cv2.waitKey(1) & 0xFF
            if key == ord("q"):
                Interface.canvas.create_image(
                    150, 150, image=VideoMaskDetection.offender_img)
                Interface.update_progress_bar(0)
                Interface.update_info_text("")
                break
            elif key == ord("s"):
                Notification.notify()

        vs.release()
        cv2.destroyAllWindows()
예제 #6
0
 def getStatus(self, mac):
     logging.debug('STATUS BLPNR')
     try:
         conn = Connector(mac)
         if not conn.isconnected:
             conn.connect(type='random')
             if not conn.isconnected:
                 return
         conn.writeCharacteristic('0x000f', '2902')
         conn.disconnect()
     except Exception as e:
         logging.error(str(e))
     try:
         conn = Connector(mac)
         if not conn.isconnected:
             conn.connect(type='random')
             if not conn.isconnected:
                 return
         logging.debug('READ notif BLPNR')
         notification = Notification(conn, Blpnr)
         #notification.subscribe(10,disconnect=True)
         notification.subscribe()
         conn.writeCharacteristic('0x0011', '0d00000d00')
     except Exception as e:
         logging.error(str(e))
예제 #7
0
 def main(self):
     sense = SenseEnvironment()
     notify = Notification()
     while True:
         # to get all devices which are paired with raspberry pi.
         p = sp.Popen(["bt-device", "--list"],
                      stdin=sp.PIPE,
                      stdout=sp.PIPE,
                      close_fds=True)
         (stdout, stdin) = (p.stdout, p.stdin)
         data = stdout.readlines()
         # Get the mac address as a string
         str_mac = str(data)
         str_mac = str(re.findall("\((.*?)\)", str_mac))
         str_mac = str_mac[2:len(str_mac) - 2]
         # searching for surrounding Bluetooth devices
         nearbyDevices = bluetooth.discover_devices()
         for macAddress in nearbyDevices:
             # checking if the mac address founded is matching the one already paired.
             if macAddress == str_mac:
                 if self.isInOneHour(macAddress) is False:
                     temp = sense.senseTmp()
                     hum = sense.senseHum()
                     notify.send_notification_via_pushbullet(
                         "",
                         " The temperature is {} and the humidity is {}".
                         format(temp, hum))
                     self.db.insert(str_mac)
         # 20 sec before next scanning
         time.sleep(20)
예제 #8
0
class List2SystemTray(UserDict.DictMixin):
    def __init__(self, icon, parent=None):
        self.system_tray_icon = SystemTrayIcon(icon, parent)
        self.system_tray_icon.show()
        self.item_to_action_dict = {}
        # self.msg("App started")
        self.notification_window = None

    def __setitem__(self, key, value):
        action = self.system_tray_icon.menu.addAction(key)
        action.triggered.connect(value)
        self.item_to_action_dict[key] = value

    def __delitem__(self, key):
        action = self.system_tray_icon.menu.removeAction(key)
        # action.triggered.connect(value)
        action.triggerd.disconnect()
        del self.item_to_action_dict[key]

    def msg(self, msg):
        # self.system_tray_icon.showMessage("Ufs system", msg, 20000)
        try:
            self.notification_window = Notification()
        except:
            import traceback

            traceback.print_exc()
        self.notification_window.noti(msg)
예제 #9
0
파일: light.py 프로젝트: BestPig/i3_tools
    def run(self):
        if not self.args.lightcommand:
            self.parser.print_help(sys.stderr)
            return
        if self.args.lightcommand == 'inc':
            self.logger.info('Increase brightness of %d%%' % self.args.value)
            check_output(self.values['increase_cmd'] % (self.args.value),
                         shell=True)
        elif self.args.lightcommand == 'dec':
            self.logger.info('Decrease brightness of %d%%' % self.args.value)
            check_output(self.values['decrease_cmd'] % (self.args.value),
                         shell=True)
        else:
            self.logger.info('Set brightness to %d%%' % self.args.value)
            check_output(self.values['set_cmd'] % (self.args.value),
                         shell=True)

        current_value = int(
            float(check_output(self.values['get_cmd'], shell=True)))
        if current_value < 50:
            icon = self.values['icon-low']
        elif current_value < 75:
            icon = self.values['icon-medium']
        elif current_value < 100:
            icon = self.values['icon-high']
        else:
            icon = self.values['icon-full']
        Notification.sendNotification("Brightness", icon, current_value)
예제 #10
0
 def read(self, mac):
     result = {}
     #account verify : 0x29
     #realtimedata : 0x30
     #settings : 0x34
     #settingsresult : 0x25
     #historydata : 0x2c
     #
     #credentials :  0x21, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0xb8, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00
     #
     #enablerealtime : 0x0B, 0x01, 0x00, 0x00, 0x00, 0x00
     #
     #units celcisu : 0x02, 0x00, 0x00, 0x00, 0x00, 0x00
     # defini seuil : dans 0x34 ecrire 010X48f4YYYY  avec x numero de sonde (commencant a 0) et y temperature x10 inverse
     #
     #0x31 0100 activer notif temp
     #batterie 0x34 082400000000
     try:
         conn = Connector(mac)
         conn.connect()
         if not conn.isconnected:
             conn.connect()
             if not conn.isconnected:
                 return
         conn.writeCharacteristic('0x29',
                                  '2107060504030201b8220000000000',
                                  response=True)
         notification = Notification(conn, Ibbq6)
         conn.writeCharacteristic('0x26', '0100', response=True)
         conn.writeCharacteristic('0x34', '082400000000', response=True)
         notification.subscribe(10)
         return result
     except Exception as e:
         logging.error(str(e))
     return result
예제 #11
0
 def _mail_log_action(self, subject, body):
     ses_settings = self._config['ses_settings']
     notif = Notification(aws_access_key=ses_settings['aws_access_key'],
                          aws_secret_key=ses_settings['aws_secret_key'],
                          region=ses_settings['region'])
     html_body = format_html_mail_body(self.app, self.job, self._config)
     log_path = self._get_log_path()
     log = {
         'original_log_path': log_path,
         'filename': os.path.basename(log_path),
     }
     try:
         for log_notif in self.app.get('log_notifications', []):
             mail = log_notif.get('email')
             if (mail and
                 (self.job['status'] in log_notif.get('job_states', [])
                  or ''.join(log_notif.get('job_states', [])) == '*')):
                 notif.send_mail(From=ses_settings.get(
                     'mail_from', MAIL_LOG_FROM_DEFAULT),
                                 To=mail,
                                 subject=subject,
                                 body_text=body,
                                 body_html=html_body,
                                 attachments=[log],
                                 sender_name='Cloud Deploy')
             pass
     except:
         self._init_log_file()
         logging.exception(
             "An exception occurred when trying to send the Job mail notification."
         )
         traceback.print_exc()
         self._close_log_file()
예제 #12
0
 def action(self, message):
     mac = message['device']['id']
     handle = message['command']['handle']
     value = message['command']['value']
     conn = Connector(mac)
     conn.connect()
     if not conn.isconnected:
         conn.connect()
         if not conn.isconnected:
             return
     try:
         if 'key' in message['command']:
             conn.writeCharacteristic('0x19',
                                      message['command']['key'],
                                      response=True)
         if handle == '0x4e':
             conn.writeCharacteristic(handle, value, response=True)
             conn.connect()
             if not conn.isconnected:
                 conn.connect()
                 if not conn.isconnected:
                     return
             conn.writeCharacteristic('0x51', '04')
             notification = Notification(conn, Miband)
             notification.subscribe(20)
             conn.writeCharacteristic('0x4c', '0100', response=True)
         else:
             conn.writeCharacteristic(handle, value)
             if value == '02':
                 time.sleep(10)
             conn.disconnect()
     except Exception as e:
         logging.error(str(e))
         conn.disconnect()
     return
예제 #13
0
 def read(self, mac):
     result = {}
     try:
         conn = Connector(mac)
         conn.connect()
         if not conn.isconnected:
             conn.connect()
             if not conn.isconnected:
                 return
         if (mac in globals.KNOWN_DEVICES
                 and globals.KNOWN_DEVICES[mac]['model']
                 == 'xiaomiht/xiaomiht_cleargrass'):
             Firm = bytearray(conn.readCharacteristic('0x2a'))
         else:
             Firm = bytearray(conn.readCharacteristic('0x24'))
             batt = bytearray(conn.readCharacteristic('0x18'))
             battery = batt[0]
             result['battery'] = battery
         firmware = "".join(map(chr, Firm))
         result['firmware'] = firmware
         notification = Notification(conn, XiaomiHT)
         conn.writeCharacteristic('0x10', '0100', response=True)
         notification.subscribe(2)
         result['id'] = mac
         logging.debug('XIAOMIHT------' + str(result))
         return result
     except Exception as e:
         logging.error(str(e))
     return result
    def run(self):
        for raw_notification in self._consumer:
            partition = raw_notification[0]
            offset = raw_notification[1].offset
            message = raw_notification[1].message.value

            notification_data = json.loads(message)

            ntype = notification_data['type']
            name = notification_data['name']
            addr = notification_data['address']
            period = notification_data['period']

            notification = Notification(ntype, partition, offset, name, addr,
                                        period,
                                        notification_data['retry_count'],
                                        notification_data['raw_alarm'])

            if self._keep_sending(notification.alarm_id, notification.state):
                wait_duration = period - (
                    time.time() - notification_data['notification_timestamp'])

                if wait_duration > 0:
                    time.sleep(wait_duration)

                notification.notification_timestamp = time.time()

                self._notifier.send([notification])
                self._producer.publish(self._topic_name,
                                       [notification.to_json()])

            self._consumer.commit()
예제 #15
0
 def _post_order(self, res_json, value, amount, operator):
     """Post processing after getting order."""
     head = HEAD_FORMAT.format(
         datetime.utcnow().strftime(DATETIME_FORMAT),
         self.config.platform, self.config.username,
         value, amount, operator)
     msg = res_json.get('errorMsg', res_json)
     data = res_json.get('data', {})
     if msg == 'OK':
         print('{} 抢到 {} 单'.format(head, len(data)))
         for order in data:
             args = {
                 'platform': self.config.platform,
                 'username': self.config.username,
                 'mobile': order['rechargeAccount'],
                 'province': order['product']['province'],
                 'operator': OPERATORS[order['product']['operator']],
                 'value': order['product']['faceValue']
             }
             if self.config.auto_confirmation:
                 Timer(self.config.confirm_delay, self._confirm_order,
                       [order['id'], args]).start()
             Notification.send_get_order(args)
     else:
         print('{} {}'.format(head, msg))
     return len(data)
예제 #16
0
def available_networks_err(*values):
	global networks
	
	networks['time'] = int(time())
	networks['acquire'] = False

	notify = Notification()
	notify.info('No Cellular Network found' % len(networks['gtklist']))
예제 #17
0
    def msg(self, msg):
        # self.system_tray_icon.showMessage("Ufs system", msg, 20000)
        try:
            self.notification_window = Notification()
        except:
            import traceback

            traceback.print_exc()
        self.notification_window.noti(msg)
예제 #18
0
 def add_notification(self, notification_type, layout, time=None):
     notification = Notification()
     if notification_type == 'create':
         notification.layout = layout
         self.createNotification = notification
     elif notification_type == 'update':
         notification.set('time', time)
         notification.layout = layout
         self.updateNotification = notification
     raise TypeError('Unknown notification type: %s', notification_type)
예제 #19
0
    def create_report(report_duration, interval, image_path, log_path, percentage, threshold, person_detected, frame):
        elapsed_time = time.time() - starting_time_system
        notification = Notification()
        if threshold < percentage:
            if report_duration <= elapsed_time:
                report_duration = elapsed_time + interval
                notification.send_notification()
                Report.save_crowd_image(image_path, frame)
                Report.write_log(log_path, percentage, person_detected)

        return report_duration
예제 #20
0
    def __init__(self, setting_name):
        setup_logger()
        logging.info('Shit_Happened initializing...')
        self.storage_name = None
        self.notification = Notification()
        self.change_checker = Change_checker()
        self.profile_dict = dict()
        self.site_dict = dict()

        logging.info('Reading settings...')
        self._read_setting(setting_name)
예제 #21
0
 def _confirm_order(self, order_id, args):
     """Confirm order with some delay."""
     data = {
         'JSESSIONID': self.session_id,
         'id': order_id,
         'orderStatus': 1,
         'submitRemark': None,
     }
     res = self.session.post(CONFIRM_URL, data=data)
     args['msg'] = res.json()['errorMsg']
     Notification.send_confirm_order(args)
예제 #22
0
    def load_notifications(self):
        notification_rows = self.database.get_notifications()
        for notification_row in notification_rows:
            notification_id = notification_row[0]
            notification_content = notification_row[1]
            date_issued = notification_row[2]
            incident = self.get_incident(notification_row[3])

            notification = Notification(incident, notification_content)
            notification.id = notification_id
            notification.date_issued = date_issued

            self.notifications[notification.id] = notification
예제 #23
0
 def notify_self(self):
     from notification import Notification
     from follower import Follower
     follower = Follower.query.filter(
         and_(Follower.Type == self.Type,
              Follower.ParentID == self.ParentID,
              Follower.UserID == self.UserID)).first()
     if follower:
         note = Notification(UserID=self.UserID,
                             Type="Comments",
                             ParentID=self.CommentID,
                             FollowerID=follower.FollowerID)
         note.save()
예제 #24
0
	def sendAction(self,conn,subhandle,data,sendNotif=True):
		try:
			packet = make_command_packet (self.session_key, conn.mac, self.mesh_id, subhandle, data)
			globals.PENDING_ACTION = True
			if sendNotif == True:
				notification = Notification(conn, Awoxmesh, {'mac': conn.mac, 'session':self.session_key})
				notification.subscribe(timer=NOTIF_TIMEOUT,disconnect=False)
			
			logging.debug("Sending packet for "+ conn.mac + " : " + packet + " with session key : "+ "".join("%02x" % b for b in self.session_key))
			return conn.writeCharacteristic(COMMAND_CHAR_UUID, packet)
		except Exception,e:
			logging.debug("Exception found while sending action")
			logging.debug(str(e))
			return False
예제 #25
0
 def parse(self, data, mac, name, manuf):
     result = {}
     result['present'] = 1
     try:
         conn = Connector(mac)
         conn.connect()
         if not conn.isconnected:
             conn.connect()
             if not conn.isconnected:
                 return
         notification = Notification(conn, LogiSwitch)
         notification.subscribe(2)
     except Exception, e:
         logging.error(str(e))
def main():
	# Where is our base folder (the one containing the auto_form.py file)?
	global base_dir 
	base_dir = os.path.normpath(os.path.dirname(os.path.realpath(sys.argv[0])))
	# Parsing arguments
	if len(sys.argv) > 2:
		print "Too many arguments"
		return
	elif len(sys.argv) == 2:
		if sys.argv[1] == "--setup-cron":
			setup_cron()
			return
		elif sys.arg[1] != "--run":
			print "invalid option: %s" % sys.argv[0]
			return
	# We are good to go!
	entities = import_entities()
	#entities = {"285000001": "Gobernacion"}
	current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
	if len(entities) == 0:
		print "%s:: No entities found. Are you sure the file is there?" % current_time
	elif len(entities) < 10:
		print "%s:: Will run against those entities %s" % (current_time,entities)
	else:
		print "%s:: Will run against %d entities" % (current_time,len(entities))
	total = 0;
	report = Report(os.path.join(base_dir,REPORTS_FOLDER))
	for entity_id, entity_name in entities.iteritems():
		print "\n***** Entity %s (%s) *****" % (entity_name, entity_id)
		new_processes = do_one(entity_id)
		if len(new_processes) > 0:
			report.append(entity_id, entity_name, new_processes)
			total += len(new_processes)

	# Notify the result
	notif = None
	if report.created:
		text_body = "Hay %d nuevos contratos disponibles.\nAdjunto el reporte." % total
		notif = Notification(text_body, report.file_path);
	else:
		notif = Notification("No hay nada nuevo hoy.", None);
	notif.send()
	# Display summary
	print "\n"
	print "#############################################################"
	print "# Summary"
	print "# We found %d new processes" % total
	print "# Report avail. at %s" % report.file_path
	print "#############################################################"
 def add_new_reservation(self, hotel_name, customer_name, Cust_number,
                         from_date, to_date):
     hotel_num = 0
     if Reservations.reserve_room(self, hotel_name, customer_name):
         for e in Hotel.hotels:
             if e[1] == hotel_name:
                 hotel_num = e[0]
         Customer.customers.append([customer_name, Cust_number])
         cust_num = len(Customer.customers)
         Reservations.reservations.append(
             [hotel_num, cust_num, from_date, to_date])
         Notification.send_text_message(
             self, "Your reservation done , Thank you " + customer_name,
             Cust_number)
         print "Done !"
예제 #28
0
	def parse(self,data,mac,name,manuf):
		action={}
		action['present'] = 1
		if mac.upper() in globals.KNOWN_DEVICES and globals.KNOWN_DEVICES[mac.upper()]['emitterallowed'] == globals.daemonname and globals.KNOWN_DEVICES[mac.upper()]['islocked'] == 1:
			conn = Connector(mac)
			conn.connect()
			if not conn.isconnected:
				conn.connect()
				if not conn.isconnected:
					return action
			conn.writeCharacteristic('0x36','0100')
			notification = Notification(conn,Itag)
			notification.subscribe()
			globals.KEEPED_CONNECTION[mac.upper()]=conn
		return action
예제 #29
0
    def read(self, mac, connection=''):
        if 'localname' in globals.KNOWN_DEVICES[mac.upper()]:
            # Make it works directly with devices paired by remote control (for testing)
            if globals.KNOWN_DEVICES[mac.upper()]['localname'].startswith(
                    "R-"):
                self.mesh_name = globals.KNOWN_DEVICES[
                    mac.upper()]['localname']
                self.mesh_password = P_DEFAULTPASSWORD

        if mac in globals.KEEPED_CONNECTION:
            logging.debug('Already a connection for ' + mac + ' use it')
            conn = globals.KEEPED_CONNECTION[mac]
        else:
            logging.debug('Creating a new connection for ' + mac)
            conn = Connector(mac)
            globals.KEEPED_CONNECTION[mac] = conn

        i = 1
        authresult = False
        while i <= 2:
            i = i + 1
            if not conn.isconnected:
                try:
                    conn.connect(retry=1)
                except:
                    pass
            if conn.isconnected:
                authresult = self.auth(conn)
            if authresult:
                break
            else:
                time.sleep(1)

        if not authresult:
            logging.debug(
                'Ending action due to authentication error on device')
            globals.PENDING_ACTION = False
            return result

        # send message
        notification = Notification(conn, Awoxmesh, {
            'mac': conn.mac,
            'session': self.session_key
        })
        notification.subscribe(timer=NOTIF_TIMEOUT, disconnect=False)
        conn.readCharacteristic(STATUS_CHAR_UUID)

        return {}
예제 #30
0
class Traker:
    def __init__(self, contract, p_target, limit, sender_pass):
        self.logger = Logger()
        self.notif = Notification(sender_pass)

        self.contract = contract
        self.p_target = p_target
        self.limit = limit
        self.scraper = Scraper(self.contract)

    def track_prices(self):
        Logger.log_target(self.limit, self.p_target)

        while True:
            try:
                current_p = self.scraper.get_price()
                Logger.log_price(current_p)
            except Exception:
                Logger.log_price("ERROR")
                continue

            mult_lim = 1 if self.limit.lower() == "superior" else -1

            if self.p_target*mult_lim - current_p*mult_lim < 0:

                Logger.log_notif_intent()
                notif_txt = self.notif.send_notifications(current_p, self.p_target, round(current_p + 0.1 * mult_lim, 2), mult_lim == 1)
                Logger.log_notif_txt(notif_txt)

                self.p_target = round(current_p + 0.1*mult_lim, 2)
                Logger.log_target(self.limit, self.p_target)

            sleep(60*2)
def parsing_notification(file_content):
    '''
    Pre-process notifications.

    :param file_content: file content
    :returns: array of notification objects
    :raise TypeError: unexpected data structure
    :raise ValueError: invalid timestamp
    '''
    notifications = []
    for line in file_content:
        # Trim whitespace
        line = line.strip()
        # Seperate elements by spaces
        elements = line.split(" ")
        try:
            # Store new notification object into array
            notifications.append(Notification(*elements))
        except TypeError:
            print "Unexpected data structure: " + line
            print "Exiting..."
            sys.exit()
        except ValueError:
            print "Invalid timestamp: " + line
            print "Exiting..."
            sys.exit()
    return notifications
예제 #32
0
def archifPullLastUpdates():
    archifStr = requests.get("https://meddl.center/archif").content.decode("utf8")

    soup = BeautifulSoup(archifStr, 'html.parser')
    ul = soup.select_one('ul.archif')

    notificationArray = []
    counter = 0
    for li in ul:
        id = counter
        epoch = datetime.now()
        source = "meddl.center"
        topic = li.findAll('a')[0].next
        description = ""
        if len(li.findAll('a')) > 0:
            if len(li.findAll('a')[0].findAll('i')) > 0:
                description = li.findAll('a')[0].findAll('i')[0].next
        notificationArray.append(Notification(id, epoch, source, topic, description))
        counter += 1
        if counter > 29:
            break

    counter = 0
    for notification in notificationArray:
        tmpEpoch = notificationArray[29 - counter].epoch
        notificationArray[29 - counter].epoch = notification.epoch
        notification.epoch = tmpEpoch
        counter += 1
        if counter == 15:
            break

    return notificationArray
예제 #33
0
    def create_notification(self, incident, content):
        notification = Notification(incident, content)
        self.database.insert_notification(notification)
        self.notifications[notification.id] = notification

        notification.date_issued = self.database.get_notification_date_issued(
            notification)

        followers = self.get_followers(incident)
        for follower in followers:
            user_notification = UserNotification(follower, notification, False)
            self.database.insert_user_notification(user_notification)

        self.database.commit()

        return notification
예제 #34
0
 def read(self, mac):
     result = {}
     try:
         conn = Connector(mac)
         conn.connect()
         if not conn.isconnected:
             conn.connect()
             if not conn.isconnected:
                 return
         batteryFirm = bytearray(conn.readCharacteristic('0x38'))
         conn.writeCharacteristic('0x33', 'a01f', response=True)
         battery = batteryFirm[0]
         firmware = "".join(map(chr, batteryFirm[2:]))
         notification = Notification(conn, Miflora)
         conn.writeCharacteristic('0x36', '0100', response=True)
         result['battery'] = battery
         result['firmware'] = firmware
         result['id'] = mac
         received = bytearray(conn.readCharacteristic('0x35'))
         temperature = float(received[1] * 256 + received[0]) / 10
         if temperature > 3276.8:
             temperature = 0 - (6553.6 - temperature)
         sunlight = received[4] * 256 + received[3]
         moisture = received[7]
         fertility = received[9] * 256 + received[8]
         result['sunlight'] = sunlight
         result['moisture'] = moisture
         result['fertility'] = fertility
         result['temperature'] = temperature
         result['source'] = globals.daemonname
         logging.debug(str(result))
         globals.JEEDOM_COM.add_changes('devices::' + conn.mac, result)
         return result
     except Exception, e:
         logging.error(str(e))
예제 #35
0
def available_networks_set(*values):
	global networks
	global window		

	networks['gtklist'].clear()
	
	gtk.gdk.threads_enter()
	for network in range(0, len(values[1])):
		networks['gtklist'].set(networks['gtklist'].append(), 0, str(network+1), 1, values[2][network], 2, str(int(values[1][network])), 3, values[3][network])
	hildon.hildon_gtk_window_set_progress_indicator(window, 0)
	gtk.gdk.threads_leave()
	networks['acquire'] = False
	networks['time'] = int(time())

	notify = Notification()
	notify.info('%d Cellular Network(s) found' % len(networks['gtklist']))
    def run(self):
        for raw_notification in self._consumer:
            partition = raw_notification[0]
            offset = raw_notification[1].offset
            message = raw_notification[1].message.value

            notification_data = json.loads(message)

            ntype = notification_data['type']
            name = notification_data['name']
            addr = notification_data['address']

            notification = Notification(ntype,
                                        partition,
                                        offset,
                                        name,
                                        addr,
                                        notification_data['retry_count'],
                                        notification_data['raw_alarm'])

            wait_duration = self._retry_interval - (
                time.time() - notification_data['notification_timestamp'])

            if wait_duration > 0:
                time.sleep(wait_duration)

            sent, failed = self._notifier.send([notification])

            if sent:
                self._producer.publish(self._topics['notification_topic'], sent)

            if failed:
                notification.retry_count += 1
                notification.notification_timestamp = time.time()
                if notification.retry_count < self._retry_max:
                    log.error(u"retry failed for {} with name {} "
                              u"at {}.  "
                              u"Saving for later retry.".format(ntype, name, addr))
                    self._producer.publish(self._topics['retry_topic'],
                                           [notification.to_json()])
                else:
                    log.error(u"retry failed for {} with name {} "
                              u"at {} after {} retries.  "
                              u"Giving up on retry."
                              .format(ntype, name, addr, self._retry_max))

            self._consumer.commit()
예제 #37
0
    def load(self, date):
        Wahl = self.accessor.clazz('wahl')

        # check wheter there is an election for this date
        if self.session.query(exists().where(Wahl.termin == date)).scalar():
            Wahlkreis = self.accessor.clazz('wahlkreis')
            Sprengel = self.accessor.clazz('sprengel')
            Parteistimmen = self.accessor.clazz('parteistimmen')
            Bezirk = self.accessor.clazz('bezirk')

            """
                Index: Label
                0: wahlkreis
                1: bezirk
                2: sprengel
                3: berechtigte
                4: abgegebene
                5: ungueltige
                6: partei
                7: stimmanzahl
            """

            # just define the query so one can check if it is correct
            query = self.session.query(Wahlkreis.wknr.label('wahlkreis'),
                                       Bezirk.bnr.label('bezirk'),
                                       Sprengel.snr.label('sprengel'),
                                       Sprengel.berechtigt.label('berechtigt'),
                                       Sprengel.abgegeben.label('abgegebene'),
                                       Sprengel.ungueltig.label('ungueltig'),
                                       Parteistimmen.pbez.label('partei'),
                                       Parteistimmen.stimmanzahl.label('stimmanzahl')). \
                select_from(Wahlkreis). \
                join(Bezirk, Bezirk.wknr == Wahlkreis.wknr). \
                join(Sprengel, and_(Sprengel.bnr == Bezirk.bnr,
                                    Sprengel.termin == date)). \
                join(Parteistimmen, and_(Parteistimmen.termin == date,
                                         Parteistimmen.bnr == Bezirk.bnr,
                                         Parteistimmen.snr == Sprengel.snr))

            # convert the data using the executed query
            data, header = WahlAnalyseDataConvertAlgorithm.convert_raw(query.all())

            return data, header
        else:
            Notification.make("Table Error", "No Data for this Date")

            return [], []
예제 #38
0
    def __init__(self, contract, p_target, limit, sender_pass):
        self.logger = Logger()
        self.notif = Notification(sender_pass)

        self.contract = contract
        self.p_target = p_target
        self.limit = limit
        self.scraper = Scraper(self.contract)
예제 #39
0
def push_notification():
    """ Send a notification with the device name and status
    """
    if request.method != "POST":
        return MethodNotAllowed(valid_methods=["POST"])

    data = json.loads(request.data)
    device_name = data.get("device_name")
    status = data.get("status")

    if not device_name or not status:
        return BadRequest(description="Parameters <device_name> and <status> are mandatory")

    notification = Notification(API_KEY)
    notification.send(registration_ids=registration_ids, data=data)
    logging.info("Notification sent about {0} with status '{1}'".format(device_name, status))
    return "200 OK"
예제 #40
0
    def save(self, *args, **kwargs):
        """ Due to cross import, can't directly import Utilisateur """
        # 
        if self.send_to_all or self.send_to_inactive:  # or self.send_to_active
            authusers = User.objects.filter(is_superuser=False).only('email')
            users = []
            if self.send_to_inactive:
                for u in authusers:
                    try:
                        if u.profile.get_picture_count() == 0:
                            users.append(u)
                    except ObjectDoesNotExist:
                        pass

            else:
                users = authusers

            from notification import Notification

            notif = Notification(debug=settings.IS_LOCAL)
            notif.set_content(self.subject, self.content)
            for u in users:
                notif.push(u.email)
            notif.send(debug=settings.IS_LOCAL)
        super(MailingList, self).save(*args, **kwargs)
예제 #41
0
 def testNewMessage(self):
     new_message("app", "user1", "level","CriticalMessage")
     notice = Notification.get_by(app="app") 
     self.assertEqual(notice.app, "app", 
                      "Value retrieved should be the stored")
     self.assertEqual(notice.user, "user1", 
                      "Value retrieved should be the stored")
     self.assertEqual(notice.level, "level", 
                      "Value retrieved should be the stored")
     self.assertEqual(notice.text, "CriticalMessage", 
                      "Value retrieved should be the stored")        
예제 #42
0
 def update_notify(self):
     show = self.config.getboolean(self.config.get_default_section(), "show_notify")
     if (self.notify):
         if (show):
             del self.notify
             self.notify = False
         else:
             self.notify.reopen()
     else:
         if (show):
             self.notify = Notification(self.config, self.tray.get_geometry)
         else:
             self.notify = False
    def run(self):
        for raw_notification in self._consumer:
            partition = raw_notification[0]
            offset = raw_notification[1].offset
            message = raw_notification[1].message.value

            notification_data = json.loads(message)

            ntype = notification_data['type']
            name = notification_data['name']
            addr = notification_data['address']
            period = notification_data['period']

            notification = Notification(ntype,
                                        partition,
                                        offset,
                                        name,
                                        addr,
                                        period,
                                        notification_data['retry_count'],
                                        notification_data['raw_alarm'])

            if self._keep_sending(notification.alarm_id, notification.state):
                wait_duration = period - (
                    time.time() - notification_data['notification_timestamp'])

                if wait_duration > 0:
                    time.sleep(wait_duration)

                notification.notification_timestamp = time.time()

                self._notifier.send([notification])
                self._producer.publish(self._topic_name,
                                       [notification.to_json()])

            self._consumer.commit()
예제 #44
0
    def get_notifications(self, old_count):
        # changes in followers
        # notification
        new_count = self.followers
        notifications = []

        if old_count != new_count:
            if self.username == USERNAME:
                notification_url = URL + '/user/followers'
                target = 'you'

            else:
                notification_url = URL + '/users/' + self.username + '/followers'
                target = self.username

            if new_count > old_count:
                params = {'per_page': self.followers}
                start_page = old_count // 100
                end_page = new_count // 100
                followers = []
                with requests.Session() as s:
                    for i in range(start_page + 1, end_page + 2):
                        params['page'] = i
                        new_page = s.get(notification_url, headers=HEADERS,
                                         params=params, auth=(USERNAME, PASSWORD)).json()
                        #print("Length of page {} : {}".format(i, len(new_page)))
                        followers += new_page

                start_index = old_count % 100
                context = "follow"
                #print("Len of followers:" + str(len(followers)))
                #print("Len of list:" + str(len(followers[start_index:])))
                for user_blob in followers[start_index:]:
                    protagonist = user_blob['login']
                    notifications += [Notification.generate_message(protagonist, context, target)]

            else:
                message = '{} users unfollowed {}'.format(old_count - new_count, target)
                notifications += [Notification(message)]

        return notifications
예제 #45
0
파일: comment.py 프로젝트: ebby/brokentv
  def add(cls, media, user, text, acl, parent_id=None, to_user=None):
    from notification import Notification

    c = Comment(media=media, user=user, text=text)
    c.mentions = [x[0] for x in re.findall(r"@\[(\d+):([a-zA-z\s]+)\]", text)]

    if parent_id:
      c.parent_comment = Comment.get_by_id(int(parent_id))
      c.is_parent = False
    elif PRIVATE_COMMENTS:
      # ACL only needed on parent. Replies don't need ACLs.
      c.acl = acl
    c.put()

    media.comment_count += 1
    media.put()

    for m in c.mentions:
      if not to_user or (to_user and m != to_user.id):
        mentioned_user = User.get_by_key_name(m)
        if not mentioned_user or True:
          # Send them notification on FB
          fetch = urlfetch.fetch(url='https://graph.facebook.com/%s/notifications' % m,
                                 payload='access_token=%s&template=%s&href=%s' %
                                 (constants.facebook_app()['APP_ACCESS_TOKEN'],
                                 '@[' + user.id + ']' + ' mentioned you in a comment on ' + media.name + '!',
                                 media.get_path()),
                                 method=urlfetch.POST)
        else:
          n = Notification.add(mentioned_user, constants.NotificationType.MENTION, c)
          broadcast.broadcastNotification(n)

    if c.is_parent:
      from useractivity import UserActivity
      broadcast.broadcastNewActivity(UserActivity.add_comment(c.user, c))
    return c
예제 #46
0
    def save(self, date, data):
        if len(data) > 0:
            Wahl = self.accessor.clazz('wahl')
            Sprengel = self.accessor.clazz('sprengel')
            Parteistimmen = self.accessor.clazz('parteistimmen')

            # make sure there is only one election per day
            wahl_at_date = self.session.query(Wahl).filter_by(termin=date).first()

            if wahl_at_date:
                self.session.delete(wahl_at_date)

            # TODO d
            self.session.commit()

            # create the election with the given date
            wahl = Wahl(termin=date, mandate=100)
            self.session.add(wahl)

            # all fields besides these are parties
            """
            T = Hierarchietyp (1 = Wien-Gesamt, 2 = Wahlkreis, 3 = Bezirk, 4 = Sprengel)
            WV = Wahlkreis Wien-Gesamt (09 bei Bundeswahl, 01 bei Regionalwahl)
            WK = Wahlkreis
            SPR = Sprengelnummer
            WBER = Wahlberechtigte
            ABG. = Abgegebene Stimmen
            UNG. = Ungültige Stimmen
            """
            reserved = ['SPR', 'BZ', 'WBER', 'ABG.', 'UNG.', 'T', 'WV', 'WK']

            # save the party names to an extra list
            parties = []
            for key in data[0].keys():
                if key not in reserved:
                    parties.append(key)

            for row in data:
                sprengel = Sprengel(
                    snr=int(row['SPR']),
                    bnr=int(row['BZ']),
                    termin=date,
                    berechtigt=int(row['WBER']),
                    abgegeben=int(row['ABG.']),
                    ungueltig=int(row['UNG.'])
                )
                self.session.add(sprengel)

                for party in parties:
                    parteistimmen = Parteistimmen(
                        pbez=party,
                        snr=int(row['SPR']),
                        bnr=int(row['BZ']),
                        termin=date,
                        stimmanzahl=int(row[party])
                    )
                    self.session.add(parteistimmen)

            try:
                self.session.commit()
            except Exception as e:
                Notification.make("Database Error", "Could not commit: " + str(e))
        else:
            Notification.make("Table Error", "Empty Data List")
예제 #47
0
def postmessage(request):
    """ Post a message as AJAX """
    remote_addr = request.META.get('REMOTE_ADDR')
    http_referer = request.META.get('HTTP_REFERER')

    L.info("Post a message from {remote} for the page {referer}".format(remote=remote_addr, referer=http_referer))

    if request.method == 'POST':
        if CommentPref.objects.get_preferences().only_registred and not request.user.is_authenticated():
            L.error('ucomment.views.postmessage: Try to post when not authenticated. ')
            return HttpResponseBadRequest('')

        parent = int(request.POST.get('parent'))
        parent = Comment.objects.get(pk=parent) if parent != 0 else None
        content = request.POST['content']
        onwallurl = request.POST.get('onwallurl')

        if content:
            referer = request.POST.get('url')
            if not referer:
                referer = "/"

            if not onwallurl and referer == '/' and onwallurl != '/':
                referer = http_referer.replace('http://%s' % Site.objects.get_current().domain, '')

            # comment = Comment.objects.create(
            comment = Comment.objects.post_comment(
                url=referer,
                message=content,
                raw_html=False,
                user=request.user,
                ip=remote_addr,
                parent=parent
            )

            # Prepare JSON
            data = {
                'username': request.user.username,
                'submission_date': convert_date(timezone.now()),
                'knowuser': True,
                'avatar': request.user.profile.avatar_or_default(),
                'userid': request.user.id,
                'commentcount': Comment.objects.filter(user=request.user, visible=True, moderate=False).only('id').count(),
                'pigstiescount': Picture.objects.filter(user=request.user, trash=False).only('id').count(),
                'content': comment.content,
                'commentid': comment.id,
                'user_authenticated': request.user.is_authenticated(),
                'csrf_token': get_token(request),
            }

            if parent is not None:
                data['parentid'] = parent.id
            else:
                data['parentid'] = comment.id

            # Send a email to all users
            if parent is not None:
                comments = list(Comment.objects.filter((Q(parent=parent) & ~Q(user=request.user))).only('user__email'))
                mails = {}
                for comment in comments:
                    mails[comment.user.email] = ''

                req = RequestContext(request, {
                    'username': request.user.username,
                    'message': comment.content,
                    'url': comment.url
                })

                if not settings.IS_LOCAL:
                    notif = Notification(settings.BANDCOCHON_CONFIG.EmailTemplates.user_comment)
                    for mail in mails.keys():
                        notif.push(mail, req)
                    notif.send()

            # Send Json
            return JsonResponse(data)
        else:
            L.error("ucomment.views.postmessage : Don't have a content message")
    else:
        L.error("ucomment.views.postmessage: Not a POST call :")

    return HttpResponseBadRequest('')
예제 #48
0
 def __init__(self, notificationType, player, cards):
     """ Initialize the Notification with the cards, the player that caused it and the notification type """
     self.cards = cards
     Notification.__init__(self, notificationType, player)
예제 #49
0
class TrayApplication(ApplicationAbstract):
    
    def __init__(self):
        self.config = Config()
        self.preferences = False
        self.control = False
    
        gettext.bindtextdomain(self.config.app_name, self.config.locale_dir)
        gettext.textdomain(self.config.app_name)
        import __builtin__
        __builtin__._ = gettext.gettext
        
        self.tray = TrayIcon(self.config)
        
        self.control = TrayMixerWindow(self.config,
                                       self.on_volume_changed,
                                       self.on_mute_changed,
                                       self.tray.get_geometry)
        
        self.menu = TrayPopupMenu(self.config,
                                  self.control.mixer.on_mute_button,
                                  self.control.mixer.get_mute,
                                  self.quit,
                                  self.on_show_preferences,
                                  self.tray
                                  )
        
        self.tray.connect("popup_menu", self.menu.on_popup_event)
        self.tray.connect("button_press_event", self.on_tray_press_event)
        self.tray.connect("scroll_event", self.on_window_scroll_event)
        
        self.notify = False
        self.update_notify()
        self.update()
        
    def update_notify(self):
        show = self.config.getboolean(self.config.get_default_section(), "show_notify")
        if (self.notify):
            if (show):
                del self.notify
                self.notify = False
            else:
                self.notify.reopen()
        else:
            if (show):
                self.notify = Notification(self.config, self.tray.get_geometry)
            else:
                self.notify = False
        
        
    def update(self):
        info = self.control.mixer.get_status_info()
        self.tray.update(info)
        if (self.notify):
            self.notify.update(info)
    
    def show(self):
        log.Notice("update_show", 1)
        if (self.notify):
            self.notify.show()
    
    def on_volume_changed(self, show):
        self.update()
        if (show):
            self.show()

    def on_mute_changed(self, show):
        self.on_volume_changed(show)
        
    def on_tray_press_event(self, widget, event, data=None):
        if event.button == 1:
            self.control.toggle()
        elif event.button == 2:
            toggle = self.config.get(self.config.get_default_section(), "toggle")
            if (toggle == "mute"):
                self.control.mixer.toggle_mute()
                self.update()
            elif (toggle == "mixer"):
                self.menu.on_show_mixer()
                
    def on_window_scroll_event(self, widget, event):
        log.Notice("scroll event")
        if event.direction == gtk.gdk.SCROLL_UP:
            self.control.mixer.inc_volume()
        elif event.direction == gtk.gdk.SCROLL_DOWN:
            self.control.mixer.dec_volume()

    def on_show_preferences(self, widget=None, data=None):
        """ Show preferences window """
        self.preferences = Preferences(self.config, self.on_preferences_close, self.on_preferences_update)
        
    def on_preferences_update(self):
        log.Notice("preferences update")
        self.control.update()
        self.update_notify()
        self.update()
        
    def on_preferences_close(self):
        self.config.save()