class TrivialContact(Item): implements(sip.IContact, ixmantissa.INavigableElement) typeName = "sine_trivialcontact" schemaVersion = 1 physicalURL = bytes() altcontact = bytes() expiryTime = timestamp() installedOn = reference() powerupInterfaces = (ixmantissa.INavigableElement, sip.IContact) def registerAddress(self, physicalURL, expiryTime): self.physicalURL = physicalURL.toString() self.expiryTime = Time.fromPOSIXTimestamp(time.time() + expiryTime) return [(physicalURL, self.expiryTime)] def unregisterAddress(self, physicalURL): storedURL = sip.parseURL(self.physicalURL) if storedURL != physicalURL: raise ValueError, "what" self.physicalURL = None return [(physicalURL, 0)] def getRegistrationInfo(self, caller): registered = False if self.physicalURL is not None: now = time.time() if now < self.expiryTime.asPOSIXTimestamp(): registered = True if registered: return [(sip.parseURL(self.physicalURL), int(self.expiryTime.asPOSIXTimestamp() - now))] elif self.altcontact: return [(sip.parseURL(self.altcontact), -1)] else: return defer.fail(sip.RegistrationError(480)) def placeCall(self, target): svc = self.store.parent.findUnique(SIPServer) svc.setupCallBetween(("", self.getRegistrationInfo(target)[0][0], {}), ("", target, {})) def callIncoming(self, name, uri, caller): Call(store=self.store, name=name, time=Time(), uri=unicode(str(uri)), kind=u'from') def callOutgoing(self, name, uri): Call(store=self.store, name=name, time=Time(), uri=unicode(str(uri)), kind=u'to') def getTabs(self): return [webnav.Tab('Voice', self.storeID, 0.25)]
class PersistentSession(item.Item): """A session that persists on the database. These sessions should not store any state, but are used only to determine that the user has previously authenticated and should be given a transient session (a regular guard session, not database persistant) without providing credentials again. """ typeName = 'persistent_session' schemaVersion = 1 sessionKey = attributes.bytes() lastUsed = attributes.timestamp() authenticatedAs = attributes.bytes() # The username and domain # that this session was # authenticated as. def __init__(self, **kw): assert kw.get( 'sessionKey' ) is not None, "None cookie propogated to PersistentSession" kw['lastUsed'] = extime.Time() super(PersistentSession, self).__init__(**kw) def __repr__(self): return "PersistentSession(%r)" % (self.sessionKey, ) def renew(self): """Renew the lifetime of this object. Call this when the user logs in so this session does not expire. """ self.lastUsed = extime.Time()
class D(Item): schemaVersion = 1 typeName = 'd' id = bytes() one = bytes() two = bytes() three = bytes() four = text()
class CalendarShareMapper(Item): typeNAme = 'db_calsharer' schemaVersion = 1 # The FQ name of the user who is sharing their calander (ie, [email protected]) owner = bytes() # FQ name of user recieving the view permission viewer = bytes()
class UsernamePassword(item.Item): """ A stored username and password. Since the password is stored in plaintext, this is primarily useful for credentials you use, not for credentials you check against. """ username = attributes.bytes(allowNone=False) password = attributes.bytes(allowNone=False)
class RedirectPlugin(Item): redirectFrom = bytes(default='admin.php') redirectTo = bytes(default='private') powerupInterfaces = (ISiteRootPlugin, ) implements(*powerupInterfaces) def produceResource(self, request, segments, viewer): if segments == tuple([self.redirectFrom]): return (URL.fromRequest(request).child(self.redirectTo), ())
class _PersistedFactory(item.Item): identifier = attributes.bytes(indexed=True) name = attributes.bytes() def dereference(self): """Returns the object to which the name attribute points. This will be a unary callable taking a store and producing a factory. """ return namedAny(self.name)
class UsernameScryptedPassword(item.Item): """ A username and a securely stored password. """ powerupInterfaces = [credentials.IUsernameHashedPassword] username = attributes.bytes(allowNone=False) _encrypted = attributes.bytes(allowNone=False) def checkPassword(self, password): """ Checks that the provided password is the same as the one used to create this set of credentials. """ return txsw.checkPassword(self._encrypted, password) @classmethod def storePassword(cls, username, password, **kwargs): """ Creates an ``IUsernameHashedPassword`` with the given username and an encrypted key securely derived from the given password. The ``kwargs`` are passed on to txscrypt's ``computeKey``. """ d = txsw.computeKey(password, **kwargs) @d.addCallback def buildItem(encrypted): return cls(username=username, _encrypted=encrypted) return d @classmethod def addPowerupFor(cls, empowered, username, password, **kwargs): """ Adds a ``IUsernameHashedPassword`` powerup for the ``empowered`` implementation that will verify against the given credentials. The ``kwargs`` are passed on to ``storePassword``. """ d = cls.storePassword(username, password, **kwargs) @d.addCallback def powerUp(usernameHashedPassword): usernameHashedPassword.store = empowered.store empowered.powerUp(usernameHashedPassword) return usernameHashedPassword return d
class IndexableThing(item.Item): implements(ixmantissa.IFulltextIndexable) _uniqueIdentifier = attributes.bytes() _textParts = attributes.inmemory() _keywordParts = attributes.inmemory() _documentType = attributes.inmemory() def uniqueIdentifier(self): return self._uniqueIdentifier def textParts(self): return self._textParts def keywordParts(self): return self._keywordParts def documentType(self): return self._documentType def sortKey(self): return self.uniqueIdentifier()
class ConfessionDispatcher(Item): implements(sip.IVoiceSystem) typeName = "sine_confession_dispatcher" schemaVersion = 1 installedOn = reference() localHost = bytes() uas = inmemory() confessionUser = dependsOn(ConfessionUser) powerupInterfaces = (sip.IVoiceSystem, ) def activate(self): svc = self.store.parent.findUnique(sipserver.SIPServer) self.uas = useragent.UserAgent.server(self, self.localHost, svc.mediaController) def lookupProcessor(self, msg, dialogs): #XXX haaaaack if 'confession@' in msg.headers['to'][0]: #double hack =/ self.uas.dialogs = dialogs return self.uas def localElementByName(self, name): if name == 'confession': return self.confessionUser else: raise sip.SIPLookupError(404)
class ShellAccount(Item): """ Axiom cred hook for creating SSH avatars. """ powerupInterfaces = (IConchUser, ) implements(IPowerupIndirector) garbage = bytes() def indirect(self, interface): """ Create an L{IConchUser} avatar which will use L{ShellServer} to interact with the connection. """ if interface is IConchUser: componentized = Componentized() user = _BetterTerminalUser(componentized, None) session = _BetterTerminalSession(componentized) session.transportFactory = TerminalSessionTransport session.chainedProtocolFactory = lambda: ServerProtocol( ShellServer, self.store) componentized.setComponent(IConchUser, user) componentized.setComponent(ISession, session) return user raise NotImplementedError(interface)
class Exercise(item.Item): """An exercise. """ identifier = attributes.bytes(allowNone=False) title = attributes.text(allowNone=False) description = attributes.text(allowNone=False) def solvedBy(self, user): """Stores that this user has just solved this exercise. You probably want to notify the user when this happens. For that, see ``solveAndNotify``. """ _Solution(store=self.store, who=user, what=self) def wasSolvedBy(self, user): """Checks if this exercise has previously been solved by the user. """ thisExercise = _Solution.what == self byThisUser = _Solution.who == user condition = q.AND(thisExercise, byThisUser) return self.store.query(_Solution, condition, limit=1).count() == 1
class RemoteStatsObserver(item.Item): """ Obsolete. Only present for schema compatibility. Do not use. """ hostname = attributes.bytes(doc="A host to send stat updates to") port = attributes.integer(doc="The port to send stat updates to") protocol = attributes.inmemory(doc="The juice protocol instance to send stat updates over")
class MessageInfo(item.Item): typeName = 'quotient_pop3_message' schemaVersion = 2 localPop3UID = attributes.bytes() localPop3Deleted = attributes.boolean(indexed=True) message = attributes.reference()
class ThingWithCharacterAndByteStrings(Item): schemaVersion = 1 typeName = 'ThingWithCharacterAndByteStrings' characterString = text(caseSensitive=True) caseInsensitiveCharString = text(caseSensitive=False) byteString = bytes()
class TimedEventFailureLog(Item): typeName = 'timed_event_failure_log' schemaVersion = 1 desiredTime = timestamp() actualTime = timestamp() runnable = reference() traceback = bytes()
class ConfessionBenefactor(Item): implements(ixmantissa.IBenefactor) typeName = 'confession_benefactor' schemaVersion = 1 # Number of users this benefactor has endowed endowed = integer(default=0) localHost = bytes()
class FusionIndexService(Item, Service): """ REMOVED: Old service powerup. """ schemaVersion = 2 powerupInterfaces = [IService] interface = a.bytes(default='', allowNone=False) port = a.integer(default=8443, allowNone=False) caPath = a.text(allowNone=False) certPath = a.text(allowNone=False)
class _StoredByName(item.Item): """ A powerup indirector for something that is stored by name. """ className = attributes.bytes(allowNone=False) def indirect(self, interface): """ Instantiates the named class with this object's store, then adapts it to the given interface. """ return interface(namedAny(self.className)(self.store))
class ServerEndpoint(item.Item, _Endpoint): """ A persisted server endpoint. """ description = attributes.bytes(allowNone=False) _cachedEndpoint = attributes.inmemory() factory = staticmethod(endpoints.serverFromString) def listen(self, factory): """ Listens with the factory on the connected endpoint. """ return self.instantiate().listen(factory)
class ClientEndpoint(_Endpoint, item.Item): """ A persisted client endpoint. """ description = attributes.bytes(allowNone=False) _cachedEndpoint = attributes.inmemory() factory = staticmethod(endpoints.clientFromString) def connect(self, factory): """ Connects the factory to the persisted endpoint. """ return self.instantiate().connect(factory)
class CalendarEntry(Item): typeName = 'db_caldate' schemaVersion = 1 # The FQ name of the entry owner (ie, [email protected]) owner = bytes() # All the bits of the date (easier to process chunks like this than a timestamp object) day = integer() month = integer() year = integer() # Start time hourS = integer() minuteS = integer() # End time hourE = integer() minuteE = integer() # The description descrip = bytes() # Should the user get emailed an allert for this emailAlert = boolean() # Repeats: 0 - does not repeat, 1- repeats every day, 2- repeats weekly, 3- repeats monthly, 4- repeays yearly repeats = integer() # Should I set a vacation message during this date :-) vacation = boolean() # Even if the users calander is shared, hide this particular one private = boolean() # Ehash ehash = bytes()
class _RemoveDocument(item.Item): """ Tracks a document deletion which should occur before the next search is performed. """ indexer = attributes.reference(doc=""" The indexer item with which this deletion is associated. """, whenDeleted=attributes.reference.CASCADE) documentIdentifier = attributes.bytes(doc=""" The identifier, as returned by L{IFulltextIndexable.uniqueIdentifier}, for the document which should be removed from the index. """, allowNone=False)
class DSPAMFilter(item.Item): """ libdspam-based L{iquotient.IHamFilter} powerup. """ implements(iquotient.IHamFilter) schemaVersion = 2 classifier = attributes.inmemory() username = attributes.inmemory() lib = attributes.inmemory() globalPath = attributes.bytes() filter = dependsOn(Filter) powerupInterfaces = (iquotient.IHamFilter, ) def installed(self): self.globalPath = self.store.parent.newFilePath("dspam").path def _homePath(self): return self.store.newFilePath('dspam-%d' % (self.storeID, )) def activate(self): username, domain = userbase.getAccountNames(self.store).next() self.username = ("%s@%s" % (username, domain)).encode('ascii') self.lib = dspam.startDSPAM(self.username, self._homePath().path.encode('ascii')) def classify(self, item): result, clas, conf = dspam.classifyMessageWithGlobalGroup( self.lib, self.username, 'global', self._homePath().path.encode('ascii'), self.globalPath, item.impl.source.open().read(), train=True) return result == dspam.DSR_ISSPAM, conf def train(self, spam, item): dspam.trainMessageFromError( self.lib, self.username, self._homePath().path.encode('ascii'), item.impl.source.open().read(), spam and dspam.DSR_ISSPAM or dspam.DSR_ISINNOCENT) def forgetTraining(self): p = self._homePath() if p.exists(): p.remove()
class Volume(Item): """ Item class represents a volume record for netflow data """ typeName = 'db_volume' schemaVersion = 1 vIn = integer() vOut = integer() timestamp = integer() month = integer() year = integer() day = integer() port = integer() localIp = bytes()
class BatchProcessingError(item.Item): processor = attributes.reference(doc=""" The batch processor which owns this failure. """) listener = attributes.reference(doc=""" The listener which caused this error. """) item = attributes.reference(doc=""" The item which actually failed to be processed. """) error = attributes.bytes(doc=""" The error message which was associated with this failure. """)
class Traceback(Item): typeName = 'mantissa_traceback' schemaVersion = 1 when = timestamp() traceback = bytes() collector = reference() def __init__(self, store, collector, failure): when = extime.Time() traceback = failure.getTraceback() super(Traceback, self).__init__( store=store, traceback=traceback, when=when, collector=collector)
class POP3UID(item.Item): grabberID = attributes.text(doc=""" A string identifying the email-address/port parts of a configured grabber """, indexed=True) value = attributes.bytes(doc=""" A POP3 UID which has already been retrieved. """, indexed=True) failed = attributes.boolean(doc=""" When set, indicates that an attempt was made to retrieve this UID, but for some reason was unsuccessful. """, indexed=True, default=False)
class SecureShellConfiguration(Item): """ Configuration object for a Mantissa SSH server. """ powerupInterfaces = (IProtocolFactoryFactory, ) implements(*powerupInterfaces) loginSystem = dependsOn(LoginSystem) hostKey = bytes(doc=""" An OpenSSH-format string giving the host key for this server. """, allowNone=False, defaultFactory=_generate) def __repr__(self): """ Return a summarized representation of this item. """ fmt = "SecureShellConfiguration(storeID=%d, hostKeyFingerprint='%s')" privateKey = Key.fromString(data=self.hostKey) publicKeyBlob = privateKey.blob() fingerprint = md5(publicKeyBlob).hexdigest() return fmt % (self.storeID, fingerprint) def getFactory(self): """ Create an L{SSHFactory} which allows access to Mantissa accounts. """ privateKey = Key.fromString(data=self.hostKey) public = privateKey.public() factory = SSHFactory() factory.publicKeys = {'ssh-rsa': public} factory.privateKeys = {'ssh-rsa': privateKey} factory.portal = Portal(IRealm(self.store), [ICredentialsChecker(self.store)]) return factory def rotate(self): """ Generate a new host key pair. """ self.hostKey = _generate()
class Secret(item.Item): """Some secret stored entropy for a user. Used to randomize exercises specific to the user. This exists for two reasons: - Allowing randomizations for a particular user to be consistent - Preventing users from requesting arbitrary amounts of random data """ user = attributes.reference(allowNone=False, indexed=True) entropy = attributes.bytes(defaultFactory=lambda: os.urandom(256 // 8)) @classmethod def forUser(cls, user): """Finds or creates a Secret for this user. """ return user.store.findOrCreate(cls, user=user)
return result == dspam.DSR_ISSPAM, conf def train(self, spam, item): dspam.trainMessageFromError( self.lib, self.username, self._homePath().path.encode('ascii'), item.impl.source.open().read(), spam and dspam.DSR_ISSPAM or dspam.DSR_ISINNOCENT) def forgetTraining(self): p = self._homePath() if p.exists(): p.remove() item.declareLegacyItem(DSPAMFilter.typeName, 1, dict( globalPath=attributes.bytes(), installedOn=attributes.reference())) def _dspamFilter1to2(old): df = old.upgradeVersion(DSPAMFilter.typeName, 1, 2, globalPath=old.globalPath, filter=old.store.findOrCreate(Filter)) return df registerUpgrader(_dspamFilter1to2, DSPAMFilter.typeName, 1, 2) class SpambayesFilter(item.Item): """ Spambayes-based L{iquotient.IHamFilter} powerup. """ implements(iquotient.IHamFilter) schemaVersion = 2
powerup, it will still be found as one one more time and this method will be called on it. """ def pop3Listener1to2(old): p3l = old.upgradeVersion(POP3Listener.typeName, 1, 2) p3l.userbase = old.store.findOrCreate(LoginSystem) return p3l registerUpgrader(pop3Listener1to2, POP3Listener.typeName, 1, 2) declareLegacyItem( POP3Listener.typeName, 2, dict(portNumber=integer(default=6110), securePortNumber=integer(default=0), certificateFile=bytes(default=None), userbase=reference(doc="dependsOn(LoginSystem)"))) def pop3listener2to3(oldPOP3): """ Create TCPPort and SSLPort items as appropriate. """ newPOP3 = oldPOP3.upgradeVersion( POP3Listener.typeName, 2, 3, userbase=oldPOP3.userbase, certificateFile=oldPOP3.certificateFile) if oldPOP3.portNumber is not None: port = TCPPort(store=newPOP3.store, portNumber=oldPOP3.portNumber, factory=newPOP3) installOn(port, newPOP3.store)
uac._doCall(partyA[1], fromName="Divmod") def sipServer1to2(old): ss = old.upgradeVersion(old.typeName, 1, 2) ss.portno = old.portno ss.pstn = old.pstn ss.userbase = old.store.findOrCreate(LoginSystem) return ss registerUpgrader(sipServer1to2, SIPServer.typeName, 1, 2) declareLegacyItem( SIPServer.typeName, 2, dict(portno=integer(), pstn=bytes(), scheduler=reference(), userbase=reference())) def sipServer2to3(old): ss = old.upgradeVersion(old.typeName, 2, 3) ss.portno = old.portno ss.pstn = old.pstn ss.userbase = old.userbase return ss registerUpgrader(sipServer2to3, SIPServer.typeName, 2, 3) class Registration(Item): typename = "sine_registration" schemaVersion = 1
if self.debug: self.factory = policies.TrafficLoggingFactory(self.factory, 'smtp') return self.factory # GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG def setServiceParent(self, parent): pass item.declareLegacyItem(typeName=MailTransferAgent.typeName, schemaVersion=2, attributes=dict(messageCount=attributes.integer(), installedOn=attributes.reference(), portNumber=attributes.integer(), securePortNumber=attributes.integer(), certificateFile=attributes.bytes(), domain=attributes.bytes())) def upgradeMailTransferAgent1to2(oldMTA): """ MailTransferAgent has been replaced with MailDeliveryAgent on B{user stores}. Delete it from user stores and create a MailDelivery agent there, but leave it alone on the site store. """ loginSystem = oldMTA.store.findUnique(userbase.LoginSystem, default=None) if loginSystem is not None: newMTA = oldMTA.upgradeVersion( 'mantissa_mta', 1, 2, messageCount=oldMTA.messageCount, installedOn=oldMTA.installedOn, portNumber=oldMTA.portNumber,
def test_bytes(self): self._test_typeFor(attributes.bytes(), amp.String)
store=site.store, portNumber=oldSite.securePortNumber, certificatePath=newCertPath, factory=site) installOn(port, site.store) newSite.deleteFromStore() declareLegacyItem( WebSite.typeName, 1, dict( hitCount = integer(default=0), installedOn = reference(), portNumber = integer(default=0), securePortNumber = integer(default=0), certificateFile = bytes(default=None))) def upgradeWebSite1To6(oldSite): return _makeSiteConfiguration(1, oldSite, False) upgrade.registerUpgrader(upgradeWebSite1To6, 'mantissa_web_powerup', 1, 6) declareLegacyItem( WebSite.typeName, 2, dict( hitCount = integer(default=0), installedOn = reference(), portNumber = integer(default=0), securePortNumber = integer(default=0), certificateFile = bytes(default=None), httpLog = bytes(default=None))) def upgradeWebSite2to6(oldSite):
contact = sip.IContact(self.store) def regged(_): return defer.succeed(None) def unregged(e): self.uas.dialogs = dialogs return self.uas return defer.maybeDeferred(contact.getRegistrationInfo, sip.parseAddress(msg.headers["from"][0])[1]).addCallbacks(regged, unregged) else: return defer.succeed(None) def localElementByName(self, n): for name, domain in userbase.getAccountNames(self.store, protocol=u'sip'): #if we got here, we have a SIP account... return useragent.ICallControllerFactory(self.store) item.declareLegacyItem(VoicemailDispatcher.typeName, 1, dict( localHost=bytes(), installedOn=reference())) def _voicemailDispatcher1to2(old): df = old.upgradeVersion(VoicemailDispatcher.typeName, 1, 2, localHost=old.localHost, voicemailUser=old.store.findOrCreate( AnonConfessionUser)) return df registerUpgrader(_voicemailDispatcher1to2, VoicemailDispatcher.typeName, 1, 2)