migrate Seen to django models and whatnot

this also adds south and django_extensions stuff, because that is the
natural thing to do. this is a pretty good start, i think
This commit is contained in:
Brian S. Stephan 2014-03-16 11:35:01 -05:00
parent 4633c936fb
commit 84ee09d4a3
8 changed files with 117 additions and 67 deletions

View File

@ -36,6 +36,8 @@ INSTALLED_APPS = (
'django.contrib.sessions', 'django.contrib.sessions',
'django.contrib.messages', 'django.contrib.messages',
'django.contrib.staticfiles', 'django.contrib.staticfiles',
'south',
'seen',
) )
MIDDLEWARE_CLASSES = ( MIDDLEWARE_CLASSES = (

View File

@ -1,6 +1,6 @@
""" """
Seen - track when a person speaks, and allow data to be queried Seen - track when a person speaks, and allow data to be queried
Copyright (C) 2010 Brian S. Stephan Copyright (C) 2014 Brian S. Stephan
This program is free software: you can redistribute it and/or modify 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 it under the terms of the GNU General Public License as published by
@ -14,92 +14,51 @@ GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
""" """
import re import re
from dateutil.tz import * from django.utils import timezone
import MySQLdb as mdb
from seen.models import SeenNick
from Module import Module from Module import Module
class Seen(Module): class Seen(Module):
"""Track when people say things in public channels, and report on it.""" """Track when people say things in public channels, and report on it."""
def db_init(self):
"""Create the table to store seen data."""
version = self.db_module_registered(self.__class__.__name__)
if version == None:
db = self.get_db()
try:
version = 1
cur = db.cursor(mdb.cursors.DictCursor)
cur.execute('''
CREATE TABLE seen_nicks (
nick VARCHAR(64) NOT NULL,
location VARCHAR(64) NOT NULL,
host VARCHAR(256) NOT NULL,
time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
what LONGTEXT NOT NULL
) ENGINE=InnoDB CHARACTER SET utf8 COLLATE utf8_bin
''')
cur.execute('''
CREATE UNIQUE INDEX seen_nicks_nick_and_location_index
ON seen_nicks (nick, location)
''')
db.commit()
self.db_register_module_version(self.__class__.__name__, version)
except mdb.Error as e:
db.rollback()
self.log.error("database error trying to create tables")
self.log.exception(e)
raise
finally: cur.close()
def do(self, connection, event, nick, userhost, what, admin_unlocked): def do(self, connection, event, nick, userhost, what, admin_unlocked):
"""Track pubmsg/privmsg events, and if asked, report on someone.""" """Track pubmsg/privmsg events, and if asked, report on someone."""
where = event.target() where = event.target()
db = self.get_db() # store the event. only learn events with real wheres
# whatever it is, store it if where:
try: try:
# if there's no where, this is probably a sub-command. don't learn it seen_nick = SeenNick.objects.get(nick=nick, channel=where)
if where: except SeenNick.DoesNotExist:
cur = db.cursor(mdb.cursors.DictCursor) seen_nick = SeenNick()
statement = 'REPLACE INTO seen_nicks (nick, location, host, what) VALUES (%s, %s, %s, %s)' seen_nick.nick = nick
cur.execute(statement, (nick, where, userhost, what)) seen_nick.channel = where
db.commit()
except mdb.Error as e: seen_nick.host = userhost
db.rollback() seen_nick.what = what
self.log.error("database error storing seen data") seen_nick.save()
self.log.exception(e)
raise
finally: cur.close()
match = re.search('^!seen\s+(\S+)$', what) match = re.search('^!seen\s+(\S+)$', what)
if match: if match:
nick = match.group(1) nick = match.group(1)
db = self.get_db()
try: try:
cur = db.cursor(mdb.cursors.DictCursor) seen_nick = SeenNick.objects.get(nick=nick, channel=where)
query = 'SELECT * FROM seen_nicks WHERE nick = %s AND location = %s' local_time = timezone.localtime(seen_nick.seen_time)
cur.execute(query, (nick,where)) return self.irc.reply(event,
result = cur.fetchone() "last saw {0:s} in {1:s} at {2:s} saying '{3:s}'."
if result: "".format(seen_nick.nick, seen_nick.channel,
seentime = result['time'].replace(tzinfo=tzlocal()) local_time, seen_nick.what))
replystr = 'last saw {0:s} in {3:s} at {1:s} saying \'{2:s}\'.'.format(result['nick'], seentime.astimezone(tzlocal()).strftime('%Y/%m/%d %H:%M:%S %Z'), result['what'], result['location']) except SeenNick.DoesNotExist:
return self.irc.reply(event, replystr) return self.irc.reply(event, "i have not seen {0:s} in {1:s}.".format(nick, where))
else:
return self.irc.reply(event, 'i have not seen {0:s} in {1:s}.'.format(nick, where))
except mdb.Error as e:
db.rollback()
self.log.error("database error retrieving seen data")
self.log.exception(e)
raise
finally: cur.close()
# vi:tabstop=4:expandtab:autoindent # vi:tabstop=4:expandtab:autoindent
# kate: indent-mode python;indent-width 4;replace-tabs on;

View File

@ -1,5 +1,7 @@
Django==1.6.2 Django==1.6.2
MySQL-python==1.2.3 MySQL-python==1.2.3
South==0.8.4
django-extensions==1.3.3
httplib2==0.7.4 httplib2==0.7.4
logilab-astng==0.24.0 logilab-astng==0.24.0
logilab-common==0.58.1 logilab-common==0.58.1

0
seen/__init__.py Normal file
View File

12
seen/admin.py Normal file
View File

@ -0,0 +1,12 @@
from django.contrib import admin
from seen.models import SeenNick
class SeenNickAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'seen_time')
admin.site.register(SeenNick, SeenNickAdmin)
# vi:tabstop=4:expandtab:autoindent

View File

@ -0,0 +1,46 @@
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'SeenNick'
db.create_table(u'seen_seennick', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('nick', self.gf('django.db.models.fields.CharField')(max_length=64)),
('channel', self.gf('django.db.models.fields.CharField')(max_length=64)),
('host', self.gf('django.db.models.fields.CharField')(max_length=255)),
('seen_time', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now, blank=True)),
('what', self.gf('django.db.models.fields.TextField')()),
))
db.send_create_signal(u'seen', ['SeenNick'])
# Adding unique constraint on 'SeenNick', fields ['nick', 'channel']
db.create_unique(u'seen_seennick', ['nick', 'channel'])
def backwards(self, orm):
# Removing unique constraint on 'SeenNick', fields ['nick', 'channel']
db.delete_unique(u'seen_seennick', ['nick', 'channel'])
# Deleting model 'SeenNick'
db.delete_table(u'seen_seennick')
models = {
u'seen.seennick': {
'Meta': {'ordering': "['-seen_time']", 'unique_together': "(('nick', 'channel'),)", 'object_name': 'SeenNick'},
'channel': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'host': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nick': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
'seen_time': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'what': ('django.db.models.fields.TextField', [], {})
}
}
complete_apps = ['seen']

View File

29
seen/models.py Normal file
View File

@ -0,0 +1,29 @@
from django.db import models
from django.utils import timezone
from django_extensions.db.fields import ModificationDateTimeField
class SeenNick(models.Model):
"""Track when a nick was seen in any channel."""
nick = models.CharField(max_length=64)
channel = models.CharField(max_length=64)
host = models.CharField(max_length=255)
seen_time = ModificationDateTimeField(editable=True)
what = models.TextField()
class Meta:
ordering = ['-seen_time',]
unique_together = ('nick', 'channel')
def __unicode__(self):
"""String representation of a seen nick."""
local_time = timezone.localtime(self.seen_time)
return u"{0:s} seen in {1:s} at {2:s}".format(self.nick, self.channel,
local_time.strftime('%Y-%m-%d %H:%M:%S %Z'))
# vi:tabstop=4:expandtab:autoindent