~ubuntu-branches/debian/wheezy/gtg/wheezy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# -*- coding: utf-8 -*-
# Copyright (c) 2009 - Luca Invernizzi <invernizzi.l@gmail.com>
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program.  If not, see <http://www.gnu.org/licenses/>.
import sys
import os
import datetime
try:
    import pygtk
    pygtk.require("2.0")
except: # pylint: disable-msg=W0702
    sys.exit(1)
try:
    import gtk
except: # pylint: disable-msg=W0702
    sys.exit(1)
from threading           import Timer

from GTG.core.task       import Task


class pluginReaper:

    DEFAULT_PREFERENCES = {'max_days': 30,
                           'is_automatic': False,
                           'show_menu_item': True}

    PLUGIN_NAME = "task-reaper"
    
    #In case of automatic removing tasks, the time
    # between two runs of the cleaner function
    TIME_BETWEEN_PURGES = 60 * 60

    def __init__(self):
        self.path = os.path.dirname(os.path.abspath(__file__))
        #GUI initialization
        self.builder = gtk.Builder()
        self.builder.add_from_file(os.path.join(
                             os.path.dirname(os.path.abspath(__file__)) + \
                             "/reaper.ui"))
        self.preferences_dialog = self.builder.get_object("preferences_dialog")
        self.pref_chbox_show_menu_item    = \
                            self.builder.get_object("pref_chbox_show_menu_item")
        self.pref_chbox_is_automatic    = \
                            self.builder.get_object("pref_chbox_is_automatic")
        self.pref_spinbtn_max_days    = \
                            self.builder.get_object("pref_spinbtn_max_days")
        SIGNAL_CONNECTIONS_DIC = {
            "on_preferences_dialog_delete_event":
                self.on_preferences_cancel,
            "on_btn_preferences_cancel_clicked":
                self.on_preferences_cancel,
            "on_btn_preferences_ok_clicked":
                self.on_preferences_ok
        }
        self.builder.connect_signals(SIGNAL_CONNECTIONS_DIC)
        self.menu_item = gtk.MenuItem("Delete old closed tasks")
        self.menu_item.connect('activate', self.delete_old_closed_tasks)

    def activate(self, plugin_api):
        self.plugin_api = plugin_api
        #preferences initialization
        self.menu_item_is_shown = False
        self.is_automatic = False
        self.timer = None
        self.logger = self.plugin_api.get_logger()
        self.preferences_load()
        self.preferences_apply()

    def onTaskClosed(self, plugin_api):
        pass

    def onTaskOpened(self, plugin_api):
        pass

    def deactivate(self, plugin_api):
        if self.menu_item_is_shown == True:
            plugin_api.remove_menu_item(self.menu_item)

## HELPER FUNCTIONS ############################################################

    def __log(self, message):
        if self.logger:
            self.logger.debug(message)

## CORE FUNCTIONS ##############################################################

    def schedule_autopurge(self):
        self.timer = Timer(self.TIME_BETWEEN_PURGES, self.delete_old_closed_tasks)
        self.timer.start()
        self.__log("Automatic deletion of old tasks scheduled")

    def cancel_autopurge(self):
        if self.timer:
            self.__log("Automatic deletion of old tasks cancelled")
            self.timer.cancel()
        pass

    def delete_old_closed_tasks(self, widget = None):
        self.__log("Starting deletion of old tasks")
        today = datetime.datetime.now().date()
        requester = self.plugin_api.get_requester()
        closed_tids = requester.get_tasks_list(status = [Task.STA_DISMISSED,
                                                  Task.STA_DONE])
        closed_tasks = [requester.get_task(tid) for tid in closed_tids]
        #print [t.get_title() for t in closed_tasks]
        delta = datetime.timedelta(days = self.preferences["max_days"])
        #print [t.get_closed_date().to_py_date() for t in closed_tasks]
        to_remove = filter(lambda t: t.get_closed_date().to_py_date() < today -delta,\
                           closed_tasks)
        map(lambda t: requester.delete_task(t.get_id()), to_remove)
        #If automatic purging is on, schedule another run
        if self.is_automatic:
            self.schedule_autopurge()


## Preferences methods #########################################################

    def is_configurable(self):
        """A configurable plugin should have this method and return True"""
        return True

    def configure_dialog(self, plugin_apis, manager_dialog):
        self.preferences_load()
        self.preferences_dialog.set_transient_for(manager_dialog)
        self.pref_chbox_is_automatic.set_active(self.preferences["is_automatic"])
        self.pref_chbox_show_menu_item.set_active(self.preferences["show_menu_item"])
        self.pref_spinbtn_max_days.set_value(self.preferences["max_days"])
        self.preferences_dialog.show_all()

    def on_preferences_cancel(self, widget = None, data = None):
        self.preferences_dialog.hide()
        return True

    def on_preferences_ok(self, widget = None, data = None):
        self.preferences["is_automatic"] = self.pref_chbox_is_automatic.get_active()
        self.preferences["show_menu_item"] = self.pref_chbox_show_menu_item.get_active()
        self.preferences["max_days"] = self.pref_spinbtn_max_days.get_value()
        self.preferences_apply()
        self.preferences_store()
        self.preferences_dialog.hide()

    def preferences_load(self):
        data = self.plugin_api.load_configuration_object(self.PLUGIN_NAME,\
                                                         "preferences")
        if data == None or type(data) != type (dict()):
            self.preferences = self.DEFAULT_PREFERENCES
        else:
            self.preferences = data

    def preferences_store(self):
        self.plugin_api.save_configuration_object(self.PLUGIN_NAME,\
                                                  "preferences", \
                                                  self.preferences)

    def preferences_apply(self):
        #Showing the GUI
        if self.preferences['show_menu_item'] == True and \
                            self.menu_item_is_shown == False:
            self.plugin_api.add_menu_item(self.menu_item)
            self.menu_item_is_shown = True
        elif self.preferences['show_menu_item'] == False and \
                            self.menu_item_is_shown == True:
            self.plugin_api.remove_menu_item(self.menu_item)
            self.menu_item_is_shown = False
        #Auto-purge
        if self.preferences['is_automatic'] == True and \
                            self.is_automatic == False:
            self.schedule_autopurge()
            self.is_automatic = True
        elif self.preferences['is_automatic'] == False and \
                            self.is_automatic == True:
            self.cancel_autopurge()
            self.is_automatic = False