Example #1
0
def export_patients_as_xdt(base_path=None):

	path = gmTools.get_unique_filename (
		prefix = u'gm-export-',
		suffix = u'',
		tmp_dir = base_path
	)
	path = os.path.splitext(path)[0]
	gmTools.mkdir(path)

	for ID in gmPerson.get_person_IDs():
		_log.info(u'exporting patient #%s', ID)
		identity = gmPerson.cPerson(aPK_obj = ID)
		_log.info(u'identity: %s', identity)
		filename = gmTools.get_unique_filename (
			prefix = u'gm_exp-%s-' % identity.dirname,
			suffix = u'.xdt',
			tmp_dir = path
		)
		_log.info(u'file: %s', filename)
		identity.export_as_gdt (
			filename = filename,
			encoding = u'utf8'
			#encoding = u'iso-8859-15'
		)
Example #2
0
def clipboard2file(check_for_filename=False):

	if wx.TheClipboard.IsOpened():
		return False

	if not wx.TheClipboard.Open():
		return False

	data_obj = wx.TextDataObject()
	got_it = wx.TheClipboard.GetData(data_obj)
	if got_it:
		clipboard_text_content = data_obj.Text
		wx.TheClipboard.Close()
		if check_for_filename:
			try:
				io.open(clipboard_text_content).close()
				return clipboard_text_content
			except IOError:
				_log.exception('clipboard does not seem to hold filename: %s', clipboard_text_content)
		fname = gmTools.get_unique_filename(prefix = 'gm-clipboard-', suffix = '.txt')
		target_file = io.open(fname, mode = 'wt', encoding = 'utf8')
		target_file.write(clipboard_text_content)
		target_file.close()
		return fname

	data_obj = wx.BitmapDataObject()
	got_it = wx.TheClipboard.GetData(data_obj)
	if got_it:
		fname = gmTools.get_unique_filename(prefix = 'gm-clipboard-', suffix = '.png')
		bmp = data_obj.Bitmap.SaveFile(fname, wx.BITMAP_TYPE_PNG)
		wx.TheClipboard.Close()
		return fname

	wx.TheClipboard.Close()
	return None
Example #3
0
def split_LOINCDBTXT(input_fname=None, data_fname=None, license_fname=None):

	_log.debug('splitting LOINC source file [%s]', input_fname)

	if license_fname is None:
		license_fname = gmTools.get_unique_filename(prefix = 'loinc_license-', suffix = '.txt')
	_log.debug('LOINC header: %s', license_fname)

	if data_fname is None:
		data_fname = gmTools.get_unique_filename(prefix = 'loinc_data-', suffix = '.csv')
	_log.debug('LOINC data: %s', data_fname)

	loinc_file = io.open(input_fname, mode = 'rt', encoding = file_encoding, errors = 'replace')
	out_file = io.open(license_fname, mode = 'wt', encoding = 'utf8', errors = 'replace')

	for line in loinc_file:

		if license_delimiter in line:
			out_file.write(line)
			out_file.close()
			out_file = io.open(data_fname, mode = 'wt', encoding = 'utf8', errors = 'replace')
			continue

		out_file.write(line)

	out_file.close()

	return data_fname, license_fname
Example #4
0
	def acquire_pages_into_files(self, delay=None, filename=None):
		"""Call XSane.

		<filename> name part must have format name-001.ext>
		"""
		if filename is None:
			filename = gmTools.get_unique_filename(prefix = 'gm-scan-')

		name, ext = os.path.splitext(filename)
		filename = '%s-001%s' % (name, cXSaneScanner._FILETYPE)
		filename = os.path.abspath(os.path.expanduser(filename))

		cmd = 'xsane --no-mode-selection --save --force-filename "%s" --xsane-rc "%s" %s %s' % (
			filename,
			self.__get_session_xsanerc(),
			gmTools.coalesce(self.device_settings_file, '', '--device-settings %s'),
			gmTools.coalesce(self.default_device, '')
		)
		normal_exit = gmShellAPI.run_command_in_shell(command = cmd, blocking = True)

		if normal_exit:
			flist = glob.glob(filename.replace('001', '*'))
			flist.sort()
			return flist

		raise OSError(-1, 'error running XSane as [%s]' % cmd)
Example #5
0
	def acquire_pages_into_files(self, delay=None, filename=None):
		"""Call XSane.

		<filename> name part must have format name-001.ext>
		"""
		if filename is None:
			filename = gmTools.get_unique_filename(prefix = 'gm-scan-')

		name, ext = os.path.splitext(filename)
		filename = '%s-001%s' % (name, cXSaneScanner._FILETYPE)
		filename = os.path.abspath(os.path.expanduser(filename))

		cmd = 'xsane --no-mode-selection --save --force-filename "%s" --xsane-rc "%s" %s %s' % (
			filename,
			self.__get_session_xsanerc(),
			gmTools.coalesce(self.device_settings_file, '', '--device-settings %s'),
			gmTools.coalesce(self.default_device, '')
		)
		normal_exit = gmShellAPI.run_command_in_shell(command = cmd, blocking = True)

		if normal_exit:
			flist = glob.glob(filename.replace('001', '*'))
			flist.sort()
			return flist

		raise OSError(-1, 'error running XSane as [%s]' % cmd)
Example #6
0
def _print_files_by_gsprint_exe(filenames=None, verbose=False):
    """Use gsprint.exe from Ghostscript tools. Windows only.

	- docs: http://pages.cs.wisc.edu/~ghost/gsview/gsprint.htm
	- download: http://www.cs.wisc.edu/~ghost/
	"""
    if os.name != 'nt':
        _log.debug('<gsprint.exe> only available under Windows')
        return False
    conf_filename = gmTools.get_unique_filename(
        prefix='gm2gsprint-',
        suffix='.cfg').encode(sys.getfilesystemencoding())
    for filename in filenames:
        conf_file = io.open(conf_filename, mode='wt', encoding='utf8')
        conf_file.write('-color\n')
        conf_file.write('-query\n')  # printer setup dialog
        conf_file.write('-all\n')  # all pages
        conf_file.write('-copies 1\n')
        conf_file.write('%s\n' % os.path.normpath(filename))
        conf_file.close()
        cmd_line = ['gsprint.exe', '-config',
                    conf_filename]  # "gsprint.exe" must be in the PATH
        success, returncode, stdout = gmShellAPI.run_process(cmd_line=cmd_line,
                                                             verbose=verbose)
        if not success:
            return False
    return True
Example #7
0
def _print_files_by_gsprint_exe(filenames=None, verbose=False):
	"""Use gsprint.exe from Ghostscript tools. Windows only.

	- docs: http://pages.cs.wisc.edu/~ghost/gsview/gsprint.htm
	- download: http://www.cs.wisc.edu/~ghost/
	"""
	if os.name != 'nt':
		_log.debug('<gsprint.exe> only available under Windows')
		return False
	conf_filename = gmTools.get_unique_filename (
		prefix = 'gm2gsprint-',
		suffix = '.cfg'
	).encode(sys.getfilesystemencoding())
	for filename in filenames:
		conf_file = io.open(conf_filename, mode = 'wt', encoding = 'utf8')
		conf_file.write('-color\n')
		conf_file.write('-query\n')			# printer setup dialog
		conf_file.write('-all\n')			# all pages
		conf_file.write('-copies 1\n')
		conf_file.write('%s\n' % os.path.normpath(filename))
		conf_file.close()
		cmd_line = ['gsprint.exe', '-config', conf_filename]		# "gsprint.exe" must be in the PATH
		success, returncode, stdout = gmShellAPI.run_process(cmd_line = cmd_line, verbose = verbose)
		if not success:
			return False
	return True
Example #8
0
    def save_to_file(self, aChunkSize=0, filename=None):

        if self._payload[self._idx['data_size']] == 0:
            return None

        if self._payload[self._idx['data_size']] is None:
            return None

        if filename is None:
            filename = gmTools.get_unique_filename(
                prefix='gm-incoming_data_unmatched-')

        success = gmPG2.bytea2file(data_query={
            'cmd':
            'SELECT substring(data from %(start)s for %(size)s) FROM clin.incoming_data_unmatched WHERE pk = %(pk)s',
            'args': {
                'pk': self.pk_obj
            }
        },
                                   filename=filename,
                                   chunk_size=aChunkSize,
                                   data_size=self._payload[
                                       self._idx['data_size']])

        if not success:
            return None

        return filename
Example #9
0
    def get_useful_filename(self, patient=None, make_unique=False, directory=None):
        patient_part = ""
        if patient is not None:
            patient_part = "-%s-" % patient["dirname"]

            # preserve original filename extension if available
        suffix = ".dat"
        if self._payload[self._idx["filename"]] is not None:
            tmp, suffix = os.path.splitext(self._payload[self._idx["filename"]])
            suffix = suffix.strip().replace(" ", "-")
            if suffix == u"":
                suffix = ".dat"

        fname = "gm-doc_part-%s-%s-%s--pg_%s" % (
            patient_part,
            self._payload[self._idx["l10n_type"]].replace(" ", "_"),
            gmDateTime.pydt_strftime(
                self._payload[self._idx["date_generated"]], "%Y-%b-%d", "utf-8", gmDateTime.acc_days
            ),
            self._payload[self._idx["seq_idx"]],
            # ,gmTools.coalesce(self.__curr_node_data['ext_ref'], '', '-%s').replace(' ', '_')
        )

        if make_unique:
            fname = gmTools.get_unique_filename(prefix="%s-" % fname, suffix=suffix, tmp_dir=directory)
        else:
            fname = os.path.join(gmTools.coalesce(directory, u""), fname + suffix)

        return fname
Example #10
0
def download_data_pack_old(url, target_dir=None):

	if target_dir is None:
		target_dir = gmTools.get_unique_filename(prefix = 'gm-dl-')

	_log.debug('downloading [%s]', url)
	_log.debug('unpacking into [%s]', target_dir)

	gmTools.mkdir(directory = target_dir)

	# FIXME: rewrite to use urllib.urlretrieve() and 

	paths = gmTools.gmPaths()
	local_script = os.path.join(paths.local_base_dir, '..', 'external-tools', 'gm-download_data')

	candidates = [u'gm-download_data', u'gm-download_data.bat', local_script, u'gm-download_data.bat']
	args = u' %s %s' % (url, target_dir)

	success = gmShellAPI.run_first_available_in_shell (
		binaries = candidates,
		args = args,
		blocking = True,
		run_last_one_anyway = True
	)

	if success:
		return True, target_dir

	_log.error('download failed')
	return False, None
Example #11
0
File: gmHL7.py Project: sk/gnumed
def format_hl7_file(filename, skip_empty_fields=True, eol=u'\n ', return_filename=False, fix_hl7=False):
	if fix_hl7:
		fixed_name = __fix_malformed_hl7_file(filename)
		hl7_file = io.open(fixed_name, mode = 'rt', encoding = 'utf8')
	else:
		hl7_file = io.open(filename, mode = 'rt', encoding = 'utf8')
	output = format_hl7_message (
		message = hl7_file.read(1024 * 1024 * 5),		# 5 MB max
		skip_empty_fields = skip_empty_fields,
		eol = eol
	)
	hl7_file.close()

	if not return_filename:
		return output

	if eol is None:
		output = u'\n '.join([ u'%s: %s' % ((o[0] + (u' ' * max_len))[:max_len], o[1]) for o in output ])

	out_name = gmTools.get_unique_filename(prefix = 'gm-formatted_hl7-', suffix = u'.hl7')
	out_file = io.open(out_name, mode = 'wt', encoding = 'utf8')
	out_file.write(output)
	out_file.close()

	return out_name
Example #12
0
def download_data_pack_old(url, target_dir=None):

	if target_dir is None:
		target_dir = gmTools.get_unique_filename(prefix = 'gm-dl-')

	_log.debug('downloading [%s]', url)
	_log.debug('unpacking into [%s]', target_dir)

	gmTools.mkdir(directory = target_dir)

	# FIXME: rewrite to use urllib.request.urlretrieve() and 

	paths = gmTools.gmPaths()
	local_script = os.path.join(paths.local_base_dir, '..', 'external-tools', 'gm-download_data')

	candidates = ['gm-download_data', 'gm-download_data.bat', local_script, 'gm-download_data.bat']
	args = ' %s %s' % (url, target_dir)

	success = gmShellAPI.run_first_available_in_shell (
		binaries = candidates,
		args = args,
		blocking = True,
		run_last_one_anyway = True
	)

	if success:
		return True, target_dir

	_log.error('download failed')
	return False, None
Example #13
0
 def export_as_mecard(self, filename=None):
     if filename is None:
         filename = gmTools.get_unique_filename(prefix='gm-praxis-',
                                                suffix='.mcf')
     with io.open(filename, mode='wt', encoding='utf8') as mecard_file:
         mecard_file.write(self.MECARD)
     return filename
Example #14
0
	def export_image2file(self, aChunkSize=0, filename=None):

		if self._payload[self._idx['size']] == 0:
			return None

		if filename is None:
			suffix = None
			# preserve original filename extension if available
			if self._payload[self._idx['filename']] is not None:
				name, suffix = os.path.splitext(self._payload[self._idx['filename']])
				suffix = suffix.strip()
				if suffix == '':
					suffix = None
			# get unique filename
			filename = gmTools.get_unique_filename (
				prefix = 'gm-tag_image-',
				suffix = suffix
			)

		success = gmPG2.bytea2file (
			data_query = {
				'cmd': 'SELECT substring(image from %(start)s for %(size)s) FROM ref.tag_image WHERE pk = %(pk)s',
				'args': {'pk': self.pk_obj}
			},
			filename = filename,
			chunk_size = aChunkSize,
			data_size = self._payload[self._idx['size']]
		)

		if success:
			return filename

		return None
Example #15
0
File: gmHL7.py Project: sk/gnumed
	def export_to_file(self, aChunkSize=0, filename=None):

		if self._payload[self._idx['data_size']] == 0:
			return None

		if self._payload[self._idx['data_size']] is None:
			return None

		if filename is None:
			filename = gmTools.get_unique_filename(prefix = 'gm-incoming_data_unmatched-')

		success = gmPG2.bytea2file (
			data_query = {
				'cmd': u'SELECT substring(data from %(start)s for %(size)s) FROM clin.incoming_data_unmatched WHERE pk = %(pk)s',
				'args': {'pk': self.pk_obj}
			},
			filename = filename,
			chunk_size = aChunkSize,
			data_size = self._payload[self._idx['data_size']]
		)

		if not success:
			return None

		return filename
Example #16
0
def format_hl7_file(filename, skip_empty_fields=True, eol='\n ', return_filename=False, fix_hl7=True):
	if fix_hl7:
		fixed_name = __fix_malformed_hl7_file(filename)
		hl7_file = io.open(fixed_name, mode = 'rt', encoding = 'utf8', newline = '')	# read universal but pass on untranslated
		source = '%s (<- %s)' % (fixed_name, filename)
	else:
		hl7_file = io.open(filename, mode = 'rt', encoding = 'utf8', newline = '')	# read universal but pass on untranslated
		source = filename
	output = format_hl7_message (
		message = hl7_file.read(1024 * 1024 * 5),		# 5 MB max
		skip_empty_fields = skip_empty_fields,
		eol = eol,
		source = source
	)
	hl7_file.close()

	if not return_filename:
		return output

	if eol is None:
		output = '\n '.join([ '%s: %s' % ((o[0] + (' ' * max_len))[:max_len], o[1]) for o in output ])

	out_name = gmTools.get_unique_filename(prefix = 'gm-formatted_hl7-', suffix = '.hl7')
	out_file = io.open(out_name, mode = 'wt', encoding = 'utf8')
	out_file.write(output)
	out_file.close()

	return out_name
Example #17
0
	def _get_vcf(self):
		vcf_fields = [
			u'BEGIN:VCARD',
			u'VERSION:4.0',
			u'KIND:org',
			_(u'FN:%(l10n_unit_category)s %(branch)s of %(l10n_organization_category)s %(praxis)s') % self,
			u'N:%(praxis)s;%(branch)s' % self
		]
		adr = self.address
		if adr is not None:
			vcf_fields.append(u'ADR:;%(subunit)s;%(street)s %(number)s;%(urb)s;%(l10n_region)s;%(postcode)s;%(l10n_country)s' % adr)
		comms = self.get_comm_channels(comm_medium = u'workphone')
		if len(comms) > 0:
			vcf_fields.append(u'TEL;VALUE=uri;TYPE=work:tel:%(url)s' % comms[0])
		comms = self.get_comm_channels(comm_medium = u'email')
		if len(comms) > 0:
			vcf_fields.append(u'EMAIL:%(url)s' % comms[0])
		vcf_fields.append(u'END:VCARD')
		vcf_fname = gmTools.get_unique_filename (
			prefix = 'gm-praxis-',
			suffix = '.vcf'
		)
		vcf_file = io.open(vcf_fname, mode = 'wt', encoding = 'utf8')
		vcf_file.write(u'\n'.join(vcf_fields))
		vcf_file.write(u'\n')
		vcf_file.close()
		return vcf_fname
Example #18
0
def __split_MSH_by_PID(filename):
	"""Assumes:
		- ONE MSH per file
		- utf8 encoding
		- first non-empty line must be MSH line
		- next line must be PID line

		IOW, what's created by __split_hl7_file_by_MSH()
	"""
	_log.debug('splitting single-MSH file [%s] into single-PID files', filename)

	MSH_in = io.open(filename, mode = 'rt', encoding = 'utf8')

	looking_for_MSH = True
	MSH_line = None
	looking_for_first_PID = True
	PID_file = None
	PID_fnames = []
	idx = 0
	for line in MSH_in:
		line = line.strip()
		# ignore empty
		if line == '':
			continue

		# first non-empty line must be MSH
		if looking_for_MSH:
			if line.startswith('MSH|'):
				looking_for_MSH = False
				MSH_line = line + HL7_EOL
				continue
			raise ValueError('HL7 MSH file <%s> does not start with "MSH" line' % filename)
		else:
			if line.startswith('MSH|'):
				raise ValueError('HL7 single-MSH file <%s> contains more than one MSH line' % filename)

		# first non-empty line after MSH must be PID
		if looking_for_first_PID:
			if not line.startswith('PID|'):
				raise ValueError('HL7 MSH file <%s> does not have "PID" line follow "MSH" line' % filename)
			looking_for_first_PID = False

		# start new file if line is PID
		if line.startswith('PID|'):
			if PID_file is not None:
				PID_file.close()
			idx += 1
			out_fname = gmTools.get_unique_filename(prefix = '%s-PID_%s-' % (gmTools.fname_stem(filename), idx), suffix = 'hl7')
			_log.debug('writing message for PID %s to [%s]', idx, out_fname)
			PID_fnames.append(out_fname)
			PID_file = io.open(out_fname, mode = 'wt', encoding = 'utf8', newline = '')
			PID_file.write(MSH_line)
		# else write line to new file
		PID_file.write(line + HL7_EOL)

	if PID_file is not None:
		PID_file.close()
	MSH_in.close()

	return PID_fnames
Example #19
0
	def _get_vcf(self):
		vcf_fields = [
			u'BEGIN:VCARD',
			u'VERSION:4.0',
			u'KIND:org',
			_(u'FN:%(l10n_unit_category)s %(branch)s of %(l10n_organization_category)s %(praxis)s') % self,
			u'N:%(praxis)s;%(branch)s' % self
		]
		adr = self.address
		if adr is not None:
			vcf_fields.append(u'ADR:;%(subunit)s;%(street)s %(number)s;%(urb)s;%(l10n_state)s;%(postcode)s;%(l10n_country)s' % adr)
		comms = self.get_comm_channels(comm_medium = u'workphone')
		if len(comms) > 0:
			vcf_fields.append(u'TEL;VALUE=uri;TYPE=work:tel:%(url)s' % comms[0])
		comms = self.get_comm_channels(comm_medium = u'email')
		if len(comms) > 0:
			vcf_fields.append(u'EMAIL:%(url)s' % comms[0])
		vcf_fields.append(u'END:VCARD')
		vcf_fname = gmTools.get_unique_filename (
			prefix = 'gm_praxis2vcf-',
			suffix = '.vcf'
		)
		vcf_file = io.open(vcf_fname, mode = 'wt', encoding = 'utf8')
		vcf_file.write(u'\n'.join(vcf_fields))
		vcf_file.write(u'\n')
		vcf_file.close()
		return vcf_fname
Example #20
0
	def contribute_translations(item=None):

		do_it = gmGuiHelpers.gm_show_question (
			aTitle = _('Contributing translations'),
			aMessage = _('Do you want to contribute your translations to the GNUmed project ?')
		)
		if not do_it:
			return False

		fname = gmTools.get_unique_filename(prefix = 'gm-db-translations-', suffix = '.sql')
		gmPG2.export_translations_from_database(filename = fname)

		msg = (
			'These are database string translations contributed by a GNUmed user.\n'
			'\n'
			'\tThe GNUmed "%s" Client'
		) % gmI18N.system_locale

		if not gmNetworkTools.compose_and_send_email (
			auth = {'user': gmNetworkTools.default_mail_sender, 'password': '******'},
			sender = 'GNUmed Client <*****@*****.**>',
			receiver = ['*****@*****.**'],
			subject = '<contribution>: database translation',
			message = msg,
			attachments = [[fname, 'text/plain', 'quoted-printable']]
		):
			gmDispatcher.send(signal = 'statustext', msg = _('Unable to send mail. Cannot contribute translations to GNUmed community.') % report, beep = True)
			return False

		gmDispatcher.send(signal = 'statustext', msg = _('Thank you for your contribution to the GNUmed community!'), beep = True)
		return True
Example #21
0
	def export_image2file(self, aChunkSize=0, filename=None):

		if self._payload[self._idx['size']] == 0:
			return None

		if filename is None:
			suffix = None
			# preserve original filename extension if available
			if self._payload[self._idx['filename']] is not None:
				name, suffix = os.path.splitext(self._payload[self._idx['filename']])
				suffix = suffix.strip()
				if suffix == u'':
					suffix = None
			# get unique filename
			filename = gmTools.get_unique_filename (
				prefix = 'gm-tag_image-',
				suffix = suffix
			)

		success = gmPG2.bytea2file (
			data_query = {
				'cmd': u'SELECT substring(image from %(start)s for %(size)s) FROM ref.tag_image WHERE pk = %(pk)s',
				'args': {'pk': self.pk_obj}
			},
			filename = filename,
			chunk_size = aChunkSize,
			data_size = self._payload[self._idx['size']]
		)

		if success:
			return filename

		return None
Example #22
0
    def __write_config_file(self, patient=None):
        xml = """<?xml version="1.0" encoding="UTF-8"?>

<konsultation version="1.1" xmlns="http://gpzk.de/ns/arriba/start-konfiguration">
	<parameter>
		%s
		<idle-timeout>0</idle-timeout>
	</parameter>
	<speicherorte>
		<status>%s</status>
		<ergebnis-xml>%s</ergebnis-xml>
		<ergebnis-pdf>%s</ergebnis-pdf>
	</speicherorte>
</konsultation>
"""
        if patient is None:
            pat_xml = ''
        else:
            active_name = patient.get_active_name()
            pat_xml = """<vorname>%s%s</vorname>
		<nachname>%s</nachname>
		<geschlecht>%s</geschlecht>
		<geburtsdatum>%s</geburtsdatum>""" % (
                active_name['firstnames'],
                gmTools.coalesce(active_name['preferred'], '',
                                 ' (%s)'), active_name['lastnames'],
                gmXdtMappings.map_gender_gm2xdt[patient['gender']],
                patient.get_formatted_dob(format=cArriba._date_format,
                                          none_string='00009999'))

        fname_cfg = gmTools.get_unique_filename(prefix='gm2arriba-',
                                                suffix='.xml')
        fname_status = gmTools.get_unique_filename(prefix='arriba2gm_status-',
                                                   suffix='.xml')
        self.xml_result = gmTools.get_unique_filename(
            prefix='arriba2gm_result-', suffix='.xml')
        self.pdf_result = gmTools.get_unique_filename(
            prefix='arriba2gm_result-', suffix='.pdf')
        xml_file = io.open(fname_cfg,
                           mode='wt',
                           encoding='utf8',
                           errors='replace')
        xml_file.write(
            xml % (pat_xml, fname_status, self.xml_result, self.pdf_result))
        xml_file.close()

        return fname_cfg
Example #23
0
	def export_to_file(self, aChunkSize=0, target_mime=None, target_extension=None, ignore_conversion_problems=False):

		if self._payload[self._idx['is_textual']]:
			return None

		if self._payload[self._idx['data_size']] == 0:
			return None

		filename = gmTools.get_unique_filename(prefix = 'gm-data_snippet-')
		success = gmPG2.bytea2file (
			data_query = {
				'cmd': u'SELECT substring(binary_data from %(start)s for %(size)s) FROM ref.keyword_expansion WHERE pk = %(pk)s',
				'args': {'pk': self.pk_obj}
			},
			filename = filename,
			chunk_size = aChunkSize,
			data_size = self._payload[self._idx['data_size']]
		)

		if not success:
			return None

		if target_mime is None:
			return filename

		if target_extension is None:
			target_extension = gmMimeLib.guess_ext_by_mimetype(mimetype = target_mime)

		target_fname = gmTools.get_unique_filename (
			prefix = 'gm-data_snippet-converted-',
			suffix = target_extension
		)
		_log.debug('attempting conversion: [%s] -> [<%s>:%s]', filename, target_mime, target_fname)
		if gmMimeLib.convert_file (
			filename = filename,
			target_mime = target_mime,
			target_filename = target_fname
		):
			return target_fname

		_log.warning('conversion failed')
		if not ignore_conversion_problems:
			return None

		_log.warning('programmed to ignore conversion problems, hoping receiver can handle [%s]', filename)
		return filename
Example #24
0
	def __init__(self):
		cDrugDataSourceInterface.__init__(self)
		_log.info(cFreeDiamsInterface.version)

		self.__imported_drugs = []

		self.__gm2fd_filename = gmTools.get_unique_filename(prefix = r'gm2freediams-', suffix = r'.xml')
		_log.debug('GNUmed -> FreeDiams "exchange-in" file: %s', self.__gm2fd_filename)
		self.__fd2gm_filename = gmTools.get_unique_filename(prefix = r'freediams2gm-', suffix = r'.xml')
		_log.debug('GNUmed <-> FreeDiams "exchange-out"/"prescription" file: %s', self.__fd2gm_filename)
		paths = gmTools.gmPaths()
		# this file can be modified by the user as needed:
		self.__fd4gm_config_file = os.path.join(paths.home_dir, '.gnumed', 'freediams4gm.conf')
		_log.debug('FreeDiams config file for GNUmed use: %s', self.__fd4gm_config_file)

		self.path_to_binary = None
		self.__detect_binary()
Example #25
0
def get_rand_fname(aDir):
    tmpname = gmTools.get_unique_filename(prefix='',
                                          suffix=time.strftime(
                                              ".%Y%m%d-%H%M%S",
                                              time.localtime()),
                                          tmp_dir=aDir)
    path, fname = os.path.split(tmpname)
    return fname
Example #26
0
def get_ext_ref():
    """This needs *considerably* more smarts."""
    dirname = gmTools.get_unique_filename(prefix='',
                                          suffix=time.strftime(
                                              ".%Y%m%d-%H%M%S",
                                              time.localtime()))
    # extract name for dir
    path, doc_ID = os.path.split(dirname)
    return doc_ID
Example #27
0
def get_ext_ref():
	"""This needs *considerably* more smarts."""
	dirname = gmTools.get_unique_filename (
		prefix = '',
		suffix = time.strftime(".%Y%m%d-%H%M%S", time.localtime())
	)
	# extract name for dir
	path, doc_ID = os.path.split(dirname)
	return doc_ID
Example #28
0
	def __write_config_file(self, patient=None):
		xml = """<?xml version="1.0" encoding="UTF-8"?>

<konsultation version="1.1" xmlns="http://gpzk.de/ns/arriba/start-konfiguration">
	<parameter>
		%s
		<idle-timeout>0</idle-timeout>
	</parameter>
	<speicherorte>
		<status>%s</status>
		<ergebnis-xml>%s</ergebnis-xml>
		<ergebnis-pdf>%s</ergebnis-pdf>
	</speicherorte>
</konsultation>
"""
		if patient is None:
			pat_xml = u''
		else:
			active_name = patient.get_active_name()
			pat_xml = """<vorname>%s%s</vorname>
		<nachname>%s</nachname>
		<geschlecht>%s</geschlecht>
		<geburtsdatum>%s</geburtsdatum>""" % (
			active_name['firstnames'],
			gmTools.coalesce(active_name['preferred'], u'', u' (%s)'),
			active_name['lastnames'],
			gmXdtMappings.map_gender_gm2xdt[patient['gender']],
			patient.get_formatted_dob(format = cArriba._date_format, encoding = u'utf8', none_string = u'00009999')
		)

		fname_cfg = gmTools.get_unique_filename(prefix = 'gm2arriba-', suffix = '.xml')
		fname_status = gmTools.get_unique_filename(prefix = 'arriba2gm_status-', suffix = '.xml')
		self.xml_result = gmTools.get_unique_filename(prefix = 'arriba2gm_result-', suffix = '.xml')
		self.pdf_result = gmTools.get_unique_filename(prefix = 'arriba2gm_result-', suffix = '.pdf')
		xml_file = io.open(fname_cfg, mode = 'wt', encoding = 'utf8', errors = 'replace')
		xml_file.write (xml % (
			pat_xml,
			fname_status,
			self.xml_result,
			self.pdf_result
		))
		xml_file.close()

		return fname_cfg
Example #29
0
    def export_to_file(self,
                       aChunkSize=0,
                       filename=None,
                       target_mime=None,
                       target_extension=None,
                       ignore_conversion_problems=False,
                       directory=None):

        if self._payload[self._idx['size']] == 0:
            return None

        if filename is None:
            filename = self.get_useful_filename(make_unique=True,
                                                directory=directory)

        success = gmPG2.bytea2file(data_query={
            'cmd':
            u'SELECT substring(data from %(start)s for %(size)s) FROM blobs.doc_obj WHERE pk=%(pk)s',
            'args': {
                'pk': self.pk_obj
            }
        },
                                   filename=filename,
                                   chunk_size=aChunkSize,
                                   data_size=self._payload[self._idx['size']])

        if not success:
            return None

        if target_mime is None:
            return filename

        if target_extension is None:
            target_extension = gmMimeLib.guess_ext_by_mimetype(
                mimetype=target_mime)

        target_path, name = os.path.split(filename)
        name, tmp = os.path.splitext(name)
        target_fname = gmTools.get_unique_filename(prefix='%s-converted-' %
                                                   name,
                                                   suffix=target_extension)
        _log.debug('attempting conversion: [%s] -> [<%s>:%s]', filename,
                   target_mime, target_fname)
        if gmMimeLib.convert_file(filename=filename,
                                  target_mime=target_mime,
                                  target_filename=target_fname):
            return target_fname

        _log.warning('conversion failed')
        if not ignore_conversion_problems:
            return None

        _log.warning(
            'programmed to ignore conversion problems, hoping receiver can handle [%s]',
            filename)
        return filename
Example #30
0
def write_generic_vaccine_sql(version, include_indications_mapping=False, filename=None):
	if filename is None:
		filename = gmTools.get_unique_filename(suffix = '.sql')
	_log.debug('writing SQL for creating generic vaccines to: %s', filename)
	sql_file = io.open(filename, mode = 'wt', encoding = 'utf8')
	sql_file.write(create_generic_vaccine_sql (
		version,
		include_indications_mapping = include_indications_mapping
	))
	sql_file.close()
	return filename
Example #31
0
def write_generic_vaccine_sql(version, include_indications_mapping=False, filename=None):
	if filename is None:
		filename = gmTools.get_unique_filename(suffix = '.sql')
	_log.debug('writing SQL for creating generic vaccines to: %s', filename)
	sql_file = open(filename, mode = 'wt', encoding = 'utf8')
	sql_file.write(create_generic_vaccine_sql (
		version,
		include_indications_mapping = include_indications_mapping
	))
	sql_file.close()
	return filename
Example #32
0
def join_files_as_pdf(files: [] = None, pdf_name: str = None) -> str:
    """Convert files to PDF and joins them into one final PDF.

	Returns:
		Name of final PDF or None
	"""
    assert (files is not None), '<files> must not be None'

    if len(files) == 0:
        return None

    sandbox = gmTools.mk_sandbox_dir()
    pdf_pages = []
    page_idx = 1
    for fname in files:
        pdf = convert_file(filename=fname,
                           target_mime='application/pdf',
                           target_filename=gmTools.get_unique_filename(
                               prefix='%s-' % page_idx,
                               suffix='.pdf',
                               tmp_dir=sandbox),
                           target_extension='.pdf',
                           verbose=True)
        if pdf is None:
            return None

        pdf_pages.append(pdf)
        page_idx += 1

    if pdf_name is None:
        pdf_name = gmTools.get_unique_filename(suffix='.pdf')
    cmd_line = ['pdfunite']
    cmd_line.extend(pdf_pages)
    cmd_line.append(pdf_name)
    success, returncode, stdout = gmShellAPI.run_process(cmd_line=cmd_line,
                                                         verbose=True)
    if not success:
        _log.debug('cannot join files into one PDF')
        return None

    return pdf_name
Example #33
0
def aes_encrypt_file(filename=None,
                     passphrase=None,
                     comment=None,
                     verbose=False,
                     remove_unencrypted=False):
    assert (filename is not None), '<filename> must not be None'
    assert (passphrase is not None), '<passphrase> must not be None'

    if len(passphrase) < 5:
        _log.error('<passphrase> must be at least 5 characters/signs/digits')
        return None
    gmLog2.add_word2hide(passphrase)

    #add 7z/winzip url to comment.txt
    _log.debug('attempting 7z AES encryption')
    for cmd in ['7z', '7z.exe']:
        found, binary = gmShellAPI.detect_external_binary(binary=cmd)
        if found:
            break
    if not found:
        _log.warning('no 7z binary found, trying gpg')
        return None

    if comment is not None:
        archive_path, archive_name = os.path.split(os.path.abspath(filename))
        comment_filename = gmTools.get_unique_filename(
            prefix='%s.7z.comment-' % archive_name,
            tmp_dir=archive_path,
            suffix='.txt')
        with open(comment_filename,
                  mode='wt',
                  encoding='utf8',
                  errors='replace') as comment_file:
            comment_file.write(comment)
    else:
        comment_filename = ''
    filename_encrypted = '%s.7z' % filename
    args = [
        binary, 'a', '-bb3', '-mx0',
        "-p%s" % passphrase, filename_encrypted, filename, comment_filename
    ]
    encrypted, exit_code, stdout = gmShellAPI.run_process(cmd_line=args,
                                                          encoding='utf8',
                                                          verbose=verbose)
    gmTools.remove_file(comment_filename)
    if not encrypted:
        return None
    if not remove_unencrypted:
        return filename_encrypted
    if gmTools.remove_file(filename):
        return filename_encrypted
    gmTools.remove_file(filename_encrypted)
    return None
Example #34
0
def export_patients_as_xdt(base_path=None):

    path = gmTools.get_unique_filename(prefix='gm-export-',
                                       suffix='',
                                       tmp_dir=base_path)
    path = os.path.splitext(path)[0]
    gmTools.mkdir(path)

    for ID in gmPerson.get_person_IDs():
        _log.info('exporting patient #%s', ID)
        identity = gmPerson.cPerson(aPK_obj=ID)
        _log.info('identity: %s', identity)
        filename = gmTools.get_unique_filename(prefix='gm_exp-%s-' %
                                               identity.subdir_name,
                                               suffix='.xdt',
                                               tmp_dir=path)
        _log.info('file: %s', filename)
        identity.export_as_gdt(filename=filename,
                               encoding='utf8'
                               #encoding = u'iso-8859-15'
                               )
Example #35
0
	def save_to_file(self, aChunkSize=0, filename=None, target_mime=None, target_extension=None, ignore_conversion_problems=False, directory=None, adjust_extension=False, conn=None):

		if self._payload[self._idx['size']] == 0:
			return None

		if filename is None:
			filename = self.get_useful_filename(make_unique = True, directory = directory)

		success = gmPG2.bytea2file (
			data_query = {
				'cmd': 'SELECT substring(data from %(start)s for %(size)s) FROM blobs.doc_obj WHERE pk=%(pk)s',
				'args': {'pk': self.pk_obj}
			},
			filename = filename,
			chunk_size = aChunkSize,
			data_size = self._payload[self._idx['size']],
			conn = conn
		)
		if not success:
			return None

		if target_mime is None:
			if filename.endswith('.dat'):
				if adjust_extension:
					return gmMimeLib.adjust_extension_by_mimetype(filename)
			return filename

		if target_extension is None:
			target_extension = gmMimeLib.guess_ext_by_mimetype(mimetype = target_mime)

		target_path, name = os.path.split(filename)
		name, tmp = os.path.splitext(name)
		target_fname = gmTools.get_unique_filename (
			prefix = '%s-conv-' % name,
			suffix = target_extension
		)
		_log.debug('attempting conversion: [%s] -> [<%s>:%s]', filename, target_mime, target_fname)
		if gmMimeLib.convert_file (
			filename = filename,
			target_mime = target_mime,
			target_filename = target_fname
		):
			return target_fname

		_log.warning('conversion failed')
		if not ignore_conversion_problems:
			return None

		if filename.endswith('.dat'):
			if adjust_extension:
				filename = gmMimeLib.adjust_extension_by_mimetype(filename)
		_log.warning('programmed to ignore conversion problems, hoping receiver can handle [%s]', filename)
		return filename
Example #36
0
def convert_file(filename=None, target_mime=None, target_filename=None, target_extension=None, verbose=False):
	"""Convert file from one format into another.

		target_mime: a mime type
	"""
	assert (target_mime is not None), '<target_mime> must not be None'
	assert (filename is not None), '<filename> must not be None'
	assert (filename != target_filename), '<target_filename> must be different from <filename>'

	source_mime = guess_mimetype(filename = filename)
	if source_mime.lower() == target_mime.lower():
		_log.debug('source file [%s] already target mime type [%s]', filename, target_mime)
		if target_filename is None:
			return filename

		shutil.copyfile(filename, target_filename)
		return target_filename

	converted_ext = guess_ext_by_mimetype(target_mime)
	if converted_ext is None:
		if target_filename is not None:
			tmp, converted_ext = os.path.splitext(target_filename)
	if converted_ext is None:
		converted_ext = target_extension		# can still stay None
	converted_fname = gmTools.get_unique_filename(suffix = converted_ext)
	_log.debug('attempting conversion: [%s] -> [<%s>:%s]', filename, target_mime, gmTools.coalesce(target_filename, converted_fname))
	script_name = 'gm-convert_file'
	paths = gmTools.gmPaths()
	local_script = os.path.join(paths.local_base_dir, '..', 'external-tools', script_name)
	candidates = [ script_name, local_script ]		#, script_name + u'.bat'
	found, binary = gmShellAPI.find_first_binary(binaries = candidates)
	if not found:
		# try anyway
		binary = script_name# + r'.bat'
	_log.debug('<%s> API: SOURCEFILE TARGET_MIMETYPE TARGET_EXTENSION TARGET_FILENAME' % binary)
	cmd_line = [
		binary,
		filename,
		target_mime,
		converted_ext.lstrip('.'),
		converted_fname
	]
	success, returncode, stdout = gmShellAPI.run_process(cmd_line = cmd_line, verbose = True)
	if not success:
		_log.error('conversion failed')
		return None

	if target_filename is None:
		return converted_fname

	shutil.copyfile(converted_fname, target_filename)
	return target_filename
Example #37
0
def download_file(url, filename=None, suffix=None):
    if filename is None:
        filename = gmTools.get_unique_filename(prefix='gm-dl-', suffix=suffix)
    _log.debug('downloading [%s] into [%s]', url, filename)
    try:
        dl_name, headers = urllib.request.urlretrieve(url, filename)
    except (ValueError, OSError, IOError):
        _log.exception('cannot download from [%s]', url)
        gmLog2.log_stack_trace()
        return None

    _log.debug('%s' % headers)
    return dl_name
Example #38
0
def split_LOINCDBTXT(input_fname=None, data_fname=None, license_fname=None):

    _log.debug('splitting LOINC source file [%s]', input_fname)

    if license_fname is None:
        license_fname = gmTools.get_unique_filename(prefix='loinc_license-',
                                                    suffix='.txt')
    _log.debug('LOINC header: %s', license_fname)

    if data_fname is None:
        data_fname = gmTools.get_unique_filename(prefix='loinc_data-',
                                                 suffix='.csv')
    _log.debug('LOINC data: %s', data_fname)

    loinc_file = io.open(input_fname,
                         mode='rt',
                         encoding=file_encoding,
                         errors='replace')
    out_file = io.open(license_fname,
                       mode='wt',
                       encoding='utf8',
                       errors='replace')

    for line in loinc_file:

        if license_delimiter in line:
            out_file.write(line)
            out_file.close()
            out_file = io.open(data_fname,
                               mode='wt',
                               encoding='utf8',
                               errors='replace')
            continue

        out_file.write(line)

    out_file.close()

    return data_fname, license_fname
Example #39
0
def clipboard2file(check_for_filename=False):

    if wx.TheClipboard.IsOpened():
        return False

    if not wx.TheClipboard.Open():
        return False

    data_obj = wx.TextDataObject()
    got_it = wx.TheClipboard.GetData(data_obj)
    if got_it:
        clipboard_text_content = data_obj.Text
        wx.TheClipboard.Close()
        if check_for_filename:
            try:
                io.open(clipboard_text_content).close()
                return clipboard_text_content
            except IOError:
                _log.exception('clipboard does not seem to hold filename: %s',
                               clipboard_text_content)
        fname = gmTools.get_unique_filename(prefix='gm-clipboard-',
                                            suffix='.txt')
        target_file = io.open(fname, mode='wt', encoding='utf8')
        target_file.write(clipboard_text_content)
        target_file.close()
        return fname

    data_obj = wx.BitmapDataObject()
    got_it = wx.TheClipboard.GetData(data_obj)
    if got_it:
        fname = gmTools.get_unique_filename(prefix='gm-clipboard-',
                                            suffix='.png')
        bmp = data_obj.Bitmap.SaveFile(fname, wx.BITMAP_TYPE_PNG)
        wx.TheClipboard.Close()
        return fname

    wx.TheClipboard.Close()
    return None
Example #40
0
	def get_useful_filename(self, patient=None, make_unique=False, directory=None, include_gnumed_tag=True, date_before_type=False, name_first=True):
		patient_part = ''
		if patient is not None:
			if name_first:
				patient_part = '%s-' % patient.subdir_name
			else:
				patient_part = '-%s' % patient.subdir_name

		# preserve original filename extension if available
		suffix = '.dat'
		if self._payload[self._idx['filename']] is not None:
			tmp, suffix = os.path.splitext (
				gmTools.fname_sanitize(self._payload[self._idx['filename']]).lower()
			)
			if suffix == '':
				suffix = '.dat'

		if include_gnumed_tag:
			fname_template = 'gm_doc-part_%s-%%s' % self._payload[self._idx['seq_idx']]
		else:
			fname_template = '%%s-part_%s' % self._payload[self._idx['seq_idx']]

		if date_before_type:
			date_type_part = '%s-%s' % (
				gmDateTime.pydt_strftime(self._payload[self._idx['date_generated']], '%Y-%m-%d', 'utf-8', gmDateTime.acc_days),
				self._payload[self._idx['l10n_type']].replace(' ', '_').replace('-', '_'),
			)
		else:
			date_type_part = '%s-%s' % (
				self._payload[self._idx['l10n_type']].replace(' ', '_').replace('-', '_'),
				gmDateTime.pydt_strftime(self._payload[self._idx['date_generated']], '%Y-%m-%d', 'utf-8', gmDateTime.acc_days)
			)

		if name_first:
			date_type_name_part = patient_part + date_type_part
		else:
			date_type_name_part = date_type_part + patient_part

		fname = fname_template % date_type_name_part

		if make_unique:
			fname = gmTools.get_unique_filename (
				prefix = '%s-' % gmTools.fname_sanitize(fname),
				suffix = suffix,
				tmp_dir = directory
			)
		else:
			fname = gmTools.fname_sanitize(os.path.join(gmTools.coalesce(directory, gmTools.gmPaths().tmp_dir), fname + suffix))

		return fname
Example #41
0
def __split_hl7_file_by_MSH(filename, encoding='utf8'):

	_log.debug('splitting [%s] into single-MSH files', filename)

	hl7_in = io.open(filename, mode = 'rt', encoding = encoding)

	idx = 0
	first_line = True
	MSH_file = None
	MSH_fnames = []
	for line in hl7_in:
		line = line.strip()
		# first line must be MSH
		if first_line:
			# ignore empty / FHS / BHS lines
			if line == '':
				continue
			if line.startswith('FHS|'):
				_log.debug('ignoring FHS')
				continue
			if line.startswith('BHS|'):
				_log.debug('ignoring BHS')
				continue
			if not line.startswith('MSH|'):
				raise ValueError('HL7 file <%s> does not start with "MSH" line' % filename)
			first_line = False
		# start new file
		if line.startswith('MSH|'):
			if MSH_file is not None:
				MSH_file.close()
			idx += 1
			out_fname = gmTools.get_unique_filename(prefix = '%s-MSH_%s-' % (gmTools.fname_stem(filename), idx), suffix = 'hl7')
			_log.debug('writing message %s to [%s]', idx, out_fname)
			MSH_fnames.append(out_fname)
			MSH_file = io.open(out_fname, mode = 'wt', encoding = 'utf8', newline = '')
		# ignore BTS / FTS lines
		if line.startswith('BTS|'):
			_log.debug('ignoring BTS')
			continue
		if line.startswith('FTS|'):
			_log.debug('ignoring FTS')
			continue
		# else write line to new file
		MSH_file.write(line + HL7_EOL)

	if MSH_file is not None:
		MSH_file.close()
	hl7_in.close()

	return MSH_fnames
Example #42
0
	def get_useful_filename(self, patient=None, make_unique=False, directory=None, include_gnumed_tag=True, date_before_type=False, name_first=True):
		patient_part = ''
		if patient is not None:
			if name_first:
				patient_part = '%s-' % patient.subdir_name
			else:
				patient_part = '-%s' % patient.subdir_name

		# preserve original filename extension if available
		suffix = '.dat'
		if self._payload[self._idx['filename']] is not None:
			tmp, suffix = os.path.splitext (
				gmTools.fname_sanitize(self._payload[self._idx['filename']]).lower()
			)
			if suffix == '':
				suffix = '.dat'

		if include_gnumed_tag:
			fname_template = 'gm_doc-part_%s-%%s' % self._payload[self._idx['seq_idx']]
		else:
			fname_template = '%%s-part_%s' % self._payload[self._idx['seq_idx']]

		if date_before_type:
			date_type_part = '%s-%s' % (
				gmDateTime.pydt_strftime(self._payload[self._idx['date_generated']], '%Y-%m-%d', 'utf-8', gmDateTime.acc_days),
				self._payload[self._idx['l10n_type']].replace(' ', '_').replace('-', '_'),
			)
		else:
			date_type_part = '%s-%s' % (
				self._payload[self._idx['l10n_type']].replace(' ', '_').replace('-', '_'),
				gmDateTime.pydt_strftime(self._payload[self._idx['date_generated']], '%Y-%m-%d', 'utf-8', gmDateTime.acc_days)
			)

		if name_first:
			date_type_name_part = patient_part + date_type_part
		else:
			date_type_name_part = date_type_part + patient_part

		fname = fname_template % date_type_name_part

		if make_unique:
			fname = gmTools.get_unique_filename (
				prefix = '%s-' % gmTools.fname_sanitize(fname),
				suffix = suffix,
				tmp_dir = directory
			)
		else:
			fname = gmTools.fname_sanitize(os.path.join(gmTools.coalesce(directory, gmTools.gmPaths().tmp_dir), fname + suffix))

		return fname
Example #43
0
def __split_hl7_file_by_MSH(filename, encoding='utf8'):

	_log.debug('splitting [%s] into single-MSH files', filename)

	hl7_in = io.open(filename, mode = 'rt', encoding = encoding)

	idx = 0
	first_line = True
	MSH_file = None
	MSH_fnames = []
	for line in hl7_in:
		line = line.strip()
		# first line must be MSH
		if first_line:
			# ignore empty / FHS / BHS lines
			if line == '':
				continue
			if line.startswith('FHS|'):
				_log.debug('ignoring FHS')
				continue
			if line.startswith('BHS|'):
				_log.debug('ignoring BHS')
				continue
			if not line.startswith('MSH|'):
				raise ValueError('HL7 file <%s> does not start with "MSH" line' % filename)
			first_line = False
		# start new file
		if line.startswith('MSH|'):
			if MSH_file is not None:
				MSH_file.close()
			idx += 1
			out_fname = gmTools.get_unique_filename(prefix = '%s-MSH_%s-' % (gmTools.fname_stem(filename), idx), suffix = 'hl7')
			_log.debug('writing message %s to [%s]', idx, out_fname)
			MSH_fnames.append(out_fname)
			MSH_file = io.open(out_fname, mode = 'wt', encoding = 'utf8', newline = '')
		# ignore BTS / FTS lines
		if line.startswith('BTS|'):
			_log.debug('ignoring BTS')
			continue
		if line.startswith('FTS|'):
			_log.debug('ignoring FTS')
			continue
		# else write line to new file
		MSH_file.write(line + HL7_EOL)

	if MSH_file is not None:
		MSH_file.close()
	hl7_in.close()

	return MSH_fnames
Example #44
0
def download_file(url, filename=None, suffix=None):

	if filename is None:
		filename = gmTools.get_unique_filename(prefix = 'gm-dl-', suffix = suffix)
	_log.debug('downloading [%s] into [%s]', url, filename)

	try:
		dl_name, headers = urllib.urlretrieve(url, filename)
	except (ValueError, OSError, IOError):
		_log.exception('cannot download from [%s]', url)
		gmLog2.log_stack_trace()
		return None

	_log.debug(u'%s' % headers)
	return dl_name
Example #45
0
    def export_to_file(
        self,
        aChunkSize=0,
        filename=None,
        target_mime=None,
        target_extension=None,
        ignore_conversion_problems=False,
        directory=None,
    ):

        if self._payload[self._idx["size"]] == 0:
            return None

        if filename is None:
            filename = self.get_useful_filename(make_unique=True, directory=directory)

        success = gmPG2.bytea2file(
            data_query={
                "cmd": u"SELECT substring(data from %(start)s for %(size)s) FROM blobs.doc_obj WHERE pk=%(pk)s",
                "args": {"pk": self.pk_obj},
            },
            filename=filename,
            chunk_size=aChunkSize,
            data_size=self._payload[self._idx["size"]],
        )

        if not success:
            return None

        if target_mime is None:
            return filename

        if target_extension is None:
            target_extension = gmMimeLib.guess_ext_by_mimetype(mimetype=target_mime)

        target_path, name = os.path.split(filename)
        name, tmp = os.path.splitext(name)
        target_fname = gmTools.get_unique_filename(prefix="%s-converted-" % name, suffix=target_extension)
        _log.debug("attempting conversion: [%s] -> [<%s>:%s]", filename, target_mime, target_fname)
        if gmMimeLib.convert_file(filename=filename, target_mime=target_mime, target_filename=target_fname):
            return target_fname

        _log.warning("conversion failed")
        if not ignore_conversion_problems:
            return None

        _log.warning("programmed to ignore conversion problems, hoping receiver can handle [%s]", filename)
        return filename
Example #46
0
	def acquire_pages_into_files(self, delay=None, filename=None):
		if filename is None:
			filename = gmTools.get_unique_filename(prefix = 'gmScannedObj-', suffix = '.bmp')
		else:
			tmp, ext = os.path.splitext(filename)
			if ext != '.bmp':
				filename = filename + '.bmp'

		self.__filename = os.path.abspath(os.path.expanduser(filename))

		if not self.__init_scanner():
			raise OSError(-1, 'cannot init TWAIN scanner device')

		self.__done_transferring_image = False
		self.__scanner.RequestAcquire(True)

		return [self.__filename]
Example #47
0
	def __get_session_xsanerc(self):

		# create an xsanerc for this session
		session_xsanerc = gmTools.get_unique_filename (
			prefix = 'gm-session_xsanerc-',
			suffix = '.conf'
		)
		_log.debug('GNUmed -> XSane session xsanerc: %s', session_xsanerc)

		# our closest bet, might contain umlauts
		enc = gmI18N.get_encoding()
		fread = io.open(self._gm_custom_xsanerc, mode = "rt", encoding = enc)
		fwrite = io.open(session_xsanerc, mode = "wt", encoding = enc)

		paths = gmTools.gmPaths()
		val_dict = {
			'tmp-path': paths.tmp_dir,
			'working-directory': paths.tmp_dir,
			'filename': '<--force-filename>',
			'filetype': cXSaneScanner._FILETYPE,
			'skip-existing-numbers': '1',
			'filename-counter-step': '1',
			'filename-counter-len': '3'
		}

		for idx, line in enumerate(fread):
			line = line.replace('\n', '')
			line = line.replace('\r', '')

			if idx % 2 == 0:			# even lines are keys
				curr_key = line.strip('"')
				fwrite.write('"%s"\n' % curr_key)
			else: 						# odd lines are corresponding values
				try:
					value = val_dict[curr_key]
					_log.debug('replaced [%s] with [%s]', curr_key, val_dict[curr_key])
				except KeyError:
					value = line
				fwrite.write('%s\n' % value)

		fwrite.flush()
		fwrite.close()
		fread.close()

		return session_xsanerc
Example #48
0
    def save_to_file(self,
                     aChunkSize=0,
                     target_mime=None,
                     target_extension=None,
                     ignore_conversion_problems=False):

        if self._payload[self._idx['is_textual']]:
            return None

        if self._payload[self._idx['data_size']] == 0:
            return None

        exported_fname = gmTools.get_unique_filename(prefix='gm-data_snippet-')
        success = gmPG2.bytea2file(data_query={
            'cmd':
            'SELECT substring(binary_data from %(start)s for %(size)s) FROM ref.keyword_expansion WHERE pk = %(pk)s',
            'args': {
                'pk': self.pk_obj
            }
        },
                                   filename=exported_fname,
                                   chunk_size=aChunkSize,
                                   data_size=self._payload[
                                       self._idx['data_size']])

        if not success:
            return None

        if target_mime is None:
            return exported_fname

        converted_fname = gmMimeLib.convert_file(filename=exported_fname,
                                                 target_mime=target_mime)
        if converted_fname is not None:
            return converted_fname

        _log.warning('conversion failed')
        if ignore_conversion_problems:
            _log.warning(
                'programmed to ignore conversion problems, hoping receiver can handle [%s]',
                exported_fname)
            return exported_fname

        return None
Example #49
0
def extract_HL7_from_XML_CDATA(filename, xml_path, target_dir=None):

	_log.debug('extracting HL7 from CDATA of <%s> nodes in XML file [%s]', xml_path, filename)

	# sanity checks/setup
	try:
		open(filename).close()
		orig_dir = os.path.split(filename)[0]
		work_filename = gmTools.get_unique_filename(prefix = 'gm-x2h-%s-' % gmTools.fname_stem(filename), suffix = '.hl7')
		if target_dir is None:
			target_dir = os.path.join(orig_dir, 'HL7')
			done_dir = os.path.join(orig_dir, 'done')
		else:
			done_dir = os.path.join(target_dir, 'done')
		_log.debug('target dir: %s', target_dir)
		gmTools.mkdir(target_dir)
		gmTools.mkdir(done_dir)
	except Exception:
		_log.exception('cannot setup unwrapping environment')
		return None

	hl7_xml = pyxml.ElementTree()
	try:
		hl7_xml.parse(filename)
	except pyxml.ParseError:
		_log.exception('cannot parse [%s]' % filename)
		return None
	nodes = hl7_xml.findall(xml_path)
	if len(nodes) == 0:
		_log.debug('no nodes found for data extraction')
		return None

	_log.debug('unwrapping HL7 from XML into [%s]', work_filename)
	hl7_file = io.open(work_filename, mode = 'wt', encoding = 'utf8', newline = '')		# universal newlines acceptance but no translation on output
	for node in nodes:
#		hl7_file.write(node.text.rstrip() + HL7_EOL)
		hl7_file.write(node.text + '')		# trick to make node.text unicode
	hl7_file.close()

	target_fname = os.path.join(target_dir, os.path.split(work_filename)[1])
	shutil.copy(work_filename, target_dir)
	shutil.move(filename, done_dir)

	return target_fname
Example #50
0
def extract_HL7_from_XML_CDATA(filename, xml_path, target_dir=None):

	_log.debug('extracting HL7 from CDATA of <%s> nodes in XML file [%s]', xml_path, filename)

	# sanity checks/setup
	try:
		open(filename).close()
		orig_dir = os.path.split(filename)[0]
		work_filename = gmTools.get_unique_filename(prefix = 'gm-x2h-%s-' % gmTools.fname_stem(filename), suffix = '.hl7')
		if target_dir is None:
			target_dir = os.path.join(orig_dir, 'HL7')
			done_dir = os.path.join(orig_dir, 'done')
		else:
			done_dir = os.path.join(target_dir, 'done')
		_log.debug('target dir: %s', target_dir)
		gmTools.mkdir(target_dir)
		gmTools.mkdir(done_dir)
	except Exception:
		_log.exception('cannot setup unwrapping environment')
		return None

	hl7_xml = pyxml.ElementTree()
	try:
		hl7_xml.parse(filename)
	except pyxml.ParseError:
		_log.exception('cannot parse [%s]' % filename)
		return None
	nodes = hl7_xml.findall(xml_path)
	if len(nodes) == 0:
		_log.debug('no nodes found for data extraction')
		return None

	_log.debug('unwrapping HL7 from XML into [%s]', work_filename)
	hl7_file = io.open(work_filename, mode = 'wt', encoding = 'utf8', newline = '')		# universal newlines acceptance but no translation on output
	for node in nodes:
#		hl7_file.write(node.text.rstrip() + HL7_EOL)
		hl7_file.write(node.text + '')		# trick to make node.text unicode
	hl7_file.close()

	target_fname = os.path.join(target_dir, os.path.split(work_filename)[1])
	shutil.copy(work_filename, target_dir)
	shutil.move(filename, done_dir)

	return target_fname
Example #51
0
def gpg_decrypt_file(filename=None, verbose=False, target_ext=None):
	"""The system is expected to be set up for safely getting the
	   passphrase from the user, typically via gpg-agent.
	"""
	assert (filename is not None), '<filename> must not be None'

	_log.debug('attempting GPG decryption')
	for cmd in ['gpg2', 'gpg', 'gpg2.exe', 'gpg.exe']:
		found, binary = gmShellAPI.detect_external_binary(binary = cmd)
		if found:
			break
	if not found:
		_log.warning('no gpg binary found')
		return None

	basename = os.path.splitext(filename)[0]
	filename_decrypted = gmTools.get_unique_filename(prefix = '%s-decrypted-' % basename, suffix = target_ext)
	args = [
		binary,
		'--utf8-strings',
		'--display-charset', 'utf-8',
		'--batch',
		'--no-greeting',
		'--enable-progress-filter',
		'--decrypt',
		'--output', filename_decrypted
		##'--use-embedded-filename'				# not all encrypted files carry a filename
	]
	if verbose:
		args.extend ([
			'--verbose', '--verbose',
			'--debug-level', '8',
			'--debug', 'packet,mpi,crypto,filter,iobuf,memory,cache,memstat,trust,hashing,clock,lookup,extprog'
			##'--debug-all',						# will log passphrase
			##'--debug, 'ipc',						# will log passphrase
			##'--debug-level', 'guru',				# will log passphrase
			##'--debug-level', '9',					# will log passphrase
		])
	args.append(filename)
	success, exit_code, stdout = gmShellAPI.run_process(cmd_line = args, verbose = verbose, encoding = 'utf-8')
	if success:
		return filename_decrypted
	return None
Example #52
0
    def contribute_translations(item=None):

        do_it = gmGuiHelpers.gm_show_question(
            aTitle=_('Contributing translations'),
            aMessage=
            _('Do you want to contribute your translations to the GNUmed project ?'
              ))
        if not do_it:
            return False

        fname = gmTools.get_unique_filename(prefix='gm-db-translations-',
                                            suffix='.sql')
        gmPG2.export_translations_from_database(filename=fname)

        msg = (
            u'These are database string translations contributed by a GNUmed user.\n'
            '\n'
            '\tThe GNUmed "%s" Client') % gmI18N.system_locale

        if not gmNetworkTools.send_mail(
                auth={
                    'user': gmNetworkTools.default_mail_sender,
                    'password': u'gnumed-at-gmx-net'
                },
                sender=u'GNUmed Client <*****@*****.**>',
                receiver=[u'*****@*****.**'],
                subject=u'<contribution>: database translation',
                message=msg,
                encoding=gmI18N.get_encoding(),
                attachments=[[fname, u'text/plain', u'quoted-printable']]):
            gmDispatcher.send(
                signal='statustext',
                msg=
                _('Unable to send mail. Cannot contribute translations to GNUmed community.'
                  ) % report,
                beep=True)
            return False

        gmDispatcher.send(
            signal='statustext',
            msg=_('Thank you for your contribution to the GNUmed community!'),
            beep=True)
        return True
Example #53
0
	def save_to_file(self, aChunkSize=0, filename=None, target_mime=None, target_extension=None, ignore_conversion_problems=False, directory=None, adjust_extension=False, conn=None):

		if filename is None:
			filename = self.get_useful_filename(make_unique = True, directory = directory)

		filename = self.__download_to_file(filename = filename)
		if filename is None:
			return None

		if target_mime is None:
			if filename.endswith('.dat'):
				if adjust_extension:
					return gmMimeLib.adjust_extension_by_mimetype(filename)
			return filename

		if target_extension is None:
			target_extension = gmMimeLib.guess_ext_by_mimetype(mimetype = target_mime)

		target_path, name = os.path.split(filename)
		name, tmp = os.path.splitext(name)
		target_fname = gmTools.get_unique_filename (
			prefix = '%s-conv-' % name,
			suffix = target_extension
		)
		_log.debug('attempting conversion: [%s] -> [<%s>:%s]', filename, target_mime, target_fname)
		converted_fname = gmMimeLib.convert_file (
			filename = filename,
			target_mime = target_mime,
			target_filename = target_fname
		)
		if converted_fname is not None:
			return converted_fname

		_log.warning('conversion failed')
		if not ignore_conversion_problems:
			return None

		if filename.endswith('.dat'):
			if adjust_extension:
				filename = gmMimeLib.adjust_extension_by_mimetype(filename)
		_log.warning('programmed to ignore conversion problems, hoping receiver can handle [%s]', filename)
		return filename
Example #54
0
def aes_encrypt_file(filename=None, passphrase=None, comment=None, verbose=False, remove_unencrypted=False):
	assert (filename is not None), '<filename> must not be None'
	assert (passphrase is not None), '<passphrase> must not be None'

	if len(passphrase) < 5:
		_log.error('<passphrase> must be at least 5 characters/signs/digits')
		return None
	gmLog2.add_word2hide(passphrase)

	#add 7z/winzip url to comment.txt
	_log.debug('attempting 7z AES encryption')
	for cmd in ['7z', '7z.exe']:
		found, binary = gmShellAPI.detect_external_binary(binary = cmd)
		if found:
			break
	if not found:
		_log.warning('no 7z binary found, trying gpg')
		return None

	if comment is not None:
		archive_path, archive_name = os.path.split(os.path.abspath(filename))
		comment_filename = gmTools.get_unique_filename (
			prefix = '%s.7z.comment-' % archive_name,
			tmp_dir = archive_path,
			suffix = '.txt'
		)
		with open(comment_filename, mode = 'wt', encoding = 'utf8', errors = 'replace') as comment_file:
			comment_file.write(comment)
	else:
		comment_filename = ''
	filename_encrypted = '%s.7z' % filename
	args = [binary, 'a', '-bb3', '-mx0', "-p%s" % passphrase, filename_encrypted, filename, comment_filename]
	encrypted, exit_code, stdout = gmShellAPI.run_process(cmd_line = args, encoding = 'utf8', verbose = verbose)
	gmTools.remove_file(comment_filename)
	if not encrypted:
		return None
	if not remove_unencrypted:
		return filename_encrypted
	if gmTools.remove_file(filename):
		return filename_encrypted
	gmTools.remove_file(filename_encrypted)
	return None
Example #55
0
	def get_useful_filename(self, patient=None, directory=None):
		patient_part = ''
		if patient is not None:
			patient_part = '-%s' % patient['dirname']

		# preserve original filename extension if available
		suffix = '.dat'
		if self._payload[self._idx['filename']] is not None:
			tmp, suffix = os.path.splitext(self._payload[self._idx['filename']])
			suffix = suffix.strip().replace(' ', '-')
			if suffix == u'':
				suffix = '.dat'

		fname = gmTools.get_unique_filename (
			prefix = 'gm-export_item%s-' % patient_part,
			suffix = suffix,
			tmp_dir = directory
		)

		return os.path.join(directory, fname)
Example #56
0
	def acquire_pages_into_files(self, delay=None, filename=None):
		if filename is None:
			filename = gmTools.get_unique_filename(prefix='gmScannedObj-', suffix='.bmp')
		else:
			tmp, ext = os.path.splitext(filename)
			if ext != '.bmp':
				filename = filename + '.bmp'

		filename = os.path.abspath(os.path.expanduser(filename))

		if delay is not None:
			time.sleep(delay)
			_log.debug('some sane backends report device_busy if we advance too fast. delay set to %s sec' % delay)

		_log.debug('Trying to get image from scanner into [%s] !' % filename)
		self.__scanner.start()
		img = self.__scanner.snap()
		img.save(filename)

		return [filename]