def _listPresetTags(self, request): (appchange, script, args, myId) = yield self._getBasicArgs(request) orgId = args["orgId"] landing = not self._ajax args['title'] = 'Preset Tags' args['menuId'] = 'tags' args["viewType"] = "tags" if script and landing: t.render(request, "admin.mako", **args) if script and appchange: t.renderScriptBlock(request, "admin.mako", "layout", landing, "#mainbar", "set", **args) presetTags = yield db.get_slice(orgId, "orgPresetTags", count=100) presetTags = utils.columnsToDict(presetTags, ordered=True).values() if presetTags: tags_ = yield db.get_slice(orgId, "orgTags", presetTags) tags_ = utils.supercolumnsToDict(tags_) else: tags_ = {} args['tagsList'] = presetTags args['tags'] = tags_ if script: t.renderScriptBlock(request, "admin.mako", "list_tags", landing, "#content", "set", **args) if not script: t.render(request, "admin.mako", **args)
def _renderKeywordMatches(self, request): (appchange, script, args, myId) = yield self._getBasicArgs(request) landing = not self._ajax keyword = utils.getRequestArg(request, 'keyword') if not keyword: errors.MissingParams(['Keyword']) args["keyword"] = keyword start = utils.getRequestArg(request, "start") or "" args["start"] = start if script and landing: t.render(request, "keyword-matches.mako", **args) if script and appchange: t.renderScriptBlock(request, "keyword-matches.mako", "layout", landing, "#mainbar", "set", **args) keywordItems = yield self._getKeywordMatches(request, keyword, start=start) args.update(keywordItems) if script: onload = "(function(obj){$$.convs.load(obj);})(this);" t.renderScriptBlock(request, "keyword-matches.mako", "feed", landing, "#convs-wrapper", "set", True, handlers={"onload": onload}, **args) if not script: t.render(request, "keyword-matches.mako", **args)
def _renderOrgInfo(self, request): (appchange, script, args, myId) = yield self._getBasicArgs(request) landing = not self._ajax args['title'] = "Update Company Info" args["menuId"] = "org" if script and landing: t.render(request, "admin.mako", **args) if script and appchange: t.renderScriptBlock(request, "admin.mako", "layout", landing, "#mainbar", "set", **args) args["viewType"] = "org" if script: handlers = {'onload': "$$.ui.bindFormSubmit('#orginfo-form');"} t.renderScriptBlock(request, "admin.mako", "orgInfo", landing, "#content", "set", True, handlers=handlers, **args) if script and landing: request.write("</body></html>") if not script: t.render(request, "admin.mako", **args)
def _renderClientDetails(self, request, clientId): (appchange, script, args, myId) = yield self._getBasicArgs(request) landing = not self._ajax args["detail"] = "apps" if script and landing: t.render(request, "apps.mako", **args) if appchange and script: t.renderScriptBlock(request, "apps.mako", "layout", landing, "#mainbar", "set", **args) client = yield db.get_slice(clientId, "apps") client = utils.supercolumnsToDict(client) if not client: raise errors.InvalidApp(clientId) args.update({"client": client, "clientId": clientId}) if script: self.setTitle(request, client["meta"]["name"]) author = base.Entity(client["meta"]["author"]) yield author.fetchData() args["entities"] = base.EntitySet(author) if script: t.renderScriptBlock(request, "apps.mako", "appDetails", landing, "#apps-contents", "set", **args) else: t.render(request, "apps.mako", **args)
def _listPendingSubscriptions(self, request, data=None): appchange, script, args, myId = yield self._getBasicArgs(request) landing = not self._ajax me = args['me'] group = data['id'] start = data['start'] or 'GI' entities = base.EntitySet(group) args.update({"menuId": "pending", "groupId": group.id, "entities": entities, "heading": group.basic['name']}) if me.id not in group.admins: raise errors.InvalidRequest('Access Denied') if script and landing: t.render(request, "group-settings.mako", **args) if script and appchange: t.renderScriptBlock(request, "group-settings.mako", "layout", landing, "#mainbar", "set", **args) data = yield Group.getPendingRequests(group, me, start) args.update(data) args["entities"].update(group) args["tab"] = 'pending' if script: t.renderScriptBlock(request, "groups.mako", "titlebar", landing, "#titlebar", "set", **args) t.renderScriptBlock(request, "group-settings.mako", "displayUsers", landing, "#groups-wrapper", "set", **args) t.renderScriptBlock(request, 'groups.mako', "pendingRequestsPaging", landing, "#groups-paging", "set", **args)
def _renderEditGroup(self, request, data=None): appchange, script, args, myId = yield self._getBasicArgs(request) landing = not self._ajax group = data['id'] args["menuId"] = "settings" args["groupId"] = group.id args["entities"] = base.EntitySet(group) args["heading"] = group.basic['name'] if myId not in group.admins: raise errors.PermissionDenied('You should be an administrator to edit group meta data') if script and landing: t.render(request, "group-settings.mako", **args) if script and appchange: t.renderScriptBlock(request, "group-settings.mako", "layout", landing, "#mainbar", "set", **args) if script: handlers = {} handlers["onload"] = """$$.ui.bindFormSubmit('#group-form');""" t.renderScriptBlock(request, "group-settings.mako", "edit_group", landing, "#center-content", "set", True, handlers=handlers, **args) else: t.render(request, "group-settings.mako", **args)
def _renderSigninForm(self, request, errcode=''): args = {} redirect = utils.getRequestArg(request, '_r', sanitize=False) or "/feed/" args["redirect"] = urllib.quote(redirect, '*@+/') args["reason"] = errcode t.render(request, "signin.mako", **args) request.finish()
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)
def renderResetPassword(self, request): email = utils.getRequestArg(request, 'email') token = utils.getRequestArg(request, 'token') if not (email and token): raise MissingParams(['']) validEmail, tokens, deleteTokens, leastTimestamp = yield _getResetPasswordTokens(email) # XXX: If not validEmail, send invite to the user if not validEmail or token not in tokens: raise PermissionDenied("Invalid token. <a href='/password/resend?email=%s'>Click here</a> to reset password" % (email)) args = {"view": "resetPassword", "email": email, "token": token} t.render(request, "signup.mako", **args)
def _events(self, request): (appchange, script, args, myId) = yield self._getBasicArgs(request) landing = not self._ajax page = utils.getRequestArg(request, 'page') or '1' entityId = utils.getRequestArg(request, 'id') or myId view = utils.getRequestArg(request, 'view') or "agenda" authinfo = request.getSession(IAuthInfo) myOrgId = authinfo.organization start = utils.getRequestArg(request, 'start') or "" #Check if entity Id is my Org or a group that I have access to. if entityId != myId and entityId != myOrgId: yield utils.getValidEntityId(request, "id", "group") if view == "invitations": entityId = "%s:%s" %(myId, "I") if page.isdigit(): page = int(page) else: page = 1 count = constants.EVENTS_PER_PAGE try: start = datetime.datetime.strptime(start, "%Y-%m-%d") except ValueError: start = None args.update({'view':view, 'menuId': 'events'}) args.update({'page':page, 'entityId': entityId}) if script and landing: t.render(request, "event.mako", **args) if script and appchange: t.renderScriptBlock(request, "event.mako", "layout", landing, "#mainbar", "set", **args) yield event.fetchMatchingEvents(request, args, entityId, count=count, start=start) if script: onload = """ $$.menu.selectItem('events'); $$.events.prepareAgendaDatePicker('%s') """ % (args["start"]) t.renderScriptBlock(request, 'event.mako', "render_events", landing, ".center-contents", "set", True, handlers={"onload": onload}, **args) else: t.render(request, "event.mako", **args)
def _listBlockedUsers(self, request): (appchange, script, args, myId) = yield self._getBasicArgs(request) orgId = args["orgId"] landing = not self._ajax start = utils.getRequestArg(request, 'start') or '' start = utils.decodeKey(start) count = PEOPLE_PER_PAGE toFetchCount = count + 1 nextPageStart = '' prevPageStart = '' args["title"] = "Manage Users" args["menuId"] = "users" args["viewType"] = "blocked" if script and landing: t.render(request, "admin.mako", **args) if script and appchange: t.renderScriptBlock(request, "admin.mako", "layout", landing, "#mainbar", "set", **args) args["heading"] = "Admin Console - Blocked Users" cols = yield db.get_slice(orgId, "blockedUsers", start=start, count=toFetchCount) blockedUsers = [col.column.name for col in cols] if len(blockedUsers) > count: nextPageStart = utils.encodeKey(blockedUsers[-1]) blockedUsers = blockedUsers[:count] if start: cols = yield db.get_slice(orgId, "blockedUsers", start=start, count=toFetchCount, reverse=True) if len(cols) > 1: prevPageStart = utils.decodeKey(cols[-1].column.name) entities = base.EntitySet(blockedUsers) yield entities.fetchData() args["entities"] = entities args['nextPageStart'] = nextPageStart args['prevPageStart'] = prevPageStart if script: t.renderScriptBlock(request, "admin.mako", "viewOptions", landing, "#users-view", "set", **args) t.renderScriptBlock(request, "admin.mako", "list_users", landing, "#content", "set", **args) if script and landing: request.write("</body></html>") if not script: t.render(request, "admin.mako", **args)
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)
def _block(self, request, blockType): token = utils.getRequestArg(request, "token") emailId = utils.getRequestArg(request, "email") sender = yield self._isValidToken(emailId, token) if blockType == "all": yield db.insert(emailId, "doNotSpam", "", "*") elif blockType == "sender": yield db.insert(emailId, "doNotSpam", "", sender) # The invitation is not removed. # This is to ensure that the sender can still whom he invited and that # the invited person did not join flocked.in args = {'view': 'block', 'blockType': blockType, 'emailId': emailId} t.render(request, "signup.mako", **args)
def _clientRegistrationForm(self, request): (appchange, script, args, myId) = yield self._getBasicArgs(request) landing = not self._ajax args["detail"] = "apps" apiKey = utils.getRequestArg(request, "type") == "apikey" title = "Generate a new API Key" if apiKey else "Register a new application" args["apiKey"] = apiKey args["title"] = title if script and landing: t.render(request, "apps.mako", **args) if script: self.setTitle(request, title) t.renderScriptBlock(request, "apps.mako", "registrationForm", landing, "#apps-contents", "set", **args)
def _renderFileList(self, request): appchange, script, args, myId = yield self._getBasicArgs(request) landing = not self._ajax myOrgId = args["orgId"] start = utils.getRequestArg(request, "start") or '' start = utils.decodeKey(start) end = utils.getRequestArg(request, "end") or '' end = utils.decodeKey(end) viewType = utils.getRequestArg(request, "type") viewType = viewType if viewType in ['myFiles', 'companyFiles', 'myFeedFiles'] else 'myFiles' args['menuId'] = 'files' if script and landing: t.render(request, "files.mako", **args) if script and appchange: t.renderScriptBlock(request, "files.mako", 'layout', landing, "#mainbar", "set", **args) args['viewType'] = viewType entityId = myId if viewType in ['myFiles', 'myFeedFiles'] else myOrgId fromFeed = viewType != 'myFiles' if script: t.renderScriptBlock(request, "files.mako", "viewOptions", landing, "#file-view", "set", args=[viewType]) files = yield userFiles(myId, entityId, args['orgId'], start, end, fromFeed) toFetchEntities = files[3] entities = base.EntitySet(toFetchEntities) yield entities.fetchData() args['entities'] = entities args['userfiles'] = files if script: t.renderScriptBlock(request, "files.mako", "listFiles", landing, "#files-content", "set", **args) t.renderScriptBlock(request, "files.mako", "pagingBar", landing, "#files-paging", "set", **args) else: t.render(request, "files.mako", **args)
def _render(self, request): (appchange, script, args, myId) = yield self._getBasicArgs(request) landing = not self._ajax (tagId, tagInfo) = yield utils.getValidTagId(request, 'id') args["tags"] = tagInfo args["tagId"] = tagId args["tagFollowing"] = False args["menuId"] = "tags" if script and landing: t.render(request, "tags.mako", **args) if script and appchange: t.renderScriptBlock(request, "tags.mako", "layout", landing, "#mainbar", "set", **args) try: yield db.get(tagId, "tagFollowers", myId) args["tagFollowing"] = True except ttypes.NotFoundException: pass if script: t.renderScriptBlock(request, "tags.mako", "header", landing, "#tags-header", "set", **args) start = utils.getRequestArg(request, "start") or '' tagItems = yield self._getTagItems(request, tagId, start=start) args.update(tagItems) if script: onload = """ (function(obj){$$.convs.load(obj);})(this); $('form').html5form({messages: 'en'}); """ t.renderScriptBlock(request, "tags.mako", "itemsLayout", landing, "#content", "set", True, handlers={"onload": onload}, **args) if not script: t.render(request, "tags.mako", **args)
def request_resetPassword(self, request): email = utils.getRequestArg(request, 'email') if not email: raise MissingParams(['']) now = time.time() validEmail, tokens, deleteTokens, leastTimestamp = yield _getResetPasswordTokens(email) if len(tokens) >= 10: delta = datetime.fromtimestamp(leastTimestamp + 86399) - datetime.fromtimestamp(now) hours = 1 + delta.seconds / 3600 raise PermissionDenied('We detected ususual activity from your account.<br/> Click the link sent to your emailId to reset password or wait for %s hours before you retry' % (hours)) if validEmail: token = utils.getRandomKey() yield db.insert(email, "userAuth", token, 'resetPasswdToken:%s' % (token), ttl=86400) yield _sendmailResetPassword(email, token) args = {"view": "forgotPassword-post"} t.render(request, "signup.mako", **args)
def _render(self, request): (appchange, script, args, myId) = yield self._getBasicArgs(request) landing = not self._ajax title = "Applications" args["title"] = title args["detail"] = "apps" if script and landing: t.render(request, "apps.mako", **args) if appchange and script: t.renderScriptBlock(request, "apps.mako", "layout", landing, "#mainbar", "set", **args) if script: self.setTitle(request, title) # XXX: Currently fetching all available apps under each category. # In future implement pagination here. appIds = yield db.get_slice(myId, "entities", ["apikeys", "apps"], count=100) appIds = utils.supercolumnsToDict(appIds, timestamps=True) appsByMe = yield db.get_slice(myId, "appsByOwner", count=100) appIds["my"] = utils.columnsToDict(appsByMe) toFetchClients = set() for val in appIds.values(): toFetchClients.update(val.keys()) clients = yield db.multiget_slice(toFetchClients, "apps") clients = utils.multiSuperColumnsToDict(clients) toFetchEntities = set([x.author for x in clients if "author" in x]) entities = base.EntitySet(toFetchEntities) yield entities.fetchData() args.update({"entities": entities, "clients": clients, "apps": appIds}) if script: t.renderScriptBlock(request, "apps.mako", "appListing", landing, "#apps-contents", "set", **args) else: t.render(request, "apps.mako", **args)
def _renderAddUsers(self, request): (appchange, script, args, myId) = yield self._getBasicArgs(request) landing = not self._ajax args["title"] = "Add Users" args["viewType"] = "add" args["menuId"] = "users" if script and landing: t.render(request, "admin.mako", **args) if script and appchange: t.renderScriptBlock(request, "admin.mako", "layout", landing, "#mainbar", "set", **args) if script: t.renderScriptBlock(request, "admin.mako", "addUsers", landing, "#addpeople-dlg", "set", **args) if script and landing: request.write("</body></html>")
def _listGroupMembers(self, request, data=None): appchange, script, args, myId = yield self._getBasicArgs(request) landing = not self._ajax me = args['me'] group = data['id'] start = data['start'] groupMembers_d = Group.getMembers(group, me, start=start) args.update({"menuId": "members", "groupId": group.id, "entities": {group.id: group}}) args["tab"] = 'manage' if myId in group.admins else '' if script and landing: t.render(request, "group-settings.mako", **args) if script and appchange: t.renderScriptBlock(request, "group-settings.mako", "layout", landing, "#mainbar", "set", **args) entities, relation, userIds, blockedUsers, \ nextPageStart, prevPageStart = yield groupMembers_d #arg.update overwrites existing entities, so add group entities.update(group) args.update({"relations": relation, "entities": entities, "userIds": userIds, "blockedUsers": blockedUsers, "nextPageStart": nextPageStart, "prevPageStart": prevPageStart, "heading": group.basic['name']}) if script: t.renderScriptBlock(request, "group-settings.mako", "titlebar", landing, "#titlebar", "set", **args) t.renderScriptBlock(request, "group-settings.mako", "displayUsers", landing, "#groups-wrapper", "set", **args) t.renderScriptBlock(request, "group-settings.mako", "paging", landing, "#groups-paging", "set", **args) else: t.render(request, "group-settings.mako", **args)
def _invite(self, request, data=None): appchange, script, args, myId = yield self._getBasicArgs(request) landing = not self._ajax group = data['id'] user = data['invitee'] me = args['me'] args["groupId"] = group.id args["heading"] = group.basic["name"] if script and landing: t.render(request, "groups.mako", **args) if script and appchange: t.renderScriptBlock(request, "groups.mako", "layout", landing, "#mainbar", "set", **args) try: yield Group.invite(group, me, user) except ttypes.NotFoundException: request.write('$$.alerts.error("You should be member of the group to Invite Others");') finally: request.write("""$("#group_add_invitee").attr("value", "");"""\ """$$.alerts.info("%s is invited to the %s");""" % (user.basic["name"], group.basic["name"]))
def _renderKeywordManagement(self, request): (appchange, script, args, myId) = yield self._getBasicArgs(request) orgId = args["orgId"] landing = not self._ajax args["title"] = "Keyword Monitoring" args["menuId"] = "keywords" if script and landing: t.render(request, "admin.mako", **args) if script and appchange: t.renderScriptBlock(request, "admin.mako", "layout", landing, "#mainbar", "set", **args) keywords = yield db.get_slice(orgId, "originalKeywords") keywords = utils.columnsToDict(keywords, ordered=True) args['keywords'] = keywords if script: t.renderScriptBlock(request, "admin.mako", "listKeywords", landing, "#content", "set", **args)
def _renderNotifications(self, request): (appchange, script, args, myId) = yield self._getBasicArgs(request) landing = not self._ajax args["menuId"] = "notifications" if script and landing: t.render(request, "notifications.mako", **args) if script and appchange: t.renderScriptBlock(request, "notifications.mako", "layout", landing, "#mainbar", "set", **args) start = utils.getRequestArg(request, "start") or '' fromFetchMore = ((not landing) and (not appchange) and start) data = yield self._getNotifications(request) latest = yield db.get_slice(myId, "latest", super_column="notifications") latest = utils.columnsToDict(latest) latestNotifyIds = [x for x in latest.values()] if not start: yield db.remove(myId, "latest", super_column="notifications") args.update(data) args['latestNotifyIds'] = latestNotifyIds if script: if fromFetchMore: t.renderScriptBlock(request, "notifications.mako", "content", landing, "#next-load-wrapper", "replace", True, handlers={}, **args) else: t.renderScriptBlock(request, "notifications.mako", "content", landing, "#notifications", "set", **args) yield utils.render_LatestCounts(request, landing) else: t.render(request, "notifications.mako", **args)
def _listBannedUsers(self, request, data=None): appchange, script, args, myId = yield self._getBasicArgs(request) landing = not self._ajax me = args['me'] group = data['id'] start = data['start'] start = utils.decodeKey(start) entities = base.EntitySet(group) args.update({"menuId": "banned", "groupId": group.id, "entities": entities, "heading": group.basic['name']}) if me.id not in group.admins: raise errors.InvalidRequest(_("Access Denied")) if script and landing: t.render(request, "group-settings.mako", **args) if script and appchange: t.renderScriptBlock(request, "group-settings.mako", "layout", landing, "#mainbar", "set", **args) data = yield Group.getBlockedMembers(group, me, start) print data.keys() args.update(data) args['entities'].update(group) args["tab"] = "banned" if script: t.renderScriptBlock(request, "group-settings.mako", "titlebar", landing, "#titlebar", "set", **args) t.renderScriptBlock(request, "group-settings.mako", "displayUsers", landing, "#groups-wrapper", "set", **args) t.renderScriptBlock(request, "group-settings.mako", "bannedUsersPaging", landing, "#groups-paging", "set", **args)
def _listAllUsers(self, request): (appchange, script, args, myId) = yield self._getBasicArgs(request) orgId = args["orgId"] landing = not self._ajax start = utils.getRequestArg(request, 'start') or '' args["title"] = "Manage Users" args["menuId"] = "users" args["viewType"] = "all" start = utils.decodeKey(start) if script and landing: t.render(request, "admin.mako", **args) if script and appchange: t.renderScriptBlock(request, "admin.mako", "layout", landing, "#mainbar", "set", **args) users, relations, userIds, blockedUsers, \ nextPageStart, prevPageStart = yield people.getPeople(myId, orgId, orgId, start=start) args["entities"] = users args["relations"] = relations args["people"] = userIds args["nextPageStart"] = nextPageStart args["prevPageStart"] = prevPageStart args["blockedUsers"] = blockedUsers if script: t.renderScriptBlock(request, "admin.mako", "viewOptions", landing, "#users-view", "set", **args) t.renderScriptBlock(request, "admin.mako", "list_users", landing, "#content", "set", **args) else: t.render(request, "admin.mako", **args)
def _listConversations(self, request): """Renders a time sorted list of coversations in a particular view. Keyword Arguments: filerType: The folder view which is to rendered. One of ['unread', 'all', 'archive', 'trash']. start: The base64 encoded timeUUID of the starting conversation id of the page that needs to be rendered. """ (appchange, script, args, myId) = yield self._getBasicArgs(request) landing = not self._ajax filterType = utils.getRequestArg(request, 'type') folder = self._folders[filterType] if filterType in self._folders else\ self._folders['inbox'] start = utils.getRequestArg(request, "start") or '' start = utils.decodeKey(start) if script and landing: t.render(request, "message.mako", **args) if appchange and script: t.renderScriptBlock(request, "message.mako", "layout", landing, "#mainbar", "set", **args) unread = [] convs = [] users = set() count = 10 fetchCount = count + 1 nextPageStart = '' prevPageStart = '' cols = yield db.get_slice(myId, folder, reverse=True, start=start, count=fetchCount) for col in cols: x, convId = col.column.value.split(':') convs.append(convId) if x == 'u': unread.append(convId) if len(cols) == fetchCount: nextPageStart = utils.encodeKey(col.column.name) convs = convs[:count] ###XXX: try to avoid extra fetch cols = yield db.get_slice(myId, folder, count=fetchCount, start=start) if cols and len(cols) > 1 and start: prevPageStart = utils.encodeKey(cols[-1].column.name) cols = yield db.multiget_slice(convs, 'mConversations') conversations = utils.multiSuperColumnsToDict(cols) m = {} for convId in conversations: if not conversations[convId]: continue participants = conversations[convId]['participants'].keys() users.update(participants) conversations[convId]['people'] = participants conversations[convId]['read'] = str(int(convId not in unread)) messageCount = yield db.get_count(convId, "mConvMessages") conversations[convId]['count'] = messageCount m[convId] = conversations[convId] users = base.EntitySet(users) yield users.fetchData() args.update({"view": "messages"}) args.update({"messages": m}) args.update({"people": users}) args.update({"mids": convs}) args.update({"menuId": "messages"}) args.update({"filterType": filterType or "all"}) args['nextPageStart'] = nextPageStart args['prevPageStart'] = prevPageStart if script: onload = """ $$.menu.selectItem('%s'); $('#mainbar .contents').removeClass("has-right"); """ % args["menuId"] t.renderScriptBlock(request, "message.mako", "render_conversations", landing, ".center-contents", "set", True, handlers={"onload": onload}, **args) yield utils.render_LatestCounts(request, landing) else: t.render(request, "message.mako", **args)
def _renderConversation(self, request): """Render a conversation. Keyword arguments: convId: The id of the conversation that needs to be rendered. """ (appchange, script, args, myId) = yield self._getBasicArgs(request) landing = not self._ajax convId = utils.getRequestArg(request, 'id', sanitize=False) if not convId: raise errors.MissingParams([]) if script and landing: t.render(request, "message.mako", **args) if appchange and script: t.renderScriptBlock(request, "message.mako", "layout", landing, "#mainbar", "set", **args) cols = yield db.get_slice(convId, "mConversations") conv = utils.supercolumnsToDict(cols) participants = set(conv.get('participants', {}).keys()) if not conv: raise errors.InvalidMessage(convId) if myId not in participants: raise errors.MessageAccessDenied(convId) timeUUID = conv['meta']['uuid'] d1 = db.remove(myId, "mUnreadConversations", timeUUID) d2 = db.remove(convId, "mConvFolders", 'mUnreadConversations', myId) d3 = db.remove(myId, "latest", timeUUID, "messages") deferreds = [d1, d2, d3] yield defer.DeferredList(deferreds) deferreds = [] cols = yield db.get_slice(convId, "mConvFolders", [myId]) cols = utils.supercolumnsToDict(cols) for folder in cols[myId]: if folder in self._folders: folder = self._folders[folder] d = db.insert(myId, folder, "r:%s" % (convId), timeUUID) deferreds.append(d) inFolders = cols[myId].keys() #FIX: make sure that there will be an entry of convId in mConvFolders cols = yield db.get_slice(convId, "mConvMessages") mids = [col.column.value for col in cols] messages = yield db.multiget_slice(mids, "messages", ["meta"]) messages = utils.multiSuperColumnsToDict(messages) s = yield defer.DeferredList(deferreds) participants.update([messages[mid]['meta']['owner'] for mid in messages]) people = base.EntitySet(participants) yield people.fetchData() args.update({"people": people}) args.update({"conv": conv}) args.update({"messageIds": mids}) args.update({'messages': messages}) args.update({"id": convId}) args.update({"flags": {}}) args.update({"view": "message"}) args.update({"menuId": "messages"}) args.update({"inFolders": inFolders}) if script: onload = """ $$.menu.selectItem("messages"); $('#mainbar .contents').addClass("has-right"); $('.conversation-reply').autogrow(); $('#message-reply-form').html5form({messages: 'en'}); """ t.renderScriptBlock(request, "message.mako", "render_conversation", landing, ".center-contents", "set", True, handlers={"onload": onload}, **args) onload = """ $$.files.init('msgreply-attach'); $('#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) yield utils.render_LatestCounts(request, landing) else: t.render(request, "message.mako", **args)
def _render(self, request): (appchange, script, args, myId) = yield self._getBasicArgs(request) # We are setting an empty value to 'cu' here just to make sure that # any errors when looking validating the entity should not leave us # in a bad state. request.addCookie('cu', '', path="/ajax/profile") if request.args.get("id", None): userId, ign = yield utils.getValidEntityId(request, "id", "user") else: userId = myId # XXX: We should use getValidEntityId to fetch the entire user # info instead of another call to the database. request.addCookie('cu', userId, path="/ajax/profile") user = base.Entity(userId) yield user.fetchData([]) if user._data: args['user'] = user detail = utils.getRequestArg(request, "dt") or "activity" args["detail"] = detail args["userId"] = userId args["menuId"] = "people" args["entities"] = base.EntitySet({myId:args['me'], userId:user}) # When scripts are enabled, updates are sent to the page as # and when we get the required data from the database. # When we are the landing page, we also render the page header # and all updates are wrapped in <script> blocks. landing = not self._ajax # User entered the URL directly # Render the header. Other things will follow. if script and landing: t.render(request, "profile.mako", **args) # Start with displaying the template and navigation menu if script and appchange: t.renderScriptBlock(request, "profile.mako", "layout", landing, "#mainbar", "set", **args) # Prefetch some data about how I am related to the user. # This is required in order to reliably filter our profile details # that I don't have access to. relation = Relation(myId, [userId]) args["relations"] = relation yield defer.DeferredList([relation.initSubscriptionsList(), relation.initGroupsList()]) # Reload all user-depended blocks if the currently displayed user is # not the same as the user for which new data is being requested. if script: t.renderScriptBlock(request, "profile.mako", "summary", landing, "#profile-summary", "set", **args) t.renderScriptBlock(request, "profile.mako", "user_subactions", landing, "#user-subactions", "set", **args) fetchedEntities = set() start = utils.getRequestArg(request, "start") or '' fromFetchMore = ((not landing) and (not appchange) and start) if detail == "activity": userItems = yield self._getUserItems(request, userId, start=start) args.update(userItems) elif detail == 'files': end = utils.getRequestArg(request, "end") or '' end = utils.decodeKey(end) start = utils.decodeKey(start) userFiles = yield files.userFiles(myId, userId, args['orgId'], start, end, fromFeed=False) args['userfiles'] = userFiles args['fromProfile'] = True if script: t.renderScriptBlock(request, "profile.mako", "tabs", landing, "#profile-tabs", "set", **args) handlers = {} if detail != "activity" \ else {"onload": "(function(obj){$$.convs.load(obj);})(this);"} if fromFetchMore and detail == "activity": t.renderScriptBlock(request, "profile.mako", "content", landing, "#next-load-wrapper", "replace", True, handlers=handlers, **args) else: t.renderScriptBlock(request, "profile.mako", "content", landing, "#profile-content", "set", True, handlers=handlers, **args) # List the user's subscriptions cols = yield db.get_slice(userId, "subscriptions", count=11) subscriptions = set(utils.columnsToDict(cols).keys()) args["subscriptions"] = subscriptions # List the user's followers cols = yield db.get_slice(userId, "followers", count=11) followers = set(utils.columnsToDict(cols).keys()) args["followers"] = followers # Fetch item data (name and avatar) for subscriptions, followers, # user groups and common items. entitiesToFetch = followers.union(subscriptions)\ .difference(fetchedEntities) # List the user's groups (and look for groups common with me) cols = yield db.multiget_slice([myId, userId], "entityGroupsMap") myGroups = set([x.column.name.split(':', 1)[1] for x in cols[myId]]) userGroups = set([x.column.name.split(':', 1)[1] for x in cols[userId]]) commonGroups = myGroups.intersection(userGroups) if len(userGroups) > 10: userGroups = sample(userGroups, 10) args["userGroups"] = userGroups args["commonGroups"] = commonGroups groupsToFetch = commonGroups.union(userGroups) entitiesToFetch = entitiesToFetch.union(groupsToFetch) entities = base.EntitySet(entitiesToFetch) yield entities.fetchData() for entityId, entity in entities.items(): if not entity._data: del entities[entityId] args["entities"].update(entities) if script: t.renderScriptBlock(request, "profile.mako", "user_subscriptions", landing, "#user-subscriptions", "set", **args) t.renderScriptBlock(request, "profile.mako", "user_followers", landing, "#user-followers", "set", **args) t.renderScriptBlock(request, "profile.mako", "user_me", landing, "#user-me", "set", **args) t.renderScriptBlock(request, "profile.mako", "user_groups", landing, "#user-groups", "set", **args) if script and landing: request.write("</body></html>") if not script: t.render(request, "profile.mako", **args)
def _renderAccessDialog(self, request): (appchange, script, args, myId) = yield self._getBasicArgs(request) authinfo = request.getSession(IAuthInfo) myOrgId = authinfo.organization clientId = utils.getRequestArg(request, "client_id") if not clientId: self._error(request, self.CLIENT_MISSING) return client = yield db.get_slice(clientId, "apps") client = utils.supercolumnsToDict(client) if not client: self._error(request, self.CLIENT_INVALID) return # We have a client now. clientMeta = client["meta"] # First verify that we were given a valid redirectUri redirectUri = utils.getRequestArg(request, 'redirect_uri', sanitize=False) clientRedirectUri = b64decode(clientMeta['redirect']) if redirectUri and redirectUri != clientRedirectUri: self._error(request, self.REDIRECTURI_MISMATCH) return # All errors from here will be sent to the redirectUri redirectUri = clientRedirectUri state = utils.getRequestArg(request, 'state', sanitize=False) or '' errorType = None # Check response type responseType = utils.getRequestArg(request, 'response_type') if not responseType: errorType = 'invalid_request' elif responseType != 'code': errorType = 'unsupported_response_type' if not errorType: scopes = utils.getRequestArg(request, 'scope') scopes = scopes.split(' ') if scopes: clientScopes = clientMeta['scope'].split(' ') if [x for x in scopes if x not in clientScopes]: errorType = 'access_denied' if errorType: self._redirectOnError(request, redirectUri, errorType, state) return # We need auth token for the form submission to go through. authToken = authinfo.token; # Render authorization form to the user args.update({"client": client, "client_id": clientId, "state": state, "redirect_uri": redirectUri, "request_scopes": scopes, "title": "Authorization Request", "token": authToken}) # Signature to ensure that the hidden params aren't changed message = "%s:%s:%s:%s:%s" % \ (myId, clientId, ' '.join(scopes), redirectUri, state) checksum = hmac.new(myOrgId, message, hashlib.sha256) args.update({"signature":checksum.hexdigest()}) t.render(request, "oauth.mako", **args)
def _error(self, request, errstr): args = {"error": True, "errstr": errstr, "title": "Authorization Error"} t.render(request, "oauth.mako", **args) return True