def _comment(self, request, data=None): authInfo = request.getSession(IAuthInfo) myId = authInfo.username orgId = authInfo.organization convId, conv = data['parent'] fids = data['fId'] comment, snippet = data['comment'] review = data['_review'] itemId, convId, items, keywords = yield Item._comment(convId, conv, comment, snippet, myId, orgId, False, review, fids) if keywords: block = t.getBlock('item.mako', 'requireReviewDlg', keywords=keywords, convId=convId) request.write('$$.convs.reviewRequired(%s, "%s");' % (json.dumps(block), convId)) return # Finally, update the UI entities = base.EntitySet([myId]) yield entities.fetchData() args = {"entities": entities, "items": items, "me": entities[myId]} numShowing = utils.getRequestArg(request, "nc") or "0" numShowing = int(numShowing) + 1 responseCount = items[convId]['meta']['responseCount'] isItemView = (utils.getRequestArg(request, "_pg") == "/item") t.renderScriptBlock(request, 'item.mako', 'conv_comments_head', False, '#comments-header-%s' % (convId), 'set', args=[convId, responseCount, numShowing, isItemView], **args) onload = """(function(){$('.comment-input', '#comment-form-%s').val(''); $('[name=\"nc\"]', '#comment-form-%s').val('%s');})();$('#comment-attach-%s-uploaded').empty()""" % (convId, convId, numShowing, convId) t.renderScriptBlock(request, 'item.mako', 'conv_comment', False, '#comments-%s' % convId, 'append', True, handlers={"onload": onload}, args=[convId, itemId], **args)
def _uploadDone(self, request): SKey = config.get('CloudFiles', 'SecretKey') AKey = config.get('CloudFiles', 'AccessKey') creds = AWSCredentials(AKey, SKey) client = s3Client.S3Client(creds) bucket = utils.getRequestArg(request, "bucket") key = utils.getRequestArg(request, "key") file_info = yield client.head_object(bucket, key) tmp_files_info = {} name = file_info['x-amz-meta-filename'][0] size = file_info['content-length'][0] fileType = file_info['content-type'][0] fileId = file_info['x-amz-meta-fileid'][0] val = "%s:%s:%s:%s" % (fileId, name, size, fileType) filename = urlsafe_b64decode(name) tmp_files_info[fileId] = [fileId, filename, size, fileType] # XXX: We currently don't generate any thumbnails! # yield threads.deferToThread(self._enqueueMessage, bucket, key, name, fileType) yield db.insert(fileId, "tmp_files", val, "fileId") response = """ <textarea data-type="application/json"> {"ok": true, "files": %s} </textarea> """ % (json.dumps(tmp_files_info)) request.write(response)
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 _changePassword(self, request): (appchange, script, args, myId) = yield self._getBasicArgs(request) currentPass = utils.getRequestArg(request, "curr_passwd", sanitize=False) newPass = utils.getRequestArg(request, "passwd1", sanitize=False) rptPass = utils.getRequestArg(request, "passwd2", sanitize=False) if not currentPass: request.write('$$.alerts.error("%s");' % _("Enter your current password")) defer.returnValue(None) if not newPass: request.write('$$.alerts.error("%s");' % _("Enter new password")) defer.returnValue(None) if not rptPass: request.write('$$.alerts.error("%s");' % _("Confirm new password")) defer.returnValue(None) if newPass != rptPass: request.write('$$.alerts.error("%s");' % _("Passwords do not match")) defer.returnValue(None) if currentPass == newPass: request.write('$$.alerts.error("%s");' % _("New password should be different from current password")) defer.returnValue(None) emailId = args["me"].basic["emailId"] col = yield db.get(emailId, "userAuth", "passwordHash") storedPass= col.column.value if not utils.checkpass(currentPass, storedPass): request.write('$$.alerts.error("%s");' % _("Incorrect Password")) defer.returnValue(None) newPasswd = utils.hashpass(newPass) yield db.insert(emailId, "userAuth", newPasswd, "passwordHash") request.write('$$.alerts.info("%s");' % _('Password changed'))
def get(self, request, entityId=None): itemType = utils.getRequestArg(request, 'type') start = utils.getRequestArg(request, 'start') or '' more = utils.getRequestArg(request, 'more') or False if more: return self._renderMore(request, entityId, start, itemType) else: return self._render(request, entityId, start, itemType)
def _getFileInfo(self, request): """Fetch the meta info on a file that is being requested to be downloaded. Returns the meta info of the file in question. Keyword Arguments: itemId: id of the conversation on which this file is attached. attachmentId: id of the file on the amazon S3 that is to be served. version: version of the file on the amazon S3 that the user is requesting. """ authinfo = request.getSession(IAuthInfo) myId = authinfo.username myOrgId = authinfo.organization itemId = utils.getRequestArg(request, "id", sanitize=False) attachmentId = utils.getRequestArg(request, "fid", sanitize=False) version = utils.getRequestArg(request, "ver", sanitize=False) or '' columns = ["meta", "attachments", "participants"] if not (itemId and attachmentId): raise errors.MissingParams([]) item = yield db.get_slice(itemId, "mConversations", columns) item = utils.supercolumnsToDict(item) if not item: raise errors.InvalidMessage(itemId) if myId not in item.get('participants', {}): raise errors.MessageAccessDenied(itemId) # Check if the attachmentId belong to item if attachmentId not in item['attachments'].keys(): raise errors.InvalidAttachment(itemId, attachmentId, version) fileId, filetype, name = None, 'text/plain', 'file' if version: version = utils.decodeKey(version) try: cols = yield db.get(attachmentId, "attachmentVersions", version) except ttypes.NotFoundException: raise errors.InvalidAttachment(itemId, attachmentId, version) except ttypes.InvalidRequestException: raise errors.InvalidAttachment(itemId, attachmentId, 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] 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])
def _S3FormData(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') domain = config.get('CloudFiles', 'Domain') bucket = config.get('CloudFiles', 'Bucket') if domain == "": calling_format = SubdomainCallingFormat() domain = "s3.amazonaws.com" else: calling_format = VHostCallingFormat() conn = S3Connection(AKey, SKey, host=domain, is_secure=True, calling_format=calling_format) filename = utils.getRequestArg(request, "name") or None #TODO:If name is None raise an exception mime = utils.getRequestArg(request, "mime") or None if mime: if not mimetypes.guess_extension(mime): mime = mimetypes.guess_type(filename)[0] else: mime = mimetypes.guess_type(filename)[0] if not mime: mime = "text/plain" filename = urlsafe_b64encode(filename) fileId = utils.getUniqueKey() key = '%s/%s/%s' % (myOrgId, myId, fileId) attachment_filename = 'attachment;filename=\"%s\"' % (filename) x_conds = ['{"x-amz-meta-uid":"%s"}' % myId, '{"x-amz-meta-filename":"%s"}' % filename, '{"x-amz-meta-fileId":"%s"}' % fileId, '{"content-type":"%s"}' % mime] x_fields = [{"name":"x-amz-meta-uid", "value":"%s" % myId}, {"name":"x-amz-meta-filename", "value":"%s" % filename}, {"name":"content-type", "value":"%s" % mime}, {"name":"x-amz-meta-fileId", "value":"%s" % fileId}] max_content_length = constants.MAX_FILE_SIZE x_conds.append('["content-length-range", 0, %i]' % max_content_length) redirect_url = config.get('General', 'URL') + "/files/update" form_data = conn.build_post_form_args(bucket, key, http_method="https", fields=x_fields, conditions=x_conds, success_action_redirect=redirect_url) request.write(json.dumps([form_data])) defer.returnValue(0)
def _registerClient(self, request): (appchange, script, args, myId) = yield self._getBasicArgs(request) landing = not self._ajax myOrgId = args["orgId"] name = utils.getRequestArg(request, "name") desc = utils.getRequestArg(request, "desc") scope = utils.getRequestArg(request, "scope", multiValued=True) category = utils.getRequestArg(request, "category") redirect = utils.getRequestArg(request, "redirect", sanitize=False) if not name: raise errors.MissingParams(["Name"]) if not scope: raise errors.MissingParams(["Permissions"]) if category != "apikey" and not redirect: raise errors.MissingParams(["Redirect URL"]) knownScopes = globals().get("scopes") unknownScopes = [x for x in scope if x not in knownScopes.keys()] if category not in ["webapp", "native", "apikey"] or unknownScopes: raise errors.BaseError("Invalid value sent for Type/Permissions") clientId = utils.getUniqueKey() clientSecret = utils.getRandomKey() meta = { "author": myId, "name": name, "org": myOrgId, "secret": utils.hashpass(clientSecret), "scope": " ".join(scope), "category": category, } if category != "apikey": meta["redirect"] = b64encode(redirect) meta["desc"] = desc yield db.batch_insert(clientId, "apps", {"meta": meta}) yield db.insert(myId, "appsByOwner", "", clientId) yield db.insert(myOrgId, "appsByOwner", "", clientId) else: yield db.batch_insert(clientId, "apps", {"meta": meta}) yield db.insert(myId, "entities", "", clientId, "apikeys") self.setTitle(request, name) args["clientId"] = clientId args["client"] = meta args["client"]["secret"] = clientSecret t.renderScriptBlock(request, "apps.mako", "registrationResults", landing, "#apps-contents", "set", **args)
def _signupGotUserData(self, request): authinfo = yield defer.maybeDeferred(request.getSession, IAuthInfo) if authinfo.username: raise errors.InvalidRequest(_("Another user is currently signed-in. Please signout and then click the invitation link")) emailId = utils.getRequestArg(request, "email") token = utils.getRequestArg(request, "token") valid = yield self._isValidToken(emailId, token) if not valid: raise InvalidRegistration("The invite is not valid anymore. Already registered?") yield self._addUser(request)
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 _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 render_GET(self, request): segmentCount = len(request.postpath) viewType = utils.getRequestArg(request, "type") or "all" start = utils.getRequestArg(request, "start") or "" start = utils.decodeKey(start) d = None if segmentCount == 0: d = self._render(request, viewType, start) elif segmentCount == 1 and self._ajax and request.postpath[0] == "invite": d = self._renderInvitePeople(request) elif segmentCount == 1 and request.postpath[0] == "suggestions": d = self._renderSuggestions(request) return self._epilogue(request, d)
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 _members(self, request): """Allow a participant of a conversation to add or remove another user to the conversation. Keyword arguments: action: Either one of [add, remove] convId: The conversation to which this user wants to either add or remove another user. """ (appchange, script, args, myId) = yield self._getBasicArgs(request) landing = not self._ajax action = utils.getRequestArg(request, "action") convId = utils.getRequestArg(request, 'parent') or None if not convId: raise errors.MissingParams([_('Conversation Id')]) if action not in ('add', 'remove'): raise errors.InvalidRequest() if action == "add": yield self._addMembers(request) elif action == "remove": yield self._removeMembers(request) cols = yield db.get_slice(convId, "mConversations") conv = utils.supercolumnsToDict(cols) participants = set(conv['participants']) people = base.EntitySet(participants) yield people.fetchData() args.update({"people": people}) args.update({"conv": conv}) args.update({"id": convId}) args.update({"view": "message"}) if script: onload = """ $('#conversation_add_member').autocomplete({ source: '/auto/users', minLength: 2, select: function( event, ui ) { $('#conversation_recipients').attr('value', ui.item.uid) } }); """ t.renderScriptBlock(request, "message.mako", "right", landing, ".right-contents", "set", True, handlers={"onload": onload}, **args)
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 _invite(self, request): src = utils.getRequestArg(request, 'from') or None rawEmailIds = request.args.get('email') stats = yield invite(request, rawEmailIds) if not src: src = "sidebar" if len(rawEmailIds) == 1 else "people" if src == "sidebar" and self._ajax: request.write("$('#invite-others').val('');") elif src == "sidebar": request.redirect('/feed/') elif src == "people" and self._ajax: pass elif src == "people": request.redirect('/people') if not stats and self._ajax: request.write("$$.alerts.error('%s');" \ % (_("Use company email addresses only."))) elif stats and self._ajax: if len(stats[0]) == 1: request.write("$$.alerts.info('%s');" % _("Invitation sent")) request.write("$$.dialog.close('invitepeople-dlg', true);") elif len(stats[0]) > 1: request.write("$$.alerts.info('%s');" % _("Invitations sent")) request.write("$$.dialog.close('invitepeople-dlg', true);") else: #TODO: when user tries to send invitations to existing members, # show these members as add-as-friend/follow list request.write("$$.alerts.info('%s');\ $$.dialog.close('invitepeople-dlg', true);" \ % _("Invitations sent"))
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))
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 checkSession(authinfo): if authinfo.username: redirectURL = utils.getRequestArg(request, "_r", sanitize=False) or "/feed/" util.redirectTo(urllib.unquote(redirectURL), request) request.finish() else: self._renderSigninForm(request)
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(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 _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 _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 _verifyProfile(self, request): email = utils.getRequestArg(request, 'email') token = utils.getRequestArg(request, 'token') if not (email and token): raise MissingParams(['Email', 'Account Verification Token']) cols = yield db.get_slice(email, "userAuth", ["reactivateToken", "isFlagged"]) cols = utils.columnsToDict(cols) if "isFlagged" in cols: storedToken = cols.get("reactivateToken", None) if storedToken == token: yield db.batch_remove({"userAuth": [email]}, names=["reactivateToken", "isFlagged"]) request.redirect('/signin')
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 _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 _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)
def _addPresetTag(self, request): orgId = request.getSession(IAuthInfo).organization tagNames = utils.getRequestArg(request, 'tag') if not tagNames: return invalidTags = [] tagNames = [x.strip().decode('utf-8', 'replace') for x in tagNames.split(',')] for tagName in tagNames: if len(tagName) < 50 and regex.match('^[\w-]*$', tagName): yield tags.ensureTag(request, tagName, orgId, True) else: invalidTags.append(tagName) presetTags = yield db.get_slice(orgId, "orgPresetTags") presetTags = utils.columnsToDict(presetTags, ordered=True).values() tags_ = yield db.get_slice(orgId, "orgTags", presetTags) tags_ = utils.supercolumnsToDict(tags_) args = {'tags': tags_, 'tagsList': presetTags} handlers = {} if invalidTags: if len(invalidTags) == 1: message = " %s is invalid tag." % (invalidTags[0]) else: message = " %s are invalid tags. " % (",".join(invalidTags)) errorMsg = "%s <br/>Tag can contain alpha-numeric characters or hyphen only. It cannot be more than 50 characters" % (message) handlers = {'onload': "$$.alerts.error('%s')" % (errorMsg)} t.renderScriptBlock(request, "admin.mako", "list_tags", False, "#content", "set", True, handlers=handlers, **args)
def _tags(self, request, term): if len(term) < 2: request.write("[]") return orgId = request.getSession(IAuthInfo).organization finish = _getFinishTerm(term) itemId = utils.getRequestArg(request, "itemId") if not itemId: request.write("[]") return toFetchTags = set() d1 = db.get_slice(orgId, "orgTagsByName", start=term, finish=finish, count=10) tags = [] matchedTags = yield d1 matchedTags = [match.column.value for match in matchedTags] if matchedTags: matchedTags = yield db.get_slice(orgId, "orgTags", matchedTags) matchedTags = utils.supercolumnsToDict(matchedTags) for tagId in matchedTags: tags.append({"title": matchedTags[tagId]["title"], "id": tagId}) tags.sort(key=itemgetter("title")) output = [] template = self._singleLineTemplate for tag in tags: data = {"title": tag["title"], "meta": ""} output.append({"value": tag["title"], "label": template % data, "href": "/tags?id=%s" % tag["id"]}) request.write(json.dumps(output))