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
			))
Esempio n. 2
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
			))
 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,
             )
         )
Esempio n. 4
0
	def create_model_entry(self, path, parent):
		"""
		Creates a row in the directory model containing a file or directory with
		its respective name, icon, size, date, and permissions.

		:param str path: The filepath of the folder the file is in.
		:param parent: A TreeIter object pointing to the parent node.
		:param str name: The name of the file.
		"""
		basename = self.path_mod.basename(path)
		try:
			stat_info = self.stat(path)
		except (OSError, IOError):
			icon = Gtk.IconTheme.get_default().load_icon('emblem-unreadable', 13, 0)
			self._tv_model.append(parent, [basename, icon, path, None, None, None, None])
			return
		perm = self._format_perm(stat_info.st_mode)
		date = datetime.datetime.fromtimestamp(stat_info.st_mtime)
		date_modified = utilities.format_datetime(date)
		if stat.S_ISDIR(stat_info.st_mode):
			icon = Gtk.IconTheme.get_default().load_icon('folder', 20, 0)
			current = self._tv_model.append(parent, (basename, icon, path, perm, None, -1, date_modified))
			self._tv_model.append(current, [None, None, None, None, None, None, None])
		else:
			file_size = self.get_file_size(path)
			hr_file_size = boltons.strutils.bytes2human(file_size)
			icon = Gtk.IconTheme.get_default().load_icon('text-x-preview', 12.5, 0)
			self._tv_model.append(parent, (basename, icon, path, perm, hr_file_size, file_size, date_modified))
Esempio n. 5
0
    def create_model_entry(self, path, parent):
        """
		Creates a row in the directory model containing a file or directory with
		its respective name, icon, size, date, and permissions.

		:param str path: The filepath of the folder the file is in.
		:param parent: A TreeIter object pointing to the parent node.
		:param str name: The name of the file.
		"""
        basename = self.path_mod.basename(path)
        try:
            stat_info = self.stat(path)
        except (OSError, IOError):
            icon = Gtk.IconTheme.get_default().load_icon(
                'emblem-unreadable', 13, 0)
            self._tv_model.append(
                parent, [basename, icon, path, None, None, None, None])
            return
        perm = self._format_perm(stat_info.st_mode)
        date = datetime.datetime.fromtimestamp(stat_info.st_mtime)
        date_modified = utilities.format_datetime(date)
        if stat.S_ISDIR(stat_info.st_mode):
            icon = Gtk.IconTheme.get_default().load_icon('folder', 20, 0)
            current = self._tv_model.append(
                parent, (basename, icon, path, perm, None, -1, date_modified))
            self._tv_model.append(current,
                                  [None, None, None, None, None, None, None])
        else:
            file_size = self.get_file_size(path)
            hr_file_size = boltons.strutils.bytes2human(file_size)
            icon = Gtk.IconTheme.get_default().load_icon(
                'text-x-preview', 12.5, 0)
            self._tv_model.append(parent,
                                  (basename, icon, path, perm, hr_file_size,
                                   file_size, date_modified))
 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()
     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')))
Esempio n. 8
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')
		))
Esempio n. 10
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'])
			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')
		))
Esempio n. 11
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')))
Esempio n. 13
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)
Esempio n. 14
0
def liststore_export(store,
                     columns,
                     cb_write,
                     cb_write_args,
                     row_offset=0,
                     write_columns=True):
    """
	A function to facilitate writing values from a list store to an arbitrary
	callback for exporting to different formats. The callback will be called
	with the row number, the column values and the additional arguments
	specified in *\\*cb_write_args*.

	.. code-block:: python

	  cb_write(row, column_values, *cb_write_args).

	:param store: The store to export the information from.
	:type store: :py:class:`Gtk.ListStore`
	:param dict columns: A dictionary mapping store column ids to the value names.
	:param function cb_write: The callback function to be called for each row of data.
	:param tuple cb_write_args: Additional arguments to pass to *cb_write*.
	:param int row_offset: A modifier value to add to the row numbers passed to *cb_write*.
	:param bool write_columns: Write the column names to the export.
	:return: The number of rows that were written.
	:rtype: int
	"""
    column_names, store_columns = _split_columns(columns)
    if write_columns:
        cb_write(0, column_names, *cb_write_args)

    store_iter = store.get_iter_first()
    rows_written = 0
    while store_iter:
        row = collections.deque()
        for column in store_columns:
            value = store.get_value(store_iter, column)
            if isinstance(value, datetime.datetime):
                value = utilities.format_datetime(value)
            row.append(value)
        cb_write(rows_written + 1 + row_offset, row, *cb_write_args)
        rows_written += 1
        store_iter = store.iter_next(store_iter)
    return rows_written
Esempio n. 15
0
def liststore_export(store, columns, cb_write, cb_write_args, row_offset=0, write_columns=True):
	"""
	A function to facilitate writing values from a list store to an arbitrary
	callback for exporting to different formats. The callback will be called
	with the row number, the column values and the additional arguments
	specified in *\\*cb_write_args*.

	.. code-block:: python

	  cb_write(row, column_values, *cb_write_args).

	:param store: The store to export the information from.
	:type store: :py:class:`Gtk.ListStore`
	:param dict columns: A dictionary mapping store column ids to the value names.
	:param function cb_write: The callback function to be called for each row of data.
	:param tuple cb_write_args: Additional arguments to pass to *cb_write*.
	:param int row_offset: A modifier value to add to the row numbers passed to *cb_write*.
	:param bool write_columns: Write the column names to the export.
	:return: The number of rows that were written.
	:rtype: int
	"""
	column_names, store_columns = _split_columns(columns)
	if write_columns:
		cb_write(0, column_names, *cb_write_args)

	store_iter = store.get_iter_first()
	rows_written = 0
	while store_iter:
		row = collections.deque()
		for column in store_columns:
			value = store.get_value(store_iter, column)
			if isinstance(value, datetime.datetime):
				value = utilities.format_datetime(value)
			row.append(value)
		cb_write(rows_written + 1 + row_offset, row, *cb_write_args)
		rows_written += 1
		store_iter = store.iter_next(store_iter)
	return rows_written
Esempio n. 16
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
Esempio n. 17
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'])
Esempio n. 18
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