Esempio n. 1
0
def _get_update_status():

	dbcfg = gmCfg.cCfgSQL()
	url = dbcfg.get2 (
		option = 'horstspace.update.url',
		workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
		bias = 'workplace',
		default = 'http://www.gnumed.de/downloads/gnumed-versions.txt'
	)
	consider_latest_branch = bool(dbcfg.get2 (
		option = 'horstspace.update.consider_latest_branch',
		workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
		bias = 'workplace',
		default = True
	))

	_cfg = gmCfg2.gmCfgData()
	update_found, msg = gmNetworkTools.check_for_update (
		url = url,
		current_branch = _cfg.get(option = 'client_branch'),
		current_version = _cfg.get(option = 'client_version'),
		consider_latest_branch = consider_latest_branch
	)

	return update_found, msg
Esempio n. 2
0
    def __init_ui(self):
        cfg = gmCfg2.gmCfgData()
        if cfg.get(option='slave'):
            self._TCTRL_patient_selector.SetEditable(0)
            self._TCTRL_patient_selector.SetToolTip(None)

        if sys.platform == 'darwin':
            _log.debug('adjusting font size on Mac for top panel parts')
            for ctrl in [
                    self._TCTRL_patient_selector, self._LBL_age,
                    self._LBL_allergies, self._TCTRL_allergies
            ]:
                curr_font = ctrl.GetFont()
                mac_font = wx.Font(curr_font.GetNativeFontInfo())
                mac_font.SetPointSize(pointSize=int(curr_font.GetPointSize() /
                                                    0.8))
                ctrl.SetFont(mac_font)

        # get panel to use
        dbcfg = gmCfg.cCfgSQL()
        pk_panel = dbcfg.get2(
            option='horstspace.top_panel.lab_panel',
            workplace=gmPraxis.gmCurrentPraxisBranch().active_workplace,
            bias='user')
        if pk_panel is None:
            self.__lab_panel = None
        else:
            self.__lab_panel = gmPathLab.cTestPanel(aPK_obj=pk_panel)
Esempio n. 3
0
	def __init_ui(self):
		cfg = gmCfg2.gmCfgData()
		if cfg.get(option = 'slave'):
			self._TCTRL_patient_selector.SetEditable(0)
			self._TCTRL_patient_selector.SetToolTip(None)

		if sys.platform == u'darwin':
			_log.debug('adjusting font size on Mac for top panel parts')
			for ctrl in [self._TCTRL_patient_selector, self._LBL_age, self._LBL_allergies, self._TCTRL_allergies]:
				curr_font = ctrl.GetFont()
				mac_font = wx.FontFromNativeInfo(curr_font.NativeFontInfo)
				mac_font.SetPointSize(pointSize = int(curr_font.GetPointSize() / 0.8))
				ctrl.SetFont(mac_font)

		# get panel to use
		dbcfg = gmCfg.cCfgSQL()
		pk_panel = dbcfg.get2 (
			option = u'horstspace.top_panel.lab_panel',
			workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
			bias = 'user'
		)
		if pk_panel is None:
			self.__lab_panel = None
		else:
			self.__lab_panel = gmPathLab.cTestPanel(aPK_obj = pk_panel)
Esempio n. 4
0
def guess_ext_by_mimetype(mimetype=''):
	"""Return file extension based on what the OS thinks a file of this mimetype should end in."""

	# ask system first
	ext = mimetypes.guess_extension(mimetype)
	if ext is not None:
		_log.debug('<%s>: %s' % (mimetype, ext))
		return ext

	_log.error("<%s>: no suitable file extension known to the OS" % mimetype)

	# try to help the OS a bit
	cfg = gmCfg2.gmCfgData()
	ext = cfg.get (
		group = 'extensions',
		option = mimetype,
		source_order = [('user-mime', 'return'), ('system-mime', 'return')]
	)

	if ext is not None:
		_log.debug('<%s>: %s (%s)' % (mimetype, ext, candidate))
		return ext

	_log.error("<%s>: no suitable file extension found in config files" % mimetype)

	return ext
Esempio n. 5
0
def guess_ext_by_mimetype(mimetype=''):
	"""Return file extension based on what the OS thinks a file of this mimetype should end in."""

	# ask system first
	ext = mimetypes.guess_extension(mimetype)
	if ext is not None:
		_log.debug('<%s>: *.%s' % (mimetype, ext))
		return ext

	_log.error("<%s>: no suitable file extension known to the OS" % mimetype)

	# try to help the OS a bit
	cfg = gmCfg2.gmCfgData()
	ext = cfg.get (
		group = 'extensions',
		option = mimetype,
		source_order = [('user-mime', 'return'), ('system-mime', 'return')]
	)

	if ext is not None:
		_log.debug('<%s>: *.%s (%s)' % (mimetype, ext, candidate))
		return ext

	_log.error("<%s>: no suitable file extension found in config files" % mimetype)

	return ext
Esempio n. 6
0
def check_for_updates():

	dbcfg = gmCfg.cCfgSQL()

	url = dbcfg.get2 (
		option = u'horstspace.update.url',
		workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
		bias = 'workplace',
		default = u'http://www.gnumed.de/downloads/gnumed-versions.txt'
	)

	consider_latest_branch = bool(dbcfg.get2 (
		option = u'horstspace.update.consider_latest_branch',
		workplace = gmPraxis.gmCurrentPraxisBranch().active_workplace,
		bias = 'workplace',
		default = True
	))

	_cfg = gmCfg2.gmCfgData()

	found, msg = gmNetworkTools.check_for_update (
		url = url,
		current_branch = _cfg.get(option = 'client_branch'),
		current_version = _cfg.get(option = 'client_version'),
		consider_latest_branch = consider_latest_branch
	)

	if found is False:
		gmDispatcher.send(signal = 'statustext', msg = _('Your client (%s) is up to date.') % _cfg.get(option = 'client_version'))
		return

	gmGuiHelpers.gm_show_info (
		msg,
		_('Checking for client updates')
	)
Esempio n. 7
0
def setup_cli():
	from Gnumed.pycommon import gmCfg2

	global _cfg
	_cfg = gmCfg2.gmCfgData()
	_cfg.add_cli (
		short_options = _known_short_options,
		long_options = _known_long_options
	)

	val = _cfg.get(option = '--debug', source_order = [('cli', 'return')])
	if val is None:
		val = False
	_cfg.set_option (
		option = 'debug',
		value = val
	)

	val = _cfg.get(option = '--slave', source_order = [('cli', 'return')])
	if val is None:
		val = False
	_cfg.set_option (
		option = 'slave',
		value = val
	)

	val = _cfg.get(option = '--skip-update-check', source_order = [('cli', 'return')])
	if val is None:
		val = False
	_cfg.set_option (
		option = 'skip-update-check',
		value = val
	)

	val = _cfg.get(option = '--hipaa', source_order = [('cli', 'return')])
	if val is None:
		val = False
	_cfg.set_option (
		option = 'hipaa',
		value = val
	)

	val = _cfg.get(option = '--local-import', source_order = [('cli', 'return')])
	if val is None:
		val = False
	_cfg.set_option (
		option = 'local-import',
		value = val
	)

	_cfg.set_option (
		option = 'client_version',
		value = current_client_version
	)

	_cfg.set_option (
		option = 'client_branch',
		value = current_client_branch
	)
Esempio n. 8
0
def setup_cli():
	from Gnumed.pycommon import gmCfg2

	global _cfg
	_cfg = gmCfg2.gmCfgData()
	_cfg.add_cli (
		short_options = _known_short_options,
		long_options = _known_long_options
	)

	val = _cfg.get(option = '--debug', source_order = [('cli', 'return')])
	if val is None:
		val = False
	_cfg.set_option (
		option = 'debug',
		value = val
	)

	val = _cfg.get(option = '--slave', source_order = [('cli', 'return')])
	if val is None:
		val = False
	_cfg.set_option (
		option = 'slave',
		value = val
	)

	val = _cfg.get(option = '--skip-update-check', source_order = [('cli', 'return')])
	if val is None:
		val = False
	_cfg.set_option (
		option = 'skip-update-check',
		value = val
	)

	val = _cfg.get(option = '--hipaa', source_order = [('cli', 'return')])
	if val is None:
		val = False
	_cfg.set_option (
		option = 'hipaa',
		value = val
	)

	val = _cfg.get(option = '--local-import', source_order = [('cli', 'return')])
	if val is None:
		val = False
	_cfg.set_option (
		option = 'local-import',
		value = val
	)

	_cfg.set_option (
		option = 'client_version',
		value = current_client_version
	)

	_cfg.set_option (
		option = 'client_branch',
		value = current_client_branch
	)
def handle_uncaught_exception_wx(t, v, tb):

	_log2.debug('unhandled exception caught:', exc_info = (t, v, tb))

	if __handle_ctrl_c(t, v, tb):
		return

	if __handle_exceptions_on_shutdown(t, v, tb):
		return

	if __ignore_dead_objects_from_async(t, v, tb):
		return

	if __handle_import_error(t, v, tb):
		return

	if __handle_access_violation(t, v, tb):
		return

	# other exceptions
	_cfg = gmCfg2.gmCfgData()
	if _cfg.get(option = 'debug') is False:
		_log2.error('enabling debug mode')
		_cfg.set_option(option = 'debug', value = True)
		root_logger = logging.getLogger()
		root_logger.setLevel(logging.DEBUG)
		_log2.debug('unhandled exception caught:', exc_info = (t, v, tb))

	if __handle_lost_db_connection(t, v, tb):
		return

	gmLog2.log_stack_trace(None, t, v, tb)

	# only do this here or else we can invalidate the stack trace
	# by Windows throwing an exception ... |-(
	# careful: MSW does reference counting on Begin/End* :-(
	wx.EndBusyCursor()

	name = os.path.basename(_logfile_name)
	name, ext = os.path.splitext(name)
	new_name = os.path.expanduser(os.path.join (
		'~',
		'.gnumed',
		'error_logs',
		'%s_%s%s' % (name, pyDT.datetime.now().strftime('%Y-%m-%d_%H-%M-%S'), ext)
	))

	dlg = cUnhandledExceptionDlg(parent = None, id = -1, exception = (t, v, tb), logfile = new_name)
	dlg.ShowModal()
	comment = dlg._TCTRL_comment.GetValue()
	dlg.Destroy()
	if (comment is not None) and (comment.strip() != u''):
		_log2.error(u'user comment: %s', comment.strip())

	_log2.warning('syncing log file for backup to [%s]', new_name)
	gmLog2.flush()
	# keep a copy around
	shutil.copy2(_logfile_name, new_name)
Esempio n. 10
0
def handle_uncaught_exception_wx(t, v, tb):

    _log2.debug("unhandled exception caught:", exc_info=(t, v, tb))

    if __handle_ctrl_c(t, v, tb):
        return

    if __handle_exceptions_on_shutdown(t, v, tb):
        return

    if __ignore_dead_objects_from_async(t, v, tb):
        return

    if __handle_import_error(t, v, tb):
        return

    if __handle_access_violation(t, v, tb):
        return

        # other exceptions
    _cfg = gmCfg2.gmCfgData()
    if _cfg.get(option="debug") is False:
        _log2.error("enabling debug mode")
        _cfg.set_option(option="debug", value=True)
        root_logger = logging.getLogger()
        root_logger.setLevel(logging.DEBUG)
        _log2.debug("unhandled exception caught:", exc_info=(t, v, tb))

    if __handle_lost_db_connection(t, v, tb):
        return

    gmLog2.log_stack_trace(None, t, v, tb)

    # only do this here or else we can invalidate the stack trace
    # by Windows throwing an exception ... |-(
    # careful: MSW does reference counting on Begin/End* :-(
    wx.EndBusyCursor()

    name = os.path.basename(_logfile_name)
    name, ext = os.path.splitext(name)
    new_name = os.path.expanduser(
        os.path.join(
            "~", ".gnumed", "error_logs", "%s_%s%s" % (name, pyDT.datetime.now().strftime("%Y-%m-%d_%H-%M-%S"), ext)
        )
    )

    dlg = cUnhandledExceptionDlg(parent=None, id=-1, exception=(t, v, tb), logfile=new_name)
    dlg.ShowModal()
    comment = dlg._TCTRL_comment.GetValue()
    dlg.Destroy()
    if (comment is not None) and (comment.strip() != u""):
        _log2.error(u"user comment: %s", comment.strip())

    _log2.warning("syncing log file for backup to [%s]", new_name)
    gmLog2.flush()
    # keep a copy around
    shutil.copy2(_logfile_name, new_name)
Esempio n. 11
0
def _signal_update_status(status):

	update_found, msg = status
	if update_found is False:
		_cfg = gmCfg2.gmCfgData()
		gmDispatcher.send(signal = 'statustext', msg = _('Your client (%s) is up to date.') % _cfg.get(option = 'client_version'))
		return

	gmGuiHelpers.gm_show_info(msg, _('Checking for client updates'))
Esempio n. 12
0
def _signal_update_status(status):

	update_found, msg = status
	if update_found is False:
		_cfg = gmCfg2.gmCfgData()
		gmDispatcher.send(signal = 'statustext', msg = _('Your client (%s) is up to date.') % _cfg.get(option = 'client_version'))
		return

	gmGuiHelpers.gm_show_info (
		msg,
		_('Checking for client updates')
	)
Esempio n. 13
0
    def __init_ui(self):
        cfg = gmCfg2.gmCfgData()
        if cfg.get(option='slave'):
            self._TCTRL_patient_selector.SetEditable(0)
            self._TCTRL_patient_selector.SetToolTip(None)

        if sys.platform == 'darwin':
            _log.debug('adjusting font size on Mac for top panel parts')
            for ctrl in [
                    self._TCTRL_patient_selector, self._LBL_age,
                    self._LBL_allergies, self._TCTRL_allergies
            ]:
                curr_font = ctrl.GetFont()
                mac_font = wx.Font(curr_font.GetNativeFontInfo())
                mac_font.SetPointSize(pointSize=int(curr_font.GetPointSize() /
                                                    0.8))
                ctrl.SetFont(mac_font)

        self.__lab_panel = self.__get_lab_panel()
Esempio n. 14
0
	def print_forms():
		# anything to do ?
		files2print = []
		form_names = []
		for form in forms:
			files2print.extend(form.final_output_filenames)
			form_names.append('%s (%s)' % (form.template['name_long'], form.template['external_version']))
		if len(files2print) == 0:
			return True
		# print
		_cfg = gmCfg2.gmCfgData()
		printed = gmPrinting.print_files(filenames = files2print, jobtype = jobtype, verbose = _cfg.get(option = 'debug'))
		if not printed:
			gmGuiHelpers.gm_show_error (
				aMessage = _('Error printing documents.'),
				aTitle = _('Printing [%s]') % jobtype
			)
			return False
		soap_lines.append(_('Printed: %s') % ', '.join(form_names))
		return True
Esempio n. 15
0
 def print_forms():
     # anything to do ?
     files2print = []
     form_names = []
     for form in forms:
         files2print.extend(form.final_output_filenames)
         form_names.append('%s (%s)' % (form.template['name_long'],
                                        form.template['external_version']))
     if len(files2print) == 0:
         return True
     # print
     _cfg = gmCfg2.gmCfgData()
     printed = gmPrinting.print_files(filenames=files2print,
                                      jobtype=jobtype,
                                      verbose=_cfg.get(option='debug'))
     if not printed:
         gmGuiHelpers.gm_show_error(aMessage=_('Error printing documents.'),
                                    aTitle=_('Printing [%s]') % jobtype)
         return False
     soap_lines.append(_('Printed: %s') % ', '.join(form_names))
     return True
Esempio n. 16
0
def regenerate_generic_vaccines():

	dbo_conn = gmAuthWidgets.get_dbowner_connection(procedure = _('Regenerating generic vaccines'))
	if dbo_conn is None:
		return False

	wx.BeginBusyCursor()
	_cfg = gmCfg2.gmCfgData()
	sql_script = gmVaccination.write_generic_vaccine_sql (
		'client-%s' % _cfg.get(option = 'client_version'),
		include_indications_mapping = False
	)
	_log.debug('regenerating generic vaccines, SQL script: %s', sql_script)
	if not gmPG2.run_sql_script(sql_script, conn = dbo_conn):
		wx.EndBusyCursor()
		gmGuiHelpers.gm_show_warning (
			aMessage = _('Error regenerating generic vaccines.\n\nSee [%s]') % sql_script,
			aTitle = _('Regenerating generic vaccines')
		)
		return False

	gmDispatcher.send(signal = 'statustext', msg = _('Successfully regenerated generic vaccines ...'), beep = False)
	wx.EndBusyCursor()
	return True
Esempio n. 17
0
def regenerate_generic_vaccines():

	dbo_conn = gmAuthWidgets.get_dbowner_connection(procedure = _('Regenerating generic vaccines'))
	if dbo_conn is None:
		return False

	wx.BeginBusyCursor()
	_cfg = gmCfg2.gmCfgData()
	sql_script = gmVaccination.write_generic_vaccine_sql (
		'client-%s' % _cfg.get(option = 'client_version'),
		include_indications_mapping = False
	)
	_log.debug('regenerating generic vaccines, SQL script: %s', sql_script)
	if not gmPG2.run_sql_script(sql_script, conn = dbo_conn):
		wx.EndBusyCursor()
		gmGuiHelpers.gm_show_warning (
			aMessage = _('Error regenerating generic vaccines.\n\nSee [%s]') % sql_script,
			aTitle = _('Regenerating generic vaccines')
		)
		return False

	gmDispatcher.send(signal = 'statustext', msg = _('Successfully regenerated generic vaccines ...'), beep = False)
	wx.EndBusyCursor()
	return True
Esempio n. 18
0
import io
import urllib.parse

if __name__ == '__main__':
    sys.path.insert(0, '../../')
from Gnumed.pycommon import gmPG2
from Gnumed.pycommon import gmTools
from Gnumed.pycommon import gmBorg
from Gnumed.pycommon import gmCfg2
from Gnumed.pycommon import gmHooks
from Gnumed.pycommon import gmBusinessDBObject

from Gnumed.business import gmOrganization

_log = logging.getLogger('gm.praxis')
_cfg = gmCfg2.gmCfgData()


#============================================================
def delete_workplace(workplace=None, delete_config=False, conn=None):

    args = {'wp': workplace}

    # delete workplace itself (plugin load list, that is)
    queries = [{
        'cmd': """
delete from cfg.cfg_item
where
	fk_template = (
		select pk
		from cfg.cfg_template
Esempio n. 19
0
    def export(self, base_dir=None, items=None, expand_compressed=False):

        if items is None:
            items = self.items

        if len(items) == 0:
            return None

        media_base_dir = base_dir

        from Gnumed.business.gmPerson import cPatient
        pat = cPatient(aPK_obj=self.__pk_identity)
        if media_base_dir is None:
            media_base_dir = gmTools.mk_sandbox_dir(prefix='exp-%s-' %
                                                    pat.subdir_name)
        _log.debug('patient media base dir: %s', media_base_dir)

        doc_dir = os.path.join(media_base_dir, r'documents')
        if os.path.isdir(doc_dir):
            index_existing_docs = True
        else:
            index_existing_docs = False
            gmTools.mkdir(doc_dir)

        _html_start_data = {
            'html_title_header':
            _('Patient data for'),
            'html_title_patient':
            gmTools.html_escape_string(
                pat.get_description_gender(with_nickname=False) + ', ' +
                _('born') + ' ' + pat.get_formatted_dob('%Y %B %d')),
            'title':
            _('Patient data export'),
            'pat_name':
            gmTools.html_escape_string(
                pat.get_description_gender(with_nickname=False)),
            'pat_dob':
            gmTools.html_escape_string(
                _('born') + ' ' + pat.get_formatted_dob('%Y %B %d')),
            'mugshot_url':
            'documents/no-such-file.png',
            'mugshot_alt':
            _('no patient photograph available'),
            'mugshot_title':
            '',
            'docs_title':
            _('Documents'),
            'browse_root':
            _('browse storage medium'),
            'browse_docs':
            _('browse documents area'),
            'browse_dicomdir':
            '',
            'run_dicom_viewer':
            ''
        }

        mugshot = pat.document_folder.latest_mugshot
        if mugshot is not None:
            _html_start_data['mugshot_url'] = mugshot.save_to_file(
                directory=doc_dir, adjust_extension=True)
            _html_start_data['mugshot_alt'] = _(
                'patient photograph from %s') % gmDateTime.pydt_strftime(
                    mugshot['date_generated'], '%B %Y')
            _html_start_data['mugshot_title'] = gmDateTime.pydt_strftime(
                mugshot['date_generated'], '%B %Y')

        if 'DICOMDIR' in os.listdir(media_base_dir):
            _html_start_data[
                'browse_dicomdir'] = '<li><a href="./DICOMDIR">%s</a></li>' % _(
                    'show DICOMDIR file')
            # copy DWV into target dir
            dwv_src_dir = os.path.join(gmTools.gmPaths().local_base_dir,
                                       'dwv4export')
            if not os.path.isdir(dwv_src_dir):
                dwv_src_dir = os.path.join(
                    gmTools.gmPaths().system_app_data_dir, 'dwv4export')
            if os.path.isdir(dwv_src_dir):
                dwv_target_dir = os.path.join(media_base_dir, 'dwv')
                gmTools.rmdir(dwv_target_dir)
                try:
                    shutil.copytree(dwv_src_dir, dwv_target_dir)
                    _html_start_data[
                        'run_dicom_viewer'] = '<li><a href="./dwv/viewers/mobile-local/index.html">%s</a></li>' % _(
                            'run Radiology Images (DICOM) Viewer')
                except (shutil.Error, OSError):
                    _log.exception('cannot include DWV, skipping')

        # index.html
        # - header
        idx_fname = os.path.join(media_base_dir, 'index.html')
        idx_file = io.open(idx_fname, mode='wt', encoding='utf8')
        idx_file.write(_html_start % _html_start_data)
        # - middle (side effect ! -> exports items into files ...)
        existing_docs = os.listdir(
            doc_dir
        )  # get them now, or else we will include the to-be-exported items
        # - export items
        for item in items:
            item_path = item.save_to_file(directory=doc_dir)
            item_fname = os.path.split(item_path)[1]
            idx_file.write(
                _html_list_item %
                (item_fname, gmTools.html_escape_string(item['description'])))
        # - preexisting documents
        for doc_fname in existing_docs:
            idx_file.write(
                _html_list_item %
                (doc_fname,
                 gmTools.html_escape_string(_('other: %s') % doc_fname)))
        # - footer
        _cfg = gmCfg2.gmCfgData()
        from Gnumed.business.gmPraxis import gmCurrentPraxisBranch
        prax = gmCurrentPraxisBranch()
        lines = []
        adr = prax.branch.org_unit.address
        if adr is not None:
            lines.extend(adr.format())
        for comm in prax.branch.org_unit.comm_channels:
            if comm['is_confidential'] is True:
                continue
            lines.append('%s: %s' % (comm['l10n_comm_type'], comm['url']))
        adr = ''
        if len(lines) > 0:
            adr = gmTools.html_escape_string('\n'.join(lines),
                                             replace_eol=True,
                                             keep_visual_eol=True)
        _html_end_data = {
            'branch':
            gmTools.html_escape_string(prax['branch']),
            'praxis':
            gmTools.html_escape_string(prax['praxis']),
            'date':
            gmTools.html_escape_string(
                gmDateTime.pydt_strftime(gmDateTime.pydt_now_here(),
                                         format='%Y %B %d')),
            'gm_ver':
            gmTools.html_escape_string(_cfg.get(option='client_version')),
            #'gm_ver': 'git HEAD',				# for testing
            'adr':
            adr
        }
        idx_file.write(_html_end % _html_end_data)
        idx_file.close()

        # start.html (just a copy of index.html, really ;-)
        start_fname = os.path.join(media_base_dir, 'start.html')
        try:
            shutil.copy2(idx_fname, start_fname)
        except Exception:
            _log.exception('cannot copy %s to %s', idx_fname, start_fname)

        # autorun.inf
        autorun_dict = {}
        autorun_dict['label'] = self._compute_autorun_inf_label(pat)
        autorun_dict['action'] = _('Browse patient data')
        autorun_dict['icon'] = ''
        media_icon_kwd = '$$gnumed_patient_media_export_icon'
        media_icon_kwd_exp = gmKeywordExpansion.get_expansion(
            keyword=media_icon_kwd, textual_only=False, binary_only=True)
        icon_tmp_file = media_icon_kwd_exp.save_to_file(
            target_mime='image/x-icon',
            target_extension='.ico',
            ignore_conversion_problems=True)
        if icon_tmp_file is None:
            _log.debug('cannot retrieve <%s>', media_icon_kwd)
        else:
            media_icon_fname = os.path.join(media_base_dir, 'gnumed.ico')
            try:
                shutil.move(icon_tmp_file, media_icon_fname)
                autorun_dict['icon'] = 'icon=gnumed.ico'
            except Exception:
                _log.exception('cannot move %s to %s', icon_tmp_file,
                               media_icon_fname)
        autorun_fname = os.path.join(media_base_dir, 'autorun.inf')
        autorun_file = io.open(autorun_fname,
                               mode='wt',
                               encoding='cp1252',
                               errors='replace')
        autorun_file.write(_autorun_inf % autorun_dict)
        autorun_file.close()

        # cd.inf
        cd_inf_fname = os.path.join(media_base_dir, 'cd.inf')
        cd_inf_file = io.open(cd_inf_fname, mode='wt', encoding='utf8')
        cd_inf_file.write(
            _cd_inf %
            (pat['lastnames'], pat['firstnames'],
             gmTools.coalesce(pat['gender'],
                              '?'), pat.get_formatted_dob('%Y-%m-%d'),
             gmDateTime.pydt_strftime(gmDateTime.pydt_now_here(),
                                      format='%Y-%m-%d'), pat.ID,
             _cfg.get(option='client_version'), ' / '.join([
                 '%s = %s (%s)' % (g['tag'], g['label'], g['l10n_label'])
                 for g in pat.gender_list
             ])))
        cd_inf_file.close()

        # README
        readme_fname = os.path.join(media_base_dir, 'README')
        readme_file = io.open(readme_fname, mode='wt', encoding='utf8')
        readme_file.write(
            _README % (pat.get_description_gender(with_nickname=False) + ', ' +
                       _('born') + ' ' + pat.get_formatted_dob('%Y %B %d')))
        readme_file.close()

        # patient demographics as GDT/XML/VCF
        pat.export_as_gdt(filename=os.path.join(media_base_dir, 'patient.gdt'))
        pat.export_as_xml_linuxmednews(
            filename=os.path.join(media_base_dir, 'patient.xml'))
        pat.export_as_vcard(
            filename=os.path.join(media_base_dir, 'patient.vcf'))

        # praxis VCF
        shutil.move(prax.vcf, os.path.join(media_base_dir, 'praxis.vcf'))

        return media_base_dir
Esempio n. 20
0
def mail_log(parent=None, comment=None, helpdesk=None, sender=None):

		if (comment is None) or (comment.strip() == ''):
			comment = wx.GetTextFromUser (
				message = _(
					'Please enter a short note on what you\n'
					'were about to do in GNUmed:'
				),
				caption = _('Sending bug report'),
				parent = parent
			)
			if comment.strip() == '':
				comment = '<user did not comment on bug report>'

		receivers = []
		if helpdesk is not None:
			receivers = regex.findall (
				'[\S]+@[\S]+',
				helpdesk.strip(),
				flags = regex.UNICODE
			)
		if len(receivers) == 0:
			if _is_public_database:
				receivers = ['*****@*****.**']

		receiver_string = wx.GetTextFromUser (
			message = _(
				'Edit the list of email addresses to send the\n'
				'bug report to (separate addresses by spaces).\n'
				'\n'
				'Note that <*****@*****.**> refers to\n'
				'the public (!) GNUmed bugs mailing list.'
			),
			caption = _('Sending bug report'),
			default_value = ','.join(receivers),
			parent = parent
		)
		if receiver_string.strip() == '':
			return

		receivers = regex.findall (
			'[\S]+@[\S]+',
			receiver_string,
			flags = regex.UNICODE
		)

		dlg = gmGuiHelpers.c2ButtonQuestionDlg (
			parent,
			-1,
			caption = _('Sending bug report'),
			question = _(
				'Your bug report will be sent to:\n'
				'\n'
				'%s\n'
				'\n'
				'Make sure you have reviewed the log file for potentially\n'
				'sensitive information before sending out the bug report.\n'
				'\n'
				'Note that emailing the report may take a while depending\n'
				'on the speed of your internet connection.\n'
			) % '\n'.join(receivers),
			button_defs = [
				{'label': _('Send report'), 'tooltip': _('Yes, send the bug report.')},
				{'label': _('Cancel'), 'tooltip': _('No, do not send the bug report.')}
			],
			show_checkbox = True,
			checkbox_msg = _('include log file in bug report')
		)
		dlg._CHBOX_dont_ask_again.SetValue(_is_public_database)
		go_ahead = dlg.ShowModal()
		if go_ahead == wx.ID_NO:
			dlg.DestroyLater()
			return

		include_log = dlg._CHBOX_dont_ask_again.GetValue()
		if not _is_public_database:
			if include_log:
				result = gmGuiHelpers.gm_show_question (
					_(
						'The database you are connected to is marked as\n'
						'"in-production with controlled access".\n'
						'\n'
						'You indicated that you want to include the log\n'
						'file in your bug report. While this is often\n'
						'useful for debugging the log file might contain\n'
						'bits of patient data which must not be sent out\n'
						'without de-identification.\n'
						'\n'
						'Please confirm that you want to include the log !'
					),
					_('Sending bug report')
				)
				include_log = (result is True)

		if sender is None:
			sender = _('<not supplied>')
		else:
			if sender.strip() == '':
				sender = _('<not supplied>')

		msg = """\
Report sent via GNUmed's handler for unexpected exceptions.

user comment  : %s

client version: %s

system account: %s
staff member  : %s
sender email  : %s

 # enable Launchpad bug tracking
 affects gnumed
 tag automatic-report
 importance medium

""" % (comment, _client_version, _local_account, _staff_name, sender)
		if include_log:
			_log.error(comment)
			_log.warning('syncing log file for emailing')
			gmLog2.flush()
			attachments = [ [_logfile_name, 'text/plain', 'quoted-printable'] ]
		else:
			attachments = None

		dlg.DestroyLater()

		wx.BeginBusyCursor()
		_cfg = gmCfg2.gmCfgData()
		try:
			gmNetworkTools.compose_and_send_email (
				sender = '%s <%s>' % (_staff_name, gmNetworkTools.default_mail_sender),
				receiver = receivers,
				subject = '<bug>: %s' % comment,
				message = msg,
				server = gmNetworkTools.default_mail_server,
				auth = {'user': gmNetworkTools.default_mail_sender, 'password': '******'},
				debug = _cfg.get(option = 'debug'),
				attachments = attachments
			)
			gmDispatcher.send(signal='statustext', msg = _('Bug report has been emailed.'))
		except:
			_log.exception('cannot send bug report')
			gmDispatcher.send(signal='statustext', msg = _('Bug report COULD NOT be emailed.'))
		wx.EndBusyCursor()
Esempio n. 21
0
	def export(self, base_dir=None, items=None, with_metadata=True):

		if items is None:
			items_found = self.items

		if len(items) == 0:
			return None

		from Gnumed.business.gmPerson import cPatient
		pat = cPatient(aPK_obj = self.__pk_identity)
		if base_dir is None:
			base_dir = gmTools.mk_sandbox_dir(prefix = u'exp-%s-' % pat.dirname)

		_log.debug('base dir: %s', base_dir)

		doc_dir = os.path.join(base_dir, r'documents')
		gmTools.mkdir(doc_dir)

		mugshot = pat.document_folder.latest_mugshot
		if mugshot is None:
			mugshot_url = u'documents/no-such-file.png'
			mugshot_alt = _('no patient photograph available')
			mugshot_title = u''
		else:
			mugshot_url = mugshot.export_to_file(directory = doc_dir)
			mugshot_alt =_('patient photograph from %s') % gmDateTime.pydt_strftime(mugshot['date_generated'], '%B %Y')
			mugshot_title = gmDateTime.pydt_strftime(mugshot['date_generated'], '%B %Y')

		# index.html
		idx_fname = os.path.join(base_dir, u'index.html')
		idx_file = io.open(idx_fname, mode = u'wt', encoding = u'utf8')

		# header
		browse_dicomdir = u''
		existing_files = os.listdir(base_dir)
		if u'DICOMDIR' in existing_files:
			browse_dicomdir = u'	<li><a href="./DICOMDIR">browse DICOMDIR</a></li>'
		idx_file.write(_html_start % {
			u'html_title_header': _('Patient data for'),
			u'html_title_patient': gmTools.html_escape_string(pat['description_gender'] + u', ' + _(u'born') + u' ' + pat.get_formatted_dob('%Y %B %d')),
			u'title': _('Patient data export'),
			u'pat_name': gmTools.html_escape_string(pat['description_gender']),
			u'pat_dob': gmTools.html_escape_string(_(u'born') + u' ' + pat.get_formatted_dob('%Y %B %d')),
			u'mugshot_url': mugshot_url,
			u'mugshot_alt': mugshot_alt,
			u'mugshot_title': mugshot_title,
			u'docs_title': _(u'Documents'),
			u'browse_root': _(u'browse storage medium'),
			u'browse_docs': _(u'browse documents area'),
			u'browse_dicomdir': browse_dicomdir
		})
		# middle
		for item in items:
			item_path = item.export_to_file(directory = doc_dir)
			item_fname = os.path.split(item_path)[1]
			idx_file.write(_html_list_item % (
				item_fname,
				gmTools.html_escape_string(item['description'])
			))
		# footer
		_cfg = gmCfg2.gmCfgData()
		idx_file.write(_html_end % (
			gmTools.html_escape_string(gmDateTime.pydt_strftime(format = '%Y %B %d', encoding = u'utf8')),
			gmTools.html_escape_string(_cfg.get(option = u'client_version'))
		))
		idx_file.close()

		# autorun.inf
		autorun_fname = os.path.join(base_dir, u'autorun.inf')
		autorun_file = io.open(autorun_fname, mode = u'wt', encoding = u'utf8')
		autorun_file.write(_autorun_inf % (
			(pat['description_gender'] + u', ' + _(u'born') + u' ' + pat.get_formatted_dob('%Y %B %d')).strip(),
			_('Browse patient data')
		))
		autorun_file.close()

		# cd.inf
		cd_inf_fname = os.path.join(base_dir, u'cd.inf')
		cd_inf_file = io.open(cd_inf_fname, mode = u'wt', encoding = u'utf8')
		cd_inf_file.write(_cd_inf % (
			pat['lastnames'],
			pat['firstnames'],
			gmTools.coalesce(pat['gender'], u'?'),
			pat.get_formatted_dob('%Y-%m-%d'),
			gmDateTime.pydt_strftime(format = '%Y-%m-%d', encoding = u'utf8'),
			pat.ID,
			_cfg.get(option = u'client_version'),
			u' / '.join([ u'%s = %s (%s)' % (g['tag'], g['label'], g['l10n_label']) for g in pat.gender_list ])
		))
		cd_inf_file.close()

		# README
		readme_fname = os.path.join(base_dir, u'README')
		readme_file = io.open(readme_fname, mode = u'wt', encoding = u'utf8')
		readme_file.write(_README % (
			pat['description_gender'] + u', ' + _(u'born') + u' ' + pat.get_formatted_dob('%Y %B %d')
		))
		readme_file.close()

		# patient demographics as GDT/XML/VCF
		pat.export_as_gdt(filename = os.path.join(base_dir, u'patient.gdt'))
		pat.export_as_xml_linuxmednews(filename = os.path.join(base_dir, u'patient.xml'))
		pat.export_as_vcard(filename = os.path.join(base_dir, u'patient.vcf'))

		return base_dir
Esempio n. 22
0
    def export(self,
               base_dir=None,
               items=None,
               with_metadata=True,
               expand_compressed=False):

        if items is None:
            items = self.items

        if len(items) == 0:
            return None

        from Gnumed.business.gmPerson import cPatient
        pat = cPatient(aPK_obj=self.__pk_identity)
        if base_dir is None:
            base_dir = gmTools.mk_sandbox_dir(prefix=u'exp-%s-' % pat.dirname)
        _log.debug('base dir: %s', base_dir)

        doc_dir = os.path.join(base_dir, r'documents')
        gmTools.mkdir(doc_dir)

        _html_start_data = {
            u'html_title_header':
            _('Patient data for'),
            u'html_title_patient':
            gmTools.html_escape_string(
                pat.get_description_gender(with_nickname=False) + u', ' +
                _(u'born') + u' ' + pat.get_formatted_dob('%Y %B %d')),
            u'title':
            _('Patient data export'),
            u'pat_name':
            gmTools.html_escape_string(
                pat.get_description_gender(with_nickname=False)),
            u'pat_dob':
            gmTools.html_escape_string(
                _(u'born') + u' ' + pat.get_formatted_dob('%Y %B %d')),
            u'mugshot_url':
            u'documents/no-such-file.png',
            u'mugshot_alt':
            _('no patient photograph available'),
            u'mugshot_title':
            u'',
            u'docs_title':
            _(u'Documents'),
            u'browse_root':
            _(u'browse storage medium'),
            u'browse_docs':
            _(u'browse documents area'),
            u'browse_dicomdir':
            u''
        }

        mugshot = pat.document_folder.latest_mugshot
        if mugshot is not None:
            _html_start_data['mugshot_url'] = mugshot.export_to_file(
                directory=doc_dir)
            _html_start_data['mugshot_alt'] = _(
                'patient photograph from %s') % gmDateTime.pydt_strftime(
                    mugshot['date_generated'], '%B %Y')
            _html_start_data['mugshot_title'] = gmDateTime.pydt_strftime(
                mugshot['date_generated'], '%B %Y')

        # index.html
        idx_fname = os.path.join(base_dir, u'index.html')
        idx_file = io.open(idx_fname, mode=u'wt', encoding=u'utf8')
        # header
        existing_files = os.listdir(base_dir)
        if u'DICOMDIR' in existing_files:
            _html_start_data[
                u'browse_dicomdir'] = u'	<li><a href="./DICOMDIR">browse DICOMDIR</a></li>'
        idx_file.write(_html_start % _html_start_data)
        # middle
        for item in items:
            item_path = item.export_to_file(directory=doc_dir)
            item_fname = os.path.split(item_path)[1]
            idx_file.write(
                _html_list_item %
                (item_fname, gmTools.html_escape_string(item['description'])))
        # footer
        _cfg = gmCfg2.gmCfgData()
        from Gnumed.business.gmPraxis import gmCurrentPraxisBranch
        prax = gmCurrentPraxisBranch()
        lines = []
        adr = prax.branch.org_unit.address
        if adr is not None:
            lines.extend(adr.format())
        for comm in prax.branch.org_unit.comm_channels:
            if comm['is_confidential'] is True:
                continue
            lines.append(u'%s: %s' % (comm['l10n_comm_type'], comm['url']))
        adr = u''
        if len(lines) > 0:
            adr = gmTools.html_escape_string(u'\n'.join(lines),
                                             replace_eol=True,
                                             keep_visual_eol=True)
        _html_end_data = {
            'branch':
            gmTools.html_escape_string(prax['branch']),
            'praxis':
            gmTools.html_escape_string(prax['praxis']),
            'date':
            gmTools.html_escape_string(
                gmDateTime.pydt_strftime(gmDateTime.pydt_now_here(),
                                         format='%Y %B %d',
                                         encoding=u'utf8')),
            'gm_ver':
            gmTools.html_escape_string(_cfg.get(option=u'client_version')),
            #'gm_ver': 'git HEAD',				# for testing
            'adr':
            adr
        }
        idx_file.write(_html_end % _html_end_data)
        idx_file.close()

        # autorun.inf
        autorun_fname = os.path.join(base_dir, u'autorun.inf')
        autorun_file = io.open(autorun_fname, mode=u'wt', encoding=u'utf8')
        autorun_file.write(
            _autorun_inf %
            ((pat.get_description_gender(with_nickname=False) + u', ' +
              _(u'born') + u' ' + pat.get_formatted_dob('%Y %B %d')).strip(),
             _('Browse patient data')))
        autorun_file.close()

        # cd.inf
        cd_inf_fname = os.path.join(base_dir, u'cd.inf')
        cd_inf_file = io.open(cd_inf_fname, mode=u'wt', encoding=u'utf8')
        cd_inf_file.write(
            _cd_inf %
            (pat['lastnames'], pat['firstnames'],
             gmTools.coalesce(pat['gender'],
                              u'?'), pat.get_formatted_dob('%Y-%m-%d'),
             gmDateTime.pydt_strftime(gmDateTime.pydt_now_here(),
                                      format='%Y-%m-%d',
                                      encoding=u'utf8'), pat.ID,
             _cfg.get(option=u'client_version'), u' / '.join([
                 u'%s = %s (%s)' % (g['tag'], g['label'], g['l10n_label'])
                 for g in pat.gender_list
             ])))
        cd_inf_file.close()

        # README
        readme_fname = os.path.join(base_dir, u'README')
        readme_file = io.open(readme_fname, mode=u'wt', encoding=u'utf8')
        readme_file.write(
            _README %
            (pat.get_description_gender(with_nickname=False) + u', ' +
             _(u'born') + u' ' + pat.get_formatted_dob('%Y %B %d')))
        readme_file.close()

        # patient demographics as GDT/XML/VCF
        pat.export_as_gdt(filename=os.path.join(base_dir, u'patient.gdt'))
        pat.export_as_xml_linuxmednews(
            filename=os.path.join(base_dir, u'patient.xml'))
        pat.export_as_vcard(filename=os.path.join(base_dir, u'patient.vcf'))

        # praxis VCF
        shutil.move(prax.vcf, os.path.join(base_dir, u'praxis.vcf'))

        return base_dir
Esempio n. 23
0
class cExportArea(object):
    def __init__(self, pk_identity):
        self.__pk_identity = pk_identity

    #--------------------------------------------------------
    def add_form(self, form=None, designation=None):

        if len(form.final_output_filenames) == 0:
            return True

        items = []
        for fname in form.final_output_filenames:
            item = self.add_file(filename=fname)
            if item is None:
                for prev_item in items:
                    delete_export_item(
                        pk_export_item=prev_item['pk_export_item'])
                return False
            items.append(item)
            item['description'] = _(u'form: %s %s (%s)') % (
                form.template['name_long'], form.template['external_version'],
                fname)
            item['designation'] = designation
            item.save()

        return True

    #--------------------------------------------------------
    def add_forms(self, forms=None, designation=None):
        all_ok = True
        for form in forms:
            all_ok = all_ok and self.add_form(form=form,
                                              designation=designation)

        return all_ok

    #--------------------------------------------------------
    def add_file(self, filename=None, hint=None):
        try:
            open(filename).close()
        except Exception:
            _log.exception('cannot open file <%s>', filename)
            return None

        file_md5 = gmTools.file2md5(filename=filename, return_hex=True)
        existing_item = self.md5_exists(md5=file_md5,
                                        include_document_parts=False)
        if existing_item is not None:
            _log.debug('md5 match (%s): %s already in export area', file_md5,
                       filename)
            return existing_item

        path, basename = os.path.split(filename)
        item = create_export_item(
            description=u'%s: %s (%s/)' %
            (gmTools.coalesce(hint, _(u'file'), u'%s'), basename, path),
            pk_identity=self.__pk_identity,
            filename=filename)

        if item.update_data_from_file(filename=filename):
            return item

        delete_export_item(pk_export_item=item['pk_export_item'])
        return None

    #--------------------------------------------------------
    def add_files(self, filenames=None, hint=None):
        all_ok = True
        for fname in filenames:
            all_ok = all_ok and (self.add_file(filename=fname, hint=hint)
                                 is not None)

        return all_ok

    #--------------------------------------------------------
    def add_documents(self, documents=None):
        for doc in documents:
            doc_tag = _(u'%s (%s)%s') % (
                doc['l10n_type'],
                gmDateTime.pydt_strftime(doc['clin_when'], '%Y %b %d'),
                gmTools.coalesce(doc['comment'], u'', u' "%s"'))
            for obj in doc.parts:
                if self.document_part_item_exists(pk_part=obj['pk_obj']):
                    continue
                f_ext = u''
                if obj['filename'] is not None:
                    f_ext = os.path.splitext(
                        obj['filename'])[1].strip('.').strip()
                if f_ext != u'':
                    f_ext = u' .' + f_ext.upper()
                obj_tag = _(u'part %s (%s%s)%s') % (
                    obj['seq_idx'], gmTools.size2str(obj['size']), f_ext,
                    gmTools.coalesce(obj['obj_comment'], u'', u' "%s"'))
                create_export_item(description=u'%s - %s' % (doc_tag, obj_tag),
                                   pk_doc_obj=obj['pk_obj'])

    #--------------------------------------------------------
    def document_part_item_exists(self, pk_part=None):
        cmd = u"SELECT EXISTS (SELECT 1 FROM clin.export_item WHERE fk_doc_obj = %(pk_obj)s)"
        args = {'pk_obj': pk_part}
        rows, idx = gmPG2.run_ro_queries(queries=[{
            'cmd': cmd,
            'args': args
        }],
                                         get_col_idx=False)
        return rows[0][0]

    #--------------------------------------------------------
    def md5_exists(self, md5=None, include_document_parts=False):
        where_parts = [u'pk_identity = %(pat)s', u'md5_sum = %(md5)s']
        args = {'pat': self.__pk_identity, 'md5': md5}

        if not include_document_parts:
            where_parts.append(u'pk_doc_obj IS NULL')

        cmd = _SQL_get_export_items % u' AND '.join(where_parts)
        rows, idx = gmPG2.run_ro_queries(queries=[{
            'cmd': cmd,
            'args': args
        }],
                                         get_col_idx=True)

        if len(rows) == 0:
            return None

        r = rows[0]
        return cExportItem(row={
            'data': r,
            'idx': idx,
            'pk_field': 'pk_export_item'
        })

    #--------------------------------------------------------
    def dump_items_to_disk(self, base_dir=None, items=None):
        if items is None:
            items = self.items

        if len(items) == 0:
            return None

        if base_dir is None:
            from Gnumed.business.gmPerson import cPatient
            pat = cPatient(aPK_obj=self.__pk_identity)
            base_dir = gmTools.mk_sandbox_dir(prefix=u'exp-%s-' % pat.dirname)
        _log.debug('dumping export items to: %s', base_dir)

        gmTools.mkdir(base_dir)
        for item in items:
            item.save_to_file(directory=base_dir)
        return base_dir

    #--------------------------------------------------------
    def export(self, base_dir=None, items=None, expand_compressed=False):

        if items is None:
            items = self.items

        if len(items) == 0:
            return None

        media_base_dir = base_dir

        from Gnumed.business.gmPerson import cPatient
        pat = cPatient(aPK_obj=self.__pk_identity)
        if media_base_dir is None:
            media_base_dir = gmTools.mk_sandbox_dir(prefix=u'exp-%s-' %
                                                    pat.dirname)
        _log.debug('patient media base dir: %s', media_base_dir)

        doc_dir = os.path.join(media_base_dir, r'documents')
        if os.path.isdir(doc_dir):
            index_existing_docs = True
        else:
            index_existing_docs = False
            gmTools.mkdir(doc_dir)

        _html_start_data = {
            u'html_title_header':
            _('Patient data for'),
            u'html_title_patient':
            gmTools.html_escape_string(
                pat.get_description_gender(with_nickname=False) + u', ' +
                _(u'born') + u' ' + pat.get_formatted_dob('%Y %B %d')),
            u'title':
            _('Patient data export'),
            u'pat_name':
            gmTools.html_escape_string(
                pat.get_description_gender(with_nickname=False)),
            u'pat_dob':
            gmTools.html_escape_string(
                _(u'born') + u' ' + pat.get_formatted_dob('%Y %B %d')),
            u'mugshot_url':
            u'documents/no-such-file.png',
            u'mugshot_alt':
            _('no patient photograph available'),
            u'mugshot_title':
            u'',
            u'docs_title':
            _(u'Documents'),
            u'browse_root':
            _(u'browse storage medium'),
            u'browse_docs':
            _(u'browse documents area'),
            u'browse_dicomdir':
            u'',
            u'run_dicom_viewer':
            u''
        }

        mugshot = pat.document_folder.latest_mugshot
        if mugshot is not None:
            _html_start_data['mugshot_url'] = mugshot.save_to_file(
                directory=doc_dir, adjust_extension=True)
            _html_start_data['mugshot_alt'] = _(
                'patient photograph from %s') % gmDateTime.pydt_strftime(
                    mugshot['date_generated'], '%B %Y')
            _html_start_data['mugshot_title'] = gmDateTime.pydt_strftime(
                mugshot['date_generated'], '%B %Y')

        if u'DICOMDIR' in os.listdir(media_base_dir):
            _html_start_data[
                u'browse_dicomdir'] = u'<li><a href="./DICOMDIR">%s</a></li>' % _(
                    u'show DICOMDIR file')
            # copy DWV into target dir
            dwv_target_dir = os.path.join(media_base_dir, u'dwv')
            gmTools.rmdir(dwv_target_dir)
            dwv_src_dir = os.path.join(gmTools.gmPaths().local_base_dir,
                                       u'dwv4export')
            if not os.path.isdir(dwv_src_dir):
                dwv_src_dir = os.path.join(
                    gmTools.gmPaths().system_app_data_dir, u'dwv4export')
            try:
                shutil.copytree(dwv_src_dir, dwv_target_dir)
                _html_start_data[
                    u'run_dicom_viewer'] = u'<li><a href="./dwv/viewers/mobile-local/index.html">%s</a></li>' % _(
                        u'run Radiology Images (DICOM) Viewer')
            except shutil.Error, OSError:
                _log.exception('cannot include DWV, skipping')

        # index.html
        # - header
        idx_fname = os.path.join(media_base_dir, u'index.html')
        idx_file = io.open(idx_fname, mode=u'wt', encoding=u'utf8')
        idx_file.write(_html_start % _html_start_data)
        # - middle (side effect ! -> exports items into files ...)
        existing_docs = os.listdir(
            doc_dir
        )  # get them now, or else we will include the to-be-exported items
        # - export items
        for item in items:
            item_path = item.save_to_file(directory=doc_dir)
            item_fname = os.path.split(item_path)[1]
            idx_file.write(
                _html_list_item %
                (item_fname, gmTools.html_escape_string(item['description'])))
        # - preexisting documents
        for doc_fname in existing_docs:
            idx_file.write(
                _html_list_item %
                (doc_fname,
                 gmTools.html_escape_string(_(u'other: %s') % doc_fname)))
        # - footer
        _cfg = gmCfg2.gmCfgData()
        from Gnumed.business.gmPraxis import gmCurrentPraxisBranch
        prax = gmCurrentPraxisBranch()
        lines = []
        adr = prax.branch.org_unit.address
        if adr is not None:
            lines.extend(adr.format())
        for comm in prax.branch.org_unit.comm_channels:
            if comm['is_confidential'] is True:
                continue
            lines.append(u'%s: %s' % (comm['l10n_comm_type'], comm['url']))
        adr = u''
        if len(lines) > 0:
            adr = gmTools.html_escape_string(u'\n'.join(lines),
                                             replace_eol=True,
                                             keep_visual_eol=True)
        _html_end_data = {
            'branch':
            gmTools.html_escape_string(prax['branch']),
            'praxis':
            gmTools.html_escape_string(prax['praxis']),
            'date':
            gmTools.html_escape_string(
                gmDateTime.pydt_strftime(gmDateTime.pydt_now_here(),
                                         format='%Y %B %d',
                                         encoding=u'utf8')),
            'gm_ver':
            gmTools.html_escape_string(_cfg.get(option=u'client_version')),
            #'gm_ver': 'git HEAD',				# for testing
            'adr':
            adr
        }
        idx_file.write(_html_end % _html_end_data)
        idx_file.close()

        # start.html (just a copy of index.html, really ;-)
        start_fname = os.path.join(media_base_dir, u'start.html')
        try:
            shutil.copy2(idx_fname, start_fname)
        except Exception:
            _log.exception('cannot copy %s to %s', idx_fname, start_fname)

        # autorun.inf
        # - compute label
        autorun_dict = {}
        name = pat.active_name
        last = name['lastnames'][:14]
        first = name['firstnames'][:min(14, 18 - len(last))]
        autorun_dict['label'] = (
            (u'%s%s%s' %
             (u'%s,%s' %
              (last, first), gmTools.coalesce(pat['gender'], u'', u' (%s)'),
              pat.get_formatted_dob(format=' %Y%m%d',
                                    none_string=u'',
                                    honor_estimation=False))).strip()
        )[:
          32]  # max 32 chars, supposedly ASCII, but CP1252 likely works pretty well
        # - compute icon
        media_icon_kwd = u'$$gnumed_patient_media_export_icon'
        media_icon_kwd_exp = gmKeywordExpansion.get_expansion(
            keyword=media_icon_kwd, textual_only=False, binary_only=True)
        icon_tmp_file = media_icon_kwd_exp.save_to_file(
            target_mime=u'image/x-icon',
            target_extension=u'.ico',
            ignore_conversion_problems=True)
        autorun_dict['icon'] = u''
        if icon_tmp_file is None:
            _log.debug(u'cannot retrieve <%s>', media_icon_kwd)
        else:
            media_icon_fname = os.path.join(media_base_dir, u'gnumed.ico')
            try:
                shutil.move(icon_tmp_file, media_icon_fname)
                autorun_dict['icon'] = u'icon=gnumed.ico'
            except Exception:
                _log.exception('cannot move %s to %s', icon_tmp_file,
                               media_icon_fname)
        # - compute action
        autorun_dict['action'] = _('Browse patient data')
        # - create file
        autorun_fname = os.path.join(media_base_dir, u'autorun.inf')
        autorun_file = io.open(autorun_fname,
                               mode='wt',
                               encoding='cp1252',
                               errors='replace')
        autorun_file.write(_autorun_inf % autorun_dict)
        autorun_file.close()

        # cd.inf
        cd_inf_fname = os.path.join(media_base_dir, u'cd.inf')
        cd_inf_file = io.open(cd_inf_fname, mode=u'wt', encoding=u'utf8')
        cd_inf_file.write(
            _cd_inf %
            (pat['lastnames'], pat['firstnames'],
             gmTools.coalesce(pat['gender'],
                              u'?'), pat.get_formatted_dob('%Y-%m-%d'),
             gmDateTime.pydt_strftime(gmDateTime.pydt_now_here(),
                                      format='%Y-%m-%d',
                                      encoding=u'utf8'), pat.ID,
             _cfg.get(option=u'client_version'), u' / '.join([
                 u'%s = %s (%s)' % (g['tag'], g['label'], g['l10n_label'])
                 for g in pat.gender_list
             ])))
        cd_inf_file.close()

        # README
        readme_fname = os.path.join(media_base_dir, u'README')
        readme_file = io.open(readme_fname, mode=u'wt', encoding=u'utf8')
        readme_file.write(
            _README %
            (pat.get_description_gender(with_nickname=False) + u', ' +
             _(u'born') + u' ' + pat.get_formatted_dob('%Y %B %d')))
        readme_file.close()

        # patient demographics as GDT/XML/VCF
        pat.export_as_gdt(
            filename=os.path.join(media_base_dir, u'patient.gdt'))
        pat.export_as_xml_linuxmednews(
            filename=os.path.join(media_base_dir, u'patient.xml'))
        pat.export_as_vcard(
            filename=os.path.join(media_base_dir, u'patient.vcf'))

        # praxis VCF
        shutil.move(prax.vcf, os.path.join(media_base_dir, u'praxis.vcf'))

        return media_base_dir
Esempio n. 24
0
import io
import logging
import csv
import os.path
import re as regex


if __name__ == '__main__':
	sys.path.insert(0, '../../')
from Gnumed.pycommon import gmPG2
from Gnumed.pycommon import gmTools
from Gnumed.pycommon import gmCfg2


_log = logging.getLogger('gm.atc')
_cfg = gmCfg2.gmCfgData()


ATC_NICOTINE = 'N07BA01'
ATC_ETHANOL  = 'V03AB16'

#============================================================
def propagate_atc(substance=None, atc=None, link_obj=None):

	_log.debug('substance <%s>, ATC <%s>', substance, atc)

	if atc is not None:
		if atc.strip() == '':
			atc = None

	if atc is None:
Esempio n. 25
0
def mail_log(parent=None, comment=None, helpdesk=None, sender=None):

    if (comment is None) or (comment.strip() == ''):
        comment = wx.GetTextFromUser(message=_(
            'Please enter a short note on what you\n'
            'were about to do in GNUmed:'),
                                     caption=_('Sending bug report'),
                                     parent=parent)
        if comment.strip() == '':
            comment = '<user did not comment on bug report>'

    receivers = []
    if helpdesk is not None:
        receivers = regex.findall('[\S]+@[\S]+',
                                  helpdesk.strip(),
                                  flags=regex.UNICODE)
    if len(receivers) == 0:
        if _is_public_database:
            receivers = ['*****@*****.**']

    receiver_string = wx.GetTextFromUser(message=_(
        'Edit the list of email addresses to send the\n'
        'bug report to (separate addresses by spaces).\n'
        '\n'
        'Note that <*****@*****.**> refers to\n'
        'the public (!) GNUmed bugs mailing list.'),
                                         caption=_('Sending bug report'),
                                         default_value=','.join(receivers),
                                         parent=parent)
    if receiver_string.strip() == '':
        return

    receivers = regex.findall('[\S]+@[\S]+',
                              receiver_string,
                              flags=regex.UNICODE)

    dlg = gmGuiHelpers.c2ButtonQuestionDlg(
        parent,
        -1,
        caption=_('Sending bug report'),
        question=_('Your bug report will be sent to:\n'
                   '\n'
                   '%s\n'
                   '\n'
                   'Make sure you have reviewed the log file for potentially\n'
                   'sensitive information before sending out the bug report.\n'
                   '\n'
                   'Note that emailing the report may take a while depending\n'
                   'on the speed of your internet connection.\n') %
        '\n'.join(receivers),
        button_defs=[{
            'label': _('Send report'),
            'tooltip': _('Yes, send the bug report.')
        }, {
            'label': _('Cancel'),
            'tooltip': _('No, do not send the bug report.')
        }],
        show_checkbox=True,
        checkbox_msg=_('include log file in bug report'))
    dlg._CHBOX_dont_ask_again.SetValue(_is_public_database)
    go_ahead = dlg.ShowModal()
    if go_ahead == wx.ID_NO:
        dlg.DestroyLater()
        return

    include_log = dlg._CHBOX_dont_ask_again.GetValue()
    if not _is_public_database:
        if include_log:
            result = gmGuiHelpers.gm_show_question(
                _('The database you are connected to is marked as\n'
                  '"in-production with controlled access".\n'
                  '\n'
                  'You indicated that you want to include the log\n'
                  'file in your bug report. While this is often\n'
                  'useful for debugging the log file might contain\n'
                  'bits of patient data which must not be sent out\n'
                  'without de-identification.\n'
                  '\n'
                  'Please confirm that you want to include the log !'),
                _('Sending bug report'))
            include_log = (result is True)

    if sender is None:
        sender = _('<not supplied>')
    else:
        if sender.strip() == '':
            sender = _('<not supplied>')

    msg = """\
Report sent via GNUmed's handler for unexpected exceptions.

user comment  : %s

client version: %s

system account: %s
staff member  : %s
sender email  : %s

 # enable Launchpad bug tracking
 affects gnumed
 tag automatic-report
 importance medium

""" % (comment, _client_version, _local_account, _staff_name, sender)
    if include_log:
        _log.error(comment)
        _log.warning('syncing log file for emailing')
        gmLog2.flush()
        attachments = [[_logfile_name, 'text/plain', 'quoted-printable']]
    else:
        attachments = None

    dlg.DestroyLater()

    wx.BeginBusyCursor()
    _cfg = gmCfg2.gmCfgData()
    try:
        gmNetworkTools.compose_and_send_email(
            sender='%s <%s>' %
            (_staff_name, gmNetworkTools.default_mail_sender),
            receiver=receivers,
            subject='<bug>: %s' % comment,
            message=msg,
            server=gmNetworkTools.default_mail_server,
            auth={
                'user': gmNetworkTools.default_mail_sender,
                'password': '******'
            },
            debug=_cfg.get(option='debug'),
            attachments=attachments)
        gmDispatcher.send(signal='statustext',
                          msg=_('Bug report has been emailed.'))
    except:
        _log.exception('cannot send bug report')
        gmDispatcher.send(signal='statustext',
                          msg=_('Bug report COULD NOT be emailed.'))
    wx.EndBusyCursor()
Esempio n. 26
0
def check_for_update(url=None,
                     current_branch=None,
                     current_version=None,
                     consider_latest_branch=False):
    """Check for new releases at <url>.

	Returns (bool, text).
	True: new release available
	False: up to date
	None: don't know
	"""
    if current_version == u'GIT HEAD':
        _log.debug('GIT HEAD always up to date')
        return (False, None)

    try:
        remote_file = wget.urlopen(url)
    except (wget.URLError, ValueError, OSError, IOError):
        # IOError: socket.error
        _log.exception("cannot retrieve version file from [%s]", url)
        return (None,
                _('Cannot retrieve version information from:\n\n%s') % url)

    _log.debug('retrieving version information from [%s]', url)

    cfg = gmCfg2.gmCfgData()
    try:
        cfg.add_stream_source(source='gm-versions', stream=remote_file)
    except (UnicodeDecodeError):
        remote_file.close()
        _log.exception("cannot read version file from [%s]", url)
        return (None, _('Cannot read version information from:\n\n%s') % url)

    remote_file.close()

    latest_branch = cfg.get('latest branch',
                            'branch',
                            source_order=[('gm-versions', 'return')])
    latest_release_on_latest_branch = cfg.get('branch %s' % latest_branch,
                                              'latest release',
                                              source_order=[('gm-versions',
                                                             'return')])
    latest_release_on_current_branch = cfg.get('branch %s' % current_branch,
                                               'latest release',
                                               source_order=[('gm-versions',
                                                              'return')])

    cfg.remove_source('gm-versions')

    _log.info('current release: %s', current_version)
    _log.info('current branch: %s', current_branch)
    _log.info('latest release on current branch: %s',
              latest_release_on_current_branch)
    _log.info('latest branch: %s', latest_branch)
    _log.info('latest release on latest branch: %s',
              latest_release_on_latest_branch)

    # anything known ?
    no_release_information_available = (
        ((latest_release_on_current_branch is None) and
         (latest_release_on_latest_branch is None))
        or (not consider_latest_branch and
            (latest_release_on_current_branch is None)))
    if no_release_information_available:
        _log.warning('no release information available')
        msg = _('There is no version information available from:\n\n%s') % url
        return (None, msg)

    # up to date ?
    if consider_latest_branch:
        _log.debug('latest branch taken into account')
        if latest_release_on_latest_branch is None:
            if compare_versions(latest_release_on_current_branch,
                                current_version) in [-1, 0]:
                _log.debug(
                    'up to date: current version >= latest version on current branch and no latest branch available'
                )
                return (False, None)
        else:
            if compare_versions(latest_release_on_latest_branch,
                                current_version) in [-1, 0]:
                _log.debug(
                    'up to date: current version >= latest version on latest branch'
                )
                return (False, None)
    else:
        _log.debug('latest branch not taken into account')
        if compare_versions(latest_release_on_current_branch,
                            current_version) in [-1, 0]:
            _log.debug(
                'up to date: current version >= latest version on current branch'
            )
            return (False, None)

    new_release_on_current_branch_available = (
        (latest_release_on_current_branch is not None) and (compare_versions(
            latest_release_on_current_branch, current_version) == 1))
    _log.info(
        '%snew release on current branch available',
        gmTools.bool2str(new_release_on_current_branch_available, '', 'no '))

    new_release_on_latest_branch_available = ((latest_branch is not None) and (
        (latest_branch > current_branch) or
        ((latest_branch == current_branch) and (compare_versions(
            latest_release_on_latest_branch, current_version) == 1))))
    _log.info(
        '%snew release on latest branch available',
        gmTools.bool2str(new_release_on_latest_branch_available, '', 'no '))

    if not (new_release_on_current_branch_available
            or new_release_on_latest_branch_available):
        _log.debug('up to date: no new releases available')
        return (False, None)

    # not up to date
    msg = _('A new version of GNUmed is available.\n\n')
    msg += _(' Your current version: "%s"\n') % current_version
    if consider_latest_branch:
        if new_release_on_current_branch_available:
            msg += u'\n'
            msg += _(' New version: "%s"') % latest_release_on_current_branch
            msg += u'\n'
            msg += _(' - bug fixes only\n')
            msg += _(' - database fixups may be needed\n')
        if new_release_on_latest_branch_available:
            if current_branch != latest_branch:
                msg += u'\n'
                msg += _(
                    ' New version: "%s"') % latest_release_on_latest_branch
                msg += u'\n'
                msg += _(' - bug fixes and new features\n')
                msg += _(' - database upgrade required\n')
    else:
        msg += u'\n'
        msg += _(' New version: "%s"') % latest_release_on_current_branch
        msg += u'\n'
        msg += _(' - bug fixes only\n')
        msg += _(' - database fixups may be needed\n')

    msg += u'\n\n'
    msg += _('Note, however, that this version may not yet\n'
             'be available *pre-packaged* for your system.')

    msg += u'\n\n'
    msg += _('Details are found on <http://wiki.gnumed.de>.\n')
    msg += u'\n'
    msg += _('Version information loaded from:\n\n %s') % url

    return (True, msg)
Esempio n. 27
0
def check_for_update(url=None, current_branch=None, current_version=None, consider_latest_branch=False):
	"""Check for new releases at <url>.

	Returns (bool, text).
	True: new release available
	False: up to date
	None: don't know
	"""
	if current_version == u'GIT HEAD':
		_log.debug('GIT HEAD always up to date')
		return (False, None)

	try:
		remote_file = wget.urlopen(url)
	except (wget.URLError, ValueError, OSError):
		_log.exception("cannot retrieve version file from [%s]", url)
		return (None, _('Cannot retrieve version information from:\n\n%s') % url)

	_log.debug('retrieving version information from [%s]', url)

	cfg = gmCfg2.gmCfgData()
	try:
		cfg.add_stream_source(source = 'gm-versions', stream = remote_file)
	except (UnicodeDecodeError):
		remote_file.close()
		_log.exception("cannot read version file from [%s]", url)
		return (None, _('Cannot read version information from:\n\n%s') % url)

	remote_file.close()

	latest_branch = cfg.get('latest branch', 'branch', source_order = [('gm-versions', 'return')])
	latest_release_on_latest_branch = cfg.get('branch %s' % latest_branch, 'latest release', source_order = [('gm-versions', 'return')])
	latest_release_on_current_branch = cfg.get('branch %s' % current_branch, 'latest release', source_order = [('gm-versions', 'return')])

	cfg.remove_source('gm-versions')

	_log.info('current release: %s', current_version)
	_log.info('current branch: %s', current_branch)
	_log.info('latest release on current branch: %s', latest_release_on_current_branch)
	_log.info('latest branch: %s', latest_branch)
	_log.info('latest release on latest branch: %s', latest_release_on_latest_branch)

	# anything known ?
	no_release_information_available = (
		(
			(latest_release_on_current_branch is None) and
			(latest_release_on_latest_branch is None)
		) or (
			not consider_latest_branch and
			(latest_release_on_current_branch is None)
		)
	)
	if no_release_information_available:
		_log.warning('no release information available')
		msg = _('There is no version information available from:\n\n%s') % url
		return (None, msg)

	# up to date ?
	if consider_latest_branch:
		_log.debug('latest branch taken into account')
		if latest_release_on_latest_branch is None:
			if compare_versions(latest_release_on_current_branch, current_version) in [-1, 0]:
				_log.debug('up to date: current version >= latest version on current branch and no latest branch available')
				return (False, None)
		else:
			if compare_versions(latest_release_on_latest_branch, current_version) in [-1, 0]:
				_log.debug('up to date: current version >= latest version on latest branch')
				return (False, None)
	else:
		_log.debug('latest branch not taken into account')
		if compare_versions(latest_release_on_current_branch, current_version) in [-1, 0]:
			_log.debug('up to date: current version >= latest version on current branch')
			return (False, None)

	new_release_on_current_branch_available = (
		(latest_release_on_current_branch is not None) and
		(compare_versions(latest_release_on_current_branch, current_version) == 1)
	)
	_log.info('%snew release on current branch available', gmTools.bool2str(new_release_on_current_branch_available, '', 'no '))

	new_release_on_latest_branch_available = (
		(latest_branch is not None)
			and
		(
			(latest_branch > current_branch) or (
				(latest_branch == current_branch) and
				(compare_versions(latest_release_on_latest_branch, current_version) == 1)
			)
		)
	)
	_log.info('%snew release on latest branch available', gmTools.bool2str(new_release_on_latest_branch_available, '', 'no '))

	if not (new_release_on_current_branch_available or new_release_on_latest_branch_available):
		_log.debug('up to date: no new releases available')
		return (False, None)

	# not up to date
	msg = _('A new version of GNUmed is available.\n\n')
	msg += _(' Your current version: "%s"\n') % current_version
	if consider_latest_branch:
		if new_release_on_current_branch_available:
			msg += u'\n'
			msg += _(' New version: "%s"') % latest_release_on_current_branch
			msg += u'\n'
			msg += _(' - bug fixes only\n')
			msg += _(' - database fixups may be needed\n')
		if new_release_on_latest_branch_available:
			if current_branch != latest_branch:
				msg += u'\n'
				msg += _(' New version: "%s"') % latest_release_on_latest_branch
				msg += u'\n'
				msg += _(' - bug fixes and new features\n')
				msg += _(' - database upgrade required\n')
	else:
		msg += u'\n'
		msg += _(' New version: "%s"') % latest_release_on_current_branch
		msg += u'\n'
		msg += _(' - bug fixes only\n')
		msg += _(' - database fixups may be needed\n')

	msg += u'\n\n'
	msg += _(
		'Note, however, that this version may not yet\n'
		'be available *pre-packaged* for your system.'
	)

	msg += u'\n\n'
	msg += _('Details are found on <http://wiki.gnumed.de>.\n')
	msg += u'\n'
	msg += _('Version information loaded from:\n\n %s') % url

	return (True, msg)