예제 #1
0
def update_gateways():
    """Add (Refresh) Gateways to Redis"""
    # Add gateways
    gateways = SESSION.query(Gateway).all()
    gateway_dict = {gw.token: gw.name for gw in gateways}
    REDIS.set("gateways", json.dumps(gateway_dict))
    logger.info(f"[INIT REDIS] add {len(gateway_dict)} gateways")
예제 #2
0
파일: lua.py 프로젝트: johnjansen/Magpie
def stored_procedure( script_name, *args ):
	try:
		sha = REDIS.get( 'lua_function:%s' % script_name )
		return REDIS.evalsha( sha, len(args), *args )
	except Exception as err:
		LOG.debug( '%s failed to run stored procedure, with error %s and args %s' % (script_name, str(err), str(args)) )
		return str(err)
예제 #3
0
 def verify_token(token):
     gateway_dict = json.loads(REDIS.get("gateways"))
     if token not in gateway_dict:
         logger.error(f"[GW OAUTH Failed] token: {token}")
         g.error_message = "Access Denied"
         return False
     g.gateway_name = gateway_dict[token]
     logger.info(f"[GW OAUTH Success] GW: {g.gateway_name}")
     return True
예제 #4
0
파일: lua.py 프로젝트: johnjansen/Magpie
import os.path
import glob

from config import LOG, REDIS

# load all the lua scripts into redis
# storing keys and sha's
LOG.info( "loading stored procedures" )

for script in glob.glob( os.path.join( 'lua', '*.lua' ) ):
	try:
		script_code = open( script, "r" ).read()
		script_name, script_type = os.path.splitext( script )
		script_name = os.path.basename( script_name )
		REDIS.set( 'lua_function:%s' % script_name, REDIS.register_script( script_code ).sha )
		LOG.debug( 'loaded %s' % script_name )
	except Exception as err:
		LOG.debug( '%s failed to load, with error %s' % (script_name, str(err)) )

def pairs_to_dictionary( array ):
	result = {}
	if len( array ) % 2 != 0:
		response = array.pop()
		if type( response ) == list:
			while len( response ) > 0:
				key = response.pop(0)
				value = response.pop(0)
				result[ key ] = value
	if len( array ) > 0:
		for key, value in pairs_to_dictionary([array]).iteritems():
			if value > 0:
예제 #5
0
 async def start(self):
     self.play = True
     while self.play:
         query = select([Room]).where(Room.id == self.room_id)
         room = await DATABASE.fetch_one(query)
         songs_query = select([Song]).where(Song.room_id == self.room_id)
         if room['room_type'] == RoomType.simple or room[
                 'room_type'] == RoomType.random:
             songs_query = songs_query.order_by(Song.order)
         else:
             songs_query = songs_query.order_by(Song.upvotes.desc(),
                                                Song.order)
         songs = await DATABASE.fetch_all(songs_query)
         if len(songs):
             to_play = songs[0] if self.paused == -1 else self.playing
             cache_data = REDIS.get(to_play['url'])
             duration = None
             if cache_data is None:
                 data = YOUTUBE.videos().list(part='contentDetails',
                                              id=to_play['url'])
                 content = data.execute()
                 if content.get('items', []):
                     duration_iso = content['items'][0].get(
                         'contentDetails', {}).get('duration')
                     duration = parse_duration(duration_iso).total_seconds()
                     REDIS.set(to_play['url'], str(int(duration)))
             else:
                 duration = int(cache_data.decode('utf-8'))
             if duration:
                 if self.paused == -1:
                     query = update(Song).where(
                         Song.room_id == to_play['room_id']).values(
                             order=Song.order - 1)
                     await DATABASE.execute(query)
                     query = update(Song).where(
                         Song.id == to_play['id']).values(upvotes=0,
                                                          order=len(songs))
                     await DATABASE.execute(query)
                     for user in USER_VOTES['voted']:
                         if to_play['id'] in USER_VOTES['voted'][user]:
                             USER_VOTES['voted'][user].remove(to_play['id'])
                     await internal_channel_propagate(
                         self.group, {'action': 'refresh_songs'})
                 self.playing = to_play
                 self.time = int(time())
                 await internal_channel_propagate(
                     self.group, {
                         'action': 'play_song',
                         'id': to_play['url'],
                         'start': 0 if self.paused == -1 else self.paused
                     })
                 if self.paused != -1:
                     for user in USER_VOTES['voted']:
                         if to_play['id'] in USER_VOTES['voted']:
                             USER_VOTES['voted'][user].remove(to_play['id'])
                     self.time = int(time()) - self.paused
                     duration -= self.paused
                 self.paused = -1
                 await asyncio.sleep(int(duration))
             else:
                 query = delete(Song).where(Song.id == to_play['id'])
                 await DATABASE.execute(query)
         else:
             self.play = False