make urlhistory give more information about when urls were linked

This commit is contained in:
Ryan Hitchman 2010-02-05 19:54:28 -07:00
parent 8f2c15b730
commit 3c4edb54c2
2 changed files with 39 additions and 23 deletions

View File

@ -1,12 +1,12 @@
import time
import math
import re
import time
from util import hook, urlnorm
from util import hook, urlnorm, timesince
url_re = re.compile(r'([a-zA-Z]+://|www\.)[^ ]*')
expiration_period = 60 * 60 * 24 # 1 day
expiration_period_text = "24 hours"
ignored_urls = [urlnorm.normalize("http://google.com")]
@ -27,19 +27,39 @@ def insert_history(db, chan, url, nick):
def get_history(db, chan, url):
db.execute("delete from urlhistory where time < ?",
(time.time() - expiration_period,))
nicks = db.execute("select nick from urlhistory where "
"chan=? and url=?", (chan, url)).fetchall()
return [x[0] for x in nicks]
return db.execute("select nick, time from urlhistory where "
"chan=? and url=? order by time desc", (chan, url)).fetchall()
def get_nicklist(nicks):
nicks = sorted(set(nicks), key=unicode.lower)
def nicklist(nicks):
nicks = sorted(dict(nicks), key=unicode.lower)
if len(nicks) <= 2:
return ' and '.join(nicks)
else:
return ', and '.join((', '.join(nicks[:-1]), nicks[-1]))
def ordinal(count):
return ["once", "twice", "%d times" % count][min(count, 3) - 1]
def format_reply(history):
if not history:
return
last_nick, recent_time = history[0]
last_time = timesince.timesince(recent_time)
if len(history) == 1:
return "%s linked that %s ago." % (last_nick, last_time)
hour_span = math.ceil((time.time() - history[-1][1]) / 3600)
hour_span = '%.0f hours' % hour_span if hour_span > 1 else 'hour'
hlen = len(history)
ordinal = ["once", "twice", "%d times" % hlen][min(hlen, 3) - 1]
if len(dict(history)) == 1:
last = "last linked %s ago" % last_time
else:
last = "last linked by %s %s ago" % (last_nick, last_time)
return "that url has been posted %s in the past %s by %s (%s)." % (ordinal,
hour_span, nicklist(history), last)
@hook.command(hook=r'(.*)', prefix=False)
def urlinput(inp, nick='', chan='', server='', reply=None, bot=None):
@ -49,15 +69,9 @@ def urlinput(inp, nick='', chan='', server='', reply=None, bot=None):
# URL detected
db = db_connect(bot, server)
try:
url = urlnorm.normalize(m.group(0))
if url not in ignored_urls:
dupes = get_history(db, chan, url)
history = get_history(db, chan, url)
insert_history(db, chan, url, nick)
if dupes and nick not in dupes:
reply("That link has been posted " + ordinal(len(dupes))
+ " in the past " + expiration_period_text + " by " +
get_nicklist(dupes))
finally:
db.commit()
db.close()
if nick not in dict(history) or True:
return format_reply(history)

View File

@ -50,6 +50,8 @@ def timesince(d, now=None):
(60 * 60, ('hour', 'hours')),
(60, ('minute', 'minutes'))
)
# Convert int or float (unix epoch) to datetime.datetime for comparison
if isinstance(d, int) or isinstance(d, float):
d = datetime.datetime.fromtimestamp(d)