Esempio n. 1
0
 def search(self, start=None, end=None, diagnosis=None):
     """Validates the parameters, search the database, and
     returns the results or an error message page.
     """
     template = self.lookup.get_template('report/results.mako')
     (u, c) = getUserInfo()
     if start and end and diagnosis:
         conn = Database()
         session = conn.get()
         results = []
         query = session.query(RadiologyRecord).filter(
             RadiologyRecord.test_date >= start,
             RadiologyRecord.test_date <= end)
         for word in diagnosis.split():
             query = query.filter(
                 RadiologyRecord.diagnosis.ilike(
                     "%" + word + "%"))
         for entry in query.all():
             results.append(
                 [entry.patient.last_name, entry.patient.first_name,
                  entry.patient.address, entry.patient.phone,
                  entry.test_date, entry.diagnosis])
         conn.close()
         if (len(results) == 0):
             template = self.lookup.get_template('report/report.mako')
             return template.render(username=u, classtype=c, action="fail")
         return template.render(username=u, classtype=c, results=results)
     else:
         return template.render(username=u, classtype=c, action="noparams")
Esempio n. 2
0
    def index(self):
        """Returns the main page of the module
        which allows a user to generate a report for analysis,
        based on specified criteria.
        """

        # Database connection
        conn = Database()
        session = conn.get()

        # Get a list of all patients
        patients = []
        testTypes = []
        for entry in session.query(User).filter(User.class_type == 'p').all():
            if (entry.person.__dict__ not in patients):
                patients.append(entry.person.__dict__)

        for entry in session.query(RadiologyRecord).distinct().all():
            if (entry.test_type not in testTypes):
                testTypes.append(entry.test_type)

        template = self.lookup.get_template('analysis/analysis.mako')
        (u, c) = getUserInfo()

        conn.close()

        return template.render(
            username=u, classtype=c, patients=patients, testTypes=testTypes)
Esempio n. 3
0
def column_take(chat_id, column):
    db = Database()
    db.query("SELECT " + column + " FROM profile WHERE chat_id = %s;",
             (chat_id, ))
    items = [item for item in db.data()]
    db.close()
    return items[0][0]
Esempio n. 4
0
class OctoPrintSchema:
    """
    Provide methods for OctoPrint profile management
    """
    def __init__(self):
        self.conn = Database().get_conn()
        self.curs = self.conn.cursor()

        self.create_octoprint_table()

    def __del__(self):
        self.conn.close()

    def create_octoprint_table(self):
        """
        Init octoprint table

        :return: void
        """

        query = """
                CREATE TABLE IF NOT EXISTS octoprint (
                    ip CHAR(22) NOT NULL UNIQUE,
                    host VARCHAR(255) NOT NULL,
                    x_api_key CHAR(32) NOT NULL UNIQUE PRIMARY KEY
                );
                """

        self.curs.execute(query)
        self.conn.commit()
Esempio n. 5
0
def start_engine():
	database = Database()
	size = database.getSize()
	while size <= maxentries:
		size = database.getSize()
		print 'Rows in database: ' + str(size)
		url = database.getUnvisited()
		database.update(url)
		if url is None:
			break
		try:
			finder = LinkFinder(url)
			if finder.isOkay():
				linklist = finder.getLinks()
				print 'Links found: ' + str(len(linklist))
				for link in linklist:
					if len(link) > 255:
						linklist.remove(link)
				try:
					database.addNew(linklist)
				except UnicodeEncodeError:
					print 'Link encoding error'
			else:
				database.markBAD(url)
				print 'Marked link as bad, reason: ' + finder.reason()
			finder.close()
		except socket.error:
			print 'timeout error'
			database.markBAD(url)
		except LookupError:
			print 'lookup error'
		if die[0]:
			break
	database.close()
Esempio n. 6
0
 def addRecord(self):
     """Returns a page that allows for the input of a radiology record
     into the system.
     """
     template = self.lookup.get_template('upload/addrecord.mako')
     (u, c) = getUserInfo()
     conn = Database()
     session = conn.get()
     patients = []
     doctors = []
     # Get a list of all patients
     for entry in session.query(User).filter(User.class_type == 'p').all():
         if (entry.person.__dict__ not in patients):
             patients.append(entry.person.__dict__)
     # Get a list of all doctors
     for entry in session.query(User).filter(User.class_type == 'd').all():
         if (entry.person.__dict__ not in doctors):
             doctors.append(entry.person.__dict__)
     if (len(patients) == 0):
         template = self.lookup.get_template('upload/upload.mako')
         return template.render(
             username=u, classtype=c, action="noPatient")
     if (len(doctors) == 0):
         template = self.lookup.get_template('upload/upload.mako')
         return template.render(
             username=u, classtype=c, action="noDoctor")
     p = sorted(patients, key=itemgetter('last_name'))
     d = sorted(doctors, key=itemgetter('last_name'))
     conn.close()
     return template.render(
         username=u, classtype=c, patients=p, doctors=d)
Esempio n. 7
0
 def index(self, username=None, password=None):
     """Returns a login page, and responsible for verifying
     the provided login information and accepting or rejecting
     it accordingly.
     """
     template = self.lookup.get_template('login.mako')
     if username and password:
         username = escape(username, True)
         password = escape(password, True)
         conn = Database()
         session = conn.get()
         try:
             user = session.query(User).filter(
                 User.user_name == username).filter(
                     User.password == password).one()
             cherrypy.session['username'] = user.user_name
             cherrypy.session['classtype'] = user.class_type
             raise cherrypy.HTTPRedirect("/home")
         except NoResultFound:
             conn.close()
             return template.render(loginStatus=1)
         except MultipleResultsFound:
             conn.close()
             return template.render(loginStatus=1)
     else:
         return template.render(loginStatus=0)
Esempio n. 8
0
def color(color):

    db = Database(DB_URL)
    con = db.controller
    res = con.get_color(color)
    db.close()

    return render_template("home.html", cars=res, colors=COLORS)
class TestServerAccount(unittest.TestCase):
    def setUp(self):
        self.db = Database()
        self.db.connect()

    def tearDown(self):
        self.db.close()

    def test_init(self):
        account = Account(self.db)
        self.assertIsInstance(account, Account)

        account2 = Account(self.db, 1)
        self.assertIsInstance(account, Account)

    def test_exists(self):
        account = Account(self.db, 123)
        account.destroy()
        self.assertFalse(account.exists())
        account.create()
        self.assertTrue(account.exists())

    def test_destroy(self):
        account = Account(self.db, 123)
        account.create()
        self.assertTrue(account.exists())
        account.destroy()
        self.assertFalse(account.exists())

    def test_create(self):
        account = Account(self.db)
        self.assertFalse(account.exists())
        accountId = account.create()
        cursor = self.db.connection.cursor()
        cursor.execute("SELECT id FROM bitcoin.accounts WHERE id = %s LIMIT 1",
                       [accountId])
        self.assertIsNotNone(cursor.fetchone())

    def test_update(self):
        account = Account(self.db)
        accountId = account.create()
        self.assertTrue(account.balanceBitcoins == 0.0)
        account.balanceBitcoins = 543.0
        account.update()

        account2 = Account(self.db, accountId)
        self.assertTrue(account2.balanceBitcoins == 543.0)

    def test_create_update_fetch_init(self):
        account = Account(self.db)
        self.assertIsInstance(account.create(), int)
        account.balanceBitcoins = 123.0
        account.update()
        account.fetch()
        self.assertTrue(account.balanceBitcoins == 123.0)
        # create new instance and test it
        self.assertTrue(
            Account(self.db, account.accountId).balanceBitcoins == 123.0)
Esempio n. 10
0
def column_add(chat_id, column, column_value):
    db = Database()
    db.query(
        "UPDATE profile SET " + column +
        " = %(column_value)s WHERE chat_id = %(chat_id)s;", ({
            'column_value': column_value,
            'chat_id': chat_id
        }))
    db.close()
class YouTubeTrendingAnalysisApplication(Form):
    def __init__(self):
        self.__db = Database()

        self.__codes_config = CountryCodesConfigForm(self, self.__db)
        self.__database_management = DatabaseManagementForm(
            self, self.__db, self.__codes_config.country_codes)
        self.__analyze_data = AnalyzeDataForm(
            self, self.__db, self.__codes_config.country_codes)

    def launch(self):
        loop = True

        while loop:

            self.__print__menu()
            choice = input(">>> Enter your choice [0-3]: ")

            if choice == '1':
                self.__codes_config.launch()

            elif choice == '2':
                self.__database_management.country_codes = self.__codes_config.country_codes
                self.__database_management.launch()

            elif choice == '3':
                self.__analyze_data.country_codes = self.__codes_config.country_codes
                self.__analyze_data.launch()

            elif choice == '0':
                self.__db.close()
                loop = False

            else:
                print(">>> Wrong option selection!")

            if not loop:
                os.system('cls')
                print('>>> Bye, bye...')

    @staticmethod
    def __print__menu():
        os.system('cls')
        print('\n', 30 * '-', 'MAIN MENU', 30 * '-', '\n')
        print('1. Configure country codes')
        print('2. Database management ')
        print('3. Analyze data')
        print('0. Exit')
        print('\n', 71 * '-', '\n')
Esempio n. 12
0
class DeviceSchema:
    def __init__(self):
        self.conn = Database().get_conn()
        self.curs = self.conn.cursor()

        self.create_device_table()
        self.create_power_strip_table()

    def __del__(self):
        self.conn.close()

    def create_device_table(self):
        query = """
                CREATE TABLE IF NOT EXISTS device (
                    id CHAR(40) NOT NULL UNIQUE PRIMARY KEY,
                    ip CHAR(22) NOT NULL,
                    type VARCHAR(255) NOT NULL,
                    path VARCHAR(10)
                )
                """

        self.curs.execute(query)
        self.conn.commit()

    def create_power_strip_table(self):
        """
        Init power_strip table

        :return: void
        """

        query = """
                CREATE TABLE IF NOT EXISTS power_strip (
                    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
                    device_id CHAR(40),
                    name VARCHAR(255) NOT NULL,
                    switch_number INT NOT NULL,
                    switch_name VARCHAR(255) NOT NULL,
                    FOREIGN KEY (device_id)
                        REFERENCES device(id)
                        ON DELETE CASCADE 
                );
                """

        self.curs.execute(query)
        self.conn.commit()
Esempio n. 13
0
 def getAll():
     try:
         conn = Database().conexao()
         cur = conn.cursor()
         sql = "SELECT contato.id, contato.nome, contato.celular,\
             contato.telefone, contato.email, endereco.cep, endereco.logradouro,\
             endereco.bairro, endereco.numero, endereco.complemento, endereco.localidade,\
             endereco.uf \
             FROM contato INNER JOIN endereco ON\
             contato.idEndereco = endereco.id"
         cur.execute(sql)
         rows = cur.fetchall()
         return rows
     except Exception as e:
         print("Erro ao consultar todos - "+e.__str__())
     finally:
         cur.close()
         conn.close()
Esempio n. 14
0
    def insere(self, endereco):
        
        try:
            conn = Database().conexao()
            cur = conn.cursor()
            sql = 'INSERT INTO endereco (idContato, cep, logradouro, bairro, numero, complemento, uf)\
                values(?,?,?,?,?,?,?)'
            cur.execute(sql, (endereco.idContato, endereco.cep,
                endereco.logradouro, endereco.bairro, endereco.numero, endereco.complemento, endereco.uf ))
            
            aux = cur.lastrowid
            conn.commit()
        except Exception as e:
            print("Erro ao inserir CONTATO - "+e.__str__())
        finally:
            cur.close()
            conn.close()

        return aux
Esempio n. 15
0
    def insere(self, contato):
        try:
            conn = Database().conexao()
            cur = conn.cursor()
            sql = "INSERT INTO contato (nome, celular, telefone, email, idEndereco)\
                values(?, ?, ?, ?, ?)"
            cur.execute(sql, (contato.getNome(), contato.getCelular(),
                contato.getTelefone(), contato.getEmail(), 0))

            aux = cur.lastrowid
            conn.commit()
        except Exception as e:
            print("Erro ao inserir CONTATO - "+e.__str__())
        finally:
            
            cur.close()
            conn.close()

        return aux
Esempio n. 16
0
    def generate(self, start=None, end=None, patient=None, testType=None):
        """Returns a generated report for the analysis module"""
        template = self.lookup.get_template('analysis/generate.mako')

        # Database connection
        conn = Database()
        session = conn.get()

        #Basic query
        #query = session.query(RadiologyRecord).join(PacsImage, RadiologyRecord.record_id == PacsImage.record_id).join(Person, RadiologyRecord.patient_id == Person.person_id)
        query = session.query(RadiologyRecord, RadiologyRecord.test_type, func.count(PacsImage.record_id).label('total')).join(PacsImage).group_by(RadiologyRecord.test_type).order_by(RadiologyRecord.patient_id)
        
        # All edge cases are inclusive
        if (start != "") and (end != ""):
            query = query.filter(
                RadiologyRecord.test_date <= end).filter(
                    RadiologyRecord.test_date >= start)

        testTypes = []

        if testType != "_ALLTESTTYPES_":
            query = query.filter(RadiologyRecord.test_type == testType)
            testTypes.append(testType)
        else:
            for entry in session.query(RadiologyRecord).distinct().all():
                if (entry.test_type not in testTypes):
                    testTypes.append(entry.test_type)

        if patient != "_ALLPATIENTS_":
            query = query.filter(RadiologyRecord.patient_id == patient)

        results = query.all()
        #results = []
        #for entry in query.all():
        #    if entry.__dict__ not in results:
        #        results.append(entry.__dict__)

        (u, c) = getUserInfo()

        conn.close()
		
        return template.render(
            username=u, classtype=c, results=results, testTypes=testTypes)
Esempio n. 17
0
def delete():

    if request.method == "POST":

        if request.form.get("target-delete"):
            target_delete = request.form.get("target-delete")

            db = Database(DB_URL)
            con = db.controller
            car, msg = con.pop(target_delete)

            if car is not None:
                try:
                    db.conn.commit()
                except sqlite3.Error:
                    db.conn.rollback()

            db.close()

    return redirect(url_for("all"))
Esempio n. 18
0
    def selectRecord(self):
        """Returns a page with a list of records from which one can
        be chosed to have images uploaded to it.

        Only records belonging to the current user are displayed.
        """
        template = self.lookup.get_template('upload/selectrecord.mako')
        (u, c) = getUserInfo()
        conn = Database()
        session = conn.get()
        user = session.query(User).filter(User.user_name == u).one()
        records = session.query(
            Person).filter(Person.person_id == user.person_id).one(
            ).radiologyrecords_radiologist
        record = []
        for r in records:
            record.append(
                [r.record_id, r.prescribing_date, r.test_date, r.diagnosis,
                 r.description])
        conn.close()
        return template.render(
            username=u, classtype=c, records=record)
Esempio n. 19
0
def order():

    if request.method == "POST":

        if request.form.get("target-move") and request.form.get("to-move"):

            target_move = request.form.get("target-move")
            to_move = request.form.get("to-move")

            db = Database(DB_URL)
            con = db.controller

            car, msg = con.pop(target_move)
            car, msg = con.insert(car, to_move)

            if car is not None:
                try:
                    db.conn.commit()
                except sqlite3.Error:
                    db.conn.rollback()

            db.close()

    return redirect(url_for("all"))
Esempio n. 20
0
    def user(self, firstname=None, lastname=None,
             address=None, email=None, phone=None,
             password=None, password2=None):
        """Returns a page to edit a user's own information.

        If new information was passed on to it, it verifies it and
        edits accordingly.
        """
        template = self.lookup.get_template('user.mako')
        (u, c) = getUserInfo()
        conn = Database()
        session = conn.get()
        user = session.query(User).filter(User.user_name == u).one()
        fail = False
        # make sure password was entered correctly
        if password or password2:
            if password == password2:
                user.password = password
            else:
                fail = True
        if firstname and not fail:
            user.person.first_name = firstname
        if lastname and not fail:
            user.person.last_name = lastname
        if address and not fail:
            user.person.address = address
        if email and not fail:
            user.person.email = email
        if phone and not fail:
            user.person.phone = phone
        if firstname or lastname or address or email or phone or password:
            if not fail:
                conn.commit()
                user = session.query(User).filter(User.user_name == u).one()
        oldinfo = []
        oldinfo.append(user.person.first_name)
        oldinfo.append(user.person.last_name)
        oldinfo.append(user.person.address)
        oldinfo.append(user.person.email)
        oldinfo.append(user.person.phone)
        if firstname or lastname or address or email or phone or password:
            if fail:
                conn.close()
                return template.render(
                    username=u, classtype=c, oldinfo=oldinfo, action="nomatch")
            else:
                conn.close()
                return template.render(
                    username=u, classtype=c, oldinfo=oldinfo, action="success")
        else:
            conn.close()
            return template.render(username=u, classtype=c, oldinfo=oldinfo)
Esempio n. 21
0
class MusiciansDBApp(npyscreen.NPSAppManaged):
    def __init__(self, *args, **keywords):
        super().__init__(*args, **keywords)
        self.database = Database('127.0.0.1', 'postgres')

    def onStart(self):
        self.database.connect('postgres', '1')
        self.fill_database()

        self.addForm("MAIN", MainList.MainListDisplay, title='Main menu')
        self.addForm("MUSICIANSLIST",
                     MusiciansList.MusiciansListDisplay,
                     title='Musicians')
        self.addForm("MUSICIANEDIT", MusicianEdit.MusicianEdit)
        self.addForm("RELEASESLIST", ReleasesList.ReleasesListDisplay)
        self.addForm("RELEASEEDIT", ReleaseEdit.ReleaseEdit)
        self.addForm("LISTENERSLIST", ListenersList.ListenersListDisplay)
        self.addForm("LISTENEREDIT", ListenerEdit.ListenerEdit)
        self.addForm("SUBSCRIBE_TO_RELEASE",
                     SubscribeToRelease.SubscribeToRelease)
        self.addForm("SEARCH_STATUS", SearchStatus.SearchStatus)
        self.addForm("SEARCH_VIDEO", SearchVideo.SearchVideo)
        self.addForm("FULLTEXT_SEARCH", FulltextSearch.FulltextSearch)

    def onCleanExit(self):
        self.database.close()

    def fill_database(self):
        self.database.create_musicians_table()
        self.database.create_releases_table()
        self.database.create_listeners_table()
        self.database.create_listeners_releases_table()

        patokaband = Musician(name='Patoka',
                              status=Status.BAND.value,
                              members=["Skiper", "Kovalski", "Rico"])
        sportband = Musician(name='Lets sport',
                             status=Status.BAND.value,
                             members=["Skiper", "Kovalski", "Private"])
        sportsband = Musician(
            name='sports',
            status=Status.ORCHESTRA.value,
            members=["Skiper", "Kovalski", "Rico", "Private"])
        sportsportsport = Musician(
            name='sport sport sport',
            status=Status.BAND.value,
            members=["sportsman1", "sportsman2", "sportsman3"])
        release1 = Release(name='Release1',
                           date=datetime.datetime(year=1999, month=1, day=7),
                           style="Pop",
                           is_video=True,
                           musician_id=3)
        release2 = Release(name='Release2',
                           date=datetime.datetime(year=2018, month=1, day=7),
                           style="Garage rock",
                           is_video=False,
                           musician_id=1)
        release3 = Release(name='Release3',
                           date=datetime.datetime(year=2018, month=1, day=7),
                           style="Rock",
                           is_video=False,
                           musician_id=3)
        listener1 = Listener(name='Anna Siryk',
                             services=["soundcloud", "bandcamp"])
        listener2 = Listener(name='Simple Listener',
                             services=["soundcloud", "vk"])
        listener3 = Listener(name='Listener3', services=["soundcloud"])

        self.database.create_new_musician(patokaband)
        self.database.create_new_musician(sportband)
        self.database.create_new_musician(sportsband)
        self.database.create_new_musician(sportsportsport)
        # self.database.generate_random_musicians(100)

        self.database.create_new_release(release1)
        self.database.create_new_release(release2)
        self.database.create_new_release(release3)

        self.database.create_new_listener(listener1)
        self.database.create_new_listener(listener2)
        self.database.create_new_listener(listener3)

        self.database.add_listener_release(1, 1)
        self.database.add_listener_release(2, 1)
        self.database.add_listener_release(1, 2)
 def test_close(self):
     db = Database()
     db.connect()
     db.close()
Esempio n. 23
0
class Launcher:
    def __init__(self, environment=SlurmEnvironment):
        print("[LAUNCH] Initialize")
        self.id_cache = {}

        self.db = Database(args.u, args.p)
        self.data_collector = DataCollector(self.db,
                                            dry_run=settings.DATA_DRY_RUN)
        # self.data_collector.add_listener(ArduinoPowerListener())
        self.data_collector.add_listener(PDUListener(sample_rate=2))

        feature_model = FeatureModel(path_handler.model_path)
        self.sampled_configs = sample_configs(feature_model)

        self.benchmark = Benchmark(
            bench_config_path=path_handler.bench_config_path)

        self.environment = environment(self.data_collector)
        self.evaluator = Plotter(self.db)

        self.model_trainer = ModelTrainer(self.db)

    def launch(self):
        self.sync_with_db()

        if self.data_collector.listeners is not None:
            for listener in self.data_collector.listeners:
                listener.start()

        print("[LAUNCH] Execute benchmark")
        self.environment.execute(self.benchmark)

        if self.data_collector.listeners is not None:
            for listener in self.data_collector.listeners:
                listener.stop()

    def evaluate(self, fixed_data=None):
        if fixed_data is None:
            ids = self.id_cache["run_sched"]
        else:
            ids = fixed_data

        self.evaluator.plot_energy_performance_tradeoff(
            ids, self.model_trainer.plotted_figures, metric="power")
        self.model_trainer.plotted_figures += 1
        self.evaluator.plot_energy_performance_tradeoff(
            ids, self.model_trainer.plotted_figures, metric="energy")
        self.model_trainer.plotted_figures += 1
        self.evaluator.plot_performance_by_host(
            ids, self.model_trainer.plotted_figures)
        self.model_trainer.plotted_figures += 1
        self.evaluator.plot_config_variance(ids)
        self.model_trainer.plotted_figures += 1

        self.evaluator.plot_power_curve(4451)
        self.model_trainer.plotted_figures += 1
        self.evaluator.plot_power_curve(3807)
        self.model_trainer.plotted_figures += 1

    def train_models(self, fixed_data=None):
        if fixed_data is None:
            ids = self.id_cache["run_sched"]
        else:
            ids = fixed_data

        self.model_trainer.train(ids, settings.BENCHMARK["name"])

    def sync_with_db(self):
        print("[LAUNCH] Sync with DB")
        hw_conf_id = 1  # TODO: Read from file or something
        self.id_cache["hw_conf"] = hw_conf_id

        self.id_cache["sw_system"] = self.db.request_id(
            "system_sw", "name", self.benchmark.command_name,
            [self.benchmark.command_name])

        bench_cmd = self.benchmark.command_name + " [OPTIONS] " + " ".join(
            self.benchmark.arguments)
        self.id_cache["benchmark"] = self.db.request_id(
            "benchmark", "command", bench_cmd,
            [settings.BENCHMARK["name"], bench_cmd])
        self.benchmark.id = self.id_cache["benchmark"]

        for config in self.sampled_configs:
            feature_hash = config.compute_hash()
            bin_features = config.get_binary_features()
            num_features = config.get_numeric_features()

            config.id = self.db.request_id("conf_sw", "feature_hash",
                                           feature_hash, [
                                               feature_hash,
                                               json.dumps(bin_features),
                                               json.dumps(num_features)
                                           ])

            run_id = self.db.request_id(
                "run_spec",
                ["hw_conf", "sw_system", "sw_version", "sw_conf", "benchmark"],
                [
                    self.id_cache["hw_conf"], self.id_cache["sw_system"], 0,
                    config.id, self.benchmark.id
                ], [
                    self.id_cache["hw_conf"], self.id_cache["sw_system"], 0,
                    config.id, self.benchmark.id
                ])

            self.benchmark.add_run(RunSpecification(run_id, config,
                                                    hw_conf_id))

        sched_id = self.db.get_free_index("run_schedule")
        self.id_cache["run_sched"] = [
            x for x in range(
                sched_id, sched_id +
                settings.RUN_REPETITIONS * len(self.benchmark.runs))
        ]

    def shutdown(self):
        print("[LAUNCH] Shutdown...")
        self.db.close()
Esempio n. 24
0
class Bot(Client):
    def __init__(self):

        Client.__init__(self)
        self.utils = Utils()
        self.timeout = Timeout()

        self.send = self.utils.send
        self.modules = self.utils.get_modules_info()
        self.config = self.utils.get_config_info()
        self.start_time = self.utils.time_now()
        self.say = self.send_message

        return

    def start_bot(self):

        try:
            try:
                self.database = Database()
                self.database.connect()
            except Exception as e:
                self._quit("Database connection error!")
                return

            # TODO MAKE BEETER
            self.loop.run_until_complete(self.start(self.config.bot.token))

        except KeyboardInterrupt:
            self._cleanup()

        finally:
            sys.stdout.write("Bot has been closed\n")
            return

    async def on_ready(self):

        self.send(1, "Logged in as: {}".format(self.user.name))
        self.send(1, "Client ID: {}".format(self.user.id))
        self.send(1, "Listening to the chat!")

        return

    def _quit(self, msg=""):
        sys.exit(msg + "\n")

    def _cleanup(self):

        try:
            self.loop.run_until_complete(self.logout())
            self.database.close()
            self.database.dispose()
        except:
            pass
        finally:
            pending = asyncio.Task.all_tasks()
            gathered = asyncio.gather(*pending)

        try:
            gathered.cancel()
            self.loop.run_until_complete(gathered)
            gathered.exception()
        except:
            pass
        finally:
            self.loop.close()

    def restart_bot(self):

        try:
            self._cleanup()
        except:
            self._quit("error restarting the bot")
        finally:
            self.start_bot()

    async def on_member_join(self, member):

        server_exists = self.database.server.exists(member.server.id)

        if not server_exists:
            self.database.server.add(member.server.id)

        server_info = self.database.server.get(member.server.id)

        if server_info.welcome_channel != None:
            channel = self.get_channel(server_info.welcome_channel)
            letter = server_info.welcome_message

            if letter != "":
                await self.send_message(channel,
                                        letter.format(member.name,
                                                      member.server.name)
                                        )  #{0=username} {1=servername}

        if server_info.welcome_private:
            letter = server_info.welcome_private_message

            if letter != "":
                await self.send_message(member, letter.format(member.name)
                                        )  #{0=username}

        return

    async def on_member_remove(self, member):

        server_info = self.database.server.get_from_server_aut_add(
            member.sesrver)
        name = self.utils.author_nickanme(member)

        if server_info.goodbye_channel != None:
            channel = self.get_channel(server_info.goodbye_channel)
            letter = server_info.goodbye_message

            if letter != "":
                await self.send_message(
                    channel,
                    letter.format(member.name, member.nick, name,
                                  member.server.name)
                )  #{0=username} {1=usernick} {2=nick then name}{3=servername}

        return

    async def on_member_update(self, before, after):

        if before.nick != after.nick:
            self.send(1, "Adding nick for {}".format(before.name))
            self.database.nickname.add(before.id, before.nick, after.nick)

        if (before.game != after.game) or (before.status != after.status):

            try:
                game_before = before.game.name
            except:
                game_before = ""

            try:
                game_after = after.game.name
            except:
                game_after = ""

            try:
                game_type = after.game.type
            except:
                game_type = 0

            self.send(1, "Updating game for {}".format(before.name))
            self.database.status.add(after.id, game_before, game_after,
                                     game_type, str(before.status),
                                     str(after.status))

        return

    async def on_message_delete(self, message):

        self.database.message.delete(message)

        return

    async def on_message_edit(self, before, after):

        return

    async def get_module(self, module_name):

        for module in self.modules:
            if module_name == module.call or module_name in module.aliases:
                return module

    async def filter_module(self, message, server_stats):

        if not message.content.startswith(server_stats.command_start):
            return

        content = message.content.replace(server_stats.command_start, "", 1)
        try:
            command, args = content.split(" ", 1)
        except:
            command = content
            args = None
        finally:
            class_name_, arguments = "", []

        # Check if cd, if not -> add
        if await self.timeout.user_cmd_check_add(message.author.id, command):
            return

        module = await self.get_module(command)

        if module is None:
            class_name_ = "GetCommand"
            arguments = command

        else:
            if module.owner:
                if message.author.id != message.server.owner.id:
                    return

            class_name_ = module.class_name

            if module.args.delimeter is None:
                if args != None:
                    arguments.append(args)

                if not (len(arguments) in module.args.length):
                    return

            elif module.args.delimeter is not None:
                if args:
                    arguments.extend(
                        args.split(module.args.delimeter, module.args.split))

                if len(arguments) not in module.args.length:
                    return

        class_ = getattr(modules, class_name_)()
        await class_.main(self, self.database, message, arguments)

        await asleep(self.database.cache.botinfo.module_timeout)

        await self.timeout.user_cmd_remove(message.author.id, command)

    async def on_message(self, message):
        """Doesn't really like private messages yet, actually not at all"""
        name = self.utils.author_nickanme(message.author)

        self.send(1, "{} > {}".format(name, message.content))

        self.database.message.add(message)

        if message.channel.is_private:
            #TODO ADD HELP MODULE HERE
            return

        user_stats = self.database.user.get_from_msg_aut_add(message)
        server_stats = self.database.server.get_from_server_aut_add(
            message.server)
        bot_stats = self.database.bot.get()

        if message.content.startswith(server_stats.command_start):
            points_amount = randint(bot_stats.cmd_point_min,
                                    bot_stats.cmd_point_max)
            xp_amount = randint(bot_stats.cmd_xp_min, bot_stats.cmd_xp_max)
        else:
            points_amount = randint(bot_stats.msg_point_min,
                                    bot_stats.msg_point_max)
            xp_amount = randint(bot_stats.msg_xp_min, bot_stats.msg_xp_max)

        messages_active = await self.timeout.check_user_msg(message.author.id)

        if not messages_active:

            self.database.user.points_alter(message.author.id, points_amount)
            self.database.user.xp_alter(message.author.id, xp_amount)
            await self.timeout.user_msg(message.author.id)

        levels = self.utils.level_check(message.author.id, user_stats.xp,
                                        user_stats.level,
                                        bot_stats.level_base_xp,
                                        bot_stats.level_scaling_xp,
                                        bot_stats.level_scaling_max)
        if levels.set_level:
            self.database.user.level_alter(message.author.id, 1)

            if server_stats.post_level:
                letter = server_stats.post_level_msg

                if server_stats.post_level_same_channel_as_msg:
                    await self.send_message(
                        message.channel, letter.format(name, levels.new_level))

                else:
                    channel = self.get_channel(server_info.post_info_channel)
                    await self.send_message(
                        channel, letter.format(name, levels.new_level))

        if message.author.id == self.user.id:
            return

        await self.filter_module(message, server_stats)

        return
Esempio n. 25
0
def chat_id_found(chat_id):
    db = Database()
    db.query("SELECT chat_id FROM profile WHERE chat_id = %s;", (chat_id, ))
    items = [item for item in db.data()]
    db.close()
    return True if len(items) > 0 else False
Esempio n. 26
0
def chat_id_del(chat_id):
    db = Database()
    db.query("DELETE FROM profile WHERE chat_id = %s;", (chat_id, ))
    db.close()
Esempio n. 27
0
def chat_id_add(chat_id):
    db = Database()
    db.query("INSERT INTO profile (chat_id) VALUES (%s);", (chat_id, ))
    db.close()
Esempio n. 28
0
class UserSchema:
    """
    Provide methods for user data management
    """
    def __init__(self):
        self.conn = Database().get_conn()
        self.curs = self.conn.cursor()

        self.create_user_table()
        self.create_otp_table()

    def __del__(self):
        """
        Body of destructor

        :return: void
        """

        self.conn.close()

    def create_user_table(self):
        """
        Init user table

        :return: void
        """

        query = """
                CREATE TABLE IF NOT EXISTS user (
                    name VARCHAR(50) NOT NULL, 
                    surname VARCHAR(50) NOT NULL,
                    username VARCHAR(50) NOT NULL UNIQUE,
                    email VARCHAR(100) NOT NULL UNIQUE,
                    api_key CHAR(64) NOT NULL UNIQUE PRIMARY KEY,
                    admin TINYINT NOT NULL DEFAULT 0, 
                    created_on DATE DEFAULT (CURRENT_DATE),
                    otp_requests INT DEFAULT 0,
                    last_otp_timestamp TIMESTAMP NULL 
                );
                """

        self.curs.execute(query)
        self.conn.commit()

    def create_otp_table(self):
        """
        Init otp table

        :return: void
        """

        query = """
                CREATE TABLE IF NOT EXISTS otp (
                    api_key CHAR(64) NOT NULL UNIQUE PRIMARY KEY, 
                    otp_code INT(6) NOT NULL,
                    otp_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
                    FOREIGN KEY (api_key)
                        REFERENCES user(api_key)
                        ON DELETE CASCADE 
                );
                """

        self.curs.execute(query)
        self.conn.commit()
Esempio n. 29
0
 def search(self, start=None, end=None, keywords=None, sort=None):
     """Validates the parameters, search the database, and
     returns the results or an error message page.
     """
     template = self.lookup.get_template('search/search_results.mako')
     (u, c) = getUserInfo()
     if not ((start and end and sort) or (keywords and sort)):
         template = self.lookup.get_template('search/search.mako')
         return template.render(username=u, classtype=c, action="noparams")
     conn = Database()
     session = conn.get()
     user = session.query(User).filter(User.user_name == u).one()
     query = session.query(RadiologyRecord)
     # Check if a date has been passed
     if (start and end):
         query = query.filter(RadiologyRecord.test_date >= start,
                              RadiologyRecord.test_date <= end)
     # Check user's security level
     if (c == 'd'):
         '''
         Checks that both the record's doctor id is the same as the
         current user's id and that the user's id is in the family_doctor
         table for the record's patient id
         '''
         query = query.join(
             FamilyDoctor, FamilyDoctor.doctor_id == user.person_id).filter(
                 RadiologyRecord.doctor_id == user.person_id).filter(
                     FamilyDoctor.patient_id == RadiologyRecord.patient_id)
     elif (c == 'r'):
         query = query.filter(
             RadiologyRecord.radiologist_id == user.person_id)
     elif (c == 'p'):
         query = query.filter(
             RadiologyRecord.patient_id == user.person_id)
     # Checks sort type
     if (sort == 'newest'):
         query = query.order_by(desc(RadiologyRecord.test_date))
     elif (sort == 'oldest'):
         query = query.order_by(RadiologyRecord.test_date)
     else:
         query = query
     if (keywords):
         '''
         Split keywords into separate words and search for each word
         as a keyword instead of the whole keyword as one string
         '''
         query = query.join(
             Person, RadiologyRecord.patient_id == Person.person_id)
         for word in keywords.split():
             query = query.filter(or_(
                 Person.last_name.ilike("%"+word+"%"),
                 Person.first_name.ilike("%"+word+"%"),
                 RadiologyRecord.diagnosis.ilike("%"+word+"%"),
                 RadiologyRecord.description.ilike("%"+word+"%")))
     results = []
     for entry in query.all():
             # Build a dict to the structure that the template expects
             current = {}
             current['id'] = entry.record_id
             current['patient_name'] = entry.patient.last_name + \
                 ", " + entry.patient.first_name
             current['doctor_name'] = entry.doctor.last_name + \
                 ", " + entry.doctor.first_name
             current['radiologist_name'] = entry.radiologist.last_name + \
                 ", " + entry.radiologist.first_name
             current['test_type'] = entry.test_type
             current['prescribing_date'] = entry.prescribing_date
             current['test_date'] = entry.test_date
             current['diagnosis'] = entry.diagnosis
             current['description'] = entry.description
             current['images'] = []
             if (len(entry.pacsimage) > 0):
                 for image in entry.pacsimage:
                     current['images'].append(
                         [image.image_id,
                             base64.b64encode(image.thumbnail),
                             base64.b64encode(image.regular_size),
                             base64.b64encode(image.full_size)])
             results.append(current)
     if (len(results) > 0):
         conn.close()
         return template.render(username=u, classtype=c, results=results)
     else:
         conn.close()
         template = self.lookup.get_template('search/search.mako')
         return template.render(username=u, classtype=c, action="fail")