def get(self):
        Utils.reset(self)  # reset/clean standard variables

        start_time = time.time()  # start count
        self.respn = '{"info":"no notification!"}'  # set default response of the action

        list = apns.get()  # get list of notifications to be sent
        parameter = '[]'  # set default blank list of notification
        if (list):  # if any notification
            parameter = json.dumps(list)
            # then parse all of it to parameters as a list (array) of notification

        # send to proxy url, which will connect with apple push notification service via socket
        result = urlfetch.fetch(
            url=config.apns['proxyurl'],
            payload='{"data":' + parameter + ', "time":' + str(start_time) +
            ',"passwd":"' + config.testing['passwd'] + '"}',
            method=urlfetch.POST,
            headers={'Content-Type': 'text/json; charset=utf-8'},
            validate_certificate=False)

        if result.status_code == 200:  # if success request
            self.respn = result.content  # return response message as result

        apns.clean()  # after all done, clean local list of notification

        logging.info(self.respn)  # also do log, so we can read in consle log

        # calculate time taken and return result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
Beispiel #2
0
class UtilsTest(unittest.TestCase):
    def setup_method(self, method):
        self.utils = Utils()
        self.header = self.utils.format_header("TOKEN-XXXXXX1")

    def test_contract_format_header(self):
        keys = self.header.keys()

        # validate number of keys in dict
        self.assertEqual(len(keys), 1, 'Testing Length of keys')

        # validate the content of key

        fake_keys = {'X-Riot-Token': 'TOKEN-XXXXXX1'}.keys()
        self.assertEqual(keys, fake_keys, 'Testing contract validation')

    def test_remove_slash_in_end_of_string(self):
        slash_in_the_end = self.utils.remove_slash_in_end_of_string(
            'https://lendico.com.br/')
        without_slash_in_the_end = self.utils.remove_slash_in_end_of_string(
            'https://lendico.com.br/')

        # validate if method remove slash in the end of string
        self.assertEqual(slash_in_the_end, 'https://lendico.com.br',
                         'Testing removing slash in the end of string')

        # validate if method dont remove the last char
        self.assertEqual(
            without_slash_in_the_end, 'https://lendico.com.br',
            'Testing dont remove last char when string dont have slash in the end of string'
        )
Beispiel #3
0
    def get(self):
        Utils.reset(self)                                                        # reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        lang = Utils.required(self, 'lang')
        version = self.request.get('version')

        if version is None or version == '':
            version = config.dictionary['version']

        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()                                                # start count

        # if error, skip this
        if self.error == '':
            data = Data.gettransui(self, float(version))
            if data is not None:
                try:
                    self.respn = json.dumps(data.as_obj[lang])
                except KeyError:
                    self.error = 'UI Text for give language was not found!'

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
Beispiel #4
0
    async def job_queue(self):
        while True:
            try:
                await sleep(Utils.seconds_until_cycle())
                t = datetime.now().astimezone(utc)
                timeframes = Utils.get_accepted_timeframes(t)

                isPremium = self.tickerId in [
                    "EURUSD", "GBPUSD", "AUDJPY", "AUDUSD", "EURJPY", "GBPJPY",
                    "NZDJPY", "NZDUSD", "CADUSD", "JPYUSD", "ZARUSD"
                ]
                if len(client.guilds) == 1:
                    refreshRate = "8H"
                elif isPremium and len(client.guilds) < 15:
                    refreshRate = "1H"
                else:
                    refreshRate = "5m"

                if refreshRate in timeframes and not self.updatingNickname:
                    client.loop.create_task(self.update_nicknames())
                if "1H" in timeframes:
                    client.loop.create_task(self.update_properties())

            except CancelledError:
                return
            except Exception:
                print(format_exc())
                if environ["PRODUCTION_MODE"]: self.logging.report_exception()
    def __init__(self):

        self.debug = False
        self.root_dir = os.path.dirname(os.path.abspath(__file__))
        self.mutations_dir = os.path.join(self.root_dir, 'mutations')
        self.hangs_dir = os.path.join(self.root_dir, 'hangs')
        self.cfg = self._initialize_config()
        self.ml = self._initialize_logging()
        self.mo = None

        # Shared memory
        self.shm = None
        self.shm_size = 0
        self.bitmap_size = 65536
        self.fd = 0
        # PIN command line
        self.cmd_l = []

        # Setup helpers
        self.ae = Aesthetics(self)
        self.utils = Utils(self)
        self.fileops = FileOperations(self)
        self.crash_analysis = CrashAnalysis(self)
        self.rpc_client = BrundleFuzzRpcClient(self)

        self._initialize_shared_memory()
        self._initialize_pin_cmd()
    def get(self):
        Utils.reset(self)  # reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        version = config.data_version['building']
        if self.request.get('version'):
            version = self.request.get('version')
        lang = config.server["defaultLanguage"]
        if self.request.get('lang'):
            lang = self.request.get('lang')

        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()  # start count

        # logical variables
        buildings = None

        # if error, skip this
        if self.error == '':
            buildings = Data.getbuildings(self, lang, float(version))

        if self.error == '' and buildings is not None:
            self.respn = buildings.data

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
 def get_request_handler(self):
     """
     Creates the HTTP controller instance from path string
     :return:
     """
     argpath = self.get_argpath()
     args = argpath.split('/')
     # TODO: Do a proper way of request path handling
     # Now we have context_root in place
     if len(args) == 0 or argpath == '/':
         #self.err_msg = SimpleHTTPStatusOK()
         handler = None
     else:
         try:
             handler_name = Utils.strip_char('/', args[1])
             self.__log.info("Handler Name is {}".format(handler_name))
             handler_module = self._get_module_path(handler_name)
             self.__log.info("Creating HTTP Controller class for {}".format(handler_module))
             handler = Utils.create_instance(handler_module, self.config)
         except Exception as e:
             self.err_msg =  SimpleHTTPErrorControllerNotExists()
             self.__log.error("Error while creating HTTP Controller instance")
             self.__log.error(self.err_msg)
             self.__log.error(str(e))
             handler = None
             #raise
     return handler
 def get_request_handler(self):
     """
     Creates the HTTP controller instance from path string
     :return:
     """
     argpath = self.get_argpath()
     args = argpath.split('/')
     # TODO: Do a proper way of request path handling
     # Now we have context_root in place
     if len(args) == 0 or argpath == '/':
         #self.err_msg = SimpleHTTPStatusOK()
         handler = None
     else:
         try:
             handler_name = Utils.strip_char('/', args[1])
             self.__log.info("Handler Name is {}".format(handler_name))
             handler_module = self._get_module_path(handler_name)
             self.__log.info("Creating HTTP Controller class for {}".format(
                 handler_module))
             handler = Utils.create_instance(handler_module, self.config)
         except Exception as e:
             self.err_msg = SimpleHTTPErrorControllerNotExists()
             self.__log.error(
                 "Error while creating HTTP Controller instance")
             self.__log.error(self.err_msg)
             self.__log.error(str(e))
             handler = None
             #raise
     return handler
    def get(self):
        Utils.reset(self)  # reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        version = self.request.get('version')
        if version is None or version == '':
            version = config.dictionary['version']

        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()  # start count

        # if error, skip this
        if self.error == '':
            data = Data.gettransui(self, float(version))
            if data is not None:
                self.respn = '['
                for lang in data.as_obj:
                    self.respn += '{"code":"' + lang + '", "lang":"' + data.as_obj[
                        lang]['language.name'] + '"},'
                self.respn = self.respn.rstrip(',') + ']'

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
Beispiel #10
0
def champion_mastery():
    endpoint_without_slash_in_the_end = Utils.remove_slash_in_end_of_string(confs.champion_mastery_endpoint)
    endpoint = endpoint_without_slash_in_the_end + '/' + confs.champion_mastery_summoner_id
    headers = Utils.format_header(confs.access_key)

    champion_mastery_json = RiotExtractor()\
        .get_data_from_api(endpoint=endpoint, headers=headers, api_name='champion mastery')

    return champion_mastery_json
    def get(self):
        Utils.reset(self)  # reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')
        chid = self.request.get('chid')

        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()  # start count

        # logic variables
        player = None

        # if error, skip this
        if self.error == '':
            player = Player.getplayer(self, uuid)

        if self.error == '' and player is not None and guid != '':
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        result = None
        if self.error == '' and player is not None:
            if chid:
                if Challenge.DeleteById(self, chid):
                    result = '"result":"deleted successfully"'
                else:
                    result = '"result":"Challenge Id=' + chid + ' could not be found, nothing was deleted"}'
            else:
                if Challenge.DeleteByUserId(self, player.uuid):
                    result = '"result":"deleted successfully"'
                elif Challenge.DeleteByUserId(self, player.fbid):
                    result = '"result":"deleted successfully"'
                else:
                    result = '"result":"nothing was deleted"'

        if self.error == '' and player is not None:
            self.respn = '{'
            Challenge.ComposeChallenges(self, player)
            self.respn += ',' + result
            self.respn = self.respn.rstrip(',') + '}'

            # update timestamp for player
            player.state_obj['updated'] = start_time
            Player.setplayer(self, player)

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
    def get(self):
        Utils.reset(self)
        uuid = Utils.required(self, 'uuid')
        version = config.data_version['building']
        if self.request.get('version'):
            version = self.request.get('version')
        lang = config.server["defaultLanguage"]
        if self.request.get('lang'):
            lang = self.request.get('lang')
        track = 'track.1'
        if self.request.get('track'):
            lang = self.request.get('track')
        score = 0
        if self.request.get('score'):
            lang = self.request.get('score')

        uuid = self.request.get('uuid')

        start_time = time.time()
        # find the right track in buildings and add the score total to it for collection

        player = Player.getplayer(self, uuid)

        # get all buildings types
        buildings = Data.getbuildings(self, lang, version)

        # get player buildings
        mybuildings = Building.getmybuildings(self, uuid)

        #find the building with the track id and give it cash
        if buildings is not None and mybuildings is not None:
            self.respn += '"building":['
            for mybuilding in mybuildings:
                _upd = False
                # for example:  "itid": "track.1",
                if mybuilding.itid == track:
                    mybuilding.amount += score
                    Building.setmybuilding(self, mybuilding)
                self.respn = Building.compose_mybuilding(
                    self.respn, mybuilding)
            self.respn = self.respn.rstrip(',') + '],'

        if self.error == '':
            self.respn = '{"state":' + player.state + ', "building":['
            self.respn = Building.compose_mybuilding(self.respn, mybuilding)
            self.respn = self.respn.rstrip(',') + ']'
            self.respn += '}'

        # calculate time taken and return the result
        time_taken = time.time() - start_time

        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
Beispiel #13
0
    def get(self):
        Utils.reset(self)
        # calculate score by linking replay times Race Winnings Data

        event1 = '{"start_bonus": [0.1, 0.2, 0.4], "shift_bonus": [0.2, 0.5, 0.8], "drift_bonus": [0.3, 0.1, 0.9]}'
        event2 = '{"start_bonus": [0.1, 0.2, 0.4], "shift_bonus": [0.2, 0.5, 0.8], "drift_bonus": [0.3, 0.1, 0.9]}'
        laptime1 = 1
        laptime2 = 2
        self.respn = json.dumps(Score.calculate(self, event1, event2, laptime1, laptime2))
        # calculate time taken and return the result
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, 1))
Beispiel #14
0
	def job_queue(self):
		while True:
			try:
				time.sleep(Utils.seconds_until_cycle())
				t = datetime.datetime.now().astimezone(pytz.utc)
				timeframes = Utils.get_accepted_timeframes(t)

				if "1h" in timeframes:
					TickerParserServer.refresh_parser_index()

			except Exception:
				print(traceback.format_exc())
				if os.environ["PRODUCTION_MODE"]: self.logging.report_exception()
Beispiel #15
0
def main():
    # checking if output path exists
    Utils.create_path_if_not_exists(confs.dest)

    # executing master leagues json writer
    master = master_leagues()
    champion = champion_mastery()

    # writer both in file system
    Writer().write_json(data=master, file_name="master_leagues", output_path=confs.dest)
    Writer().write_json(data=champion, file_name="champion_mastery", output_path=confs.dest)

    # plotting and save championPointchart
    RiotChampionPointsXChampionID(champion).save_chart_as_image(path=confs.dest)
    def get(self):
        Utils.reset(self)  # reset/clean standard variables
        name = self.request.get('name')
        if name == '':
            name = 'Guest?'

        name2 = self.request.get('name2')
        if name2 == '':
            name2 = 'Guest??'

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')
        track = Utils.required(self, 'track')
        toid = Utils.required(self, 'toid')
        image = self.request.get('image')
        image2 = self.request.get('image2')

        friend = False
        if self.request.get('friend'):
            friend = bool(self.request.get('friend'))

        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()  # start count

        Utils.LogRequest(self)

        # logic variables
        player = None

        # if error, skip this
        if self.error == '':
            player = Player.getplayer(self, uuid)

        if self.error == '' and player is not None and guid != '':
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        if self.error == '' and player is not None:
            logging.warn('creating new challenge with' + player.uuid)
            challenge = Challenge.Create(self, track, player.uuid, toid, name,
                                         name2, image, image2, friend)
            if challenge is not None:
                self.respn = '{'
                Challenge.ComposeActualChallenge(self, challenge)
                self.respn = self.respn.rstrip(',') + '}'
            # update timestamp for player
            player.state_obj['updated'] = start_time
            Player.setplayer(self, player)

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
Beispiel #17
0
	def run(self):
		while self.isServiceAvailable:
			try:
				sleep(Utils.seconds_until_cycle())
				t = datetime.now().astimezone(utc)
				timeframes = Utils.get_accepted_timeframes(t)

				if "1m" in timeframes:
					self.update_accounts()
					self.process_price_alerts()

			except (KeyboardInterrupt, SystemExit): return
			except Exception:
				print(format_exc())
				if environ["PRODUCTION_MODE"]: self.logging.report_exception()
    def get(self):
        Utils.reset(self)  # reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')
        version = config.data_version['building']
        if self.request.get('version'):
            version = self.request.get('version')
        lang = config.server["defaultLanguage"]
        if self.request.get('lang'):
            lang = self.request.get('lang')
        checklist = self.request.get('checklist')

        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()  # start count

        # logic variables
        player = None

        # if error, skip this
        if self.error == '':
            player = Player.getplayer(self, uuid)

        if self.error == '' and player is not None and guid != '':
            logging.info(guid + '==' + player.state_obj['guid'])
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        if self.error == '' and player is not None:
            if checklist:
                player.state_obj['advice_checklist'] = checklist

            # update timestamp for player
            player.state_obj['updated'] = start_time
            Player.setplayer(self, player)

            self.respn = '{"advice_checklist_saved":"true"}'

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))
Beispiel #19
0
    def job_queue(self):
        while True:
            try:
                time.sleep(Utils.seconds_until_cycle())
                t = datetime.datetime.now().astimezone(pytz.utc)
                timeframes = Utils.get_accepted_timeframes(t)

                if "4H" in timeframes:
                    self.update_popular_tickers()

            except (KeyboardInterrupt, SystemExit):
                return
            except Exception:
                print(traceback.format_exc())
                if os.environ["PRODUCTION_MODE"]:
                    self.logging.report_exception()
Beispiel #20
0
 def get(self):
     self.respn = 'Images,ComposeActualChallenge, caradata escaped, Added cardata, name and photo to challenges' \
                  'Challengedelete now retuns new challenge list' \
                  '"removed replay -> score code. changed":"Cast [created] to string, delayed cron for 1st",' \
                  '"version":"3"}'
     self.response.headers['Content-Type'] = 'text/html'
     self.response.write(Utils.RESTreturn(self, 1))
 def do_ssl_certs_exist(self):
     """
     Checks if ssl related files exist in the system
     :return:
     """
     ssl_files = [self.ssl_cafile, self.ssl_certfile, self.ssl_keyfile]
     return Utils.do_files_exist(ssl_files, self.__log)
Beispiel #22
0
    async def job_queue(self):
        while True:
            try:
                await sleep(Utils.seconds_until_cycle())
                t = datetime.now().astimezone(utc)
                timeframes = Utils.get_accepted_timeframes(t)

                if "1m" in timeframes:
                    await self.update_system_status(t)
                if "15m" in timeframes:
                    client.loop.create_task(self.update_alpha_guild_roles())
            except CancelledError:
                return
            except Exception:
                print(format_exc())
                if environ["PRODUCTION_MODE"]: self.logging.report_exception()
Beispiel #23
0
    def execute(self):
        if not self._city:
            try:
                self._city = Utils.get_weather_city(self._user_id)[0]
            except:
                raise exceptions.CityNotLinkedError

        r = requests.get("http://api.openweathermap.org/data/2.5/weather",
                         params={
                             "q": self._city,
                             "APPID": "81d59d3e4bcd5bd5b69f6f95250213ee"
                         })
        if r.status_code != 200:
            raise exceptions.ApiRequestError

        js = r.json()
        if not js or js["cod"] == "404":
            raise exceptions.CityNotFoundError

        temperature = round(float(js['main']['temp']) - 273)
        wind = js['wind']['speed']
        descr = self.WEATHER_STATE.get(js['weather'][0]['main'],
                                       js['weather'][0]['main'])
        country = js['sys']['country']
        humidity = js['main']['humidity']
        text = f"{self._city.capitalize()}, {country}\n{descr}\nТемпература: {temperature}°C\nВлажность: {humidity}%\nСкорость ветра: {wind} м/с"
        return self.Message(text)
Beispiel #24
0
	def update_guild_properties(self, settings, changes, timestamp):
		"""Updates Discord guild properties

		Parameters
		----------
		settings : [google.cloud.firestore_v1.document.DocumentSnapshot]
			complete document snapshot
		changes : [google.cloud.firestore_v1.watch.DocumentChange]
			database changes in the sent snapshot
		timestamp : int
			timestamp indicating time of change in the database
		"""

		try:
			for change in changes:
				guildId = change.document.id
				properties = change.document.to_dict()

				if "addons" not in properties:
					database.document("discord/properties/guilds/{}".format(guildId)).set(Utils.create_guild_settings(properties))
					continue
				if properties["addons"]["satellites"].get("count") is not None and not properties["addons"]["satellites"]["enabled"]:
					properties["addons"]["satellites"].pop("count", None)
					database.document("discord/properties/guilds/{}".format(guildId)).set(properties)
					continue

				if change.type.name in ["ADDED", "MODIFIED"]:
					self.guildProperties[guildId] = properties
				else:
					self.guildProperties.pop(guildId)
			self.serviceStatus[2] = True

		except Exception:
			print(traceback.format_exc())
			if os.environ["PRODUCTION_MODE"]: self.logging.report_exception(user=guildId)
Beispiel #25
0
 def execute(self):
     if not self._user_id:
         self._user_id = self._from_id
     logging.info("Getting user role.")
     message = "Роль: "
     if Utils.has_role(self._user_id, Roles.ADMIN):
         role = "админ"
     elif Utils.has_role(self._user_id, Roles.DONATOR):
         expires, role = Utils.get_donator_expire_date(self._user_id)
         if role is None:
             role = "донатер"
         role += f"\nУ вас осталось {expires} команд"
     else:
         role = "юзер"
     message += role
     return self.Message(message)
Beispiel #26
0
    def _get_command_object(self):
        command_object = None
        if issubclass(self.cmd, staticCommands.StaticCommand):
            logging.debug("Static command.")
            command_object = self.cmd(key=self._key)

        elif issubclass(self.cmd, commands.ILevelCommand):
            logging.debug("Level command.")
            command_object = self.cmd(
                user_id=self.event.from_id,
                chat_id=self.event.peer_id,
                target_id=Utils.find_user_id(self._value),
                amount=Utils.get_experience_amount(self._value))

        elif issubclass(self.cmd, commands.ICommandManager):
            logging.debug("Commands managing.")
            if not Utils.has_role(self.event.from_id,
                                  Roles.DONATOR | Roles.ADMIN):
                raise exceptions.AccesDeniesError
            command_object = self.cmd(message=self.event.text,
                                      attachments=self.event.attachments,
                                      author_id=self.event.from_id)

        elif issubclass(self.cmd, commands.IAdminCommand):
            logging.debug("Admin managing.")
            if not Utils.is_creator(self.event.from_id):
                raise exceptions.AccesDeniesError
            user_id = Utils.find_user_id(self.event.text)
            command_object = self.cmd(user_id, self.event.from_id)

        elif issubclass(self.cmd, commands.IDonatorManager):
            logging.debug("Donator managing.")
            if not Utils.is_creator(self.event.from_id):
                raise exceptions.AccesDeniesError
            command_object = self.cmd(self._value, self.event.from_id)

        elif issubclass(self.cmd, commands.IOsuCommand):
            logging.debug("osu! command")
            # Need to get server and username from db
            # server, username, user_id dict
            params = Utils.get_osu_params(self._value, self.event.from_id)
            logging.debug(self.event)
            fwd_message = Utils.get_reply_message_from_event(self.event)
            if fwd_message is not None:
                params["beatmap_id"] = Utils.find_beatmap_id(
                    fwd_message["text"])
            command_object = self.cmd(**params)

        else:
            logging.debug("Other command.")
            command_object = self.cmd(self._value, self.event.from_id)
        return command_object
Beispiel #27
0
	def request_ccxt_quote(self, request):
		ticker = request.get_ticker()
		exchange = request.get_exchange()

		try:
			if exchange is None: return None, None
			exchange = Exchange(exchange.id)

			tf, limitTimestamp, candleOffset = Utils.get_highest_supported_timeframe(exchange.properties, datetime.datetime.now().astimezone(pytz.utc))
			try:
				rawData = exchange.properties.fetch_ohlcv(ticker.symbol, timeframe=tf.lower(), since=limitTimestamp, limit=300)
				if len(rawData) == 0 or rawData[-1][4] is None or rawData[0][1] is None: return None, None
			except:
				print(traceback.format_exc())
				return None, None

			price = [rawData[-1][4], rawData[0][1]] if len(rawData) < candleOffset else [rawData[-1][4], rawData[-candleOffset][1]]
			if ticker.isReversed: price = [1 / price[0], 1 / price[1]]
			volume = None if price[0] is None else sum([candle[5] for candle in rawData if int(candle[0] / 1000) >= int(exchange.properties.milliseconds() / 1000) - 86400]) / (price[0] if exchange.id in ["bitmex", "binancefutures"] else 1)
			priceChange = 0 if tf == "1m" or price[1] == 0 else (price[0] / price[1]) * 100 - 100

			payload = {
				"quotePrice": "{:,.8f}".format(price[0]) if ticker.isReversed else Utils.format_price(exchange.properties, ticker.symbol, price[0]),
				"quoteVolume": volume,
				"quoteConvertedPrice": "≈ ${:,.6f}".format(price[0] * self.lastBitcoinQuote["quotePrice"][0]) if ticker.quote == "BTC" else None,
				"quoteConvertedVolume": "≈ ${:,.4f}".format(volume * self.lastBitcoinQuote["quotePrice"][0]) if ticker.quote == "BTC" else None,
				"title": ticker.name,
				"baseTicker": "USD" if ticker.base in QuoteProcessor.stableCoinTickers else ticker.base,
				"quoteTicker": "USD" if ticker.quote in QuoteProcessor.stableCoinTickers else ticker.quote,
				"change": priceChange,
				"thumbnailUrl": TickerParser.get_coingecko_image(ticker.base),
				"messageColor": "amber" if priceChange == 0 else ("green" if priceChange > 0 else "red"),
				"sourceText": "on {}".format(exchange.name),
				"platform": "CCXT",
				"raw": {
					"quotePrice": [price[0]] if tf == "1m" else price[:1],
					"quoteVolume": volume,
					"ticker": ticker,
					"exchange": exchange,
					"timestamp": time.time()
				}
			}
			return payload, None
		except Exception:
			print(traceback.format_exc())
			if os.environ["PRODUCTION_MODE"]: self.logging.report_exception()
			return None, None
Beispiel #28
0
def master_leagues():
    endpoint = confs.master_leagues_endpoint
    headers = Utils.format_header(confs.access_key)

    master_leagues_json = RiotExtractor()\
        .get_data_from_api(endpoint=endpoint, headers=headers, api_name='master leagues')

    return master_leagues_json
Beispiel #29
0
	def job_queue(self):
		while True:
			try:
				sleep(Utils.seconds_until_cycle())
				t = datetime.now().astimezone(utc)
				timeframes = Utils.get_accepted_timeframes(t)

				if "1H" in timeframes:
					self.refresh_ccxt_index()
					self.refresh_coingecko_index()
					self.refresh_serum_index()
					self.refresh_coingecko_exchange_rates()
				if "1D" in timeframes:
					self.refresh_iexc_index()

			except Exception:
				print(format_exc())
				if environ["PRODUCTION_MODE"]: self.logging.report_exception()
Beispiel #30
0
 def execute(self):
     self._user_id = Utils.find_user_id(self._args[0])
     self._role = self._parse_role_name()
     logging.info(f"Editing role: {self._user_id} -> {self._role}")
     glob.c.execute("UPDATE donators SET role = ? WHERE id = ?",
                    (self._role, self._user_id))
     glob.db.commit()
     return self.Message(
         f"Роль {self._user_id} была успешно изменена на {self._role}")
    def get(self):
        Utils.reset(self)														# reset/clean standard variables

        # validate and assign parameters
        passwd = Utils.required(self, 'passwd')
        version = config.data_version['building']
        if self.request.get('version'):
            version = self.request.get('version')
        lang = config.server["defaultLanguage"]
        if self.request.get('lang'):
            lang = self.request.get('lang')
        uuid = Utils.required(self, 'uuid')
        guid = self.request.get('guid')

        # check password
        if self.error == '' and passwd != config.testing['passwd']:
            self.error = 'passwd is incorrect.'

        start_time = time.time()												# start count

        # logical variables
        player = None
        mycars = None

        # if error, skip this
        if self.error == '':
            player = Player.getplayer(self, uuid)

        if self.error == '' and player is not None and guid != '':
            if guid != player.state_obj['guid']:
                player = None
                self.error = config.error_message['dup_login']

        if self.error == '' and player is not None:
            mycars = Car.list(self, uuid)
            self.respn = '['
            for _car in mycars:
                self.respn += Car.compose_mycar('', _car) + ','
            self.respn = self.respn.rstrip(',') + ']'

        # calculate time taken and return the result
        time_taken = time.time() - start_time
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(Utils.RESTreturn(self, time_taken))