Beispiel #1
0
	def inizializeChannel(self):
		self.welcomeChannel = Channel("Welcome_Channel", "welcome to the server", "No", 0, list())
		self.channel1 = Channel("Channel_1", "Description of channel 1", "No", 0, list())
		self.channel2 = Channel("Channel_2", "Description of channel 1", "No", 0, list())
		self.channel3 = Channel("Channel_3", "Description of channel 1", "No", 0, list())
		self.channelManager.addChannel(self.welcomeChannel)
		self.channelManager.addChannel(self.channel1)
		self.channelManager.addChannel(self.channel2)
		self.channelManager.addChannel(self.channel3)
Beispiel #2
0
    async def add_spectator(self, new_spec: 'Player') -> bool:
        spec_chan_name = f"#spec_{self.id}"
        if not Context.channels.get(spec_chan_name):
            # in this case, we need to create channel for our spectator in temp mode
            spec = Channel(server_name=spec_chan_name,
                           description=f"Spectator channel for {self.name}",
                           public_read=True,
                           public_write=True,
                           temp_channel=True)

            Context.channels[spec_chan_name] = spec
            await spec.join_channel(self)

        c: 'Channel' = Context.channels.get(spec_chan_name)
        if not await c.join_channel(new_spec):
            logger.elog(
                f"{self.name} failed to join in {spec_chan_name} spectator channel!"
            )
            return False

        fellow_packet = await PacketBuilder.FellowSpectatorJoined(new_spec.id)
        for spectator in self.spectators:
            spectator.enqueue(fellow_packet)
            new_spec.enqueue(await
                             PacketBuilder.FellowSpectatorJoined(spectator.id))

        self.spectators.append(new_spec)
        new_spec.spectating = self

        self.enqueue(await PacketBuilder.SpectatorJoined(new_spec.id))
        logger.slog(f"{new_spec.name} started to spectating {self.name}!")
        return True
Beispiel #3
0
async def load_default_channels():
    async for channel in Context.mysql.iterall(
            "select name as server_name, description, public_read, public_write from bancho_channels"
    ):
        if channel['server_name'] in Context.channels:
            continue

        Context.channels[channel['server_name']] = Channel(**channel)

        logger.slog(f"[Channels] Create channel {channel['server_name']}")
Beispiel #4
0
async def create_match(packet_data: bytes, token: 'Player'):
    match_object: 'TypedReadMatch' = await PacketResolver.read_match(
        packet_data)

    if not match_object['password']:
        match_object['password'] = None

    # Make match object
    match = Match(id=Context.matches_id,
                  name=match_object['name'],
                  password=match_object['password'],
                  host=Context.players.get_token(uid=match_object['host_id']))
    Context.matches_id += 1  # increment match id
    match.beatmap_name = match_object['beatmap_name']
    match.beatmap_md5 = match_object['beatmap_md5']
    match.beatmap_id = match_object['beatmap_id']

    match.mods = match_object['mods']
    match.seed = match_object['seed']

    match.match_type = match_object['match_type']
    match.match_playmode = match_object['play_mode']
    match.match_scoring_type = match_object['scoring_type']
    match.match_team_type = match_object['team_type']
    match.match_freemod = match_object['match_freemod']

    match.slots = match_object['slots']

    # Create match temp channel
    match_channel = Channel(server_name=f"#multi_{match.id}",
                            description=f"Channel for #multi_{match.id}",
                            public_read=True,
                            public_write=True,
                            temp_channel=True)

    # Register that channel and match
    Context.channels[f"#multi_{match.id}"] = match_channel
    match.channel = match_channel
    Context.matches[match.id] = match

    await match.join_player(token, match_object['password']
                            )  # allow player to join match

    info_packet = await PacketBuilder.NewMatch(match)
    for user in Context.players.get_all_tokens(ignore_tournament_clients=True):
        if not user.is_in_lobby:
            continue
        if user == token:
            continue  # ignore us, because we will receive it first
        user.enqueue(info_packet)

    return True
def app(mode=1):
    restart = False  # By default. If a network error occurs somewhere, this will turn True and restart automatically

    if mode == 1:
        print(
            "getting channels from Notion — All YouTube Channels ... please wait"
        )
        collection = collections.getCollectionFromViewUrl(
            cst.notion_all_channels)
    elif mode == 2:
        print("getting playlists from Notion — My Playlists ... please wait")
        collection = collections.getCollectionFromViewUrl(
            cst.notion_my_playlists)

    try:
        rows = collection.get_rows()
        print("total nb of items in collection : {}".format(len(rows)),
              end=cst.star)

        for row in rows:
            if mode == 1:
                ch = Channel(row.title, str(row.uri), row.episodes_url,
                             row.language)
                if (row.to_index and ch.yt_url != "" and row.uri != "—"):
                    leech.channel_or_playlist(ch, row)

            elif mode == 2:
                plst = Playlist(row.title, row.url, row.episodes_url, None)
                leech.channel_or_playlist(plst, row, my_playlists=True)

    # except requests.exceptions.HTTPError as httpError:
    except Exception as exc:
        print("!!! The following error has occured :", exc, end=cst.line)
        # mth.beep(cst.beeps_number_crash, 0.5) # alert user

        # Raise it and stop or continue and retry ?
        raise exc
        # restart = True

    finally:
        var.driver.quit()  # always empty process in RAM whatever happens

    # Check if it should restart or no (yes if there has been a network / hasardous error, no if everything was successful)
    if restart:
        print(">>> Will now restart software...", end=cst.star)
        app(mode)
        return
    else:  # finish stuff and beep to tell user
        mth.beep(cst.beeps_number_finish, 0.2)
Beispiel #6
0
async def mp_make(args: List[str], player: 'Player', _):
    if len(args) < 2:
        return 'Enter in format: !mp make <name>'

    match_name = ' '.join(args[1:]).strip()
    if player.match:
        return 'First of all, you need to close the previous match'

    match = Match(
        id=Context.matches_id,
        name=match_name,
        password=new_utils.random_hash(),
        is_tourney=True,
        host=player,
        host_tourney=player
    )
    Context.matches_id += 1  # increment match id
    match.beatmap_id = 0

    # Create match temp channel
    match_channel = Channel(
        server_name=f"#multi_{match.id}",
        description=f"Channel for #multi_{match.id}",
        public_read=True,
        public_write=True,
        temp_channel=True
    )

    # Register that channel and match
    Context.channels[f"#multi_{match.id}"] = match_channel
    match.channel = match_channel
    Context.matches[match.id] = match

    # TODO: IRC Ignore join
    if not player.is_tourneymode:
        await match.join_player(player, match.password)  # allow player to join match
    else:
        # join only in channel
        await match_channel.join_channel(player)

    info_packet = await PacketBuilder.NewMatch(match)
    for user in Context.players.get_all_tokens(ignore_tournament_clients=True):
        if not user.is_in_lobby:
            continue
        user.enqueue(info_packet)

    if player.is_tourneymode:
        player.id_tourney = match.id
    return f"Tourney match #{match.id} created!"
Beispiel #7
0
    def handleInput(self, command):
        command = command.split()

        if command[0] == self.cmdClear.name:
            os.system('cls' if os.name == 'nt' else 'clear')

        elif command[0] == self.cmdListClients.name:
            if len(self.clientManager.clientList) < 1:
                self.logHelper.log("error", "No clients connected")
            else:
                self.logHelper.log("error", "Connected clients:")
                for clientObject in self.clientManager.clientList:
                    self.logHelper.log(
                        "info", clientObject.ip + " with name " +
                        clientObject.username + " in " +
                        clientObject.channelObject.name)

        elif command[0] == self.cmdHelp.name:
            self.logHelper.log("info", "Commands:")
            self.logHelper.log(
                "info",
                "----------------------------------------------------------")
            for command in self.commandList:
                self.logHelper.log(
                    "info", command.syntax + " : " + command.description)
            self.logHelper.log(
                "info",
                "----------------------------------------------------------")

        elif command[0] == self.cmdKick.name:
            if len(self.clientManager.clientList) < 1:
                self.logHelper.log("error", "No clients connected")
            else:
                client = None
                try:
                    client = command[1]
                except IndexError:
                    self.logHelper.log("error",
                                       "Syntax: " + self.cmdKick.syntax)
                if client != None:
                    if self.clientManager.ipExists(client):
                        for clientObject in self.clientManager.clientList:
                            if clientObject.ip == client:
                                self.logHelper.log(
                                    "info", clientObject.ip + " : " +
                                    clientObject.username + " got kicked")
                                clientObject.socketObject.sendall(
                                    self.decEncHelper.stringToBytes("402"))
                                clientObject.socketObject.close()
                    elif self.clientManager.usernameExists(client):
                        for clientObject in self.clientManager.clientList:
                            if clientObject.username.lower() == client:
                                self.logHelper.log(
                                    "info", clientObject.ip + " : " +
                                    clientObject.username + " got kicked")
                                clientObject.socketObject.sendall(
                                    self.decEncHelper.stringToBytes("402"))
                                clientObject.socketObject.close()
                    else:
                        self.logHelper.log(
                            "error", "Your given Ip/Name doesn't exist.")

        elif command[0] == self.cmdBan.name:
            if len(self.clientManager.clientList) < 1:
                self.logHelper.log("error", "No clients connected")
            else:
                client = None
                banTime = None
                try:
                    client = command[1]
                    banTime = int(command[2])
                except IndexError:
                    if client or banTime == None:
                        self.logHelper.log("error",
                                           "Syntax: " + self.cmdBan.syntax)
                if client != None:
                    if self.clientManager.ipExists(client):
                        for clientObject in self.clientManager.clientList:
                            if clientObject.ip == client:
                                if banTime != None:
                                    if banTime == 0:
                                        self.fileHelper.addClientToBanList(
                                            clientObject.ip)
                                        self.logHelper.log(
                                            "info", clientObject.ip + " : " +
                                            clientObject.username +
                                            " got permanantly banned")
                                        clientObject.socketObject.sendall(
                                            self.decEncHelper.stringToBytes(
                                                "405" +
                                                "You got permanantly banned by the console"
                                            ))
                                        clientObject.socketObject.close()
                                    else:
                                        currentTimeStamp = datetime.datetime.now(
                                        ).timestamp()
                                        self.fileHelper.addClientToBanList(
                                            clientObject.ip + ":" +
                                            str(currentTimeStamp +
                                                int(banTime) * 60))
                                        self.logHelper.log(
                                            "info", clientObject.ip + " : " +
                                            clientObject.username +
                                            " got banned for " + str(banTime) +
                                            "minutes")
                                        clientObject.socketObject.sendall(
                                            self.decEncHelper.stringToBytes(
                                                "405" + "You got banned for " +
                                                str(banTime) +
                                                " minutes by the console"))
                                        clientObject.socketObject.close()
                                else:
                                    self.fileHelper.addClientToBanList(
                                        clientObject.ip)
                                    self.logHelper.log(
                                        "info", clientObject.ip + " : " +
                                        clientObject.username +
                                        " got permanantly banned")
                                    clientObject.socketObject.sendall(
                                        self.decEncHelper.stringToBytes(
                                            "405" +
                                            "You got permanantly banned by the console"
                                        ))
                                    clientObject.socketObject.close()
                    elif self.clientManager.usernameExists(client):
                        for clientObject in self.clientManager.clientList:
                            if clientObject.username.lower() == client:
                                if banTime != None:
                                    if banTime == 0:
                                        self.fileHelper.addClientToBanList(
                                            clientObject.ip)
                                        self.logHelper.log(
                                            "info", clientObject.ip + " : " +
                                            clientObject.username +
                                            " got permanantly banned")
                                        clientObject.socketObject.sendall(
                                            self.decEncHelper.stringToBytes(
                                                "405" +
                                                "You got permanantly banned by the console"
                                            ))
                                        clientObject.socketObject.close()
                                    else:
                                        currentTimeStamp = datetime.datetime.now(
                                        ).timestamp()
                                        self.fileHelper.addClientToBanList(
                                            clientObject.ip + ":" +
                                            str(currentTimeStamp +
                                                int(banTime) * 60))
                                        self.logHelper.log(
                                            "info", clientObject.ip + " : " +
                                            clientObject.username +
                                            " got banned for " + str(banTime) +
                                            "minutes")
                                        clientObject.socketObject.sendall(
                                            self.decEncHelper.stringToBytes(
                                                "405" + "You got banned for " +
                                                str(banTime) +
                                                " minutes by the console"))
                                        clientObject.socketObject.close()
                                else:
                                    self.fileHelper.addClientToBanList(
                                        clientObject.ip)
                                    self.logHelper.log(
                                        "info", clientObject.ip + " : " +
                                        clientObject.username +
                                        " got permanantly banned")
                                    clientObject.socketObject.sendall(
                                        self.decEncHelper.stringToBytes(
                                            "405" +
                                            "You got permanantly banned by the console"
                                        ))
                                    clientObject.socketObject.close()
                    else:
                        print(
                            "[Server/Error] Your given Ip/Name doesn't exist.")

        elif command[0] == self.cmdListChannel.name:
            self.logHelper.log("info", "Channels:")
            self.logHelper.log(
                "info",
                "----------------------------------------------------------")
            for channel in self.channelManager.channelList:
                self.logHelper.log(
                    "info", "-" + channel.name + " : Description:" +
                    channel.description)
                self.logHelper.log("info", " Clients:")
                if len(channel.clientList) < 1:
                    self.logHelper.log("info", " -channel is empty")
                else:
                    for client in channel.clientList:
                        self.logHelper.log(
                            "info", " -" + client.ip + " : " + client.username)
            self.logHelper.log(
                "info",
                "----------------------------------------------------------")

        elif command[
                0] == self.cmdCreateChannel.name:  #TODO: add things to remove user error when acces level isnst int and description contains spaces
            name = None
            description = None
            password = None
            accessLevel = None
            try:
                name = command[1]
                description = command[2]
                password = command[3]
                accessLevel = int(command[4])
                self.channelManager.addChannel(
                    Channel(name, description, password, accessLevel, list()))
                self.logHelper.log("info", "Channel " + name + " created.")
            except:
                if name or description or password or accessLevel == None:
                    self.logHelper.log(
                        "error", "Syntax: " + self.cmdCreateChannel.syntax)

        elif command[0] == self.cmdRemoveChannel.name:
            name = None
            try:
                name = command[1]
                for channel in self.channelManager.channelList:
                    if channel.name == name:
                        self.channelManager.removeChannel(channel)
                self.logHelper.log("info", "Channel " + name + " was removed.")
            except:
                if name == None:
                    self.logHelper.log(
                        "error", "Syntax: " + self.cmdRemoveChannel.syntax)

        elif command[
                0] == self.cmdChangeRank.name:  #TODO: add things to remove user error for rank and check if rank isnt even a rank
            if len(self.clientManager.clientList) < 1:
                self.logHelper.log("error", "No clients connected")
            else:
                client = None
                rank = None
                try:
                    client = command[1]
                    rank = command[2]
                except IndexError:
                    self.logHelper.log("error",
                                       "Syntax: " + self.cmdChangeRank.syntax)
                if client != None:
                    if rank != None:
                        if self.clientManager.ipExists(client):
                            for clientObject in self.clientManager.clientList:
                                if clientObject.ip == client:
                                    prevRank = clientObject.rank
                                    clientObject.rank = rank
                                    self.mysqlHelper.updateAccountRank(
                                        clientObject)
                                    self.logHelper.log(
                                        "info", "Changed " + clientObject.ip +
                                        ":" + str(clientObject.port) + " " +
                                        clientObject.username +
                                        " 's rank from " + prevRank + " to " +
                                        rank)

                        elif self.clientManager.usernameExists(client):
                            for clientObject in self.clientManager.clientList:
                                if clientObject.username.lower() == client:
                                    prevRank = clientObject.rank
                                    clientObject.rank = rank
                                    self.mysqlHelper.updateAccountRank(
                                        clientObject)
                                    #clientObject.sendall(self.decEncHelper.stringToBytes("904" + rank))TODO:
                                    self.logHelper.log(
                                        "info", "Changed " + clientObject.ip +
                                        ":" + str(clientObject.port) + " " +
                                        clientObject.username +
                                        " 's rank from " + prevRank + " to " +
                                        rank)
                        else:
                            self.logHelper.log(
                                "error", "Your given Ip/Name doesn't exist.")

        elif command[0] == self.cmdMonitorMode.name:
            monitor = True
            config = self.fileHelper.getConfig("Server Config")
            ip = config.ip + ":" + str(config.port)
            if len(ip) != 20:
                ip = " " * (20 - len(ip)) + ip
            while monitor:
                clearCount = 0
                connectedClients = str(len(self.clientManager.clientList))
                connectedAdmins = str(len(self.clientManager.getAdmins()))
                if len(connectedClients) != 3:
                    connectedClients = "0" * (
                        3 - len(connectedClients)) + connectedClients
                if len(connectedAdmins) != 3:
                    connectedAdmins = "0" * (
                        3 - len(connectedAdmins)) + connectedAdmins
                os.system('cls' if os.name == 'nt' else 'clear')
                try:
                    print(
                        "##############Monitoring##############\n#Server Ip/Port: "
                        + ip + "#\n#Uptime:                     " +
                        time.strftime(
                            '%H:%M:%S',
                            time.gmtime(int(time.time() - self.upTime))) +
                        "#\n#Connected Clients:               " +
                        connectedClients +
                        "#\n#Connected Admins:                " +
                        connectedAdmins +
                        "#\n##############Monitoring##############")
                    while clearCount != 5:
                        sys.stdout.write("\x1b[1A")
                        sys.stdout.write("\x1b[2K")
                        clearCount = clearCount + 1
                    time.sleep(0.5)
                except KeyboardInterrupt:
                    monitor = False
                    os.system('cls' if os.name == 'nt' else 'clear')
                    self.logHelper.log("info", "Exited monitor mode.")

        else:
            self.logHelper.log("error", "Unknown command: " + command[0])
            self.logHelper.log("error", "type /help for a list of commands")