本文整理汇总了Python中txircd.utils.now函数的典型用法代码示例。如果您正苦于以下问题:Python now函数的具体用法?Python now怎么用?Python now使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了now函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ping
def ping(self, intervals):
timeout = self.factory.servconfig["client_timeout_delay"] + self.factory.servconfig["client_ping_interval"] * (intervals - 1)
if (now() - self.type.lastpong).total_seconds() > timeout:
log.msg("Client has stopped responding to PING and is now disconnecting.")
self.transport.loseConnection()
self.connectionLost(None)
elif self.type.lastactivity > self.type.lastpong:
self.type.lastpong = now()
else:
self.sendMessage("PING",":{}".format(self.factory.name))
示例2: execute
def execute(self, server, data):
if "lostserver" in data:
return True
if data["dest"] == self.ircd.serverID:
if data["source"] == server.serverID:
server.cache["pongtime"] = now()
else:
self.ircd.servers[data["source"]].cache["pongtime"] = now()
return True
self.ircd.servers[data["dest"]].sendMessage("PONG", data["source"], data["dest"], prefix=data["prefix"])
return True
示例3: pingServer
def pingServer(self, server):
if "pingtime" not in server.cache or "pongtime" not in server.cache:
server.cache["pingtime"] = now()
server.cache["pongtime"] = now()
pingTime = server.cache["pingtime"]
pongTime = server.cache["pongtime"]
if pongTime < pingTime:
self.ircd.log.debug("Server {server.serverID} pinged out (last pong time '{pongTime}' was less than last ping time '{pingTime}' at the next ping interval)", server=server, pongTime=pongTime, pingTime=pingTime)
server.disconnect("Ping timeout")
return
server.sendMessage("PING", self.ircd.serverID, server.serverID, prefix=self.ircd.serverID)
server.cache["pingtime"] = now()
示例4: __init__
def __init__(self, ircd, name):
if not isValidChannelName(name):
raise InvalidChannelNameError
self.ircd = ircd
self.name = name[:self.ircd.config.get("channel_name_length", 64)]
self.users = WeakKeyDictionary()
self.modes = {}
self.existedSince = now()
self.topic = ""
self.topicSetter = ""
self.topicTime = now()
self._metadata = CaseInsensitiveDictionary()
self.cache = {}
示例5: ChannelFactory
def ChannelFactory(self, name):
logfile = "{}/{}".format(self.app_log_dir, irc_lower(name))
if not os.path.exists(logfile):
os.makedirs(logfile)
c = Channel(
name,
now(),
{"message": None, "author": "", "created": now()},
CaseInsensitiveDictionary(),
ChannelModes(self, None),
DailyLogFile("log", logfile),
)
c.mode.parent = c
c.mode.combine("nt", [], name)
return c
示例6: execute
def execute(self, user, data):
if "server" in data:
server = data["server"]
server.sendMessage("USERTIMEREQ", server.serverID, prefix=user.uuid)
else:
user.sendMessage(irc.RPL_TIME, self.ircd.name, str(now()))
return True
示例7: disconnect
def disconnect(self, reason):
"""
Disconnects the user from the server.
"""
self.ircd.log.debug("Disconnecting user {user.uuid} ({user.hostmask()}): {reason}", user=self, reason=reason)
# Sometimes, actions deferred from initial connection may cause registration to occur after disconnection if
# disconnection happens before registration completes. If the user is unregistered on disconnection, this prevents
# the user from completing registration.
self.addRegisterHold("QUIT")
if self._pinger:
if self._pinger.running:
self._pinger.stop()
self._pinger = None
if self._registrationTimeoutTimer:
if self._registrationTimeoutTimer.active():
self._registrationTimeoutTimer.cancel()
self._registrationTimeoutTimer = None
if self._connectHandlerTimer and self._connectHandlerTimer.active():
self._connectHandlerTimer.cancel()
self._connectHandlerTimer = None
self.ircd.recentlyQuitUsers[self.uuid] = now()
del self.ircd.users[self.uuid]
if self.isRegistered():
del self.ircd.userNicks[self.nick]
userSendList = [self]
while self.channels:
channel = self.channels[0]
userSendList.extend(channel.users.keys())
self._leaveChannel(channel)
userSendList = [u for u in set(userSendList) if u.uuid[:3] == self.ircd.serverID]
userSendList.remove(self)
self.ircd.runActionProcessing("quitmessage", userSendList, self, reason, users=[self] + userSendList)
self.ircd.runActionStandard("quit", self, reason, users=self)
self.transport.loseConnection()
示例8: getPeriodData
def getPeriodData(self):
"""Returns (period as integer, time to end of period)"""
nowTS = timestamp(now())
interval = self.ircd.config["rate_interval"]
period = int(nowTS / interval)
timeToEnd = (period + 1) * interval - nowTS
return period, timeToEnd
示例9: onUse
def onUse(self, user, data):
if "targetuser" not in data:
return
targets = data["targetuser"]
for u in targets:
user.sendMessage(irc.RPL_WHOISUSER, u.nickname, u.username, u.hostname, "*", ":{}".format(u.realname))
if "o" in user.mode or user == u:
user.sendMessage(irc.RPL_WHOISHOST, u.nickname, ":is connecting from {}@{} {}".format(u.username, u.realhost, u.ip))
chanlist = []
for chan in self.ircd.channels.itervalues():
if u in chan.users:
chanlist.append(chan)
chandisplay = []
for cdata in chanlist:
if user in cdata.users or ("s" not in cdata.mode and "p" not in cdata.mode):
statuses = cdata.users[u] if u in cdata.users else ""
status = self.ircd.prefixes[statuses[0]][0] if statuses else ""
chandisplay.append("{}{}".format(status, cdata.name))
if chandisplay:
user.sendMessage(irc.RPL_WHOISCHANNELS, u.nickname, ":{}".format(" ".join(chandisplay)))
user.sendMessage(irc.RPL_WHOISSERVER, u.nickname, u.server, ":{}".format(self.ircd.servconfig["server_description"] if u.server == self.ircd.name else self.ircd.servers[u.server].description))
if "accountname" in u.metadata["ext"]:
user.sendMessage(irc.RPL_WHOISACCOUNT, u.nickname, u.metadata["ext"]["accountname"], ":is logged in as")
if u.socket.secure:
user.sendMessage(irc.RPL_WHOISSECURE, u.nickname, ":is using a secure connection")
if "certfp" in u.metadata["server"]:
user.sendMessage(irc.RPL_WHOISCERTFP, u.nickname, ":has client certificate fingerprint {}".format(u.metadata["server"]["certfp"]))
if "o" in u.mode:
user.sendMessage(irc.RPL_WHOISOPERATOR, u.nickname, ":is an IRC operator")
if "whoisdata" in self.ircd.actions:
for action in self.ircd.actions["whoisdata"]:
action(user, u)
user.sendMessage(irc.RPL_WHOISIDLE, u.nickname, str(epoch(now()) - epoch(u.lastactivity)), str(epoch(u.signon)), ":seconds idle, signon time")
user.sendMessage(irc.RPL_ENDOFWHOIS, u.nickname, ":End of /WHOIS list")
示例10: pingUser
def pingUser(self, user):
if "pingtime" not in user.cache or "pongtime" not in user.cache:
user.cache["pingtime"] = now()
user.cache["pongtime"] = now()
pingTime = user.cache["pingtime"]
pongTime = user.cache["pongtime"]
if pongTime < pingTime:
self.ircd.log.debug("User {user.uuid} pinged out (last pong time '{pongTime}' was less than last ping time '{pingTime}' at the next ping interval)", user=user, pongTime=pongTime, pingTime=pingTime)
user.disconnect("Ping timeout")
return
if user.idleSince > user.cache["pongtime"]:
user.cache["pingtime"] = now()
user.cache["pongtime"] = now()
return
user.sendMessage("PING", self.ircd.name, to=None, prefix=None)
user.cache["pingtime"] = now()
示例11: disconnect
def disconnect(self, reason):
"""
Disconnects the user from the server.
"""
self.ircd.log.debug("Disconnecting user {user.uuid} ({user.hostmask()}): {reason}", user=self, reason=reason)
if self._pinger:
if self._pinger.running:
self._pinger.stop()
self._pinger = None
if self._registrationTimeoutTimer:
if self._registrationTimeoutTimer.active():
self._registrationTimeoutTimer.cancel()
self._registrationTimeoutTimer = None
self.ircd.recentlyQuitUsers[self.uuid] = now()
del self.ircd.users[self.uuid]
if self.isRegistered():
del self.ircd.userNicks[self.nick]
userSendList = [self]
while self.channels:
channel = self.channels[0]
userSendList.extend(channel.users.keys())
self._leaveChannel(channel)
userSendList = [u for u in set(userSendList) if u.uuid[:3] == self.ircd.serverID]
userSendList.remove(self)
self.ircd.runActionProcessing("quitmessage", userSendList, self, reason, users=[self] + userSendList)
self.ircd.runActionStandard("quit", self, reason, users=self)
self.transport.loseConnection()
示例12: apply
def apply(self, actionName, channel, param, user, data):
if "targetchans" not in data or channel not in data["targetchans"]:
return
if self.ircd.runActionUntilValue("checkexemptchanops", "chanflood", channel, user):
return
if "floodhistory" not in channel.users[user]:
channel.users[user]["floodhistory"] = []
currentTime = now()
channel.users[user]["floodhistory"].append((data["targetchans"][channel], currentTime))
maxLines, seconds = param.split(":")
maxLines = int(maxLines)
seconds = int(seconds)
duration = timedelta(seconds=seconds)
floodTime = currentTime - duration
floodHistory = channel.users[user]["floodhistory"]
while floodHistory:
if floodHistory[0][1] <= floodTime:
del floodHistory[0]
else:
break
channel.users[user]["floodhistory"] = floodHistory
if len(floodHistory) > maxLines:
user.leaveChannel(channel, "KICK", { "byuser": False, "server": self.ircd, "reason": "Channel flood limit reached" })
示例13: startService
def startService(self):
self.log.info("Starting up...")
self.startupTime = now()
self.log.info("Loading configuration...")
self.config.reload()
self.name = self.config["server_name"]
self.serverID = self.config["server_id"]
self.log.info("Loading storage...")
self.storage = shelve.open(self.config["datastore_path"], writeback=True)
self.storageSyncer = LoopingCall(self.storage.sync)
self.storageSyncer.start(self.config.get("storage_sync_interval", 5), now=False)
self.log.info("Starting processes...")
self.pruneRecentlyQuit = LoopingCall(self.pruneQuit)
self.pruneRecentlyQuit.start(10, now=False)
self.pruneRecentChannels = LoopingCall(self.pruneChannels)
self.pruneRecentChannels.start(15, now=False)
self.log.info("Loading modules...")
self._loadModules()
self.log.info("Binding ports...")
self._bindPorts()
self.log.info("txircd started!")
try:
self._logFilter.setLogLevelForNamespace("txircd", LogLevel.levelWithName(self.config["log_level"]))
except (KeyError, InvalidLogLevelError):
self._logFilter.setLogLevelForNamespace("txircd", LogLevel.warn)
self.runActionStandard("startup")
示例14: addUserToWhowas
def addUserToWhowas(self, user, reason):
if not user.isRegistered():
# user never registered a nick, so no whowas entry to add
return
lowerNick = ircLower(user.nick)
allWhowas = self.ircd.storage["whowas"]
if lowerNick in allWhowas:
whowasEntries = allWhowas[lowerNick]
else:
whowasEntries = []
serverName = self.ircd.name
if user.uuid[:3] != self.ircd.serverID:
serverName = self.ircd.servers[user.uuid[:3]].name
whowasEntries.append({
"nick": user.nick,
"ident": user.ident,
"host": user.host(),
"gecos": user.gecos,
"server": serverName,
"when": timestamp(now())
})
whowasEntries = self.removeOldEntries(whowasEntries)
if whowasEntries:
allWhowas[lowerNick] = whowasEntries
elif lowerNick in allWhowas:
del allWhowas[lowerNick]
示例15: disconnect
def disconnect(self, reason, netsplitQuitMsg = None):
"""
Disconnects the server.
"""
if self.nextClosest == self.ircd.serverID:
self.ircd.log.warn("Disconnecting server {server.name}: {reason}", server=self, reason=reason)
else:
self.ircd.log.warn("Removing server {server.name}: {reason}", server=self, reason=reason)
self.ircd.runActionStandard("serverquit", self, reason)
if self.serverID in self.ircd.servers:
if netsplitQuitMsg is None:
netsplitQuitMsg = "{} {}".format(self.ircd.servers[self.nextClosest].name if self.nextClosest in self.ircd.servers else self.ircd.name, self.name)
allUsers = self.ircd.users.values()
for user in allUsers:
if user.uuid[:3] == self.serverID:
user.disconnect(netsplitQuitMsg, True)
allServers = self.ircd.servers.values()
for server in allServers:
if server.nextClosest == self.serverID:
server.disconnect(reason, netsplitQuitMsg)
self.ircd.recentlyQuitServers[self.serverID] = now()
del self.ircd.servers[self.serverID]
del self.ircd.serverNames[self.name]
self.bursted = None
if self._pinger.running:
self._pinger.stop()
if self._registrationTimeoutTimer.active():
self._registrationTimeoutTimer.cancel()
self._endConnection()