Beispiel #1
0
    def next_image(self, _):

        if not os.path.exists(self.media_dir):
            os.makedirs(self.media_dir)

        url = 'https://unsplash.it/'
        if self.gray_mood: url += 'g/'
        url += '{w}/{h}/?random'
        if self.blur: url += '&blur'

        url = url.format(w=self.screen_width, h=self.screen_height)
        file_name = self.media_dir + datetime.datetime.now().strftime("%H:%M:%S.%f") + '.jpg'

        try:
            self.icon = 'img/wait.png'
            urllib.urlretrieve(url, file_name)
            file_url = NSURL.fileURLWithPath_(file_name)

            # Get shared workspace
            ws = NSWorkspace.sharedWorkspace()

            # Iterate over all screens
            for screen in NSScreen.screens():
                # Tell the workspace to set the desktop picture
                (result, error) = ws.setDesktopImageURL_forScreen_options_error_(
                    file_url, screen, {}, None)
            self.icon = 'img/icon.png'
        except IOError:
            print('Service unavailable, check your internet connection.')
            rumps.alert(title='Connection Error', message='Service unavailable\n'
                                                          'Please, check your internet connection')
Beispiel #2
0
 def about(self, sender):
     rumps.alert('About Pompy',
                 'Pompy was made in 2014 by Camilo Payan.\n' +
                 'The code is available at ' +
                 'http://github.com/camilopayan/pompy/\n' +
                 'Pompy\'s icon is from http://icons8.com\n',
                 ok='Thanks!')
 def activate_scene(self, scene_id):
     if not scene_id in self.scenes:
         rumps.alert(title="No such scene.", message="Looks like that scene is missing!", ok=None, cancel="Abort")
     for light_name, value in self.scenes[scene_id].iteritems():
         if light_name.startswith('__'):
             continue
         self.lights[light_name].set_level(value)
Beispiel #4
0
    def connect(self, *args):

        """ Called via our connect thread...

        Attempt to create a new connection with our Connect
        class and store the value to our self.connection instance variable """

        # With the potential dropped internet connections, sessions ending and more,
        # which have caused errors, it's easier and safer if we attempt to create a
        # new instance of Connect which provides a clean session. Future improvements
        # could be made to rectify this action to help memory/performance.
        self.connection = Connect()
        self.title = GumpyTitles.CONNECTING

        try:
            self.connection.connect()
            rumps.notification(GumpyTitles.CONNECTION_SUCCESS, '', 'Have a cookie')

            # This explicitly calls get_tickets method on a rumps.Timer (new thread) interval
            if self.refresh_interval_timer is None:
                self.refresh_interval_thread()
            else:
                # If this isn't the first time connect is being called, we will update
                # our ticket results by refreshing our interval thread which calls get_tickets
                self.refresh_interval_thread(force_refresh=True)

        except Exception as e:
            rumps.alert(e)
        finally:
            self.title = GumpyTitles.GUMPY
    def check_update(self, _):
        last_update_date = self.settings.get('date', '')
        if not last_update_date:
            last_update_date = datetime.datetime.today()
        else:
            last_update_date = parser.parse(last_update_date)

        if not self.settings['apps']:
            return

        page = 1
        try:
            while page > 0:
                response = requests.get(SOURCE_URL.format(page=page), timeout=10)
                soup = bs4.BeautifulSoup(response.text, 'html.parser')
                apps = soup.find('ul', class_='post_list row').find_all('a', title=True)
                for app in apps:
                    update_date = app.find('span', class_='item date')
                    app_update_date = parser.parse(update_date.text)
                    if app_update_date < last_update_date:
                        page = 0
                        break

                    app_href = app.attrs['href']
                    app_name = app_href[app_href.rfind('/') + 1:app_href.rfind('.')]
                    if app_name not in self.settings['apps']:
                        continue

                    # app_data = json.dumps()
                    rumps.notification(app_name, 'xclient.info', '{} updated on {}.'.format(app_name, update_date.text),
                                       data={'name': app_name, 'date': update_date.text, 'href': app_href})
                page += 1 if page > 0 else 0
        except Exception as e:
            rumps.alert('Check update failed! Exception: {}'.format(repr(e)))
            return
Beispiel #6
0
    def set_apikey(self):
        ''' Open window to set api key '''
        self.logger.info('Opening \'set_apikey\' window')
        api_key_window = rumps.Window(
            title='Enter your API key:',
            message='Right click to paste',
            default_text=self.config['apikey'],
            ok='Confirm',
            cancel='I don\'t have one',
            dimensions=(250, 20),
        )

        response = api_key_window.run()

        if response.clicked == 0:  # Cancel
            self.logger.info('Cancelled \'set_apikey\' window')
            return False

        apikey = response.text.strip()

        if not apikey:
            self.logger.info('API Key was not entered')
            rumps.alert(title='You did not enter an API Key',
                        message='Try again')
            return self.set_apikey()

        self.logger.info('Setting API Key')
        self.config['apikey'] = apikey
        self.climacell.set_apikey(apikey)
        CONFIG.save(self.config)

        return True
Beispiel #7
0
    def __init__(self):
        super(Sharfoo, self).__init__("Initializing")
        self.menu = ["Restart router"]
        self.connected_mac = set()
        self.mac_to_name = dict()
        self.mac_to_ip = dict()
        if _create_template_file():
            rumps.alert(
                "Created config file",
                "Please enter router admin credentials in %s and press OK" %
                _CONF_LOCATION)

        username, password, host, self.bssid = _read_admin_credentials()
        if self.bssid is None:
            while True:
                if _are_credentials_valid(username, password, host):
                    break
                else:
                    rumps.alert(
                        "Invalid credentials, please update and click OK")
                    username, password, host, _ = _read_admin_credentials()

            _, self.bssid = _get_bssid()
            _update_config_file(username, password, host, self.bssid)

        self.tl = TippiLink(username, password, host)
Beispiel #8
0
    def start(self):
        ''' Restoring the config and start the timer '''
        self.logger.info('Running start script')
        detect_location = False

        try:
            self.logger.info('Trying to read config')
            config = CONFIG.read()
            if not valid_config(config, self.default_config):
                raise IncompatibleConfigError()
            self.config = config
        except FileNotFoundError:
            # First time running app
            self.logger.info('Config file not found')
            detect_location = True
        except:
            self.logger.info('Config file was incompatible')
            rumps.alert(title='Something went wrong whilst loading settings',
                        message='Default settings have been applied')
            detect_location = True

        if not self.config['apikey']:
            self.logger.error('ClimaCell API key is misising')
            self.handle_missing_apikey()

        if detect_location:
            try:
                self.logger.info('Tying to load local config')
                local_config = self.local_config()
            except LocationNotFoundError:
                self.logger.error(
                    'LocationNotFoundError: Coud not get current location')
            except requests.ConnectionError:
                self.logger.error(
                    'ConnectionError: Coud not get current location')
            except:
                self.logger.exception(
                    'Something went wrong whilst loading local config')

            if not self.confirm_location(local_config['location']):
                self.prefs(local_config['location'])
                return
            self.config = local_config

        self.climacell.set_location(self.config['latitude'],
                                    self.config['longitude'])
        self.climacell.set_unit_system(self.config['unit_system'])
        self.climacell.set_apikey(self.config['apikey'])

        # Set to opposite so that it can be switched back when calling live_location()
        self.config['live_location'] = not self.config['live_location']

        CONFIG.save(self.config)

        self.update_display_units()

        self.live_location()

        self.logger.info('Starting timer')
        self.timer.start()
Beispiel #9
0
    def translateTextService_userData_error_(self, pboard, data, err):
        logger.debug('received some request from service:{} {}'.format(
            pboard, data))
        try:
            types = pboard.types()
            pboard_string = None
            if NSStringPboardType in types:
                pboard_string = pboard.stringForType_(NSStringPboardType)
            if pboard_string is None:
                return error(
                    NSLocalizedString(
                        "Error: Pasteboard doesn't contain a string.",
                        "Pasteboard couldn't give string.",
                    ))

            new_string = translate_text.translate(pboard_string)
            rumps.alert(new_string)

            types = [NSStringPboardType]
            pboard.declareTypes_owner_([NSStringPboardType], None)
            pboard.setString_forType_(new_string, NSStringPboardType)
            return ''

        except Exception as e:  # noqa: E722, B001
            capture_exception(e)
            # import traceback
            # traceback.print_exc()
            return error("Exception, see traceback")
Beispiel #10
0
 def cb(sender):
     minutes = sender.value
     if not minutes:
         dlg = rumps.Window("Enter interval length in minutes:",
                            "Custom interval",
                            str(self.config.interval),
                            dimensions=(320, 120),
                            cancel=True)
         while True:
             res = dlg.run()
             if res.clicked == 0:
                 return
             try:
                 minutes = int(res.text)
                 break
             except ValueError:
                 rumps.alert("Error", "Invalid input!")
                 dlg.default_text = res.text
                 continue
         sender.title = "Custom: %s minutes" % minutes
     else:
         menu["Custom..."].title = "Custom..."
     # Closure magic...
     for item in menu.values():
         item.state = False
     sender.state = True
     self.set_interval(minutes)
Beispiel #11
0
def terminate_pid(pid):
    try:
        name = get_name(pid)
        if is_system_process(pid):
            message = "Process %s (%s) is a critical process that should not be terminated." % (
                pid, get_name(pid))
            rumps.alert("Tempo: Terminate Canceled", message)
            return
        title = "Are you sure you want to terminate process %s (%s)?" % (pid,
                                                                         name)
        message = ("Terminating this process could lead to data loss.\n\n" +
                   "If this is a system process, it may just get restarted. " +
                   "In the worst case, you could lock up your machine.\n\n" +
                   "We suggest you suspend the process, not terminate it.")
        if not rumps.alert(title,
                           message,
                           ok="Terminate, I know what I am doing",
                           cancel="Cancel"):
            log.log("User canceled termination of process %d (%s)" %
                    (pid, name))
            return
        return get_process(pid).terminate()
    except psutil.AccessDenied:
        return execute_as_root(
            "terminate process %d (%s)" % (pid, get_name(pid)),
            "kill -TERM %s" % pid)
    except (psutil.NoSuchProcess, psutil.ZombieProcess):
        pass
    except Exception as e:
        log.log("Unhandled Error in process.terminate", e)
Beispiel #12
0
    def update_weather(self, _):
        logging.info('Current apiKey and cityId: %s,%s' %
                     (self.apiKey, self.cityId))
        url = base_weather_url % (self.cityId, self.apiKey, self.units)
        logging.info(url)
        if self.apiKey == '' or self.cityId == '':
            result = rumps.alert(
                'No API key or City id',
                'Open Preferences to set API key or City id. You can get both from OpenWeatherMap.com. After you set them in preferences, restart the app!',
                ok="Open Preferences",
                other='Go to OpenWeatherMap',
                icon_path='app_icon.png')
            if result == 1:
                subprocess.Popen(["open", "-t", home_dir + '/config.json'])
            else:
                subprocess.Popen(["open", 'https://openweathermap.com'])
            return
        try:
            req = urllib.request.Request(url)
            response = urllib.request.urlopen(req)
            data = json.loads(response.read())
            self.icon = 'icons/' + data['weather'][0]['icon'] + '.png'
            title_button = self.menu['Weather description']
            title_button.title = data['weather'][0]['main'] + " (" + data[
                'weather'][0]['description'] + ")"
            title_button = self.menu['Wind description']
            title_button.title = 'Wind: %s%s %s' % (
                data['wind']['speed'], wind_speed_text[self.units],
                degree_to_direction(data['wind']['speed']))
            title_button = self.menu['City']
            title_button.title = data['name']
            self.title = temp_base_text[self.units] % data['main']['temp']

            url = forecast_url % (self.cityId, self.apiKey, self.units)
            req = urllib.request.Request(url)
            response = urllib.request.urlopen(req)
            data = json.loads(response.read())
            forecast_id = 0
            for forecast in data['list'][:3]:
                forecast_id += 1
                forecast_button = self.menu['Forecast Data %s' % forecast_id]
                forecast_button.icon = 'icons/' + forecast['weather'][0][
                    'icon'] + '.png'
                forecast_button.template = True
                forecasted_temp = temp_base_text[
                    self.units] % forecast['main']['temp'] + " " + forecast[
                        'weather'][0]['main'] + " (" + forecast['weather'][0][
                            'description'] + ")"
                forecast_button.title = forecasted_temp
        except Exception as e:
            result = rumps.alert(
                'Problem with accessing OpenWeatherMap',
                'Weatherette had problem with connecting OpenWeatherMap. Check if you API key is correct and the site is online!',
                ok="Close",
                other='Go to OpenWeatherMap',
                icon_path='app_icon.png')
            logging.exception('message')

        pass
Beispiel #13
0
 def prefs(self, _):
     if len(self.people_now_present) > 0:
         res = ""
         for p in self.people_now_present:
             res += "-" + str(p) + "\n"
     else:
         res = "Nobody is there .. for the moment ! \n"
     rumps.alert(res)
def summary_callback(_):
    global info
    if len(info) > 1:
        rumps.alert(get_simple_formatted_info(info))
    else:
        msg = "No information available. Please refresh or wait until the next hour elapses."
        rumps.alert(msg)
        logger.warning(msg)
Beispiel #15
0
 def window_about():
     rumps.alert(
         title=_("About TransPad"),
         message=
         "ProjectURL:https://github.com/rexzhang/trans-pad \nConfigPath:{} \n{}"
         .format(get_path_for_file_config(), get_path_for__file__()),
         icon_path="icon.icns",
     )
Beispiel #16
0
 def load_credentials(self):
     session_keychain = keychain.Keychain()
     infos = session_keychain.get_generic_password('login', None, 'webcronic')
     if isinstance(infos, dict):
         self.API_USERNAME = infos['account']
         self.API_PASSWORD = infos['password']
     else:
         rumps.alert("Vous devez créer un élément 'webcronic' dans le trousseau d'accès !")
Beispiel #17
0
def suspend_pid(pid):
    if is_system_process(pid):
        rumps.alert(
            "HappyMac: Suspend Canceled",
            "Process %s (%s) is a critical process that should not be suspended." % (pid, get_name(pid))
        )
        return False
    return execute_shell_command("suspend", pid, "kill -STOP %s" % pid)
Beispiel #18
0
 def trad_ba(self, _):
     data, meta_data = ts.get_intraday('BA')
     data_df = pd.DataFrame(data).iloc[:, 0]
     rumps.alert(title='BA latest stock insights',
                 message="Open: " + data_df['1. open'] + "$" + "\nHigh: " +
                 data_df['2. high'] + "$" + "\nLow: " + data_df['3. low'] +
                 "$" + "\nClose: " + data_df['4. close'] + "$" +
                 "\nVolume: " + data_df['5. volume'])
Beispiel #19
0
 def get_user_info(self):
     if self.geek_hub is None:
         self.geek_hub = Robot(self.setting_config.get("session"))
     user_name = self.geek_hub.get_user_info()
     if user_name:
         self.user_name_menu.title = user_name
     else:
         rumps.alert("session过期或获取用户名失败", icon_path=self.get_icon('alert'))
 def changeit(self, _):
     response = rumps.Window('Enter new interval (In seconds)').run()
     if response.clicked:
         try:
             rumps.timer.__dict__["*timers"][0].interval = int(response.text)
             rumps.alert("Interval set as %s seconds." % response.text)
         except ValueError:
             rumps.alert("Invalid value")
Beispiel #21
0
 def about_command(self, _):
     msg = "URLify is a little application that quickly cleans up text so you can use it in other locations " \
           "(e.g. convert a title to a file name).\n\n" \
           "It's created by Michael Kennedy and is built with Python 3 and RUMPS. " \
           "\n" \
           "\n" \
           "Updates at https://github.com/mikeckennedy/urlify"
     rumps.alert(message=msg, title=f"URLify v{VERSION}")
Beispiel #22
0
 def update_trojan_client(self, sender):
     result, message = do_update_trojan()
     if result:
         if hasattr(self.status_item,
                    "title") and self.status_item.title == "当前状态:开启":
             stop_trojan()
             start_trojan()
     rumps.alert(message)
Beispiel #23
0
 def update_trojan_client(self, sender):
     if do_update_trojan():
         if hasattr(self.status_item,
                    "title") and self.status_item.title == u"当前状态:开启":
             stop_trojan()
             start_trojan()
         rumps.alert(u"更新成功!")
     else:
         rumps.alert(u"已是最新版本,无需更新!")
Beispiel #24
0
def about(sender, _):
    description = ('Программа показывает курсы в статус баре.\n'+
        'Обновление курсов происходит раз в минуту.\n'+
        'Если курс изменился, то он будет окружен зведочками - *курс*.\n'+
        'Если курс не удалось получить, то он будет показан так: последний курс**.\n'+
        'Курсы НБУ и Межбанка обновляются раз в час.\n'+
        'По умолчанию, город - Харьков, валюта - USD-UAH\n'
        ) 
    rumps.alert(message=description, title='Obmenka Status Bar v.'+version)
Beispiel #25
0
 def configure_name(self, _):
     config.run()
     f = open('.name', 'r+')
     names = f.read()
     rumps.alert("We think your name is one of "+names)
     window = rumps.Window(title="if that's incorrect, correct it here", default_text=names.split(',')[0], dimensions=(100, 20))
     name = window.run().text
     f.write(","+name)
     f.close()
Beispiel #26
0
 def break_popup(self, _=None):
     """
     Popup prompting the user to let the app know when they have returned.
     """
     self.bring_to_front()
     rumps.alert(title="Go On Break", message="Get away from the computer!", ok="Back!")
     self.app.icon = "wind.png"
     self.checkin = datetime.datetime.now()
     self.delta = self.work_delta
 def activate_scene(self, scene_id):
     if not scene_id in self.scenes:
         rumps.alert(title="No such scene.",
                     message="Looks like that scene is missing!",
                     ok=None,
                     cancel="Abort")
     for light_name, value in self.scenes[scene_id].iteritems():
         if light_name.startswith('__'):
             continue
         self.lights[light_name].set_level(value)
Beispiel #28
0
def click_search(self):
    response = rumps.Window(
        cancel="Cancel",
        title="Enter a name",
        message="Enter a complete name or search by first/last name.",
        dimensions=(300, 20),
    ).run()

    if response.clicked:
        rumps.alert(title="Search: %s" % (response.text), message=mlh.search_user(response.text))
Beispiel #29
0
 def get_ui(self):
     daemon = xmlrpclib.ServerProxy("http://localhost:7080/")
     try:
         daemon.is_running()
         webbrowser.get('safari').open("lbry://lbry")
     except:
         try:
             rumps.notification(title='LBRY', subtitle='', message="Couldn't connect to lbrynet daemon", sound=True)
         except:
             rumps.alert(title='LBRY', message="Couldn't connect to lbrynet daemon")
Beispiel #30
0
 def time_done(self):
     self.title = DEFAULT_TITLE
     rumps.alert(
         title="Boxy",
         message="Hey! Times up!")
     rumps.notification(
         title="Boxy",
         subtitle="A message for you",
         message="Hey! Times up!",
         sound=True)
Beispiel #31
0
 def start(self, sender):
     rumps.alert("Timer Started")
     for i in range(1501):
         # if not self.active:
         #     super(StatusBarPomodoro, self).__init__("Pomodoro Timer", title = str(time.strftime("%M:%S", time.gmtime(self.seconds))))
         #     break
         time.sleep(1)
         super(StatusBarPomodoro, self).__init__("Pomodoro Timer", title = str(time.strftime("%M:%S", time.gmtime(self.seconds - i))))
     rumps.alert("Time's up! Take a break!")
     self.active = True
Beispiel #32
0
 def preferences(self, _):
     response = rumps.Window('输入你的 Session', cancel="取消", ok="确认").run()
     if response.clicked:
         if response.text.strip():
             session = response.text
             self.setting_config['session'] = session
             self.save_settings()
             self.init_app()
         else:
             rumps.alert("session 值存在问题!", icon_path=self.get_icon('alert'))
Beispiel #33
0
    def prefs_reload(self, sender):
        self.config.load()

        if self.config.warnings != {}:
            warning_str = ""
            for item, warning in self.config.warnings.items():
                warning_str += '"{}" is {}.\n'.format(item, warning)
            rumps.alert(title='Warning!', message=warning_str)

        self.stop_watching()
        self.start_watching()
Beispiel #34
0
 def about(self, _):
     ''' Send alert window displaying application information '''
     self.logger.info('Opening \'About\' window')
     rumps.alert(
         title='About',
         message=(
             'Developed by Wai Lam Fergus Yip.\n'
             'Weather information provided by ClimaCell API\n'
             'Geocoding provided by GeoPy Contributors and ipapi\n'
             'Icon by Catalin Fertu, reused under the CC BY License.\n\n'
             'https://github.com/FergusYip/WeatherBarApp'))
Beispiel #35
0
    def updateWallpaper(self, _):

        # Make sure there's enough wallpapers to set new wallpaper
        numberOfLocalWallpapers = wallpaper.localWallpaperCount()
        if numberOfLocalWallpapers < 2:
            rumps.alert("Not enough local wallpapers found. \
            Downloading new wallpapers now.")

        # Set new wallpaper
        newWallpaper = wallpaper.setRandomWallpaper(self.currentWallpaper)
        self.currentWallpaper = newWallpaper
 def load_config(self, path):
     config = {}
     # load the JSON config file
     try:
         fh = open(path, 'r')
         json_data = fh.read()
         config = json.loads(json_data)
         fh.close()
     except Exception, e:
         rumps.alert(title="Config Error", message=str(e), ok="Okie :)", cancel=None)
         os.exit(1)
Beispiel #37
0
 def check_in(self, callback=None, silent=False):
     if self.geek_hub is None:
         self.geek_hub = Robot(self.setting_config.get("session"))
     score = self.geek_hub.check_in()
     if isinstance(score, int):
         self.user_score_menu.title = f'积分:{score}'
         if not silent:
             rumps.notification(
                 "签到", "签到成功!", f"当前积分{score}", icon=self.get_icon('notification'))
     else:
         rumps.alert("获取积分失败,请尝试重新获取", icon_path=self.get_icon('alert'))
Beispiel #38
0
        def playlist_weekend(song_nums, page):
            def listToString(s):
                str1 = ""

                for ele in s:
                    str1 += ele

                return str1

            if len(song_nums) != 3:
                print("Problem fetching song numbers")
                rumps.alert("Error",
                            "There was a problem fetching the song numbers")
                return 1

            direc = __file__

            x = direc.rfind("/")
            my_file = direc[0:x + 1]

            newfile = []
            line = [
                "<track><location>Songs/sjjm_E_{}_r720P.mp4</location></track>"
                .format(s.zfill(3)) for s in song_nums
            ]
            top = '<?xml version="1.0" encoding="UTF-8"?><playlist xmlns="http://xspf.org/ns/0/" xmlns:vlc="http://www.videolan.org/vlc/playlist/ns/0/" version="1"><title>Playlist</title><trackList>'
            bottom = ' </trackList><extension application="http://www.videolan.org/vlc/playlist/0"><vlc:item tid="0"/></extension></playlist>'

            if page:
                imgs = [x.start() for x in re.finditer("<img src", page)]

                images = []

                for img in imgs:
                    images.append("<track><location>https://wol.jw.org/" +
                                  page[img + 11:img + 42].split('"', 1)[0] +
                                  "</location></track>")

                line.insert(2, listToString(images))

            newfile.insert(0, top)
            newfile.insert(1, listToString(line))
            newfile.insert(2, bottom)

            lines = listToString(newfile)

            with open(my_file + "Meeting.xspf", "w") as file:
                file.writelines(lines)

            subprocess.call(["open", my_file + "Meeting.xspf"])

            print("Finished!\nOpening VLC..")

            return 0
Beispiel #39
0
 def start_new_file(self, _):
     today = datetime.date.today()
     path = today.strftime(os.envget("FREECODE_DIR") + "/%Y/%m/")
     if not os.path.exists(path):
         os.makedirs(path)
     filename = today.strftime('fc_%Y_%m_%d.py')
     full_path = os.path.join(path, filename)
     if os.path.isfile(full_path):
         rumps.alert("Today's file is already created")
     else:
         with open(full_path, 'w') as file:
             file.write(file_template % today.isoformat())
     rumps.notification("Halotis", "started a new file", "good to go")
Beispiel #40
0
def measure_time(_):
    timer_now = time.time()
    remaining_time = int(minutes - (timer_now - start))
    timer_minutes = str((remaining_time) // 60)
    timer_second = str((remaining_time) % 60)
    if int(timer_second) < 10:
        timer_second = '0' + timer_second

    if (remaining_time) > 0:
        app.title = '残り時間:' + timer_minutes + ':' + timer_second
    elif (remaining_time) <= 0:
        app.title = 'TIMEUP'
        rumps.alert(message='時間になりました!')
        rumps.quit_application()
Beispiel #41
0
    def get_stations(self):
        if len(self.stations) > 0:
            return

        try:
            with open('channels.json') as json_data:
                j = json.load(json_data)
                for c in j['channels']:
                    self.stations.append(c)
                    self.urls[c['title']] = c['url']
        except requests.exceptions.RequestException as e:
            rumps.alert(e)

        self.build_menu()
Beispiel #42
0
def terminate_pid(pid):
    if is_system_process(pid):
        rumps.alert(
            "HappyMac: Terminate Canceled",
            "Process %s (%s) is a critical process that should not be terminated." % (pid, get_name(pid))
        )
        return False
    title = "Are you sure you want to terminate process %s (%s)?" % (pid, get_name(pid))
    message = ("Terminating this process could lead to data loss.\n\n" +
            "We suggest you suspend the process, not terminate it.")
    if rumps.alert(title, message, ok="Terminate, I know what I am doing", cancel="Cancel"):
        return execute_shell_command("terminate", pid, "kill -9 %s" % pid)
    else:
        log.log("User skipped termination of process %d (%s)" % (pid, get_name(pid)))
Beispiel #43
0
    def disp_balance(self):
        daemon = xmlrpclib.ServerProxy("http://localhost:7080/")
        try:
            balance = daemon.get_balance()
            r = round(float(balance), 2)
            try:
                rumps.notification(title='LBRY', subtitle='', message=str("Your balance is %.2f LBC" % r), sound=False)
            except:
                rumps.alert(title='LBRY',  message=str("Your balance is %.2f LBC" % r))

        except:
            try:
                rumps.notification(title='LBRY', subtitle='', message="Couldn't connect to lbrynet daemon", sound=True)
            except:
                rumps.alert(title='LBRY', message="Couldn't connect to lbrynet daemon")
Beispiel #44
0
def check_updates(sender,_):
    try:
        latest_version = urllib2.urlopen('http://vlak.us/~vlak/obmenka/latest-version', timeout = 10).read()
    except Exception as e:
        print e
    else:
        latest_version = latest_version.rstrip()
        if str(version) < str(latest_version):
            print 'version!'+version+'!'
            print 'latest version!'+latest_version+'!'
            update_message = ('Необходимо обновление!\n'+
                'Последняя версия: Obmenka-'+latest_version+'\n'+
                'Последняя версия доступна на сайте:\n'+
                'http://vlak.us/~vlak/obmenka/Obmenka-latest.zip'
                )
            rumps.alert(message=update_message, title='Obmenka Status Bar v.'+version)
Beispiel #45
0
 def settings_popup(self):
     settings = {'username':'',
                 'password':'',
                 'harmony_ip':'',}
     w = rumps.Window('Change settings in the textbox below', 'Harmenubar settings')
     w.icon = self.resource_path + 'icon.png'
     if self.settings is None:
         w.default_text = json.dumps(settings, indent=4)
     else:
         w.default_text = json.dumps(self.settings, indent=4)
     w.add_button('Cancel')
     r = w.run()
     if r.clicked == 1:
         self.settings = json.loads(r.text)
         self.save_settings()
     else:
         rumps.alert('No settings enterred, quitting')
         sys.exit('')
Beispiel #46
0
    def _add_timer(self, _):
        window_title = rumps.Window(title=WINDOW_TITLE_MESSAGE,
                                    message='',
                                    default_text='',
                                    cancel=True,
                                    dimensions=WINDOW_DIM)
        window_title.icon = PATH_RES_IMG_MY_TIME
        res_title = window_title.run()
        if not res_title.clicked:
            return

        sec = None
        while sec is None:
            window_sec = rumps.Window(title=WINDOW_TIME_MESSAGE,
                                      message='',
                                      default_text=TIME_EXAMPLE,
                                      cancel=True,
                                      dimensions=WINDOW_DIM)
            window_sec.icon = PATH_RES_IMG_MY_TIME
            res_sec = window_sec.run()
            if not res_sec.clicked:
                return

            try:
                sec = MultiTimerApp.hms_to_sec(res_sec.text)
            except TypeError:
                rumps.alert(INVALID_TIME_FORMAT_MESSAGE)

        title = res_title.text

        def on_finish():
            self._update_view(None)
            rumps.alert(TIME_FINISHED_FORMAT.format(title))
            self._stop_timer(self._get_timer(title))

        self.timers.append(Timer(title, sec, on_finish))
        self.menu.add(rumps.MenuItem(title=title,
                                     callback=self._switch_timer,
                                     icon=PATH_RES_IMG_PLAY))

        remove_menu = self.menu[MENU_ITEM_REMOVE_TIMER]
        remove_menu.set_callback(lambda: None)
        remove_menu.add(rumps.MenuItem(title, callback=self._remove_timer))
Beispiel #47
0
def currency_rates(sender,_):
    crates = str("USD-UAH: " + str(c['usd_uah']['retailBuy']) + "-" + str(c['usd_uah']['retailSell']) + "\n"
                 "EUR-UAH: " + str(c['eur_uah']['retailBuy']) + "-" + str(c['eur_uah']['retailSell']) + "\n"
                 "RUB-UAH: " + str(c['rub_uah']['retailBuy']) + "-" + str(c['rub_uah']['retailSell']) + "\n"
                 "GBP-UAH: " + str(c['gbp_uah']['retailBuy']) + "-" + str(c['gbp_uah']['retailSell']) + "\n"
                 "EUR-USD: " + str(c['eur_usd']['retailBuy']) + "-" + str(c['eur_usd']['retailSell']) + "\n"
                 "USD-RUB: " + str(c['usd_rub']['retailBuy']) + "-" + str(c['usd_rub']['retailSell']) + "\n"
                 "GBP-USD: " + str(c['gbp_usd']['retailBuy']) + "-" + str(c['gbp_usd']['retailSell']) + "\n"
             )
    if rumps.alert(message=crates, title='Текущие курсы в '+city+'е', ok='Open Site', cancel='Close') == 1:
        webbrowser.open_new_tab(obm_url)
Beispiel #48
0
    def set_renotify_time(self, sender):
        w = self.ask('Please enter a new renotify time, in minutes')
        if w.clicked and w.text:
            try:
                int(w.text)
                self.config.set('main', 'renotify_time', w.text)
                sender.title = 'Change renotify time (now {} minutes)'.format(w.text)

                old = self.tickets
                # Create a new expiring dict with the new time
                self.tickets = expiringdict.ExpiringDict(max_len=100, max_age_seconds=int(w.text) * 60)
                # Copy all old keys
                for k, v in old.items():
                    self.tickets[k] = v
            except ValueError:
                rumps.alert('The given renotify time is not a valid integer!')
        else:
            return False
        self.save_config()
        return True
Beispiel #49
0
    def run_monitor(self, _):
        try:
            url = self.config.get('main', 'url')
            user = self.config.get('main', 'user')
            password = keyring.get_password(self.__class__.__name__, user)
            r = requests.get(url, auth=(user, password), timeout=3)
            if r.status_code == 401:
                # Forbidden, user/pass combo is probably wrong. Reask.
                rumps.alert('Could not login, please reenter username and password!')
                self.set_user_pass(None)
                user = self.config.get('main', 'user')
                password = keyring.get_password(self.__class__.__name__, user)
                r = requests.get(url, auth=(user, password), timeout=3)

            soup = BeautifulSoup(r.text, "lxml")
            tables = soup.find_all("table", {"class": "ticket-list collection-as-table"})

            self.menu['Recent tickets'] = []

            owned = []
            unowned = None
            if len(tables):
                owned = [tables[0]]

            if len(tables) > 1:
                unowned = tables[1]

            if len(tables) > 2:
                owned += [tables[2]]

            for t in owned:
                self.process_table(self.tickets, t, url, user)

            if unowned:
                self.process_table(self.tickets, unowned, url, user, filter_owner=False)

        except requests.exceptions.RequestException:
            logging.warning("Could not connect to Request Tracker, trying again soon")
            pass
Beispiel #50
0
 def about(self, sender):
     rumps.alert(title='%s' % __prog__,
                 message='Gmail notification in Menu bar.\n' +
                 'Version %s\n' % __version__ +
                 '%s' % __copyright__)
Beispiel #51
0
 def about(self, _):
     rumps.alert("umma",
                 "US Mobile Menu App: Track usage\n" +
                 "http://github.com/mankoff/umma")
Beispiel #52
0
 def prefs(self, _):
     rumps.alert("Talk to Jachin.")
Beispiel #53
0
def print_something(_):
    rumps.alert(message='something', ok='YES!', cancel='NO!')
Beispiel #54
0
 def prefs(self, sender):
     rumps.alert("todo")
Beispiel #55
0
 def pause(self, _):
     rumps.alert("todo")
Beispiel #56
0
def about(sender):
    sender.title = 'NOM' if sender.title == 'About' else 'About'  # can adjust titles of menu items dynamically
    rumps.alert("This is a cool app!")
 def prefs(self, _):
     rumps.alert("jk! no preferences available!")
Beispiel #58
0
 def on_finish():
     self._update_view(None)
     rumps.alert(TIME_FINISHED_FORMAT.format(title))
     self._stop_timer(self._get_timer(title))
Beispiel #59
0
 def prefs(self, _):
     rumps.alert("No preferences yet")
Beispiel #60
0
 def uninstall(self, sender):
     ret = rumps.alert('Do you want to uninstall MenuBarGmail?',
                       ok='OK', cancel='Cancel')
     if ret == 1:
         self.remove_me()