Exemplo n.º 1
0
    def __init__(self):

        super(WeatheretteApp, self).__init__("Weatherette")

        if os.path.exists(home_dir + '/config.json'):
            config = json.load(open(home_dir + '/config.json'))
            self.apiKey = config['apiKey']
            self.cityId = config['cityId']
            self.cityName = config['cityName']
            self.units = config['units']
        self.save_config()

        self.menu = [
            'Weather description', 'Wind description', separator,
            "Forecast (next 9 hours)", "Forecast Data 1", "Forecast Data 2",
            "Forecast Data 3", separator, "City", separator, "Display",
            "Preferences", separator, "About Weatherette"
        ]
        self.icon = 'icons/01d.png'
        self.title = 'No data'
        self.template = True

        title_button = self.menu['City']
        title_button.title = self.cityName

        self.menu['Display'].add(
            MenuItem(
                'Metric',
                callback=lambda sender: self.set_region('metric', sender)))
        self.menu['Display'].add(
            MenuItem(
                'Imperial',
                callback=lambda sender: self.set_region('imperial', sender)))

        logging.info('Starting app')
Exemplo n.º 2
0
 def create_preferences_menu(self):
     """Create the preferences menu."""
     self.menu.add(
         MenuItem(self.Menu.Preferences.value,
                  callback=self.clicked_preferences))
     self.menu.add(
         MenuItem(self.Menu.ReloadConfigFile.value,
                  callback=self.clicked_reload_config_file))
     self.menu.add(rumps.separator)
Exemplo n.º 3
0
def insert_unload_reload(ar: rumps.MenuItem, j: launchd.LaunchdJob):
    print(j.plistfilename)
    ar.add(
        rumps.MenuItem("Unload",
                       callback=lambda x: launchd.unload(j.plistfilename)))
    ar.add(
        rumps.MenuItem("Reload",
                       callback=lambda x: launchd.unload(j.plistfilename) and
                       launchd.load(j.plistfilename)))
Exemplo n.º 4
0
 def update_zone_menu(self):
     players = []
     for z in self.zones:
         menuitem = MenuItem(z.player_name, callback=self.select_zone)
         menuitem.state = 1 if self.zone == z else 0
         players.append(menuitem)
     players.append(MenuItem('Update zones', callback=self.update_zones_fork))
     if self.menu['Zones']:
         self.menu['Zones'].clear()
     self.menu['Zones'].update(players)
Exemplo n.º 5
0
 def add_local_clock(self):
     # add local zone by default
     local_zone = get_localzone().zone
     self.add_clock(local_zone)
     if self.timezones_menu.has_key(local_zone):
         self.timezones_menu[local_zone].state = 1
     else:
         item = MenuItem(local_zone, callback=self.switch_clock_callback)
         item.state = 1
         self.timezones_menu.add(item)
Exemplo n.º 6
0
 def update_menu(self):
     self.menu.clear()
     self.menu = [
         MenuItem(f'Translate to {self.dest_lang_title}',
                  callback=self.translate,
                  key='t'), separator,
         [
             MenuItem('Select target language'),
             self.list_languages_menu(self.define_target_language)
         ], separator,
         MenuItem(f'Quit', callback=self.quit, key='q')
     ]
Exemplo n.º 7
0
        def select(sender: rumps.MenuItem):
            index = None
            _options = []
            if isinstance(options, dict):
                _options = list(options.keys())
                index = osa_api.choose_from_list(sender.title, description, _options, multi)
            elif isinstance(options, list):
                index = osa_api.choose_from_list(sender.title, description, options, multi)

            if index is not None:
                content = None
                if isinstance(options, dict):
                    content = options[_options[index]]
                elif isinstance(options, list):
                    content = options[index]

                setattr(self.config, key, content)

                if empty_state:
                    sender.state = content != ''

                self.config.save()
                return True

            return False
Exemplo n.º 8
0
def insert_log_menu_items(ar: rumps.MenuItem, ag):
    log = ag['StandardOutPath']
    log_cb = lambda x: subprocess.call(["open", "-a", "Console", log])
    err = ag['StandardErrorPath']
    err_cb = lambda x: subprocess.call(["open", "-a", "Console", err])
    ar.add(rumps.separator)
    ar.add(rumps.MenuItem("View Log", callback=log_cb if log else None))
    ar.add(rumps.MenuItem("View Error Log", callback=err_cb if err else None))
    ar.add(rumps.separator)
Exemplo n.º 9
0
    def __init__(self, app, path):
        self.app = app
        self.path = path
        self.name = path.split("/")[-1]
        self.insecure = None

        self.menu_item = MenuItem(
            self.path,
            callback=self.clicked,
            key=self.path,
            icon=ICONS.GRAY,
        )

        self.requirement_files = None
        self.ui_helper = UIHelper.alloc().initWithApp_(app)

        NSApp.activateIgnoringOtherApps_(True)
Exemplo n.º 10
0
 def init_menu(self):
     # add timezones menu
     self.timezones_menu = MenuItem('Time Zones')
     for tz in TIMEZONES:
         self.timezones_menu.add(MenuItem(tz, callback=self.switch_clock_callback))
     # recently added menu
     self.recent_menu = MenuItem('Add Recent')
     # add interval menu
     self.interval_menu = MenuItem('Update Time')
     for secs in INTVLS:
         item = MenuItem(secs, callback=self.update_interval)
         if secs == DEFAULT_INTVL_STR:
             item.state = 1
         self.interval_menu.add(item)
     self.about_btn = MenuItem('About', callback=self.open_about)
     self.quit_btn = MenuItem('Quit', callback=self.quit_app)
     self.menu = [self.timezones_menu, self.recent_menu,
                  self.interval_menu, self.about_btn, self.quit_btn]
Exemplo n.º 11
0
 def set_menu(self):
     self.app.menu.clear()
     self.app.menu = [
         MenuItem("Add Quote",
                  callback=lambda _=None: [
                      Quote(quote=dialog_prompt(
                          "Please enter in your quote!")).save(),
                      self.set_menu()
                  ])
     ]
Exemplo n.º 12
0
    def new_project(self, _):
        window = rumps.Window(
            title='Enter a project name',
            dimensions=(250, 23),
        )

        if project_name := window.run().text:
            self.start_project(project_name)
            menu_item = MenuItem(project_name, callback=None)
            self.menu.insert_after(projects[-1], menu_item)
            projects.append(project_name)
Exemplo n.º 13
0
    def __init__(self, project, path, requirements):
        self.project = project
        self.path = path

        self.menu_item = MenuItem(
            self.path,
            key=path,
            callback=self.clicked,
            icon=ICONS.GRAY,
        )

        self.requirements = requirements
Exemplo n.º 14
0
 def _event_menu_item(self, event) -> MenuItem:
     """
     Generate a menu item for an event. The callback will navigate the user
     to the agenda item in the browser.
     """
     event_date = ''
     if 'dateTime' in event['start']:
         start = parse(event['start']['dateTime'])
         event_date = start.strftime("%m-%d %H:%M")
     elif 'date' in event['start']:
         event_date = event['start']['date']
     return MenuItem(f'{event_date} - {event["summary"]}',
                     callback=lambda _: webbrowser.open(event['htmlLink']))
Exemplo n.º 15
0
def get_profiles(callback: object) -> List[MenuItem]:
    """
    Parse AWS Config and generate rumps MenuItem list

    @type callback: object
    @rtype: MenuItem[]
    """
    path = pathlib.PosixPath('~/.aws/config')
    CONFIG.read(path.expanduser())
    profile_items = []
    for profile in CONFIG.sections():
        profile_items.append(
            MenuItem(profile.replace('profile ', ''), callback=callback))
    return profile_items
Exemplo n.º 16
0
 def update_title(self,_):
     track = self.zone.group.coordinator.get_current_track_info()
     title = "%s: %s" % (track['artist'], track['title'])
     album = track['album']
     uri = track['album_art']
     if not (self.title and self.title == title):
         self.title = None
         self.title = title
     if uri and not self.uri == title:
         self.uri = uri
         filename = os.path.join(rumps.application_support(self.name), 'track.jpeg')
         urlretrieve (uri, filename)
         if self.menu['Album info']:
             self.menu['Album info'].clear()
         art = MenuItem(album, icon=filename, dimensions=[256, 256], callback=lambda x: None)
         self.menu['Album info'].update(art)
     self.menu['Mute'].state = 1 if self.zone.mute else 0
Exemplo n.º 17
0
        def set_input(sender: rumps.MenuItem):
            content = osa_api.dialog_input(sender.title, getattr(self.lang, description),
                                           str(getattr(self.config, key, '')), hidden=hidden)

            if content is not None:
                if to_int:
                    if isinstance(content, str) and content.replace('-', '', 1).isnumeric():
                        setattr(self.config, key, int(content))
                else:
                    setattr(self.config, key, content)

                if empty_state:
                    sender.state = content != ''

                self.config.save()
                return True

            return False
Exemplo n.º 18
0
        def set_input(sender: rumps.MenuItem):
            content = osa_api.dialog_input(sender.title,
                                           getattr(self.lang, description),
                                           str(getattr(self.config, key, '')),
                                           hidden=hidden)

            if content is not None:
                if convertor is not None:
                    content = convertor(content)

                if content is not None:
                    setattr(self.config, key, content)

                if empty_state:
                    sender.state = content != ''

                self.config.save()
                return True

            return False
Exemplo n.º 19
0
    def __init__(self):
        super().__init__(TITLE_DEFAULT)

        print('[-] Booting the app...')

        # Check if there's currently a running task
        self.task_name, self.task_start_time = get_watson_status()
        if self.task_name and self.task_start_time:
            self.task_started = True

        # Fill menu items and bind click events
        for project in projects:
            menu_item = MenuItem(
                project,
                callback=None if self.task_started else self.project_click)
            self.menu.add(menu_item)

        # Add an empty line before the Quit button
        self.menu.add(None)
        self.menu.add('Stop')
Exemplo n.º 20
0
 def update_menu(self, _):
     """
     Function that runs on a timer to keep osx menu bar up to date
     @rtype: object
     """
     self.menu.clear()
     self.menu = [
         f'Current profile {self.vault.current_profile}',
         (
             'Console Login',
             get_profiles(self.vault.console_login)
         ),
         (
             'Start Metadata Server',
             get_profiles(self.vault.start_metadata_server)
         ),
         MenuItem(
             'Stop Metadata Server',
             callback=self.vault.stop_metadata_server
         ),
         APP.quit_button,
     ]
Exemplo n.º 21
0
 def _refresh_menu(self):
     """
     Load the menu items, if the user is not authenticated we display the
     configure menu with the supported platforms.
     """
     if not self._authenticated:
         self.menu = [[
             MenuItem('Configure'),
             [MenuItem('Google Calendar', callback=self.configure_google)]
         ], None,
                      MenuItem('Quit', key='q', callback=quit_application)]
     else:
         self.menu = [
             MenuItem(
                 'Open Calendar',
                 callback=lambda _: webbrowser.open(self.CALENDAR_URL)),
             [MenuItem('Upcoming Items'),
              self._create_event_items()], None,
             MenuItem('Logout', callback=self.logout), None,
             MenuItem('Quit', key='q', callback=quit_application)
         ]
Exemplo n.º 22
0
 def set_menu(self):
     list(map(lambda i: self.app.menu.pop(i), list(self.app.menu.keys())))
     print("getting zip code...")
     zip_code = re.findall(
         "(?s)(\d{5})</span>.*<span>.*Weather</span>",
         requests.get("https://www.google.com/search?q=weather").text)[0]
     hourly, tenday = requests.get(
         "https://weather.com/weather/hourbyhour/l/%s" %
         (zip_code)).text, requests.get(
             "https://weather.com/weather/tenday/l/%s" % (zip_code)).text
     hourly_time = list(
         map(
             lambda i: i.strip(),
             key(
                 "text",
                 BeautifulSoup(hourly).findAll(
                     "div", attrs={"class": "hourly-time"}))))
     hourly_date = list(
         map(
             lambda i: i.strip(),
             key(
                 "text",
                 BeautifulSoup(hourly).findAll(
                     "div", attrs={"class": "hourly-date"}))))
     hourly_desc = list(
         map(
             lambda i: i.strip(),
             key(
                 "text",
                 BeautifulSoup(hourly).findAll(
                     "td", attrs={"class": "description"}))))
     hourly_temp = list(
         map(
             lambda i: i.strip(),
             key(
                 "text",
                 BeautifulSoup(hourly).findAll("td",
                                               attrs={"class": "temp"}))))
     tenday_time = list(
         map(
             lambda i: i.strip(),
             key(
                 "text",
                 BeautifulSoup(tenday).findAll("span",
                                               attrs={"class":
                                                      "date-time"}))))
     tenday_date = list(
         map(
             lambda i: i.strip(),
             key(
                 "text",
                 BeautifulSoup(tenday).findAll(
                     "span", attrs={"class": "day-detail"}))))
     tenday_desc = list(
         map(
             lambda i: i.strip(),
             key(
                 "text",
                 BeautifulSoup(tenday).findAll(
                     "td", attrs={"class": "description"}))))
     tenday_temp = list(
         map(
             lambda i: i.strip(),
             key(
                 "text",
                 BeautifulSoup(tenday).findAll("td",
                                               attrs={"class": "temp"}))))
     hourly_prints = lmap(
         lambda time, date, desc, temp: "{} on {}, {} - {}".format(
             time, date, desc, temp),
         list(zip(hourly_time, hourly_date, hourly_desc, hourly_temp)))
     tenday_prints = lmap(
         lambda time, date, desc, temp: "{} on {}, {} - {}".format(
             time, date, desc, temp),
         list(zip(tenday_time, tenday_date, tenday_desc, tenday_temp)))
     self.app.icon = urllib.request.urlretrieve(
         "https://cdn3.iconfinder.com/data/icons/bebreezee-weather-symbols/690/icon-weather-sunrainheavy-512.png",
         "icon.png")[0]
     self.app.menu = [
         MenuItem("Hourly"),
         *list(map(lambda i: MenuItem(i), hourly_prints)),
         MenuItem(""),
         MenuItem("Tenday"),
         *list(map(lambda i: MenuItem(i), tenday_prints))
     ]
     self.app.run()
Exemplo n.º 23
0
class Project(object):
    def __init__(self, app, path):
        self.app = app
        self.path = path
        self.name = path.split("/")[-1]
        self.insecure = None

        self.menu_item = MenuItem(
            self.path,
            callback=self.clicked,
            key=self.path,
            icon=ICONS.GRAY,
        )

        self.requirement_files = None
        self.ui_helper = UIHelper.alloc().initWithApp_(app)

        NSApp.activateIgnoringOtherApps_(True)

    @property
    def is_valid(self):
        return self.requirement_files is not None and self.requirement_files

    @property
    def needs_check(self):
        return self.insecure is None

    def find_requirement_files(self):
        def is_likely_a_requirement(path):
            if "req" in path:
                if path.endswith(".txt") or path.endswith(".pip"):
                    return True
            return False

        def parse(file_name):
            reqs = []
            try:
                with open(file_name) as fh:
                    for item in read_requirements(fh):
                        if isinstance(item, SafetyPackage):
                            reqs.append(item)
                        elif isinstance(item, SafetyRequirementFile):
                            for other_file in parse(item.path):
                                yield other_file
                    if reqs:
                        yield RequirementFile(project=self,
                                              requirements=reqs,
                                              path=file_name)
            except:
                pass

        for item in os.listdir(self.path):
            full_path = os.path.join(self.path, item)
            if os.path.isdir(full_path):
                for item_deep in os.listdir(full_path):
                    full_path_deep = os.path.join(full_path, item_deep)
                    if os.path.isfile(
                            full_path_deep) and is_likely_a_requirement(
                                full_path_deep):
                        for req_file in parse(full_path_deep):
                            yield req_file
            elif os.path.isfile(full_path) and is_likely_a_requirement(
                    full_path):
                for req_file in parse(full_path):
                    yield req_file

    def check(self):
        if self.requirement_files is None:
            self.requirement_files = list(self.find_requirement_files())

        insecure = False
        for req in self.requirement_files:
            vulns = req.check()
            if vulns:
                insecure = True
        self.insecure = insecure
        if insecure:
            self.menu_item.icon = ICONS.RED
        else:
            self.menu_item.icon = ICONS.GREEN

    def add(self):
        self.menu_item.update([r.menu_item for r in self.requirement_files])

        # self.app.menu.update(self.menu_item)
        self.ui_helper.pyobjc_performSelectorOnMainThread_withObject_(
            'updateMenuItem:', self.menu_item)

    def clicked(self, sender):
        subprocess.call(['open', self.path])

    def __eq__(self, other):
        if isinstance(other, Project):
            return self.path == other.path
        return super(Project, self).__eq__(other)

    def __ne__(self, other):
        return not self.__eq__(other)
Exemplo n.º 24
0
class ClockApp(App):

    def __init__(self):
        super(ClockApp, self).__init__("Clock", quit_button=None)
        self.init_menu()
        self.clocks = Clocks(times_to_flip=INTVLS_MAP.get(DEFAULT_INTVL_STR))
        self.load_clocks_data()
        self.load_intvl_data()

    def load_clocks_data(self):
        clocks_tz = []
        filepath = application_support(APP_NAME) + '/' + SUPPORT_CLOCKS_FILENAME
        if os.path.exists(filepath):
            f = open(filepath, 'r')
            for e in pickle.load(f):
                if isinstance(e, str):
                    clocks_tz.append(e)
        if len(clocks_tz) > 0:
            for tz in clocks_tz:
                self.add_clock(tz)
        else:
            self.add_local_clock()
        return

    def dump_clocks_data(self):
        filepath = application_support(APP_NAME) + '/' + SUPPORT_CLOCKS_FILENAME
        f = open(filepath, 'wb')
        pickle.dump(self.clocks.clock_keys, f)
        return

    def load_intvl_data(self):
        filepath = application_support(APP_NAME) + '/' + SUPPORT_INTVL_FILENAME
        if os.path.exists(filepath):
            f = open(filepath, 'r')
            intvl = pickle.load(f)
            self.clocks.set_times_to_flip(intvl)
            for s, i in INTVLS_MAP.items():
                self.interval_menu[s].state = 1 if i == intvl else 0

    def dump_intvl_data(self):
        filepath = application_support(APP_NAME) + '/' + SUPPORT_INTVL_FILENAME
        f = open(filepath, 'wb')
        pickle.dump(self.clocks.times_to_flip, f)
        return

    def init_menu(self):
        # add timezones menu
        self.timezones_menu = MenuItem('Time Zones')
        for tz in TIMEZONES:
            self.timezones_menu.add(MenuItem(tz, callback=self.switch_clock_callback))
        # recently added menu
        self.recent_menu = MenuItem('Add Recent')
        # add interval menu
        self.interval_menu = MenuItem('Update Time')
        for secs in INTVLS:
            item = MenuItem(secs, callback=self.update_interval)
            if secs == DEFAULT_INTVL_STR:
                item.state = 1
            self.interval_menu.add(item)
        self.about_btn = MenuItem('About', callback=self.open_about)
        self.quit_btn = MenuItem('Quit', callback=self.quit_app)
        self.menu = [self.timezones_menu, self.recent_menu,
                     self.interval_menu, self.about_btn, self.quit_btn]

    @timer(1)
    def update(self, _):
        self.title = self.clocks.get_clock_time_str()
        self.update_clocks_menu()

    def update_interval(self, sender):
        for item in self.interval_menu.values():
            item.state = 0
        sender.state = 1
        self.clocks.set_times_to_flip(INTVLS_MAP.get(sender.title, 5))

    def add_clock(self, tz_name):
        if self.clocks.add_clock(tz_name):
            self.update_clocks_menu()
            self.timezones_menu[tz_name].state = 1

    def remove_clock(self, tz_name):
        if self.clocks.remove_clock(tz_name):
            self.update_clocks_menu()
            self.timezones_menu[tz_name].state = 0

    def update_clocks_menu(self):
        # reconstruct clocks menu
        items = []
        items.extend(self.clocks.get_all_clock_time_str())
        items.append(separator)
        items.append(self.timezones_menu)
        if len(self.recent_menu.keys()) > 0:
            self.recent_menu.clear()
        for c in self.clocks.get_history_clocks():
            self.recent_menu.add(
                MenuItem(c, callback=self.add_clock_from_recent_callback))
        items.append(self.recent_menu)
        items.append(self.interval_menu)
        items.append(self.about_btn)
        items.append(self.quit_btn)
        self.menu.clear()
        self.menu.update(items)

    def switch_clock_callback(self, sender):
        tz_name = str(sender.title)
        if sender.state == 0:
            self.add_clock(tz_name)
        else:
            self.remove_clock(tz_name)

    def add_clock_from_recent_callback(self, sender):
        tz_name = str(sender.title)
        self.add_clock(tz_name)
        self.timezones_menu[tz_name].state = 1

    def add_local_clock(self):
        # add local zone by default
        local_zone = get_localzone().zone
        self.add_clock(local_zone)
        if self.timezones_menu.has_key(local_zone):
            self.timezones_menu[local_zone].state = 1
        else:
            item = MenuItem(local_zone, callback=self.switch_clock_callback)
            item.state = 1
            self.timezones_menu.add(item)

    def open_about(self, sender):
        import webbrowser
        # new = 2 for opening in the tab if possible
        webbrowser.open(ABOUT_URL, new=2)
        return

    def quit_app(self, sender):
        self.dump_clocks_data()
        self.dump_intvl_data()
        quit_application(sender)
Exemplo n.º 25
0
def test_get_config(
    mock_config_sections,
    mock_config_read,
):
    config.get_profiles(mock.ANY)
    assert config.get_profiles(mock.ANY) == [MenuItem('sso_test', mock.ANY)]
Exemplo n.º 26
0
 def switch(sender: rumps.MenuItem):
     sender.state = not sender.state
     setattr(self.config, key, bool(sender.state))
     self.config.save()
Exemplo n.º 27
0
 def list_languages_menu(self, callback):
     return [
         MenuItem(lang, callback=callback) for lang in constants.LANGCODES
     ]