Example #1
0
    def _vote(self, request):
        convId, conv = yield utils.getValidItemId(request, 'id', 'poll', ['options'])
        vote = utils.getRequestArg(request, 'option')
        if not vote or vote not in conv.get("options", {}):
            raise errors.MissingParams(["Option"])

        optionCounts = {}
        myId = request.getSession(IAuthInfo).username

        prevVote = yield db.get_slice(myId, "userVotes", [convId])
        prevVote = prevVote[0].column.value if prevVote else False
        if prevVote == vote:
            yield self._results(request)
            return

        if prevVote:
            yield db.remove(convId, "votes", myId, prevVote)
            prevOptionCount = yield db.get_count(convId, "votes", prevVote)
            optionCounts[prevVote] = str(prevOptionCount)

        yield db.insert(myId, "userVotes", vote, convId)
        yield db.insert(convId, "votes",  '', myId, vote)

        voteCount = yield db.get_count(convId, "votes", vote)
        optionCounts[vote] = str(voteCount)

        yield db.batch_insert(convId, "items", {"counts": optionCounts})
        yield self._results(request)
Example #2
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 #3
0
    def _listFileVersions(self, request):
        authinfo = request.getSession(IAuthInfo)
        myId = authinfo.username
        myOrgId = authinfo.organization
        relation = Relation(myId, [])

        attachmentId = utils.getRequestArg(request, "fid", sanitize=False)
        itemId, item = yield utils.getValidItemId(request, 'id')

        if not attachmentId:
            raise errors.MissingParams()

        # Check if the attachmentId belong to item
        if attachmentId not in item.get('attachments', {}).keys():
            version = None
            raise errors.AttachmentAccessDenied(itemId, attachmentId, version)

        #get the latest file
        files = []
        cols = yield db.get_slice(attachmentId, "attachmentVersions", reverse=True)
        cols = utils.supercolumnsToDict(cols)
        for attachmentId in cols:
            fileId, ftype, name = None, 'text/plain', 'file'
            for tuuid in cols[attachmentId]:
                fileId, name, size, ftype = cols[attachmentId][tuuid].split(':')
                files.append([itemId, attachmentId, name, size, ftype])
        ##TODO: use some widget to list the files
        request.write(json.dumps(files))
Example #4
0
    def _removeKeywordMatched(self, request):
        orgId = request.getSession(IAuthInfo).organization
        (itemId, item) = yield utils.getValidItemId(request, 'id',
                                                    columns=['tags'])
        yield deleteItem(request, itemId, orgId, item)

        # Update the UI
        request.write("$$.convs.remove('%s');" % itemId)
Example #5
0
    def _ignoreKeywordMatched(self, request):
        orgId = request.getSession(IAuthInfo).organization
        keyword = utils.getRequestArg(request, "keyword")
        (itemId, item) = yield utils.getValidItemId(request, 'id')

        # Remove this item from this list of keywordItems.
        timeUUID = item["meta"]["uuid"]
        yield db.remove(orgId + ":" + keyword, "keywordItems", timeUUID)

        # Update the UI
        request.write("$$.convs.remove('%s');" % itemId)
Example #6
0
 def _link(self, request):
     itemId, item = yield utils.getValidItemId(request, "id", "link")
     meta = item.get("meta", {})
     embedType = meta.get("link_embedType", "") or meta.get("embedType", "")
     embedSrc = meta.get("link_embedSrc", "") or meta.get("embedSrc", "")
     if embedSrc:
         if embedType == "photo":
             src = '<img src="%s"></img>' % embedSrc
         elif embedType in ["video", "audio"]:
             src = embedSrc
         if src:
             request.write(self._template % src)
Example #7
0
    def _change(self, request):
        convId, conv = yield utils.getValidItemId(request, "id", "poll")

        data = {}
        userId = request.getSession(IAuthInfo).username
        yield poll.fetchData(data, convId, userId, ["meta"])

        myVotes = data["myVotes"]
        voted = myVotes[convId] if (convId in myVotes and myVotes[convId])\
                                else False

        t.renderScriptBlock(request, "poll.mako", 'poll_options',
                            False, '#poll-contents-%s' % convId, 'set',
                            args=[convId, voted], **data)
Example #8
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 #9
0
    def _newComment(self, request):
        token = self._ensureAccessScope(request, 'post-item')
        convId = request.postpath[0]
        orgId = token.org
        userId = token.user
        convId, conv = yield utils.getValidItemId(request, '', itemId=convId,  myOrgId=orgId, myId=userId)

        snippet, comment = utils.getTextWithSnippet(request, "comment",
                                                constants.COMMENT_PREVIEW_LENGTH,
                                                richText=True)
        review = int(utils.getRequestArg(request, '_review') or '0')

        itemId, convId, items, keywords = yield Item._comment(convId, conv,
                                                    comment, snippet, userId,
                                                    orgId, True, review)
        if keywords:
            raise errors.InvalidRequest(_('Matching keywords found(%s). Set reportOK=1.') % ', '.join(keywords))
        else:
            self._success(request, 201, {'id': itemId})
Example #10
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 #11
0
    def _getFileInfo(self, request):
        authinfo = request.getSession(IAuthInfo)
        myId = authinfo.username
        myOrgId = authinfo.organization

        itemId, item = yield utils.getValidItemId(request, 'id')
        attachmentId = utils.getRequestArg(request, "fid", sanitize=False)
        version = utils.getRequestArg(request, "ver", sanitize=False)

        if not attachmentId:
            raise errors.MissingParams()

        # Check if the attachmentId belong to item
        if attachmentId not in item['attachments'].keys():
            raise errors.EntityAccessDenied("attachment", attachmentId)
        if version:
            version = utils.decodeKey(version)
            cols = yield db.get(attachmentId, "attachmentVersions", version)
            cols = utils.columnsToDict([cols])
        else:
            cols = yield db.get_slice(attachmentId, 'attachmentVersions', count=1, reverse=True)
            cols = utils.columnsToDict(cols)
            version = cols.keys()[0]

        if not cols:
            raise errors.InvalidRequest()

        fileId, fileType, name = None, 'text/plain', 'file'
        fileId, name, size, fileType = cols[version].split(':')

        files = yield db.get_slice(fileId, "files", ["meta"])
        files = utils.supercolumnsToDict(files)

        url = files['meta']['uri']
        owner = files["meta"]["owner"]
        defer.returnValue([owner, url, fileType, size, name])
Example #12
0
    def _invite(self, request, convId=None):
        (appchange, script, args, myId) = yield self._getBasicArgs(request)
        landing = not self._ajax
        myOrgId = args['orgId']
        convId, conv = yield utils.getValidItemId(request, "id", columns=["invitees"])

        # Parse invitees from the tag edit plugin values
        arg_keys = request.args.keys()
        invitees, new_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)

        if myId not in conv["invitees"].keys():
            raise errors.invalidRequest(_("Only those who are invited can invite others"))

        res = base.EntitySet(invitees)
        yield res.fetchData()
        invitees = [x for x in res.keys() if res[x].basic["org"] == myOrgId]
        invitees = [x for x in invitees if x not in conv["invitees"].keys()]
        relation = Relation(myId, [])

        updateConv = {"meta":{}, "invitees":{}}
        if myId == conv["meta"]["owner"]:
            #If invited by owner, add the invitees to the ACL
            acl = conv["meta"]["acl"]
            acl = pickle.loads(acl)
            acl.setdefault("accept", {}).setdefault("users", [])
            acl["accept"]["users"].extend(invitees)
            updateConv["meta"]["acl"] = pickle.dumps(acl)
            new_invitees.extend(invitees)
        else:
            for invitee in invitees:
                relation = Relation(invitee, [])
                yield relation.initGroupsList()
                withinAcl = utils.checkAcl(invitee, myOrgId, False,
                                           relation, conv["meta"])
                if withinAcl:
                    new_invitees.append(invitee)

        if new_invitees:
            convMeta = conv["meta"]
            starttime = int(convMeta["event_startTime"])
            starttimeUUID = utils.uuid1(timestamp=starttime)
            starttimeUUID = starttimeUUID.bytes

            endtime = int(convMeta["event_endTime"])
            endtimeUUID = utils.uuid1(timestamp=endtime)
            endtimeUUID = endtimeUUID.bytes

            updateConv["invitees"] = dict([(x, myId) for x in new_invitees])
            d = yield db.batch_insert(convId, "items", updateConv)

            yield event.inviteUsers(request, starttimeUUID, endtimeUUID,
                                    convId, conv["meta"], myId,
                                    myOrgId, new_invitees)
            request.write("""$$.alerts.info('%s');""" \
                            %("%d people invited to this event" %len(new_invitees)))
        else:
            if not invitees:
                request.write("""$$.alerts.info('%s');""" \
                                %("Invited persons are already on the invitation list"))
            else:
                request.write("""$$.alerts.info('%s');""" \
                                %("Invited persons do not have access to this event"))

        request.write("$('#item-subactions .tagedit-listelement-old').remove();")
Example #13
0
    def _rsvp(self, request):
        (appchange, script, args, myId) = yield self._getBasicArgs(request)
        landing = not self._ajax
        orgId = args['orgId']

        response = utils.getRequestArg(request, 'response')
        deferreds = []
        prevResponse = ""

        if not response or response not in ('yes', 'maybe', 'no'):
            raise errors.InvalidRequest()

        convId, conv = yield utils.getValidItemId(request, "id",
                                                  columns=["invitees"])

        if not conv:
            raise errors.MissingParams([_("Event ID")])

        if ("type" in conv["meta"] and conv["meta"]["type"] != "event"):
            raise errors.InvalidRequest("Not a valid event")

        #Find out if already stored response is the same as this one. Saves
        # quite a few queries
        rsvp_names = ["%s:%s" %(x, myId) for x in ['yes', 'no', 'maybe']]
        cols = yield db.get_slice(convId, "eventResponses", names=rsvp_names)
        if cols:
            prevResponse = cols[0].column.name.split(":", 1)[0]

        if prevResponse == response:
            defer.returnValue(0)

        starttime = int(conv["meta"]["event_startTime"])
        endtime = int(conv["meta"]["event_endTime"])
        starttimeUUID = utils.uuid1(timestamp=starttime)
        starttimeUUID = starttimeUUID.bytes
        endtimeUUID = utils.uuid1(timestamp=endtime)
        endtimeUUID = endtimeUUID.bytes

        #Now insert the event in the user's agenda list if the user has
        # never responded to this event or the user is not in the invited list.
        #In the second case the agenda was already updated when creating the
        # event
        if prevResponse == "" and myId not in conv["invitees"].keys():
            d1 = db.insert(myId, "userAgenda", convId, starttimeUUID)
            d2 = db.insert(myId, "userAgenda", convId, endtimeUUID)
            d3 = db.insert("%s:%s" %(myId, convId), "userAgendaMap", "",
                          starttimeUUID)
            d4 = db.insert("%s:%s" %(myId, convId), "userAgendaMap", "",
                          endtimeUUID)
            deferreds.extend([d1, d3, d2, d4])

        #Remove any old responses to this event by this user.
        yield db.batch_remove({'eventResponses': [convId]}, names=rsvp_names)

        #Now insert the user's new response.
        d = db.insert(convId, "eventResponses", "", "%s:%s" %(response, myId))
        deferreds.append(d)

        if script:
            #Update the inline status of the rsvp status
            if response == "yes":
                rsp = _("You are attending")
            elif response == "no":
                rsp = _("You are not attending")
            elif response == "maybe":
                rsp = _("You may attend")

            request.write("$('#event-rsvp-status-%s').text('%s');"
                                                            %(convId, rsp))
            request.write("$('#conv-%s .event-join-decline').text('%s');"
                                                            %(convId, rsp))

        if deferreds:
            res = yield defer.DeferredList(deferreds)

        if script:
            args.update({"items":{convId:conv}, "convId":convId})
            entityIds = yield event.fetchData(args, convId)
            entities = base.EntitySet(entityIds)
            yield entities.fetchData()
            args["entities"] = entities

            t.renderScriptBlock(request, "event.mako", "event_meta",
                                landing, "#item-meta", "set", **args)

        # Push Feed Updates
        responseType = "E"
        convMeta = conv["meta"]
        convType = convMeta["type"]
        convOwnerId = convMeta["owner"]
        commentSnippet = convMeta["event_title"]
        itemId = convId
        convACL = convMeta["acl"]
        extraEntities = [convMeta["owner"]]
        # Importing social.feed at the beginning of the module leads to
        # a cyclic dependency as feed in turn imports plugins.
        from social.core import Feed

        if response == "yes":
            timeUUID = uuid.uuid1().bytes

            # Add user to the followers list of parent item
            yield db.insert(convId, "items", "", myId, "followers")

            # Update user's feed, feedItems, feed_*
            userItemValue = ":".join([responseType, itemId, convId, convType,
                                      convOwnerId, commentSnippet])
            yield db.insert(myId, "userItems", userItemValue, timeUUID)
            yield db.insert(myId, "userItems_event", userItemValue, timeUUID)

            # Push to feed
            feedItemVal = "%s:%s:%s:%s" % (responseType, myId, itemId,
                                            ','.join(extraEntities))
            yield Feed.push(myId, orgId, convId, conv, timeUUID, feedItemVal)
        elif prevResponse != "":
            rsvpTimeUUID = None
            cols = yield db.get_slice(myId, "userItems")
            cols = utils.columnsToDict(cols)
            for k, v in cols.iteritems():
                if v.startswith("E"):
                    rsvpTimeUUID = k

            if rsvpTimeUUID:
                # Remove update if user changes RSVP to no/maybe from yes.
                # Do not update if user had RSVPed to this event.
                feedUpdateVal = "%s:%s:%s:%s" % (responseType, myId, itemId,
                                                 convOwnerId)
                yield Feed.unpush(myId, orgId, convId, conv, feedUpdateVal)

                # FIX: if user updates more than one item at exactly same time,
                #      one of the updates will overwrite the other. Fix it.
                yield db.remove(myId, "userItems", rsvpTimeUUID)
                yield db.remove(myId, "userItems_event", rsvpTimeUUID)

        if myId != convOwnerId and response == "yes":
            timeUUID = uuid.uuid1().bytes
            yield _notify("EA", convId, timeUUID, convType=convType,
                              convOwnerId=convOwnerId, myId=myId, me=args["me"])
Example #14
0
    def _submitReport(self, request, action):
        (appchange, script, args, myId) = yield self._getBasicArgs(request)
        landing = not self._ajax
        snippet, comment = utils.getTextWithSnippet(request, "comment",
                                            constants.COMMENT_PREVIEW_LENGTH)
        orgId = args['orgId']
        isNewReport = False
        timeUUID = uuid.uuid1().bytes

        convId, conv = yield utils.getValidItemId(request, "id")
        convMeta = conv["meta"]
        convOwnerId = convMeta["owner"]
        convType = convMeta["type"]
        convACL = convMeta["acl"]
        toFetchEntities = set([myId, convOwnerId])

        if "reportId" in convMeta:
            reportId = convMeta["reportId"]
            isNewReport = False
            toFetchEntities.add(convMeta['reportedBy'])
        else:
            isNewReport = True
            reportId = utils.getUniqueKey()

        if isNewReport and convOwnerId == myId:
            raise errors.InvalidRequest(_("You cannot report your own Item. \
                                                Delete the item instead"))

        toFetchEntities.remove(myId)
        entities = base.EntitySet(toFetchEntities)
        yield entities.fetchData()
        entities.update({myId: args["me"]})

        if myId == convOwnerId:
            if action not in ["accept", "repost"]:
                raise errors.InvalidRequest(_('Invalid action was performed on the report'))

            convReport = {"reportStatus": action}
            yield db.batch_insert(convId, "items", {"meta": convReport})

            if action == "accept":
                # Owner removed the comment. Delete the item from his feed
                yield Item.deleteItem(convId, myId, orgId)
                request.write("$$.fetchUri('/feed/');")
                request.write("$$.alerts.info('%s')" % _("Your item has been deleted"))
                request.finish()
            else:
                # Owner posted a reply, so notify reporter of the same
                yield Item._notify("RFC", convId, timeUUID, convType=convType,
                               convOwnerId=convOwnerId, myId=myId, entities=entities,
                               me=args["me"], reportedBy=convMeta["reportedBy"])
        else:
            if action not in ["report", "repost", "reject"]:
                raise errors.InvalidRequest(_('Invalid action was performed on the report'))

            if isNewReport:
                # Update Existing Item Information with Report Meta
                newACL = pickle.dumps({"accept": {"users": [convOwnerId, myId]}})
                convReport = {"reportedBy": myId, "reportId": reportId,
                              "reportStatus": "pending", "state": "flagged"}
                convMeta.update(convReport)
                yield db.batch_insert(convId, "items", {"meta": convReport})

                reportLink = """&#183;<a class="button-link" title="View Report" href="/item/report?id=%s"> View Report</a>""" % convId
                request.write("""$("#item-footer-%s").append('%s');""" % (convId, reportLink))
                yield Item._notify("FC", convId, timeUUID, convType=convType, entities=entities,
                              convOwnerId=convOwnerId, myId=myId, me=args["me"])
            else:
                if action == "repost":
                    # Remove the reportId key, so owner cannot post any comment
                    yield db.batch_remove({'items': [convId]},
                                            names=["reportId", "reportStatus",
                                                   "reportedBy", "state"],
                                            supercolumn='meta')

                    oldReportMeta = {"reportedBy": convMeta["reportedBy"],
                                     "reportId": reportId}

                    # Save the now resolved report in items and remove its
                    #  reference in the item meta so new reporters wont't see
                    #  old reports
                    timestamp = str(int(time.time()))
                    yield db.insert(convId, "items", reportId, timestamp, "reports")
                    yield db.batch_insert(reportId, "items", {"meta": oldReportMeta})

                    # Notify the owner that the report has been withdrawn
                    yield Item._notify("UFC", convId, timeUUID, convType=convType,
                                  convOwnerId=convOwnerId, myId=myId,
                                  entities=entities, me=args["me"])

                elif action  in ["reject", "report"]:
                    # Reporter rejects the comment by the owner or reports the
                    #  same item again.
                    convReport = {"reportStatus": "pending"}
                    yield Item._notify("RFC", convId, timeUUID, convType=convType,
                                  convOwnerId=convOwnerId, myId=myId, entities=entities,
                                  me=args["me"], reportedBy=convMeta["reportedBy"])
                    yield db.batch_insert(convId, "items", {"meta": convReport})

        args.update({"entities": entities, "ownerId": convOwnerId,
                     "convId": convId})

        # Update New Report comment Details
        commentId = utils.getUniqueKey()
        timeUUID = uuid.uuid1().bytes
        meta = {"owner": myId, "parent": reportId, "comment": comment,
                "timestamp": str(int(time.time())),
                "uuid": timeUUID, "richText": str(False)}
        if snippet:
            meta['snippet'] = snippet

        yield db.batch_insert(commentId, "items", {'meta': meta})

        # Update list of comments for this report
        yield db.insert(reportId, "itemResponses",
                        "%s:%s:%s" % (myId, commentId, action), timeUUID)

        yield self._renderReportResponses(request, convId, convMeta, args)
        request.write("$('#report-comment').attr('value', '')")
Example #15
0
    def renderItem(self, request, toFeed=False):
        (appchange, script, args, myId) = yield self._getBasicArgs(request)
        landing = not self._ajax
        myOrgId = args["orgId"]

        convId, conv = yield utils.getValidItemId(request, "id", columns=['tags'])
        itemType = conv["meta"].get("type", None)

        if 'parent' in conv['meta']:
            raise errors.InvalidItem('conversation', convId)

        start = utils.getRequestArg(request, "start") or ''
        start = utils.decodeKey(start)

        args['convId'] = convId
        args['isItemView'] = True
        args['items'] = {convId: conv}
        meta = conv["meta"]
        owner = meta["owner"]

        relation = Relation(myId, [])
        yield defer.DeferredList([relation.initGroupsList(),
                                  relation.initSubscriptionsList()])
        args["relations"] = relation

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

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

        args["entities"] = {}
        toFetchEntities = set()
        toFetchTags = set(conv.get("tags", {}).keys())

        plugin = plugins[itemType] if itemType in plugins else None
        if plugin:
            entityIds = yield plugin.fetchData(args)
            toFetchEntities.update(entityIds)

        toFetchEntities.add(conv['meta']['owner'])
        if "target" in conv["meta"]:
            toFetchEntities.update(conv['meta']['target'].split(','))

        if conv['meta']['owner'] not in toFetchEntities:
            toFetchEntities.add(conv['meta']['owner'])
        entities = base.EntitySet(toFetchEntities)
        yield entities.fetchData()
        args["entities"] = entities

        renderers = []

        if script:
            t.renderScriptBlock(request, "item.mako", "conv_root",
                                landing, "#conv-root-%s > .conv-summary" % (convId),
                                "set", **args)

        convOwner = args["items"][convId]["meta"]["owner"]
        args["ownerId"] = convOwner
        if script:
            if itemType != "feedback":
                t.renderScriptBlock(request, "item.mako", "conv_owner",
                                    landing, "#conv-avatar-%s" % convId,
                                    "set", **args)
            else:
                feedbackType = conv['meta']['subType']
                t.renderScriptBlock(request, "item.mako", "feedback_icon",
                                    landing, "#conv-avatar-%s" % convId,
                                    "set", args=[feedbackType])

        # A copy of this code for fetching comments is present in _responses
        # Most changes here may need to be done there too.
        itemResponses = yield db.get_slice(convId, "itemResponses",
                                           start=start, reverse=True,
                                           count=constants.COMMENTS_PER_PAGE + 1)
        nextPageStart = itemResponses[-1].column.name\
                        if len(itemResponses) > constants.COMMENTS_PER_PAGE\
                        else None
        itemResponses = itemResponses[:-1] \
                        if len(itemResponses) > constants.COMMENTS_PER_PAGE\
                        else itemResponses
        responseKeys = []
        for response in itemResponses:
            userKey, responseKey = response.column.value.split(":")
            responseKeys.append(responseKey)
            toFetchEntities.add(userKey)
        responseKeys.reverse()

        subscriptions = list(relation.subscriptions)
        likes = yield db.get_slice(convId, "itemLikes", subscriptions) \
                            if subscriptions else defer.succeed([])
        toFetchEntities.update([x.column.name for x in likes])
        entities = base.EntitySet(toFetchEntities)
        d1 = entities.fetchData()
        d2 = db.multiget_slice(responseKeys, "items", ["meta", "attachments"])
        d3 = db.multiget_slice(responseKeys + [convId], "itemLikes", [myId])
        d4 = db.get_slice(myOrgId, "orgTags", toFetchTags)\
                                    if toFetchTags else defer.succeed([])

        yield d1
        fetchedItems = yield d2
        myLikes = yield d3
        fetchedTags = yield d4

        fetchedItems = utils.multiSuperColumnsToDict(fetchedItems)
        myLikes = utils.multiColumnsToDict(myLikes)
        fetchedTags = utils.supercolumnsToDict(fetchedTags)

        # Do some error correction/consistency checking to ensure that the
        # response items actually exist. I don't know of any reason why these
        # items may not exist.
        missingIds = [x for x, y in fetchedItems.items() if not y]
        if missingIds:
            yield self._cleanupMissingComments(convId, missingIds, itemResponses)

        args["items"].update(fetchedItems)
        args["entities"].update(entities)
        args["myLikes"] = myLikes
        args["tags"] = fetchedTags
        args["responses"] = {convId: responseKeys}
        if nextPageStart:
            args["oldest"] = utils.encodeKey(nextPageStart)

        if script:
            t.renderScriptBlock(request, "item.mako", 'conv_footer',
                                landing, '#item-footer-%s' % convId,
                                'set', **args)
            t.renderScriptBlock(request, "item.mako", 'conv_tags',
                                landing, '#conv-tags-wrapper-%s' % convId, 'set',
                                handlers={"onload": "$('#conv-meta-wrapper-%s').removeClass('no-tags')" % convId} if toFetchTags else None, **args)
            t.renderScriptBlock(request, "item.mako", 'conv_comments',
                                landing, '#conv-comments-wrapper-%s' % convId, 'set', **args)
            t.renderScriptBlock(request, "item.mako", 'conv_comment_form',
                                landing, '#comment-form-wrapper-%s' % convId, 'set',
                                True, handlers={"onload": "(function(obj){$$.convs.load(obj);})(this);"}, **args)

            numLikes = int(conv["meta"].get("likesCount", "0"))
            if numLikes:
                numLikes = int(conv["meta"].get("likesCount", "0"))
                iLike = myId in args["myLikes"].get(convId, [])
                t.renderScriptBlock(request, "item.mako", 'conv_likes',
                                    landing, '#conv-likes-wrapper-%s' % convId, 'set',
                                    args=[convId, numLikes, iLike, [x.column.name for x in likes]],
                                    entities=args['entities'])

        if plugin and hasattr(plugin, 'renderItemSideBlock'):
            plugin.renderItemSideBlock(request, landing, args)

        if script and landing:
            request.write("</body></html>")

        if not script:
            t.render(request, "item.mako", **args)
Example #16
0
    def _renderReport(self, request, partial=False):
        (appchange, script, args, myId) = yield self._getBasicArgs(request)
        landing = not self._ajax

        convId, conv = yield utils.getValidItemId(request, "id", columns=["reports"])
        if 'parent' in conv['meta']:
            raise errors.InvalidItem('conversation', convId)

        args["entities"] = {}
        toFetchEntities = set()

        args['convId'] = convId
        args['items'] = {convId: conv}
        convMeta = conv["meta"]
        convType = convMeta.get("type", None)

        relation = Relation(myId, [])
        yield relation.initGroupsList()
        args["relations"] = relation

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

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

        plugin = plugins[convType] if convType in plugins else None
        if plugin:
            entityIds = yield plugin.fetchData(args)
            toFetchEntities.update(entityIds)

        convOwner = convMeta['owner']
        toFetchEntities.add(convOwner)
        if "target" in convMeta:
            toFetchEntities.update(convMeta['target'].split(','))
        if "reportId" in convMeta:
            toFetchEntities.add(convMeta['reportedBy'])

        entities = base.EntitySet(toFetchEntities)
        yield entities.fetchData()
        args["entities"] = entities
        args["ownerId"] = convOwner

        if script:
            t.renderScriptBlock(request, "item.mako", "conv_root",
                                landing, "#conv-root-%s > .conv-summary" % (convId),
                                "set", **args)

            t.renderScriptBlock(request, "item-report.mako", 'conv_footer',
                                landing, '#item-footer-%s' % convId,
                                'set', **args)

            if convType != "feedback":
                t.renderScriptBlock(request, "item.mako", "conv_owner",
                                    landing, "#conv-avatar-%s" % convId,
                                    "set", **args)
            else:
                feedbackType = conv['meta']['subType']
                t.renderScriptBlock(request, "item.mako", "feedback_icon",
                                    landing, "#conv-avatar-%s" % convId,
                                    "set", args=[feedbackType])

        yield self._renderReportResponses(request, convId, convMeta, args)

        if not script:
            t.render(request, "item-report.mako", **args)