def load_campaigns(self):
		"""Load campaigns from the remote server and populate the :py:class:`Gtk.TreeView`."""
		store = self._model
		store.clear()
		campaigns = self.application.rpc.graphql_find_file('get_campaigns.graphql')
		for campaign in campaigns['db']['campaigns']['edges']:
			campaign = campaign['node']
			company = campaign['company']['name'] if campaign['company'] else None
			created_ts = utilities.datetime_utc_to_local(campaign['created'])
			created_ts = utilities.format_datetime(created_ts)
			campaign_type = campaign['campaignType']['name'] if campaign['campaignType'] else None
			expiration_ts = campaign['expiration']
			if expiration_ts is not None:
				expiration_ts = utilities.datetime_utc_to_local(expiration_ts)
				expiration_ts = utilities.format_datetime(expiration_ts)
			store.append((
				campaign['id'],
				False,
				campaign['name'],
				company,
				campaign_type,
				campaign['user']['name'],
				created_ts,
				expiration_ts
			))
 def load_campaigns(self):
     """Load campaigns from the remote server and populate the :py:class:`Gtk.TreeView`."""
     store = self._model
     store.clear()
     for campaign in self.application.rpc.remote_table("campaigns"):
         company = campaign.company
         if company:
             company = company.name
         created_ts = utilities.datetime_utc_to_local(campaign.created)
         created_ts = utilities.format_datetime(created_ts)
         campaign_type = campaign.campaign_type
         if campaign_type:
             campaign_type = campaign_type.name
         expiration_ts = campaign.expiration
         if expiration_ts is not None:
             expiration_ts = utilities.datetime_utc_to_local(campaign.expiration)
             expiration_ts = utilities.format_datetime(expiration_ts)
         store.append(
             (
                 str(campaign.id),
                 False,
                 campaign.name,
                 company,
                 campaign_type,
                 campaign.user_id,
                 created_ts,
                 expiration_ts,
             )
         )
Example #3
0
	def load_campaigns(self):
		"""Load campaigns from the remote server and populate the :py:class:`Gtk.TreeView`."""
		store = self._model
		store.clear()
		for campaign in self.application.rpc.remote_table('campaigns'):
			company = campaign.company
			if company:
				company = company.name
			created_ts = utilities.datetime_utc_to_local(campaign.created)
			created_ts = utilities.format_datetime(created_ts)
			campaign_type = campaign.campaign_type
			if campaign_type:
				campaign_type = campaign_type.name
			expiration_ts = campaign.expiration
			if expiration_ts is not None:
				expiration_ts = utilities.datetime_utc_to_local(campaign.expiration)
				expiration_ts = utilities.format_datetime(expiration_ts)
			store.append((
				str(campaign.id),
				False,
				campaign.name,
				company,
				campaign_type,
				campaign.user_id,
				created_ts,
				expiration_ts
			))
Example #4
0
 def __async_rpc_cb_load_campaigns(self, results):
     if self.destroyed:
         return
     store = self._tv_model
     style_context = self.dialog.get_style_context()
     bg_color = gui_utilities.gtk_style_context_get_color(
         style_context, 'theme_color_tv_bg', default=ColorHexCode.WHITE)
     fg_color = gui_utilities.gtk_style_context_get_color(
         style_context, 'theme_color_tv_fg', default=ColorHexCode.BLACK)
     hlbg_color = gui_utilities.gtk_style_context_get_color(
         style_context,
         'theme_color_tv_hlbg',
         default=ColorHexCode.LIGHT_YELLOW)
     hlfg_color = gui_utilities.gtk_style_context_get_color(
         style_context, 'theme_color_tv_hlfg', default=ColorHexCode.BLACK)
     now = datetime.datetime.now()
     campaigns = results['db']['campaigns']
     for campaign in campaigns['edges']:
         campaign = campaign['node']
         created_ts = utilities.datetime_utc_to_local(campaign['created'])
         expiration_ts = campaign['expiration']
         is_expired = False
         if expiration_ts is not None:
             expiration_ts = utilities.datetime_utc_to_local(expiration_ts)
             is_expired = expiration_ts < now
         store.append(
             _ModelNamedRow(
                 id=str(campaign['id']),
                 description=(html.escape(campaign['description'],
                                          quote=True)
                              if campaign['description'] else None),
                 bg_color=(hlbg_color if is_expired else bg_color),
                 fg_color=(hlfg_color if is_expired else fg_color),
                 name=campaign['name'],
                 company=(campaign['company']['name']
                          if campaign['company'] is not None else None),
                 type=(campaign['campaignType']['name']
                       if campaign['campaignType'] is not None else None),
                 messages=campaign['messages']['total'],
                 user=campaign['user']['name'],
                 created=created_ts,
                 expiration=expiration_ts,
             ))
     self.gobjects['label_campaign_info'].set_text(
         "Showing {0} of {1:,} Campaign{2}".format(
             len(self._tv_model_filter), len(self._tv_model),
             ('' if len(self._tv_model) == 1 else 's')))
     if campaigns['total']:
         progress = len(self._tv_model) / campaigns['total']
     else:
         progress = 1.0
     self.gobjects['progressbar_loading'].set_text(
         "Loaded {:,} of {:,} campaigns ({:.1f}%)".format(
             len(self._tv_model), campaigns['total'], progress * 100))
     self.gobjects['progressbar_loading'].set_fraction(progress)
     if campaigns['pageInfo']['hasNextPage']:
         self.load_campaigns(cursor=campaigns['pageInfo']['endCursor'])
     else:
         self.gobjects['revealer_loading'].set_reveal_child(False)
         self.gobjects['progressbar_loading'].set_fraction(1.0)
Example #5
0
 def load_campaigns(self):
     """Load campaigns from the remote server and populate the :py:class:`Gtk.TreeView`."""
     store = self._tv_model
     store.clear()
     style_context = self.dialog.get_style_context()
     bg_color = gui_utilities.gtk_style_context_get_color(
         style_context, 'theme_color_tv_bg', default=ColorHexCode.WHITE)
     fg_color = gui_utilities.gtk_style_context_get_color(
         style_context, 'theme_color_tv_fg', default=ColorHexCode.BLACK)
     hlbg_color = gui_utilities.gtk_style_context_get_color(
         style_context,
         'theme_color_tv_hlbg',
         default=ColorHexCode.LIGHT_YELLOW)
     hlfg_color = gui_utilities.gtk_style_context_get_color(
         style_context, 'theme_color_tv_hlfg', default=ColorHexCode.BLACK)
     now = datetime.datetime.now()
     campaigns = self.application.rpc.graphql_find_file(
         'get_campaigns.graphql')
     for campaign in campaigns['db']['campaigns']['edges']:
         campaign = campaign['node']
         created_ts = utilities.datetime_utc_to_local(campaign['created'])
         expiration_ts = campaign['expiration']
         is_expired = False
         if expiration_ts is not None:
             expiration_ts = utilities.datetime_utc_to_local(expiration_ts)
             is_expired = expiration_ts < now
         store.append(
             _ModelNamedRow(
                 id=str(campaign['id']),
                 description=(html.escape(campaign['description'],
                                          quote=True)
                              if campaign['description'] else None),
                 bg_color=(hlbg_color if is_expired else bg_color),
                 fg_color=(hlfg_color if is_expired else fg_color),
                 name=campaign['name'],
                 company=(campaign['company']['name']
                          if campaign['company'] is not None else None),
                 type=(campaign['campaignType']['name']
                       if campaign['campaignType'] is not None else None),
                 messages=campaign['messages']['total'],
                 user=campaign['user']['name'],
                 created=created_ts,
                 expiration=expiration_ts,
             ))
     self.gobjects['label_campaign_info'].set_text(
         "Showing {0} of {1:,} Campaign{2}".format(
             len(self._tv_model_filter), len(self._tv_model),
             ('' if len(self._tv_model) == 1 else 's')))
Example #6
0
    def _set_defaults(self):
        """
		Set any default values for widgets. Also load settings from the existing
		campaign if one was specified.
		"""
        calendar = self.gobjects['calendar_campaign_expiration']
        default_day = datetime.datetime.today() + datetime.timedelta(days=31)
        gui_utilities.gtk_calendar_set_pydate(calendar, default_day)

        if self.is_new_campaign:
            return
        campaign = self.application.get_graphql_campaign()

        # set entries
        self.gobjects['entry_campaign_name'].set_text(campaign['name'])
        self.gobjects['entry_validation_regex_username'].set_text(
            campaign['credentialRegexUsername'] or '')
        self.gobjects['entry_validation_regex_password'].set_text(
            campaign['credentialRegexPassword'] or '')
        self.gobjects['entry_validation_regex_mfa_token'].set_text(
            campaign['credentialRegexMfaToken'] or '')

        if campaign['description'] is not None:
            self.gobjects['entry_campaign_description'].set_text(
                campaign['description'])
        if campaign['campaignType'] is not None:
            combobox = self.gobjects['combobox_campaign_type']
            model = combobox.get_model()
            model_iter = gui_utilities.gtk_list_store_search(
                model, campaign['campaignType']['id'], column=0)
            if model_iter is not None:
                combobox.set_active_iter(model_iter)

        self.gobjects['checkbutton_alert_subscribe'].set_property(
            'active',
            self.application.rpc('campaign/alerts/is_subscribed',
                                 self.campaign_id))
        self.gobjects['checkbutton_reject_after_credentials'].set_property(
            'active', bool(campaign['maxCredentials']))

        if campaign['company'] is not None:
            self.gobjects['radiobutton_company_existing'].set_active(True)
            combobox = self.gobjects['combobox_company_existing']
            model = combobox.get_model()
            model_iter = gui_utilities.gtk_list_store_search(
                model, campaign['company']['id'], column=0)
            if model_iter is not None:
                combobox.set_active_iter(model_iter)

        if campaign['expiration'] is not None:
            expiration = utilities.datetime_utc_to_local(
                campaign['expiration'])
            self.gobjects['checkbutton_expire_campaign'].set_active(True)
            self._expiration_time.time = expiration.time()
            gui_utilities.gtk_calendar_set_pydate(
                self.gobjects['calendar_campaign_expiration'],
                expiration.date())
Example #7
0
	def _load_url_treeview_tsafe(self, hostname=None, refresh=False):
		if refresh or not self._url_information['created']:
			self._url_information['data'] = self.application.rpc.graphql_find_file('get_site_templates.graphql')
			self._url_information['created'] = datetime.datetime.utcnow()
		url_information = self._url_information['data']
		if not url_information:
			return

		rows = []
		domains = []
		for edge in url_information['siteTemplates']['edges']:
			template = edge['node']
			for page in template['metadata']['pages']:
				if hostname and template['hostname'] and not template['hostname'].startswith(hostname):
					continue
				page = page.strip('/')
				resource = '/' + '/'.join((template.get('path', '').strip('/'), page)).lstrip('/')
				domains.append(template['hostname'])
				rows.append(_ModelNamedRow(
					hostname=template['hostname'],
					page=page,
					url=self._build_url(template['hostname'], resource, 'http'),
					classifiers=template['metadata']['classifiers'],
					authors=template['metadata']['authors'],
					description=template['metadata']['description'].strip('\n'),
					created=utilities.format_datetime(utilities.datetime_utc_to_local(template['created']))
				))

				if self._server_uses_ssl:
					rows.append(_ModelNamedRow(
						hostname=template['hostname'],
						page=page,
						url=self._build_url(template['hostname'], resource, 'https'),
						classifiers=template['metadata']['classifiers'],
						authors=template['metadata']['authors'],
						description=template['metadata']['description'].strip('\n'),
						created=utilities.format_datetime(utilities.datetime_utc_to_local(template['created']))
					))

		gui_utilities.glib_idle_add_once(self.gobjects['treeselection_url_selector'].unselect_all)
		gui_utilities.glib_idle_add_store_extend(self._url_model, rows, clear=True)
		# make domain list unique in case multiple pages are advertised for the domains
		domains = [[domain] for domain in set(domains)]
		gui_utilities.glib_idle_add_store_extend(self._hostname_list_store, domains, clear=True)
 def load_campaigns(self):
     """Load campaigns from the remote server and populate the :py:class:`Gtk.TreeView`."""
     store = self._tv_model
     store.clear()
     style_context = self.dialog.get_style_context()
     bg_color = gui_utilities.gtk_style_context_get_color(
         style_context, 'theme_color_tv_bg', default=ColorHexCode.WHITE)
     fg_color = gui_utilities.gtk_style_context_get_color(
         style_context, 'theme_color_tv_fg', default=ColorHexCode.BLACK)
     hlbg_color = gui_utilities.gtk_style_context_get_color(
         style_context,
         'theme_color_tv_hlbg',
         default=ColorHexCode.LIGHT_YELLOW)
     hlfg_color = gui_utilities.gtk_style_context_get_color(
         style_context, 'theme_color_tv_hlfg', default=ColorHexCode.BLACK)
     now = datetime.datetime.now()
     for campaign in self.application.rpc.remote_table('campaigns'):
         company = campaign.company
         if company:
             company = company.name
         created_ts = utilities.datetime_utc_to_local(campaign.created)
         created_ts = utilities.format_datetime(created_ts)
         campaign_type = campaign.campaign_type
         if campaign_type:
             campaign_type = campaign_type.name
         expiration_ts = campaign.expiration
         is_expired = False
         if expiration_ts is not None:
             expiration_ts = utilities.datetime_utc_to_local(
                 campaign.expiration)
             if expiration_ts < now:
                 is_expired = True
             expiration_ts = utilities.format_datetime(expiration_ts)
         store.append(
             (str(campaign.id), campaign.name, company, campaign_type,
              campaign.user_id, created_ts, expiration_ts,
              (hlbg_color if is_expired else bg_color),
              (hlfg_color if is_expired else fg_color),
              (html.escape(campaign.description, quote=True)
               if campaign.description else None)))
     self.gobjects['label_campaign_info'].set_text(
         "Showing {0} of {1:,} Campaign{2}".format(
             len(self._tv_model_filter), len(self._tv_model),
             ('' if len(self._tv_model) == 1 else 's')))
	def load_campaigns(self):
		"""Load campaigns from the remote server and populate the :py:class:`Gtk.TreeView`."""
		store = self._tv_model
		store.clear()
		style_context = self.dialog.get_style_context()
		bg_color = gui_utilities.gtk_style_context_get_color(style_context, 'theme_color_tv_bg', default=ColorHexCode.WHITE)
		fg_color = gui_utilities.gtk_style_context_get_color(style_context, 'theme_color_tv_fg', default=ColorHexCode.BLACK)
		hlbg_color = gui_utilities.gtk_style_context_get_color(style_context, 'theme_color_tv_hlbg', default=ColorHexCode.LIGHT_YELLOW)
		hlfg_color = gui_utilities.gtk_style_context_get_color(style_context, 'theme_color_tv_hlfg', default=ColorHexCode.BLACK)
		now = datetime.datetime.now()
		for campaign in self.application.rpc.remote_table('campaigns'):
			company = campaign.company
			if company:
				company = company.name
			created_ts = utilities.datetime_utc_to_local(campaign.created)
			created_ts = utilities.format_datetime(created_ts)
			campaign_type = campaign.campaign_type
			if campaign_type:
				campaign_type = campaign_type.name
			expiration_ts = campaign.expiration
			is_expired = False
			if expiration_ts is not None:
				expiration_ts = utilities.datetime_utc_to_local(campaign.expiration)
				if expiration_ts < now:
					is_expired = True
				expiration_ts = utilities.format_datetime(expiration_ts)
			store.append((
				str(campaign.id),
				campaign.name,
				company,
				campaign_type,
				campaign.user_id,
				created_ts,
				expiration_ts,
				(hlbg_color if is_expired else bg_color),
				(hlfg_color if is_expired else fg_color),
				(html.escape(campaign.description, quote=True) if campaign.description else None)
			))
		self.gobjects['label_campaign_info'].set_text("Showing {0} of {1:,} Campaign{2}".format(
			len(self._tv_model_filter),
			len(self._tv_model),
			('' if len(self._tv_model) == 1 else 's')
		))
Example #10
0
    def _set_defaults(self):
        """
		Set any default values for widgets. Also load settings from the existing
		campaign if one was specified.
		"""
        calendar = self.gobjects['calendar_campaign_expiration']
        default_day = datetime.datetime.today() + datetime.timedelta(days=31)
        gui_utilities.gtk_calendar_set_pydate(calendar, default_day)

        if self.campaign_id is None:
            return
        campaign = self.application.rpc.remote_table_row('campaigns',
                                                         self.campaign_id,
                                                         cache=True,
                                                         refresh=True)

        self.gobjects['entry_campaign_name'].set_text(campaign.name)
        if campaign.description is not None:
            self.gobjects['entry_campaign_description'].set_text(
                campaign.description)
        if campaign.campaign_type_id is not None:
            combobox = self.gobjects['combobox_campaign_type']
            model = combobox.get_model()
            model_iter = gui_utilities.gtk_list_store_search(
                model, campaign.campaign_type_id, column=0)
            if model_iter is not None:
                combobox.set_active_iter(model_iter)

        self.gobjects['checkbutton_alert_subscribe'].set_property(
            'active',
            self.application.rpc('campaign/alerts/is_subscribed',
                                 self.campaign_id))
        self.gobjects['checkbutton_reject_after_credentials'].set_property(
            'active', campaign.reject_after_credentials)

        if campaign.company_id is not None:
            self.gobjects['radiobutton_company_existing'].set_active(True)
            combobox = self.gobjects['combobox_company_existing']
            model = combobox.get_model()
            model_iter = gui_utilities.gtk_list_store_search(
                model, campaign.company_id, column=0)
            if model_iter is not None:
                combobox.set_active_iter(model_iter)

        if campaign.expiration is not None:
            expiration = utilities.datetime_utc_to_local(campaign.expiration)
            self.gobjects['checkbutton_expire_campaign'].set_active(True)
            gui_utilities.gtk_calendar_set_pydate(
                self.gobjects['calendar_campaign_expiration'], expiration)
            self.gobjects['spinbutton_campaign_expiration_hour'].set_value(
                expiration.hour)
            self.gobjects['spinbutton_campaign_expiration_minute'].set_value(
                expiration.minute)
	def load_campaigns(self):
		"""Load campaigns from the remote server and populate the :py:class:`Gtk.TreeView`."""
		store = self._tv_model
		store.clear()
		style_context = self.dialog.get_style_context()
		bg_color = gui_utilities.gtk_style_context_get_color(style_context, 'theme_color_tv_bg', default=ColorHexCode.WHITE)
		fg_color = gui_utilities.gtk_style_context_get_color(style_context, 'theme_color_tv_fg', default=ColorHexCode.BLACK)
		hlbg_color = gui_utilities.gtk_style_context_get_color(style_context, 'theme_color_tv_hlbg', default=ColorHexCode.LIGHT_YELLOW)
		hlfg_color = gui_utilities.gtk_style_context_get_color(style_context, 'theme_color_tv_hlfg', default=ColorHexCode.BLACK)
		now = datetime.datetime.now()
		campaigns = self.application.rpc.graphql_find_file('get_campaigns.graphql')
		for campaign in campaigns['db']['campaigns']['edges']:
			campaign = campaign['node']
			created_ts = utilities.datetime_utc_to_local(campaign['created'])
			created_ts = utilities.format_datetime(created_ts)
			expiration_ts = campaign['expiration']
			is_expired = False
			if expiration_ts is not None:
				expiration_ts = utilities.datetime_utc_to_local(expiration_ts)
				if expiration_ts < now:
					is_expired = True
				expiration_ts = utilities.format_datetime(expiration_ts)
			store.append((
				str(campaign['id']),
				campaign['name'],
				(campaign['company']['name'] if campaign['company'] is not None else None),
				(campaign['campaignType']['name'] if campaign['campaignType'] is not None else None),
				"{0:,}".format(campaign['messages']['total']),
				campaign['user']['name'],
				created_ts,
				expiration_ts,
				(hlbg_color if is_expired else bg_color),
				(hlfg_color if is_expired else fg_color),
				(html.escape(campaign['description'], quote=True) if campaign['description'] else None)
			))
		self.gobjects['label_campaign_info'].set_text("Showing {0} of {1:,} Campaign{2}".format(
			len(self._tv_model_filter),
			len(self._tv_model),
			('' if len(self._tv_model) == 1 else 's')
		))
Example #12
0
	def load_campaigns(self):
		"""Load campaigns from the remote server and populate the :py:class:`Gtk.TreeView`."""
		treeview = self.gobjects['treeview_campaigns']
		store = treeview.get_model()
		if store == None:
			store = Gtk.ListStore(str, str, str, str)
			treeview.set_model(store)
		else:
			store.clear()
		for campaign in self.parent.rpc.remote_table('campaigns'):
			created_ts = utilities.datetime_utc_to_local(campaign.created)
			created_ts = utilities.format_datetime(created_ts)
			store.append([str(campaign.id), campaign.name, campaign.user_id, created_ts])
	def load_campaigns(self):
		"""Load campaigns from the remote server and populate the :py:class:`Gtk.TreeView`."""
		treeview = self.gobjects['treeview_campaigns']
		store = treeview.get_model()
		if store is None:
			store = Gtk.ListStore(str, str, str, str, str, str, str, str, str)
			treeview.set_model(store)
		else:
			store.clear()
		for campaign in self.application.rpc.remote_table('campaigns'):
			company = campaign.company
			if company:
				company = company.name
			created_ts = utilities.datetime_utc_to_local(campaign.created)
			created_ts = utilities.format_datetime(created_ts)
			campaign_type = campaign.campaign_type
			if campaign_type:
				campaign_type = campaign_type.name
			expiration_ts = campaign.expiration
			expiration_color = ColorHexCode.WHITE
			if expiration_ts is not None:
				expiration_ts = utilities.datetime_utc_to_local(campaign.expiration)
				if expiration_ts < datetime.datetime.now():
					expiration_color = ColorHexCode.LIGHT_YELLOW
				expiration_ts = utilities.format_datetime(expiration_ts)
			store.append((
				str(campaign.id),
				campaign.name,
				company,
				campaign_type,
				campaign.user_id,
				created_ts,
				expiration_ts,
				expiration_color,
				(campaign.description if campaign.description else None)
			))
		self.gobjects['label_campaign_info'].set_text("Showing {0:,} Campaign{1}".format(len(store), ('' if len(store) == 1 else 's')))
Example #14
0
def rfc2282_timestamp(dt=None, utc=False):
	"""
	Convert a :py:class:`datetime.datetime` instance into an :rfc:`2282`
	compliant timestamp suitable for use in MIME-encoded messages.

	:param dt: A time to use for the timestamp otherwise the current time is used.
	:type dt: :py:class:`datetime.datetime`
	:param utc: Whether to return the timestamp as a UTC offset or from the local timezone.
	:return: The timestamp.
	:rtype: str
	"""
	dt = dt or datetime.datetime.utcnow()
	# email.utils.formatdate wants the time to be in the local timezone
	dt = utilities.datetime_utc_to_local(dt)
	return email.utils.formatdate(time.mktime(dt.timetuple()), not utc)
Example #15
0
	def format_cell_data(self, cell_data):
		"""
		This method provides formatting to the individual cell values returned
		from the :py:meth:`.format_row_data` function. Values are converted into
		a format suitable for reading.

		:param cell: The value to format.
		:return: The formatted cell value.
		:rtype: str
		"""
		if isinstance(cell_data, datetime.datetime):
			cell_data = utilities.datetime_utc_to_local(cell_data)
			return utilities.format_datetime(cell_data)
		elif cell_data is None:
			return ''
		return str(cell_data)
Example #16
0
    def _load_graph(self, info_cache):
        # define the necessary colors
        color_bg = self.get_color('bg', ColorHexCode.WHITE)
        color_fg = self.get_color('fg', ColorHexCode.BLACK)
        color_line_bg = self.get_color('line_bg', ColorHexCode.WHITE)
        color_line_fg = self.get_color('line_fg', ColorHexCode.BLACK)
        visits = info_cache['visits']
        first_visits = [
            utilities.datetime_utc_to_local(visit.first_visit)
            for visit in visits
        ]

        ax = self.axes[0]
        ax.tick_params(axis='both',
                       which='both',
                       colors=color_fg,
                       top='off',
                       bottom='off')
        ax.set_axis_bgcolor(color_line_bg)
        ax.set_ylabel('Number of Visits',
                      color=self.get_color('fg', ColorHexCode.WHITE),
                      size=10)
        self._ax_hide_ticks(ax)
        self._ax_set_spine_color(ax, color_bg)
        if not len(first_visits):
            ax.set_yticks((0, ))
            ax.set_xticks((0, ))
            return

        first_visits.sort()
        ax.plot_date(first_visits,
                     range(1,
                           len(first_visits) + 1),
                     '-',
                     color=color_line_fg,
                     linewidth=6)
        self.figure.autofmt_xdate()
        self.figure.subplots_adjust(top=0.85,
                                    right=0.95,
                                    bottom=0.25,
                                    left=0.1)

        locator = dates.AutoDateLocator()
        ax.xaxis.set_major_locator(locator)
        ax.xaxis.set_major_formatter(dates.AutoDateFormatter(locator))
        return
Example #17
0
	def _set_defaults(self):
		"""
		Set any default values for widgets. Also load settings from the existing
		campaign if one was specified.
		"""
		calendar = self.gobjects['calendar_campaign_expiration']
		default_day = datetime.datetime.today() + datetime.timedelta(days=31)
		gui_utilities.gtk_calendar_set_pydate(calendar, default_day)

		if self.campaign_id is None:
			return
		campaign = self.application.get_graphql_campaign()

		# set entries
		self.gobjects['entry_campaign_name'].set_text(campaign['name'])
		self.gobjects['entry_validation_regex_username'].set_text(campaign['credentialRegexUsername'] or '')
		self.gobjects['entry_validation_regex_password'].set_text(campaign['credentialRegexPassword'] or '')
		self.gobjects['entry_validation_regex_mfa_token'].set_text(campaign['credentialRegexMfaToken'] or '')

		if campaign['description'] is not None:
			self.gobjects['entry_campaign_description'].set_text(campaign['description'])
		if campaign['campaignType'] is not None:
			combobox = self.gobjects['combobox_campaign_type']
			model = combobox.get_model()
			model_iter = gui_utilities.gtk_list_store_search(model, campaign['campaignType']['id'], column=0)
			if model_iter is not None:
				combobox.set_active_iter(model_iter)

		self.gobjects['checkbutton_alert_subscribe'].set_property('active', self.application.rpc('campaign/alerts/is_subscribed', self.campaign_id))
		self.gobjects['checkbutton_reject_after_credentials'].set_property('active', bool(campaign['maxCredentials']))

		if campaign['company'] is not None:
			self.gobjects['radiobutton_company_existing'].set_active(True)
			combobox = self.gobjects['combobox_company_existing']
			model = combobox.get_model()
			model_iter = gui_utilities.gtk_list_store_search(model, campaign['company']['id'], column=0)
			if model_iter is not None:
				combobox.set_active_iter(model_iter)

		if campaign['expiration'] is not None:
			expiration = utilities.datetime_utc_to_local(campaign['expiration'])
			self.gobjects['checkbutton_expire_campaign'].set_active(True)
			self._expiration_time.time = expiration.time()
			gui_utilities.gtk_calendar_set_pydate(self.gobjects['calendar_campaign_expiration'], expiration.date())
Example #18
0
    def _set_defaults(self):
        """
		Set any default values for widgets. Also load settings from the existing
		campaign if one was specified.
		"""
        calendar = self.gobjects["calendar_campaign_expiration"]
        default_day = datetime.datetime.today() + datetime.timedelta(days=31)
        gui_utilities.gtk_calendar_set_pydate(calendar, default_day)

        if self.campaign_id is None:
            return
        campaign = self.application.rpc.remote_table_row("campaigns", self.campaign_id, cache=True, refresh=True)

        self.gobjects["entry_campaign_name"].set_text(campaign.name)
        if campaign.description is not None:
            self.gobjects["entry_campaign_description"].set_text(campaign.description)
        if campaign.campaign_type_id is not None:
            combobox = self.gobjects["combobox_campaign_type"]
            model = combobox.get_model()
            model_iter = gui_utilities.gtk_list_store_search(model, campaign.campaign_type_id, column=0)
            if model_iter is not None:
                combobox.set_active_iter(model_iter)

        self.gobjects["checkbutton_alert_subscribe"].set_property(
            "active", self.application.rpc("campaign/alerts/is_subscribed", self.campaign_id)
        )
        self.gobjects["checkbutton_reject_after_credentials"].set_property("active", campaign.reject_after_credentials)

        if campaign.company_id is not None:
            self.gobjects["radiobutton_company_existing"].set_active(True)
            combobox = self.gobjects["combobox_company_existing"]
            model = combobox.get_model()
            model_iter = gui_utilities.gtk_list_store_search(model, campaign.company_id, column=0)
            if model_iter is not None:
                combobox.set_active_iter(model_iter)

        if campaign.expiration is not None:
            expiration = utilities.datetime_utc_to_local(campaign.expiration)
            self.gobjects["checkbutton_expire_campaign"].set_active(True)
            gui_utilities.gtk_calendar_set_pydate(self.gobjects["calendar_campaign_expiration"], expiration)
            self.gobjects["spinbutton_campaign_expiration_hour"].set_value(expiration.hour)
            self.gobjects["spinbutton_campaign_expiration_minute"].set_value(expiration.minute)
Example #19
0
	def _load_graph(self, info_cache):
		# define the necessary colors
		color_bg = self.get_color('bg', ColorHexCode.WHITE)
		color_fg = self.get_color('fg', ColorHexCode.BLACK)
		color_line_bg = self.get_color('line_bg', ColorHexCode.WHITE)
		color_line_fg = self.get_color('line_fg', ColorHexCode.BLACK)
		visits = info_cache['visits']['edges']
		first_seen_timestamps = [utilities.datetime_utc_to_local(visit['node']['firstSeen']) for visit in visits]

		ax = self.axes[0]
		ax.tick_params(
			axis='both',
			which='both',
			colors=color_fg,
			top='off',
			bottom='off'
		)
		ax.set_facecolor(color_line_bg)
		ax.set_ylabel('Number of Visits', color=self.get_color('fg', ColorHexCode.WHITE), size=10)
		self._ax_hide_ticks(ax)
		self._ax_set_spine_color(ax, color_bg)
		if not len(first_seen_timestamps):
			ax.set_yticks((0,))
			ax.set_xticks((0,))
			return

		first_seen_timestamps.sort()
		ax.plot_date(
			first_seen_timestamps,
			range(1, len(first_seen_timestamps) + 1),
			'-',
			color=color_line_fg,
			linewidth=6
		)
		self.figure.autofmt_xdate()
		self.figure.subplots_adjust(top=0.85, right=0.95, bottom=0.25, left=0.1)

		locator = dates.AutoDateLocator()
		ax.xaxis.set_major_locator(locator)
		ax.xaxis.set_major_formatter(dates.AutoDateFormatter(locator))
		return
Example #20
0
 def __async_rpc_cb_populate_url_info(self, hostname, path, results):
     self._cache_site_template[(hostname, path)] = results
     template = results['siteTemplate']
     if template is None:
         return
     self.gobjects['label_url_info_created'].set_text(
         utilities.format_datetime(
             utilities.datetime_utc_to_local(template['created'])))
     metadata = template['metadata']
     if metadata is None:
         return
     self.gobjects['label_url_info_title'].set_text(metadata['title'])
     self.gobjects['label_url_info_authors'].set_text('\n'.join(
         metadata['authors']))
     self.gobjects['label_url_info_description'].set_text(
         metadata['description'])
     if metadata['referenceUrls']:
         gui_utilities.gtk_listbox_populate_urls(
             self.gobjects['listbox_url_info_references'],
             metadata['referenceUrls'],
             signals={'activate-link': self.signal_label_activate_link})
     gui_utilities.gtk_listbox_populate_labels(
         self.gobjects['listbox_url_info_classifiers'],
         metadata['classifiers'])
Example #21
0
	def format_cell_data(self, cell_data, encoding='utf-8'):
		"""
		This method provides formatting to the individual cell values returned
		from the :py:meth:`.format_row_data` function. Values are converted into
		a format suitable for reading.

		:param cell: The value to format.
		:param str encoding: The encoding to use to coerce the return value into a unicode string.
		:return: The formatted cell value.
		:rtype: str
		"""
		if isinstance(cell_data, datetime.datetime):
			cell_data = utilities.datetime_utc_to_local(cell_data)
			return utilities.format_datetime(cell_data, encoding=encoding)

		if cell_data is None:
			cell_data = ''
		elif isinstance(cell_data, int):
			cell_data = str(cell_data)

		# ensure that the return value is a unicode string
		if isinstance(cell_data, bytes):
			cell_data = cell_data.decode(encoding)
		return cell_data
Example #22
0
    def format_cell_data(self, cell_data, encoding='utf-8'):
        """
		This method provides formatting to the individual cell values returned
		from the :py:meth:`.format_row_data` function. Values are converted into
		a format suitable for reading.

		:param cell: The value to format.
		:param str encoding: The encoding to use to coerce the return value into a unicode string.
		:return: The formatted cell value.
		:rtype: str
		"""
        if isinstance(cell_data, datetime.datetime):
            cell_data = utilities.datetime_utc_to_local(cell_data)
            return utilities.format_datetime(cell_data, encoding=encoding)

        if cell_data is None:
            cell_data = ''
        elif isinstance(cell_data, int):
            cell_data = str(cell_data)

        # ensure that the return value is a unicode string
        if isinstance(cell_data, bytes):
            cell_data = cell_data.decode(encoding)
        return cell_data
Example #23
0
    def load_campaigns(self):
        """Load campaigns from the remote server and populate the :py:class:`Gtk.TreeView`."""
        store = self._tv_model
        store.clear()
        style_context = self.dialog.get_style_context()
        bg_color = gui_utilities.gtk_style_context_get_color(
            style_context, 'theme_color_tv_bg', default=ColorHexCode.WHITE)
        fg_color = gui_utilities.gtk_style_context_get_color(
            style_context, 'theme_color_tv_fg', default=ColorHexCode.BLACK)
        hlbg_color = gui_utilities.gtk_style_context_get_color(
            style_context,
            'theme_color_tv_hlbg',
            default=ColorHexCode.LIGHT_YELLOW)
        hlfg_color = gui_utilities.gtk_style_context_get_color(
            style_context, 'theme_color_tv_hlfg', default=ColorHexCode.BLACK)
        now = datetime.datetime.now()
        campaigns_query = """\
		{
			db {
				campaigns {
					edges {
						node {
							id,
							name,
							description,
							company {
								name
							},
							campaignType {
								name
							},
							messages {
								total
							},
							user {
								id
							},
							created,
							expiration
						}
					}
				}
			}
		}
		"""
        campaigns = self.application.rpc.graphql(campaigns_query)
        for campaign in campaigns['db']['campaigns']['edges']:
            campaign = campaign['node']
            created_ts = utilities.datetime_utc_to_local(campaign['created'])
            created_ts = utilities.format_datetime(created_ts)
            expiration_ts = campaign['expiration']
            is_expired = False
            if expiration_ts is not None:
                expiration_ts = utilities.datetime_utc_to_local(expiration_ts)
                if expiration_ts < now:
                    is_expired = True
                expiration_ts = utilities.format_datetime(expiration_ts)
            store.append((str(campaign['id']), campaign['name'],
                          (campaign['company']['name']
                           if campaign['company'] is not None else None),
                          (campaign['campaignType']['name']
                           if campaign['campaignType'] is not None else None),
                          "{0:,}".format(campaign['messages']['total']),
                          campaign['user']['id'], created_ts, expiration_ts,
                          (hlbg_color if is_expired else bg_color),
                          (hlfg_color if is_expired else fg_color),
                          (html.escape(campaign['description'], quote=True)
                           if campaign['description'] else None)))
        self.gobjects['label_campaign_info'].set_text(
            "Showing {0} of {1:,} Campaign{2}".format(
                len(self._tv_model_filter), len(self._tv_model),
                ('' if len(self._tv_model) == 1 else 's')))
Example #24
0
def _dt_field(value):
    return value if value is None else utilities.datetime_utc_to_local(value)