class EmailAddressExtract(SimpleExtractMixin, Item): typeName = 'quotient_email_address_extract' schemaVersion = 2 start = attributes.integer() end = attributes.integer() text = attributes.text(indexed=True) message = attributes.reference() part = attributes.reference() timestamp = attributes.timestamp() person = attributes.reference() regex = re.compile(ur'[\w\-\.]+@(?:[a-z0-9-]+\.)+[a-z]+', re.UNICODE | re.IGNORECASE) def worthStoring(message, extractedText): return not message.sender == extractedText worthStoring = staticmethod(worthStoring) def asStan(self): return tags.b[self.text]
class _ListItem(Item): typeName = 'list_item' schemaVersion = 1 _index = integer() _value = reference() _container = reference()
class Garment(item.Item, Enhancement): implements(iimaginary.IClothing, iimaginary.IDescriptionContributor) powerupInterfaces = (iimaginary.IClothing, iimaginary.IDescriptionContributor) thing = attributes.reference() # templated / constant stuff garmentSlots = attributes.textlist(allowNone=False) bulk = attributes.integer(allowNone=False, default=1) garmentDescription = attributes.text(doc=""" Description of this as an individual garment. """, allowNone=False) # transient / mutable stuff wearer = attributes.reference() wearLevel = attributes.integer(default=0) def conceptualize(self): return language.ExpressString(u'This can be worn.') def expressTo(self, observer): """ Describe the garment as it looks when it is worn. The garment's normal description is C{self.thing.description} or somesuch. """ return self.garmentDescription
class BearBlindness(item.Item, Enhancement): """ An enhancement for an actor which causes that actor to become unable to see bears. (This could be installed on something other than an actor, which would cause all bears on the other side of whatever link it was to become invisible to all.) """ powerupInterfaces = interfaces thing = attributes.reference(""" This is a reference to a Thing which is blind to bears. """) bear = attributes.reference(""" This is a reference to a Thing which is the one and only bear in the universe, which you cannot see. THERE CAN ONLY BE ONE. """) def annotationsFor(self, link, idea): """ Yield an annotation for all links which causes bears on the opposite side of you to be invisible to you. """ yield BearsHiddenBeyondThisLink(bear=self.bear)
class Header(item.Item): """ Database resident representation of a MIME header. """ typeName = 'quotient_mime_header' schemaVersion = 1 message = attributes.reference( "A reference to the stored top-level L{xquotient.exmess.Message} " "object to which this header pertains.", reftype=exmess.Message, whenDeleted=attributes.reference.CASCADE) part = attributes.reference( "A reference to the stored MIME part object to which this header " "directly pertains.") name = attributes.text("The name of this header. What it is called.", allowNone=False) value = attributes.text("The decoded value of this header.", allowNone=False) index = attributes.integer("The position of this header within a part.", indexed=True, allowNone=False) # This compound index matches the getHeader[s] query and is critical for # interactive performance. attributes.compoundIndex(part, name)
class InventoryEntry(ActivateHelper, Item): typeName = 'test_app_inv' schemaVersion = 1 owner = reference() owned = reference() activated = inmemory()
class Tether(Item, Enhancement): """ I am a force that binds two objects together. Right now this force isn't symmetric; the idea is that the thing that we are tethered 'to' is immovable for some other reason. This is why we're in the example rather than a real robust piece of game-library functionality in imaginary proper. The C{thing} that we are installed on is prevented from moving more than a certain distance away from the thing it is tethered C{to}. This is accomplished by preventing movement of the object's container; i.e. if you pick up a ball that is tied to the ground, you can't move until you drop it. """ thing = reference(reftype=Thing, whenDeleted=reference.CASCADE, allowNone=False) # XXX 'thing' and 'to' should be treated more consistently, or at least the # differences between them explained officially. to = reference(reftype=Thing, whenDeleted=reference.CASCADE, allowNone=False) implements(IMovementRestriction) powerupInterfaces = [IMovementRestriction] def movementImminent(self, movee, destination): """ The object which is tethered is trying to move somewhere. If it has an IActor, assume that it's a player trying to move on its own, and emit an appropriate message. Otherwise, assume that it is moving *to* an actor, and install a L{MovementBlocker} on that actor. """ # There isn't enough information provided to moveTo just yet; we need # to know who is doing the moving. In the meanwhile, if you have an # actor, we'll assume you're a player. if IActor(movee, None) is not None: raise ActionFailure( ThatDoesntWork(actor=self.thing, actorMessage=[ u"You can't move, you're tied to ", self.to, "." ], otherMessage=[self.thing, u' struggles.'])) MovementBlocker.destroyFor(self.thing.location) if self.to != destination: MovementBlocker.createFor(destination, tether=self) return False
class File(item.Item): typeName = 'quotient_file' schemaVersion = 1 type = attributes.text(allowNone=False) body = attributes.path(allowNone=False) name = attributes.text(allowNone=False) message = attributes.reference() cabinet = attributes.reference(allowNone=False)
class Image(Item): typeName = 'quotient_image' schemaVersion = 2 part = attributes.reference() thumbnailPath = attributes.path() mimeType = attributes.text() imageSet = attributes.reference() message = attributes.reference()
class PublicWeb(item.Item, website.PrefixURLMixin): """ Fixture for site-wide public-facing content. I implement ISiteRootPlugin and use PrefixURLMixin; see the documentation for each of those for a detailed explanation of my usage. I wrap a L{websharing.SharingIndex} around an app store. I am installed in an app store when it is created. """ implements(ISiteRootPlugin, ixmantissa.ISessionlessSiteRootPlugin) typeName = 'mantissa_public_web' schemaVersion = 3 prefixURL = attributes.text(doc=""" The prefix of the URL where objects represented by this fixture will appear. For the front page this is u'', for other pages it is their respective URLs. """, allowNone=False) application = attributes.reference(doc=""" A L{SubStore} for an application store. """, allowNone=False) installedOn = attributes.reference(doc=""" """) sessioned = attributes.boolean(doc=""" Will this resource be provided to clients with a session? Defaults to False. """, default=False) sessionless = attributes.boolean(doc=""" Will this resource be provided without a session to clients without a session? Defaults to False. """, default=False) def createResource(self): """ When invoked by L{PrefixURLMixin}, return a L{websharing.SharingIndex} for my application. """ pp = ixmantissa.IPublicPage(self.application, None) if pp is not None: warn( "Use the sharing system to provide public pages, not IPublicPage", category=DeprecationWarning, stacklevel=2) return pp.getResource() return SharingIndex(self.application.open())
class PersistedMailer(item.Item): """ A persisted mailer. """ endpoint = attributes.reference() credentials = attributes.reference() indirected = attributes.inmemory() def activate(self): endpoint = self.endpoint.instantiate() self.indirected = mailer.Mailer(endpoint, self.credentials)
class FileMeta(item.Item): """A file that has been uploaded.""" schemaVersion = 1 data = A.reference(doc="The FileData item that holds this file's data") thumbnail = A.reference( doc="The FileData item that holds the image thumbnail, if any") filename = A.text(doc="The basename of the file") mimeType = A.text(doc="The mime-type of the file") md5 = A.text(doc="The md5 hash of the file data") user = A.reference(doc="The User item who uploaded (owns?) the file") width = A.integer(doc="The width in pixels of the image, if an image") height = A.integer(doc="The height in pixels of the image, if an image")
class Book(Item): typeName = 'book' schemaVersion = 1 title = text() author = text() isbn = text() pages = integer() datePublished = timestamp() lentTo = reference() library = reference()
class Chair(Enhancement, Item): """ A chair is a thing you can sit in. """ implements(ISittable, IMovementRestriction) powerupInterfaces = [ISittable] thing = reference() container = reference() def movementImminent(self, movee, destination): """ A player tried to move while they were seated. Prevent them from doing so, noting that they must stand first. (Assume the player was trying to move themselves, although there's no way to know currently.) """ raise ActionFailure( ThatDoesntWork( actor=movee, actorMessage=u"You can't do that while sitting down.")) def applyEnhancement(self): """ Apply this enhancement to this L{Chair}'s thing, creating a L{Container} to hold the seated player, if necessary. """ super(Chair, self).applyEnhancement() container = IContainer(self.thing, None) if container is None: container = Container.createFor(self.thing, capacity=300) self.container = container def seat(self, player): """ The player sat down on this chair; place them into it and prevent them from moving elsewhere until they stand up. """ player.thing.moveTo(self.container) player.thing.powerUp(self, IMovementRestriction) def unseat(self, player): """ The player stood up; remove them from this chair. """ player.thing.powerDown(self, IMovementRestriction) player.thing.moveTo(self.container.thing.location)
class _IndexerInputSource(item.Item): """ Tracks L{IBatchProcessor}s which have had an indexer added to them as a listener. """ indexer = attributes.reference(doc=""" The indexer item with which this input source is associated. """, whenDeleted=attributes.reference.CASCADE) source = attributes.reference(doc=""" The L{IBatchProcessor} which acts as the input source. """, whenDeleted=attributes.reference.CASCADE)
class FlavorPermission(Item): """ I am associated with a top-level Blurb and specify the associated roles for all of its children. For example: if there is a top-level blurb X with the BLOG flavor, there might be a FlavorPermission associated with it that makes reference to a 'writer staff' role for the BLOG_POST flavor, which has permissions IViewable, ICommentable - but conspicuously omits IEditable. That collection of properties means that when posts are made on blog X they will be viewable and commentable by the writer staff, but not editable by them. A separate flavor permission might deal with the editorial staff. Each permission is a zope Interface object. """ # XXX "FlavorPermission" is a terrible name for this class, but I hope this # docstring is explanitory enough that someone else might help me think of # a better one. at any rate, it's *mainly* an implementation detail, # although there does need to be some UI for managing this. typeName = 'hyperbola_flavor_permission' flavor = text(doc=""" The 'flavor' attribute is the name of the flavor of a potential child of the blurb this permission applies to. For example, if this permission controls comments on a blurb that has the flavor FLAVOR.BLOG_POST, this attribute will be FLAVOR.BLOG_COMMENT. """) blurb = reference(doc=""" The 'blurb' attribute is a reference to a L{Blurb}, whose children this object is controlling the permissions of. """) role = reference(doc=""" The 'role' attribute is a reference to a L{Role}, which is the role that the permissions will be shared to. """) # XXX TODO -- right now sharing has a list of interfaces, axiom.dependecy # has a list of typeclasses, and hyperbola has this list of interfaces that # are slightly different than sharing's. we should implement a "list of # interface objects" attribute, and a "list of typeName" attribute, so the # logic around this can be more abstract. permissions = textlist(doc=""" A list of the names of Python interfaces that will be exposed to this permission's role. """)
class Exit(item.Item): fromLocation = attributes.reference( doc=""" Where this exit leads from. """, allowNone=False, whenDeleted=attributes.reference.CASCADE, reftype=Thing) toLocation = attributes.reference(doc=""" Where this exit leads to. """, allowNone=False, whenDeleted=attributes.reference.CASCADE, reftype=Thing) name = attributes.text(doc=""" What this exit is called/which direction it is in. """, allowNone=False) sibling = attributes.reference(doc=""" The reverse exit object, if one exists. """) def link(cls, a, b, forwardName, backwardName=None): if backwardName is None: backwardName = OPPOSITE_DIRECTIONS[forwardName] me = cls(store=a.store, fromLocation=a, toLocation=b, name=forwardName) him = cls(store=b.store, fromLocation=b, toLocation=a, name=backwardName) me.sibling = him him.sibling = me link = classmethod(link) def destroy(self): if self.sibling is not None: self.sibling.deleteFromStore() self.deleteFromStore() # NOTHING def conceptualize(self): return language.ExpressList( [u'the exit to ', language.Noun(self.toLocation).nounPhrase()])
class ImaginaryWorld(Item): """ An instance of L{ImaginaryWorld} is a handle onto an Imaginary simulation. All connected users are tracked on this item, and new characters are created via the L{create} method. """ origin = reference(doc=""" The L{Thing} where all new characters will be placed. It will be created in the first call to L{create} if it is not provided. """, reftype=Thing) connected = inmemory(doc=""" A C{list} of L{Thing} instances which correspond to the users currently connected. """) def activate(self): self.connected = [] def create(self, name, **kw): """ Make a new character L{Thing} with the given name and return it. @type name: C{unicode} @rtype: L{Thing} """ if self.origin is None: self.origin = Thing(store=self.store, name=u"The Place") Container.createFor(self.origin, capacity=1000) character = Thing(store=self.store, weight=100, name=name, proper=True, **kw) Container.createFor(character, capacity=10) Actor.createFor(character) # Unfortunately, world -> garments -> creation -> action -> # world. See #2906. -exarkun from imaginary.garments import Wearer Wearer.createFor(character) character.moveTo( self.origin, lambda player: MovementArrivalEvent( thing=player, origin=None, direction=None)) return character def loggedIn(self, character): """ Indicate that a character is now participating in the simulation. """ self.connected.append(character) def loggedOut(self, character): """ Indicate that a character is no longer participating in the simulation. """ self.connected.remove(character)
class Container(item.Item, Containment, _Enhancement): """ A generic L{_Enhancement} that implements containment. """ contentsTemplate = attributes.text( doc=""" Define how the contents of this container are presented to observers. Certain substrings will be given special treatment. @see: L{imaginary.language.ConceptTemplate} """, allowNone=True, default=None) capacity = attributes.integer( doc=""" Units of weight which can be contained. """, allowNone=False, default=1) closed = attributes.boolean( doc=""" Indicates whether the container is currently closed or open. """, allowNone=False, default=False) thing = attributes.reference( doc=""" The object this container powers up. """)
def dependsOn(itemType, itemCustomizer=None, doc='', indexed=True, whenDeleted=reference.NULLIFY): """ This function behaves like L{axiom.attributes.reference} but with an extra behaviour: when this item is installed (via L{axiom.dependency.installOn} on a target item, the type named here will be instantiated and installed on the target as well. For example:: class Foo(Item): counter = integer() thingIDependOn = dependsOn(Baz, lambda baz: baz.setup()) @param itemType: The Item class to instantiate and install. @param itemCustomizer: A callable that accepts the item installed as a dependency as its first argument. It will be called only if an item is created to satisfy this dependency. @return: An L{axiom.attributes.reference} instance. """ frame = sys._getframe(1) locals = frame.f_locals # Try to make sure we were called from a class def. if (locals is frame.f_globals) or ('__module__' not in locals): raise TypeError("dependsOn can be used only from a class definition.") ref = reference(reftype=itemType, doc=doc, indexed=indexed, allowNone=True, whenDeleted=whenDeleted) if "__dependsOn_advice_data__" not in locals: addClassAdvisor(_dependsOn_advice) locals.setdefault('__dependsOn_advice_data__', []).append( (itemType, itemCustomizer, ref)) return ref
self._deliverAnswer(answer) nextmsg = self.store.findFirst(_QueuedMessage, default=None) if nextmsg is not None: delay = _RETRANSMIT_DELAY else: nextanswer = self.store.findFirst(_AlreadyAnswered, default=None) if nextanswer is not None: delay = _RETRANSMIT_DELAY if delay is not None: return IScheduler(self.store).now() + timedelta(seconds=delay) declareLegacyItem( MessageQueue.typeName, 1, dict(messageCounter=integer(default=0, allowNone=False), scheduler=reference())) def upgradeMessageQueue1to2(old): """ Copy the C{messageCounter} attribute to the upgraded MessageQueue. """ return old.upgradeVersion( MessageQueue.typeName, 1, 2, messageCounter=old.messageCounter) registerUpgrader(upgradeMessageQueue1to2, MessageQueue.typeName, 1, 2) #### High-level convenience API #### AMP_MESSAGE_TYPE = u'mantissa.amp.message' AMP_ANSWER_TYPE = u'mantissa.amp.answer'
def listen(self): if self._listen is not None: _listen = self._listen else: from twisted.internet import reactor _listen = reactor.listenTCP return _listen(self.portNumber, self.factory.getFactory(), interface=self.interface.encode('ascii')) declareLegacyItem( typeName=normalize(qual(TCPPort)), schemaVersion=1, attributes=dict( portNumber=integer(), factory=reference(), parent=inmemory(), _listen=inmemory(), listeningPort=inmemory())) registerAttributeCopyingUpgrader(TCPPort, 1, 2) class SSLPort(PortMixin, Item): """ An Axiom Service Item which will bind a TCP port to a protocol factory when it is started. """ schemaVersion = 2
newCertPath = site.store.newFilePath('server.pem') oldCertPath.moveTo(newCertPath) port = SSLPort( 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),
def upgradeParentHook1to2(oldHook): """ Add the scheduler attribute to the given L{_SubSchedulerParentHook}. """ newHook = oldHook.upgradeVersion( oldHook.typeName, 1, 2, loginAccount=oldHook.loginAccount, scheduledAt=oldHook.scheduledAt, scheduler=oldHook.store.findFirst(Scheduler)) return newHook registerUpgrader(upgradeParentHook1to2, _SubSchedulerParentHook.typeName, 1, 2) declareLegacyItem( _SubSchedulerParentHook.typeName, 2, dict(loginAccount=reference(), scheduledAt=timestamp(default=None), scheduler=reference())) def upgradeParentHook2to3(old): """ Copy the C{loginAccount} attribute, but drop the others. """ return old.upgradeVersion( old.typeName, 2, 3, loginAccount=old.loginAccount) registerUpgrader(upgradeParentHook2to3, _SubSchedulerParentHook.typeName, 2, 3) declareLegacyItem( _SubSchedulerParentHook.typeName, 3,
# XXX This really should use in-database state, otherwise a restart in # the middle will muck things up. def go(): for msg in work: for f in filters: f.train(msg._spam, msg) yield None self.reclassify() return coiterate(go()) registerAttributeCopyingUpgrader(Filter, 1, 2) item.declareLegacyItem(Filter.typeName, 2, dict(installedOn = attributes.reference(), usePostiniScore = attributes.boolean(default=False,allowNone=False), postiniThreshhold = attributes.ieee754_double(default=0.03))) def _filter2to3(old): """ add dependencies as attributes, remove installedOn """ filter = old.upgradeVersion(old.typeName, 2, 3) s = old.store filter.usePostiniScore = old.usePostiniScore filter.postiniThreshhold = old.postiniThreshhold filter.messageSource = s.findOrCreate(MessageSource) filter.tiSource = s.findOrCreate(_TrainingInstructionSource)
def _declareLegacyIndexerItem(typeClass, version): item.declareLegacyItem(typeClass.typeName, version, dict(indexCount=attributes.integer(), installedOn=attributes.reference(), indexDirectory=attributes.text()))
registerUpgrader(sword2to3, 'test_app_sword', 2, 3) ####### DOUBLE-LEGACY UPGRADE SPECTACULAR !! ########### # declare legacy class. from axiom.item import declareLegacyItem declareLegacyItem(typeName = 'test_app_sword', schemaVersion = 2, attributes = dict(name=text(), damagePerHit=integer(), owner=reference(), activated=inmemory())) def upgradePlayerAndSword(oldplayer): newplayer = oldplayer.upgradeVersion('test_app_player', 1, 2) newplayer.name = oldplayer.name oldsword = oldplayer.sword newsword = oldsword.upgradeVersion('test_app_sword', 1, 3, name=oldsword.name, damagePerHit=oldsword.hurtfulness * 2) invent = InventoryEntry(store=newsword.store, owner=newplayer, owned=newsword)
registerAdapter(ExtractRenderer, EmailAddressExtract, IRenderer) registerExtractUpgrader1to2(EmailAddressExtract) extractTypes = {'url': URLExtract, 'phone number': PhoneNumberExtract, 'email address': EmailAddressExtract} class ExtractPowerup(Item): schemaVersion = 2 gallery = dependsOn(Gallery) thumbnailDisplayer = dependsOn(ThumbnailDisplayer) def installed(self): self.store.findUnique(mail.MessageSource).addReliableListener(self) def processItem(self, message): extractImages(message) for et in extractTypes.itervalues(): et.extract(message) declareLegacyItem(ExtractPowerup.typeName, 1, dict( installedOn = attributes.reference())) def _extractPowerup1to2(old): return old.upgradeVersion(ExtractPowerup.typeName, 1, 2, gallery=old.store.findOrCreate(Gallery), thumbnailDisplayer=old.store.findOrCreate(ThumbnailDisplayer)) registerUpgrader(_extractPowerup1to2, ExtractPowerup.typeName, 1, 2)
emailTemplate %= {'blurb': u'', 'subject': 'Welcome to a Generic Axiom Application!', 'linktext': "Click here to claim your 'generic axiom application' account"} return old.upgradeVersion('free_signup', 2, 3, prefixURL=old.prefixURL, booth=old.booth, benefactor=old.benefactor, emailTemplate=emailTemplate) upgrade.registerUpgrader(freeTicketSignup2To3, 'free_signup', 2, 3) declareLegacyItem(typeName='free_signup', schemaVersion=3, attributes=dict(prefixURL=text(), booth=reference(), benefactor=reference(), emailTemplate=text())) def freeTicketSignup3To4(old): return old.upgradeVersion('free_signup', 3, 4, prefixURL=old.prefixURL, booth=old.booth, benefactor=old.benefactor, emailTemplate=old.emailTemplate, prompt=u'Sign Up') upgrade.registerUpgrader(freeTicketSignup3To4, 'free_signup', 3, 4)
self.assertTrue(isinstance(t2, UpgradedItem)) class UpgradedItem(Item): """ A simple item which is the current version of L{nonUpgradedItem}. """ schemaVersion = 3 ref = reference() nonUpgradedItem = declareLegacyItem( UpgradedItem.typeName, 1, dict(ref=reference())) nonUpgradedItem2 = declareLegacyItem( UpgradedItem.typeName, 2, dict(ref=reference())) registerAttributeCopyingUpgrader(UpgradedItem, 1, 2) def item2to3(old): """ Upgrade an nonUpgradedItem to UpgradedItem """ return old.upgradeVersion(UpgradedItem.typeName, 2, 3, ref=old.ref)
# IPowerupIndirector def indirect(self, interface): """ Indirect the implementation of L{IWebViewer} to L{_AuthenticatedWebViewer}. """ if interface == IWebViewer: return _AuthenticatedWebViewer(self) return self PrivateApplicationV2 = declareLegacyItem(PrivateApplication.typeName, 2, dict( installedOn = reference(), preferredTheme = text(), hitCount = integer(default=0), privateKey = integer(), privateIndexPage = reference(), )) PrivateApplicationV3 = declareLegacyItem(PrivateApplication.typeName, 3, dict( preferredTheme=text(), hitCount=integer(default=0), privateKey=integer(), privateIndexPage=reference(), customizedPublicPage=reference("dependsOn(CustomizedPublicPage)"), authenticationApplication=reference("dependsOn(AuthenticationApplication)"), preferenceAggregator=reference("dependsOn(PreferenceAggregator)"), defaultPreferenceCollection=reference("dependsOn(DefaultPreferenceCollection)"),
""" Create the extra state tracking items necessary for efficiently determining distinct source addresses. """ newInbox = oldInbox.upgradeVersion( "quotient_inbox", 1, 2, installedOn=oldInbox.installedOn, uiComplexity=oldInbox.uiComplexity ) return newInbox registerUpgrader(upgradeInbox1to2, "quotient_inbox", 1, 2) declareLegacyItem( Inbox.typeName, 2, dict(installedOn=attributes.reference(), uiComplexity=attributes.integer(), catalog=attributes.reference()), ) registerAttributeCopyingUpgrader(Inbox, 2, 3) declareLegacyItem( Inbox.typeName, 3, dict( installedOn=attributes.reference(), catalog=attributes.reference(), uiComplexity=attributes.integer(), showMoreDetail=attributes.boolean(), ), )
pg = POP3Grabber( store=self.store, username=username, password=password, domain=domain, port=port, config=self, ssl=ssl) # DO IT *NOW* self.scheduler.schedule(pg, extime.Time()) # OR MAYBE A LITTLE LATER item.declareLegacyItem(GrabberConfiguration.typeName, 1, dict( paused=attributes.boolean(default=False), installedOn=attributes.reference())) def _grabberConfiguration1to2(old): new = old.upgradeVersion(GrabberConfiguration.typeName, 1, 2, paused=old.paused, privateApplication = old.store.findOrCreate(PrivateApplication), deliveryAgent = old.store.findOrCreate(DeliveryAgent)) return new registerUpgrader(_grabberConfiguration1to2, GrabberConfiguration.typeName, 1, 2) item.declareLegacyItem(GrabberConfiguration.typeName, 2, dict( paused=attributes.boolean(default=False), scheduler=attributes.reference(), privateApplication=attributes.reference(), deliveryAgent=attributes.reference(), ))
'LOGIN': imap4.LOGINCredentials, }, certOpts) 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,
def installed(self): self.indexer.addSource(self.messageSource) def count(self, term): raise NotImplementedError("No one should ever call count, I think.") def search(self, *a, **k): if 'sortAscending' not in k: k['sortAscending'] = False d = self.indexer.search(*a, **k) d.addCallback(_mailsearchui.SearchAggregatorFragment, self.store) return d declareLegacyItem(MessageSearchProvider.typeName, 1, dict( indexer=attributes.reference(), installedOn=attributes.reference())) def _messageSearchProvider1to2(old): new = old.upgradeVersion(MessageSearchProvider.typeName, 1, 2, indexer=old.indexer, messageSource=old.store.findUnique(mail.MessageSource)) return new registerUpgrader(_messageSearchProvider1to2, MessageSearchProvider.typeName, 1, 2) class QuotientBenefactor(Item): implements(ixmantissa.IBenefactor) typeName = 'quotient_benefactor' schemaVersion = 1
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) securePortNumber = oldPOP3.securePortNumber
def upgradeCompose1to2(oldComposer): """ Version 2 of the Composer powers up IMessageSender, which version 1 did not. Correct that here. """ newComposer = oldComposer.upgradeVersion( 'quotient_composer', 1, 2, installedOn=oldComposer.installedOn) newComposer.installedOn.powerUp( newComposer, iquotient.IMessageSender) return newComposer registerUpgrader(upgradeCompose1to2, 'quotient_composer', 1, 2) item.declareLegacyItem(Composer.typeName, 2, dict(installedOn=attributes.reference())) def composer2to3(old): """ Remove the L{Composer.fromAddress} attribute """ return old.upgradeVersion(old.typeName, 2, 3, installedOn=old.installedOn) registerUpgrader(composer2to3, Composer.typeName, 2, 3) item.declareLegacyItem(Composer.typeName, 3, dict(installedOn=attributes.reference()))
""" return None # IPowerupIndirector def indirect(self, interface): """ Indirect the implementation of L{IWebViewer} to L{_AnonymousWebViewer}. """ if interface == IWebViewer: return _AnonymousWebViewer(self.store) return super(AnonymousSite, self).indirect(interface) AnonymousSite1 = item.declareLegacyItem( 'xmantissa_publicweb_anonymoussite', 1, dict( loginSystem=attributes.reference(), )) def _installV2Powerups(anonymousSite): """ Install the given L{AnonymousSite} for the powerup interfaces it was given in version 2. """ anonymousSite.store.powerUp(anonymousSite, IWebViewer) anonymousSite.store.powerUp(anonymousSite, IMantissaSite) upgrade.registerAttributeCopyingUpgrader(AnonymousSite, 1, 2, _installV2Powerups)
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 parent = reference()
####### DOUBLE-LEGACY UPGRADE SPECTACULAR !! ########### # declare legacy class. from axiom.item import declareLegacyItem declareLegacyItem(typeName="test_app_player", schemaVersion=2, attributes=dict(name=text(allowNone=True))) registerAttributeCopyingUpgrader(Adventurer, 2, 3) declareLegacyItem( typeName="test_app_sword", schemaVersion=2, attributes=dict(name=text(), damagePerHit=integer(), owner=reference(), activated=inmemory()), ) def upgradePlayerAndSword(oldplayer): newplayer = oldplayer.upgradeVersion("test_app_player", 1, 2) newplayer.name = oldplayer.name oldsword = oldplayer.sword newsword = oldsword.upgradeVersion( "test_app_sword", 1, 2, name=oldsword.name, damagePerHit=oldsword.hurtfulness * 2, owner=newplayer ) return newplayer, newsword
nextTry = datetime.timedelta(seconds=self.RETRANS_TIMES[self.tries]) sch.schedule(self, extime.Time() + nextTry) if not self.running: self.running = True self.tries += 1 d = self.sendmail() d.addCallback(self.mailSent, sch) d.addErrback(self.failureSending, sch) d.addErrback(log.err) item.declareLegacyItem(DeliveryToAddress.typeName, 2, dict(composer = attributes.reference(), message = attributes.reference(), fromAddress = attributes.reference(), toAddress = attributes.text(), tries = attributes.integer(default=0))) def deliveryToAddress2to3(old): delivery = MessageDelivery(composer=old.composer, message=old.message, store=old.store) new = old.upgradeVersion(old.typeName, 2, 3, delivery=delivery, message=old.message, fromAddress=old.fromAddress,