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")
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])
def removeConvFromFeed(x): timestamps = [col.column.name for col in x] if timestamps: yield db.batch_remove({'feed': [feedId]}, names=timestamps) else: yield db.remove(feedId, 'feed', conv['meta']['uuid']) yield db.remove(feedId, 'feedItems', super_column=convId)
def _deletePresetTag(self, request): orgId = request.getSession(IAuthInfo).organization tagId = utils.getRequestArg(request, 'id') if not tagId: return try: tag = yield db.get(orgId, 'orgTags', super_column=tagId) tag = utils.supercolumnsToDict([tag]) tagName = tag[tagId]['title'] if 'isPreset' in tag[tagId]: yield db.remove(orgId, "orgTags", 'isPreset', tagId) yield db.remove(orgId, 'orgPresetTags', tagName) presetTags = yield db.get_slice(orgId, "orgPresetTags") 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, 'tags': tags_} request.write('$("#tag-%s").remove()' % (tagId)) except ttypes.NotFoundException: return
def clearChannels(userId, sessionId): key = "%s:%s" % (userId, sessionId) cols = yield db.get_slice(key, "sessionChannelsMap") channels = utils.columnsToDict(cols).keys() for channelId in channels: yield db.remove(channelId, "channelSubscribers", key) yield db.remove(key, "sessionChannelsMap")
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)
def deleteFileInfo(myId, orgId, itemId, item, conv=None): if 'parent' in item['meta']: if not conv: conv = yield db.get_slice(item['meta']['parent'], 'items', ['meta']) conv = utils.supercolumnsToDict(conv) convId = item['meta']['parent'] else: conv = item convId = itemId acl = pickle.loads(conv['meta']['acl']) allowedGroups = acl.get('accept', {}).get('groups', []) deniedGroups = acl.get('deny', {}).get('groups', []) groups = [x for x in allowedGroups if x not in deniedGroups] allowedOrgs = acl.get('accept', {}).get('orgs', []) ownerId = conv['meta']['owner'] entityIds = [myId] entityIds.extend(groups) entityIds.extend(allowedOrgs) entityIds_ = yield utils.expandAcl(myId, orgId, conv['meta']['acl'], convId, ownerId, True) entityIds.extend(entityIds_) deferreds = [] for attachmentId in item.get('attachments', {}): col = yield db.get_slice(attachmentId, 'attachmentVersions', count=1) tuuid = col[0].column.name deferreds.append(db.remove(myId, "user_files", tuuid)) #TODO: use batch remove/batch mutate for entityId in entityIds: deferreds.append(db.remove(entityId, "entityFeed_files", tuuid)) if deferreds: yield defer.DeferredList(deferreds)
def clearSession(self, uid): session = yield self.getSession(uid) authInfo = session.getComponent(IAuthInfo) userId = authInfo.username orgId = authInfo.organization yield db.remove(uid, "sessions", "auth") yield db.remove(userId, "userSessionsMap", uid) yield utils.cleanupChat(uid, userId, orgId)
def _editCompany(self, request): (appchange, script, args, myId) = yield self._getBasicArgs(request) remove = utils.getRequestArg(request, 'action') == 'd' encodedCompanyId = utils.getRequestArg(request, 'id', sanitize=False) companyId = utils.decodeKey(encodedCompanyId) if encodedCompanyId else None if companyId and remove: db.remove(myId, "entities", companyId, "companies") request.write('$("#%s").remove();' % encodedCompanyId) return today = datetime.date.today() try: startYear = int(utils.getRequestArg(request, 'startyear')) startMonth = int(utils.getRequestArg(request, 'startmonth')) startDay = datetime.date(startYear, startMonth, 1) except (ValueError, TypeError): raise errors.InvalidRequest('Please give a valid start month and year') try: endYear = utils.getRequestArg(request, 'endyear') if not endYear: endYear = 9999 endMonth = 12 else: endYear = int(endYear) endMonth = int(utils.getRequestArg(request, 'endmonth')) endDay = datetime.date(endYear, endMonth, 1) except (ValueError, TypeError): raise errors.InvalidRequest('Please give a valid end month and year') if startDay > today or startDay > endDay or (endDay > today and endYear != 9999): raise errors.InvalidRequest('The start month/year and end month/year are invalid!') name = utils.getRequestArg(request, 'company') title = utils.getRequestArg(request, 'title') if not remove and not name: errors.MissingParams(['Name']) if companyId: db.remove(myId, "entities", companyId, "companies") newCompanyId = "%s%s:%s%s:%s" % (endYear, endMonth, startYear, startMonth, name) newCompanyVal = title db.insert(myId, "entities", newCompanyVal, newCompanyId, "companies") if companyId: yield t.renderScriptBlock(request, "settings.mako", "companyItem", False, "#"+encodedCompanyId, "replace", args=[newCompanyId, newCompanyVal]) else: onload = """$('#company-empty-msg').remove();"""+\ """$('#addemp-wrap').replaceWith('<div id="addemp-wrap"><button class="button ajax" id="addedu-button" data-ref="/settings/company">Add Company</button></div>');""" yield t.renderScriptBlock(request, "settings.mako", "companyItem", False, "#companies-wrapper", "append", True, handlers={'onload': onload}, args=[newCompanyId, newCompanyVal])
def _unblockUser(self, request, data=None): orgId = request.getSession(IAuthInfo).organization user = data['id'] emailId = user.basic.get("emailId", None) yield db.remove(emailId, "userAuth", "isBlocked") yield db.remove(orgId, "blockedUsers", user.id) t.renderScriptBlock(request, "admin.mako", "admin_actions", False, "#user-actions-%s" % (user.id), "set", args=[user.id, 'unblocked'])
def _removeFromPending(group, user): "" yield db.remove(group.id, "pendingConnections", "GI:%s" % (user.id)) yield db.remove(user.id, "pendingConnections", "GO:%s" % (group.id)) #also remove any group invites yield db.remove(user.id, "pendingConnections", "GI:%s" % (group.id)) cols = yield db.get_slice(group.id, "latest", ['groups']) cols = utils.supercolumnsToDict(cols) for tuuid, key in cols.get('groups', {}).items(): if key == user.id: yield db.remove(group.id, "latest", tuuid, 'groups')
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)
def _deleteKeyword(self, request): orgId = request.getSession(IAuthInfo).organization keyword = utils.getRequestArg(request, 'keyword') or '' keyword = utils.decodeKey(keyword) if not keyword: return yield db.remove(orgId, "keywords", keyword) yield db.remove(orgId, "originalKeywords", keyword) yield db.remove(orgId + ':' + keyword, "keywordItems") request.write('$("#keyword-%s").remove()' % (utils.encodeKey(keyword)))
def _moveConversation(self, request, convIds, toFolder): """Move a conversation or conversations from one folder to another. Keyword Arguments: convIds: List of conversation ids which need to be moved. toFolder: The final destination of the above conversations CF Changes: mConvFolders mUnreadConversations mAllConversations mDeletedConversations """ myId = request.getSession(IAuthInfo).username convs = yield db.multiget_slice(convIds, "mConversations") convs = utils.multiSuperColumnsToDict(convs) for convId in convs: conv = convs.get(convId, {}) if not conv: raise errors.InvalidMessage(convId) if myId not in conv.get('participants', {}): raise errors.MessageAccessDenied(convId) timeUUID = conv['meta']['uuid'] val = "%s:%s" % ('u' if toFolder == 'unread' else 'r', convId) cols = yield db.get_slice(convId, 'mConvFolders', [myId]) cols = utils.supercolumnsToDict(cols) for folder in cols[myId]: cf = self._folders[folder] if folder in self._folders else folder if toFolder != 'unread': if folder != 'mUnreadConversations': col = yield db.get(myId, cf, timeUUID) val = col.column.value yield db.remove(myId, cf, timeUUID) yield db.remove(convId, "mConvFolders", cf, myId) else: yield db.insert(myId, cf, "u:%s" % (convId), timeUUID) if toFolder == 'unread': val = "u:%s" % (convId) yield db.insert(convId, 'mConvFolders', '', 'mUnreadConversations', myId) yield db.insert(myId, 'mUnreadConversations', val, timeUUID) else: folder = self._folders[toFolder] yield db.insert(myId, folder, val, timeUUID) yield db.insert(convId, 'mConvFolders', '', folder, myId)
def updateAndPublishStatus(userId, orgId, sessionId, status, user=None): # Check if there is a change in the online status results = yield db.get_slice(orgId, 'presence', super_column=userId) results = utils.columnsToDict(results) oldPublishedStatus = getMostAvailablePresence(results.values()) # Update the online status if status != 'offline': yield db.insert(orgId, 'presence', status, sessionId, userId) else: yield db.remove(orgId, 'presence', sessionId, userId) # If status changed broadcast the change # XXX: Currently everyone on the network will get the presence update. # This will not scale well with big networks results[sessionId] = status newPublishedStatus = getMostAvailablePresence(results.values()) if oldPublishedStatus != newPublishedStatus: if not user: user = base.Entity(userId) yield user.fetchData() data = {"userId": userId, 'status': newPublishedStatus, 'name': user.basic['name'], 'title': user.basic['jobTitle'], 'avatar': utils.userAvatar(userId, user, 's')} yield comet.publish('/presence/' + orgId, data)
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)
def _unfollow(self, request): authInfo = request.getSession(IAuthInfo) myId = authInfo.username orgId = authInfo.organization tagId, tag = yield utils.getValidTagId(request, "id") count = int(tag[tagId].get('followersCount', 0)) if count % 5 == 3: count = yield db.get_count(tagId, "tagFollowers") count = count - 1 if count > 0 else count yield db.remove(tagId, 'tagFollowers', myId) yield db.insert(orgId, "orgTags", str(count), "followersCount", tagId) tag[tagId]['followersCount'] = count args = {'tags': tag} args['tagsFollowing'] = [] fromListTags = (utils.getRequestArg(request, '_pg') == '/tags/list') if fromListTags: t.renderScriptBlock(request, "tags.mako", "_displayTag", False, "#tag-%s" % tagId, "replace", args=[tagId], **args) else: t.renderScriptBlock(request, 'tags.mako', "tag_actions", False, "#tag-actions-%s" % (tagId), "set", args=[tagId, False, False])
def _updateExpertise(self, request, remove=False): myId = request.getSession(IAuthInfo).username orgId = request.getSession(IAuthInfo).organization expertise = utils.getRequestArg(request, 'expertise', False) if not expertise: raise errors.MissingParams(['Expertise']) if not remove: decoded = expertise.decode('utf-8', 'replace') if len(decoded) > 50 or not re.match('^[\w-]*$', decoded): raise errors.InvalidRequest('Expertise can only be upto 50 characters long and can include numerals, alphabet and hyphens (-) only.') yield db.insert(myId, "entities", '', expertise, "expertise") else: yield db.remove(myId, "entities", utils.decodeKey(expertise), "expertise") me = base.Entity(myId) yield me.fetchData([]) expertise = me.get('expertise') onload = "$('#expertise-textbox').val('');" yield t.renderScriptBlock(request, "settings.mako", "_expertise", False, "#expertise-container", "set", True, handlers={"onload": onload}, args=[expertise]) yield search.solr.updatePeopleIndex(myId, me, orgId)
def _removeTempFile(self, request): (appchange, script, args, myId) = yield self._getBasicArgs(request) landing = not self._ajax myOrgId = args["orgId"] SKey = config.get('CloudFiles', 'SecretKey') AKey = config.get('CloudFiles', 'AccessKey') bucket = config.get('CloudFiles', 'Bucket') creds = AWSCredentials(AKey, SKey) client = s3Client.S3Client(creds) fileId = utils.getRequestArg(request, "id") key = "%s/%s/%s" % (myOrgId, myId, fileId) #Check if the file is not in the "files" CF. In other words, it is not # attached to an existing item. Also check if I am the owner of the # file. Finally clear the existing entry in the "temp_files" CF res = yield db.get_slice(fileId, "tmp_files", ["fileId"]) if len(res) == 1: try: res = yield db.get(fileId, "files", super_column="meta") except ttypes.NotFoundException: file_info = yield client.head_object(bucket, key) owner = file_info['x-amz-meta-uid'][0] if owner == myId: yield client.delete_object(bucket, key) yield db.remove(fileId, "tmp_files") else: raise errors.EntityAccessDenied("attachment", fileId) else: raise errors.InvalidRequest()
def _delete(self, request): authinfo = request.getSession(IAuthInfo) myId = authinfo.username myOrgId = authinfo.organization clientId = utils.getRequestArg(request, "id", sanitize=False) client = yield db.get_slice(clientId, "apps") client = utils.supercolumnsToDict(client) if not client: raise errors.InvalidApp(clientId) if client["meta"]["author"] != myId: raise errors.AppAccessDenied(clientId) yield db.remove(clientId, "apps") yield db.remove(myId, "appsByOwner", clientId) yield db.remove(myOrgId, "appsByOwner", clientId)
def unlike(itemId, item, myId, orgId): # Make sure that I liked this item try: cols = yield db.get(itemId, "itemLikes", myId) likeTimeUUID = cols.column.value except ttypes.NotFoundException: defer.returnValue(None) convId = item["meta"].get("parent", itemId) if convId != itemId: conv = yield db.get(convId, "items", super_column="meta") conv = utils.supercolumnsToDict([conv]) else: conv = item convOwnerId = conv["meta"]["owner"] convType = conv["meta"]["type"] convACL = conv["meta"]["acl"] # 1. remove the user from likes list. yield db.remove(itemId, "itemLikes", myId) # Update the likes count likesCount = int(item["meta"].get("likesCount", "1")) if likesCount % 5 == 0: likesCount = yield db.get_count(itemId, "itemLikes") item['meta']['likesCount'] = likesCount - 1 yield db.insert(itemId, "items", str(likesCount - 1), "likesCount", "meta") responseType = 'L' # 2. Don't remove the user from followers list # (use can also become follower by responding to item, # so user can't be removed from followers list) # Ignore if i am owner of the item if myId != item["meta"]["owner"]: # 3. delete from user's feed, feedItems, feed_* likeUpdateVal = "L:%s:%s:%s" % (myId, itemId, item['meta']['owner']) yield Feed.unpush(myId, orgId, convId, conv, likeUpdateVal) # 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", likeTimeUUID) if convType in plugins and plugins[convType].hasIndex: yield db.remove(myId, "userItems_" + convType, likeTimeUUID) defer.returnValue(item)
def delete(self, myId, convId, conv): log.debug("plugin:delete", convId) user_tuids = {} # Get the list of every user who responded to this event res = yield db.get_slice(convId, "eventResponses") attendees = [x.column.name.split(":", 1)[1] for x in res] # Add all the invited people of the item res = yield db.get_slice(convId, "items", ['invitees']) res = utils.supercolumnsToDict(res) attendees.extend(res["invitees"].keys()) invitedPeople = res["invitees"].keys() log.debug("Maps", ["%s:%s"%(uId, convId) for \ uId in attendees]) # Get the Org and GroupIds if any. convMeta = conv["meta"] groupIds = convMeta["target"].split(",") if "target" in convMeta else [] attendees.extend(groupIds+[convMeta["org"]]) log.debug("Attendees", attendees) # Get the timeuuids that were inserted for this user res = yield db.multiget_slice(["%s:%s"%(uId, convId) for \ uId in attendees], "userAgendaMap") res = utils.multiColumnsToDict(res) for k, v in res.iteritems(): uid = k.split(":", 1)[0] tuids = v.keys() if tuids: user_tuids[uid] = tuids log.debug("userAgenda Removal", user_tuids) # Delete their entries in the user's list of event entries for attendee in user_tuids: yield db.batch_remove({'userAgenda': [attendee]}, names=user_tuids[attendee]) # Delete invitation entries for invited people invited_tuids = dict([[x, user_tuids[x]] for x in invitedPeople]) log.debug("userAgenda Invitation Removal", invited_tuids) for attendee in invited_tuids: yield db.batch_remove({'userAgenda': ['%s:%s' %(attendee, 'I')]}, names=invited_tuids[attendee]) log.debug("eventResponses Removal", convId) # Delete the event's entry in eventResponses yield db.remove(convId, "eventResponses") log.debug("userAgendaMap Removal", user_tuids) # Delete their entries in userAgendaMap for attendee in user_tuids: yield db.batch_remove({'userAgendaMap': ["%s:%s"%(attendee, convId)]}, names=user_tuids[attendee])
def _editSchool(self, request): (appchange, script, args, myId) = yield self._getBasicArgs(request) remove = utils.getRequestArg(request, 'action') == 'd' encodedSchoolId = utils.getRequestArg(request, 'id', sanitize=False) schoolId = utils.decodeKey(encodedSchoolId) if encodedSchoolId else None if schoolId and remove: db.remove(myId, "entities", schoolId, "schools") request.write('$("#%s").remove();' % encodedSchoolId) return curYear = datetime.date.today().year try: year = int(utils.getRequestArg(request, 'year')) if not 1920 < year <= curYear: raise ValueError except (ValueError,TypeError): raise errors.InvalidRequest('Invalid graduation year') name = utils.getRequestArg(request, 'school') degree = utils.getRequestArg(request, 'degree') if not remove and not name: errors.MissingParams(['Name']) if schoolId: db.remove(myId, "entities", schoolId, "schools") newSchoolId = "%s:%s" % (year, name) newSchoolVal = degree db.insert(myId, "entities", newSchoolVal, newSchoolId, "schools") if schoolId: yield t.renderScriptBlock(request, "settings.mako", "schoolItem", False, "#"+encodedSchoolId, "replace", args=[newSchoolId, newSchoolVal]) else: onload = """$('#school-empty-msg').remove();"""+\ """$('#addedu-wrap').replaceWith('<div id="addedu-wrap"><button class="button ajax" id="addedu-button" data-ref="/settings/school">Add School</button></div>');""" yield t.renderScriptBlock(request, "settings.mako", "schoolItem", False, "#schools-wrapper", "append", True, handlers={'onload': onload}, args=[newSchoolId, newSchoolVal])
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)
def unblock(group, user, me): """Unblock a blocked user. 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') yield db.remove(group.id, "blockedUsers", user.id)
def updateData(): convIds = set() rows = yield db.get_range_slice('item_files', count=1000) for row in rows: convId = row.key convIds.add(convId) attachments = utils.supercolumnsToDict(row.columns) for attachmentId in attachments: for timeuuid in attachments[attachmentId]: encodedTimeUUID, aid, name, size, ftype = attachments[attachmentId][timeuuid].split(':') yield db.insert(attachmentId, "attachmentVersions", "%s:%s:%s:%s" %(aid, name, size, ftype), timeuuid) rows = yield db.get_range_slice('items', count=10000) for row in rows: itemId = row.key item = utils.supercolumnsToDict(row.columns) attachments = {} for attachmentId in item.get('attachments', {}): if len(item['attachments'][attachmentId].split(':')) == 4: x,name, size, ftype = item['attachments'][attachmentId].split(':') attachments[attachmentId] = "%s:%s:%s" %(name, size, ftype) if attachments: yield db.remove(itemId, 'items', super_column='attachments') yield db.batch_insert(itemId, "items", {"attachments": attachments}) rows = yield db.get_range_slice('mConversations', count=10000) for row in rows: messageId = row.key message = utils.supercolumnsToDict(row.columns) attachments = {} print messageId for attachmentId in message.get('attachments', {}): if len(message['attachments'][attachmentId].split(':')) == 4: x,name, size, ftype = message['attachments'][attachmentId].split(':') attachments[attachmentId] = "%s:%s:%s" %(name, size, ftype) if attachments: yield db.remove(messageId, 'mConversations', super_column='attachments') yield db.batch_insert(messageId, "mConversations", {"attachments": attachments})
def edit(me, group, name, access, desc, displayPic): """update group meta info. Only group-admin can edit group meta info. Keyword params: @me: @group: @name: name of the group. @access: group access type (open/closed). @desc: description of the group. @displayPic: profile pic of the group. """ if me.id not in group.admins: raise errors.PermissionDenied('Only administrator can edit group meta data') if name: start = name.lower() + ':' cols = yield db.get_slice(me.basic['org'], "entityGroupsMap", start=start, count=1) for col in cols: name_, groupId_ = col.column.name.split(':') if name_ == name.lower() and groupId_ != group.id: raise errors.InvalidGroupName(name) meta = {'basic': {}} if name and name != group.basic['name']: meta['basic']['name'] = name if desc and desc != group.basic.get('desc', ''): meta['basic']['desc'] = desc if access in ['closed', 'open'] and access != group.basic['access']: meta['basic']['access'] = access if displayPic: avatar = yield saveAvatarItem(group.id, me.basic['org'], displayPic) meta['basic']['avatar'] = avatar if name and name != group.basic["name"]: members = yield db.get_slice(group.id, "groupMembers") members = utils.columnsToDict(members).keys() entities = members + [me.basic['org']] oldColName = "%s:%s" % (group.basic["name"].lower(), group.id) colname = '%s:%s' % (name.lower(), group.id) mutations = {} for entity in entities: mutations[entity] = {'entityGroupsMap': {colname: '', oldColName: None}} #XXX:notify group-members about the change in name yield db.batch_mutate(mutations) if meta['basic']: yield db.batch_insert(group.id, 'entities', meta) if not desc and group.basic.get('desc', ''): yield db.remove(group.id, "entities", 'desc', 'basic') if (not desc and group.basic.get('desc', '')) or meta['basic']: defer.returnValue(True)
def _revoke(self, request): authinfo = request.getSession(IAuthInfo) myId = authinfo.username myOrgId = authinfo.organization clientId = utils.getRequestArg(request, "id", sanitize=False) client = yield db.get_slice(clientId, "apps") client = utils.supercolumnsToDict(client) if not client: raise errors.InvalidApp(clientId) me = yield db.get_slice(myId, "entities", ["apikeys", "apps"]) me = utils.supercolumnsToDict(me) # Remove the client in case of API Key if client["meta"]["category"] == "apikey": if client["meta"]["author"] != myId: raise errors.AppAccessDenied(clientId) d1 = db.remove(clientId, "apps") d2 = db.remove(myId, "appsByOwner", clientId) d3 = db.remove(myId, "entities", clientId, "apikeys") d4 = db.remove(myOrgId, "appsByOwner", clientId) yield defer.DeferredList([d1, d2, d3, d4]) # Remove the refresh token # XXX: Valid access tokens could still exist else: authorization = me["apps"][clientId] d1 = db.remove(myId, "entities", clientId, "apps") d2 = db.remove(authorization, "oAuthData") yield defer.DeferredList([d1, d2])
def unfollow(group, user): """Remove @user from @group followers Keyword params: @group: entity object of group @user: entity object of user """ try: yield db.get(group.id, "groupMembers", user.id) yield db.remove(group.id, "followers", user.id) defer.returnValue(True) except ttypes.NotFoundException: return
def _blockUser(self, request, data=None): authInfo = request.getSession(IAuthInfo) myId = authInfo.username orgId = authInfo.organization user = data['id'] # Admin cannot block himself. if user.id == myId: raise errors.InvalidRequest(_("You cannot block yourself.")) emailId = user.basic.get("emailId", None) yield db.insert(emailId, "userAuth", 'True', "isBlocked") yield db.insert(orgId, "blockedUsers", '', user.id) sessionIds = yield db.get_slice(user.id, "userSessionsMap") sessionIds = utils.columnsToDict(sessionIds) for sessionId in sessionIds: yield db.remove(sessionId, "sessions") yield utils.cleanupChat(sessionId, user.id, orgId) yield db.remove(user.id, "userSessionsMap") t.renderScriptBlock(request, "admin.mako", "admin_actions", False, "#user-actions-%s" % (user.id), "set", args=[user.id, 'blocked'])