Skip to content

Instantly share code, notes, and snippets.

@ameliaikeda
Last active December 13, 2015 19:08
Show Gist options
  • Save ameliaikeda/4960297 to your computer and use it in GitHub Desktop.
Save ameliaikeda/4960297 to your computer and use it in GitHub Desktop.
A gist to stick a push notifications addition into hanyuu, until i clone the repo.
# in Class Song
# -- in method faves
@property
def api_keys(self):
keys_dict = {}
with manager.MySQLCursor as cur:
cur.execute("SELECT enick.apikey, enick.type FROM esong JOIN efave ON "
"efave.isong = esong.id JOIN enick ON efave.inick = "
"enick.id WHERE esong.hash = %s AND "
"enick.apikey IS NOT NULL ORDER BY enick.nick ASC",
(self.song.digest,))
if cur.rowcount == 0:
return {}
for row in cur:
keys_dict[row['type']].update({row['apikey'] : []})
return keys_dict
# ----------------------------------------------------------
import pushnotify
import re
# other imports implied
# No Dev Key (Yet). NotifyMyAndroid, Rate=800/hour
nma_client = pushnotify.nma.Client(application=config.app_name)
# Dev Key. Prowl, iOS, Rate=1000/hour
prowl_client = pushnotify.prowl.Client(config.prowl_key, config.app_name)
# Dev Key. Pushover, iOS + Android, Rate=8000/day. Pretty poor, if you ask me.
# might get a higher rate if it's cheap and this feature is popular enough
pushover_client = pushnotify.pushover.Client(config.pushover_key, config.app_name)
def send_push_notification(keys, metadata, key_type):
"""
Example:
faves.keys = {
1 : {api_key: []},
2 : {api_key: []},
3 : {api_key: []},
}
for key_type, key_list in faves.keys:
send_push_notification(key_list, metadata, key_type)
"""
if not keys:
return
if key_type == 1:
client = pushnotify.nma.Client(application=config.app_name)
elif key_type == 2:
client = pushnotify.prowl.Client(config.prowl_key, config.app_name)
elif key_type == 3:
client = pushnotify.pushover.Client(config.pushover_key)
else:
logging.warning("Unknown Key Type Used. Check the Database...")
return
try:
client.apikeys = keys
client.notify(metadata, "(Fave) Now Playing on R/a/dio: {0}".format(metadata), kwargs={"url" : "http://www.r-a-d.io"})
except pushnotify.exceptions.PushNotifyError:
logging.warning("Something went wrong and I can't be bothered to go fix it.")
# Basic Sanitising on keys.
def check_key(key):
if re.match(r"\W", key):
return False
return True
# Verify key is valid
def verify_key(key_type, key):
if key_type == u"nma":
if pushnotify.nma.Client().verify_user(key):
return 1
elif key_type == u"prowl":
if pushnotify.prowl.Client(config.prowl_key).verify_user(key):
return 2
elif key_type == u"pushover":
if pushnotify.prowl.Client(config.pushover_key).verify_user(key):
return 3
return None
def register_fave_key(server, nick, channel, text, hostmask):
text = tokenize(text)
if len(text) >= 4:
key = text[2]
key_type = text[3]
if check_key(key):
verify = verify_key(key_type.lower(), key)
if verify:
with manager.MySQLCursor as cur:
cur.execute("INSERT INTO enick (nick, apikey, type) VALUES (%(nick)s, %(apikey)s, %(type_)s) "
"ON DUPLICATE KEY UPDATE apikey=%(apikey)s, type=%(type_)s", { nick : nick, apikey: key,
type_ : verify })
else:
server.privmsg(nick, u"Invalid key type or invalid key. Valid types are nma, pushover, or prowl. Keys are case sensitive.")
else:
server.privmsg(nick, u"Keys must be alphanumeric.")
else:
server.privmsg(nick, u"Syntax: REGISTER KEY <key> <nma|prowl|pushover>. (e.g. REGISTER KEY abcdef1234567890 nma)")
return
register_fave_key.handler = ("on_text", r'REGISTER KEY', irc.ALL_NICKS, irc.PRIVATE_MESSAGE)
spam = bootstrap.Switch(True) # side effect: hanyuu no longer spams as ferociously if that pesky race condition returns
def announce(server, spam=spam):
np = manager.NP()
faves = np.api_keys
status = manager.Status()
if not spam: # No more requiring a fave for a now starting announce. (Hiroto)
message = u"Now starting:{c4} '{np}' {c}[{length}]({listeners} listeners), {faves} fave{fs}, played {times} time{ts}, {c3}LP:{c} {lp}".format(
np=np.metadata, length=np.lengthf, listeners=status.listeners,
faves=np.favecount,
fs="" if (np.favecount == 1) else "s",
times=np.playcount,
ts="" if (np.playcount == 1) else "s",
lp=np.lpf,
**irc_colours)
server.privmsg("#r/a/dio", message)
spam.reset()
for type_, push_dict in api_keys:
send_push_notification(push_dict, np.metadata, type_) # sticking it in spam
for nick in np.faves:
if (server.inchannel("#r/a/dio", nick)):
server.notice(nick, u"Fave: {0} is playing."\
.format(np.metadata))
announce.exposed = True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment