Skip to content

Commit

Permalink
Revert "Migrate modules to new db"
Browse files Browse the repository at this point in the history
This reverts commit f263963.
  • Loading branch information
embolalia committed Dec 16, 2014
1 parent f4087f7 commit f2e3790
Show file tree
Hide file tree
Showing 6 changed files with 208 additions and 111 deletions.
19 changes: 13 additions & 6 deletions willie/modules/adminchannel.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,8 @@ def topic(bot, trigger):

narg = 1
mask = None
mask = bot.db.get_channel_value(channel, 'topic_mask')
if bot.db and channel in bot.db.preferences:
mask = bot.db.preferences.get(channel, 'topic_mask')
mask = mask or default_mask(trigger)
mask = mask.replace('%s', '{}')
narg = len(re.findall('{}', mask))
Expand All @@ -342,15 +343,21 @@ def set_mask(bot, trigger):
"""
if bot.privileges[trigger.sender][trigger.nick] < OP:
return
bot.db.set_channel_value(trigger.sender, 'topic_mask', trigger.group(2))
bot.say("Gotcha, " + trigger.nick)
if not bot.db:
bot.say("I'm afraid I can't do that.")
else:
bot.db.preferences.update(trigger.sender.lower(), {'topic_mask': trigger.group(2)})
bot.say("Gotcha, " + trigger.nick)


@commands('showmask')
def show_mask(bot, trigger):
"""Show the topic mask for the current channel."""
if bot.privileges[trigger.sender][trigger.nick] < OP:
return
mask = bot.db.get_channel_value(trigger.sender, 'topic_mask')
mask = mask or default_mask(trigger)
bot.say(mask)
if not bot.db:
bot.say("I'm afraid I can't do that.")
elif trigger.sender.lower() in bot.db.preferences:
bot.say(bot.db.preferences.get(trigger.sender.lower(), 'topic_mask'))
else:
bot.say(default_mask(trigger))
105 changes: 61 additions & 44 deletions willie/modules/clock.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,14 @@ def configure(config):
'Preferred time format (http://strftime.net)', '%F - %T%Z')


def setup(bot):
#Having a db means pref's exists. Later, we can just use `if bot.db`.
if bot.db and not bot.db.preferences.has_columns('tz'):
bot.db.preferences.add_columns(['tz'])
if bot.db and not bot.db.preferences.has_columns('time_format'):
bot.db.preferences.add_columns(['time_format'])


@commands('t', 'time')
@example('.t America/New_York')
def f_time(bot, trigger):
Expand All @@ -51,6 +59,8 @@ def update_user(bot, trigger):
"""
if not pytz:
bot.reply("Sorry, I don't have timezone support installed.")
elif not bot.db:
bot.reply("I can't remember that; I don't have a database.")
else:
tz = trigger.group(2)
if not tz:
Expand All @@ -62,7 +72,7 @@ def update_user(bot, trigger):
"http://dft.ba/-tz")
return

bot.db.set_nick_value(trigger.nick, 'timezone', tz)
bot.db.preferences.update(trigger.nick, {'tz': tz})
if len(tz) < 7:
bot.say("Okay, {}, but you should use one from http://dft.ba/-tz "
"if you use DST.".format(trigger.nick))
Expand All @@ -77,30 +87,33 @@ def update_user_format(bot, trigger):
Sets your preferred format for time. Uses the standard strftime format. You
can use http://strftime.net or your favorite search engine to learn more.
"""
tformat = trigger.group(2)
if not tformat:
bot.reply("What format do you want me to use? Try using"
" http://strftime.net to make one.")

tz = get_timezone(bot.db, bot.config, None, None, trigger.sender)

# Get old format as back-up
old_format = bot.db.get_nick_value(trigger.nick, 'time_format')

# Save the new format in the database so we can test it.
bot.db.set_nick_value(trigger.nick, 'time_format', tformat)

try:
timef = format_time(db=bot.db, zone=tz, nick=trigger.nick)
except:
bot.reply("That format doesn't work. Try using"
" http://strftime.net to make one.")
# New format doesn't work. Revert save in database.
bot.db.set_nick_value(trigger.nick, 'time_format', old_format)
return
bot.reply("Got it. Your time will now appear as %s. (If the "
"timezone is wrong, you might try the settz command)"
% timef)
if bot.db:
tformat = trigger.group(2)
if not tformat:
bot.reply("What format do you want me to use? Try using"
" http://strftime.net to make one.")
return

tz = get_timezone(bot.db, bot.config, None, None, trigger.sender)

# Get old format as back-up
old_format = bot.db.preferences.get(trigger.nick, 'time_format')

# Save the new format in the database so we can test it.
bot.db.preferences.update(trigger.nick, {'time_format': tformat})

try:
timef = format_time(db=bot.db, zone=tz, nick=trigger.nick)
except:
bot.reply("That format doesn't work. Try using"
" http://strftime.net to make one.")
# New format doesn't work. Revert save in database.
bot.db.preferences.update(trigger.nick, {'time_format': old_format})
return
bot.reply("Got it. Your time will now appear as {}. (If the timezone "
"is wrong, you might try the settz command)".format(timef))
else:
bot.reply("I can't remember that; I don't have a database.")


@commands('channeltz')
Expand All @@ -113,6 +126,8 @@ def update_channel(bot, trigger):
return
elif not pytz:
bot.reply("Sorry, I don't have timezone support installed.")
elif not bot.db:
bot.reply("I can't remember that; I don't have a database.")
else:
tz = trigger.group(2)
if not tz:
Expand All @@ -124,7 +139,7 @@ def update_channel(bot, trigger):
"http://dft.ba/-tz")
return

bot.db.set_channel_value(trigger.sender, 'timezone', tz)
bot.db.preferences.update(trigger.sender, {'tz': tz})
if len(tz) < 7:
bot.say("Okay, {}, but you should use one from http://dft.ba/-tz "
"if you use DST.".format(trigger.nick))
Expand All @@ -142,21 +157,23 @@ def update_channel_format(bot, trigger):
"""
if bot.privileges[trigger.sender][trigger.nick] < OP:
return

tformat = trigger.group(2)
if not tformat:
bot.reply("What format do you want me to use? Try using"
" http://strftime.net to make one.")

tz = get_timezone(bot.db, bot.config, None, None, trigger.sender)
try:
timef = format_time(zone=tz)
except:
bot.reply("That format doesn't work. Try using"
" http://strftime.net to make one.")
return
bot.db.set_channel_value(trigger.sender, 'time_format', tformat)
bot.reply("Got it. Times in this channel will now appear as %s "
"unless a user has their own format set. (If the timezone"
" is wrong, you might try the settz and channeltz "
"commands)" % timef)
elif not bot.db:
bot.reply("I can't remember that; I don't have a database.")
else:
tformat = trigger.group(2)
if not tformat:
bot.reply("What format do you want me to use? Try using"
" http://strftime.net to make one.")

tz = get_timezone(bot.db, bot.config, None, None, trigger.sender)
try:
timef = format_time(zone=tz)
except:
bot.reply("That format doesn't work. Try using"
" http://strftime.net to make one.")
return
bot.db.preferences.update(trigger.sender, {'time_format': tformat})
bot.reply("Got it. Times in this channel will now appear as {} "
"unless a user has their own format set. (If the timezone"
" is wrong, you might try the settz and channeltz "
"commands)".format(timef))
110 changes: 84 additions & 26 deletions willie/modules/rss.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@
def setup(bot):
bot.memory['rss_manager'] = RSSManager(bot)

if not bot.db:
raise ConfigurationError("Database not set up, or unavailable.")
conn = bot.db.connect()
c = conn.cursor()

Expand All @@ -38,14 +40,31 @@ def setup(bot):
c.execute('SELECT * FROM rss_feeds')
except StandardError:
create_table(bot, c)
migrate_from_old_tables(bot, c)

# These tables are no longer used, but lets not delete them right away.
# c.execute('DROP TABLE IF EXISTS rss')
# c.execute('DROP TABLE IF EXISTS recent')

conn.commit()

# The modified column was added on 2013-07-21.
try:
c.execute('SELECT modified FROM rss_feeds')
except StandardError:
c.execute('ALTER TABLE rss_feeds ADD modified TEXT')
conn.commit()

conn.close()


def create_table(bot, c):
# MySQL needs to only compare on the first n characters of a TEXT field
# but SQLite won't accept the syntax needed to make it do it.
primary_key = '(channel, feed_name)'
if bot.db.type == 'mysql':
primary_key = '(channel(254), feed_name(254))'
else:
primary_key = '(channel, feed_name)'

c.execute('''CREATE TABLE IF NOT EXISTS rss_feeds (
channel TEXT,
Expand All @@ -63,6 +82,41 @@ def create_table(bot, c):
)'''.format(primary_key))


def migrate_from_old_tables(bot, c):
sub = bot.db.substitution

try:
c.execute('SELECT * FROM rss')
oldfeeds = c.fetchall()
except StandardError:
oldfeeds = []

for feed in oldfeeds:
channel, site_name, site_url, fg, bg = feed

# get recent article if possible
try:
c.execute('''
SELECT article_title, article_url FROM recent
WHERE channel = {0} AND site_name = {0}
'''.format(sub), (channel, site_name))
article_title, article_url = c.fetchone()
except (StandardError, TypeError):
article_title = article_url = None

# add feed to new table
if article_url:
c.execute('''
INSERT INTO rss_feeds (channel, feed_name, feed_url, fg, bg, article_title, article_url)
VALUES ({0}, {0}, {0}, {0}, {0}, {0}, {0})
'''.format(sub), (channel, site_name, site_url, fg, bg, article_title, article_url))
else:
c.execute('''
INSERT INTO rss_feeds (channel, feed_name, feed_url, fg, bg)
VALUES ({0}, {0}, {0}, {0}, {0})
'''.format(sub), (channel, site_name, site_url, fg, bg))


def colour_text(text, fg=None, bg=None):
"""Given some text and fore/back colours, return a coloured text string."""
if fg is None:
Expand All @@ -81,6 +135,7 @@ def manage_rss(bot, trigger):
class RSSManager:
def __init__(self, bot):
self.running = True
self.sub = bot.db.substitution

# get a list of all methods in this class that start with _rss_
self.actions = sorted(method[5:] for method in dir(self) if method[:5] == '_rss_')
Expand Down Expand Up @@ -149,19 +204,19 @@ def _rss_add(self, bot, trigger, c):
bg = int(match.group(5)) % 16 if match.group(5) else None

c.execute('''
SELECT * FROM rss_feeds WHERE channel = ? AND feed_name = ?
''', (channel, feed_name))
SELECT * FROM rss_feeds WHERE channel = {0} AND feed_name = {0}
'''.format(self.sub), (channel, feed_name))
if not c.fetchone():
c.execute('''
INSERT INTO rss_feeds (channel, feed_name, feed_url, fg, bg)
VALUES (?, ?, ?, ?, ?)
''', (channel, feed_name, feed_url, fg, bg))
VALUES ({0}, {0}, {0}, {0}, {0})
'''.format(self.sub), (channel, feed_name, feed_url, fg, bg))
bot.reply("Successfully added the feed to the channel.")
else:
c.execute('''
UPDATE rss_feeds SET feed_url = ?, fg = ?, bg = ?
WHERE channel = ? AND feed_name = ?
''', (feed_url, fg, bg, channel, feed_name))
UPDATE rss_feeds SET feed_url = {0}, fg = {0}, bg = {0}
WHERE channel = {0} AND feed_name = {0}
'''.format(self.sub), (feed_url, fg, bg, channel, feed_name))
bot.reply("Successfully modified the feed.")
return True

Expand All @@ -185,9 +240,9 @@ def _rss_del(self, bot, trigger, c):
args = [arg for arg in (channel, feed_name) if arg]

c.execute(('DELETE FROM rss_feeds WHERE '
+ ('channel = ? AND ' if channel else '')
+ ('feed_name = ?' if feed_name else '')
).rstrip(' AND '), args)
+ ('channel = {0} AND ' if channel else '')
+ ('feed_name = {0}' if feed_name else '')
).rstrip(' AND ').format(self.sub), args)

if c.rowcount:
noun = 'feeds' if c.rowcount != 1 else 'feed'
Expand Down Expand Up @@ -225,10 +280,10 @@ def _toggle(self, bot, trigger, c):
feed_name = match.group(3).strip('"') if match.group(3) else None
args = [arg for arg in (enabled, channel, feed_name) if arg is not None]

c.execute(('UPDATE rss_feeds SET enabled = ? WHERE '
+ ('channel = ? AND ' if channel else '')
+ ('feed_name = ?' if feed_name else '')
).rstrip(' AND '), args)
c.execute(('UPDATE rss_feeds SET enabled = {0} WHERE '
+ ('channel = {0} AND ' if channel else '')
+ ('feed_name = {0}' if feed_name else '')
).rstrip(' AND ').format(self.sub), args)

if c.rowcount:
noun = 'feeds' if c.rowcount != 1 else 'feed'
Expand Down Expand Up @@ -320,6 +375,7 @@ def read_feeds(bot, force=False):
if not bot.memory['rss_manager'].running and not force:
return

sub = bot.db.substitution
conn = bot.db.connect()
c = conn.cursor()
c.execute('SELECT * FROM rss_feeds')
Expand All @@ -334,9 +390,9 @@ def read_feeds(bot, force=False):

def disable_feed():
c.execute('''
UPDATE rss_feeds SET enabled = ?
WHERE channel = ? AND feed_name = ?
''', (0, feed.channel, feed.name))
UPDATE rss_feeds SET enabled = {0}
WHERE channel = {0} AND feed_name = {0}
'''.format(sub), (0, feed.channel, feed.name))
conn.commit()

try:
Expand All @@ -360,9 +416,9 @@ def disable_feed():
feed.name, fp.href
)
c.execute('''
UPDATE rss_feeds SET feed_url = ?
WHERE channel = ? AND feed_name = ?
''', (fp.href, feed.channel, feed.name))
UPDATE rss_feeds SET feed_url = {0}
WHERE channel = {0} AND feed_name = {0}
'''.format(sub), (fp.href, feed.channel, feed.name))
conn.commit()

elif status == 410: # GONE
Expand Down Expand Up @@ -393,10 +449,10 @@ def disable_feed():
# save article title, url, and modified date
c.execute('''
UPDATE rss_feeds
SET article_title = ?, article_url = ?, published = ?, etag = ?, modified = ?
WHERE channel = ? AND feed_name = ?
''', (entry.title, entry.link, entry_dt, feed_etag, feed_modified,
feed.channel, feed.name))
SET article_title = {0}, article_url = {0}, published = {0}, etag = {0}, modified = {0}
WHERE channel = {0} AND feed_name = {0}
'''.format(sub), (entry.title, entry.link, entry_dt, feed_etag, feed_modified,
feed.channel, feed.name))
conn.commit()

if feed.published and entry_dt:
Expand All @@ -419,7 +475,9 @@ def disable_feed():
timestamp = entry_update_dt or entry_dt
if timestamp:
# attempt to get time format from preferences
tformat = bot.db.get_channel_value(feed.channel, 'time_format')
tformat = ''
if feed.channel in bot.db.preferences:
tformat = bot.db.preferences.get(feed.channel, 'time_format') or tformat
if not tformat and bot.config.has_option('clock', 'time_format'):
tformat = bot.config.clock.time_format

Expand Down
Loading

0 comments on commit f2e3790

Please sign in to comment.