Пример #1
0
async def fetch_online_pixelzone():
    """Returns the number of users who are currently online pixelzone, integer."""
    socket_url = "{0}://pixelzone.io/socket.io/?EIO=3&transport={1}"
    sid = None
    async with aiohttp.ClientSession() as session:
        attempts = 0
        while attempts < 3:
            try:
                async with session.get(socket_url.format("https", "polling"),
                                       headers=useragent) as r:
                    sid = json.loads(str((await r.read())[4:-4],
                                         "utf-8"))['sid']
                    break
            except aiohttp.client_exceptions.ClientOSError:
                attempts += 1

        if not sid:
            raise HttpCanvasError('pixelzone')

        attempts = 0
        while attempts < 3:
            try:
                await session.post(socket_url.format("https", "polling") +
                                   "&sid=" + sid,
                                   data='11:42["hello"]',
                                   headers=useragent)
                break
            except aiohttp.client_exceptions.ClientOSError:
                attempts += 1
    async with websockets.connect(socket_url.format("wss", "websocket&sid=") +
                                  sid,
                                  extra_headers=useragent) as ws:
        await ws.send("2probe")
        async for msg in ws:
            if msg == '3probe':
                break
        await ws.send("5")
        await ws.send("42hello")
        async for msg in ws:
            if msg[4:11] == 'welcome':
                break
        try:
            async for msg in ws:
                if msg[4:17] == 'playerCounter':
                    d = json.loads(msg[2:])
                    data = d[1]
                    break
        except websockets.ConnectionClosed:
            raise HttpCanvasError('pixelzone')
    return data
Пример #2
0
async def _fetch_chunks_pixelzone(chunks: Iterable[ChunkPz]):
    socket_url = "{0}://pixelzone.io/socket.io/?EIO=3&transport={1}"
    sid = None
    chunks = [x for x in chunks if x.is_in_bounds()]
    if len(chunks) == 0:
        return
    async with aiohttp.ClientSession() as session:
        attempts = 0
        while attempts < 3:
            try:
                async with session.get(socket_url.format("https", "polling"), headers=useragent) as r:
                    sid = json.loads(str((await r.read())[4:-4], "utf-8"))['sid']
                    break
            except aiohttp.client_exceptions.ClientOSError:
                attempts += 1

        if not sid:
            raise HttpCanvasError('pixelzone')

        attempts = 0
        while attempts < 3:
            try:
                await session.post(socket_url.format("https", "polling") + "&sid=" + sid, data='11:42["hello"]',
                                   headers=useragent)
                break
            except aiohttp.client_exceptions.ClientOSError:
                attempts += 1

    async with websockets.connect(socket_url.format("wss", "websocket&sid=") + sid, extra_headers=useragent) as ws:
        try:
            await ws.send("2probe")
            await ws.recv()
            await ws.send("5")
            await ws.send('42["useAPI", "{}"]'.format(config.PZ_API_KEY))
            for ch in chunks:
                data = {}
                await ws.send(ch.url)
                async for msg in ws:
                    d = json.loads(msg[msg.find('['):])
                    if type(d) == int:
                        continue
                    if d[0] == "c":
                        data = d[1]
                        break
                ch = next((x for x in chunks if x.x == data['cx'] and x.y == data['cy']))
                ch.load(data['data'])
        except websockets.ConnectionClosed as e:
            raise HttpCanvasError('pixelzone')
Пример #3
0
async def _fetch_chunks_pixelcanvas(bigchunks: Iterable[BigChunk]):
    """Fetches chunk data from pixelcanvas.io.
    
    Arguments:
    bigchunks - An iterable of a list of BigChunk objects."""
    async with aiohttp.ClientSession() as session:
        for bc in bigchunks:
            await asyncio.sleep(0)
            if not bc.is_in_bounds():
                continue
            data = None
            attempts = 0
            while attempts < 3:
                try:
                    async with session.get(bc.url, headers=useragent) as resp:
                        data = await resp.read()
                        if len(data) == 460800:
                            break
                except aiohttp.ClientPayloadError:
                    pass
                data = None
                attempts += 1
            if not data:
                raise HttpCanvasError('pixelcanvas')
            bc.load(data)
Пример #4
0
async def fetch_online_pixelzone():
    socket_url = "{0}://pixelzone.io/socket.io/?EIO=3&transport={1}"
    sid = None
    async with aiohttp.ClientSession() as session:
        attempts = 0
        while attempts < 3:
            try:
                async with session.get(socket_url.format("http", "polling"), headers=useragent) as r:
                    sid = json.loads(str((await r.read())[4:-4], "utf-8"))['sid']
                    break
            except aiohttp.client_exceptions.ClientOSError:
                attempts += 1

        if not sid:
            raise HttpCanvasError('pixelzone')

        attempts = 0
        while attempts < 3:
            try:
                await session.post(socket_url.format("http", "polling") + "&sid=" + sid, data='11:42["hello"]',
                                   headers=useragent)
                break
            except aiohttp.client_exceptions.ClientOSError:
                attempts += 1
    async with websockets.connect(socket_url.format("ws", "websocket&sid=") + sid, extra_headers=useragent) as ws:
        await ws.send("2probe")
        await ws.recv()
        await ws.send("5")
        await ws.recv()
        await ws.send("42['useAPI', '{}'".format(config.PZ_API_KEY))
        try:
            async for msg in ws:
                d = json.loads(msg[msg.find('['):])
                if type(d) == int:
                    continue
                if d[0] == "g":
                    data = d[1]
                    break
        except websockets.ConnectionClosed as e:
            raise HttpCanvasError('pixelzone')
    return data
Пример #5
0
async def _fetch_chunks_pixelzone(bot, chunks: Iterable[ChunkPz]):
    """Fetches chunk data from pixelzone.io.

    Arguments:
    chunks - An iterable of ChunkPz objects."""
    chunks = [x for x in chunks if x.is_in_bounds()]
    if len(chunks) == 0:
        return

    async def check_cache(chunks):
        async with bot.pz.chunk_lock:
            for chunk in chunks:
                cached = bot.pz.chunks.get(f"{chunk.x}_{chunk.y}", None)
                if cached:
                    chunk._image = cached.to_image()
                    chunk.loaded = True

    async def get_chunks(chunks):
        for chunk in chunks:
            chunk.loaded = False

        await check_cache(chunks)

        if all(chunk.loaded for chunk in chunks):
            return

        chunks = [c for c in chunks if not c.loaded]

        for chunk in chunks:
            await bot.pz.chunk_queue.put([chunk.x, chunk.y])

        while True:
            await check_cache(chunks)

            if all(chunk.loaded for chunk in chunks):
                return
            await asyncio.sleep(0.1)

    try:
        await asyncio.wait_for(get_chunks(chunks), timeout=60)
    except asyncio.TimeoutError:
        raise HttpCanvasError('pixelzone')
Пример #6
0
async def _fetch_chunks_pixelplanet(bigchunks: Iterable[ChunkPP]):
    async with aiohttp.ClientSession() as session:
        for bc in bigchunks:
            await asyncio.sleep(0)
            if not bc.is_in_bounds():
                continue
            data = None
            attempts = 0
            while attempts < 3:
                try:
                    async with session.get(bc.url, headers=useragent) as resp:
                        data = await resp.read()
                        if len(data) == 65536:
                            break
                except aiohttp.ClientPayloadError:
                    pass
                data = None
                attempts += 1
            if not data:
                raise HttpCanvasError('pixelplanet')
            bc.load(data)
Пример #7
0
async def _fetch_chunks_pixelzone(chunks: Iterable[ChunkPz]):
    global pz_rate_limiter
    if pz_rate_limiter is None:
        pz_rate_limiter = RateLimitingSemaphore(2, 0.4,
                                                asyncio.get_event_loop())
    socket_url = "{0}://pixelzone.io/socket.io/?EIO=3&transport={1}"
    sid = None
    chunks = [x for x in chunks if x.is_in_bounds()]
    if len(chunks) == 0:
        return
    async with aiohttp.ClientSession() as session:
        attempts = 0
        while attempts < 3:
            try:
                async with session.get(socket_url.format("https", "polling"),
                                       headers=useragent) as r:
                    sid = json.loads(str((await r.read())[4:-4],
                                         "utf-8"))['sid']
                    break
            except aiohttp.client_exceptions.ClientOSError:
                attempts += 1

        if not sid:
            raise HttpCanvasError('pixelzone')

        attempts = 0
        while attempts < 3:
            try:
                await session.post(socket_url.format("https", "polling") +
                                   "&sid=" + sid,
                                   data='11:42["hello"]',
                                   headers=useragent)
                break
            except aiohttp.client_exceptions.ClientOSError:
                attempts += 1

    async with websockets.connect(socket_url.format("wss", "websocket&sid=") +
                                  sid,
                                  extra_headers=useragent) as ws:
        try:
            await ws.send("2probe")
            async for msg in ws:
                if msg == '3probe':
                    break
            await ws.send("5")
            await ws.send("42hello")
            async for msg in ws:
                if msg[4:11] == 'welcome':
                    break
            await ws.send('42["useAPI", "{}"]'.format(config.PZ_API_KEY))
            async for msg in ws:
                if msg[4:18] == 'useAPICallback':
                    break
            async with pz_rate_limiter:
                for ch in chunks:
                    await ws.send(ch.url)
                    packet = None
                    async for msg in ws:
                        if packet is None:
                            if msg[:2] == '45':
                                packet = {}
                                data = json.loads(msg[msg.find('-') + 1:])[1]
                                packet['cx'] = data['cx']
                                packet['cy'] = data['cy']
                        else:
                            packet['data'] = msg[1:]
                            break
                    ch = next((x for x in chunks
                               if x.x == packet['cx'] and x.y == packet['cy']))
                    ch.load(packet['data'])
        except websockets.ConnectionClosed:
            raise HttpCanvasError('pixelzone')
Пример #8
0
async def fetch_online_pxlsspace(bot):
    """Returns the number of users who are currently online pxls.space, integer."""
    if bot.px.player_count:
        return bot.px.player_count
    else:
        raise HttpCanvasError('pxlsspace')
Пример #9
0
async def fetch_online_pixelzone(bot):
    """Returns the number of users who are currently online pixelzone, integer."""
    if bot.pz.player_count:
        return bot.pz.player_count
    else:
        raise HttpCanvasError('pixelzone')