Пример #1
0
    def stop_tunnel(self):
        """
        Stop the VPN tunnel.

        :return:
        """
        logger.info("Stopping VPN...")
        if self.MOUNT_FOLDERS and not self.lost_connectivity:
            self.unmount_folders()

        vpn_command = f'{self.vpn_util} stop "{self.VPN_NAME}"'
        logger.debug(f'VPN command: "{vpn_command}"')

        result = mac_utils.run_command(vpn_command, as_user=True)
        # If 'Has been stopped' or 'Disconnected' is in the result, the VPN stopped already
        if 'has been stopped' not in result and 'Disconnected' not in result:
            logger.info("Unable to stop VPN. Please do this manually")
            logger.info(f'vpnutil responded: {result}')
        self.active = False
        mac_utils.flush_routing_table(reset_interfaces=False)
        network_interface = mac_utils.get_active_network_interface()
        gateway_address = mac_utils.gateway_for_interface(network_interface)
        mac_utils.set_default_route(self.active_interface,
                                    ip_address=gateway_address)
        if self.MACOS_NOTIFICATION_ENABLED:
            pync.notify(f'Tunnel is stopped.')
Пример #2
0
def show_notification(website_status, website_url):

    if platform.system() == 'Linux':
        import notify2
        notify2.init("internet-noti")
        noti = notify2.Notification("internet-noti ",
                                    website_status + website_url,
                                    noti_constants.ICON_NOTI_TRAY)
        noti.show()
    elif platform.system() == 'Darwin':  #MacOS
        import pync
        pync.notify(title='internet-noti ',
                    message=website_url,
                    subtitle=website_status,
                    remove='ALL')
    elif platform.system() == 'Windows':
        from plyer import notification
        notification.notify(
            title='internet-noti ',
            message=website_status + website_url,
            app_icon=None,
            timeout=10,
        )
    # -----
    logger.debug('Notification displayed for system > %s', platform.system())
Пример #3
0
def MacNotification(headline, security, recommendation):
    if recommendation == 1:
        str_rec = 'Buy '
    elif recommendation == 0:
        str_rec = 'Pass on '
    title = str_rec + security
    pync.notify(headline, title=title)
Пример #4
0
def notify(device: str, title: str, artist: str):
    ''' Ping macOs '''
    pync.notify("Playing: %s by %s | %s" % (title, artist, device),
                 title='Spotify',
                 activate='com.spotify.client',
                 group=os.getpid(),
                 appIcon='https://i.imgur.com/zmKJPEk.png')
Пример #5
0
 def __init__(self):
     super(AwesomeStatusBarApp, self).__init__("awstunnel")
     self.menu = ["Preferences", "Restart", "Reload", 'Unison_restart']
     self.unison_filename = 'unison.prefs.txt'
     self.unison_connect(self.unison_filename)
     self.initiate('clientlist.txt')
     pync.notify('Started monitoring')
Пример #6
0
def my_notify(*args, **kwargs):
    if kwargs.get('sound', None):
        sound_file = kwargs['sound']
        kwargs.pop('sound')
    t = Thread(target=sound, args=(sound_file,))
    t.start()
    pync.notify(*args, **kwargs)
Пример #7
0
    def notific(self, parsent, icon):
        pync.notify(str(parsent) + "%やで",
                    title="ばってりーちぇっかー。",
                    appIcon="icon/{}%.png".format(str(icon)))

        print("notific", str(parsent) + "%やで")
        self.icon = "icon/{}%.png".format(str(icon))
Пример #8
0
def notify(title='title', body='text', icon='python'):
    """Notifier function."""
    if PLT == "win32":
        toaster.show_toast(title,
                           body,
                           threaded=True,
                           icon_path=path.join(path.dirname(__file__), 'data',
                                               '%s.ico' % icon))
    elif PLT == "linux":
        reply = None

        with closing(open_dbus_connection(bus='SESSION')) as bus:
            msg = new_method_call(NOTIFIER, 'Notify', 'susssasa{sv}i', (
                "routEar",
                NOTIF_ID or 0,
                'file://%s' %
                path.join(path.dirname(__file__), 'data', '%s.png' % icon),
                title,
                body,
                [],
                {},
                -1,
            ))
            reply = bus.send_and_get_reply(msg)
        globals()['NOTIF_ID'] = reply.body[0] if reply else None
    elif PLT == "darwin":
        pync.notify(f"{title} \n {body}", title="routEar")

    else:
        return False
    return True
Пример #9
0
def check_for_ads(spotify: Wasp):
    try:
        track = spotify.get_track()
        state = spotify.get_state()
    except Exception:
        # spotify was closed
        exit()

    if state['state'] != 'playing':
        time.sleep(5)
        return

    duration_sec = track['duration'] / 1000

    if duration_sec < 40 and track['popularity'] == 0:
        # this check handles also video ads
        previous_volume = state['volume']
        mute_duration = math.floor(duration_sec - state['position']) + 0.5
        if mute_duration > 0:
            # weird bug occured that sometimes duration was negative
            pync.notify(
                f'Ad detected, muting spotify for {mute_duration} seconds',
                title='Spotify ads muter')
            spotify.set_volume(0)
            time.sleep(mute_duration)
            spotify.set_volume(previous_volume)
    else:
        time.sleep(1)
Пример #10
0
 def reload(self, _):
     print('Entering Reload')
     for i in self.tunnels:
         print('Stoppeing {}', i.address)
         i.stop()
     self.tunnels = []
     self.initiate('clientlist.txt')
     pync.notify('Reloaded')
Пример #11
0
def notify(title, message):
    # wait for call terminal-notifier
    # https://stackoverflow.com/questions/37010132/launchd-python-notifier-notify-not-producing-expected-output/52968611#52968611
    pync.notify(message,
                title=title,
                open='https://google.com/',
                sender='com.apple.launchpad.launcher',
                wait=True)
Пример #12
0
 def send_break_notification(self, sender):
     notify(
         "Take a 10 min. break!",
         title="EyeBreak",
         sound="default",
         appIcon=ICON,
     )
     self.stop_scheduling(sender)
Пример #13
0
def posture_reminders():
    """Thread to send user random reminders to fix their posture"""
    while True:
        s = random.randint(POSTURE_LOWER_BOUND, POSTURE_UPPER_BOUND)
        time.sleep(s)
        pync.notify("Fix your posture!",
                    appIcon="128.png",
                    title="ScreenBOT Says:")
Пример #14
0
    def notific(self, parsent, icon):
        # rumps.notification("バッテリーチェッカー", str(parsent)+"%やで","",icon="icon/{}%.png".format(str(parsent)))
        pync.notify(str(parsent) + "%やで",
                    title="ばってりーちぇっかー。",
                    appIcon="icon/{}%.png".format(str(icon)))

        print("notific", str(parsent) + "%やで")
        self.icon = "icon/{}%.png".format(str(icon))
def main():
    pync.notify("GPU Changer Service Started.")
    set_graphics_switching()
    while True:
        recent_charging_log = is_battery_charging()
        sleep(5)
        if is_battery_charging() != recent_charging_log:
            Thread(target=notify_toggle, args=()).start()
Пример #16
0
def notification(title, text, execute=False, icon=''):
    text = text.replace('[', '')
    text = text.replace(']', '')

    if execute == False:
        pync.notify(text, title=title, appIcon=icon)
    else:
        pync.notify(text, title=title, execute=execute, appIcon=icon)
Пример #17
0
def send_notification(message):
    if message == 'Нет соединения' or message == 'Нет результата':
        try:
            last_course = load_last_course()
        except FileNotFoundError:
            return pync.notify('Невозможно получить данные', title='Ошибка')
        return pync.notify(last_course, title='Нет сети. Последние сохранённые данные.')
    title = 'Доллара США по курсу ЦБ РФ'
    return pync.notify(f'На сегодня {message} руб.', title=title)
Пример #18
0
def notify(title, text):
    favicon_link = config.olx_favicon
    open_link = config.olx_url
    main_sound_name = "Ping"
    pync.notify(text,
                title=title,
                appIcon=favicon_link,
                sound=main_sound_name,
                open=open_link)
Пример #19
0
 def add_event(self, phrase):
     hour, message = self.extract_time(phrase)
     if not hour or not message:
         return
     if hour in self.time_lst:
         self.time_lst[hour].append(message)
     else:
         self.time_lst[hour] = [message]
     pync.notify('Alarm set for ' + message + ' at ' + hour)
Пример #20
0
def handle_hotkey_press(hotkey: str):
    print(hotkey)
    pync.notify(
        title=hotkey["keys"].replace("<", "").replace(">", ""),
        subtitle=hotkey["name"],
        message=hotkey["description"],
        ignoreDnD=True,
        appIcon="",
    )
Пример #21
0
def triggerNotification(emailData, service):
    toOpen = 'https://github.com/Qgiv/Secure/pulls'

    # Not currently used, but if you want to skip a message, you can set this to true
    # like if you wanted to ignore messageText containing a certain string, etc
    skipTrigger = False

    for data in emailData['payload']["parts"]:

        if (data.has_key('body') and data['body'].has_key('data')
                and (len(data['body']['data'])) > 0):
            # https://gist.github.com/perrygeo/ee7c65bb1541ff6ac770
            # apparently there's no padding in certain cases, so we need to add it in
            # we can add arbitrary padding length in, it'll ignore the rest of it.
            toDecode = data['body']['data'] + '======================='

            try:
                # Parse body text
                messageText = base64.b64decode(toDecode)
            except:
                e = sys.exc_info()[1]
                print(e)

            strPos = messageText.find("You are receiving this because you")

            if strPos != -1:
                subMessageText = messageText[strPos:(len(messageText))]

                # https://stackoverflow.com/questions/6038061/regular-expression-to-find-urls-within-a-string
                url = re.search(
                    '(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?',
                    subMessageText)

                if url:
                    # Overriding our default URL with a more email-specific URL
                    # We're assuming the URL is the very first one we run into
                    toOpen = url.group(0)

    labelToRemove = {"removeLabelIds": ['UNREAD'], "addLabelIds": []}

    if not skipTrigger:
        try:
            # Remove unread label
            service.users().messages().modify(userId='me',
                                              id=emailData['id'],
                                              body=labelToRemove).execute()
        except:
            pass

        # Send a user notification
        pync.notify(
            emailData['snippet'],
            title='Github Notification',
            appIcon=
            'https://github.githubassets.com/images/modules/logos_page/Octocat.png',
            open=toOpen)
Пример #22
0
    def send_darwin(self):
        """Notify on macos with pync."""
        try:
            import pync

            pync.notify(
                message=self.__description, title=self.__title, appIcon=self.__icon_path
            )
        except ImportError:
            raise ImportError("notifications are not supported, can't import pync")
Пример #23
0
 def _on_change(self, url):
     if (PLATFORM_NAME == 'Linux'):
         Notify.Notification.new(
             "This url:{} has changed".format(url)).show()
     else:
         pync.notify("This url:{} has changed".format(url),
                     title='Has changed!',
                     open=str(url).rstrip())
     QtWidgets.QMessageBox.information(
         self, 'Has changed!', "this url:{} has changed".format(url))
Пример #24
0
    def _notify(self):
        args = {"title": self.title}
        self.set_if_not_none(args, "url")
        self.set_if_not_none(args, "activate")
        self.set_if_not_none(args, "execute")
        self.set_if_not_none(args, "groupid")
        self.set_if_not_none(args, "sound")
        self.set_if_not_none(args, "appIcon")

        pync.notify(self.message, **args)
Пример #25
0
 def desktopNotification(self, title, message):
     logging.info('Triggering desktop notification')
     if platform.system() == 'Darwin':
         pync.notify(message, title, sound='default')
     elif platform.system() == 'Windows':
         toaster = ToastNotifier()
         toaster.show_toast(title, message)
     elif platform.system() == 'Linux':
         notify2.init(title)
         n = notify2.Notification(title, message)
         n.show()
Пример #26
0
    def on_any_event(event):
        if event.is_directory:
            return None

        elif event.event_type == 'created':
            pync.notify("Se ha creado %s"% event.src_path, group=os.getpid())
            print("Received created event - %s." % event.src_path)
           

        elif event.event_type == 'modified':
            pync.notify("Se ha modificado %s"% event.src_path, group=os.getpid())
            print("Received modified event - %s." % event.src_path)
Пример #27
0
def log_status():
    # TODO: Delete this
    o = subprocess.run('pmset -g batt'.split(), stdout=subprocess.PIPE)
    try:
        battery_level = o.stdout.decode().strip().split('\t')[1].split(';')[0]
        with open('battery_level.txt', 'a') as f:
            f.write(f'{battery_level}\n')
    except Exception:
        pync.notify('Unable to read battery, something went wrong')

    with open('battery_output.txt', 'a') as f:
        f.write(o.stdout.decode())
Пример #28
0
def notify(
    message: str,
    kind: NotificationKind = NotificationKind.SUCCESS,
):
    titleSuffix = kind.name.lower().capitalize(
    ) if kind != NotificationKind.SUCCESS else ''

    pync.notify(
        message,
        title=f'{APPLICATION_NAME}{f" - {titleSuffix}" if titleSuffix else ""}',
        appIcon=getattr(NotificationLogo, kind.name).value,
        sound=getattr(NotificationSound, kind.name).value,
    )
Пример #29
0
def send_notification(title, message, sound="Pop", silent=False):
    """Send a notification using the pync module.

    Args:
        title: Title of the message
        message: Message
        sound:
            The name of the aiff sound file
            (from /System/Library/Sounds/)
        silent: Whether to print the output
    """
    pync.notify(message, title=title, group="specify7_notifications")
    run_process("afplay /System/Library/Sounds/%s.aiff" % sound, silent)
Пример #30
0
    def send_alert(self, name: str, monitor: Monitor) -> None:
        """Send the message."""

        alert_type = self.should_alert(monitor)
        message = ""

        if alert_type not in [AlertType.FAILURE, AlertType.CATCHUP]:
            return
        message = self.build_message(AlertLength.NOTIFICATION, alert_type, monitor)

        if not self._dry_run:
            pync.notify(message=message, title="SimpleMonitor")
        else:
            self.alerter_logger.info("dry_run: would send message: %s", message)
Пример #31
0
    def send_alert(self, name, monitor):
        """Send the message."""

        alert_type = self.should_alert(monitor)
        message = ""

        if alert_type == "":
            return
        elif alert_type == "failure":
            message = "Monitor {} failed!".format(name)
        elif alert_type == "success":
            message = "Monitor {} succeeded.".format(name)
        else:
            self.alerter_logger.error("Unknown alert type: {}".format(alert_type))
            return

        if not self.dry_run:
            pync.notify(message=message, title="SimpleMonitor")
        else:
            self.alerter_logger.info("dry_run: would send message: {}".format(message))