async def map_info_page(self, *ids): if self.site != 'sm': url = '{base}/maps/get_map_info/multi/{ids}'.format( base=self.base_url(True), ids=','.join(str(i) for i in ids[0]) ) else: url = '{base}/maps/{ids}'.format( base=self.base_url(True), ids=','.join(str(i) for i in ids[0]) ) params = {'key': self.key} if self.key else {} response = await self.session.get(url, params=params) if response.status == 404: raise MXMapNotFound('Map has not been found!') if response.status == 302: raise MXInvalidResponse('Map author has declined info for the map. Status code: {}'.format(response.status)) if response.status < 200 or response.status > 399: raise MXInvalidResponse('Got invalid response status from ManiaExchange: {}'.format(response.status)) maps = [] for info in await response.json(): # Parse some differences between the api game endpoints. mx_id = info['TrackID'] if 'TrackID' in info else info['MapID'] info['MapID'] = mx_id info['MapUID'] = info['TrackUID'] if 'TrackUID' in info else info['MapUID'] maps.append((mx_id, info)) return maps
async def map_offline_record(self, trackid): url = '{base}/replays/get_replays/{id}/1'.format(base=self.base_url(True), id=trackid) params = {'key': self.key} if self.key else {} response = await self.session.get(url, params=params) if response.status == 404: raise MXMapNotFound('Map has not been found!') if response.status == 302: raise MXInvalidResponse('Map author has declined info for the map. Status code: {}'.format(response.status)) if response.status < 200 or response.status > 399: raise MXInvalidResponse('Got invalid response status from ManiaExchange: {}'.format(response.status)) return [info for info in await response.json()]
async def map_offline_records(self, trackid): url = '{base}/replays/get_replays/{id}/10'.format(base=self.base_url(True), id=trackid) response = await self.session.get(url) if response.status == 404: raise MXMapNotFound('Map has not been found!') if response.status == 302: raise MXInvalidResponse('Map author has declined info for the map. Status code: {}'.format(response.status)) if response.status < 200 or response.status > 399: raise MXInvalidResponse('Got invalid response status from ManiaExchange: {}'.format(response.status)) record = [] for info in await response.json(): print(info) record.append((info)) return record
async def download(self, mx_id): url = '{base}/maps/download/{id}'.format( base=self.base_url(), id=mx_id, ) params = {'key': self.key} if self.key else {} response = await self.session.get(url, params=params) if response.status == 404: raise MXMapNotFound('Map has not been found!') if response.status == 302: raise MXInvalidResponse( 'Map author has declined download of the map. Status code: {}'.format(response.status)) if response.status < 200 or response.status > 399: raise MXInvalidResponse('Got invalid response status from ManiaExchange: {}'.format(response.status)) return response
async def search_pack(self, options, **kwargs): if options is None: options = dict() if self.key: options['key'] = self.key options['api'] = 'on' url = '{}/mappacksearch/search'.format(self.base_url()) response = await self.session.get(url, params=options) if response.status == 404: raise MXMapNotFound('Got not found status from ManiaExchange: {}'.format(response.status)) if response.status < 200 or response.status > 399: raise MXInvalidResponse('Got invalid response status from ManiaExchange: {}'.format(response.status)) maps = list() json = await response.json() if not 'results' in json: return list() for info in json['results']: # Parse some differences between the api game endpoints. maps.append(info) return maps
async def search(self, options, **kwargs): if options is None: options = { "api": "on", "mode": 0, "style": 0, "order": -1, "length": -1, "page": 0, "gv": 1, "limit": 150 } if self.key: options['key'] = self.key url = '{}/tracksearch2/search'.format(self.base_url()) response = await self.session.get(url, params=options) if response.status == 404: raise MXMapNotFound('Got not found status from ManiaExchange: {}'.format(response.status)) if response.status < 200 or response.status > 399: raise MXInvalidResponse('Got invalid response status from ManiaExchange: {}'.format(response.status)) maps = [] json = await response.json() for info in json['results']: # Parse some differences between the api game endpoints. mx_id = info['TrackID'] if 'TrackID' in info else info['MapID'] info['MapID'] = mx_id info['MapUID'] = info['TrackUID'] if 'TrackUID' in info else info['MapUID'] maps.append(info) return maps
async def pack_info(self, id, token): url = '{base}/api/mappack/get_info/{id}?token={token}&secret={token}'.format( base=self.base_url(), id=id, token=token ) params = {'key': self.key} if self.key else {} response = await self.session.get(url, params=params) if response.status == 404: raise MXMapNotFound('Map has not been found!') if response.status == 302: raise MXInvalidResponse('Map author has declined info for the map. Status code: {}'.format(response.status)) if response.status < 200 or response.status > 399: raise MXInvalidResponse('Got invalid response status from ManiaExchange: {}'.format(response.status)) return response.json()
async def activate_session(self, session_seed): """ This method will activate the session based on the seed it created earlier. :param session_seed: Seed of the session created earlier. """ api_key = await self.app.setting_mx_karma_key.get_value() hash = hashlib.sha512('{apikey}{seed}'.format( apikey=api_key, seed=session_seed).encode('utf-8')).hexdigest() url = '{url}/activateSession?sessionKey={key}&activationHash={hash}'.format( url=self.api_url, key=self.key, hash=hash) response = await self.session.get(url) if response.status < 200 or response.status > 399: raise MXInvalidResponse( 'Got invalid response status from ManiaExchange: {}'.format( response.status)) result = await response.json() if result['success'] is False: self.activated = False logger.error( 'Error while getting information from ManiaExchange, error {code}: {message}' .format(code=result['data']['code'], message=result['data']['message'])) else: self.activated = result['data']['activated'] if self.activated: logger.info('Successfully started the MX Karma session.') else: logger.warning('Unable to start a MX Karma session.')
async def get_pack_ids(self, pack_id, token): if self.site == 'tmnext': url = '{base}/api/mappack/get_mappack_tracks/{id}?token={token}'.format( base=self.base_url(), id=pack_id, token=token) else: url = '{base}/api/mappack/get_tracks/{id}?token={token}'.format( base=self.base_url(), id=pack_id, token=token) params = {'key': self.key} if self.key else {} response = await self.session.get(url, params=params) if response.status == 404: raise MXMapNotFound('Map pack not found!') if response.status < 200 or response.status > 399: raise MXInvalidResponse( 'Got invalid response status from ManiaExchange: {}'.format( response.status)) maps = list() if response.content_length > 0: for info in await response.json(): # Parse some differences between the api game endpoints. mx_id = info['TrackID'] maps.append((mx_id, info)) return maps else: raise MXMapNotFound("Mx returned with empty response.")
async def start_session(self): """ Create the MX Karma session by authenticating with the API. This method will make sure the server is ready to get and post karma entries to the API. """ if self.session is None: await self.create_session() elif self.key is None: logger.debug('Starting MX Karma session ...') url = '{url}/startSession?serverLogin={login}&applicationIdentifier={app}&testMode=false'.format( url=self.api_url, login=self.app.app.instance.game.server_player_login, app='PyPlanet {version}'.format(version=version)) response = await self.session.get(url) if response.status < 200 or response.status > 399: raise MXInvalidResponse( 'Got invalid response status from ManiaExchange: {}'. format(response.status)) result = await response.json() if result['success'] is False: logger.error( 'Error while starting ManiaExchange session, error {code}: {message}' .format(code=result['data']['code'], message=result['data']['message'])) else: self.key = result['data']['sessionKey'] await self.activate_session(result['data']['sessionSeed'])
async def save_votes(self, map, is_import=False, map_length=0, votes=None): """ Save votes to the MX Karma API. :param map: Map instance :param is_import: State if the votes are imported from local karma. :param map_length: Map length. :param votes: Votes payload. :return: Status or updated value. """ if not self.activated: return if votes is None: return url = '{url}/saveVotes?sessionKey={key}'.format(url=self.api_url, key=self.key) content = { 'gamemode': await self.app.app.instance.mode_manager.get_current_full_script(), 'titleid': self.app.app.instance.game.dedicated_title, 'mapuid': map.uid, 'mapname': map.name, 'mapauthor': map.author_login, 'isimport': is_import, 'maptime': map_length, 'votes': votes } response = await self.session.post(url, json=content) if response.status < 200 or response.status > 399: raise MXInvalidResponse( 'Got invalid response status from ManiaExchange: {}'.format( response.status)) result = await response.json() if result['success'] is False: logger.error( 'Error while saving information to ManiaExchange, error {code}: {message}' .format(code=result['data']['code'], message=result['data']['message'])) return False else: if votes is not None: logger.debug( 'Amount of MX Karma votes saved for this map: {}'.format( len(votes))) return result['data']['updated']
async def download(self, mx_id): url = 'https://{site}.mania-exchange.com/tracks/download/{id}'.format( site=self.site, id=mx_id, ) params = {'key': self.key} if self.key else {} response = await self.session.get(url, params=params) if response.status == 404: raise MXMapNotFound('Map has not been found!') if response.status < 200 or response.status > 399: raise MXInvalidResponse('Got invalid response status from ManiaExchange: {}'.format(response.status)) return response
async def map_info(self, *ids): url = 'https://api.mania-exchange.com/{site}/maps/{ids}'.format( site=self.site, ids=','.join(ids)) params = {'key': self.key} if self.key else {} response = await self.session.get(url, params=params) if response.status == 404: raise MXMapNotFound('Map has not been found!') if response.status == 302: raise MXInvalidResponse( 'Map author has declined info for the map. Status code: {}'. format(response.status)) if response.status < 200 or response.status > 399: raise MXInvalidResponse( 'Got invalid response status from ManiaExchange: {}'.format( response.status)) maps = list() for info in await response.json(): # Parse some differences between the api game endpoints. mx_id = info['TrackID'] if 'TrackID' in info else info['MapID'] info['MapID'] = mx_id info['MapUID'] = info['TrackUID'] if 'TrackUID' in info else info[ 'MapUID'] maps.append((mx_id, info)) return maps
async def get_map_rating(self, map, player_login=None): """ Get rating for the specific map instance. :param map: Map model instance. :param player_login: Player login, optional :return: Dictionary with data for the given map, received from the API. """ if not self.activated: return url = '{url}/getMapRating?sessionKey={key}'.format(url=self.api_url, key=self.key) logins = [vote.player.login for vote in self.app.app.current_votes] content = { 'gamemode': await self.app.app.instance.mode_manager.get_current_full_script(), 'titleid': self.app.app.instance.game.dedicated_title, 'mapuid': map.uid, 'getvotesonly': False, 'playerlogins': logins } response = await self.session.post(url, json=content) if response.status < 200 or response.status > 399: raise MXInvalidResponse( 'Got invalid response status from ManiaExchange: {}'.format( response.status)) result = await response.json() if result['success'] is False: logger.error( 'Error while getting information from ManiaExchange, error {code}: {message}' .format(code=result['data']['code'], message=result['data']['message'])) return None else: data = result['data'] return data