Subversion Repositories basico

Rev

Rev 129 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
4 t00mlabs 1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3
# File: callbacks.py
4
# Author: Tomás Vírseda
5
# License: GPL v3
6
# Description: UI and related callbacks service
7
 
8
import os
9
import csv
10
import json
74 t00mlabs 11
import time
12
import glob
13
from os.path import basename
14
from datetime import datetime
4 t00mlabs 15
 
16
import gi
17
gi.require_version('Gtk', '3.0')
18
gi.require_version('WebKit', '3.0')
105 t00mlabs 19
from gi.repository import GLib
4 t00mlabs 20
from gi.repository import Gtk
21
from gi.repository import Gio
22
from gi.repository import Pango
23
from gi.repository.GdkPixbuf import Pixbuf
24
from gi.repository import WebKit
25
 
74 t00mlabs 26
from concurrent.futures import ThreadPoolExecutor as Executor
27
 
4 t00mlabs 28
from .service import Service
29
 
74 t00mlabs 30
SEP = os.path.sep
4 t00mlabs 31
 
74 t00mlabs 32
# PROPKEYS = CSV headers. SAP Note metadata
33
PROPKEYS = ['id', 'title', 'type', 'componentkey',
34
            'componenttxt', 'category', 'priority', 'releaseon',
35
            'language', 'version']
36
 
37
# Extend PROPKEYS with custom basico metadata
38
PROPKEYS.extend (['Tasks', 'Bookmark'])
39
 
4 t00mlabs 40
class Callback(Service):
41
    def initialize(self):
42
        self.get_services()
43
 
44
    def get_services(self):
126 t00mlabs 45
        self.settings = self.app.get_service('Settings')
112 t00mlabs 46
        self.db = self.app.get_service('DB')
4 t00mlabs 47
        self.gui = self.app.get_service('GUI')
48
        self.uif = self.app.get_service("UIF")
49
        self.sap = self.app.get_service('SAP')
50
        self.tasks = self.app.get_service('Tasks')
51
        self.alert = self.app.get_service('Notify')
81 t00mlabs 52
        self.im = self.app.get_service('IM')
74 t00mlabs 53
        self.utils = self.app.get_service('Utils')
4 t00mlabs 54
 
55
    def execute_action(self, *args):
56
        action = args[0]
57
        action_name = action.get_name()
58
        try:
59
            callback = "self.%s()" % action_name.replace('-', '_')
60
            return eval(callback)
61
        except Exception as error:
62
            self.log.error(error)
63
            self.log.error("Callback for action '%s' not registered" % action_name)
64
            raise
65
 
66
 
67
    def actions_browse(self, *args):
126 t00mlabs 68
        SAP_NOTE_URL = self.settings.get('SAP', 'SAP_NOTE_URL')
101 t00mlabs 69
        sapnoteview = self.gui.get_widget('viewmenu')
128 t00mlabs 70
        visor = self.gui.get_widget('visor')
71
        sapnotes = visor.get_toggled()
74 t00mlabs 72
        lurl = []
73
        for sid in sapnotes:
74
            url = SAP_NOTE_URL % sid
75
            lurl.append(url)
76
            self.log.debug("Browsing SAP Note %s" % sid)
77
        self.utils.browse(lurl)
4 t00mlabs 78
 
79
 
80
    def actions_other_delete(self, *args):
74 t00mlabs 81
        db = self.get_service('DB')
101 t00mlabs 82
        sapnoteview = self.gui.get_widget('viewmenu')
129 t00mlabs 83
        visor = self.gui.get_widget('visor')
84
        sapnotes = visor.get_toggled()
4 t00mlabs 85
        sapnotes.sort()
128 t00mlabs 86
        winroot = self.gui.get_widget('mainwindow')
4 t00mlabs 87
 
88
        dialog = Gtk.MessageDialog(winroot, 0, Gtk.MessageType.WARNING,
89
            Gtk.ButtonsType.OK_CANCEL, "Are you sure?")
90
        dialog.set_title("Deleting SAP Notes...")
91
        dialog.set_modal(True)
92
        dialog.set_transient_for(winroot)
93
        dialog.format_secondary_text(
94
            "These SAP Notes will be deleted:\n%s" % ', '.join(sapnotes))
95
 
96
        response = dialog.run()
97
        if response == Gtk.ResponseType.OK:
74 t00mlabs 98
            db = self.get_service('DB')
129 t00mlabs 99
            visor = self.gui.get_widget('visor')
100
            sapnotes = visor.get_toggled()
4 t00mlabs 101
            for sapnote in sapnotes:
74 t00mlabs 102
                db.delete(sapnote)
4 t00mlabs 103
            self.search_notes()
104
            self.refresh_view()
105
            self.alert.show('Delete', 'Selected SAP Notes deleted', 'information')
106
            self.log.info("Selected SAP Notes deleted")
74 t00mlabs 107
            db.save_notes()
4 t00mlabs 108
        elif response == Gtk.ResponseType.CANCEL:
109
            self.alert.show('Delete', 'Delete action canceled by user', 'warning')
110
            self.log.info("Delete action canceled by user")
111
 
112
        dialog.destroy()
113
 
114
        return response
115
 
91 t00mlabs 116
    def update_titlebar_title(self, title, icon, capitalize=True):
81 t00mlabs 117
        image = self.gui.get_widget('imgtitlebar')
84 t00mlabs 118
        icon = self.im.get_pixbuf_icon(icon.lower(), 24, 24)
81 t00mlabs 119
        image.set_from_pixbuf(icon)
120
        image.show_all()
121
        titlebar = self.gui.get_widget("lbltitlebar")
91 t00mlabs 122
        if capitalize:
123
            title = title.capitalize()
124
        titlebar.set_markup("<big><b>%s</b></big>" % title)
4 t00mlabs 125
 
81 t00mlabs 126
 
78 t00mlabs 127
    def show_dashboard(self, *args):
128
        notebook = self.gui.get_widget('mainbox')
129
        notebook.set_current_page(0)
84 t00mlabs 130
        self.update_titlebar_title("Dashboard", "dashboard")
78 t00mlabs 131
 
132
 
133
    def show_workplace(self, *args):
134
        notebook = self.gui.get_widget('mainbox')
135
        notebook.set_current_page(1)
84 t00mlabs 136
        self.update_titlebar_title("Workplace", "workplace")
78 t00mlabs 137
 
138
 
81 t00mlabs 139
    def show_school(self, *args):
140
        notebook = self.gui.get_widget('mainbox')
141
        notebook.set_current_page(2)
91 t00mlabs 142
        self.update_titlebar_title("My SAP School", "school", False)
81 t00mlabs 143
 
144
 
83 t00mlabs 145
    def show_workbook(self, *args):
81 t00mlabs 146
        notebook = self.gui.get_widget('mainbox')
147
        notebook.set_current_page(3)
92 t00mlabs 148
        self.update_titlebar_title("Workbook", "comments")
81 t00mlabs 149
 
83 t00mlabs 150
 
101 t00mlabs 151
    #~ def show_search(self, *args):
152
        #~ def reveal_search():
153
            #~ revsearch = self.gui.get_widget('revSearch')
154
            #~ tgbsearch = self.gui.get_widget('tgbSearch')
155
            #~ if tgbsearch.get_active():
156
                #~ revsearch.set_reveal_child(True)
157
                #~ revsearch.set_no_show_all(False)
158
                #~ revsearch.show_all()
159
            #~ else:
160
                #~ revsearch.set_reveal_child(False)
161
                #~ revsearch.set_no_show_all(True)
162
                #~ revsearch.hide()
84 t00mlabs 163
 
101 t00mlabs 164
        #~ tgbsearch = self.gui.get_widget('tgbSearch')
165
        #~ reveal_search()
166
        #~ self.show_workplace()
84 t00mlabs 167
 
168
 
169
    def toggle_search(self, *args):
170
        tgbsearch = self.gui.get_widget('tgbSearch')
171
        toggled = tgbsearch.get_active()
172
        tgbsearch.set_active(not toggled)
173
 
93 t00mlabs 174
    def show_help(self, *args):
175
        notebook = self.gui.get_widget('mainbox')
176
        notebook.set_current_page(5)
177
        self.update_titlebar_title("Help", "basico_help")
84 t00mlabs 178
 
122 t00mlabs 179
    def show_settings(self, button):
180
        notebook = self.gui.get_widget('mainbox')
181
        notebook.set_current_page(4)
182
        self.update_titlebar_title("Settings", "settings")
79 t00mlabs 183
 
110 t00mlabs 184
        #Toggle popover visibility
122 t00mlabs 185
        #~ if popover.get_visible():
186
            #~ popover.hide()
187
        #~ else:
188
            #~ popover.show_all()
189
 
190
    def show_popover(self, button, popover):
191
        #Toggle popover visibility
110 t00mlabs 192
        if popover.get_visible():
193
            popover.hide()
194
        else:
195
            popover.show_all()
79 t00mlabs 196
 
122 t00mlabs 197
 
198
    def show_popover_menu(self, button, popover):
119 t00mlabs 199
        #Toggle popover visibility
200
        if popover.get_visible():
201
            popover.hide()
202
        else:
203
            popover.show_all()
204
 
205
 
74 t00mlabs 206
    def show_properties(self, *args):
207
        notebook = self.gui.get_widget('ntbOperations')
208
        toggle = self.gui.get_widget('tgbShowManage')
209
        notebook.set_current_page(0)
210
        toggle.set_active(True)
211
 
212
 
4 t00mlabs 213
    def actions_manage_tasks(self, *args):
101 t00mlabs 214
        #~ sapnoteview = self.gui.get_widget('viewmenu')
74 t00mlabs 215
        #~ try:
129 t00mlabs 216
            #~ visor = self.gui.get_widget('visor')
217
            #~ sapnotes = visor.get_toggled()
74 t00mlabs 218
        #~ except:
219
            #~ sapnote = ''
220
        self.tasks.show_window(active=True)
221
 
222
 
223
    def link_tasks_to_sapnotes(self, *args):
101 t00mlabs 224
        sapnoteview = self.gui.get_widget('viewmenu')
129 t00mlabs 225
        visor = self.gui.get_widget('visor')
226
        sapnotes = visor.get_toggled()
74 t00mlabs 227
        tasks = self.tasks.get_selected()
228
        self.sap.link_to_task(sapnotes, tasks)
4 t00mlabs 229
 
230
    def actions_bookmark(self, *args):
74 t00mlabs 231
        db = self.get_service('DB')
101 t00mlabs 232
        sapnoteview = self.gui.get_widget('viewmenu')
129 t00mlabs 233
        visor = self.gui.get_widget('visor')
234
        sapnotes = visor.get_toggled()
74 t00mlabs 235
        self.log.debug("Action bookmark triggered for SAP Notes: %s" % sapnotes)
4 t00mlabs 236
        view = sapnoteview.get_view()
237
        self.sap.set_bookmark(sapnotes)
74 t00mlabs 238
        db.save_notes()
4 t00mlabs 239
        self.refresh_view(view=view)
240
        self.alert.show('Bookmarks', 'Selected SAP Notes bookmarked', 'information')
241
 
242
 
243
    def actions_unbookmark(self, *args):
74 t00mlabs 244
        db = self.get_service('DB')
101 t00mlabs 245
        sapnoteview = self.gui.get_widget('viewmenu')
129 t00mlabs 246
        visor = self.gui.get_widget('visor')
247
        sapnotes = visor.get_toggled()
74 t00mlabs 248
        self.log.debug("Action unbookmark triggered for SAP Notes: %s" % sapnotes)
4 t00mlabs 249
        self.sap.set_no_bookmark(sapnotes)
74 t00mlabs 250
        db.save_notes()
4 t00mlabs 251
        self.refresh_view(view='bookmarks')
252
        self.alert.show('Bookmarks', 'Selected SAP Notes unbookmarked', 'information')
253
 
254
 
118 t00mlabs 255
    def bookmark(self, lsid):
256
        self.db.set_bookmark(lsid)
112 t00mlabs 257
 
118 t00mlabs 258
    def unbookmark(self, lsid):
259
        self.db.set_no_bookmark(lsid)
112 t00mlabs 260
 
118 t00mlabs 261
 
4 t00mlabs 262
    def actions_export_csv(self, *args):
74 t00mlabs 263
        db = self.get_service('DB')
128 t00mlabs 264
        winroot = self.gui.get_widget('mainwndow')
101 t00mlabs 265
        sapnoteview = self.gui.get_widget('viewmenu')
129 t00mlabs 266
        visor = self.gui.get_widget('visor')
267
        sapnotes = visor.get_toggled()
128 t00mlabs 268
        dialog = Gtk.FileChooserDialog("Save file", winroot,
4 t00mlabs 269
            Gtk.FileChooserAction.SAVE,
270
                (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
271
                 Gtk.STOCK_SAVE, Gtk.ResponseType.OK))
272
        response = dialog.run()
273
 
274
        if response == Gtk.ResponseType.OK:
275
            export_path = dialog.get_filename()
276
            writer = csv.writer(open(export_path, 'w'), delimiter=';', quoting=csv.QUOTE_ALL)
277
            csvrow = []
74 t00mlabs 278
 
4 t00mlabs 279
            for key in PROPKEYS:
74 t00mlabs 280
                csvrow.append(key.capitalize())
4 t00mlabs 281
            writer.writerow(csvrow)
74 t00mlabs 282
 
283
            for tid in sapnotes:
284
                sid = "0"*(10 - len(tid)) + tid
285
                self.log.debug("Exporting SAP Note %s to CSV file" % sid)
4 t00mlabs 286
                csvrow = []
74 t00mlabs 287
                props = db.get_sapnote_metadata(sid)
288
 
4 t00mlabs 289
                for prop in PROPKEYS:
290
                    if prop == 'tasks':
291
                        tasks = ', '.join(props[prop])
292
                        csvrow.append(tasks)
293
                    else:
294
                        csvrow.append(props[prop])
295
                writer.writerow(csvrow)
296
            self.alert.show('Export', 'Selected SAP Notes exported successfully to CSV format', 'information')
297
            self.log.info("Selected SAP Notes exported to CSV format: %s" % export_path)
298
        else:
299
            self.alert.show('Export', 'Export canceled by user', 'warning')
300
            self.log.info("Export canceled by user")
301
        dialog.destroy()
302
 
303
 
304
    def actions_export_txt(self, *args):
305
        rootwin = self.gui.get_widget('mainwndow')
101 t00mlabs 306
        sapnoteview = self.gui.get_widget('viewmenu')
129 t00mlabs 307
        visor = self.gui.get_widget('visor')
308
        sapnotes = visor.get_toggled()
4 t00mlabs 309
        dialog = Gtk.FileChooserDialog("Save file", rootwin,
310
            Gtk.FileChooserAction.SAVE,
311
                (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
312
                 Gtk.STOCK_SAVE, Gtk.ResponseType.OK))
313
        response = dialog.run()
314
 
315
        if response == Gtk.ResponseType.OK:
316
            export_path = dialog.get_filename()
317
            fout = open(export_path, 'w')
318
            for sapnote in sapnotes:
319
                fout.write("%s\n" % sapnote)
320
            self.alert.show('Export', 'Selected SAP Notes exported successfully to TXT format', 'information')
321
            self.log.info("Selected SAP Notes exported to TXT format: %s" % export_path)
322
        else:
323
            self.alert.show('Export', 'Export canceled by user', 'warning')
324
            self.log.info("Export canceled by user")
325
        dialog.destroy()
326
 
327
 
74 t00mlabs 328
    def actions_export_json(self, *args):
329
        db = self.get_service('DB')
4 t00mlabs 330
        rootwin = self.gui.get_widget('mainwndow')
101 t00mlabs 331
        sapnoteview = self.gui.get_widget('viewmenu')
129 t00mlabs 332
        visor = self.gui.get_widget('visor')
333
        sapnotes = visor.get_toggled()
4 t00mlabs 334
        dialog = Gtk.FileChooserDialog("Save file", rootwin,
74 t00mlabs 335
            Gtk.FileChooserAction.SELECT_FOLDER,
4 t00mlabs 336
                (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
337
                 Gtk.STOCK_SAVE, Gtk.ResponseType.OK))
338
        response = dialog.run()
339
 
340
        if response == Gtk.ResponseType.OK:
341
            export_path = dialog.get_filename()
342
            bag = {}
74 t00mlabs 343
            for tid in sapnotes:
344
                sid = "0"*(10 - len(tid)) + tid
345
                sapnote = db.get_sapnote_metadata(sid)
4 t00mlabs 346
                bag[sid] = sapnote
74 t00mlabs 347
            now = datetime.now()
348
            target = export_path + SEP + 'basico-%s.json' % now.strftime("%Y%m%d_%H%M%S")
349
            db.export_basico_package(bag, target)
350
            self.alert.show('Export', 'Selected SAP Notes exported successfully to JSON format', 'information')
351
            self.log.info("Selected SAP Notes exported to JSON: %s" % target)
4 t00mlabs 352
        else:
353
            self.alert.show('Export', 'Export canceled by user', 'warning')
354
            self.log.info("Export canceled by user")
355
        dialog.destroy()
356
 
357
 
74 t00mlabs 358
    def actions_import_json(self, *args):
359
        self.import_notes_from_file()
360
        #~ db = self.get_service('DB')
361
        #~ rootwin = self.gui.get_widget('mainwndow')
101 t00mlabs 362
        #~ sapnoteview = self.gui.get_widget('viewmenu')
129 t00mlabs 363
        #~ visor = self.gui.get_widget('visor')
364
        #~ sapnotes = visor.get_toggled()
74 t00mlabs 365
        #~ dialog = Gtk.FileChooserDialog("Select Basico JSON file", rootwin,
366
            #~ Gtk.FileChooserAction.OPEN,
367
                #~ (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
368
                 #~ Gtk.STOCK_SAVE, Gtk.ResponseType.OK))
369
        #~ response = dialog.run()
4 t00mlabs 370
 
74 t00mlabs 371
        #~ if response == Gtk.ResponseType.OK:
372
            #~ source = dialog.get_filename()
373
            #~ try:
374
                #~ with open(source, 'r') as fp:
375
                    #~ bag = json.load(fp)
376
                    #~ db.import(bag)
377
                    #~ self.log.debug ("Imported %d notes" % len(bag))
378
            #~ except Exception as error:
379
                #~ self.log.info("SAP Notes database not found. Creating a new one")
380
                #~ self.save_notes()
381
 
382
            #~ self.alert.show('Export', 'Selected SAP Notes exported successfully to JSON format', 'information')
383
            #~ self.log.info("Selected SAP Notes exported to JSON: %s" % target)
384
        #~ else:
385
            #~ self.alert.show('Export', 'Export canceled by user', 'warning')
386
            #~ self.log.info("Export canceled by user")
387
        #~ dialog.destroy()
388
 
389
 
390
 
391
    def actions_import_launchpad(self, *args):
392
        self.show_addsapnotes_dialog()
393
 
394
 
4 t00mlabs 395
    def set_search_filter_key(self, key):
396
        self.gui.set_key('cmbvalue', key)
397
 
398
 
399
    def get_search_filter_key(self):
400
        cmbvalue = self.gui.get_key('cmbvalue')
401
 
402
 
403
    def set_search_term(self, term):
404
        searchentry = self.gui.get_widget("stySearchInfo")
405
        searchentry.set_text(term)
406
 
407
 
408
    def search_notes(self, *args):
74 t00mlabs 409
        db = self.get_service('DB')
4 t00mlabs 410
        searchentry = self.gui.get_widget("stySearchInfo")
411
        cmbvalue = self.gui.get_key('cmbvalue')
115 t00mlabs 412
 
4 t00mlabs 413
        try:
414
            term = searchentry.get_text()
415
        except:
416
            term = ''
74 t00mlabs 417
 
115 t00mlabs 418
        self.log.debug("cmbvalue: %s" % cmbvalue)
419
        self.log.debug("term: %s" % term)
420
 
123 t00mlabs 421
        visor = self.gui.get_widget('visor')
74 t00mlabs 422
        sapnotes = db.get_notes()
4 t00mlabs 423
        found = {}
424
 
425
        if len(term) == 0:
426
            self.current_notes = found = sapnotes
115 t00mlabs 427
            self.log.debug("Found: %s" % len(found))
123 t00mlabs 428
            visor.populate(found)
115 t00mlabs 429
            #~ viewmenu.collapse()
102 t00mlabs 430
            self.log.debug("--> Displaying all database")
4 t00mlabs 431
            return
432
 
74 t00mlabs 433
        self.log.debug("Looking for '%s'" % term)
4 t00mlabs 434
        if cmbvalue == 'search':
435
            for sid in sapnotes:
436
                if term.upper() in sapnotes[sid]['title'].upper():
437
                   found[sid] = sapnotes[sid]
438
        elif cmbvalue == 'project':
439
            for sid in sapnotes:
440
                try:
441
                    projects = sapnotes[sid]['projects']
442
                    for project in projects:
443
                        if term.upper() in project.upper():
444
                           found[sid] = sapnotes[sid]
445
                except: pass
446
        elif cmbvalue == 'task':
447
            for sid in sapnotes:
448
                try:
449
                    tasks = sapnotes[sid]['tasks']
450
                    for task in tasks:
451
                        if term.upper() in task.upper():
452
                           found[sid] = sapnotes[sid]
453
                except: pass
74 t00mlabs 454
        elif cmbvalue == 'title':
455
            for sid in sapnotes:
456
                try:
457
                    title = sapnotes[sid]['title']
458
                    if term.upper() in title.upper():
459
                       found[sid] = sapnotes[sid]
460
                except: pass
461
        elif cmbvalue == 'priority':
462
            for sid in sapnotes:
463
                try:
464
                    priority = sapnotes[sid]['priority']
465
                    if term.upper() in priority.upper():
466
                       found[sid] = sapnotes[sid]
467
                except: pass
4 t00mlabs 468
        elif cmbvalue == 'component':
469
            for sid in sapnotes:
470
                if term.upper() in sapnotes[sid]['componentkey'].upper():
471
                   found[sid] = sapnotes[sid]
472
        elif cmbvalue == 'category':
473
            for sid in sapnotes:
474
                if term.upper() in sapnotes[sid]['category'].upper():
475
                   found[sid] = sapnotes[sid]
476
        elif cmbvalue == 'type':
477
            for sid in sapnotes:
478
                if term.upper() in sapnotes[sid]['type'].upper():
479
                   found[sid] = sapnotes[sid]
480
        elif cmbvalue == 'version':
481
            for sid in sapnotes:
482
                if term.upper() in sapnotes[sid]['version'].upper():
483
                   found[sid] = sapnotes[sid]
484
        elif cmbvalue == 'id':
485
            for sid in sapnotes:
486
                if term in sid:
487
                   found[sid] = sapnotes[sid]
488
        self.log.info("Term: '%s' (%d results)" % (term, len(found)))
489
        self.current_notes = found
490
        self.log.debug("Current Notes: %d" % len(self.current_notes))
123 t00mlabs 491
        visor.populate(found)
4 t00mlabs 492
 
493
 
74 t00mlabs 494
    #~ def import_notes(self, entry):
495
        #~ ntbimport = self.gui.get_widget('ntbAddSAPNotes')
496
        #~ imptype = ntbimport.get_current_page() # 0 -> Download, 1 -> Import from file
497
        #~ if imptype == 0:
498
            #~ self.import_notes_from_sapnet()
499
        #~ elif imptype == 1:
500
            #~ self.import_notes_from_file()
501
 
4 t00mlabs 502
    def import_notes(self, entry):
74 t00mlabs 503
        self.import_notes_from_sapnet()
4 t00mlabs 504
 
505
 
506
    def import_notes_from_file(self):
74 t00mlabs 507
        db = self.get_service('DB')
4 t00mlabs 508
        notebook = self.gui.get_widget('notebook')
130 t00mlabs 509
        #~ rootwin = self.gui.get_widget('mainbox')
510
        #~ self.log.debug (type(rootwin))
74 t00mlabs 511
 
130 t00mlabs 512
        dialog = Gtk.FileChooserDialog("Select Basico JSON file", None,
74 t00mlabs 513
            Gtk.FileChooserAction.OPEN,
514
                (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
515
                 Gtk.STOCK_SAVE, Gtk.ResponseType.OK))
516
        response = dialog.run()
517
 
518
        if response == Gtk.ResponseType.OK:
519
            source = dialog.get_filename()
520
            try:
521
                with open(source, 'r') as fp:
522
                    bag = json.load(fp)
523
                    db.import_sapnotes(bag)
524
                    self.log.info ("Imported %d notes from %s" % (len(bag), source))
525
            except Exception as error:
526
                self.log.info("SAP Notes database not found. Creating a new one")
527
                self.save_notes()
101 t00mlabs 528
            sapnoteview = self.gui.get_widget('viewmenu')
4 t00mlabs 529
            self.current_notes = bag
530
            sapnoteview.populate(bag)
74 t00mlabs 531
            db.save_notes()
4 t00mlabs 532
            self.refresh_view()
533
            switch = self.gui.get_widget('schSelectNotesAllNone')
130 t00mlabs 534
            #~ sapnoteview.select_all_none(switch, True)
535
            #~ sapnoteview.select_all_none(switch, False)
536
            #~ sapnoteview.expand_all()
74 t00mlabs 537
        else:
4 t00mlabs 538
            self.alert.show('Import', 'Nothing imported', 'error')
74 t00mlabs 539
            self.log.debug("Nothing imported")
540
        dialog.destroy()
4 t00mlabs 541
 
125 t00mlabs 542
    def import_notes_from_sapnet(self, lines):
74 t00mlabs 543
        db = self.get_service('DB')
544
        driver = self.get_service('Driver')
4 t00mlabs 545
 
546
        notebook = self.gui.get_widget('notebook')
128 t00mlabs 547
        winroot = self.gui.get_widget('mainwindow')
4 t00mlabs 548
        sapnotes = []
549
        bag = set()
125 t00mlabs 550
        #~ txtnotes = self.gui.get_widget('txtSAPNotes')
551
        #~ textbuffer = txtnotes.get_buffer()
552
        #~ istart, iend = textbuffer.get_bounds()
553
        #~ lines = textbuffer.get_text(istart, iend, False)
4 t00mlabs 554
 
74 t00mlabs 555
        lines = lines.replace(' ', ',')
556
        lines = lines.replace('\n', ',')
557
        sapnotes.extend(lines.split(','))
4 t00mlabs 558
 
559
        for sapnote in sapnotes:
560
            if len(sapnote.strip()) > 0:
561
                bag.add(sapnote.strip())
562
 
563
        self.log.debug("%d SAP Notes to be downloaded: %s" % (len(bag), ', '.join(list(bag))))
564
 
565
        resnotes = {}
566
 
74 t00mlabs 567
        self.sap.start_fetching(len(bag))
568
        dlbag = {}
569
 
570
        # FIXME: max_workers = 1 = Threads disabled
130 t00mlabs 571
        with Executor(max_workers=1) as exe:
74 t00mlabs 572
            jobs = []
573
            for sapnote in bag:
574
                job = exe.submit(self.sap.fetch, sapnote)
575
                jobs.append(job)
576
 
577
            for job in jobs:
578
                rc, sapnote = job.result()
579
                self.log.debug("\tRC SAP Note %s: %s" % (sapnote, rc))
580
                resnotes[sapnote] = rc
127 t00mlabs 581
                time.sleep(0.2)
74 t00mlabs 582
 
583
        driver.close()
584
        self.sap.stop_fetching()
585
        db.save_notes()
586
        db.build_stats()
587
 
125 t00mlabs 588
        #~ textbuffer.set_text("")
4 t00mlabs 589
        self.log.info("Task completed.")
590
        notebook.set_current_page(0)
591
        dialog = Gtk.MessageDialog(winroot, 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, "Task completed")
592
        msgrc = ""
593
        ko = 0
594
        ok = 0
595
        for sapnote in resnotes:
596
            rc = resnotes[sapnote]
597
            if rc:
598
                ok += 1
599
            else:
600
                ko += 1
601
        msgrc += "Downloaded: %d\nErroneus: %d" % (ok, ko)
602
        self.alert.show('Download', msgrc, 'information')
603
        dlbag = {}
74 t00mlabs 604
        mysapnotes = db.get_notes()
4 t00mlabs 605
        erroneus = set()
606
        for sid in bag:
607
            sid = "0"*(10 - len(sid)) + sid
608
            try:
609
                dlbag[sid] = mysapnotes[sid]
610
            except Exception as error:
611
                self.log.error(error)
612
                erroneus.add(sid)
74 t00mlabs 613
 
101 t00mlabs 614
        sapnoteview = self.gui.get_widget('viewmenu')
4 t00mlabs 615
        self.current_notes = dlbag
74 t00mlabs 616
        #~ self.refresh_view()
617
        self.refresh_and_clear_view()
4 t00mlabs 618
        sapnoteview.populate(dlbag)
619
        sapnoteview.expand_all()
74 t00mlabs 620
        boxMenu = self.gui.get_widget('boxMenu')
621
        boxMenu.show_all()
4 t00mlabs 622
 
623
 
624
    def stop_dl_notes(self, *args):
625
        notebook = self.gui.get_widget('notebook')
626
        txtSAPNotes = self.gui.get_widget('txtSAPNotes')
627
        buffer = txtSAPNotes.get_buffer()
628
        buffer.set_text("")
629
        notebook.set_current_page(0)
630
        self.refresh_view()
74 t00mlabs 631
        #~ self.alert.show('Download', 'Action canceled by user', 'warning')
632
        boxMenu = self.gui.get_widget('boxMenu')
633
        boxMenu.show_all()
634
        self.refresh_and_clear_view()
4 t00mlabs 635
 
74 t00mlabs 636
 
637
    def rebuild_database(self, *args):
638
        self.log.debug("Rebuild database...")
639
 
640
        db = self.get_service('DB')
128 t00mlabs 641
        CACHE_DIR = self.get_var('CACHE', 'local')
74 t00mlabs 642
 
128 t00mlabs 643
        #~ FSAPNOTE = CACHE_DIR + sid + '.xml'
74 t00mlabs 644
        #~ if path is None:
128 t00mlabs 645
            #~ path = CACHE_DIR
74 t00mlabs 646
 
128 t00mlabs 647
        files = glob.glob("%s%s*.xml" % (CACHE_DIR, SEP))
74 t00mlabs 648
        sap = self.app.get_service('SAP')
649
        for filename in files:
650
            self.log.debug("Filename: %s" % filename)
651
            sid = basename(filename)[0:-4]
652
            self.log.debug("SAP Note Id: %s" % sid)
653
 
654
            valid = False
655
            if db.is_stored(sid):
656
                self.log.debug("\tSAP Note %s will be analyzed again" % sid)
657
                content = db.get_sapnote_content(sid)
658
                sapnote = sap.analyze_sapnote_metadata(sid, content)
659
                if len(sapnote) > 0:
660
                    db = self.get_service('DB')
661
                    db.add(sapnote)
662
                    db.store(sid, content)
663
                    valid = True
664
 
665
        self.refresh_view()
666
 
4 t00mlabs 667
    def refresh_and_clear_view(self, *args):
102 t00mlabs 668
        self.log.debug("Refresh & clear view ( I)")
4 t00mlabs 669
        switch = self.gui.get_widget('schSelectNotesAllNone')
101 t00mlabs 670
        sapnoteview = self.gui.get_widget('viewmenu')
4 t00mlabs 671
        self.set_search_filter_key('search')
672
        self.set_search_term('')
673
        self.search_notes()
102 t00mlabs 674
        #~ self.refresh_view()
125 t00mlabs 675
        #~ sapnoteview.select_all_none(switch, False)
676
        #~ sapnoteview.collapse()
4 t00mlabs 677
 
74 t00mlabs 678
 
4 t00mlabs 679
    def refresh_view(self, action=None, callback=None, view=None):
102 t00mlabs 680
        self.log.debug("Refresh & clear view (II)")
4 t00mlabs 681
        window = self.gui.get_widget('mainwindow')
116 t00mlabs 682
        viewmenu = self.gui.get_widget('viewmenu')
115 t00mlabs 683
        #~ switch_expand = self.gui.get_widget('schExpandCollapse')
684
        #~ switch_select = self.gui.get_widget('schSelectNotesAllNone')
74 t00mlabs 685
        #~ active_ = switch.get_active()
686
 
4 t00mlabs 687
        if view is not None:
688
            viewlabel = self.gui.get_widget('lblViewCurrent')
91 t00mlabs 689
            #~ name = "<span size='20000'><b>%-10s</b></span>" % view.capitalize()
690
            name = "<b>%-10s</b>" % view.capitalize()
4 t00mlabs 691
            viewlabel.set_markup(name)
116 t00mlabs 692
        viewmenu.set_view(view)
693
        #~ self.search_notes()
115 t00mlabs 694
        #~ switch_expand.set_active(True)
695
        #~ switch_expand.set_active(False)
696
        #~ switch_select.set_active(False)
697
        #~ switch_select.set_active(True)
698
        #~ switch_select.set_active(False)
4 t00mlabs 699
 
700
 
80 t00mlabs 701
    def setup_dashboard(self):
702
        lblStatsSAPNotesCount = self.gui.add_widget('lblStatsSAPNotesCount')
703
 
74 t00mlabs 704
 
705
    def show_addsapnotes_dialog(self, *args):
101 t00mlabs 706
        sapnoteview = self.gui.get_widget('viewmenu')
74 t00mlabs 707
        sapnoteview.set_view('download')
708
        notebook = self.gui.get_widget('notebook')
709
        boxMenu = self.gui.get_widget('boxMenu')
710
        boxMenu.hide()
711
        notebook.set_current_page(1)
712
 
713
 
714
    def default_preferences(self, *args):
715
        prefs = self.get_service('Settings')
716
        gui = self.get_service('GUI')
717
        settings = prefs.get_default_settings()
718
        for key in settings:
719
            widget = gui.get_widget(key)
720
            widget.set_text(str(settings[key]))
721
 
722
        self.config[self.section] = settings
723
        self.save_config()
724
        self.log.debug("Settings reverted to default")
725
 
726
 
126 t00mlabs 727
    #~ def apply_preferences(self, *args):
728
        #~ self.sap.apply_preferences()
729
        #~ notebook = self.gui.get_widget('notebook')
730
        #~ notebook.set_current_page(0)
731
        #~ self.refresh_view(view='tasks')
732
        #~ self.alert.show('Settings', 'SAP preferences saved', 'information')
4 t00mlabs 733
 
734
 
735
    def update_components_stats(self, *args):
736
        statsviewer = self.gui.get_widget('scrStatsViewer')
737
        view = WebKit.WebView()
738
        chart = self.stats.build_pie_maincomp()
739
        view.load_string(chart, 'text/html', 'UTF-8','/')
740
        self.gui.swap_widget(statsviewer, view)
741
 
74 t00mlabs 742
 
4 t00mlabs 743
    def update_categories_stats(self, *args):
744
        statsviewer = self.gui.get_widget('scrStatsViewer')
745
        view = WebKit.WebView()
746
        chart = self.stats.build_pie_categories()
747
        view.load_string(chart, 'text/html', 'UTF-8','/')
748
        self.gui.swap_widget(statsviewer, view)
749
 
750
 
74 t00mlabs 751
    def check_task_link_button_status(self):
752
        tasks = self.get_service('Tasks')
753
        button = self.gui.get_widget('btnLinkTasksApply')
101 t00mlabs 754
        sapnoteview = self.gui.get_widget('viewmenu')
74 t00mlabs 755
 
756
        tasks_selected = len(tasks.get_selected()) > 0
757
        notes_selected = len(sapnoteview.get_selected_notes()) > 0
758
        if  tasks_selected and notes_selected:
759
            #~ button.set_no_show_all(False)
760
            #~ button.show_all()
761
            button.set_sensitive(True)
762
            self.log.debug("Task link button enabled")
763
        else:
764
            #~ button.hide()
765
            #~ button.set_no_show_all(True)
766
            button.set_sensitive(False)
767
            self.log.debug("Task link button disabled")
768
 
769
 
4 t00mlabs 770
    def test(self, *args):
771
        self.log.debug(args)