esme.py 10.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 24 15:35:04 2017

@author: Lorenz Steinert
"""

import os
Lorenz Steinert's avatar
Lorenz Steinert committed
10
import re
Lorenz Steinert's avatar
Lorenz Steinert committed
11
import sys
Lorenz Steinert's avatar
Lorenz Steinert committed
12
13
import time
import codecs
Lorenz Steinert's avatar
Lorenz Steinert committed
14
import configparser
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import ldap3 as ldap

try:
    import pwd
except ImportError:
    import getpass
    pwd = None


def current_user():
    """get the current user"""
    if pwd:
        return pwd.getpwuid(os.geteuid()).pw_name
    return getpass.getuser()


31
class FsrLdap:
32
33
    """Class die die protokoll .tex datei erstellt"""

34
    def __init__(self, server, base, debug=False, timeout=1):
35
36
        self.debug = debug

37
        self.server = ldap.Server(server,
Lorenz Steinert's avatar
Lorenz Steinert committed
38
                                  connect_timeout=timeout)
39
        self.base = base
40

41
    def get_protokollant_ldap(self, config):
42
43
44
45
46
47
        """search the LDAP for the current user"""
        print("Fetching Protokollant from LDAP ...")
        try:
            conn = ldap.Connection(self.server)
            conn.bind()
            fil = "(uid="+current_user()+")"
48
            if conn.search('ou=people,' + self.base, fil,
Lorenz Steinert's avatar
Lorenz Steinert committed
49
                           attributes=['displayName']):
50
                return " ".join(str(conn.entries[0]['displayName']).split(", ")[::-1])
51
            return get_protokollant(config)
52
53
        except ldap.core.exceptions.LDAPException as error_message:
            if self.debug:
Lorenz Steinert's avatar
Lorenz Steinert committed
54
55
                print("Couldn't Connect to ldap.\n \
                      Using fallback default.\n%s\n" % error_message)
56
57
            else:
                print("Couldn't Connect to ldap.\nUsing fallback default.\n")
58
            return get_protokollant(config)
59

Lorenz Steinert's avatar
Lorenz Steinert committed
60
    def get_fsr_ldap(self, share_dir):
61
62
63
64
65
66
        """get fsr from LDAP"""
        print("Fetching FSR from LDAP ...")
        try:
            conn = ldap.Connection(self.server)
            conn.bind()
            fil = '(cn=intern)'
Lorenz Steinert's avatar
Lorenz Steinert committed
67
            fsr = []
68
69
70
71
72
            if conn.search('ou=group,'+self.base, fil,
                           attributes=['memberUid']):
                for i in conn.entries[0]['memberUid']:
                    if conn.search('ou=people,' + self.base,
                                   '(uid='+i+')', attributes=['displayName']):
Lorenz Steinert's avatar
Lorenz Steinert committed
73
74
75
76
77
                        fsr += [str(conn.entries[0]['displayName'])]
                fsr.sort()
                fsr = [" ".join(i.split(', ')[::-1]) for i in fsr]
                return fsr
            return get_fallback_fsr(share_dir)
78
79
        except ldap.core.exceptions.LDAPException as error_message:
            if self.debug:
Lorenz Steinert's avatar
Lorenz Steinert committed
80
81
                print("Couldn't Connect to ldap.\n \
                      Using fallback File.\n%s\n" % error_message)
82
83
            else:
                print("Couldn't Connect to ldap.\nUsing fallback File.\n")
Lorenz Steinert's avatar
Lorenz Steinert committed
84
            return get_fallback_fsr(share_dir)
85

Lorenz Steinert's avatar
Lorenz Steinert committed
86
    def get_fsr_extern_ldap(self, share_dir):
87
88
89
90
91
92
        """get the EFSR from LDAP"""
        print("Fetching EFSR from LDAP ...")
        try:
            conn = ldap.Connection(self.server)
            conn.bind()
            fil = '(cn=extern)'
Lorenz Steinert's avatar
Lorenz Steinert committed
93
            fsr_extern = []
94
95
96
97
98
            if conn.search('ou=group,'+self.base, fil,
                           attributes=['memberUid']):
                for i in conn.entries[0]['memberUid']:
                    if conn.search('ou=people,' + self.base,
                                   '(uid='+i+')', attributes=['displayName']):
Lorenz Steinert's avatar
Lorenz Steinert committed
99
100
101
102
103
                        fsr_extern += [str(conn.entries[0]['displayName'])]
                fsr_extern.sort()
                fsr_extern = [" ".join(i.split(', ')[::-1]) for i in fsr_extern]
                return fsr_extern
            return get_fallback_fsr_extern(share_dir)
104
105
        except ldap.core.exceptions.LDAPException as error_message:
            if self.debug:
Lorenz Steinert's avatar
Lorenz Steinert committed
106
107
                print("Couldn't Connect to ldap.\n \
                      Using fallback File.\n%s\n" % error_message)
108
109
            else:
                print("Couldn't Connect to ldap.\nUsing fallback File.\n")
Lorenz Steinert's avatar
Lorenz Steinert committed
110
111
112
113
114
            return get_fallback_fsr_extern(share_dir)


def get_fallback_fsr(share_dir):
    """get fsr form fallback file"""
115
116
117
118
119
120
121
122
123
124
125
126
    if os.path.isfile(os.path.join(share_dir, 'fsr')):
        return sorted([re.sub(re.escape('\t'), ' ',
                              line.rstrip('\n'))
                       for line in codecs.open(os.path.join(share_dir,
                                                            'fsr'),
                                               'r',
                                               'utf-8').readlines()],
                      key=lambda x: ''.join(x.split(' ')[::-1]))
    else:
        print(os.path.abspath(os.path.join(share_dir, 'fsr'))
              + ' not found. Using empty FSR.')
        return []
Lorenz Steinert's avatar
Lorenz Steinert committed
127
128
129
130


def get_fallback_fsr_extern(share_dir):
    """get fsr_extern from fallback file"""
131
132
133
134
135
136
137
138
139
140
141
142
    if os.path.isfile(os.path.join(share_dir, 'fsr_extern')):
        return sorted([re.sub(re.escape('\t'), ' ',
                              line.rstrip('\n'))
                       for line in codecs.open(os.path.join(share_dir,
                                                            'fsr_extern'),
                                               'r',
                                               'utf-8').readlines()],
                      key=lambda x: ''.join(x.split(' ')[::-1]))
    else:
        print(os.path.abspath(os.path.join(share_dir, 'fsr_extern'))
              + ' not found. Using empty FSR_extern.')
        return []
143

Lorenz Steinert's avatar
Lorenz Steinert committed
144

145
146
147
def get_sprecher(config=None):
    """get sprecher from user input or config"""
    if config:
148
        sprecher = config['PROTOKOLL']['Sprecher']
149
150
    else:
        sprecher = ''
151
152
153
154
155
    stmp = input("Sprecher ["+sprecher+"]: ")
    if stmp != "":
        return stmp
    return sprecher

Lorenz Steinert's avatar
Lorenz Steinert committed
156

157
158
159
def get_protokollant(config=None):
    """get protokollant from user input or config"""
    if config:
160
        protokollant = config['PROTOKOLL']['Protokollant']
161
162
    else:
        protokollant = ''
163
164
165
166
167
    ptmp = input("Protokollant ["+protokollant+"]: ")
    if ptmp != "":
        return ptmp
    return protokollant

Lorenz Steinert's avatar
Lorenz Steinert committed
168

Lorenz Steinert's avatar
Lorenz Steinert committed
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def get_date(test=False):
    """get current date then ask user"""
    if test:
        date = ('01.01.2000', '2000', '01', '01')
    else:
        year = str(time.localtime()[0])
        mon = str(time.localtime()[1])
        if len(mon) < 2:
            mon = "0"+mon
        day = str(time.localtime()[2])
        if len(day) < 2:
            day = "0"+day
        date = (day + '.' + mon + '.' + year, year, mon, day)

183
184
185
    dtmp = input("Datum ["+date[0]+"]: ")
    if dtmp != "":
        day, mon, year = dtmp.split('.')
Lorenz Steinert's avatar
Lorenz Steinert committed
186
187
188
189
        if len(mon) < 2:
            mon = "0" + mon
        if len(day) < 2:
            day = "0" + day
190
191
        date = day + "." + mon + "." + year
        return (date, year, mon, day)
Lorenz Steinert's avatar
Lorenz Steinert committed
192

193
194
    return date

Lorenz Steinert's avatar
Lorenz Steinert committed
195

196
197
198
199
200
201
def get_editor(editor):
    """get the editor to use from user input"""
    etmp = input("Editor ["+editor+"]: ")
    if etmp != "":
        return etmp
    return editor
Lorenz Steinert's avatar
Lorenz Steinert committed
202
203


Lorenz Steinert's avatar
Lorenz Steinert committed
204
205
def get_config(rundir, config_path=None, default=False):
    """get the location of the config file and load configparser"""
Lorenz Steinert's avatar
Lorenz Steinert committed
206
207
208
209
210
211
212
213
    if config_path:
        if os.path.isfile(config_path):
            config = configparser.ConfigParser()
            config.read(config_path)
            return config
        else:
            print(config_path + ': Not a file')
            sys.exit(2)
Lorenz Steinert's avatar
Lorenz Steinert committed
214
215
216
217
218
219
220
221
222
223
224
225
    elif default:
        if os.path.isfile(os.path.join(rundir, '../etc/proto.ini.default')):
            config = configparser.ConfigParser()
            config.read(os.path.join(rundir, '../etc/proto.ini.default'))
            return config
        else:
            print('No default File found at '
                  + os.path.abspath(os.path.join(rundir,
                                                 '../etc/proto.ini.default')))
            sys.exit(1)
    elif os.path.isfile(os.path.join(rundir,
                                     '../etc/proto.ini')) and not default:
Lorenz Steinert's avatar
Lorenz Steinert committed
226
227
228
        config = configparser.ConfigParser()
        config.read(os.path.join(rundir, '../etc/proto.ini'))
        return config
229
230
231
232
233
    elif os.path.isfile(os.path.join(rundir, '../etc/proto.ini.default')):
        print('No non default ini file found using default.')
        config = configparser.ConfigParser()
        config.read(os.path.join(rundir, '../etc/proto.ini.default'))
        return config
Lorenz Steinert's avatar
Lorenz Steinert committed
234
    else:
235
        print('No ini file found. Using hardcoded defaults.')
Lorenz Steinert's avatar
Lorenz Steinert committed
236
237
238
239
        return None


def get_share(rundir, config=None, sharedir=None):
Lorenz Steinert's avatar
Lorenz Steinert committed
240
    """get the location of the share directory"""
Lorenz Steinert's avatar
Lorenz Steinert committed
241
242
243
244
245
246
247
    if sharedir:
        if os.path.isdir(sharedir):
            return sharedir
        else:
            print(sharedir + ': Not a Directory')
            sys.exit(2)
    elif config:
248
249
        if os.path.isdir(config['PROTOKOLL']['share']):
            return config['PROTOKOLL']['share']
Lorenz Steinert's avatar
Lorenz Steinert committed
250
        else:
251
            print(config['PROTOKOLL']['share'] + ': Not a Directory')
Lorenz Steinert's avatar
Lorenz Steinert committed
252
253
254
255
            sys.exit(2)
    elif os.path.isdir(os.path.join(rundir, '../share')):
        return os.path.join(rundir, '../share')
    else:
Lorenz Steinert's avatar
Lorenz Steinert committed
256
257
        print('No share Directory found at '
              + os.path.abspath(os.path.join(rundir, '../share')))
Lorenz Steinert's avatar
Lorenz Steinert committed
258
259
260
261
        sys.exit(1)


def get_path(rundir, config=None, path=None):
Lorenz Steinert's avatar
Lorenz Steinert committed
262
    """get the location of the protokoll directory"""
Lorenz Steinert's avatar
Lorenz Steinert committed
263
264
265
266
267
268
269
    if path:
        if os.path.isdir(path):
            return path
        else:
            print(path + ': Not a Directory')
            sys.exit(2)
    elif config:
270
271
        if os.path.isdir(config['PROTOKOLL']['path']):
            return config['PROTOKOLL']['path']
Lorenz Steinert's avatar
Lorenz Steinert committed
272
        else:
273
            print(config['PROTOKOLL']['path'] + ': Not a Directory')
Lorenz Steinert's avatar
Lorenz Steinert committed
274
275
276
277
            sys.exit(2)
    elif os.path.isdir(os.path.join(rundir, '../..')):
        return os.path.join(rundir, '../..')
    else:
Lorenz Steinert's avatar
Lorenz Steinert committed
278
279
        print('No Protokoll Directory found at '
              + os.path.abspath(os.path.join(rundir, '../..')))
Lorenz Steinert's avatar
Lorenz Steinert committed
280
        sys.exit(1)
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300

def get_ldap_server(config=None, server=None):
    """get the ldap server for the fsr lookup"""
    if server:
        return server
    elif config:
        return config['SERVER']['NAME']
    else:
        print("No LDAP Server supplied. Triing to use \"rincwind.fs.physik.uni-kl.de\".")
        return "rincewind.fs.physik.uni-kl.de"

def get_ldap_base(config=None, base=None):
    """get the search base for the ldap server"""
    if base:
        return base
    elif config:
        return config['SERVER']['BASE']
    else:
        print("No LDAP search base supplied. Triing to use \"dc=fs,dc=physik,dc=uni-kl,dc=de\".")
        return "dc=fs,dc=physik,dc=uni-kl,dc=de"
301
302
303
304
305
306
307
308
309

def get_server_timeout(config=None, test=None):
    """get the timeout for the connection to the ldap server"""
    if test:
        return 1
    elif config:
        return config['SERVER'].getint('connect_timeout')
    else:
        return 10