Ejemplo n.º 1
0
    def _check_user_experience(self, login, user_right_id_list):
        last_usage_call = PPMSAPICalls.NewCall(calling_mode)
        get_usage_info = last_usage_call.getLastUsage(login)
        last_usage_list = []
        last_training_list = []

        for usage_entry in get_usage_info:
            if usage_entry['id'] in user_right_id_list:
                if usage_entry['last res'] != 'n/a':
                    last_usage_list.append(
                        datetime.strptime(usage_entry['last res'], '%Y/%m/%d'))
                if usage_entry['last train'] != 'n/a':
                    last_training_list.append(
                        datetime.strptime(usage_entry['last train'],
                                          '%Y/%m/%d'))
        try:
            last_usage_date = max(last_usage_list)
            days_since_last_usage = self._current_date - max(last_usage_list)
            recent_usage = days_since_last_usage < timedelta(days=730)
            last_usage_date = datetime.strftime(last_usage_date, '%d/%m/%Y')
        except ValueError:
            recent_usage = False
            last_usage_date = 'n/a'
        try:
            days_since_last_training = self._current_date - max(
                last_training_list)
            recent_training = days_since_last_training < timedelta(days=730)
        except ValueError:
            recent_training = False

        active_within_2y = recent_usage or recent_training
        training_year_list = [td.year for td in last_training_list]
        return active_within_2y, training_year_list, last_usage_date
Ejemplo n.º 2
0
    def _get_active_users(self):

        # get all logins in PPMS, for accounts with the 'active' flag set
        active_user_call = PPMSAPICalls.NewCall(calling_mode)
        active_user_logins = active_user_call.getAllUsers(True)

        user_list = []
        for login in active_user_logins:
            # check if account is not an account to ignore
            if (login not in self.ignored_login_list):

                # get the microscopes with enabled user rights, for the given account, generate a microscope id list
                microscopes_with_user_right_list = equipment.microscope_list_with_user_rights(
                    login)
                microscope_ids_with_user_right_list = [
                    m.id for m in microscopes_with_user_right_list
                ]

                # check whether the user has been working or been trained on a microscope in the last two years,
                # get the years when the user has been trained and the date of the last activity
                active_within_2years, training_year_list, last_usage = self._check_user_experience(
                    login, microscope_ids_with_user_right_list)

                # if the user has shown activity in the last two years, create an user object,
                # add it to the microscope.user_list and the ActiveBICUsers.user_list
                if active_within_2years:
                    active_user = BICUser(login,
                                          microscopes_with_user_right_list,
                                          last_usage, training_year_list)
                    user_list.append(active_user)
                    for microscope in microscopes_with_user_right_list:
                        microscope.add_user(active_user)
        return user_list
Ejemplo n.º 3
0
    def _get_active_user_rights(self):

        user_rights_call = PPMSAPICalls.NewCall(calling_mode)
        user_rights = user_rights_call.getUserRights(system_id=self.id)

        login_list = []
        for user_right in user_rights:
            user_right = user_right.split(',')
            if ('D' != user_right[0]) and ('.' in user_right[1]):
                login_list.append(user_right[1].strip('"'))
        return login_list
Ejemplo n.º 4
0
	def run(self):
		
		def receive_data(sock):	# Read message length and unpack it into an integer
			raw_msglen = recvall(sock, 4)
			if not raw_msglen:
				return None
			msglen = struct.unpack('>I', raw_msglen)[0]
			# Read the message data
			return recvall(sock, msglen)

		def recvall(sock, n): # Helper function to recv n bytes or return None if EOF is hit
			data = ''
			while len(data) < n:
				packet = sock.recv(n - len(data))
				if not packet:
					return None
				data += packet
			return data
	
		encrypted_call = receive_data(self.connection)

		# try to decrypt and unpickle; closes connection after 1 sec, if e.g. wrong key was used,
		try:
			iv2 = encrypted_call[:AES.block_size]
			ciphered_msg = encrypted_call[AES.block_size:]
			decryptor = AES.new(self.AES_key, AES.MODE_CFB, iv2)
			decrypted_message = decryptor.decrypt(ciphered_msg)
			parameters = pickle.loads(decrypted_message)
		except:
			time.sleep(1)
			self.connection.close()
		else:
			call_to_Paris = PPMSAPICalls.NewCall('PPMS API')

			try:
				response = call_to_Paris._performCall(parameters)
			except Errors.APIError as e:
				response = e

			response_from_Paris = pickle.dumps(response)

			iv = Random.new().read(AES.block_size)
			encryptor = AES.new(self.AES_key, AES.MODE_CFB, iv)
			encrypted_data = iv + encryptor.encrypt(response_from_Paris)
			data_from_Paris = struct.pack('>I', len(encrypted_data)) + encrypted_data

			# if client disconnects during sending data, close connection
			try:
				self.connection.sendall(data_from_Paris)
			except:
				self.connection.close()
Ejemplo n.º 5
0
 def _get_user_rights(self, user_login):
     get_user_rights = PPMSAPICalls.NewCall(calling_mode)
     user_right_microscope_list = []
     try:
         user_rights = get_user_rights.getUserRights(login=user_login)
     # TODO: Somehow 'except Errors.APIError:' does not catch the exception raised in PPMSAPICalls._performCall (l49)
     except Exception:
         return user_right_microscope_list
     else:
         for user_right in user_rights:
             user_right = user_right.split(',')
             if 'D' != user_right[0]:
                 for microscope in self._microscope_list:
                     if microscope.id == user_right[1]:
                         user_right_microscope_list.append(microscope)
                         break
     return user_right_microscope_list
Ejemplo n.º 6
0
    def _get_bic_systems(self):
        def identify_active_systems(ppms_system_string):
            ppms_system_info = ppms_system_string.split(',')
            # check if a system is active, and needs to set to novice
            if 'True' == ppms_system_info[5] and int(
                    ppms_system_info[1]) in Equipment.system_ids:
                new_system = Instrument(
                    ppms_system_info[1],
                    ppms_system_info[3].strip('"'),
                    ppms_system_info[2].strip('"'),
                    None,
                )
                return new_system

        ppms_system_call = PPMSAPICalls.NewCall(calling_mode)
        ppms_system_list = ppms_system_call.getSystems()

        for system in ppms_system_list:
            instrument = identify_active_systems(system)
            if instrument:
                self.active_system_list.append(instrument)
Ejemplo n.º 7
0
    def _get_bic_microscopes(self):
        def get_system_status(system_id):
            sys_stat = None
            if system_id in self._central_microscope_ids:
                sys_stat = 'central'
            if system_id in self._decentral_microscope_ids:
                sys_stat = 'decentral'
            if system_id in self._external_tracked_microscope_ids:
                sys_stat = 'external'
            return sys_stat

        def identify_microscopes(ppms_system_string):
            ppms_system_info = ppms_system_string.split(',')

            # check if system is a microscope, and if it is active
            if 'Microscope' in ppms_system_info[
                    2] and 'True' == ppms_system_info[5]:
                start_index = ppms_system_info[2].index('(')
                stop_index = ppms_system_info[2].index(')')

                system_type = ppms_system_info[2][start_index + 1:stop_index]
                system_status = get_system_status(int(ppms_system_info[1]))

                if system_status:
                    new_microscope = Instrument(
                        ppms_system_info[1],
                        ppms_system_info[3].strip('"'),
                        system_type,
                        system_status,
                    )
                    return new_microscope

        ppms_system_call = PPMSAPICalls.NewCall(calling_mode)
        ppms_system_list = ppms_system_call.getSystems()

        for system in ppms_system_list:
            instrument = identify_microscopes(system)
            if instrument:
                self.microscope_list.append(instrument)
Ejemplo n.º 8
0
 def _populate_group_info(self):
     group_info_call = PPMSAPICalls.NewCall(calling_mode)
     full_group_info = group_info_call.getGroupFullInfo(self.id)
     return full_group_info['unitbcode'], full_group_info[
         'unitname'], full_group_info['department']
Ejemplo n.º 9
0
 def _get_user_full_info(self):
     user_info_call = PPMSAPICalls.NewCall(calling_mode)
     return user_info_call.getUserFullInfo(self.login)
else:
    year = str(args.year)

save_dir = os.path.join(OPTIONS.getValue('save_dir'), year)
if not os.path.isdir(save_dir):
    os.mkdir(save_dir)

# read list of already downloaded references, to be skipped
with open(OPTIONS.getValue('PMID_knownlist'), 'r') as knownlist:
    PMID_known = knownlist.readlines()
PMID_known = [PMID.strip('\n') for PMID in PMID_known]

# from the PPMS database retrieve group PIs and users belonging to that group, query Pubmed for publications authored by PI and each user
new_publications = []

get_groups = PPMSAPICalls.NewCall('PPMS API')
group_list = get_groups.getGroupList()

for group in group_list:
    get_groupPI = PPMSAPICalls.NewCall('PPMS API')
    try:
        group_head = unidecode.unidecode(get_groupPI.getGroupPI(group))
        get_user_API = PPMSAPICalls.NewCall('PPMS API')
        users = get_user_API.getGroupUsers(group)
    except Exception:
        pass

    for user in users:
        try:
            user_call_API = PPMSAPICalls.NewCall('PPMS API')
            user_name = user_call_API.getUserFullName(user)
Ejemplo n.º 11
0
publication_dir = 'N:\\Facility\\temperature_logger\\Publication_Tracker\\Publications'

list_of_years = sorted(
    filter(os.path.isdir, [
        os.path.join(publication_dir, subdir)
        for subdir in os.listdir(publication_dir)
    ]))
workbook = xlsxwriter.Workbook(
    os.path.join(publication_dir, 'publications_by_group.xlsx'))
bold = workbook.add_format({'bold': True})
labels = ('Authors', 'Title', 'Journal', 'EpubDate', 'URL')

sheets_to_PIs = {}

get_groups = PPMSAPICalls.NewCall('PPMS API')
group_list = get_groups.getGroupList()
get_groupPI = PPMSAPICalls.NewCall('PPMS API')
group_heads = [
    unidecode.unidecode(get_groupPI.getGroupPI(group)).split(', ')[0]
    for group in group_list
]
# group_heads = ['May', 'Leist', 'Groettrup', 'Dietrich', 'Kroth', 'Mayer', 'Gross', 'Sturmer', 'Burkle', 'Scheffner', 'Adamska', 'Mecking', 'Begemann', 'Galizia', 'Kleineidam', 'Marx', 'Brunner', 'Thum', 'Wittmann', 'Colfen', 'Drescher', 'Farhan', 'Frickey', 'May', 'Hartig', 'Leitenstorfer', 'Zumbusch', 'Hauck', 'Groth', 'FlowKon', 'Meyer', 'Bottcher', 'Spiteller', 'Legler', 'Hutteroth', 'Wikelski', 'Deuerling', 'Gebauer', 'Wittemann', 'Laumann', 'Schink', 'Polarz', 'Isono', 'Rossy', 'Schmidt-Mende', 'Rothhaupt', 'Kratochwil', 'Funck', 'Couzin', 'Hauser', 'Becks']

PI_publications = {}
for group_head in group_heads:
    PI_publications[group_head] = []
PI_publications['other'] = []

for year_dir in list_of_years:
    file_list = filter(lambda x: x.endswith('.txt'), os.listdir(year_dir))
Ejemplo n.º 12
0
# print get_user_rights.getUserRights('alexander.finke')
#
#
# get_username = PPMSAPICalls.NewCall(calling_mode)
# user_name = get_username.getUserFullName('martin.stoeckl')
# print user_name
#
# get_userexp = PPMSAPICalls.NewCall(calling_mode)
# print get_userexp.getExperience('martin.stoeckl', system_id)
#
# get_userid = PPMSAPICalls.NewCall(calling_mode)
# user_id = get_userid.getUserID(user_name, facility_id)
# print user_id
#
# # make_booking = PPMSAPICalls.NewCall(calling_mode)
# # make_booking.makeBooking('2017-08-22T18:00:00', '2017-08-22T20:00:00', '2017-08-04T17:00:00', user_id, system_id, facility_id)
#
# get_groups = PPMSAPICalls.NewCall(calling_mode)
# grouplist = get_groups.getGroupList()
# for group in grouplist:
# 	get_group = PPMSAPICalls.NewCall(calling_mode)
# 	print get_group.getGroupPI(group)
# 	get_user = PPMSAPICalls.NewCall(calling_mode)
# 	users = get_group.getGroupUsers(group)
# 	print users

get_group = PPMSAPICalls.NewCall(calling_mode)
print(get_group.getGroupFullInfo('mikhail.fonin'))


Ejemplo n.º 13
0
        print('--------------------')


def set_userright_novice(ppms_call, system_obj):
    with Timer(f'Setting users of {system_obj.name} to Novice...', 'Done!'):
        for user_login in system_obj.unfiltered_login_list:
            try:
                ppms_call.setUserRight(system_obj.id, user_login, 'N')
                print(f'{user_login} set to Novice on {system_obj.name}!')
            except Errors.APIError as e:
                print(
                    f'Error: Setting{user_login} to Novice on {system_obj.name} failed!'
                )
                print(f'Cause: {e.msg}')


SYSTEM_OPTIONS = Options.OptionReader('SystemOptions.txt')
calling_mode = SYSTEM_OPTIONS.getValue('calling_mode')

with Timer('Getting facility system info from PPMS...',
           'Microscope list populated!'):
    equipment = Equipment()

# print_microscope_users(equipment.active_system_list)

set_novice_call = PPMSAPICalls.NewCall(calling_mode)
with Timer('Setting user_rights to novice...',
           'All user rights set to novice!'):
    for system in equipment.active_system_list:
        set_userright_novice(set_novice_call, system)
Ejemplo n.º 14
0
from lib import Options, PPMSAPICalls, Errors

try:
	current_directory = os.path.dirname(__file__)
	parent_directory = os.path.split(current_directory)[0]
	print(parent_directory)
	SYSTEM_OPTIONS = Options.OptionReader(parent_directory + '/SystemOptions.txt')
except Errors.FatalError as e:
	exit(e.msg)

facility_id = SYSTEM_OPTIONS.getValue('PPMS_facilityid')
system_id = SYSTEM_OPTIONS.getValue('PPMS_systemid')
calling_mode = SYSTEM_OPTIONS.getValue('calling_mode')
user_login = SYSTEM_OPTIONS.getValue('user_login')

get_systemname = PPMSAPICalls.NewCall(calling_mode, SYSTEM_OPTIONS)
try:
	system_name = get_systemname.getSystemName(system_id)
	print(system_name)
except Errors.APIError as e:
	print(e.msg)

get_booking = PPMSAPICalls.NewCall(calling_mode, SYSTEM_OPTIONS)
print(get_booking.getTodaysBookings(facility_id, system_name))

get_username = PPMSAPICalls.NewCall(calling_mode, SYSTEM_OPTIONS)
user_name = get_username.getUserFullName(user_login)
print(user_name)

test_date = datetime.date.today() - datetime.timedelta(days=10)
for _ in range(10):