~ubuntu-branches/ubuntu/utopic/gozerbot/utopic

« back to all changes in this revision

Viewing changes to build/lib/gplugs/olddb/infoitem.py

  • Committer: Package Import Robot
  • Author(s): Jeremy Malcolm
  • Date: 2012-04-03 21:58:28 UTC
  • mfrom: (3.1.11 sid)
  • Revision ID: package-import@ubuntu.com-20120403215828-6mik0tzug5na93la
Tags: 0.99.1-2
* Removes logfiles on purge (Closes: #668767)
* Reverted location of installed files back to /usr/lib/gozerbot.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# plugs/infoitem.py
 
2
#
 
3
#
 
4
 
 
5
""" information items .. keyword/description pairs """
 
6
 
 
7
__copyright__ = 'this file is in the public domain'
 
8
 
 
9
from gozerbot.commands import cmnds
 
10
from gozerbot.examples import examples
 
11
from gozerbot.redispatcher import rebefore, reafter
 
12
from gozerbot.datadir import datadir
 
13
from gozerbot.persist.persist import Persist
 
14
from gozerbot.generic import lockdec, cchar
 
15
from gozerbot.aliases import aliases
 
16
from gozerbot.plughelp import plughelp
 
17
from gozerbot.callbacks import callbacks
 
18
from gozerbot.users import users
 
19
from gozerbot.config import config
 
20
if not config['nodb']:
 
21
    from gozerbot.database.db import db
 
22
import thread, os, time
 
23
 
 
24
plughelp.add('infoitem', 'also known as factoids .. info can be retrieved \
 
25
by keyword or searched')
 
26
 
 
27
infolock = thread.allocate_lock()
 
28
 
 
29
# create lock descriptor
 
30
locked = lockdec(infolock)
 
31
 
 
32
class Infoitems(Persist):
 
33
 
 
34
    """ information items """
 
35
 
 
36
    @locked
 
37
    def add(self, item, issue, userhost=None, ttime=None):
 
38
        """ add an item """
 
39
        item = item.lower()
 
40
        if self.data.has_key(item):
 
41
            if not issue in self.data[item]:
 
42
                self.data[item].append(issue)
 
43
        else:
 
44
            self.data[item] = [issue]
 
45
        self.save()
 
46
 
 
47
    @locked
 
48
    def addnosave(self, item, issue, userhost=None, ttime=None):
 
49
        """ add item but don't save """
 
50
        item = item.lower()
 
51
        if self.data.has_key(item):
 
52
            self.data[item].append(issue)
 
53
        else:
 
54
            self.data[item] = [issue]
 
55
 
 
56
    @locked
 
57
    def deltxt(self, item, txt):
 
58
        """ delete todo item with txt in it """
 
59
        got = 0
 
60
        if not self.data.has_key(item):
 
61
            return got
 
62
        for i in range(len(self.data[item])-1, -1, -1):
 
63
            if txt in self.data[item][i]:
 
64
                del self.data[item][i]
 
65
                got += 1
 
66
                break
 
67
        if got:
 
68
            self.save()
 
69
        return got
 
70
 
 
71
    @locked
 
72
    def delete(self, item, itemnr):
 
73
        """ delete item with nr from list """
 
74
        try:
 
75
            del self.data[item.lower()][int(itemnr)]
 
76
            self.save()
 
77
            return 1
 
78
        except IndexError:
 
79
            return 0
 
80
        except ValueError:
 
81
            return 0
 
82
        except KeyError:
 
83
            return 0
 
84
 
 
85
    def get(self, item):
 
86
        """ get description of item """
 
87
        if self.data.has_key(item):
 
88
            return self.data[item]
 
89
 
 
90
    def size(self):
 
91
        """ return number of items """
 
92
        return len(self.data)
 
93
 
 
94
    def searchdescr(self, txt):
 
95
        result = []
 
96
        for i, j in self.data.iteritems():
 
97
            for z in j:
 
98
                if txt in z:
 
99
                    result.append((i, z))
 
100
        return result
 
101
 
 
102
    def searchitem(self, txt):
 
103
        result = []
 
104
        for i, j in self.data.iteritems():
 
105
            if txt in i:
 
106
                result.append((i, j))
 
107
        return result
 
108
 
 
109
class InfoitemsDb(object):
 
110
 
 
111
    """ information items """
 
112
 
 
113
    def add(self, item, description, userhost, ttime):
 
114
        """ add an item """
 
115
        item = item.lower()
 
116
        result = db.execute(""" INSERT INTO infoitems(item, description, \
 
117
userhost, time) VALUES(%s, %s, %s, %s) """, (item, description, \
 
118
userhost, ttime))
 
119
        return result
 
120
 
 
121
    def get(self, item):
 
122
        """ get infoitems """
 
123
        item = item.lower()
 
124
        result = db.execute(""" SELECT description FROM \
 
125
infoitems WHERE item = %s """, item)
 
126
        res = []
 
127
        if result:
 
128
            for i in result:
 
129
                res.append(i[0])
 
130
        return res
 
131
 
 
132
    def delete(self, indexnr):
 
133
        """ delete item with indexnr  """
 
134
        result = db.execute(""" DELETE FROM infoitems WHERE indx = %s """, \
 
135
indexnr)
 
136
        return result
 
137
 
 
138
    def deltxt(self, item, txt):
 
139
        """ delete item with matching txt """
 
140
        result = db.execute(""" DELETE FROM infoitems WHERE item = %s AND \
 
141
description LIKE %s """, (item, '%%%s%%' % txt))
 
142
        return result
 
143
 
 
144
    def size(self):
 
145
        """ return number of items """
 
146
        result = db.execute(""" SELECT COUNT(*) FROM infoitems """)
 
147
        return result[0][0]
 
148
 
 
149
    def searchitem(self, search):
 
150
        """ search items """
 
151
        result = db.execute(""" SELECT item, description \
 
152
FROM infoitems WHERE item LIKE %s """, '%%%s%%' % search)
 
153
        return result
 
154
 
 
155
    def searchdescr(self, search):
 
156
        """ search descriptions """
 
157
        result = db.execute(""" SELECT item, description \
 
158
FROM infoitems WHERE description LIKE %s """, '%%%s%%' % search)
 
159
        return result
 
160
 
 
161
if not config['nodb']:
 
162
    info = InfoitemsDb()
 
163
else:
 
164
    info = Infoitems(datadir + os.sep + 'infoitems')
 
165
    if not info.data:
 
166
        info.data = {}
 
167
assert(info)
 
168
 
 
169
def size():
 
170
    """ return number of infoitems """
 
171
    return info.size()
 
172
 
 
173
def infopre(bot, ievent):
 
174
    """ see if info callback needs to be called """
 
175
    cc = cchar(bot, ievent)
 
176
    if ievent.origtxt and cc == ievent.origtxt[0] and not ievent.usercmnd \
 
177
and ievent.txt:
 
178
        return 1
 
179
 
 
180
def infocb(bot, ievent):
 
181
    """ implement a !infoitem callback """
 
182
    if users.allowed(ievent.userhost, 'USER'):
 
183
        data = info.get(ievent.txt)
 
184
        if data:
 
185
            ievent.reply('%s is: ' % ievent.txt, data , dot=True)
 
186
 
 
187
callbacks.add('PRIVMSG', infocb, infopre)
 
188
 
 
189
def handle_infosize(bot, ievent):
 
190
    """ info-size .. show number of information items """
 
191
    ievent.reply("we have %s infoitems" % info.size())
 
192
 
 
193
cmnds.add('info-size', handle_infosize, ['USER', 'WEB', 'ANON'])
 
194
examples.add('info-size', 'show number of infoitems', 'info-size')
 
195
 
 
196
def handle_addinfoitem(bot, ievent):
 
197
    """ <keyword> = <description> .. add information item """
 
198
    try:
 
199
        (what, description) = ievent.groups
 
200
    except ValueError:
 
201
        ievent.reply('i need <item> <description>')
 
202
        return
 
203
    if len(description) < 3:
 
204
        ievent.reply('i need at least 3 chars for the description')
 
205
        return
 
206
    what = what.strip()
 
207
    info.add(what, description, ievent.userhost, time.time())
 
208
    ievent.reply('item added')
 
209
 
 
210
rebefore.add(10, '^(.+?)\s+=\s+(.+)$', handle_addinfoitem, ['USER', \
 
211
'INFOADD'], allowqueue=False)
 
212
examples.add('=', 'add description to item', 'dunk = top')
 
213
 
 
214
def handle_question(bot, ievent):
 
215
    """ <keyword>? .. ask for information item description """
 
216
    try:
 
217
        what = ievent.groups[0]
 
218
    except IndexError:
 
219
        ievent.reply('i need a argument')
 
220
        return
 
221
    what = what.strip().lower()
 
222
    infoitems = info.get(what)
 
223
    if infoitems:
 
224
        ievent.reply("%s is: " % what, infoitems, dot=True)
 
225
    else:
 
226
        ievent.reply('nothing known about %s' % what)
 
227
        return
 
228
 
 
229
reafter.add(10, '^(.+)\?$', handle_question, ['USER', 'WEB', 'JCOLL', \
 
230
'ANON'], allowqueue=True)
 
231
reafter.add(10, '^\?(.+)$', handle_question, ['USER', 'WEB', 'JCOLL', \
 
232
'ANON'], allowqueue=True)
 
233
examples.add('?', 'show infoitems of <what>', '1) test? 2) ?test')
 
234
 
 
235
def handle_forget(bot, ievent):
 
236
    """ forget <keyword> <txttomatch> .. remove information item where \
 
237
        description matches txt given """
 
238
    if len(ievent.args) > 1:
 
239
        what = ' '.join(ievent.args[:-1])
 
240
        txt = ievent.args[-1]
 
241
    else:
 
242
        ievent.missing('<item> <txttomatch> (min 3 chars)')
 
243
        return
 
244
    if len(txt) < 3:
 
245
        ievent.reply('i need txt with at least 3 characters')
 
246
        return
 
247
    what = what.strip().lower()
 
248
    try:
 
249
        nrtimes = info.deltxt(what, txt)
 
250
    except KeyError:
 
251
        ievent.reply('no records matching %s found' % what)
 
252
        return
 
253
    if nrtimes:
 
254
        ievent.reply('item deleted')
 
255
    else:
 
256
        ievent.reply('delete %s of %s failed' % (txt, what))
 
257
 
 
258
cmnds.add('info-forget', handle_forget, ['FORGET', 'OPER'])
 
259
examples.add('info-forget', 'forget <item> containing <txt>', 'info-forget \
 
260
dunk bla')
 
261
aliases.data['forget'] = 'info-forget'
 
262
 
 
263
def handle_searchdescr(bot, ievent):
 
264
    """ info-sd <txttosearchfor> .. search information items descriptions """
 
265
    if not ievent.rest:
 
266
        ievent.missing('<txt>')
 
267
        return
 
268
    else:
 
269
        what = ievent.rest
 
270
    what = what.strip().lower()
 
271
    result = info.searchdescr(what)
 
272
    if result: 
 
273
        res = []
 
274
        for i in result:
 
275
            res.append("[%s] %s" % (i[0], i[1]))
 
276
        ievent.reply("the following matches %s: " % what, res, dot=True)
 
277
    else:
 
278
        ievent.reply('none found')
 
279
 
 
280
cmnds.add('info-sd', handle_searchdescr, ['USER', 'WEB', 'ANON'])
 
281
examples.add('info-sd', 'info-sd <txt> ..  search description of \
 
282
infoitems', 'info-sd http')
 
283
aliases.data['sd'] = 'info-sd'
 
284
aliases.data['sl'] = 'info-sd'
 
285
 
 
286
def handle_searchitem(bot, ievent):
 
287
    """ info-si <txt> .. search information keywords """
 
288
    if not ievent.rest:
 
289
        ievent.missing('<txt>')
 
290
        return
 
291
    else:
 
292
        what = ievent.rest
 
293
    what = what.strip().lower()
 
294
    result = info.searchitem(what)
 
295
    if result:
 
296
        res = []
 
297
        for i in result:
 
298
            res.append("[%s] %s" % (i[0], i[1]))
 
299
        ievent.reply("the following matches %s: " % what, res, dot=True)
 
300
    else:
 
301
        ievent.reply('none found')
 
302
 
 
303
cmnds.add('info-si', handle_searchitem, ['USER', 'WEB', 'ANON'])
 
304
examples.add('info-si', 'info-si <txt> ..  search the infoitems keys', \
 
305
'info-si test')
 
306
aliases.data['si'] = 'info-si'