Example #1
0
def main():

    if not Database.initialize():
        Database.terminate()
        return

    global request_processor
    request_processor = RequestProcessor()

    chain_thread = threading.Thread(target=thread_func)
    chain_thread.start()

    params = config("httpserver")
    hostname = params["host"]
    port = int(params["port"])

    logger.info("starting http server...")
    server = ThreadingHTTPServer((hostname, port), RequestHandler)
    logger.info("listening on {}:{}...".format(hostname, port))
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        logger.info("HTTP SERVER STOPPED")
        global running
        running = False
        global chain_scheduler
        chain_scheduler.cancel(event)
    chain_thread.join()
    Database.terminate()
 def process_contacts(contact_group):
     for contact in contact_group:
         try:
             if contact[1] > contact[3]:
                 Database.update_risk_level(contact[2], min(int(contact[3] + contact[1] * contact[5]), 4))
             else:
                 Database.update_risk_level(contact[0], min(int(contact[1] + contact[3] * contact[5]), 4))
         except Exception as ex:
             logger.error("EXCEPTION DATABASE: {} {}".format(type(ex), ex))
             return ErrorResponse("Database error")
    def process_contact(user_id1, user_id2, relevance_factor):
        logger.info("Processing contact between {} and {} with relevance_factor {}".format(user_id1, user_id2,
                                                                                           relevance_factor))

        risk_level1 = Database.get_users_risk_level(user_id1)
        risk_level2 = Database.get_users_risk_level(user_id2)

        try:
            Database.update_risk_level(user_id2, min(int(risk_level2 + risk_level1 * relevance_factor), 4))
        except Exception as ex:
            logger.error("EXCEPTION DATABASE: {} {}".format(type(ex), ex))
            return ErrorResponse("Database error")
Example #4
0
    def _process_update_user_status_request(self, request):
        assert isinstance(request, UpdateUserStatusRequest)
        logger.debug("PROCESSING UPDATE USER STATUS REQUEST...")

        user_id = request.user_id
        new_user_status = request.new_user_status

        try:
            Database.update_risk_level(user_id, new_user_status)
        except Exception as ex:
            logger.error("EXCEPTION DATABASE: {} {}".format(type(ex), ex))
            return ErrorResponse("Database error")
        return SuccessResponse("Status update succeeded")
    def process_chains():
        logger.info("Processing chains")

        try:
            risk_group = Database.get_users_by_risk_level(5)

            for risk_id in risk_group:
                contact_group = Database.get_contacts_after_timestamp(risk_id[0], datetime.now() - timedelta(hours=1))

                ChainIterator.process_contacts(contact_group)
        except Exception as ex:
            logger.error("EXCEPTION DATABASE: {} {}".format(type(ex), ex))
            return ErrorResponse("Database error")
Example #6
0
    def _process_upload_personal_data_request(self, request):
        assert isinstance(request, UploadPersonalDataRequest)
        logger.debug("PROCESSING UPLOAD USER DATA REQUEST...")

        user_id = request.user_id
        firstname = request.firstname
        lastname = request.lastname
        phonenumber = request.phonenumber

        try:
            Database.insert_infected(user_id, firstname, lastname, phonenumber)
        except Exception as ex:
            logger.error("EXCEPTION DATABASE: {} {}".format(type(ex), ex))
            return ErrorResponse("Database error")
        return SuccessResponse("Upload succeeded")
    def iterate_geo_data():
        logger.info("Iterating geo data")

        risk_group = Database.get_users_by_risk_level(5)

        try:
            for risk_id in risk_group:
                geo_data = Database.get_geo_data_after_timestamp(risk_id, datetime.now() - timedelta(hours=1))
                contact_subjects = Database.get_users_below_risk_level(4)

                for subject in contact_subjects:
                    geo_data_subject = Database.get_geo_data_after_timestamp(subject[0],
                                                                             datetime.now() - timedelta(hours=1))
                    GeoProcessor.identify_contacts(risk_id, geo_data, geo_data_subject)
        except Exception as ex:
            logger.error("EXCEPTION DATABASE: {} {}".format(type(ex), ex))
            return ErrorResponse("Database error")
Example #8
0
    def __init__(self,
                 creator: User,
                 data: Database,
                 stock_ticker: str = '',
                 sign: int = 0,
                 margin: float = 0.0,
                 amount_staked: float = 0.0,
                 seconds: int = 0):
        # initializing our own ADTs
        self._creator = creator
        self._key = data.make_bet_key()
        data.bets()[self._key] = self

        # initializing our arguments
        self._stock_ticker = stock_ticker
        self._sign = sign
        self._margin = margin
        self._amount_staked = amount_staked

        # initializing initial and target stock price with some data reader stuff, edit initial price
        self._initial_price = self.get_current_price()
        self._target_price = self._initial_price * (1 +
                                                    self._sign * self._margin)

        # creating necessary data structures
        self._for_map = {creator.get_address(): amount_staked}
        self._against_map = {}
        self._for_count = 1
        self._against_count = 0
        self._for_rep = creator.get_rep()
        self._against_rep = 0.0
        self._for_staked = amount_staked
        self._against_staked = 0.0

        # timing the bet, adjust back for longer time frames after testing
        # current_time = datetime.utcnow()
        # tz = timezone.utc
        # set_time = datetime(year, month, day, 20, 0, 1, 0, tz)
        # timedelta = set_time - current_time
        # self._total_seconds = timedelta.total_seconds()
        self._total_seconds = seconds

        # starting the timer for the voting duration once the bet is initialized
        voting_period = self.voting_period()
        timer = Timer(voting_period, self.timed_payout)
        timer.start()
Example #9
0
    def _process_upload_track_request(self, request):
        assert isinstance(request, UploadTrackRequest)
        logger.debug("PROCESSING UPLOAD TRACK REQUEST...")

        contacts = request.contacts
        positions = request.positions
        user_id = request.user_id
        try:
            for contact in contacts:
                Database.report_contact(contact[0], contact[1], contact[2],
                                        contact[3])

            for position in positions:
                Database.insert_geo_data(user_id, position[0], position[1],
                                         position[2])

        except Exception as ex:
            logger.error("EXCEPTION DATABASE: {} {}".format(type(ex), ex))
            return ErrorResponse("Database error")
        return SuccessResponse("Upload succeeded")
Example #10
0
    def _process_get_user_status_request(self, request):
        assert isinstance(request, GetUserStatusRequest)
        logger.debug("PROCESSING UPDATE USER STATUS REQUEST...")

        user_id = request.user_id
        risk_level = None
        try:
            risk_level = Database.get_users_risk_level(user_id)
        except Exception as ex:
            logger.error("EXCEPTION DATABASE: {} {}".format(type(ex), ex))
            return ErrorResponse("Database error")
        return CustomResponse(success=True, message="", status=risk_level)
Example #11
0
    def __init__(self):
        self._upload_bucket = MagicMock()
        self._collection_bucket = MagicMock()

        mock_database_client = create_autospec(FaunaClient, instance=True)
        mocked_database = Database(
            client_factory=lambda _: mock_database_client,
            secret=Secret('test-secret'))
        self._database = mocked_database

        mock_annotation_database_client = create_autospec(FaunaClient,
                                                          instance=True)
        mocked_annotation_database = AnnotationDatabase(
            client_factory=lambda _: mock_annotation_database_client,
            secret=Secret('test-secret'))
        self._annotation_database = mocked_annotation_database

        self._cognito_client = MagicMock()
Example #12
0
 def _process_register_user_request(self, request):
     assert request.request_type is RequestType.REGISTER_USER
     logger.debug("PROCESSING REGISTER USER REQUEST...")
     try:
         user_id = Database.insert_user()
     except Exception as ex:
         logger.error("EXCEPTION DATABASE: {} {}".format(type(ex), ex))
         return ErrorResponse("Database error")
     # create json web token
     payload = {
         "userId": user_id,
         "time": int(time.time()),
         "app": "corona_tracker"
     }
     params = config("auth")
     secret = params["jwtsecret"]
     encoded = jwt.encode(payload=payload, key=secret,
                          algorithm="HS256").decode("utf-8")
     return CustomResponse(success=True,
                           message="",
                           userId=user_id,
                           jwt=encoded)
Example #13
0
def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        g._database = Database()
    return g._database
Example #14
0
    # executes a timed payout after the voting period ends
    def timed_payout(self):
        sleep(self.observation_period())
        self.payout(parse(self._stock_ticker))

    # timer for main method to return updated account balances in test
    def see_balances(self):
        for user, balance in self._for_map.items():
            print(user, " voted for and has: ", balance)

        for user, balance in self._against_map.items():
            print(user, " voted against and has: ")


if __name__ == '__main__':
    database = Database()
    timmy = User(database, 'timmy')
    timmy.update_rep(100.0)
    timmy.update_bank(100.0)
    bet = Bet(timmy, database, 'FB', -1, 0.0, 50.0, 60)
    print(bet.get_current_price())
'''
if __name__ == '__main__':
    database = Database()
    timmy = User(database, 'timmy')
    timmy.update_rep(100.0)
    timmy.update_bank(100.0)
    bet = Bet(timmy, database, 'FB', -1, 0.0, 50.0, 60)
    loop = True
    timer = Timer(60.0, bet.see_balances)
    timer.start()
Example #15
0
 def __init__(self):
     self.db = Database()
     self.secret_key = uuid.uuid4().hex
Example #16
0
 def database(self):
     return Database(secret=os.environ['DATABASE_SECRET'])
Example #17
0
 def __init__(self, data: Database, address: str = ''):
     # takes in the database, and user address as argument. Keeps track of user's rep and bank
     self._address = address
     self._rep = 0.0
     self._bank = 0.0
     data.users()[address] = self