Subversion Repositories basico

Rev

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