tools.py 8.37 KB
Newer Older
HUC Stéphane's avatar
HUC Stéphane committed
1
#!/usr/bin/env python3
HUC Stéphane's avatar
HUC Stéphane committed
2
3
4
5
6
7
8
9
10
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-

#
# # Authors informations
#
# @author: HUC Stéphane
# @email: <devs@stephane-huc.net>
# @url: http://stephane-huc.net
#
11
# @license : OpenBSD
HUC Stéphane's avatar
HUC Stéphane committed
12
13
#

14
''' Tools needed '''
HUC Stéphane's avatar
HUC Stéphane committed
15

16
from bs4 import BeautifulSoup
HUC Stéphane's avatar
HUC Stéphane committed
17
import os
HUC Stéphane's avatar
HUC Stéphane committed
18
import pprint
19
import re
HUC Stéphane's avatar
HUC Stéphane committed
20
import webbrowser as web
HUC Stéphane's avatar
HUC Stéphane committed
21

HUC Stéphane's avatar
HUC Stéphane committed
22
# Import Personals Modules
23
24
25
26
27
28
29
30
31
32
33
34
35
try:
    from modules.notification import Info as info
except ImportError:
    print(f'Cant import notification module onto Service')
    sys.exit(1)

try:
    from modules.message import Message as mssg
except ImportError:
    print(f'Cant import window_message module onto Service')
    sys.exit(1)


HUC Stéphane's avatar
HUC Stéphane committed
36
class Tools(object):
37
    '''Tools for YUP'''
HUC Stéphane's avatar
HUC Stéphane committed
38
39
40

    def __init__(self, init):

41
42
43
        if isinstance(init, dict):
            for i in init:
                setattr(self, i, init[i])
HUC Stéphane's avatar
HUC Stéphane committed
44

HUC Stéphane's avatar
HUC Stéphane committed
45
        self.ppp = pprint.PrettyPrinter(indent=4)
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
        
        self.dict_for_info = dict()     # dict for class Info
        self.dict_for_info = {
            'icon': self.icon,
            'NAME': self.NAME,
            'title': self.title['main_window'],
        }

        self.dict_for_mssg = dict()    # dict for class Message
        self.dict_for_mssg = {
            #'debug': self.debug,
            'log': self.log,
        }

        self.info = info(self.dict_for_info)
        self.wmssg = mssg(self.dict_for_mssg)
HUC Stéphane's avatar
HUC Stéphane committed
62

63
64
        self.log.info('=> Using Tools ...')

HUC Stéphane's avatar
HUC Stéphane committed
65
66
67
68
69
70
71
72
73
74
    @staticmethod
    def array_search(haystack, needle):
        ''' Equivalent PHP array_search() '''

        return [k for k, v in enumerate(haystack) if v == needle][0]

    def array_search_by_label(self, haystack, needle):
        ''' Search k if label exists and comp with needle '''

        try:
HUC Stéphane's avatar
HUC Stéphane committed
75
76
            return [
                k for k, v in enumerate(haystack['index'])
HUC Stéphane's avatar
HUC Stéphane committed
77
                if self.cmp(needle, haystack[v]['label']) == 0][0]
HUC Stéphane's avatar
HUC Stéphane committed
78
79

        except IndexError as iee:
80
            print(f'Error Index => {iee}')
HUC Stéphane's avatar
HUC Stéphane committed
81
            self.ppp.pprint(haystack)
82
            print(f'needle: {needle}')
HUC Stéphane's avatar
HUC Stéphane committed
83
            self.log.debug('haystack: \n' + str(self.ppp.pformat(haystack)))
HUC Stéphane's avatar
HUC Stéphane committed
84
85
86
87
88
89
            self.log.debug('needle: %s ' % needle)

    def array_search_by_label2(self, haystack, needle):
        ''' Search v if label exists and comp with needle '''

        try:
HUC Stéphane's avatar
HUC Stéphane committed
90
91
            return [
                v for k, v in enumerate(haystack['index'])
HUC Stéphane's avatar
HUC Stéphane committed
92
                if self.cmp(needle, haystack[v]['label']) == 0][0]
HUC Stéphane's avatar
HUC Stéphane committed
93
94

        except IndexError as iee:
95
            print(f'Error Index => {iee}')
HUC Stéphane's avatar
HUC Stéphane committed
96
            self.ppp.pprint(haystack)
97
            print(f'needle: {needle}')
HUC Stéphane's avatar
HUC Stéphane committed
98
            self.log.debug('haystack: \n' + str(self.ppp.pformat(haystack)))
HUC Stéphane's avatar
HUC Stéphane committed
99
100
            self.log.debug('needle: %s ' % needle)

101
102
103
    @staticmethod
    def check_files_exists(file_cfg):
        '''Check if config files exists'''
HUC Stéphane's avatar
HUC Stéphane committed
104

105
        try:
106
107
            with open(file_cfg) as file:
                return True
HUC Stéphane's avatar
HUC Stéphane committed
108

109
        except IOError as ioe:
110
            print(f'Error to read document: {ioe}')
111
            return False
HUC Stéphane's avatar
HUC Stéphane committed
112

HUC Stéphane's avatar
HUC Stéphane committed
113
114
115
    def cmp(self, value, needle):
        '''Compare two values'''
        return (value>needle)-(value<needle)
HUC Stéphane's avatar
HUC Stéphane committed
116

HUC Stéphane's avatar
HUC Stéphane committed
117
    def fill_tk_cbb(self, haystack):
118
        '''Fill dynamically combobox'''
HUC Stéphane's avatar
HUC Stéphane committed
119
        self.log.debug('Haystack: %s' % haystack)
HUC Stéphane's avatar
HUC Stéphane committed
120

HUC Stéphane's avatar
HUC Stéphane committed
121
        array = list()
HUC Stéphane's avatar
HUC Stéphane committed
122
123
        for key, val in enumerate(haystack['index']):
            if haystack[val]['active']:
HUC Stéphane's avatar
HUC Stéphane committed
124
                array.append(haystack[val]['label'])
HUC Stéphane's avatar
HUC Stéphane committed
125

HUC Stéphane's avatar
HUC Stéphane committed
126
127
128
        if array:
            return array
        del array
129

130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
    @staticmethod
    def check_size(needle, auth=0):
        '''Compare size file with max authorized'''
        
        size = Tools.get_size(needle)
        
        if size == 0:
            self.wmssg.display('error', self.text['error']['size'])
            return False
        
        elif auth > 0 and size > auth:
            self.wmssg.display('error', self.text['error']['big_size'])
            return False
        
        else:
            return True
    
147
148
149
150
151
    @staticmethod
    def get_size(needle):
        '''Get file size'''
        return os.path.getsize(needle)

HUC Stéphane's avatar
HUC Stéphane committed
152
153
154
155
156
157
158
159
160
    @staticmethod
    def in_array(haystack, needle):
        ''' Equivalent PHP in_array() '''

        if needle in haystack:
            return True
        else:
            return False

HUC Stéphane's avatar
HUC Stéphane committed
161
162
163
    def open_historic(self, log):
        '''Display historic file html'''
        web.open_new_tab('file://' + log)
164
        self.log.debug('log: %s ' %log)
HUC Stéphane's avatar
HUC Stéphane committed
165

HUC Stéphane's avatar
HUC Stéphane committed
166
    @staticmethod
167
    def read_file(filename):
HUC Stéphane's avatar
HUC Stéphane committed
168
169
170
        '''Read file'''

        try:
171
172
173
174
            with open(filename, 'r') as rfile:
                strings = rfile.read()
                rfile.close()
                
HUC Stéphane's avatar
HUC Stéphane committed
175
176
177
178
                return strings

        except IOError as ioe:
            self.log.exception('Error to read document: %s' % ioe)
179
            self.wmssg.display('error', self.texts['error']['read_file'] % ioe)
HUC Stéphane's avatar
HUC Stéphane committed
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
            return False

    @staticmethod
    def rebuild_dict(haystack):
        ''' Rebuild dictionnary to remove index if active is false '''

        haystack['key'] = haystack['index']
        haystack['index'] = list()

        for name in haystack['key']:

            if haystack[name]['active']:
                haystack['index'].append(name)

        del haystack['key']
        return haystack

197
198
    def sed_lines(self, filename, pattern=None, replace=None):
        '''Edit file to replace lines'''
199
200

        try:
201
202
            self.log.info('=> Sed Lines :: Filename : %s' % filename)
            self.log.debug('=> Sed Lines :: pattern : %s' % pattern)
203
204
205
206
207
208
209
210

            with open(filename, 'r') as rfile:
                lines = rfile.readlines()
                self.log.debug('=> Sed Lines :: Lines: %s' % lines)

            with open(filename, 'w') as wfile:
                for line in lines:

211
212
213
214
                    if pattern in line:
                        reg = re.compile(r'' + pattern, re.MULTILINE)
                        line = reg.sub(replace, line)
                        del(reg)
215

216
                    wfile.write(line)
217
                            
218
219
220
221
222
223
224
225
            return True

        except ImportError as iee:
            self.log.exception('Error to import module: %s' % iee)
            return False

        except IOError as ioe:
            self.log.exception('Error to write document: %s' % ioe)
226
            self.wmssg.display('error', self.texts['error']['write_file'] % ioe)
227
228
            return False

229
230
    def sed_tags(self, filename):
        '''Edit file html historic to replace tags'''
HUC Stéphane's avatar
HUC Stéphane committed
231
232

        try:
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
            patterns = [
                '{ABOUT}',
                '{COPYRIGHT}',
                '{DESCR}',
                '{LANG}',
                '{LICENCE}',
                '{NAME}',
                '{TITLE}',
                '{URL_HISTORIC}',
                '{URL_WEB}',
            ]
            replaces = [
                self.text['about']['historic'],
                self.text['about']['copyright'],
                self.DESCR, 
                self.config['lang'], 
                self.text['about']['license'],
                self.NAME, 
                self.title['html'],
                self.text['html']['url_historic'],
                self.url['web'],
            ]
255

HUC Stéphane's avatar
HUC Stéphane committed
256
257
            with open(filename, 'r') as rfile:
                lines = rfile.readlines()
258
                self.log.debug('=> Sed Lines :: Lines: %s' % lines)
HUC Stéphane's avatar
HUC Stéphane committed
259
260
261
262

            with open(filename, 'w') as wfile:
                for line in lines:

263
                    for key, pattern in enumerate(patterns):
HUC Stéphane's avatar
HUC Stéphane committed
264
                        if pattern in line:
265
                            reg = re.compile(r'' + pattern, re.MULTILINE)
266
                            line = reg.sub(replaces[key], line)
267
                            del(reg)
268

269
                    wfile.write(line)
270

HUC Stéphane's avatar
HUC Stéphane committed
271
272
            return True

HUC Stéphane's avatar
HUC Stéphane committed
273
274
        except ImportError as iee:
            self.log.exception('Error to import module: %s' % iee)
275
276
            return False

HUC Stéphane's avatar
HUC Stéphane committed
277
278
        except IOError as ioe:
            self.log.exception('Error to write document: %s' % ioe)
279
            self.wmssg.display('error', self.texts['error']['write_file'] % ioe)
HUC Stéphane's avatar
HUC Stéphane committed
280
281
282
            return False

    @staticmethod
283
    def write_file(text, filename):
HUC Stéphane's avatar
HUC Stéphane committed
284
285
286
        ''' Write file '''

        try:
287
288
289
290
            with open(filename, 'w') as wfile:
                wfile.write(text)
                wfile.close()

HUC Stéphane's avatar
HUC Stéphane committed
291
292
293
294
                return True

        except IOError as ioe:
            self.log.exception('Error to write document: %s' % ioe)
295
            self.wmssg.display('error', self.texts['error']['write_file'] % ioe)
HUC Stéphane's avatar
HUC Stéphane committed
296
            return False