Example #1
0
def removeAdmin(group, user, me):
    """strip admin privileges of user.
    Throw an error if @me is not group-admin or is the only admin and
    trying to removing self.
    Raise an exception when user is not a group-memeber or not a group-admin.

    Keyword params:
    @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'))
    if me.id == user.id and len(group.admins.keys()) == 1:
        raise errors.InvalidRequest(_('You are the only administrator of the group'))

    cols = yield db.get_slice(group.id, "groupMembers", [user.id])
    if not cols:
        raise errors.InvalidRequest(_("User is not a member of the group"))

    if user.id not in group.admins:
        raise errors.InvalidRequest(_('User is not administrator of the group'))

    yield db.remove(group.id, "entities", user.id, "admins")
    yield db.remove(user.id, "entities", group.id, "adminOfGroups")
Example #2
0
def getValidEntityId(request, arg, type="user", columns=None):
    entityId = getRequestArg(request, arg, sanitize=False)
    if not entityId:
        raise errors.MissingParams([_("%s id") % _(type).capitalize()])

    if not columns:
        columns = []
    columns.extend(["basic"])

    entity = yield db.get_slice(entityId, "entities", columns)
    if not entity:
        raise errors.InvalidEntity(type, entityId)

    entity = supercolumnsToDict(entity)
    basic = entity["basic"]

    if type != basic["type"]:
        raise errors.InvalidEntity(type, entityId)

    authinfo = request.getSession(IAuthInfo)
    myOrgId = authinfo.organization
    org = basic["org"] if basic["type"] != "org" else entityId
    if myOrgId != org:
        raise errors.EntityAccessDenied(type, entityId)
    defer.returnValue((entityId, entity))
Example #3
0
    def _invite(self, request):
        src = utils.getRequestArg(request, 'from') or None
        rawEmailIds = request.args.get('email')
        stats = yield invite(request, rawEmailIds)

        if not src:
            src = "sidebar" if len(rawEmailIds) == 1 else "people"
        if src == "sidebar" and self._ajax:
            request.write("$('#invite-others').val('');")
        elif src == "sidebar":
            request.redirect('/feed/')
        elif src == "people" and self._ajax:
            pass
        elif src == "people":
            request.redirect('/people')
        if not stats and self._ajax:
            request.write("$$.alerts.error('%s');" \
                            % (_("Use company email addresses only.")))
        elif stats and self._ajax:
            if len(stats[0]) == 1:
                request.write("$$.alerts.info('%s');" % _("Invitation sent"))
                request.write("$$.dialog.close('invitepeople-dlg', true);")
            elif len(stats[0]) > 1:
                request.write("$$.alerts.info('%s');" % _("Invitations sent"))
                request.write("$$.dialog.close('invitepeople-dlg', true);")
            else:
                #TODO: when user tries to send invitations to existing members,
                #      show these members as add-as-friend/follow list
                request.write("$$.alerts.info('%s');\
                               $$.dialog.close('invitepeople-dlg', true);" \
                               % _("Invitations sent"))
Example #4
0
def untag(itemId, item, tagId, tag, myId, orgId):
    if "parent" in item:
        raise errors.InvalidRequest(_("Tags cannot be applied or removed from comments"))

    if tagId not in item.get("tags", {}):
        raise errors.InvalidRequest(_("No such tag on the item"))  # No such tag on item

    d1 = db.remove(itemId, "items", tagId, "tags")
    d2 = db.remove(tagId, "tagItems", item["meta"]["uuid"])
    d3 = db.get_slice(tagId, "tagFollowers")

    try:
        itemsCountCol = yield db.get(orgId, "orgTags", "itemsCount", tagId)
        tagItemsCount = int(itemsCountCol.column.value) - 1
        if tagItemsCount % 10 == 7:
            tagItemsCount = yield db.get_count(tagId, "tagItems")
            tagItemsCount = tagItemsCount - 1
        db.insert(orgId, "orgTags", "%s" % tagItemsCount, "itemsCount", tagId)
    except ttypes.NotFoundException:
        pass
    result = yield defer.DeferredList([d1, d2, d3])
    followers = utils.columnsToDict(result[2][1]).keys()


    feedUpdateVal = "T:%s:%s::%s" % (myId, itemId, tagId)
    yield Feed.unpush(myId, orgId, itemId, item,
                      feedUpdateVal, followers + [myId])
Example #5
0
    def _attendance(self, request):
        itemId, item = yield utils.getValidItemId(request, "id",
                                                  columns=["invitees"])
        list_type = utils.getRequestArg(request, 'type') or "yes"
        user_list = []

        if itemId and list_type in ["yes", "no", "maybe"]:
            cols = yield db.get_slice(itemId, "eventResponses")
            res = utils.columnsToDict(cols)
            for rsvp in res.keys():
                resp = rsvp.split(":")[0]
                uid = rsvp.split(":")[1]
                if resp == list_type:
                    if uid in item["invitees"] and \
                      item["invitees"][uid] == list_type:
                        user_list.insert(0, uid)
                    else:
                        user_list.append(uid)

            invited = user_list
            owner = item["meta"].get("owner")

            entities = base.EntitySet(invited+[owner])
            yield entities.fetchData()

            args = {"users": invited, "entities": entities}
            args['title'] = {"yes":_("People attending this event"),
                             "no": _("People not attending this event"),
                             "maybe": _("People who may attend this event")
                             }[list_type]

            t.renderScriptBlock(request, "item.mako", "userListDialog", False,
                                    "#invitee-dlg-%s"%(itemId), "set", **args)
Example #6
0
def delete(itemId, item, myId, orgId):
    convId = item["meta"].get("parent", itemId)
    itemOwnerId = item["meta"]["owner"]

    if itemId == convId:
        conv = item
        convOwnerId = itemOwnerId
    else:
        conv = yield db.get_slice(convId, "items", ["meta", "tags"])
        conv = utils.supercolumnsToDict(conv)
        if not conv:
            raise errors.InvalidRequest(_('Conversation does not exist!'))

        convOwnerId = conv["meta"]["owner"]

    # TODO: Admin actions.
    # Do I have permission to delete the comment
    if (itemOwnerId != myId and convOwnerId != myId):
        raise errors.PermissionDenied(_("You must either own the comment or the conversation to delete this comment"))

    deferreds = []
    convType = conv["meta"].get('type', 'status')
    convACL = conv["meta"]["acl"]
    timestamp = str(int(time.time()))
    itemUUID = item["meta"]["uuid"]

    # The conversation is lazy deleted.
    # If it is the comment being deleted, rollback all feed updates
    # that were made due to this comment and likes on this comment.
    d = deleteItem(itemId, myId, orgId, item, conv)
    deferreds.append(d)

    yield defer.DeferredList(deferreds)
    defer.returnValue(conv)
Example #7
0
    def renderFeedSideBlock(self, request, landing, entityId, args):
        authinfo = request.getSession(IAuthInfo)
        myId = authinfo.username
        myOrgId = authinfo.organization
        groupId = args["groupId"] if "groupId" in args else None

        if entityId == myOrgId:
            args["title"] = _("Company Wide Events")
            yield event.fetchMatchingEvents(request, args, myOrgId)
            t.renderScriptBlock(request, "event.mako", "side_agenda",
                                   landing, "#feed-side-block-container",
                                   "append", **args)
        elif entityId == myId:
            args["title"] = _("My Upcoming Events")
            yield event.fetchMatchingEvents(request, args, myId)
            t.renderScriptBlock(request, "event.mako", "side_agenda",
                                   landing, "#feed-side-block-container",
                                   "append", **args)
        elif entityId == groupId:
            args["title"] = _("Group Agenda")
            groupId = args["groupId"]
            yield event.fetchMatchingEvents(request, args, groupId)
            t.renderScriptBlock(request, "event.mako", "side_agenda",
                                   landing, "#feed-side-block-container",
                                   "append", **args)
Example #8
0
def tag(itemId, item, tagName, myId, orgId):
    if "parent" in item["meta"]:
        raise errors.InvalidRequest(_("Tag cannot be applied on a comment"))

    (tagId, tag) = yield tags._ensureTag(tagName, myId, orgId)
    if tagId in item.get("tags", {}):
        raise errors.InvalidRequest(_("Tag already exists on the choosen item"))

    d1 = db.insert(itemId, "items", myId, tagId, "tags")
    d2 = db.insert(tagId, "tagItems", itemId, item["meta"]["uuid"])
    d3 = db.get_slice(tagId, "tagFollowers")

    tagItemsCount = int(tag.get("itemsCount", "0")) + 1
    if tagItemsCount % 10 == 7:
        tagItemsCount = yield db.get_count(tagId, "tagItems")
        tagItemsCount += 1
    db.insert(orgId, "orgTags", "%s" % tagItemsCount, "itemsCount", tagId)

    result = yield defer.DeferredList([d1, d2, d3])
    followers = utils.columnsToDict(result[2][1]).keys()

    if followers:
        timeUUID = uuid.uuid1().bytes
        feedUpdateVal = "T:%s:%s::%s" % (myId, itemId, tagId)
        yield Feed.push(myId, orgId, itemId, item, timeUUID,
                        feedUpdateVal, feeds=followers)

    defer.returnValue((tagId, tag))
Example #9
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)
Example #10
0
    def _likes(self, request, data=None):
        itemId, item = data['id']
        entities, users = yield Item.likes(itemId, item)
        args = {"users": users, "entities": entities}
        if not users:
            raise errors.InvalidRequest(_("Currently, no one likes the item"))
        itemType = item['meta'].get('type', 'comment')
        ownerId = item["meta"]["owner"]
        args['title'] = _("People who like %s's %s") %\
                          (utils.userName(ownerId, entities[ownerId]), _(itemType))

        t.renderScriptBlock(request, "item.mako", "userListDialog", False,
                            "#likes-dlg-%s" % (itemId), "set", **args)
Example #11
0
def createNewItem(request, itemType, owner, acl=None, subType=None, groupIds=None, richText=False):
    if not acl:
        acl = getRequestArg(request, "acl", sanitize=False)

    try:
        acl = json.loads(acl)
        orgs = acl.get("accept", {}).get("orgs", [])
        if len(orgs) > 1 or (len(orgs) == 1 and orgs[0] != owner.basic["org"]):
            msg = "Cannot grant access to other orgs on this item"
            raise errors.PermissionDenied(_(msg))
    except:
        acl = {"accept": {"orgs": [owner.basic["org"]]}}

    accept_groups = acl.get("accept", {}).get("groups", [])
    deny_groups = acl.get("deny", {}).get("groups", [])
    groups = [x for x in accept_groups if x not in deny_groups]
    if groups:
        relation = Relation(owner.id, [])
        yield relation.initGroupsList()
        if not all([x in relation.groups for x in groups]):
            msg = "Only group members can post to a group"
            raise errors.PermissionDenied(_(msg))

    acl = pickle.dumps(acl)
    item = {
        "meta": {
            "acl": acl,
            "org": owner.basic["org"],
            "type": itemType,
            "uuid": uuid.uuid1().bytes,
            "owner": owner.id,
            "timestamp": str(int(time.time())),
            "richText": str(richText),
        },
        "followers": {owner.id: ""},
    }
    if subType:
        item["meta"]["subType"] = subType
    if groups:
        item["meta"]["target"] = ",".join(groups)

    tmpFileIds = getRequestArg(request, "fId", False, True)
    attachments = {}
    if tmpFileIds:
        attachments = yield _upload_files(owner.id, tmpFileIds)
        if attachments:
            item["attachments"] = {}
            for attachmentId in attachments:
                fileId, name, size, ftype = attachments[attachmentId]
                item["attachments"][attachmentId] = "%s:%s:%s" % (name, size, ftype)
    defer.returnValue(item)
Example #12
0
def block(group, user, me):
    """Block user from joining a group/ sending further group-join requests.

    Keyword params:
    @me: entity object with my info
    @user: entity object of the user
    @group: entity object of the group
    """
    if me.id not in group.admins:
        raise errors.PermissionDenied('Access Denied')

    if me.id == user.id:
        raise errors.InvalidRequest(_("An administrator cannot ban himself/herself from the group"))
    try:
        yield db.get(group.id, "pendingConnections", "GI:%s" % (user.id))
        yield _removeFromPending(group, user)
        # Add user to blocked users
        yield db.insert(group.id, "blockedUsers", '', user.id)
        defer.returnValue(True)

    except ttypes.NotFoundException:
        # If the users is already a member, remove the user from the group
        colname = _entityGroupMapColName(group)
        yield db.remove(group.id, "groupMembers", user.id)
        yield db.remove(group.id, "followers", user.id)
        yield db.remove(user.id, "entityGroupsMap", colname)
        # Add user to blocked users
        yield db.insert(group.id, "blockedUsers", '', user.id)
        defer.returnValue(False)
Example #13
0
    def _create(self, request, data=None):
        authInfo = request.getSession(IAuthInfo)
        myId = authInfo.username

        name = data['name']
        description = data['desc']
        access = data['access']
        dp = data['dp']
        me = base.Entity(myId)
        yield me.fetchData()
        try:
            yield Group.create(request, me, name, access, description, dp)
        except errors.InvalidGroupName as e:
            request.write("<script> parent.$$.alerts.error('Group with same name already exists.'); </script>")
            raise e

        response = """
                    <script>
                        parent.$$.alerts.info('%s');
                        parent.$.get('/ajax/notifications/new');
                        parent.$$.fetchUri('/groups');
                        parent.$$.dialog.close('addgroup-dlg', true);
                    </script>
                   """ % (_("Group Created"))
        request.write(response)
Example #14
0
def getValidItemId(request, arg, type=None, columns=None, itemId=None, myOrgId=None, myId=None):
    if not itemId:
        itemId = getRequestArg(request, arg, sanitize=False)
    itemType = type if type else "item"
    if not itemId:
        raise errors.MissingParams([_("%s id") % _(itemType).capitalize()])

    columns = [] if not columns else columns
    columns.extend(["meta", "attachments"])

    item = yield db.get_slice(itemId, "items", columns)
    if not item:
        raise errors.InvalidItem(itemType, itemId)

    item = supercolumnsToDict(item)
    meta = item["meta"]

    if type and meta["type"] != type:
        raise errors.InvalidItem(itemType, itemId)

    parentId = meta.get("parent", None)
    if parentId:
        parent = yield db.get_slice(parentId, "items", ["meta"])
        parent = supercolumnsToDict(parent)
        acl = parent["meta"]["acl"]
        owner = parent["meta"]["owner"]
        deleted = parent["meta"].get("state", None) == "deleted"
    else:
        parent = item
        acl = meta["acl"]
        owner = meta["owner"]
        deleted = parent["meta"].get("state", None) == "deleted"

    if deleted:
        raise errors.InvalidItem(itemType, itemId)

    if not myOrgId:
        myOrgId = request.getSession(IAuthInfo).organization
    if not myId:
        myId = request.getSession(IAuthInfo).username

    relation = Relation(myId, [])
    yield relation.initGroupsList()
    if not checkAcl(myId, myOrgId, False, relation, parent["meta"]):
        raise errors.ItemAccessDenied(itemType, itemId)

    defer.returnValue((itemId, item))
Example #15
0
    def _changePassword(self, request):
        (appchange, script, args, myId) = yield self._getBasicArgs(request)

        currentPass = utils.getRequestArg(request, "curr_passwd", sanitize=False)
        newPass = utils.getRequestArg(request, "passwd1", sanitize=False)
        rptPass = utils.getRequestArg(request, "passwd2", sanitize=False)

        if not currentPass:
            request.write('$$.alerts.error("%s");' % _("Enter your current password"))
            defer.returnValue(None)
        if not newPass:
            request.write('$$.alerts.error("%s");' % _("Enter new password"))
            defer.returnValue(None)
        if not rptPass:
            request.write('$$.alerts.error("%s");' % _("Confirm new password"))
            defer.returnValue(None)
        if newPass != rptPass:
            request.write('$$.alerts.error("%s");' % _("Passwords do not match"))
            defer.returnValue(None)
        if currentPass == newPass:
            request.write('$$.alerts.error("%s");' % _("New password should be different from current password"))
            defer.returnValue(None)

        emailId = args["me"].basic["emailId"]
        col = yield db.get(emailId, "userAuth", "passwordHash")
        storedPass= col.column.value

        if not utils.checkpass(currentPass, storedPass):
            request.write('$$.alerts.error("%s");' % _("Incorrect Password"))
            defer.returnValue(None)

        newPasswd = utils.hashpass(newPass)
        yield db.insert(emailId, "userAuth", newPasswd, "passwordHash")
        request.write('$$.alerts.info("%s");' % _('Password changed'))
Example #16
0
    def _editWorkInfo(self, request):
        # Contact information at work.
        myId = request.getSession(IAuthInfo).username
        orgId = request.getSession(IAuthInfo).organization

        me = base.Entity(myId)
        yield me.fetchData([])
        data = {}
        to_remove = []

        for field in ["phone", "mobile"]:
            val = utils.getRequestArg(request, field)
            if val:
                data[field] = val
            else:
                to_remove.append(field)

        if 'phone' in data and not re.match('^\+?[0-9x\- ]{5,20}$', data['phone']):
            raise errors.InvalidRequest(_('Phone numbers can only have numerals, hyphens, spaces and a plus sign'))

        if 'mobile' in data and not re.match('^\+?[0-9x\- ]{5,20}$', data['mobile']):
            raise errors.InvalidRequest(_('Phone numbers can only have numerals, hyphens, spaces and a plus sign'))

        if data:
            yield db.batch_insert(myId, "entities", {"contact": data})
        if to_remove:
            yield db.batch_remove({"entities":[myId]}, names=to_remove, supercolumn='contact')

        contactInfo = me.get('contact', {})
        if any([contactInfo.get(x, None) != data.get(x, None) for x in ["phone", "mobile"]]):
            request.write('$$.alerts.info("%s");' % _('Profile updated'))

        args = {"detail": "", "me": me}
        suggestedSections = yield self._checkProfileCompleteness(request, myId, args)
        tmp_suggested_sections = {}
        for section, items in suggestedSections.iteritems():
            if len(suggestedSections[section]) > 0:
                tmp_suggested_sections[section] = items
        args.update({'suggested_sections':tmp_suggested_sections})

        t.renderScriptBlock(request, "settings.mako", "right",
                            False, ".right-contents", "set", **args)
        me.update({'contact':data})
        yield search.solr.updatePeopleIndex(myId, me, orgId)
Example #17
0
    def _render(self, request, viewType, start):
        (appchange, script, args, myId) = yield self._getBasicArgs(request)
        landing = not self._ajax

        orgId = args["orgId"]
        args["entities"] = {}
        args["menuId"] = "people"

        if script and landing:
            t.render(request, "people.mako", **args)

        if script and appchange:
            t.renderScriptBlock(request, "people.mako", "layout",
                                landing, "#mainbar", "set", **args)

        d = None
        if viewType == "all":
            d = getPeople(myId, orgId, orgId, start=start, fetchBlocked=False)
        elif viewType == "invitations":
            d = _getInvitationsSent(myId, start=start)
        else:
            raise errors.InvalidRequest(_("Unknown view type"))

        sentInvitationsCount = yield db.get_count(myId, "invitationsSent")

        if viewType == 'all':
            users, relations, userIds,\
                blockedUsers, nextPageStart, prevPageStart = yield d

            # First result tuple contains the list of user objects.
            args["entities"] = users
            args["relations"] = relations
            args["people"] = userIds
        elif viewType == 'invitations':
            emailIds, prevPageStart, nextPageStart = yield d
            args['emailIds'] = emailIds

        # display the invitations tab only when there are invitations sent or
        # when user explicitly checks for viewType "invitations"
        showInvitationsTab = sentInvitationsCount > 0 or viewType == 'invitations'
        args["nextPageStart"] = nextPageStart
        args["prevPageStart"] = prevPageStart
        args["viewType"] = viewType
        args['showInvitationsTab'] = showInvitationsTab

        if script:
            t.renderScriptBlock(request, "people.mako", "viewOptions",
                                landing, "#people-view", "set", args=[viewType],
                                showInvitationsTab=showInvitationsTab)
            t.renderScriptBlock(request, "people.mako", "listPeople",
                                landing, "#users-wrapper", "set", **args)
            t.renderScriptBlock(request, "people.mako", "paging",
                                landing, "#people-paging", "set", **args)

        if not script:
            t.render(request, "people.mako", **args)
Example #18
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])
Example #19
0
    def _addKeywords(self, request):
        orgId = request.getSession(IAuthInfo).organization
        original = utils.getRequestArg(request, 'keywords', sanitize=False)
        if not original:
            return

        original = original.split(',')
        decoded = set([x.decode('utf-8', 'replace').strip() for x in original])

        # Check if any word is longer than 50 chars
        decoded = set([x for x in decoded if len(x) < 50])
        if len(decoded) != len(original):
            raise errors.InvalidRequest(_('Keywords cannot be more than 50 characters long'))

        # Check if any word has invalid characters
        decoded = set([x for x in decoded if regex.match('^[\w-]*$', x)])
        if len(decoded) != len(original):
            raise errors.InvalidRequest(_('Keywords can only include numerals, alphabet and hyphens (-)'))

        # Convert to lower case
        decoded = set([x.lower() for x in decoded])

        # Remove stopwords
        keywords = set([x.encode('utf-8') for x in decoded\
                        if x not in stopwords.words()])

        # After all this if we still have words, add them to database
        if keywords:
            for keyword in keywords:
                yield db.insert(orgId, "keywords", '', keyword)
                yield db.insert(orgId, "originalKeywords", '', keyword)

            keywords = yield db.get_slice(orgId, "originalKeywords", count=100)
            keywords = utils.columnsToDict(keywords, ordered=True)
            args = {'keywords': keywords}

            t.renderScriptBlock(request, "admin.mako", "listKeywords",
                                    False, "#content", "set", **args)

        # We may want to display an error when we removed stopwords.
        if len(keywords) < len(decoded):
            pass
Example #20
0
def decodeKey(key):
    if not key.startswith("xX"):
        return key

    length = len(key) - 2
    try:
        decoded_key = base64.urlsafe_b64decode(key[2:] + ((length % 4) * "="))
    except TypeError:
        raise errors.InvalidRequest(_("Invalid Key"))
    else:
        return decoded_key
Example #21
0
    def _newItem(self, request):
        token = self._ensureAccessScope(request, 'post-item')
        authInfo = utils.AuthInfo()
        authInfo.username = token.user
        authInfo.organization = token.org
        convType = 'status'

        convId, conv, keywords = yield Item.new(request, authInfo, convType, richText=True)
        if keywords:
            raise errors.InvalidRequest(_('Matching keywords found(%s). Set reportOK=1.') % ', '.join(keywords))
        else:
            self._success(request, 201, {'id': convId})
Example #22
0
def getValidTagId(request, arg):
    tagId = getRequestArg(request, arg, sanitize=False)
    if not tagId:
        raise errors.MissingParams([_("Tag id")])

    orgId = request.getSession(IAuthInfo).organization
    tag = yield db.get_slice(orgId, "orgTags", [tagId])
    if not tag:
        raise errors.InvalidTag(tagId)

    tag = supercolumnsToDict(tag)
    defer.returnValue((tagId, tag))
Example #23
0
    def _signupGotUserData(self, request):
        authinfo = yield defer.maybeDeferred(request.getSession, IAuthInfo)
        if authinfo.username:
            raise errors.InvalidRequest(_("Another user is currently signed-in.  Please signout and then click the invitation link"))

        emailId = utils.getRequestArg(request, "email")
        token = utils.getRequestArg(request, "token")

        valid = yield self._isValidToken(emailId, token)
        if not valid:
            raise InvalidRegistration("The invite is not valid anymore.  Already registered?")

        yield self._addUser(request)
Example #24
0
    def _updateNotifications(self, request):
        authinfo = request.getSession(IAuthInfo)
        myId = authinfo.username
        getArg = utils.getRequestArg
        def _get(typ):
            val = getArg(request, typ)
            try:
                return val if (0 < int(val) <= 3) else '0'
            except (ValueError,TypeError):
                return '0'

        prefVal = ''.join([_get(x) for x in _notifyNames])
        yield db.insert(myId, 'entities', prefVal, 'notify', 'basic')
        request.write('$$.alerts.info("%s");' % _('Preferences saved'))
Example #25
0
    def _signupCheckToken(self, request):
        authinfo = yield defer.maybeDeferred(request.getSession, IAuthInfo)
        if authinfo.username:
            raise errors.InvalidRequest(_("Another user is currently signed-in.  Please signout and then click the invitation link"))

        emailId = utils.getRequestArg(request, "email")
        token = utils.getRequestArg(request, "token")

        valid = yield self._isValidToken(emailId, token)
        if not valid:
            raise InvalidRegistration("The invite is not valid anymore.  Already registered?")

        args = {'emailId': emailId, 'token': token, 'view': 'userinfo'}
        t.render(request, "signup.mako", **args)
Example #26
0
    def _renderReportDialog(self, request):
        authinfo = request.getSession(IAuthInfo)
        myId = authinfo.username
        myOrgId = authinfo.organization
        itemId, item = yield utils.getValidItemId(request, "id")
        args = {}

        itemType = item["meta"].get("type")

        args['title'] = _("Report this %s") % itemType
        args['convId'] = itemId

        t.renderScriptBlock(request, "item-report.mako", "report_dialog", False,
                            "#report-dlg-%s" % (itemId), "set", **args)
Example #27
0
    def _deleteUser(self, request, data=None):
        myId = request.getSession(IAuthInfo).username
        user = data['id']
        delete = data['deleted'] == 'deleted'

        # Admin cannot block himself.
        if user.id == myId:
            raise errors.InvalidRequest(_("You are the only administrator, you can not delete yourself"))

        if delete:
            yield utils.removeUser(request, user.id, myId, user)
            t.renderScriptBlock(request, "admin.mako", "admin_actions",
                                    False, "#user-actions-%s" % (user.id),
                                    "set", args=[user.id, 'deleted'])
Example #28
0
    def _listVoters(self, request):
        convId, item = yield utils.getValidItemId(request, "id", "poll", ["options"])

        option = utils.getRequestArg(request, "option")
        if not option or option not in item.get("options", {}):
            raise errors.MissingParams([_('Option')])

        votes = yield db.get_slice(convId, "votes", [option])
        votes = utils.supercolumnsToDict(votes)
        voters = set()
        if votes:
            for option in votes:
                voters.update(votes[option].keys())

        args = {'entities': {}, 'users': voters}
        args['title'] = _('List of people who voted for "%s"')\
                                                    % item["options"][option]
        if voters:
            people = base.EntitySet(voters)
            yield people.fetchData()
            args['entities'] = people

        t.renderScriptBlock(request, "item.mako", "userListDialog", False,
                            "#poll-users-%s-%s" % (option, convId), "set", **args)
Example #29
0
    def _members(self, request):
        """Allow a participant of a conversation to add or remove another user
        to the conversation.

        Keyword arguments:
        action: Either one of [add, remove]
        convId: The conversation to which this user wants to either add or
            remove another user.

        """
        (appchange, script, args, myId) = yield self._getBasicArgs(request)
        landing = not self._ajax
        action = utils.getRequestArg(request, "action")
        convId = utils.getRequestArg(request, 'parent') or None

        if not convId:
            raise errors.MissingParams([_('Conversation Id')])
        if action not in ('add', 'remove'):
            raise errors.InvalidRequest()

        if action == "add":
            yield self._addMembers(request)
        elif action == "remove":
            yield self._removeMembers(request)

        cols = yield db.get_slice(convId, "mConversations")
        conv = utils.supercolumnsToDict(cols)
        participants = set(conv['participants'])
        people = base.EntitySet(participants)
        yield people.fetchData()

        args.update({"people": people})
        args.update({"conv": conv})
        args.update({"id": convId})
        args.update({"view": "message"})
        if script:
            onload = """
                     $('#conversation_add_member').autocomplete({
                           source: '/auto/users',
                           minLength: 2,
                           select: function( event, ui ) {
                               $('#conversation_recipients').attr('value', ui.item.uid)
                           }
                      });
                     """
            t.renderScriptBlock(request, "message.mako", "right",
                                landing, ".right-contents", "set", True,
                                handlers={"onload": onload}, **args)
Example #30
0
def simpleTimestamp(timestamp, timezone="Asia/Kolkata"):
    tzinfo = gettz(timezone)
    if not tzinfo:
        tzinfo = gettz("Asia/Kolkata")

    current = datetime.datetime.now(tzinfo)
    ts = datetime.datetime.fromtimestamp(timestamp, tzinfo)
    delta = current - ts

    # Map used for localization
    params = {
        "minutes": ts.minute,
        "24hour": ts.hour,
        "12hour": 12 if not (ts.hour % 12) else (ts.hour % 12),
        "month": _(monthName(ts.month, True)),
        "year": ts.year,
        "ampm": "am" if ts.hour <= 11 else "pm",
        "dow": _(weekName(ts.weekday(), True)),
        "date": ts.day,
    }
    tooltip = _("%(dow)s, %(month)s %(date)s, %(year)s at %(12hour)s:%(minutes)02d%(ampm)s") % params

    if delta < datetime.timedelta(days=1):
        if delta.seconds < 60:
            formatted = _("a few seconds ago")
        elif delta.seconds < 3600:
            formatted = _("%s minutes ago") % (delta.seconds / 60)
        elif delta.seconds < 7200:
            formatted = _("about one hour ago")
        else:
            formatted = _("%s hours ago") % (delta.seconds / 3600)
    else:
        if current.year == ts.year:
            formatted = _("%(month)s %(date)s at %(12hour)s:%(minutes)02d%(ampm)s") % params
        else:
            formatted = _("%(month)s %(date)s, %(year)s at %(12hour)s:%(minutes)02d%(ampm)s") % params

    return "<abbr class='timestamp' title='%s' data-ts='%s'>%s</abbr>" % (tooltip, timestamp, formatted)