コード例 #1
0
ファイル: website.py プロジェクト: jonathanj/mantissa
class StaticSite(PrefixURLMixin, Item):
    implements(ISessionlessSiteRootPlugin,     # implements both so that it
               ISiteRootPlugin)                # works in both super and sub
                                               # stores.
    typeName = 'static_web_site'
    schemaVersion = 2

    prefixURL = text()
    staticContentPath = text()

    sessioned = boolean(default=False)
    sessionless = boolean(default=True)

    def __str__(self):
        return '/%s => file(%s)' % (self.prefixURL, self.staticContentPath)

    def createResource(self):
        return File(self.staticContentPath)

    def installSite(self):
        """
        Not using the dependency system for this class because it's only
        installed via the command line, and multiple instances can be
        installed.
        """
        for iface, priority in self.__getPowerupInterfaces__([]):
            self.store.powerUp(self, iface, priority)
コード例 #2
0
ファイル: userbase.py プロジェクト: DalavanCloud/axiom-1
class LoginMethod(Item):
    typeName = 'login_method'
    schemaVersion = 2

    localpart = text(doc="""
    A local-part of my user's identifier.
    """,
                     indexed=True,
                     allowNone=False)

    domain = text(doc="""
    The domain part of my user's identifier. [XXX See TODO below]
    May be None (generally for "system" users).
    """,
                  indexed=True)

    internal = boolean(doc="""
    Flag indicating whether this is a method maintained by this server, or if
    it represents an external contact mechanism (such as a third-party email
    provider)
    """,
                       allowNone=False)

    protocol = text(indexed=True, allowNone=False)
    account = reference(doc="""
    A reference to the LoginAccount for which this is a login method.
    """,
                        allowNone=False)

    verified = boolean(indexed=True, allowNone=False)
コード例 #3
0
ファイル: website.py プロジェクト: jonathanj/mantissa
class StaticRedirect(Item, PrefixURLMixin):
    implements(inevow.IResource,
               ISessionlessSiteRootPlugin,
               ISiteRootPlugin)

    schemaVersion = 2
    typeName = 'web_static_redirect'

    targetURL = text(allowNone=False)

    prefixURL = text(allowNone=False)

    sessioned = boolean(default=True)
    sessionless = boolean(default=True)

    def __str__(self):
        return '/%s => url(%s)' % (self.prefixURL, self.targetURL)

    def locateChild(self, ctx, segments):
        return self, ()

    def renderHTTP(self, ctx):
        return URL.fromContext(ctx).click(self.targetURL)

    def createResource(self):
        return self
コード例 #4
0
class TestFilter(Item):
    """
    Ultra stupid classifier.  Always classifies every message as whatever you
    tell it to at creation time.
    """
    implements(IHamFilter)

    powerupInterfaces = (IHamFilter, )

    result = boolean(default=False, allowNone=False)
    test = inmemory()

    forgotTraining = boolean(default=False)

    trainCount = integer(default=0)

    def classify(self, item):
        return self.result, 0

    def forgetTraining(self):
        self.forgotTraining = True

    def train(self, spam, message):
        self.trainCount += 1
        # We're only ever called in the context of retraining, so let's make
        # sure that what we're being told matches the message that we've been
        # given.
        if spam:
            self.test.failUnless(message.hasStatus(SPAM_STATUS))
        else:
            self.test.failUnless(message.hasStatus(CLEAN_STATUS))
        self.test.failUnless(message.hasStatus(TRAINED_STATUS))
コード例 #5
0
ファイル: publicweb.py プロジェクト: jonathanj/mantissa
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())
コード例 #6
0
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.
        """)
コード例 #7
0
class GrabberConfiguration(item.Item):
    """
    Manages the creation, operation, and destruction of grabbers
    (items which retrieve information from remote sources).
    """
    schemaVersion = 3

    paused = attributes.boolean(doc="""
    Flag indicating whether grabbers created by this Item will be
    allowed to run.
    """,
                                default=False)

    privateApplication = dependsOn(PrivateApplication)
    deliveryAgent = dependsOn(DeliveryAgent)

    def addGrabber(self, username, password, domain, ssl):
        # DO IT
        if ssl:
            port = 995
        else:
            port = 110

        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())
コード例 #8
0
ファイル: donate.py プロジェクト: jsza/bdm
class Donator(Item):
    implements(IDonator)

    steamID = text(allowNone=True, doc=u'64-bit SteamID')
    anonymous = boolean(allowNone=False, doc=u'Display the user publicly?')
    totalAmount = point2decimal(allowNone=False, default=Decimal('0'))

    @property
    def donations(self):
        return self.powerupsFor(IDonation)


    def getDonationAmount(self):
        return Decimal(sum(donation.amount for donation in self.donations))


    def addDonation(self, amount, paypalID):
        donation = Donation(store=self.store, amount=amount, paypalID=paypalID)
        donation.installOn(self)
        return donation


    def calculateTotal(self):
        """
        Calls L{getDonationAmount} and sets L{totalAmount} to the result.
        """
        self.totalAmount = self.getDonationAmount()
コード例 #9
0
class StubStoredMessageAndImplAndSource(item.Item):
    """
    Mock several objects at once:

    1. An L{exmess.Message}

    2. The 'impl' attribute of that message, typically a L{mimestore.Part}

    3. The message file returned from the C{open} method of C{impl}.
       XXX: This returns something that doesn't conform to the file protocol,
       but the code that triggers the usage of that protocol isn't triggered
       by the following tests.
    """

    calledStartedSending = attributes.boolean(default=False)
    impl = property(lambda s: s)
    source = property(lambda self: self._source or FilePath(__file__))
    _source = None
    headers = attributes.inmemory()
    statuses = attributes.inmemory()

    def open(self):
        return "HI DUDE"

    def startedSending(self):
        self.calledStartedSending = True

    def addStatus(self, status):
        if not hasattr(self, 'statuses'):
            self.statuses = [status]
        else:
            self.statuses.append(status)
コード例 #10
0
ファイル: test_axiomatic.py プロジェクト: perkinslr/axiom-py3
class RecorderService(Item):
    """
    Minimal L{IService} implementation which remembers if it was ever started.
    This is used by tests to make sure services get started when they should
    be.
    """
    implements(IService)

    started = boolean(doc="""
        A flag which is initially false and set to true once C{startService} is
        called.
        """,
                      default=False)

    name = "recorder"

    def setServiceParent(self, parent):
        """
        Do the standard Axiom thing to make sure this service becomes a child
        of the top-level store service.
        """
        IServiceCollection(parent).addService(self)

    def startService(self):
        """
        Remember that this method was called.
        """
        self.started = True

    def stopService(self):
        """
コード例 #11
0
class DummyService(Item):
    """
    Service which does nothing but mark itself as run, if it's ever run.  After
    the upgrader it should not be run.
    """
    typeName = 'substore_service_upgrade_stub_service'
    everStarted = boolean(default=False)
    implements(IService)

    name = property(lambda: "sucky-service")
    running = property(lambda: False)

    def setName(self, name):
        pass

    def setServiceParent(self, parent):
        pass

    def disownServiceParent(self):
        pass

    def startService(self):
        self.everStarted = True

    def stopService(self):
        pass

    def privilegedStartService(self):
        pass
コード例 #12
0
ファイル: quiche.py プロジェクト: zeeneddie/imaginary
class VendingMachine(item.Item, objects.Containment, Enhancement):
    implements(iimaginary.IContainer)

    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=True)

    thing = attributes.reference(doc="""
    The object this container powers up.
    """)

    _currencyCounter = attributes.integer(doc="""
    The number of coins which have been added to this vending machine since it
    last ejected an item.
    """, allowNone=False, default=0)

    def coinAdded(self, coin):
        """
        Called when a coin is added to this thing.

        @type coin: C{ICoin} provider
        """
        self._currencyCounter += 1
        if self._currencyCounter >= 5 and self.getContents():
            self._currencyCounter = 0
            try:
                obj = iter(self.getContents()).next()
            except StopIteration:
                evt = events.Success(
                    actor=self.thing,
                    target=obj,
                    otherMessage=language.Sentence([self.thing, " thumps loudly."]))
            else:
                evt = events.Success(
                    actor=self.thing,
                    target=obj,
                    otherMessage=language.Sentence([
                        language.Noun(self.thing).definiteNounPhrase(),
                        " thumps loudly and spits out ", obj,
                        " onto the ground."]))
                state = self.closed
                self.closed = False
                try:
                    obj.moveTo(self.thing.location)
                finally:
                    self.closed = state
            evt.broadcast()


    def add(self, obj):
        coin = ICoin(obj, None)
        if coin is not None:
            self.coinAdded(coin)
        else:
            return super(VendingMachine, self).add(obj)
コード例 #13
0
class MessageInfo(item.Item):
    typeName = 'quotient_pop3_message'
    schemaVersion = 2

    localPop3UID = attributes.bytes()
    localPop3Deleted = attributes.boolean(indexed=True)

    message = attributes.reference()
コード例 #14
0
class NullRunnable(Item):
    """
    Runnable item which does nothing.
    """
    ran = boolean(default=False)

    def run(self):
        pass
コード例 #15
0
ファイル: test_substore.py プロジェクト: DalavanCloud/axiom-1
class YouShouldStartThis(Item, Service):
    parent = inmemory()
    running = inmemory()
    name = inmemory()

    started = boolean(default=False)

    def startService(self):
        self.started = True
コード例 #16
0
class _DependencyConnector(Item):
    """
    I am a connector between installed items and their targets.
    """
    installee = reference(doc="The item installed.")
    target = reference(doc="The item installed upon.")
    explicitlyInstalled = boolean(doc="Whether this item was installed"
                                  "explicitly (and thus whether or not it"
                                  "should be automatically uninstalled when"
                                  "nothing depends on it)")
コード例 #17
0
class FakeApplication(Item):
    """
    Fake implementation of an application installed by an offering.
    """
    implements(IPublicPage)

    index = boolean(doc="""
    Flag indicating whether this application wants to be included on the front
    page.
    """)
コード例 #18
0
class Recording(Item):
    """
    A certain recording.
    """

    created = timestamp()
    caller_id = text()
    filename = text()
    duration = integer()  # in frames
    use_in_ending = boolean()
    user_recording = boolean()

    def filenameAsPath(self, app):
        """
        Return absolute filename without extension
        """
        return app.recordingsPath.child(self.filename).path

    def filenameAsURL(self):
        """
        Return filename as MP3 url
        """
        return "/recordings/" + self.filename + ".mp3"

    def filenameAsAsterisk(self):
        return "weareforests-recordings/%s" % self.filename

    @staticmethod
    def userRecordingFilename(app):
        """
        Generate a new filename for a user recording.
        """
        base = "user-%d" % time.time()
        fn = base
        f = app.recordingsPath.child(fn)
        i = 1
        while f.exists():
            fn = base + ("-%d" % i)
            f = app.recordingsPath.child(fn)
            i += 1
        return fn
コード例 #19
0
class ScheduleCallingItem(Item):
    """
    Item which invokes C{schedule} on its store's L{IScheduler} from its own
    C{run} method.
    """

    ran = boolean(default=False)
    rescheduleFor = timestamp()

    def run(self):
        scheduler = IScheduler(self.store)
        scheduler.schedule(self, self.rescheduleFor)
        self.ran = True
コード例 #20
0
ファイル: Database.py プロジェクト: calston/tums
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()
コード例 #21
0
ファイル: test_xatop.py プロジェクト: DalavanCloud/axiom-1
class TestItem(item.Item):
    schemaVersion = 1
    typeName = 'TestItem'
    foo = attributes.integer(indexed=True, default=10)
    bar = attributes.text()
    baz = attributes.timestamp()
    other = attributes.reference()
    booleanT = attributes.boolean()
    booleanF = attributes.boolean()

    activated = attributes.inmemory()
    checkactive = attributes.inmemory()
    checked = attributes.inmemory()

    myStore = attributes.reference()

    attributes.compoundIndex(bar, baz)

    def activate(self):
        self.activated = True
        if getattr(self, 'checkactive', False):
            assert isinstance(self.other, TestItem), repr(self.other)
            assert self.other != self, repr(self.other)
            self.checked = True
コード例 #22
0
class CustomizedEnhancement(Item, Enhancement):
    """
    An enhancement which has customized apply / remove behavior.
    """

    thing = reference(allowNone=False)
    applied = boolean()
    removed = boolean()

    def applyEnhancement(self):
        """
        The enhancement is about to be applied; modify our attributes to
        account for that.
        """
        self.applied = True
        super(CustomizedEnhancement, self).applyEnhancement()

    def removeEnhancement(self):
        """
        The enhancement is about to be removed; modify our attributes to
        account for that.
        """
        self.removed = True
        super(CustomizedEnhancement, self).removeEnhancement()
コード例 #23
0
ファイル: test_sharing.py プロジェクト: jonathanj/mantissa
class PrivateThing(Item):
    implements(IPrivateThing, IReadOnly)
    publicData = integer(indexed=True)
    externalized = boolean()
    typeName = 'test_sharing_private_thing'
    schemaVersion = 1

    def mutateSomeState(self):
        self.publicData += 5

    def retrieveSomeState(self):
        """
        Retrieve my public data.
        """
        return self.publicData
コード例 #24
0
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)
コード例 #25
0
class Container(item.Item, Containment, _Enhancement):
    """A generic powerup that implements containment."""

    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.
    """)
コード例 #26
0
class Status(item.Item):
    """
    Represents the latest status of a particular grabber.
    """

    when = attributes.timestamp(doc="""
    Time at which this status was set.
    """)

    message = attributes.text(doc="""
    A short string describing the current state of the grabber.
    """)

    success = attributes.boolean(doc="""
    Flag indicating whether this status indicates a successful action
    or not.
    """)

    changeObservers = attributes.inmemory(doc="""
    List of single-argument callables which will be invoked each time
    this status changes.
    """)

    def __repr__(self):
        return '<Status %r>' % (self.message, )

    def activate(self):
        self.changeObservers = []
        self.message = u"idle"

    def addChangeObserver(self, observer):
        self.changeObservers.append(observer)
        return lambda: self.changeObservers.remove(observer)

    def setStatus(self, message, success=True):
        self.when = extime.Time()
        self.message = message
        self.success = success
        for L in self.changeObservers:
            try:
                L(message)
            except:
                log.err(None, "Failure in status update")
コード例 #27
0
class TracebackViewer(Item):
    implements(INavigableElement)

    typeName = 'mantissa_tb_viewer'
    schemaVersion = 2

    allowDeletion = boolean(default=False)

    privateApplication = dependsOn(PrivateApplication)
    powerupInterfaces = (INavigableElement,)

    def getTabs(self):
        return [webnav.Tab('Admin', self.storeID, 0.0,
                           [webnav.Tab('Errors', self.storeID, 0.3)],
                           authoritative=False)]

    def _getCollector(self):
        def ifCreate(coll):
            installOn(coll, self.store.parent)
        return self.store.parent.findOrCreate(TracebackCollector, ifCreate)
コード例 #28
0
ファイル: product.py プロジェクト: jonathanj/mantissa
class Installation(Item):
    """
    I represent a collection of functionality installed on a user store. I
    reference a collection of powerups, probably designated by a Product.
    """

    types = textlist()
    _items = textlist()
    suspended = boolean(default=False)

    def items(self):
        """
        Loads the items this Installation refers to.
        """
        for id in self._items:
            yield self.store.getItemByID(int(id))
    items = property(items)
    def allPowerups(self):
        return set(chain(self.items, *[installedRequirements(self.store, i) for
                                       i in self.items]))
    allPowerups = property(allPowerups)

    def install(self):
        """
        Called when installed on the user store. Installs my powerups.
        """
        items = []
        for typeName in self.types:
            it = self.store.findOrCreate(namedAny(typeName))
            installOn(it, self.store)
            items.append(str(it.storeID).decode('ascii'))
        self._items = items

    def uninstall(self):
        """
        Called when uninstalled from the user store. Uninstalls all my
        powerups.
        """
        for item in self.items:
            uninstallFrom(item, self.store)
        self._items = []
コード例 #29
0
ファイル: spam.py プロジェクト: rcarmo/divmod.org
        # 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)
    return filter
コード例 #30
0
ファイル: inbox.py プロジェクト: pombredanne/quotient
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(),
    ),
)


def inbox3to4(old):
    """
    Copy over all attributes except for 'installedOn' and 'catalog', which
    have been deleted.

    To avoid triggering an Axiom bug where installOn will load the Inbox
    instance being upgraded and re-entrantly run its remaining upgraders,
    rely on inbox4to5 to set the 'filter' attribute which was added in this
    version of the schema either to a L{xquotient.spam.Filter} that exists
    in the store, or to a new one.
    """
コード例 #31
0
class LinkEntryComment(Item):
    implements(IFulltextIndexable)

    typeName = 'eridanus_plugins_linkdb_linkentrycomment'
    schemaVersion = 1

    created = timestamp(doc="""
    Timestamp of when this comment was created.
    """, defaultFactory=lambda: Time())

    parent = reference(doc="""
    L{LinkEntry} item this comment refers to.
    """, indexed=True, allowNone=False, reftype=LinkEntry)

    nick = text(doc="""
    The nickname of the person who commented on L{parent}.
    """, allowNone=False)

    comment = text(doc="""
    The comment text that L{nick} made.
    """, allowNone=False)

    initial = boolean(doc="""
    Indicates whether this was the initial comment made when the entry was created.
    """, allowNone=False, default=False)

    def __repr__(self):
        return '<%s %s: %r>' % (type(self).__name__, self.nick, self.comment)


    def stored(self):
        # Tell the batch processor that we have data to index.
        s = self.store.findUnique(LinkEntryCommentSource)
        s.itemAdded()


    def getEntry(self):
        return self.parent


    @property
    def displayTimestamp(self):
        """
        Convert the C{self.created} timestamp into a human-readable string.
        """
        return self.created.asHumanly(tzinfo=const.timezone)


    @property
    def humanReadable(self):
        """
        Display this comment's information in a concise, human-readble string.
        """
        return u'#%d: %s -- \002%s\002 (%s)' % (self.parent.eid, self.comment, self.nick, self.displayTimestamp)


    # IFulltextIndexable

    def uniqueIdentifier(self):
        return str(self.storeID)


    def textParts(self):
        yield self.comment
コード例 #32
0
class LinkEntry(Item):
    implements(IFulltextIndexable)

    typeName = 'eridanus_plugins_linkdb_linkentry'
    schemaVersion = 1

    eid = integer(doc="""
    The ID of this entry.
    """, indexed=True, allowNone=False)

    created = timestamp(doc="""
    Timestamp of when this entry was created.
    """, defaultFactory=lambda: Time())

    modified = timestamp(doc="""
    Timestamp of when this entry was last modified.
    """, defaultFactory=lambda: Time())

    channel = text(doc="""
    The channel where this entry was first submitted.
    """, indexed=True, allowNone=False)

    nick = text(doc=u"""
    The nickname of the person who submitted this entry first.
    """, allowNone=False)

    url = text(doc=u"""
    Entry's URL.
    """, indexed=True, allowNone=False)

    title = text(doc=u"""
    Optional title for this entry.
    """)

    occurences = integer(doc="""
    Number of times this entry has been mentioned.
    """, default=1)

    isDiscarded = boolean(doc="""
    Indicates whether this item is to be considered for searches and the like.
    """, default=False)

    isDeleted = boolean(doc="""
    Indicates whether this item is to be considered at all.
    """, default=False)

    def __repr__(self):
        return '<%s %s %s>' % (type(self).__name__, self.canonical, self.url)

    def stored(self):
        # Tell the batch processor that we have data to index.
        s = self.store.findUnique(LinkEntrySource)
        s.itemAdded()


    def getEntry(self):
        return self


    def getComments(self, initial=None):
        criteria = [LinkEntryComment.parent == self]
        if initial is not None:
            criteria.append(LinkEntryComment.initial == initial)

        return iter(self.store.query(LinkEntryComment,
                                     AND(*criteria),
                                     sort=LinkEntryComment.created.ascending))

    @property
    def comments(self):
        util.deprecation('This is legacy crap, use getComments rather')
        return self.getComments(initial=False)

    @property
    def initialComment(self):
        util.deprecation('This is legacy crap, use getInitialComment rather')
        return self.getInitialComment()

    @property
    def displayComment(self):
        comment = self.getInitialComment()
        if comment is None:
            return u''
        return u' [%s]' % (comment.comment,)

    @property
    def slug(self):
        for slug in reversed(self.url.split('/')):
            if slug:
                return urllib.unquote(slug)

    @property
    def displayTitle(self):
        def getMetadata():
            metadata = self.getMetadata()

            contentType = metadata.get(u'contentType')
            if contentType is not None:
                yield contentType

                if contentType.startswith('image'):
                    dims = metadata.get(u'dimensions')
                    if dims is not None:
                        yield dims

            size = metadata.get(u'size')
            if size is not None:
                yield size

        if self.title is not None:
            title = self.title
        else:
            comment = self.getInitialComment()
            if comment is not None:
                title = comment.comment
            else:
                title = self.slug

            md = list(getMetadata())
            if md:
                title = u'%s [%s]' % (title, u' '.join(md),)

        return title

    @property
    def displayTimestamp(self):
        return self.created.asHumanly(tzinfo=const.timezone)

    @property
    def displayModifiedTimestamp(self):
        return self.modified.asHumanly(tzinfo=const.timezone)

    def displayCompleteHumanReadable(self, modified=False):
        if modified:
            timestamp = u'modified %s' % (self.displayModifiedTimestamp,)
        else:
            timestamp = u'posted %s' % (self.displayTimestamp,)
        return u'#%d: \037%s\037%s @ %s %s by \002%s\002.' % (self.eid, self.displayTitle, self.displayComment, self.url, timestamp, self.nick)

    # XXX: these properties suck, they should all be replaced with functions
    #      and the some of them merged
    @property
    def completeHumanReadable(self):
        return self.displayCompleteHumanReadable()

    @property
    def humanReadable(self):
        return u'#%d: \037%s\037%s posted %s by \002%s\002.' % (self.eid, self.displayTitle, self.displayComment, self.displayTimestamp, self.nick)

    @property
    def canonical(self):
        return u'#%d.%s' % (self.eid, self.channel)

    def getInitialComment(self):
        try:
           return self.getComments(initial=True).next()
        except StopIteration:
            return None

    def _getMetadata(self):
        return self.store.query(LinkEntryMetadata,
                                LinkEntryMetadata.entry == self)

    def getMetadata(self):
        return dict((md.kind, md.data) for md in self._getMetadata())

    def addComment(self, nick, comment):
        """
        Add a comment to this entry.

        If this is the first comment made by the original author of the entry,
        it is specially marked as the initial comment.
        See L{self.getInitialComment}.

        @type nick: C{unicode}
        @param nick: Nickname of the person commenting on this entry

        @type comment: C{unicode}
        @param comment: Comment content

        @rtype: L{LinkEntryComment}
        @return: The newly created comment
        """
        initial = self.getInitialComment() is None and nick == self.nick
        return self.store.findOrCreate(LinkEntryComment, parent=self, nick=nick, comment=comment, initial=initial)

    def touchEntry(self):
        """
        Update the modification time and number of occurences of this entry.
        """
        self.modified = Time()
        self.occurences += 1

    # XXX: does anything use this?
    #def getMetadataByKind(self, kind):
    #    """
    #    Get all L{LinkEntryMetadata} items associated with this entry.
    #    """
    #    return self.store.query(LinkEntryMetadata,
    #                            AND(LinkEntryMetadata.entry == self,
    #                                LinkEntryMetadata.kind == kind))

    def updateMetadata(self, metadata):
        """
        Update this entry's metadata.

        @type metadata: C{dict}
        @param metadata: A mapping of metadata kinds to metadata data to use
            for updating this entry's metadata
        """
        store = self.store
        for kind, data in metadata.iteritems():
            md = store.findOrCreate(LinkEntryMetadata, entry=self, kind=kind)
            md.data = data

    # IFulltextIndexable

    def uniqueIdentifier(self):
        return str(self.storeID)

    def textParts(self):
        yield self.url

        if self.title is not None:
            yield self.title
コード例 #33
0
ファイル: webadmin.py プロジェクト: fusionapp/mantissa
        return [webnav.Tab('Admin', self.storeID, 0.0,
                           [webnav.Tab('Errors', self.storeID, 0.3)],
                           authoritative=False)]

    def _getCollector(self):
        def ifCreate(coll):
            installOn(coll, self.store.parent)
        return self.store.parent.findOrCreate(TracebackCollector, ifCreate)

    # this needs to be moved somewhere else, topPanelContent is no more
    #def topPanelContent(self):
    #    # XXX There should really be a juice protocol for this.
    #    return '%d errors logged' % (self._getCollector().tracebackCount,)

declareLegacyItem(TracebackViewer, 1,
                  dict(allowDeletion=boolean(default=False)))

def _tracebackViewer1to2(old):
    return old.upgradeVersion(TracebackViewer.typeName, 1, 2,
                              allowDeletion=old.allowDeletion,
                              privateApplication=old.store.findOrCreate(PrivateApplication))
registerUpgrader(_tracebackViewer1to2, TracebackViewer.typeName, 1, 2)


class TracebackViewerFragment(rend.Fragment):
    implements(INavigableFragment)

    live = False
    fragmentName = 'traceback-viewer'

    def head(self):
コード例 #34
0
ファイル: grabber.py プロジェクト: rcarmo/divmod.org
            port = 110

        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(),
コード例 #35
0
ファイル: test_axiomtypes.py プロジェクト: lvh/txampext
 def test_boolean(self):
     self._test_typeFor(attributes.boolean(), amp.Boolean)