Ejemplo n.º 1
0
    def test_workspace_tile(self):
        ''' This will test the existence of the workspaces.tile
        and its functionality
        '''
        tile = api.content.get_view('workspaces.tile', self.portal,
                                    self.request)
        su = StatusUpdate('Proposal draft V1.0 # This is a mock!!!', **{
            'microblog_context': self.workspace,
        })
        su.id = 123456789L
        su.creator = 'charlotte_holzer'
        su.date = DateTime('2008/02/14 18:43')
        mb = queryUtility(IMicroblogTool)
        mb.add(su)
        workspaces = tile.workspaces(include_activities=True)
        self.assertEqual(len(workspaces), 1)

        demo_ws = workspaces[0]

        activities = demo_ws['activities']
        self.assertEqual(len(activities), 1)
        self.assertDictEqual(
            activities[0], {
                'object': 'Proposal draft V1.0 # This is a mock!!!',
                'subject': 'charlotte_holzer',
                'time': {
                    'datetime': '2008-02-14',
                    'title': '14 February 2008, 18:43'
                },
                'verb': 'posted'
            })
Ejemplo n.º 2
0
def create(
    text,
    context=None,
    thread_id=None,
    mention_ids=None,
    tags=None,
    user=None,
    userid=None,
    time=None,
):
    """Create a status update (post).

    :param text: [required] text of the post
    :type text: Unicode object

    :param context: Container of the post
    :type context: Content object

    :param user: User who should post. By default the current user posts.
    :type user: user object

    :param userid: userid of the user who should post.
    :type userid: string

    :param time: time when the post should happen. By default the current time.
    :type time: datetime object

    :returns: Newly created statusupdate
    :rtype: StatusUpdate object
    """
    status_obj = StatusUpdate(
        text=text,
        context=context,
        thread_id=thread_id,
        mention_ids=mention_ids,
        tags=tags
    )
    # By default the post is done by the current user
    # Passing a userid or user allows to post as a different user
    if user is None and userid is not None:
        user = api.user.get(userid=userid)
    if user is not None:
        status_obj.userid = user.getId()
        status_obj.creator = user.getUserName()

    # By default the post happens now
    # Passing a time (as a datetime-object) the id and the date can be set
    if time is not None:
        assert(isinstance(time, datetime))
        delta = time - datetime.utcfromtimestamp(0)
        status_obj.id = long(delta.total_seconds() * 1e6)
        status_obj.date = DateTime(time)

    status_id = status_obj.id
    microblog = queryUtility(IMicroblogTool)
    microblog.add(status_obj)
    return microblog.get(status_id)
Ejemplo n.º 3
0
def create(
    text,
    microblog_context=None,
    thread_id=None,
    mention_ids=None,
    tags=None,
    user=None,
    userid=None,
    time=None,
):
    """Create a status update (post).

    :param text: [required] text of the post
    :type text: Unicode object

    :param microblog_context: Container of the post
    :type microblog_context: Content object

    :param user: User who should post. By default the current user posts.
    :type user: user object

    :param userid: userid of the user who should post.
    :type userid: string

    :param time: time when the post should happen. By default the current time.
    :type time: datetime object

    :returns: Newly created statusupdate
    :rtype: StatusUpdate object
    """
    status_obj = StatusUpdate(
        text=text,
        microblog_context=microblog_context,
        thread_id=thread_id,
        mention_ids=mention_ids,
        tags=tags
    )
    # By default the post is done by the current user
    # Passing a userid or user allows to post as a different user
    if user is None and userid is not None:
        user = api.user.get(userid=userid)
    if user is not None:
        status_obj.userid = user.getId()
        status_obj.creator = user.getUserName()

    # By default the post happens now
    # Passing a time (as a datetime-object) the id and the date can be set
    if time is not None:
        assert(isinstance(time, datetime))
        delta = time - datetime.utcfromtimestamp(0)
        status_obj.id = long(delta.total_seconds() * 1e6)
        status_obj.date = DateTime(time)

    status_id = status_obj.id
    microblog = queryUtility(IMicroblogTool)
    microblog.add(status_obj)
    return microblog.get(status_id)
Ejemplo n.º 4
0
def create_stream(context, stream, files_dir):
    contexts_cache = {}
    microblog = queryUtility(IMicroblogTool)
    if len([x for x in microblog.keys()]) > 0:
        log.info("microblog already setup. skipping for speed.")
        return

    like_tool = getUtility(INetworkTool)
    microblog.clear()
    for status in stream:
        kwargs = {}
        microblog_context = status['microblog_context']
        if microblog_context:
            if microblog_context not in contexts_cache:
                contexts_cache[microblog_context] = api.content.get(
                    path='/' + decode(microblog_context).lstrip('/')
                )
            kwargs['microblog_context'] = contexts_cache[microblog_context]
        status_obj = StatusUpdate(status['text'], **kwargs)
        status_obj.userid = status['user']
        status_obj.creator = api.user.get(
            username=status['user']
        ).getUserName()
        offset_time = status['timestamp'] * 60
        status_obj.id -= int(offset_time * 1e6)
        status_obj.date = DateTime(time.time() - offset_time)
        # THIS BREAKS BECAUSE docconv.client.async.queueConversionJob FIXME
        # if 'attachment' in status:
        #     _definition = status['attachment']
        #     _filename = os.path.join(files_dir, _definition['filename'])
        #     _data = context.readDataFile(_filename)
        #     attachment_obj = create_attachment(_filename, _data)
        #     attachments = IAttachmentStorage(status_obj)
        #     attachments.add(attachment_obj)
        microblog.add(status_obj)

        # like some status-updates
        if 'likes' in status:
            for user_id in status['likes']:
                like_tool.like(
                    "update",
                    user_id=user_id,
                    item_id=str(status_obj.id),

                )
Ejemplo n.º 5
0
def create_stream(context, stream, files_dir):
    contexts_cache = {}
    microblog = queryUtility(IMicroblogTool)
    like_tool = getUtility(ILikesTool)
    microblog.clear()
    for status in stream:
        kwargs = {}
        if status['context']:
            if status['context'] not in contexts_cache:
                contexts_cache[status['context']] = api.content.get(
                    path='/' + decode(status['context']).lstrip('/')
                )
            kwargs['context'] = contexts_cache[status['context']]
        status_obj = StatusUpdate(status['text'], **kwargs)
        status_obj.userid = status['user']
        status_obj.creator = api.user.get(
            username=status['user']
        ).getUserName()
        offset_time = status['timestamp'] * 60
        status_obj.id -= int(offset_time * 1e6)
        status_obj.date = DateTime(time.time() - offset_time)
        microblog.add(status_obj)
        # THIS BREAKS BECAUSE DOCCONV. FIX DOCCONV, UNCOMMENT
        # if 'attachment' in status:
        #     attachment_definition = status['attachment']
        #     attachment_filename = os.path.join(
        #         files_dir,
        #         attachment_definition['filename']
        #     )
        #     attachment = context.openDataFile(attachment_filename)
        #     fake_field = FakeFileField(
        #         attachment_definition['filename'],
        #         attachment
        #     )
        #     attachment_obj = create_attachment(fake_field)
        #     attachments = IAttachmentStorage(status_obj)
        #     attachments.add(attachment_obj)

        # like some status-updates
        if 'likes' in status:
            for user_id in status['likes']:
                like_tool.like(
                    item_id=str(status_obj.id),
                    user_id=user_id,
                )
Ejemplo n.º 6
0
def create_stream(context, stream, files_dir):
    contexts_cache = {}
    microblog = queryUtility(IMicroblogTool)
    if len([x for x in microblog.keys()]) > 0:
        log.info("microblog already setup. skipping for speed.")
        return

    like_tool = getUtility(INetworkTool)
    microblog.clear()
    for status in stream:
        kwargs = {}
        microblog_context = status['microblog_context']
        if microblog_context:
            if microblog_context not in contexts_cache:
                contexts_cache[microblog_context] = api.content.get(
                    path='/' + decode(microblog_context).lstrip('/'))
            kwargs['microblog_context'] = contexts_cache[microblog_context]
        status_obj = StatusUpdate(status['text'], **kwargs)
        status_obj.userid = status['user']
        status_obj.creator = api.user.get(
            username=status['user']).getUserName()
        offset_time = status['timestamp'] * 60
        status_obj.id -= int(offset_time * 1e6)
        status_obj.date = DateTime(time.time() - offset_time)
        # THIS BREAKS BECAUSE docconv.client.async.queueConversionJob FIXME
        # if 'attachment' in status:
        #     _definition = status['attachment']
        #     _filename = os.path.join(files_dir, _definition['filename'])
        #     _data = context.readDataFile(_filename)
        #     attachment_obj = create_attachment(_filename, _data)
        #     attachments = IAttachmentStorage(status_obj)
        #     attachments.add(attachment_obj)
        microblog.add(status_obj)

        # like some status-updates
        if 'likes' in status:
            for user_id in status['likes']:
                like_tool.like(
                    "update",
                    user_id=user_id,
                    item_id=str(status_obj.id),
                )
Ejemplo n.º 7
0
    def test_workspace_tile(self):
        ''' This will test the existence of the workspaces.tile
        and its functionality
        '''
        tile = api.content.get_view(
            'workspaces.tile',
            self.portal,
            self.request
        )
        su = StatusUpdate(
            'Proposal draft V1.0 # This is a mock!!!',
            **{
                'microblog_context': self.workspace,
            }
        )
        su.id = 123456789L
        su.creator = 'charlotte_holzer'
        su.date = DateTime('2008/02/14 18:43')
        mb = queryUtility(IMicroblogTool)
        mb.add(su)
        workspaces = tile.workspaces()
        self.assertEqual(len(workspaces), 1)

        demo_ws = workspaces[0]
        activities = demo_ws['activities']
        self.assertEqual(len(activities), 1)
        self.assertDictEqual(
            activities[0],
            {
                'object': 'Proposal draft V1.0 # This is a mock!!!',
                'subject': 'charlotte_holzer',
                'time': {
                    'datetime': '2008-02-14',
                    'title': '14 February 2008, 18:43'
                },
                'verb': 'posted'
            }
        )
Ejemplo n.º 8
0
def create(
    text=u'',
    microblog_context=None,
    thread_id=None,
    mention_ids=None,
    tags=None,
    user=None,
    userid=None,
    time=None,
    content_context=None,
    action_verb=None,
):
    """Create a status update (post).

    :param text: text of the post
    :type text: Unicode object

    :param microblog_context: Container of the post
    :type microblog_context: Content object

    :param user: User who should post. By default the current user posts.
    :type user: user object

    :param userid: userid of the user who should post.
    :type userid: string

    :param time: time when the post should happen. By default the current time.
    :type time: timezone aware datetime object

    :param content_context: a content referenced we are talking about
    :type content_context: content object

    :param action_verb: indicate event source (posted, created, published)
    :type action_verb: string

    :returns: Newly created statusupdate
    :rtype: StatusUpdate object

    Note that you can add attachments to statusupdates by calling
    .add_attachment(filename, data)
    on the returned StatusUpdate.
    """
    if IPloneSiteRoot.providedBy(microblog_context):
        microblog_context = None
    if IPloneSiteRoot.providedBy(content_context):
        content_context = None

    # Avoid circulat dependencies
    from ploneintranet.microblog.statusupdate import StatusUpdate
    status_obj = StatusUpdate(
        text=text,
        microblog_context=microblog_context,
        thread_id=thread_id,
        mention_ids=mention_ids,
        tags=tags,
        content_context=content_context,
        action_verb=action_verb,
    )
    # By default the post is done by the current user
    # Passing a userid or user allows to post as a different user
    if user is None and userid is not None:
        user = api.user.get(userid=userid)
    if user is not None:
        status_obj.userid = user.getId()
        status_obj.creator = user.getId()

    # By default the post happens now
    # Passing a time (as a datetime-object) the id and the date can be set
    if time is not None:
        assert (isinstance(time, datetime))
        if not time.tzinfo or time.tzinfo.utcoffset(time) is None:
            raise ValueError("Naive datetime not supported")
        UTC = pytz.timezone('UTC')
        epoch = UTC.localize(datetime.utcfromtimestamp(0))
        delta = time - epoch
        status_obj.id = long(delta.total_seconds() * 1e6)
        status_obj.date = DateTime(time)
        if time > datetime.now(UTC):
            raise ValueError("Future statusupdates are an abomination")

    microblog = queryUtility(IMicroblogTool)
    microblog.add(status_obj)
    # take care - statusupdate may still be queued for storage
    # and not actually written into the container yet
    # this may change the status_obj.id
    return status_obj
Ejemplo n.º 9
0
def demo(context):

    if context.readDataFile('ploneintranet.socialsuite_demo.txt') is None:
        return

    portal = site = context.getSite()
    avatar_path = os.path.join(context._profile_path, 'avatars')

    # create users
    users = []
    for file_name in os.listdir(avatar_path):
        userid = str(file_name.split('.')[0])
        users.append(userid)
        properties = dict(
            fullname=" ".join([x.capitalize() for x in userid.split("_")]),
            location=random.choice(
                ("New York", "Chicago", "San Francisco",
                 "Paris", "Amsterdam", "Zurich")),
            description=" ".join(loremipsum.get_sentences(2)))
        try:
            api.user.create(email='*****@*****.**' % userid,
                            username=userid,
                            password='******',
                            properties=properties)
        except ValueError:
            user = api.user.get(username=userid)
            user.setMemberProperties(properties)

        portrait = context.openDataFile(file_name, 'avatars')
        scaled, mimetype = scale_image(portrait)
        portrait = Image(id=userid, file=scaled, title='')
        memberdata = getToolByName(site, 'portal_memberdata')
        memberdata._setPortrait(portrait, userid)

    # setup social network
    graph = queryUtility(INetworkGraph)
    graph.clear()
    testusers = ['clare_presler', 'kurt_silvio']
    graph.follow("user", testusers[0], testusers[1])
    # give clare som extra followers
    for fan in ['christian_stoner', 'guy_hachey', 'jamie_jacko']:
        graph.follow("user", testusers[0], fan)
    # fully random followers
    for i in xrange(100):
        followee = random.choice(users)
        follower = random.choice(users)
        if followee in testusers or follower in testusers \
                or followee == follower:
            continue
        else:
            graph.follow("user", followee, follower)

    # setup publicly accessible folder and document
    portal.invokeFactory('Folder', 'public', title=u"Public Folder")
    public = portal['public']
    public.invokeFactory('Document', 'd1', title=u"Public Document")

    # create and fill a local IMicroblogContext workspace
    workspace_users = ['clare_presler',
                       'dollie_nocera',
                       'esmeralda_claassen',
                       'pearlie_whitby']
    if 'workspace' not in portal:
        portal.invokeFactory('Folder', 'workspace',
                             title=u"Secure Workspace")
        # enable local microblog
        directlyProvides(portal.workspace, IMicroblogContext)
        # in testing we don't have the 'normal' default workflow
        workflowTool = getToolByName(portal, 'portal_workflow')
        if workflowTool.getInfoFor(portal.workspace,
                                   'review_state') != 'private':
            workflowTool.doActionFor(portal.workspace, 'hide')
        # share workspace with some users
        for userid in workspace_users:
            api.user.grant_roles(username=userid,
                                 obj=portal.workspace,
                                 roles=['Contributor', 'Reader', 'Editor'])
        # update object_provides + workflow state + sharing indexes
        portal.workspace.reindexObject()

    # microblog random loremipsum
    # prepare microblog
    microblog = queryUtility(IMicroblogTool)
    microblog.clear()  # wipe all
    tags = ("hr", "marketing", "fail", "innovation", "learning", "easy",
            "newbiz", "conference", "help", "checkthisout")
    for i in xrange(100):
        # select random user
        userid = random.choice(users)
        # generate text
        text = " ".join(loremipsum.get_sentences(3))
        if random.choice((True, False)):
            text += " #%s" % random.choice(tags)
        if userid in workspace_users:
            # workspace
            status = StatusUpdate(text, context=portal.workspace,
                                  tags=['girlspace'])
        else:
            # global
            status = StatusUpdate(text)
        status.userid = userid
        status.creator = " ".join([x.capitalize() for x in userid.split("_")])
        # distribute most over last week
        if i < 90:
            offset_time = random.random() * 3600 * 24 * 7
            status.id -= int(offset_time * 1e6)
            status.date = DateTime(time.time() - offset_time)
        microblog.add(status)

    # microblog deterministic test content most recent
    # workspace
    t0 = ('Workspaces can have local microblogs and activitystreams. '
          'Local activitystreams show only local status updates. '
          'Microblog updates will show globally only for users who '
          'have the right permissions. This demo has a #girlspace workspace.')
    s0 = StatusUpdate(t0, context=portal.workspace, tags=['girlspace'])
    s0.userid = workspace_users[0]  # clare
    s0.creator = " ".join([x.capitalize() for x in s0.userid.split("_")])
    microblog.add(s0)
    # global
    t1 = ('The "My Network" section only shows updates '
          'of people you are following.')
    s1 = StatusUpdate(t1)
    s1.userid = testusers[0]  # clare
    s1.creator = " ".join([x.capitalize() for x in s1.userid.split("_")])
    microblog.add(s1)
    t2 = 'The "Explore" section shows all updates of all people.'
    s2 = StatusUpdate(t2)
    s2.userid = testusers[1]  # kurt
    s2.creator = " ".join([x.capitalize() for x in s2.userid.split("_")])
    microblog.add(s2)
    t3 = 'The #demo hashtag demonstrates that you can filter on topic'
    s3 = StatusUpdate(t3, tags=['demo'])
    s3.userid = s2.userid  # kurt
    s3.creator = s2.creator
    microblog.add(s3)

    # commit
    microblog.flush_queue()
    transaction.commit()
Ejemplo n.º 10
0
def demo(context):

    if context.readDataFile('ploneintranet.socialsuite_demo.txt') is None:
        return

    portal = site = context.getSite()
    avatar_path = os.path.join(context._profile_path, 'avatars')

    # create users
    users = []
    for file_name in os.listdir(avatar_path):
        userid = str(file_name.split('.')[0])
        users.append(userid)
        properties = dict(
            fullname=" ".join([x.capitalize() for x in userid.split("_")]),
            location=random.choice(
                ("New York", "Chicago", "San Francisco",
                 "Paris", "Amsterdam", "Zurich")),
            description=" ".join(loremipsum.get_sentences(2)))
        try:
            api.user.create(email='*****@*****.**' % userid,
                            username=userid,
                            password='******',
                            properties=properties)
        except ValueError:
            user = api.user.get(username=userid)
            user.setMemberProperties(properties)

        portrait = context.openDataFile(file_name, 'avatars')
        scaled, mimetype = scale_image(portrait)
        portrait = Image(id=userid, file=scaled, title='')
        memberdata = getToolByName(site, 'portal_memberdata')
        memberdata._setPortrait(portrait, userid)

    # setup social network
    graph = queryUtility(INetworkGraph)
    graph.clear()
    testusers = ['clare_presler', 'kurt_silvio']
    graph.follow("user", testusers[0], testusers[1])
    # give clare som extra followers
    for fan in ['christian_stoner', 'guy_hachey', 'jamie_jacko']:
        graph.follow("user", testusers[0], fan)
    # fully random followers
    for i in xrange(100):
        followee = random.choice(users)
        follower = random.choice(users)
        if followee in testusers or follower in testusers \
                or followee == follower:
            continue
        else:
            graph.follow("user", followee, follower)

    # setup publicly accessible folder and document
    portal.invokeFactory('Folder', 'public', title=u"Public Folder")
    public = portal['public']
    public.invokeFactory('Document', 'd1', title=u"Public Document")

    # create and fill a local IMicroblogContext workspace
    workspace_users = ['clare_presler',
                       'dollie_nocera',
                       'esmeralda_claassen',
                       'pearlie_whitby']
    if 'workspace' not in portal:
        portal.invokeFactory('Folder', 'workspace',
                             title=u"Secure Workspace")
        # enable local microblog
        alsoProvides(portal.workspace, IMicroblogContext)
        # in testing we don't have the 'normal' default workflow
        workflowTool = getToolByName(portal, 'portal_workflow')
        if workflowTool.getInfoFor(portal.workspace,
                                   'review_state') != 'private':
            workflowTool.doActionFor(portal.workspace, 'hide')
        # share workspace with some users
        for userid in workspace_users:
            api.user.grant_roles(username=userid,
                                 obj=portal.workspace,
                                 roles=['Contributor', 'Reader', 'Editor'])
        # update object_provides + workflow state + sharing indexes
        portal.workspace.reindexObject()

    # microblog random loremipsum
    # prepare microblog
    microblog = queryUtility(IMicroblogTool)
    microblog.clear()  # wipe all
    tags = ("hr", "marketing", "fail", "innovation", "learning", "easy",
            "newbiz", "conference", "help", "checkthisout")
    for i in xrange(100):
        # select random user
        userid = random.choice(users)
        # generate text
        text = " ".join(loremipsum.get_sentences(3))
        if random.choice((True, False)):
            text += " #%s" % random.choice(tags)
        if userid in workspace_users:
            # workspace
            status = StatusUpdate(
                text,
                microblog_context=portal.workspace,
                tags=['girlspace']
            )
        else:
            # global
            status = StatusUpdate(text)
        status.userid = userid
        status.creator = " ".join([x.capitalize() for x in userid.split("_")])
        # distribute most over last week
        if i < 90:
            offset_time = random.random() * 3600 * 24 * 7
            status.id -= int(offset_time * 1e6)
            status.date = DateTime(time.time() - offset_time)
        microblog.add(status)

    # microblog deterministic test content most recent
    # workspace
    t0 = ('Workspaces can have local microblogs and activitystreams. '
          'Local activitystreams show only local status updates. '
          'Microblog updates will show globally only for users who '
          'have the right permissions. This demo has a #girlspace workspace.')
    s0 = StatusUpdate(
        t0,
        microblog_context=portal.workspace,
        tags=['girlspace']
    )
    s0.userid = workspace_users[0]  # clare
    s0.creator = " ".join([x.capitalize() for x in s0.userid.split("_")])
    microblog.add(s0)
    # global
    t1 = ('The "My Network" section only shows updates '
          'of people you are following.')
    s1 = StatusUpdate(t1)
    s1.userid = testusers[0]  # clare
    s1.creator = " ".join([x.capitalize() for x in s1.userid.split("_")])
    microblog.add(s1)
    t2 = 'The "Explore" section shows all updates of all people.'
    s2 = StatusUpdate(t2)
    s2.userid = testusers[1]  # kurt
    s2.creator = " ".join([x.capitalize() for x in s2.userid.split("_")])
    microblog.add(s2)
    t3 = 'The #demo hashtag demonstrates that you can filter on topic'
    s3 = StatusUpdate(t3, tags=['demo'])
    s3.userid = s2.userid  # kurt
    s3.creator = s2.creator
    microblog.add(s3)

    # commit
    microblog.flush_queue()
    transaction.commit()