def post(self, childTitle, childBody, childAuthor, roleToPerms=None): """ Create a new child of this Blurb, with a flavor derived from the mapping into FLAVOR.commentFlavors of self.flavor, shared to every role specified by FlavorPermission items that refer to the new flavor of blurb that will be created, and this blurb or any of my parents. For example, if I am a FLAVOR.BLOG, the child will be a FLAVOR.BLOG_POST. If the FlavorPermissions are set up correctly for me, one role will be able to view that post, another to comment on it. By using FlavorPermissions appropriately, you can have a blog that allows public posting, and a blog that allows private posting and no public viewing, and a blog that allows public viewing but only permissioned posting and commenting, all in the same store. @return: A share ID. """ newFlavor = FLAVOR.commentFlavors[self.flavor] newBlurb = Blurb(store=self.store, flavor=newFlavor, parent=self, body=childBody, title=childTitle, author=childAuthor, dateCreated=Time(), dateLastEdited=Time(), hits=0) if roleToPerms is None: roleToPerms = self._getChildPerms(childAuthor) return self._setBlurbPermissions(newBlurb, roleToPerms)
def testScheduledErrorWithHandler(self): S = IScheduler(self.store) now = Time() spec = SpecialErrorHandler(store=self.store) S.schedule(spec, now) d = Deferred() te = TestEvent(store=self.store, testCase=self, name=u't1', maxRunCount=1, runAgain=None, winner=True, deferred=d) self.te = te # don't gc the deferred now2 = Time() S.schedule(te, now2) self.assertEquals(self.store.query(TimedEventFailureLog).count(), 0) def later(result): errs = log.flushErrors(SpecialError) self.assertEquals(len(errs), 1) self.assertEquals( self.store.query(TimedEventFailureLog).count(), 0) self.failUnless(spec.procd) self.failIf(spec.broken) return d.addCallback(later)
def test_blurbCreationNoSource(self): """ Test that blurb creation goes OK when there is no L{hyperbola.hyperblurb.BlurbSource} installed """ hyperblurb.Blurb(store=self.store, title=u'', body=u'', author=self.me, hits=0, dateCreated=Time(), dateLastEdited=Time(), flavor=hyperblurb.FLAVOR.BLOG)
def makeMessage(receiver, parts, impl): """ Create a new L{exmess.Message}, either by parsing C{parts} or by wrapping one around C{impl}. """ if impl is None: return receiver.feedStringNow(parts) else: return testMessageFactory(store=impl.store, receivedWhen=Time(), sentWhen=Time(), spam=False, subject=u'', impl=impl)
def _makeBlurb(self, flavor, title=None, body=None): """ Make a minimal nonsense blurb with flavor C{flavor} @param flavor: the blurb flavor @type flavor: one of the C{unicode} L{hyperbola.hyperblurb.FLAVOR} constants @param title: the blurb title. defaults to C{flavor} @type title: C{unicode} @param body: the blurb body. defaults to C{flavor} @type body: C{unicode} @rtype: L{hyperbola.hyperblurb.Blurb} """ if title is None: title = flavor if body is None: body = flavor return hyperblurb.Blurb(store=self.userStore, title=title, body=body, flavor=flavor, dateCreated=Time(), author=self.role)
class _ControllerMixin: aliceEmail = u'*****@*****.**' bobEmail = u'*****@*****.**' tzfactor = time.daylight and time.altzone or time.timezone sent = Time.fromDatetime(datetime(1999, 12, 13)) sent2 = Time().oneDay() + timedelta(hours=16, minutes=5, seconds=tzfactor) def getInbox(self): """ Return a newly created Inbox, in a newly created Store. """ s = Store() LoginMethod(store=s, internal=False, protocol=u'email', localpart=u'default', domain=u'host', verified=True, account=s) installOn(Composer(store=s), s) installOn(Catalog(store=s), s) installOn(MessageLister(store=s), s) inbox = Inbox(store=s) installOn(inbox, s) return inbox def widgetFor(self, inbox): """ Create and return an InboxScreen for the given inbox. """ fragment = InboxScreen(inbox) fragment.messageDetailFragmentFactory = ActionlessMsgDetailWithStubCompose fragment.setFragmentParent(self) return fragment
def _txn(): svc = s.findOrCreate( DataService, smtpFrom=unicode(self['smtpFrom']), smtpServer=unicode(self['smtpServer']), ) installOn(svc, s) ircsvc = s.findOrCreate(ircserver.IRCService, portNumber=6667, interface=u'127.0.0.1') installOn(ircsvc, s) websvc = s.findOrCreate( web.WebService, portNumber=8080, ) installOn(websvc, s) if self['demodata']: s.findOrCreate(User, email=u'*****@*****.**', nick=u'MFen', password=u'password') s.findOrCreate(Channel, name=u'#vellum', topic=u'Welcome to #vellum', topicAuthor=u'VellumTalk', topicTime=Time())
def testUnscheduling(self): """ Test the unscheduleFirst method of the scheduler. """ now = Time() d = Deferred() sch = IScheduler(self.store) t1 = TestEvent(testCase=self, name=u't1', store=self.store, maxRunCount=0) t2 = TestEvent(testCase=self, name=u't2', store=self.store, maxRunCount=1, runAgain=None, winner=True, deferred=d) # Make sure the inmemory attributes hang around self.ts = [t1, t2] sch.schedule(t1, now + timedelta(milliseconds=100)) sch.schedule(t2, now + timedelta(milliseconds=200)) sch.unscheduleFirst(t1) return d
class Paste(Item): """ Paste item. """ created = timestamp(defaultFactory=lambda: Time(), doc=u'Creation timestamp') languageHint = text(doc=u'Paste content language hint') name = text(allowNone=False, indexed=True, doc=u'Paste name') content = text(allowNone=False, doc=u'Paste content') def run(self): self.deleteFromStore() def toJSON(self): """ Describe the L{Paste} item as I{JSON}. """ attrs = dict(self.persistentValues()) attrs['id'] = attrs['name'] return json.dumps(attrs, default=jsonSerialize) @classmethod def findByName(cls, store, name): """ Get a L{Paste} item by name. """ return store.findUnique(Paste, Paste.name == name)
def run(self): # When this is run from testSubScheduler, we want to make an # additional assertion. There is exactly one SubStore in this # configuration, so there should be no more than one # TimedEvent with a _SubSchedulerParentHook as its runnable. if self.store.parent is not None: count = 0 s = self.store.parent for evt in s.query(TimedEvent): if isinstance(evt.runnable, _SubSchedulerParentHook): count += 1 if count > 1: return self.fail("Too many TimedEvents for the SubStore", count) self.runCount += 1 if self.runCount > self.maxRunCount: return self.fail("%s ran too many times" % (self.name)) if self.runAgain is not None: result = Time() + timedelta(milliseconds=self.runAgain) self.runAgain = None else: if self.winner and self.deferred is not None: self.deferred.callback('done') result = None return result
def enter_recording(self, currentlyPlaying=None, offset=0): """ User has pressed '1' to start the recording. """ self.app.pingWebSessions() start = Time() filename = Recording.userRecordingFilename(self.app) d = self.agi.recordFile("weareforests-recordings/" + filename, "gsm", chr(self.digit), 45) def save(r): digit, tpe, duration = r duration = duration / 8000 rec = Recording(store=self.app.store, filename=unicode(filename), created=start, caller_id=self.callerId, duration=duration, user_recording=True) print "saved!" if tpe == 'hangup': print "user hung up during recording." self.app.sessionEnded(self.channel) # add it to everybody's queue self.app.recordingAdded(self, rec) # resume play where we stopped self.setStateAfterSample("play", "weareforests-audio/listen", currentlyPlaying, offset) d.addCallback(save) d.addErrback(self.catchHangup)
def edit(self, newTitle, newBody, newAuthor, newTags): """ Edit an existing blurb, saving a PastBlurb of its current state for rollback purposes. """ # Edit is only called on subsequent edits, not the first time, so we # need to save our current contents as history. editDate = Time() pb = PastBlurb(store=self.store, title=self.title, body=self.body, author=self.author, blurb=self, dateEdited=self.dateLastEdited, hits=self.hits) catalog = self.store.findOrCreate(Catalog) for tag in self.tags(): catalog.tag(pb, tag) self.title = newTitle self.body = newBody self.dateLastEdited = editDate self.author = newAuthor self.store.query(Tag, Tag.object == self).deleteFromStore() for tag in newTags: catalog.tag(self, tag)
def createBlog(self, title, description): """ Create a top-level BLOG-flavored Blurb with the given title and description, shared for edit with the owner of this store and for viewing with everyone, and return it. @param title: the blog title @type title: C{unicode} @param description: the blog description @type description: C{unicode} """ store = self.store now = Time() blog = Blurb(store=self.store, dateCreated=now, dateLastEdited=now, title=title, body=description, flavor=FLAVOR.BLOG, author=sharing.getSelfRole(self.store)) authorsRole = sharing.getPrimaryRole(store, title + u' blog', True) sharing.getSelfRole(store).becomeMemberOf(authorsRole) sharing.shareItem(blog, authorsRole, shareID=u'blog') everyoneRole = sharing.getEveryoneRole(store) sharing.shareItem(blog, everyoneRole, shareID=u'blog', interfaces=[IViewable]) # this should be configurable blog.permitChildren(everyoneRole, FLAVOR.BLOG_POST, IViewable)
def now(timezoneName): """ Get the current time in the timezone named C{timezoneName}. @rtype: C{datetime.datetime} """ return Time().asDatetime(tzinfo=pytz.timezone(timezoneName))
def makeMessages(self, number, **flags): messages = [] for i in xrange(number): m = testMessageFactory(store=self.store, receivedWhen=Time(), **flags) messages.append(m) return messages
def makeMessages(n, email): return list(reversed(list( testMessageFactory(store=s, subject=u'Message %d' % (i,), sender=email, spam=False, receivedWhen=Time()) for i in xrange(n))))
def lookupNextRecording(self): timePoint = Time() - timedelta(minutes=15) for r in self.app.store.query(Recording, Recording.created >= timePoint, sort=Recording.created.ascending): if r.storeID in self.listened: continue return r return random.choice(self.app.getIdleRecordings())
def test_extraction(self): """ Ensure that user store extraction works correctly, particularly in the presence of timed events. """ thing = ThingThatMovesAround(store=self.accountStore, superValue=self.IMPORTANT_VALUE) self.ss.schedule(thing, Time() + datetime.timedelta(days=1)) self.test_noTimedEventsExtraction()
def cleanRecentlyDisconnected(self): now = Time() dirty = False for callerId, t in self.recentlyDisconnected.items(): if (now-t).seconds > 300: del self.recentlyDisconnected[callerId] dirty = True if dirty: self.pingWebSessions()
def setUp(self): self.siteStore = Store(filesdir=self.mktemp()) Mantissa().installSite(self.siteStore, u'example.com', u"", False) self.loginSystem = self.siteStore.findUnique(LoginSystem) userAccount = self.loginSystem.addAccount(u'alice', u'example.com', u'password') self.userStore = userAccount.avatars.open() product = Product( store=self.siteStore, types=[qual(hyperbola_model.HyperbolaPublicPresence)]) product.installProductOn(self.userStore) self.publicPresence = self.userStore.findUnique( hyperbola_model.HyperbolaPublicPresence) self.me = Role(store=self.userStore, externalID=u'*****@*****.**', description=u'foobar') self.you = Role(store=self.userStore, externalID=u'*****@*****.**', description=u'rad yo') blog = self.blog = hyperblurb.Blurb(store=self.userStore, title=u"Hello World", body=u"Hello World!~!!", author=self.me, hits=0, dateCreated=Time(), dateLastEdited=Time(), flavor=hyperblurb.FLAVOR.BLOG) blog.permitChildren(self.me, hyperblurb.FLAVOR.BLOG_POST, ihyperbola.ICommentable) blog.permitChildren(self.me, hyperblurb.FLAVOR.BLOG_COMMENT, ihyperbola.ICommentable) blog.permitChildren(self.you, hyperblurb.FLAVOR.BLOG_POST, ihyperbola.ICommentable) blog.permitChildren(self.you, hyperblurb.FLAVOR.BLOG_COMMENT, ihyperbola.ICommentable) shareItem(blog, getEveryoneRole(self.userStore), shareID=u'blog', interfaces=[ihyperbola.IViewable])
class Factoid(Item): """ A factoid. The crux of this item is the key/value concept. The goal is to have keys mapping to multiple values, which can be built up into a simple snippets of information tied to topics. """ typeName = 'eridanus_plugins_factoid_factoid' schemaVersion = 1 created = timestamp(doc=""" Creation time of this Factoid. """, defaultFactory=lambda: Time()) creator = text(doc=""" The name of the original creator. """, allowNone=False) modified = timestamp(doc=""" Modification time of this Factoid. """, defaultFactory=lambda: Time()) editor = text(doc=""" The name of the last person to modify this factoid. """, allowNone=False) key = text(doc=""" The factoid key. """, indexed=True, allowNone=False) value = text(doc=""" A factoid value. """, allowNone=False) def touchFactoid(self, editor): self.editor = editor self.modified = Time()
class _PendingUpload(Item): """ Marker for a pending upload to a backend store. """ objectId = text(allowNone=False) backend = reference(allowNone=False) # reftype=IBackendStore scheduled = timestamp(indexed=True, allowNone=False, defaultFactory=lambda: Time()) def _nextAttempt(self): """ Determine the time to schedule the next attempt. """ return Time() + timedelta(minutes=2) def run(self): self.attemptUpload() def attemptUpload(self): """ Attempt an upload of an object to a backend store. If the upload fails, it will be rescheduled; if it succeeds, this item will be deleted. """ def _uploadObject(obj): d = obj.getContent() d.addCallback(lambda content: self.backend.storeObject( content, obj.contentType, obj.metadata, obj.created, objectId=self.objectId)) return d def _reschedule(f): # We do this instead of returning a Time from attemptUpload, # because that can only be done synchronously. log.failure( 'Error uploading object {objectId!r} to backend store {backend!r}', failure=f, objectId=self.objectId, backend=self.backend) self.scheduled = self._nextAttempt() self.schedule() d = succeed(None) d.addCallback( lambda ign: IContentStore(self.store).getObject(self.objectId)) d.addCallback(_uploadObject) d.addCallbacks(lambda ign: self.deleteFromStore(), _reschedule) return d def schedule(self): IScheduler(self.store).schedule(self, self.scheduled)
def getInitialQueue(self): timePoint = Time() - timedelta(minutes=15) try: q = [r.filenameAsAsterisk() for r in self.store.query(Recording, AND(Recording.created >= timePoint, Recording.use_in_ending == False), sort=Recording.created.ascending)] except: log.err() intro = self.getRecordingByName("intro") if intro: q.insert(0, intro.filenameAsAsterisk()) return q
def test_noSender(self): """ Test that a message with no sender headers gets handled properly. """ self.msg.addHeader(u"to", u"*****@*****.**") self.msg.addHeader(u"date", u"Fri, 13 Feb 2004 13:43:48 +0100") self.msg.addHeader(u"content-type", u"multipart/mixed") self.msg.addHeader(u"subject", u"Awesome Email") self.wrapper = MessageWrapperForPart(self.msg, Time()) self.assertEqual(self.wrapper.sender, u'') self.assertEqual(self.wrapper.senderDisplay, u'')
def initialize(): s = store.Store('postit.axiom') postit = IPostit(s, None) if not postit: Application(store=s, name='Postit').installOn(s) Post(store=s, title="This is the title", url="http://www.divmod.org", content="Here is the content for the link", author="dialtone", created=Time()) return s
def createDatabase(s): """ Populate the given Store with a deferred message. """ messageData = DummyMessageImplementation(store=s) fakeScheduler = FakeScheduler(store=s) s.powerUp(fakeScheduler, IScheduler) m = Message.createIncoming(s, messageData, u'test') m.classifyClean() m.markRead() now = Time() m.deferFor(timedelta(days=1), timeFactory=lambda: now)
def _makeContentObject((data, response)): hash, contentDigest = objectId.split(u':', 1) contentType = response.headers.getRawHeaders( 'Content-Type', ['application/octet-stream'])[0].decode('ascii') # XXX: Actually get the real creation time return MemoryObject(content=data, hash=hash, contentDigest=contentDigest, contentType=contentType, metadata={}, created=Time())
def __init__(self, flavor, title, body, children, author): self.flavor = flavor self.title = title self.body = body self.children = children self.dateLastEdited = Time() #pretend to be a SharedProxy too self._sharedItem = self class author(object): externalID = author self.author = author
def setUp(self): self.store = Store() self.inbox = Inbox(store=self.store) installOn(self.inbox, self.store) self.translator = self.inbox.privateApplication self.messages = [] for i in range(self.NUM_MESSAGES): self.messages.append( testMessageFactory(store=self.store, spam=False, receivedWhen=Time(), subject=u'')) self.messages.reverse()
def testBasicScheduledError(self): S = IScheduler(self.store) now = Time() S.schedule(NotActuallyRunnable(store=self.store), now) d = Deferred() te = TestEvent(store=self.store, testCase=self, name=u't1', maxRunCount=1, runAgain=None, winner=True, deferred=d) self.te = te # don't gc the deferred now2 = Time() S.schedule(te, now2) self.assertEquals(self.store.query(TimedEventFailureLog).count(), 0) def later(result): errs = log.flushErrors(AttributeError) self.assertEquals(len(errs), 1) self.assertEquals( self.store.query(TimedEventFailureLog).count(), 1) return d.addCallback(later)