print "Loading mod: chat_filter v2016-10-05 (http://forum.worldoftanks.eu/index.php?/topic/479948-)"

OWN_FAIL = "Keep up with your own rules"

def MYPPRINT(obj, name = None):
    import inspect, pprint
    if name:
        print name
    if isinstance(obj, dict) or isinstance(obj, list):
        pprint.pprint(obj)
    elif hasattr(obj, '__call__'):
        pprint.pprint(inspect.getargspec(obj))
    else:
        pprint.pprint(inspect.getmembers(obj))

def DOLOG(msg):
    from debug_utils import LOG_NOTE
    from datetime import datetime
    LOG_NOTE("%s: %s" % (datetime.now().strftime('%Y-%m-%d %H:%M:%S'), msg))

def MYLOGLIVE(message, permanent_log = True, make_red = True):
    from messenger import MessengerEntry
    if message=="":
        return
    if permanent_log:
        DOLOG(message)
    if make_red:
        message = '<font color="#FF0000">' + message + '</font>'
    MessengerEntry.g_instance.gui.addClientMessage(message)
    
# config

_config = {}
d = False

import os, ResMgr, json, re, csv, codecs
_mods_name = os.path.basename(__file__).split(".")[0]
_conf_file = "./res_mods/%s.json" % _mods_name
if not os.path.isfile(_conf_file):
    _conf_file = ResMgr.openSection('../paths.xml')['Paths'].values()[0:2][0].asString + ("/scripts/client/gui/mods/%s.json" % _mods_name)
#print "config file: " + _conf_file

def buildRe(cfg):
    pattern = _config[cfg].get("regularExpression", "")
    words = _config[cfg].get("commaSeparatedWords", "")
    if words:
        for word in words.split(","):
            word = "\\b" + re.escape(word) + "\\b"
            if pattern:
                pattern = pattern + "|"
            pattern = pattern + word
    if pattern:
        if d: DOLOG("%s pattern: %s" % (cfg, pattern))
        return re.compile(pattern, re.IGNORECASE | re.UNICODE)
    else:
        return None

def loadConfig():
    global _config
    global _config_error
    global _abuse_re
    global _offensive_re
    global _spam_re
    global _exception_re
    global d
    if os.path.isfile(_conf_file):
        with codecs.open(_conf_file, 'r', 'utf-8-sig') as data_file:
            try:
                _config = json.load(data_file)
                d = _config.get("debug", False)
            except:
                import sys
                print "Error while loading %s: %s" % (_conf_file, sys.exc_info()[0])
                _config_error = "%s mod: configuration file corrupted - running on default values" % _mods_name
    else:
        _config_error = "%s mod: configuration file missing - running on default values" % _mods_name
    if _config.get("useTextFilters", True):
        if _config.get("abuseFilter", ""):
            _abuse_re = buildRe("abuseFilter")
        if _config.get("offensiveFilter", ""):
            _offensive_re = buildRe("offensiveFilter")
        if _config.get("spamFilter", ""):
            _spam_re = buildRe("spamFilter")
        if _config.get("exceptionFilter", ""):
            _exception_re = buildRe("exceptionFilter")

_abuse_re = None
_offensive_re = None
_spam_re = None
_exception_re = None
_re_stats = {}
_abusers = {}
_reports = {}
_enemies = {}
_squadders = {}

loadConfig()

if _config.get("logStats", False):
    log_filename = "%s.csv" % _mods_name
    log_writer = csv.writer(open(log_filename, 'at'), quoting=csv.QUOTE_ALL)
    if os.stat(log_filename).st_size==0:
        log_writer.writerow(("battleEnd","allMessages","offensiveMessages","battleType"))

from messenger.gui.Scaleform.battle_entry import BattleEntry
from messenger.m_constants import MESSENGER_COMMAND_TYPE
from gui.battle_control.controllers.chat_cmd_ctrl import ChatCommandsController
from messenger.m_constants import MESSENGER_COMMAND_TYPE

def getSenderID(obj):
    if hasattr(obj, "originator"):
        return obj.originator
    else:
        return obj.accountDBID
        
def getText(obj):
    if hasattr(obj, "text"):
        return obj.text
    else:
        return ""

from constants import DENUNCIATION, VIOLATOR_KIND
from messenger.proto.bw_chat2.entities import BWUnitChannelEntity
    
def BattleEntry__me_onMessageReceived(self, message, channel):
    if channel is not None:
        text = getText(message)
        if text:
            _re_stats["allMessages"] += 1
            if not type(channel) is BWUnitChannelEntity:
                senderID = getSenderID(message)
                if d: DOLOG("%d: %s (%s)" % (senderID, text, channel.__class__.__name__))                
                if _abuse_re and _abuse_re.search(text):
                    if d: DOLOG("filtered out abusing message: %s" % text)
                    _re_stats["offensiveMessages"] += 1
                    if _config.get("abuserPermaBlock", True):
                        _abusers[senderID] = True
                    if _config.get("abuserReport", True) and not _reports.has_key(senderID):
                        _reports[senderID] = True
                        left = getattr(BigWorld.player(), 'denunciationsLeft', 0)
                        if left > 0:
                            if d: DOLOG("abuser reported, %d reports left" % (left - 1))
                            BigWorld.player().makeDenunciation(senderID, DENUNCIATION.OFFEND, VIOLATOR_KIND.UNKNOWN)
                        else:
                            if d: DOLOG("abuser not reported, %d reports available" % left)
                    return
                abuser = _abusers.has_key(senderID)
                if _exception_re and _exception_re.search(text) and not abuser:
                    if d: DOLOG("exceptional message: %s" % text)
                    pass
                else:
                    if _offensive_re and _offensive_re.search(text):
                        if d: DOLOG("filtered out offensive message: %s" % text)
                        _re_stats["offensiveMessages"] += 1
                        return
                    if abuser:
                        if d: DOLOG("filtered out abuser's message: %s" % text)
                        return                    
                    if _spam_re and _spam_re.search(text):
                        if d: DOLOG("filtered out spam message: %s" % text)
                        return
                    if isSpam(text, senderID):
                        if d: DOLOG("spam message: %s" % text)
                        return
                    if ignorePlayer(senderID):
                        if d: DOLOG("ignored player's message: %s" % text)
                        return
        controller = self._BattleEntry__channelsCtrl.getController(channel.getClientID())
        if controller is None or not controller.isEnabled():
            return
        import BattleReplay
        if BattleReplay.g_replayCtrl.isRecording and not self._BattleEntry__enableRecord:
            BattleReplay.g_replayCtrl.skipMessage()
        controller.addMessage(message)

def BattleEntry__me_onCommandReceived(self, command):
    senderID = command.getSenderID()
    if not _clan_battle and not _squadders.has_key(senderID) and (
        ignorePlayer(senderID) or isSpam("BattleEntry:%s" % command.getCommandText(), senderID)
        ):
        if d: DOLOG("ignored command (1): %s" % command.getCommandText())
        return
    controller = self._BattleEntry__channelsCtrl.getController(command.getClientID())
    if controller:
        import BattleReplay
        if BattleReplay.g_replayCtrl.isRecording and (not self._BattleEntry__enableRecord or command.getCommandType() == MESSENGER_COMMAND_TYPE.ADMIN):
            BattleReplay.g_replayCtrl.skipMessage()
        controller.addCommand(command)
    else:
        LOG_ERROR('Controller not found', command)

def ChatCommandsController__me_onCommandReceived(self, cmd):
    if cmd.getCommandType() != MESSENGER_COMMAND_TYPE.BATTLE:
        return
    senderID = cmd.getSenderID()
    if not _clan_battle and not _squadders.has_key(senderID) and (
        ignorePlayer(senderID) or isSpam("ChatCommandsController:%s" % cmd.getCommandText(), senderID)
        ):
        if d: DOLOG("ignored command (2): %s" % cmd.getCommandText())
        return
    if cmd.isOnMinimap():
        self._ChatCommandsController__feedback.markCellOnMinimap(cmd.getCellIndex())
    elif cmd.isPrivate():
        self._ChatCommandsController__handlePrivateCommand(cmd)
    else:
        self._ChatCommandsController__playSound(cmd)
        if cmd.isPublic():
            self._ChatCommandsController__handlePublicCommand(cmd)
        else:
            self._ChatCommandsController__handleSimpleCommand(cmd)

def ChatCommandsController__sendChatCommand(self, command):
    if not _clan_battle:
        if isSpam("ChatCommandsController:%s" % command.getCommandText(), -1):
            return MYLOGLIVE(OWN_FAIL + " (spam)")
        elif not BigWorld.player().isVehicleAlive and _config.get("blockDead", False):
            return MYLOGLIVE(OWN_FAIL + " (dead)")
    old__ChatCommandsController__sendChatCommand(self, command)

from messenger.gui.Scaleform.channels.bw_chat2.battle_controllers import _ChannelController, SquadChannelController

def _ChannelController_sendMessage(self, message):
    if d: DOLOG("_ChannelController_sendMessage %s" % self.__class__.__name__)
    if not type(self) is SquadChannelController:
        if _abuse_re and _abuse_re.search(message):
            MYLOGLIVE(OWN_FAIL + " (abuse)")
            return False
        if _offensive_re and _offensive_re.search(message):
            MYLOGLIVE(OWN_FAIL + " (offensive)")
            return False
        if _spam_re and _spam_re.search(message):
            MYLOGLIVE(OWN_FAIL + " (spam)")
            return False
        if not BigWorld.player().isVehicleAlive and _config.get("blockDead", False):
            MYLOGLIVE(OWN_FAIL + " (dead)")
            return False
    return old__ChannelController_sendMessage(self, message)
    
old__BattleEntry__me_onMessageReceived = BattleEntry._BattleEntry__me_onMessageReceived
BattleEntry._BattleEntry__me_onMessageReceived = BattleEntry__me_onMessageReceived

old__BattleEntry__me_onCommandReceived = BattleEntry._BattleEntry__me_onCommandReceived
BattleEntry._BattleEntry__me_onCommandReceived = BattleEntry__me_onCommandReceived

old__ChatCommandsController__me_onCommandReceived = ChatCommandsController._ChatCommandsController__me_onCommandReceived
ChatCommandsController._ChatCommandsController__me_onCommandReceived = ChatCommandsController__me_onCommandReceived

old__ChatCommandsController__sendChatCommand = ChatCommandsController._ChatCommandsController__sendChatCommand
ChatCommandsController._ChatCommandsController__sendChatCommand = ChatCommandsController__sendChatCommand

old__ChannelController_sendMessage = _ChannelController.sendMessage
_ChannelController.sendMessage = _ChannelController_sendMessage

import BigWorld #, AccountCommands
from PlayerEvents import g_playerEvents
from constants import ARENA_PERIOD, ARENA_BONUS_TYPE
import datetime

_arenaUniqueID = 0
_clan_battle = False
_stat_keys = {}
_vehicle2player = {}
_players_alive = {}
_ratings = {}
_domination = False
_playerDatabaseID = None

from ConnectionManager import connectionManager

def region():
    serverUserName = connectionManager.serverUserName
    if d: DOLOG("serverUserName: %s" % serverUserName)
    if serverUserName:
        serverUserName = serverUserName.split(" ")[1]
        if serverUserName.startswith("EU"):
            return "eu"
        elif serverUserName.startswith("RU"):
            return "ru"
        else:
            return "com"
    else:
        return _config.get("region", "eu")

def noXVM():
    return _xvm_stat is None #and _stat.cacheBattle and _stat.cacheBattle.itervalues().next().get('wn8', None))

def onAccountShowGUI(ctx):
    global _playerDatabaseID
    if d: DOLOG("onAccountShowGUI(%s)" % str(ctx))
    _playerDatabaseID = ctx['databaseID']

_xvm_stat = None

def onArenaPeriodChange(period, periodEndTime, periodLength, periodAdditionalInfo, *args):
    global _arenaUniqueID
    global _clan_battle
    global _domination
    global _xvm_stat
    bw_player = BigWorld.player()
    arena = bw_player.arena
    _clan_battle = arena.bonusType in (
        #ARENA_BONUS_TYPE.UNKNOWN,
        #ARENA_BONUS_TYPE.REGULAR,
        ARENA_BONUS_TYPE.TRAINING,
        ARENA_BONUS_TYPE.COMPANY,
        #ARENA_BONUS_TYPE.TOURNAMENT,
        ARENA_BONUS_TYPE.CLAN,
        #ARENA_BONUS_TYPE.TUTORIAL,
        #ARENA_BONUS_TYPE.CYBERSPORT,
        #ARENA_BONUS_TYPE.HISTORICAL,
        #ARENA_BONUS_TYPE.EVENT_BATTLES,
        ARENA_BONUS_TYPE.SORTIE,
        ARENA_BONUS_TYPE.FORT_BATTLE,
        #ARENA_BONUS_TYPE.RATED_CYBERSPORT,
        ARENA_BONUS_TYPE.GLOBAL_MAP
    )
    _domination = (arena.bonusType == ARENA_BONUS_TYPE.EVENT_BATTLES)
    #DOLOG("onArenaPeriodChange(%d, %d, %d, %s) %d=%s" % (period, periodEndTime, periodLength, periodAdditionalInfo, arena.bonusType, str(_clan_battle)))
    if arena.arenaUniqueID != _arenaUniqueID:
        _arenaUniqueID = arena.arenaUniqueID
        _stat_keys.clear()
        _vehicle2player.clear()
        _players_alive.clear()
        _ratings.clear()
        _enemies.clear()
        _squadders.clear()
        _squadders[_playerDatabaseID] = True
        cache.clear()
        DbIDs = []
        prebattleID = None
        for (vehId, vData) in arena.vehicles.items():
            if vData['accountDBID'] == _playerDatabaseID:
                prebattleID = vData['prebattleID'] or -1
                if d: DOLOG("prebattleID: %s" % str(prebattleID))
                break
        for (vehId, vData) in arena.vehicles.items():
            vId = None
            if 'typeCompDescr' in vData:
                vId = vData['typeCompDescr']
            elif 'vehicleType' in vData:
                vId = vData['vehicleType'].type.compactDescr
            else:
                vId = 0
            accountDBID = vData['accountDBID']
            _stat_keys[accountDBID] = '%d=%d' % (accountDBID, vId)
            if accountDBID:
                DbIDs.append(str(accountDBID))
                if vData['isAlive']==True or accountDBID == _playerDatabaseID:
                    _vehicle2player[vehId] = accountDBID
                    _players_alive[accountDBID] = True
                if _config.get("blockEnemies", False) and not vData['team'] == bw_player.team:
                    _enemies[accountDBID] = True
                if prebattleID == vData['prebattleID']:
                    _squadders[accountDBID] = True
        if _xvm_stat is None and _config.get('minimal', {}).get('xvm', [0, 0])[1]:
            try:
                from xvm_main.python.stats import _stat
                _xvm_stat = _stat
            except ImportError:
                if d: DOLOG("xvm stats import failed")
                pass
        if noXVM() and _config.get("minimal", {}).get("globalRating", 0):
            res = ','.join(DbIDs)
            request = 'http://api.worldoftanks.{region}/wot/account/info/?application_id=demo&fields=global_rating&account_id={id}'.format(id=res, region=region())
            BigWorld.callback(0.0, lambda: getRatings(request))
        if d:
            DOLOG("_vehicle2player: %s" % str(_vehicle2player))
            DOLOG("_players_alive: %s" % str(_players_alive))
            DOLOG("_squadders: %s" % str(_squadders))
        _re_stats["allMessages"] = 0
        _re_stats["offensiveMessages"] = 0
        arena.onVehicleKilled += myOnVehicleKilled
    if arena.period == ARENA_PERIOD.AFTERBATTLE:
        if _config.get("logStats", False):
            periodEndTimeStr = (datetime.datetime.now() + datetime.timedelta(seconds=(periodEndTime - BigWorld.serverTime()))).strftime("%Y-%m-%d %H:%M:%S")
            log_writer.writerow((periodEndTimeStr, _re_stats["allMessages"], _re_stats["offensiveMessages"], arena.bonusType))

def getRatings(request):
    if d: DOLOG("getting " + request)
    import urllib2, json
    try:
        data = json.loads(urllib2.urlopen(request, timeout=15).read())['data']
        if d: MYPPRINT(data)
        for k, v in data.iteritems():
            if v:
                _ratings[int(k)] = v["global_rating"]
    except:
        from debug_utils import LOG_CURRENT_EXCEPTION
        LOG_CURRENT_EXCEPTION()
                
g_playerEvents.onArenaPeriodChange += onArenaPeriodChange
g_playerEvents.onAccountShowGUI += onAccountShowGUI

def myOnVehicleKilled(vehicleID, *args):
    if not _domination:
        del _players_alive[_vehicle2player[vehicleID]]

def ignorePlayer(accountDBID, text = None):
    result = False
    current = None
    if not _clan_battle:
        if not _players_alive.has_key(accountDBID) and _config.get("blockDead", False):
            if d and text:
                DOLOG("ignored dead player's message: %s" % text)
            return True
        if _enemies.has_key(accountDBID):
            if d and text:
                DOLOG("ignored enemy player's message: %s" % text)
            return True
    try:
        if noXVM():
            benchmark = "globalRating"
            minimal = _config.get('minimal', {}).get(benchmark, 0)
            if minimal:
                if minimal <= 1:
                    minimal = minimal * _ratings.get(_playerDatabaseID, 0)
                    if minimal > 1:
                        _config['minimal'][benchmark] = minimal
                current = _ratings.get(accountDBID, None)
            else:
                return False
        else:
            minimal = _config.get('minimal', {}).get('xvm', None)
            if minimal:
                benchmark = minimal[0]
                minimal = minimal[1]
                if minimal > 0 and minimal <= 1:
                    key = _stat_keys.get(_playerDatabaseID, '')
                    if key:
                        minimal = minimal * _xvm_stat.cacheBattle[key].get(benchmark, 0)
                        if minimal > 1:
                            _config['minimal']['xvm'] = [benchmark, minimal]
                    else:
                        DOLOG("no player's key: own")
                        return result
                key = _stat_keys.get(accountDBID, '')
                if key:
                    try:
                        current = _xvm_stat.cacheBattle[key].get(benchmark, None)
                    except:
                        from debug_utils import LOG_CURRENT_EXCEPTION
                        LOG_CURRENT_EXCEPTION()
                        return result
                else:
                    DOLOG("no player's key: %d" % accountDBID)
                    return result
            else:
                return False
        if d:
            if current is None:
                current = 0
            if text:
                DOLOG('ignorePlayer(%d) %s: %d < %d %s (%s)' % (accountDBID, benchmark, current, minimal, str(current < minimal), text))
            else:
                DOLOG('ignorePlayer(%d) %s: %d < %d %s' % (accountDBID, benchmark, current, minimal, str(current < minimal)))
        result = current < minimal
    except:
        from debug_utils import LOG_CURRENT_EXCEPTION
        LOG_CURRENT_EXCEPTION()
    finally:
        return result


# credits for below to: https://github.com/PavelMaca/WoT-BattleMessenger

import time
cache = {}

def isSpam(message, playerUid):
    if _clan_battle:
        return False
    
    duplicateCount = 0
    playerCount = 0
    currentTime = int(time.clock())
    
    # turn off duplicateCounter
    if _config.get("antispamDuplicateCount", 2) <= 0 or _config.get("antispamDuplicateInterval", 7) <= 0:
        duplicateCount = -1
    
    # turn off playerCounter
    if _config.get("antispamPlayerCount", 3) <= 0 or _config.get("antispamPlayerInterval", 7) <= 0:
        playerCount = -1
    
    # init cache for player
    if not cache.has_key(playerUid):
        cache[playerUid] = {}
    
    for msgTime in cache[playerUid]:
            # is messenge in time interval && msg match
            if duplicateCount >= 0 and msgTime > currentTime - _config.get("antispamDuplicateInterval", 7):
                if cache[playerUid][msgTime] == message:
                    duplicateCount += 1

            if playerCount >= 0 and msgTime > currentTime - _config.get("antispamPlayerInterval", 7):
                playerCount += 1    
    
    isDuplicate = (duplicateCount >= _config.get("antispamDuplicateCount", 2))
    isSpam = (playerCount >= _config.get("antispamPlayerCount", 3))
    
    if isDuplicate or isSpam:
        return True
    else:
        # add message to cache
        cache[playerUid][currentTime] = message        
        return False

channels_quarantined = {}
contacts_available = False

from messenger.proto.events import g_messengerEvents
from messenger.proto.xmpp.find_criteria import ItemsFindCriteria
from messenger.proto.xmpp.xmpp_constants import XMPP_ITEM_TYPE

def onUsersListReceived(tags):
    global contacts_available
    if d: DOLOG("onUsersListReceived %s (proto=%s, contacts_available=%s)" % (str(tags), str(not proto is None), str(contacts_available)))
    if proto and "friend" in tags and not "cached" in tags and not contacts_available:
        if d: DOLOG("we got contacts (count = %d)" % len(proto.contacts.usersStorage.all()))
        contacts_available = True
        for key, value in channels_quarantined.items():
            channel = value["channel"]
            cname = None
            try:
                cname = channel.getName()
            except AttributeError:
                pass
            if cname is None or (not getContact(cname) is None and not cname == "Russian_Scout"):
                BigWorld.cancelCallback(value["callback"])
                releaseChannel(key)
            elif not channel.isJoined():
                if d and cname: DOLOG("not a contact - requesting history for %s" % cname)
                proto.messages.requestChatHistory(channel.getID())


def releaseChannel(key):
    value = channels_quarantined[key]
    if d: DOLOG("releasing channel %s" % value["channel"].getName())
    old__LobbyEntry__handleLobbyChannelCtlInited(LobbyEntry, value["event"])
    del channels_quarantined[key]
    
g_messengerEvents.users.onUsersListReceived += onUsersListReceived

def getContact(name):
    if not contacts_available:
        return None
    for user in proto.contacts.usersStorage.all():
        if name==user.getName():
            return user
    return None
    
from gui.shared import EVENT_BUS_SCOPE, g_eventBus
from gui.shared.events import MessengerEvent

proto = None
LobbyEntry = None

from messenger.gui.Scaleform.lobby_entry import LobbyEntry

def _LobbyEntry__handleLobbyChannelCtlInited(self, event):
    global LobbyEntry, proto
    LobbyEntry = self
    ctx = event.ctx
    controller = ctx.get('controller')
    if controller is None:
        LOG_ERROR('Controller is not defined', ctx)
        return
    channel = controller.getChannel()
    if d: DOLOG("new channel inited: %s (clientID=%d, %s)" % (channel.getName(), channel.getClientID(), channel.__class__.__name__))
    if hasattr(controller.proto, "contacts") and proto is None:
        if d: DOLOG("we got proto")
        proto = controller.proto
    if channel.isSystem():
        DOLOG("system channel ready to launch: %s (clientID=%d)" % (channel.getName(), channel.getClientID()))
        old__LobbyEntry__handleLobbyChannelCtlInited(self, event)
    elif not hasattr(controller.proto, "contacts"):
        DOLOG("contactless system channel ready to launch: %s (clientID=%d)" % (channel.getName(), channel.getClientID()))
        old__LobbyEntry__handleLobbyChannelCtlInited(self, event)
    elif not getContact(channel.getName()) is None:
        DOLOG("contact's channel ready to launch: %s (clientID=%d)" % (channel.getName(), channel.getClientID()))
        old__LobbyEntry__handleLobbyChannelCtlInited(self, event)
    else:
        key = channel.getClientID()
        channels_quarantined[key] = {
            "channel": channel,
            "event": event,
            "callback": BigWorld.callback(_config["garageChannelsQuarantineSeconds"], lambda: checkChannel(key))
        }
        DOLOG("quarantined")

if _config["garageChannelsQuarantineSeconds"] > 0:
    old__LobbyEntry__handleLobbyChannelCtlInited = LobbyEntry._LobbyEntry__handleLobbyChannelCtlInited
    LobbyEntry._LobbyEntry__handleLobbyChannelCtlInited = _LobbyEntry__handleLobbyChannelCtlInited

from messenger.gui import events_dispatcher
from gui import SystemMessages

def getNameOrClass(channel):
    return channel.getName() if hasattr(channel, "getName") else channel.__class__.__name__
    
def checkChannel(key):
    if not contacts_available:
        channels_quarantined[key]["callback"] = BigWorld.callback(1, lambda: checkChannel(key))
        return
    history, kill = None, None
    channel = channels_quarantined[key]["channel"]
    if d: DOLOG("checking quarantined channel: %s" % getNameOrClass(channel))
    for text in channel.getHistory():
        if d: DOLOG("text line: %s" % text)
        if _abuse_re and _abuse_re.search(text):
            if d: DOLOG("abusing message in quarantined channel: %s" % text)
            kill = "abuse"
            break            
        if _offensive_re and _offensive_re.search(text):
            if d: DOLOG("offensive message in quarantined channel: %s" % text)
            kill = "offensive"
            break
        if _spam_re and _spam_re.search(text):
            if d: DOLOG("spam message in quarantined channel: %s" % text)
            kill = "spam"
            break
    releaseChannel(key)
    if kill:
        if _config.get("garageChannelsNotifyExit", True):
            SystemMessages.pushMessage("New quarantined channel (%s) was closed (%s)" % (getNameOrClass(channel), kill), SystemMessages.SM_TYPE.Warning)
        events_dispatcher.rqExitFromChannel(key)


import Avatar

def Avatar_processInvitations(self, invitations):
    if d: DOLOG('processInvitations')
    filtered_invitations = []
    for i in invitations:
        if ignorePlayer(i['senderDBID']):
            if d: DOLOG("rejecting invitation %d" % i['id'])
            BigWorld.player().prebattleInvitations.declineInvitation(i['id'], i['senderDBID'])            
        else:
            filtered_invitations.append(i)
    if filtered_invitations:
        old_Avatar_processInvitations(self, filtered_invitations)

old_Avatar_processInvitations = Avatar.PlayerAvatar.processInvitations
Avatar.PlayerAvatar.processInvitations = Avatar_processInvitations

from gui.battle_control.controllers.dyn_squad_functional import DynSquadMessagesController, _DynSquadSoundsController

def DoNothing(*args, **kwargs):
    pass

DynSquadMessagesController._squadCreatedByAllies = DoNothing
DynSquadMessagesController._squadCreatedByEnemies = DoNothing
DynSquadMessagesController._someoneJoinedAlliedSquad = DoNothing

#_DynSquadSoundsController._inviteReceived = DoNothing

if _config.get("blockAllTextInReplay", False):
    if d: DOLOG('blockAllTextInReplay')
    import BattleReplay
    BattleReplay.BattleReplay.onBattleChatMessage = DoNothing

# from gui.Scaleform.daapi.view.battle.legacy.messages.FadingMessages import FadingMessages
# 
# def FadingMessages_showMessage(self, key, args = None, extra = None, postfix = ''):
#     if d: DOLOG([key, args, extra, postfix])
#     if not key in _config.get("filterSystemMessages", []):
#         return old_showMessage(self, key, args, extra, postfix)
# 
# old_showMessage = FadingMessages.showMessage
# FadingMessages.showMessage = FadingMessages_showMessage
