Exemplo n.º 1
0
    def create(self, request, me, convId, richText=False, data=None):
        url = data['url']
        comment, snippet = data['comment']

        summary, title, image, embed = yield self._summary(url)

        item = yield utils.createNewItem(request, self.itemType, me, richText=richText)
        meta = {"comment": comment}
        if snippet:
            meta['snippet'] = snippet

        meta["link_url"] = url
        if summary:
            summary = _sanitize(summary, 200)
            meta["link_summary"] = summary
        if title:
            title = _sanitize(title, 75)
            meta["link_title"] = title
        if image:
            meta['link_imgSrc'] = image
        if embed:
            embedType = embed.get("type")
            embedSrc = embed.get("url") if embedType == "photo" else embed.get("html")
            embedWidth = embed.get("width")
            embedHeight = embed.get("height")
            if embedHeight and embedWidth and embedSrc:
                meta["link_embedType"] = embedType
                meta["link_embedSrc"] = embedSrc
                meta["link_embedHeight"] = str(embedHeight)
                meta["link_embedWidth"] = str(embedWidth)
        item["meta"].update(meta)

        defer.returnValue(item)
Exemplo n.º 2
0
    def create(self, request, me, convId, richText=False, data=None):
        comment, snippet = data["comment"]

        item = yield utils.createNewItem(request, self.itemType, me, richText=richText)
        meta = {"comment": comment}
        if snippet:
            meta["snippet"] = snippet

        item["meta"].update(meta)
        defer.returnValue(item)
Exemplo n.º 3
0
def unsubscribe(request, group, user):
    """Unsubscribe @user from @group.
    Remove the user from group-followers, group from user-groups,
    create a group-leave activity item and push item to group-followers
    and group feed. Remove the group from user display name indices.

    Raises an error if user is not member of group or when
    user is the only administrator of the group.

    keyword params:
    @user: entity object of user
    @group: entity object of the group
    @request:

    """
    try:
        yield db.get(group.id, "groupMembers", user.id)
    except ttypes.NotFoundException:
        raise errors.InvalidRequest(_("You are not a member of the group"))

    if len(getattr(group, 'admins', {}).keys()) == 1 \
       and user.id in group.admins:
        raise errors.InvalidRequest(_("You are the only administrator of this group"))

    colname = _entityGroupMapColName(group)
    itemType = "activity"
    responseType = "I"

    itemId = utils.getUniqueKey()
    acl = {"accept": {"groups": [group.id]}}
    _acl = pickle.dumps(acl)
    item = yield utils.createNewItem(request, itemType, user,
                                     acl, "groupLeave")
    item["meta"]["target"] = group.id

    d1 = db.remove(group.id, "followers", user.id)
    d2 = db.remove(user.id, "entityGroupsMap", colname)
    d3 = db.batch_insert(itemId, 'items', item)
    d4 = db.remove(group.id, "groupMembers", user.id)
    d5 = feed.pushToOthersFeed(user.id, user.basic['org'],
                               item["meta"]["uuid"], itemId, itemId, _acl,
                               responseType, itemType, user.id,
                               promoteActor=False)
    d6 = utils.updateDisplayNameIndex(user.id, [group.id], None,
                                      user.basic['name'])
    deferreds = [d1, d2, d3, d4, d5, d6]
    if user.id in group.admins:
        d7 = db.remove(group.id, "entities", user.id, "admins")
        d8 = db.remove(user.id, "entities", group.id, "adminOfGroups")
        deferreds.extend([d7, d8])

    yield defer.DeferredList(deferreds)
Exemplo n.º 4
0
    def create(self, request, me, convId, richText=False, data=None):
        comment, snippet = data['comment']
        options = data['options']
        showResults = data['showResults']

        item = yield utils.createNewItem(request, self.itemType, me, richText=richText)

        meta = {"comment": comment, "showResults": showResults}
        if snippet:
            meta["snippet"] = snippet

        pollOptions = " ".join(options)
        meta["poll_options"] = pollOptions  # XXX:Required for keyword monitoring

        options = OrderedDict([('%02d' % (x), options[x]) for x in range(len(options))])
        item["options"] = options
        item["meta"].update(meta)

        defer.returnValue(item)
Exemplo n.º 5
0
def _addMember(request, group, user):
    """Add a new member to the group.
    Add user to group followers, create a group-join activity item and push
    item to group, group-followers feed. Update user groups with new group.

    Keyword params:
    @group: entity object of the group
    @user: entity object of the user
    @request:

    """
    deferreds = []
    itemType = "activity"
    relation = Relation(user.id, [])
    if not getattr(user, 'basic', []):
        yield user.fetchData(['basic'])

    responseType = "I"
    acl = {"accept": {"groups": [group.id]}}
    _acl = pickle.dumps(acl)

    itemId = utils.getUniqueKey()
    colname = _entityGroupMapColName(group)
    yield db.insert(user.id, "entityGroupsMap", "", colname)
    yield db.insert(group.id, "groupMembers", itemId, user.id)
    item = yield utils.createNewItem(request, "activity", user,
                                     acl, "groupJoin")
    item["meta"]["target"] = group.id

    d1 = db.insert(group.id, "followers", "", user.id)
    d2 = db.batch_insert(itemId, 'items', item)
    d3 = feed.pushToFeed(group.id, item["meta"]["uuid"], itemId,
                         itemId, responseType, itemType, user.id)
    d4 = feed.pushToOthersFeed(user.id, user.basic['org'],
                                item["meta"]["uuid"], itemId,
                                itemId, _acl, responseType,
                                itemType, user.id, promoteActor=False)

    d5 = utils.updateDisplayNameIndex(user.id, [group.id],
                                      user.basic['name'], None)

    deferreds = [d1, d2, d3, d4, d5]
    yield defer.DeferredList(deferreds)
Exemplo n.º 6
0
def makeAdmin(request, group, user, me):
    """make user admin of the group.
    Only an group-administrator can make an group-member and administrator.

    Keyword params:
    @request:
    @me:
    @user: user object
    @group: group object
    """
    if me.id not in group.admins:
        raise errors.PermissionDenied(_('You are not an administrator of the group'))

    cols = yield db.get_slice(group.id, "groupMembers", [user.id])
    if not cols:
        raise errors.InvalidRequest(_('Only group member can become administrator'))

    if user.id in group.admins:
        defer.returnValue(None)

    yield db.insert(group.id, "entities", '', user.id, 'admins')
    yield db.insert(user.id, "entities", group.basic['name'],
                    group.id, "adminOfGroups")

    itemType = "activity"
    responseType = "I"
    acl = {"accept": {"groups": [group.id]}}
    _acl = pickle.dumps(acl)

    itemId = utils.getUniqueKey()
    item = yield utils.createNewItem(request, "activity", user,
                                     acl, "groupAdmin")
    item["meta"]["target"] = group.id

    d1 = db.batch_insert(itemId, 'items', item)
    d2 = feed.pushToFeed(group.id, item["meta"]["uuid"], itemId,
                         itemId, responseType, itemType, user.id)
    d3 = feed.pushToOthersFeed(user.id, user.basic['org'],
                                item["meta"]["uuid"], itemId, itemId,
                                _acl, responseType, itemType,
                                user.id, promoteActor=False)

    yield defer.DeferredList([d1, d2, d3])
Exemplo n.º 7
0
    def create(self, request, me, convId, richText=False):
        startDate = utils.getRequestArg(request, 'startDate')
        endDate = utils.getRequestArg(request, 'endDate')
        title = utils.getRequestArg(request, 'title')
        desc = utils.getRequestArg(request, 'desc')
        location = utils.getRequestArg(request, 'location')
        allDay = utils.getRequestArg(request, "allDay")
        acl = utils.getRequestArg(request, "acl", sanitize=False)
        isPrivate = utils.getRequestArg(request, "isPrivate")

        if not ((title or desc) and startDate and endDate):
            raise errors.MissingParams([_('Title'), _('Start date'), _('End date')])

        if startDate.isdigit() and endDate.isdigit():
            startDate = int(startDate)/1000
            endDate = int(endDate)/1000
        else:
            raise errors.InvalidRequest("Invalid start or end dates")

        if endDate < startDate:
            raise errors.InvalidRequest("Event end date is set in the past")

        # Parse invitees from the tag edit plugin values
        arg_keys = request.args.keys()
        invitees = []
        for arg in arg_keys:
            if arg.startswith("invitee[") and arg.endswith("-a]"):
                rcpt = arg.replace("invitee[", "").replace("-a]", "")
                if rcpt != "":
                    invitees.append(rcpt)
        # The owner is always invited to the event
        invitees.append(me.id)

        meta = {"event_startTime": str(startDate), "event_endTime": str(endDate)}

        if title:
            meta["event_title"] = title
        if desc:
            meta["event_desc"] = desc
        if location:
            meta["event_location"] = location
        if allDay:
            meta["event_allDay"] = '1'
        else:
            meta["event_allDay"] = '0'

        # Check if the invited user ids are valid
        res = base.EntitySet(invitees)
        yield res.fetchData()
        invitees = [x for x in res.keys() if res[x].basic["org"] == me.basic['org']]

        # Modify the received ACL to include those who were invited including
        # the owner of this item.
        acl = json.loads(acl)
        acl.setdefault("accept", {})
        acl["accept"].setdefault("users", [])
        acl["accept"]["users"].extend(invitees)
        acl = json.dumps(acl)
        item = yield utils.createNewItem(request, self.itemType, me,
                                         richText=richText, acl=acl)

        item["meta"].update(meta)
        item["invitees"] = dict([(x, me.id) for x in invitees])

        starttimeUUID = utils.uuid1(timestamp=startDate)
        starttimeUUID = starttimeUUID.bytes

        endtimeUUID = utils.uuid1(timestamp=endDate)
        endtimeUUID = endtimeUUID.bytes

        yield self.inviteUsers(request, starttimeUUID, endtimeUUID, convId,
                                        item["meta"], me.id, me.basic['org'],
                                                                invitees, acl)
        defer.returnValue(item)
Exemplo n.º 8
0
    def postFeedback(self, request):
        """creates a feedback item with feedback, feedback-{mood} tags.
        Push item to feeback, feedback-{mood} tag followers.
        Note: Item is owned by feedback-domain/synovel.com, not user sending
        the feedback. Only users of feedback-domain/synovel.com can access
        the item.
        """
        comment = utils.getRequestArg(request, 'comment')
        mood = utils.getRequestArg(request, 'mood')
        if not mood or not comment:
            raise errors.MissingParams([_("Feedback")])

        authInfo = request.getSession(IAuthInfo)
        myId = authInfo.username
        orgId = authInfo.organization

        tagName = 'feedback'
        moodTagName = 'feedback-' + mood

        feedbackDomain = config.get('Feedback', 'Domain') or 'synovel.com'
        cols = yield db.get_slice(feedbackDomain, 'domainOrgMap')
        if not cols:
            raise errors.ConfigurationError("feedbackDomain is invalid!")

        # Only one org exists per domain
        synovelOrgId = cols[0].column.name

        tagId, tag = yield tags.ensureTag(request, tagName, synovelOrgId)
        moodTagId, moodTag = yield tags.ensureTag(request, moodTagName,
                                                  synovelOrgId)

        # Anyone in synovel can receive feedback.
        acl = {'accept': {'orgs': [synovelOrgId]}}
        acl = json.dumps(acl)
        synovelOrg = base.Entity(synovelOrgId)
        yield synovelOrg.fetchData()
        # createNewItem expects an entity object with has org in basic info.
        # organizations wont have 'org' set.
        synovelOrg.basic['org'] = synovelOrgId

        item = yield utils.createNewItem(request, 'feedback', synovelOrg,
                                         acl, subType=mood)
        item['meta']['org'] = synovelOrgId
        item['meta']['userId'] = myId
        item['meta']['userOrgId'] = orgId
        item['meta']['comment'] = comment
        item['tags'] = {tagId: synovelOrgId, moodTagId: synovelOrgId}

        itemId = utils.getUniqueKey()

        tagItemCount = int(tag['itemsCount'])
        moodTagItemCount = int(moodTag['itemsCount'])
        if tagItemCount % 10 == 7:
            tagItemCount = yield db.get_count(tagId, "tagItems")
        if moodTagItemCount % 10 == 7:
            moodTagItemCount = yield db.get_count(moodTagId, "tagItems")

        tagItemCount += 1
        moodTagItemCount += 1

        # Finally save the feedback
        yield db.batch_insert(itemId, "items", item)
        yield db.insert(tagId, "tagItems", itemId, item["meta"]["uuid"])
        yield db.insert(moodTagId, "tagItems", itemId, item["meta"]["uuid"])
        yield db.insert(synovelOrgId, "orgTags", str(tagItemCount),
                        "itemsCount", tagId)
        yield db.insert(synovelOrgId, "orgTags", str(moodTagItemCount),
                        "itemsCount", moodTagId)

        cols = yield db.multiget_slice([tagId, moodTagId], "tagFollowers")
        followers = utils.multiColumnsToDict(cols)
        followers = set(followers[tagId].keys() + followers[moodTagId].keys())

        value = {"feed": {item['meta']['uuid']: itemId}}
        muts = dict([(x, value) for x in followers])
        if muts:
            yield db.batch_mutate(muts)