Example #1
0
    def default(self, team):
        s = Session()
        our_teams = dict((t.name, t) for t in s.query(Team).all())
        s.close()

        if team in our_teams:
            team = our_teams[team]
            return ("teampage", {'team': team})

        return "Invalid page"
Example #2
0
    def default(self, team):
        s = Session()
        our_teams = dict((t.name, t) for t in s.query(Team).all())
        s.close()

        if team in our_teams:
            team = our_teams[team]
            return ("teampage", {'team': team})

        return "Invalid page"
Example #3
0
def login(email, senha):
    session, mensagem = Session.login(email, senha, LOGIN_URL)
    crawler = None
    if mensagem == 'Acesso liberado. Aguarde...':
        crawler = EvpCrawler(session)
        print(mensagem)
    else:
        raise LoginException(mensagem)
    return crawler
Example #4
0
    def addteam_(self, **kwargs):
        success, serial = self._addteamform.Validate(kwargs)
        if not success:
            raise cpy.HTTPRedirect("/admin/addteam?%s" % Form.Encode(serial))

        session = Session()
        team = Team(kwargs['name'], 
                    kwargs['thumb'],
                    kwargs['fullsize'],
                    encrypt(kwargs['password']),
                    1,
                    kwargs['description'])
        session.save(team)
        session.commit()
        session.close()

        raise cpy.HTTPRedirect("/admin/lsteam/")
Example #5
0
    def editteam_(self, **kwargs):
        success, serial = self._editteamform.Validate(kwargs)
        if not success:
            raise cpy.HTTPRedirect("/admin/editteam?%s" % Form.Encode(serial))

        session = Session()
        #TODO: load the team, see what's different, and change those fields
        team = session.query(Team).filter_by(id=kwargs["team_id"]).first()
        if team.name != kwargs["name"]: 
            team.name = kwargs.name
        if team.description != kwargs["description"]: 
            team.description = kwargs["description"]
        if team.fullsize != kwargs["fullsize"]:
            team.fullsize = kwargs["fullsize"]
        if "password" in kwargs:
            team.password = encrypt(kwargs["password"])
        session.commit()
        session.close()
        raise cpy.HTTPRedirect("/admin/lsteam/")
Example #6
0
	def __init__(self, dbh):
		threading.Thread.__init__(self)
		self.dbh = dbh
		self.cmdqueue = Queue.Queue(25)
		self.session = Session()
		self.songqueue = util.Queue.QueueManager(dbh, self)
Example #7
0
class Player(threading.Thread):

	dbh = None
	shutdown = 0
	cmdqueue = None
	state = "OK"
	sink = "oss"
	session = None
	cursong = None
	songqueue = None
	status = "PLAYING"
	songid = -1
	totaltime = -1
	playedtime = -1
	playedpercentage = -1

	def __init__(self, dbh):
		threading.Thread.__init__(self)
		self.dbh = dbh
		self.cmdqueue = Queue.Queue(25)
		self.session = Session()
		self.songqueue = util.Queue.QueueManager(dbh, self)

	def _pop_cmd(self):
		try:
			return self.cmdqueue.get(0)
		except Exception:
			return None

	def push_cmd(self, cmd):
		try:
			self.cmdqueue.put(cmd)
			log.debug("audio", "Command %s pushed into queue", cmd)
			return True
		except Exception:
			return False

	def queueMove(self, oldindex, newindex):
		self.songqueue.move(oldindex, newindex)

	def queueRemove(self, index):
		log.debug("audio", "Removing index %d", index)
		self.songqueue.remove(index)

	def queueShuffle(self):
		log.debug("audio", "Shuffling Queue")
		self.songqueue.shuffle()

	def queueClear(self):
		self.songqueue.clear()

	def queueSong(self, songid):
		self.songqueue.add(songid)

	def setVolume(self, volume):
		if self.mixer is not None:
			bossao.bossao_setvol(volume)

	def getStatus(self):
		result = {}
		result['queuemd5sum'] = self.songqueue.getmd5sum()
		result['status'] = self.state
		if self.mixer is not None:
			result['volume'] = bossao.bossao_getvol()
		else:
			result['volume'] = 0
		#if self.songqueue.usingqueue == True:
		result['queueindex'] = int(self.songqueue.getCurrentIndex())
		#else:
			#result['queueindex'] = -1
		if self.state != "STOP":
			result['songid'] = int(self.songid)
			result['playedpercentage'] = float(self.playedpercentage)
			result['timeplayed'] = float(self.playedtime)
			result['songlength'] = float(self.totaltime)
		return result

	def updateTimeInfo(self):
		self.playedtime = bossao.bossao_time_current()
		self.totaltime = bossao.bossao_time_total()
		if self.totaltime > 0:
			self.playedpercentage = self.playedtime / self.totaltime * 100
			if self.playedflag == 1 and self.playedpercentage > 75:
				self.dbh.incrementTimesPlayed(self.songid);
				self.playedflag = 0

		if bossao.bossao_finished() == 1:
			self.state = "NEXT"
			self.handleNextCommand()

	def _update_status(self):
		if self.session.hasKey('shutdown'):
			self.shutdown = 1
			self.state = "SHUTDOWN"
		else:
			if self.state != "SHUTDOWN":
				self.updateTimeInfo()

	def initializeao(self):
		self.songdetails = self.songqueue.getCurrentSong()
		#opendev = bossao.bossao_start(self.lib, self.configfile)
		opendev = 0;
		if opendev is not 0:
			log.debug("audio", "Audio device not opened.  Closing...")
			self.session['shutdown'] = 1
			self.shutdown = 1
			self.state = "SHUTDOWN"
		else:
			time.sleep(.1)
			#log.debug("audio", "Using AO device: %s", bossao2.bossao_driver_name(self.lib))
			self.aoinitialized = 1
			self.shutdown = 0
			self.state = "STOPPED"

	def startPlaying(self):
		log.debug("funcs", "Player.startPlaying()")
		self.songdetails = self.songqueue.getCurrentSong()		
		if self.songdetails is not None:
			log.debug("audio", "Calling bossao_play with filename %s", self.songdetails['filename'])
			bossao.bossao_stop ()
			bossao.bossao_play(self.songdetails['filename'])
			log.debug("audio", "bossao_play returned")
			self.playedflag = 1
			self.songid = self.songdetails["songid"]
			self.state = "PLAYING"
			self.dbh.incrementTimesStarted(self.songid);
			self.sleeplength = .3

	def handleStopCommand(self):
		bossao.bossao_stop ()
		#bossao.bossao_shutdown(self.lib)
		self.state = "STOPPED"
		self.sleeplength = 1

	def handlePlayCommand(self):
		if self.state != "STOPPED":
			self.state = "PLAYING"
			bossao.bossao_unpause()
		else:
			self.startPlaying()

	def handlePauseCommand(self):
		if self.state != "STOPPED":
			# bossao_pause toggles the pause state and returns the new state
			# 1 = paused, 0 = playing
			pauseresult = bossao.bossao_pause()
			if pauseresult == 1:
				self.state = "PAUSED"
				self.sleeplength = 1
			else:
				self.state = "PLAYING"
				self.sleeplength = .3

	def handleNextCommand(self):
		self.songqueue.next()
		self.startPlaying()

	def handleJumpCommand(self, index):
		if 0 <= index < len(self.songqueue.getSongIDs()):
			self.songqueue.jump(index)
			self.startPlaying()

	def run(self):
		commandhandlers = {"play": self.handlePlayCommand,
				   "stop": self.handleStopCommand,
				   "pause": self.handlePauseCommand,
				   "next": self.handleNextCommand}
		self.aoinitialized = 0
		session = Session()
		self.configfile = session['cfg']
		self.lib = bossao.bossao_new(self.configfile, None)
		#self.mixer = bossao.bossao_new_mixer()
		self.mixer = 1
		self.playedflag = 0

		if self.dbh.getSongCacheSize() == 0:
			log.debug("audio", "No songs in database.  Waiting for some to get imported.")
			self.state = "EMPTY DB"
			time.sleep(.5)
			while self.dbh.getSongCacheSize() == 0 and session.hasKey('shutdown') == 0:
				time.sleep(.5)

		#bossao.bossao_open_mixer(self.mixer, self.configfile.get("mixerdevice"), self.configfile.get("mixertype"))
		self.initializeao()

		if self.shutdown == 0:
			self.songdetails = None
			if self.configfile.getBoolean("stoponstart") == True:
				log.debug("audio", "Starting stopped")
				self.state = "STOPPED"
				self.sleeplength = 1
			else:
				self.sleeplength = .3
				self.startPlaying()
			log.debug("audio", "Starting player loop")

			while self.shutdown == 0:
				try:
					self._update_status()
					try:
						currentcommand = self._pop_cmd()
						if currentcommand is not None:
							log.debug("audio", "We have a command...%s",  currentcommand)
							# call the handler for the current command
							# handlers will change self.state and self.sleeplength
							commandhandlers[currentcommand]()
					except KeyError:
						# We have to special case playindex because it has an argument
						if currentcommand[:len("playindex")] == "playindex" and len(currentcommand[len("playindex"):]) > 0:
							try:
								tmpsongid = int(currentcommand[len("playindex"):])
								self.handleJumpCommand(tmpsongid)
							except Exception:
								log.exception("Error in playindex")
						else:
							log.error("Got unknown command %s", currentcommand)

				except EndOfQueueException.EndOfQueueException:
					log.debug("audio", "No songs left to play.  Stopping...")
					self.state = "STOPPED"
					self.sleeplength = 1
				time.sleep(self.sleeplength)

			time.sleep(1)
			log.debug("audio", "Calling shutdown")
			#bossao.bossao_shutdown(self.lib)
			#bossao.bossao_stop ()
			bossao.bossao_free ()
		#bossao.bossao_close_mixer(self.mixer)
		log.debug("audio", "Closing lib")
Example #8
0
	def run(self):
		commandhandlers = {"play": self.handlePlayCommand,
				   "stop": self.handleStopCommand,
				   "pause": self.handlePauseCommand,
				   "next": self.handleNextCommand}
		self.aoinitialized = 0
		session = Session()
		self.configfile = session['cfg']
		self.lib = bossao.bossao_new(self.configfile, None)
		#self.mixer = bossao.bossao_new_mixer()
		self.mixer = 1
		self.playedflag = 0

		if self.dbh.getSongCacheSize() == 0:
			log.debug("audio", "No songs in database.  Waiting for some to get imported.")
			self.state = "EMPTY DB"
			time.sleep(.5)
			while self.dbh.getSongCacheSize() == 0 and session.hasKey('shutdown') == 0:
				time.sleep(.5)

		#bossao.bossao_open_mixer(self.mixer, self.configfile.get("mixerdevice"), self.configfile.get("mixertype"))
		self.initializeao()

		if self.shutdown == 0:
			self.songdetails = None
			if self.configfile.getBoolean("stoponstart") == True:
				log.debug("audio", "Starting stopped")
				self.state = "STOPPED"
				self.sleeplength = 1
			else:
				self.sleeplength = .3
				self.startPlaying()
			log.debug("audio", "Starting player loop")

			while self.shutdown == 0:
				try:
					self._update_status()
					try:
						currentcommand = self._pop_cmd()
						if currentcommand is not None:
							log.debug("audio", "We have a command...%s",  currentcommand)
							# call the handler for the current command
							# handlers will change self.state and self.sleeplength
							commandhandlers[currentcommand]()
					except KeyError:
						# We have to special case playindex because it has an argument
						if currentcommand[:len("playindex")] == "playindex" and len(currentcommand[len("playindex"):]) > 0:
							try:
								tmpsongid = int(currentcommand[len("playindex"):])
								self.handleJumpCommand(tmpsongid)
							except Exception:
								log.exception("Error in playindex")
						else:
							log.error("Got unknown command %s", currentcommand)

				except EndOfQueueException.EndOfQueueException:
					log.debug("audio", "No songs left to play.  Stopping...")
					self.state = "STOPPED"
					self.sleeplength = 1
				time.sleep(self.sleeplength)

			time.sleep(1)
			log.debug("audio", "Calling shutdown")
			#bossao.bossao_shutdown(self.lib)
			#bossao.bossao_stop ()
			bossao.bossao_free ()
		#bossao.bossao_close_mixer(self.mixer)
		log.debug("audio", "Closing lib")
Example #9
0
def auth():
    session = Session()
    users = dict(
        (str(t.name), str(t.password)) for t in session.query(Team).all())
    session.close()
    return users
Example #10
0
 def getteam(self, name, default):
     session = Session()
     team = session.query(Team).filter_by(name=name).first() or default
     session.close()
     return team
Example #11
0
 def lsteam(self):
     session = Session()
     teams = session.query(Team).all()
     session.close()
     #TODO: move the admin templates into a subdir?
     return ("lsteam", {"teams": teams})
Example #12
0
def auth():
    session = Session()
    users = dict((str(t.name), str(t.password)) for t in session.query(Team).all())
    session.close()
    return users
Example #13
0
from models.model import Category, Product, Store
from util import Session, get_unique_df_values, read_csv

# create a Session
sess = Session()


class DBFeed:
    """
    A class used to insert data into mysql database
    """
    def __init__(self, file_name):
        """
        Parameters
        ----------
        file_name : str
            The name of the csv file
       
        """
        self.file_name = file_name

    def populate_category(self):
        """ 
        Insert data into category table
        """
        df = read_csv(self.file_name)
        unique_category_list = get_unique_df_values(df, 'main_category')

        for c in unique_category_list:
            cat = Category(category_name=c)
            sess.add(cat)