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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
|
# -*- Encoding: UTF-8 -*-
###
# Copyright (c) 2010, Elián Hanisch
# All rights reserved.
#
#
###
import supybot.conf as conf
import supybot.utils as utils
from supybot.commands import *
import supybot.plugins as plugins
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks
from supybot.ircutils import bold
from storm.locals import *
from storm.sqlobject import AutoUnicode
import re
from datetime import datetime
today = datetime.today
urls_schema = \
"""CREATE TABLE urls (\
id INTEGER PRIMARY KEY AUTOINCREMENT,\
channel TEXT COLLATE NOCASE,\
nick TEXT COLLATE NOCASE,\
url TEXT COLLATE NOCASE,\
date DATETIME,
UNIQUE (channel, url))
"""
others_schema = \
"""CREATE TABLE other_urls (\
id INTEGER PRIMARY KEY AUTOINCREMENT,\
channel TEXT COLLATE NOCASE,\
nick TEXT COLLATE NOCASE,\
url_id INTEGER references urls(id),\
date DATETIME)
"""
class Url(object):
__storm_table__ = 'urls'
id = Int(primary=True)
channel = AutoUnicode()
nick = AutoUnicode()
url = AutoUnicode()
date = DateTime()
def __init__(self, url, nick, channel):
self.url = url
self.nick = nick
self.channel = channel
self.date = today()
class OtherUrl(object):
__storm_table__ = 'other_urls'
id = Int(primary=True)
channel = AutoUnicode()
nick = AutoUnicode()
url_id = Int()
date = DateTime()
url = Reference(url_id, Url.id)
def __init__(self, nick, channel):
self.nick = nick
self.channel = channel
self.date = today()
octet = r'(?:2(?:[0-4]\d|5[0-5])|1\d\d|\d{1,2})'
ipAddr = r'%s(?:\.%s){3}' % (octet, octet)
label = r'[\w][-\w]*[\w]?'
domain = r'%s(?:\.%s)*\.[a-z][-\w]*[a-z]?' % (label, label)
urlre = r'(\w+://(?:%s|%s)(?::\d+)?(?:/[^\])>\s]*)?)' % (domain, ipAddr)
urlre = re.compile(urlre, re.I + re.U)
def makePattern(p):
s = ''
for c in p:
if c == '%':
s += '\%'
elif c == '_':
s += '\_'
elif c == '*':
s += '%'
elif c == '?':
s += '_'
else:
s += c
return unicode(s, 'utf-8')
class Urldb(callbacks.Plugin):
"""Add the help for "@plugin help Urldb" here
This should describe *how* to use this plugin."""
def __init__(self, irc):
self.__parent = super(Urldb, self)
self.__parent.__init__(irc)
import os
path = conf.supybot.directories.data()
filename = os.path.join(path, 'Urldb.sqlite.db')
db = create_database('sqlite:%s' %filename)
global store
store = Store(db)
try:
store.execute(urls_schema)
store.execute(others_schema)
store.commit()
except:
pass
def die(self):
store.commit()
store.close()
def doPrivmsg(self, irc, msg):
channel = msg.args[0]
if not self.registryValue('enabled', channel):
return
message = unicode(msg.args[1], 'utf-8')
#self.log.debug(message)
match = urlre.findall(message)
if not match:
return
#self.log.debug('MATCH: %s' %match)
for url in match:
_url = store.find(Url, Url.url.like(url)).one()
if _url:
other = OtherUrl(msg.nick, channel)
other.url = _url
store.add(other)
else:
url = Url(url, msg.nick, channel)
store.add(url)
store.commit()
class url(callbacks.Commands):
def search(self, irc, msg, args, channel, pattern, optlist):
"""[<channel>] <pattern> [--nick <pattern>]
Search urls that matches *pattern*, use '*' or '?' for wildcards, '\\' for escapes."""
nick = None
for k, v in optlist:
if k == 'nick':
nick = makePattern(v)
if pattern[0] != '*' and pattern[-1] != '*':
pattern = '*%s*' %pattern
#self.log.debug(s)
expressions = [
Url.url.like(makePattern(pattern), escape='\\'),
Url.channel.like(channel)]
if nick:
expressions.append(Url.nick.like(nick, escape='\\'))
result = store.find(Url, And(*expressions))
result.order_by(Desc(Url.date))
if result.is_empty():
irc.reply("Nothing found with '%s' in %s." %(pattern, channel))
else:
L = []
for url in result:
L.append("#%s %s by %s" %(url.id,
bold(url.url.encode('utf-8')),
str(url.nick)))
irc.reply('Found %s urls: %s' %(len(L), ', '.join(L)))
search = wrap(search, ['channel', 'something', getopts({'nick': 'something'})])
def info(self, irc, msg, args, id):
"""<id>
Displays information about an url, like who and when it was posted.
Url's id must be an integer."""
url = store.get(Url, id)
if not url:
irc.reply("Nothing found.")
return
irc.reply('#%s %s posted by %s in %s on %s' %(url.id,
bold(url.url.encode('utf-8')), bold(str(url.nick)),
str(url.channel), url.date))
info = wrap(info, ['int'])
def last(self, irc, msg, args, channel, nick):
"""[<channel>] [<nick>]
Displays the last url posted by <nick> or seen in channel."""
expressions = [ Url.channel.like(channel) ]
if nick:
expressions.append(Url.nick.like(makePattern(nick)))
result = store.find(Url, And(*expressions))
result.order_by(Url.date)
if result.is_empty():
irc.reply("Nothing found.")
else:
url = result.last()
irc.reply("#%s %s" %(url.id, bold(url.url.encode('utf-8'))))
last = wrap(last, ['channel', optional('something')])
def remove (self, irc, msg, args, id):
"""<id>
Removes url from the database."""
obj = store.get(Url, id)
if not obj:
irc.reply("No url found with #%s." %id)
return
store.find(OtherUrl, OtherUrl.url_id == id).remove()
store.remove(obj)
store.commit()
irc.reply("Url #%s deleted." %id)
remove = wrap(remove, ['admin', 'int'])
Class = Urldb
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
|