# Path: constants/exceptions.py
# class loginFailedException(Exception):
# class loginBannedException(Exception):
# class tokenNotFoundException(Exception):
# class channelNoPermissionsException(Exception):
# class channelUnknownException(Exception):
# class channelModeratedException(Exception):
# class noAdminException(Exception):
# class commandSyntaxException(Exception):
# class banchoConfigErrorException(Exception):
# class banchoMaintenanceException(Exception):
# class moderatedPMException(Exception):
# class userNotFoundException(Exception):
# class alreadyConnectedException(Exception):
# class stopSpectating(Exception):
# class matchWrongPasswordException(Exception):
# class matchNotFoundException(Exception):
# class matchJoinErrorException(Exception):
# class matchCreateError(Exception):
# class banchoRestartingException(Exception):
# class apiException(Exception):
# class invalidArgumentsException(Exception):
# class messageTooLongWarnException(Exception):
# class messageTooLongException(Exception):
# class userSilencedException(Exception):
# class need2FAException(Exception):
# class userRestrictedException(Exception):
# class haxException(Exception):
# class forceUpdateException(Exception):
# class loginLockedException(Exception):
# class unknownStreamException(Exception):
# class userTournamentException(Exception):
# class userAlreadyInChannelException(Exception):
# class userNotInChannelException(Exception):
# class missingReportInfoException(Exception):
# class invalidUserException(Exception):
# class wrongChannelException(Exception):
# class periodicLoopException(Exception):
# 
# Path: constants/serverPackets.py
# def loginFailed():
# def forceUpdate():
# def loginBanned():
# def loginLocked():
# def loginError():
# def needSupporter():
# def needVerification():
# def userID(uid):
# def silenceEndTime(seconds):
# def protocolVersion(version = 19):
# def mainMenuIcon(icon):
# def userSupporterGMT(supporter, GMT, tournamentStaff):
# def friendList(userID):
# def onlineUsers():
# def userLogout(userID):
# def userPanel(userID, force = False):
# def userStats(userID, force = False):
# def sendMessage(fro, to, message):
# def channelJoinSuccess(userID, chan):
# def channelInfo(chan):
# def channelInfoEnd():
# def channelKicked(chan):
# def userSilenced(userID):
# def addSpectator(userID):
# def removeSpectator(userID):
# def spectatorFrames(data):
# def noSongSpectator(userID):
# def fellowSpectatorJoined(userID):
# def fellowSpectatorLeft(userID):
# def createMatch(matchID):
# def updateMatch(matchID, censored = False):
# def matchStart(matchID):
# def disposeMatch(matchID):
# def matchJoinSuccess(matchID):
# def matchJoinFail():
# def changeMatchPassword(newPassword):
# def allPlayersLoaded():
# def playerSkipped(userID):
# def allPlayersSkipped():
# def matchFrames(slotID, data):
# def matchComplete():
# def playerFailed(slotID):
# def matchTransferHost():
# def matchAbort():
# def switchServer(address):
# def notification(message):
# def banchoRestart(msUntilReconnection):
# def rtx(message):
# 
# Path: helpers/chatHelper.py
# def joinChannel(userID = 0, channel = "", token = None, toIRC = True, force=False):
# def partChannel(userID = 0, channel = "", token = None, toIRC = True, kick = False, force=False):
# def sendMessage(fro = "", to = "", message = "", token = None, toIRC = True):
# def fixUsernameForBancho(username):
# def fixUsernameForIRC(username):
# def IRCConnect(username):
# def IRCDisconnect(username):
# def IRCJoinChannel(username, channel):
# def IRCPartChannel(username, channel):
# def IRCAway(username, message):
# 
# Path: helpers/countryHelper.py
# def getCountryID(code):
# def getCountryLetters(code):
# 
# Path: helpers/locationHelper.py
# def getCountry(ip):
# def getLocation(ip):
# 
# Path: objects/glob.py
# 		VERSION = f.read().strip()
# 	VERSION = "Unknown"
# DATADOG_PREFIX = "peppy"


import sys
import time
import traceback
from common.constants import privileges
from common.log import logUtils as log
from common.ripple import userUtils
from constants import exceptions
from constants import serverPackets
from helpers import chatHelper as chat
from helpers import countryHelper
from helpers import locationHelper
from objects import glob


		# Save HWID in db for multiaccount detection
		hwAllowed = userUtils.logHardware(userID, clientData, firstLogin)

		# This is false only if HWID is empty
		# if HWID is banned, we get restricted so there's no
		# need to deny bancho access
		if not hwAllowed:
			raise exceptions.haxException()

		# Log user IP
		userUtils.logIP(userID, requestIP)

		# Delete old tokens for that user and generate a new one
		isTournament = "tourney" in osuVersion
		if not isTournament:
			glob.tokens.deleteOldTokens(userID)
		responseToken = glob.tokens.addToken(userID, requestIP, timeOffset=timeOffset, tournament=isTournament)
		responseTokenString = responseToken.token

		# Check restricted mode (and eventually send message)
		responseToken.checkRestricted()

		# Send message if donor expires soon
		if responseToken.privileges & privileges.USER_DONOR > 0:
			expireDate = userUtils.getDonorExpire(responseToken.userID)
			if expireDate-int(time.time()) <= 86400*3:
				expireDays = round((expireDate-int(time.time()))/86400)
				expireIn = "{} days".format(expireDays) if expireDays > 1 else "less than 24 hours"

# Path: constants/exceptions.py
# class loginFailedException(Exception):
# class loginBannedException(Exception):
# class tokenNotFoundException(Exception):
# class channelNoPermissionsException(Exception):
# class channelUnknownException(Exception):
# class channelModeratedException(Exception):
# class noAdminException(Exception):
# class commandSyntaxException(Exception):
# class banchoConfigErrorException(Exception):
# class banchoMaintenanceException(Exception):
# class moderatedPMException(Exception):
# class userNotFoundException(Exception):
# class alreadyConnectedException(Exception):
# class stopSpectating(Exception):
# class matchWrongPasswordException(Exception):
# class matchNotFoundException(Exception):
# class matchJoinErrorException(Exception):
# class matchCreateError(Exception):
# class banchoRestartingException(Exception):
# class apiException(Exception):
# class invalidArgumentsException(Exception):
# class messageTooLongWarnException(Exception):
# class messageTooLongException(Exception):
# class userSilencedException(Exception):
# class need2FAException(Exception):
# class userRestrictedException(Exception):
# class haxException(Exception):
# class forceUpdateException(Exception):
# class loginLockedException(Exception):
# class unknownStreamException(Exception):
# class userTournamentException(Exception):
# class userAlreadyInChannelException(Exception):
# class userNotInChannelException(Exception):
# class missingReportInfoException(Exception):
# class invalidUserException(Exception):
# class wrongChannelException(Exception):
# class periodicLoopException(Exception):
# 
# Path: constants/serverPackets.py
# def loginFailed():
# def forceUpdate():
# def loginBanned():
# def loginLocked():
# def loginError():
# def needSupporter():
# def needVerification():
# def userID(uid):
# def silenceEndTime(seconds):
# def protocolVersion(version = 19):
# def mainMenuIcon(icon):
# def userSupporterGMT(supporter, GMT, tournamentStaff):
# def friendList(userID):
# def onlineUsers():
# def userLogout(userID):
# def userPanel(userID, force = False):
# def userStats(userID, force = False):
# def sendMessage(fro, to, message):
# def channelJoinSuccess(userID, chan):
# def channelInfo(chan):
# def channelInfoEnd():
# def channelKicked(chan):
# def userSilenced(userID):
# def addSpectator(userID):
# def removeSpectator(userID):
# def spectatorFrames(data):
# def noSongSpectator(userID):
# def fellowSpectatorJoined(userID):
# def fellowSpectatorLeft(userID):
# def createMatch(matchID):
# def updateMatch(matchID, censored = False):
# def matchStart(matchID):
# def disposeMatch(matchID):
# def matchJoinSuccess(matchID):
# def matchJoinFail():
# def changeMatchPassword(newPassword):
# def allPlayersLoaded():
# def playerSkipped(userID):
# def allPlayersSkipped():
# def matchFrames(slotID, data):
# def matchComplete():
# def playerFailed(slotID):
# def matchTransferHost():
# def matchAbort():
# def switchServer(address):
# def notification(message):
# def banchoRestart(msUntilReconnection):
# def rtx(message):
# 
# Path: helpers/chatHelper.py
# def joinChannel(userID = 0, channel = "", token = None, toIRC = True, force=False):
# def partChannel(userID = 0, channel = "", token = None, toIRC = True, kick = False, force=False):
# def sendMessage(fro = "", to = "", message = "", token = None, toIRC = True):
# def fixUsernameForBancho(username):
# def fixUsernameForIRC(username):
# def IRCConnect(username):
# def IRCDisconnect(username):
# def IRCJoinChannel(username, channel):
# def IRCPartChannel(username, channel):
# def IRCAway(username, message):
# 
# Path: helpers/countryHelper.py
# def getCountryID(code):
# def getCountryLetters(code):
# 
# Path: helpers/locationHelper.py
# def getCountry(ip):
# def getLocation(ip):
# 
# Path: objects/glob.py
# 		VERSION = f.read().strip()
# 	VERSION = "Unknown"
# DATADOG_PREFIX = "peppy"


# Path: events/loginEvent.py
import sys
import time
import traceback
from common.constants import privileges
from common.log import logUtils as log
from common.ripple import userUtils
from constants import exceptions
from constants import serverPackets
from helpers import chatHelper as chat
from helpers import countryHelper
from helpers import locationHelper
from objects import glob



		# Save HWID in db for multiaccount detection
		hwAllowed = userUtils.logHardware(userID, clientData, firstLogin)

		# This is false only if HWID is empty
		# if HWID is banned, we get restricted so there's no
		# need to deny bancho access
		if not hwAllowed:
			raise exceptions.haxException()

		# Log user IP
		userUtils.logIP(userID, requestIP)

		# Delete old tokens for that user and generate a new one
		isTournament = "tourney" in osuVersion
		if not isTournament:
			glob.tokens.deleteOldTokens(userID)
		responseToken = glob.tokens.addToken(userID, requestIP, timeOffset=timeOffset, tournament=isTournament)
		responseTokenString = responseToken.token

		# Check restricted mode (and eventually send message)
		responseToken.checkRestricted()

		# Send message if donor expires soon
		if responseToken.privileges & privileges.USER_DONOR > 0:
			expireDate = userUtils.getDonorExpire(responseToken.userID)
			if expireDate-int(time.time()) <= 86400*3:
				expireDays = round((expireDate-int(time.time()))/86400)
				expireIn = "{} days".format(expireDays) if expireDays > 1 else "less than 24 hours"

				responseToken.enqueue(serverPackets.notification("Your donor tag expires in {}! When your donor tag expires, you won't have any of the donor privileges, like yellow username, custom badge and discord custom role and username color! If you wish to keep supporting Ripple and you don't want to lose your donor privileges, you can donate again by clicking on 'Support us' on Ripple's website.".format(expireIn)))