def update(self): self.execute(None) user = get_current() objects = find_entities( user=user, interfaces=[IChallenge], metadata_filter={'states': ['pending']}, sort_on='release_date') url = self.request.resource_url(self.context, self.name) batch = Batch( objects, self.request, url=url, default_size=BATCH_HOME_DEFAULT_SIZE) batch.target = "#results-home-challenges" len_result = batch.seqlen user = get_current() if len_result == 0: self.no_challenges = True result = {} result_body = [] else: self.title = self.request.localizer.translate(self.title) result_body, result = render_listing_objs( self.request, batch, user, 'card') values = { 'bodies': result_body, 'batch': batch } body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]} return result
def start(self, context, request, appstruct, **kw): context.state = PersistentList(['rejected']) context.modified_at = datetime.datetime.now(tz=pytz.UTC) context.reindex() author = getattr(context, 'author', None) user = get_current() if author and user is not author: site = get_site_folder(True, request) alert('internal', [site], [author], {'kind': InternalAlertKind.moderation_alert, 'subjects': [context]}) request.registry.notify(ActivityExecuted(self, [context], get_current())) return {}
def start(self, context, request, appstruct, **kw): root = getSite() copy_of_amendment = copy(context, (context.proposal, 'amendments'), omit=('created_at', 'modified_at', 'explanations')) keywords_ids = appstruct.pop('keywords') result, newkeywords = root.get_keywords(keywords_ids) for nkw in newkeywords: root.addtoproperty('keywords', nkw) result.extend(newkeywords) appstruct['keywords_ref'] = result copy_of_amendment.set_data(appstruct) copy_of_amendment.text = normalize_text(copy_of_amendment.text) copy_of_amendment.setproperty('originalentity', context) copy_of_amendment.state = PersistentList(['draft']) copy_of_amendment.setproperty('author', get_current()) localizer = request.localizer # copy_of_amendment.title = context.proposal.title + \ # localizer.translate(_('_Amended version ')) + \ # str(getattr(context.proposal, # '_amendments_counter', 1)) copy_of_amendment.title = localizer.translate(_('Amended version ')) + \ str(getattr(context.proposal, '_amendments_counter', 1)) grant_roles(roles=(('Owner', copy_of_amendment), )) copy_of_amendment.text_diff = get_text_amendment_diff( context.proposal, copy_of_amendment) copy_of_amendment.reindex() context.proposal._amendments_counter = getattr(context.proposal, '_amendments_counter', 1) + 1 context.reindex() return {'newcontext': copy_of_amendment}
def _add_sub_amendment(self, context, request, group): data = self._get_explanation_data(context, group) keywords_ref = context.keywords_ref amendment = Amendment() for k in keywords_ref: amendment.addtoproperty('keywords_ref', k) amendment.set_data(data) context.proposal.addtoproperty('amendments', amendment) amendment.state.append('published') grant_roles(roles=(('Owner', amendment), )) amendment.setproperty('author', get_current()) #amendment.setproperty('originalentity', context) explanations = sorted(group['explanations'], key=lambda e: e['oid']) i = 1 for explanation in explanations: explanation['oid'] = i amendment.explanations[str(i)] = explanation i += 1 explanations, text_diff = get_text_amendment_diff_submitted( amendment, request) amendment.explanations = PersistentDict(explanations) amendment.text_diff = text_diff amendment.reindex() self._publish_ideas(amendment)
def update(self): result = {} site = get_site_folder(True, self.request) user = get_current(self.request) is_manager = has_any_roles( user=user, roles=('Admin', ('SiteAdmin', site))) or\ is_site_moderator(self.request) duplicates = find_duplicates_artist(self.context, self.duplicates_state) diff_bodies = {} context_view = self.content( args={'object': self.context}, template=self.context.templates.get('diff', None))['body'] for duplicate in duplicates: duplicate_view = self.content( args={'object': duplicate}, template=duplicate.templates.get('diff', None))['body'] soupt, textdiff = html_diff_wrapper.render_html_diff( context_view, duplicate_view) diff_bodies[duplicate] = (textdiff, get_oid(duplicate)) values = {'context': self.context, 'oid': get_oid(self.context), 'context_view': context_view, 'contents': diff_bodies, 'row_len': math.ceil(len(diff_bodies)/2), 'is_manager': is_manager, 'view': self} body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]} return result
def start(self, context, request, appstruct, **kw): user = get_current() source = appstruct['source'] targets = appstruct['targets'] if can_access(user, source) and all(can_access(user, target) for target in targets): diff_bodies = {} source_view = renderers.render( source.templates.get('diff', None), {'object': source}, request) for target in targets: target_view = renderers.render( target.templates.get('diff', None), {'object': target}, request) soupt, textdiff = html_diff_wrapper.render_html_diff( source_view, target_view) diff_bodies[target] = (textdiff, get_oid(target)) return {'context_view': source_view, 'contents': diff_bodies} return {}
def start(self, context, request, appstruct, **kw): root = request.root url = request.resource_url(context, "") deadline_date = context.init_deadline( datetime.datetime.now(tz=pytz.UTC)) deadline_str = to_localized_time( deadline_date, request, translate=True) mail_template = root.get_mail_template( 'preregistration', getattr(context, 'locale', root.locale)) email_data = get_user_data(context, 'recipient', request) subject = mail_template['subject'].format( novaideo_title=root.title) deadline_str = to_localized_time( deadline_date, request, translate=True) message = mail_template['template'].format( url=url, deadline_date=deadline_str.lower(), novaideo_title=root.title, **email_data) alert('email', [root.get_site_sender()], [context.email], subject=subject, body=message) request.registry.notify(ActivityExecuted( self, [context], get_current())) return {}
def before_update(self): user = get_current() if not getattr(user, 'is_cultural_animator', False): self.schema.children.remove(self.schema.get('structure')) if not has_role(role=('Advertiser',), ignore_superiors=True): self.schema.children.remove(self.schema.get('company'))
def update(self): self.execute(None) root = getSite() try: navbars = generate_navbars(self, self.context, self.request) except ObjectRemovedException: return HTTPFound(self.request.resource_url(root, '')) result = {} user = get_current() parent = self.context.__parent__ can_access_parent = False if not (parent is root) and can_access(user, parent): can_access_parent = True values = {'object': self.context, 'navbar_body': navbars['navbar_body'], 'can_access_parent': can_access_parent} body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) item['messages'] = navbars['messages'] item['isactive'] = navbars['isactive'] result.update(navbars['resources']) result['coordinates'] = {self.coordinates: [item]} return result
def start(self, context, request, appstruct, **kw): user = get_current() context.state = PersistentList(['archived']) context.modified_at = datetime.datetime.now(tz=pytz.UTC) context.reindex() request.registry.notify(ActivityExecuted(self, [context], user)) return {}
def update(self): self.execute(None) objects = find_entities( user=get_current(), interfaces=[IOrganization], sort_on='modified_at', reverse=True) batch = Batch(objects, self.request, default_size=BATCH_DEFAULT_SIZE) batch.target = "#results_organizations" len_result = batch.seqlen index = str(len_result) if len_result > 1: index = '*' self.title = _(CONTENTS_MESSAGES[index], mapping={'nember': len_result}) result_body = [] for obj in batch: object_values = {'object': obj} body = self.content(args=object_values, template=obj.templates['default'])['body'] result_body.append(body) result = {} values = { 'bodies': result_body, 'length': len_result, 'batch': batch, } body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]} return result
def start(self, context, request, appstruct, **kw): root = getSite() user = get_current(request) mask = user.get_mask(root) if hasattr(user, 'get_mask') else user author = mask if appstruct.get('anonymous', False) and mask else user answer = appstruct['_object_data'] context.addtoproperty('answers', answer) answer.init_title() answer.format(request) answer.state = PersistentList(['published']) answer.reindex() if getattr(answer, 'option', None) is not None: answer.question.add_selected_option(user, answer.option) transaction.commit() grant_roles(user=author, roles=(('Owner', answer), )) answer.setproperty('author', author) if appstruct.get('associated_contents', []): answer.set_associated_contents( appstruct['associated_contents'], author) self._alert_users(context, request, author, answer) context.reindex() user.set_read_date(answer.channel, datetime.datetime.now(tz=pytz.UTC)) return {}
def update(self): self.execute(None) try: navbars = generate_navbars(self, self.context, self.request) except ObjectRemovedException: return HTTPFound(self.request.resource_url(getSite(), '')) result = {} user = get_current() related_contents, len_contents = self.get_related_contents(user) values = { 'object': self.context, 'state': get_states_mapping(user, self.context, self.context.state[0]), 'related_contents': related_contents, 'len_contents': len_contents, 'navbar_body': navbars['navbar_body'], 'actions_bodies': navbars['body_actions'], 'footer_body': navbars['footer_body'], 'get_oid': get_oid, 'is_portalmanager': has_role(user=user, role=('PortalManager',)) } body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) item['messages'] = navbars['messages'] item['isactive'] = navbars['isactive'] result.update(navbars['resources']) result['coordinates'] = {self.coordinates: [item]} return result
def add(self): user = get_current() path = self.params('path') dir_ = None if path is not None: #dir_ = traversal.traverse(self.context, path).get('context', None) dir_ = get_file(path) if dir_ is None: dir_ = user field_storage = self.params('newfile') new_img = Image( fp=field_storage.file, title=field_storage.filename) new_img.mimetype = field_storage.type new_img.fp.seek(0) if hasattr(dir_, 'files'): dir_.addtoproperty('files', new_img) else: root = getSite() root.addtoproperty('files', new_img) grant_roles(user=user, roles=(('Owner', new_img), )) result = { 'Path': get_file_url(new_img, self.request), 'Name': new_img.title, 'Code': 0 } return '<textarea>'+json.dumps(result)+'</textarea>'
def update(self): self.execute(None) objects = self.context.organizations now = datetime.datetime.now(tz=pytz.UTC) objects = sorted(objects, key=lambda e: getattr(e, 'modified_at', now), reverse=True) batch = Batch( objects, self.request, default_size=BATCH_DEFAULT_SIZE) batch.target = "#results_organizations" len_result = batch.seqlen index = str(len_result) if len_result > 1: index = '*' self.title = _(CONTENTS_MESSAGES[index], mapping={'number': len_result}) user = get_current() result_body, result = render_listing_objs( self.request, batch, user) values = { 'bodies': result_body, 'length': len_result, 'batch': batch, } body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]} return result
def start(self, context, request, appstruct, **kw): root = getSite() comment = appstruct['_object_data'] user = get_current(request) mask = user.get_mask(root) author = mask if appstruct.get('anonymous', False) and mask else user channel = root.channel #TODO get if channel: channel.addtoproperty('comments', comment) channel.add_comment(comment) comment.state = PersistentList(['published']) comment.reindex() comment.format(request) comment.setproperty('author', author) grant_roles(user=author, roles=(('Owner', comment), )) if appstruct.get('associated_contents', []): comment.set_associated_contents( appstruct['associated_contents'], user) self._alert_users(context, request, author, comment, channel) context.reindex() user.set_read_date(channel, datetime.datetime.now(tz=pytz.UTC)) return {}
def update(self): comment_id = self.params('comment_id') user = get_current() comment = None try: obj = get_obj(int(comment_id)) if comment_id else None if isinstance(obj, Comment) and can_access(user, obj): comment = obj except Exception as error: log.warning(error) comment_body = '' if comment: comment_body = render_listing_obj( self.request, comment, user) values = { 'comment_body': comment_body } result = {} body = self.content( args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]} result = merge_dicts(self.requirements_copy, result) return result
def start(self, context, request, appstruct, **kw): from ..proposal_management.behaviors import exclude_participant_from_wg root = getSite() context.state.remove('active') context.state.append('deactivated') context.set_organization(None) proposals = getattr(context, 'participations', []) anonymous_proposals = getattr(context.mask, 'participations', []) for proposal in proposals: exclude_participant_from_wg( proposal, request, context, root) for proposal in anonymous_proposals: exclude_participant_from_wg( proposal, request, context.mask, root) context.modified_at = datetime.datetime.now(tz=pytz.UTC) context.reindex() pref_author = list(get_users_by_preferences(context)) alert('internal', [request.root], pref_author, internal_kind=InternalAlertKind.content_alert, subjects=[context], alert_kind='user_deactivated') request.registry.notify(ActivityExecuted( self, [context], get_current())) return {}
def start(self, context, request, appstruct, **kw): correlation = appstruct['_object_data'] correlation.setproperty('source', context) correlation.setproperty('author', get_current()) root = getSite() root.addtoproperty('correlations', correlation) return {}
def start(self, context, request, appstruct, **kw): item = appstruct['item'] content = appstruct['content'] item_data = context.corrections[item] if item_data.get('content', '#') == content: if appstruct.get('edited', False) and \ appstruct.get('new_text', None): self._edit_item(context, content, appstruct) item_data['favour'] = [] item_data['against'] = [] vote = appstruct['vote'].lower() == 'true' user = get_current(request) user = context.proposal.working_group.get_member(user) user_oid = get_oid(user) if user_oid not in item_data['favour'] and \ user_oid not in item_data['against']: if vote: self._include_vote(context, request, item, content, 'favour', user_oid, user) else: self._include_vote(context, request, item, content, 'against', user_oid, user) return {}
def start(self, context, request, appstruct, **kw): user = get_current() appstruct.pop('_csrf_token_') classifications_ids = appstruct.get('classifications', []) classifications = [] source_class = None if classifications_ids: appstruct.pop('classifications') classifications = [CLASSIFICATIONS[fid] for fid in classifications_ids] classifications.reverse() for classification in classifications: source_class = classification(source_class) objects = find_entities(user=user, include_site=True, filters=appstruct['filters'] ) default = datetime.datetime.now(tz=pytz.UTC) objects = sorted(objects, key=lambda e: getattr(e, 'modified_at', default), reverse=True) from lac.content.smart_folder import generate_search_smart_folder folder = generate_search_smart_folder('Extraction folder') folder.classifications = source_class odtfile = folder.classifications.extract(objects, request, folder, template_type="extraction", filters=appstruct['filters']) return {'file': odtfile, 'filters': appstruct['filters'], 'user': user}
def start(self, context, request, appstruct, **kw): context.set_organization(None) context.modified_at = datetime.datetime.now(tz=pytz.UTC) context.reindex() request.registry.notify(ActivityExecuted( self, [context], get_current())) return {}
def start(self, context, request, appstruct, **kw): members = appstruct['members'] are_managers = appstruct['are_managers'] for member in members: new_member = False if member not in context.members: context.addtoproperty('members', member) member.init_contents_organizations() new_member = True if are_managers and (new_member or not has_role( user=member, role=('OrganizationResponsible', context), ignore_superiors=True)): grant_roles( user=member, roles=(('OrganizationResponsible', context),)) member.reindex() context.reindex() context.modified_at = datetime.datetime.now(tz=pytz.UTC) request.registry.notify(ActivityExecuted( self, [context], get_current())) return {}
def start(self, context, request, appstruct, **kw): site = get_site_folder(True, request) user = get_current(request) is_manager = has_any_roles( user=user, roles=('Admin', ('SiteAdmin', site))) or\ is_site_moderator(request) if is_manager or all(has_role(user=user, role=('Owner', v)) for v in appstruct['targets'] if 'published' not in v.state): root = getSite() source = appstruct['source'] targets = appstruct['targets'] for artist in targets: replaced = artist.replace_by(source) if replaced: request.registry.notify(ObjectReplaced( old_object=artist, new_object=source )) root.delfromproperty('artists', artist) else: return {'error': True} return {}
def find_cinema_venue(self): name = self.params('q') if name: user = get_current() page_limit, current_page, start, end = self._get_pagin_data() if is_all_values_key(name): result = find_entities(user=user, interfaces=[IVenue], keywords=['cinema']) else: result = find_entities(user=user, interfaces=[IVenue], text_filter={'text_to_search': name}, keywords=['cinema']) result = [res for res in result] if len(result) >= start: result = result[start:end] else: result = result[:end] entries = [{'id': str(get_oid(e)), 'text': e.title, 'description': e.description} for e in result] result = {'items': entries, 'total_count': len(result)} return result return {'items': [], 'total_count': 0}
def update(self): self.execute(None) user = get_current() objects = getattr(self.context.working_group, 'members', []) url = self.request.resource_url(self.context, self.name) batch = Batch(objects, self.request, url=url, default_size=BATCH_DEFAULT_SIZE) batch.target = "#results_proposal_members" + str(self.context.__oid__) len_result = batch.seqlen index = str(len_result) if len_result > 1: index = '*' result_body = render_small_listing_objs( self.request, batch, user) result = {} self.title = _(MEMBERS_MESSAGES[index], mapping={'number': len_result}) values = { 'bodies': result_body, 'batch': batch, 'empty_message': _("No members"), 'empty_icon': 'glyphicon glyphicon-user' } body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]} return result
def update(self): self.execute(None) objects = self.context.newsletters batch = Batch(objects, self.request, default_size=BATCH_DEFAULT_SIZE) batch.target = "#results_newsletters" len_result = batch.seqlen index = str(len_result) if len_result > 1: index = '*' self.title = _(CONTENTS_MESSAGES[index], mapping={'number': len_result}) user = get_current() result_body, result = render_listing_objs( self.request, batch, user) result = {} values = { 'bodies': result_body, 'length': len_result, 'batch': batch, } body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]} return result
def start(self, context, request, appstruct, **kw): root = getSite() user = get_current() artist = appstruct['_object_data'] root.addtoproperty('artists', artist) artist.state = PersistentList(['editable']) grant_roles(user=user, roles=(('Owner', artist), )) artist.setproperty('author', user) artist.add_contributors(context.contributors) artist.add_contributors([user]) artist.setproperty('original', context) artist.set_metadata(appstruct) artist.hash_picture_fp() artist.hash_artist_data() source = request.GET.get('source', '') if source: source_artist = get_obj(int(source)) if source_artist: replaced = source_artist.replace_by(artist) if replaced: request.registry.notify(ObjectReplaced( old_object=source_artist, new_object=artist )) root.delfromproperty('artists', source_artist) artist.reindex() request.registry.notify(ActivityExecuted(self, [artist], user)) return {'newcontext': artist}
def start(self, context, request, appstruct, **kw): comment = appstruct['_object_data'] user = get_current(request) channel = context.get_channel(user) if not channel: channel = PrivateChannel() context.addtoproperty('channels', channel) channel.addtoproperty('members', user) channel.addtoproperty('members', context) context.set_read_date(channel, comment.created_at) if channel: channel.addtoproperty('comments', comment) channel.add_comment(comment) comment.state = PersistentList(['published']) comment.reindex() comment.format(request) comment.setproperty('author', user) grant_roles(user=user, roles=(('Owner', comment), )) if appstruct.get('associated_contents', []): comment.set_associated_contents( appstruct['associated_contents'], user) self._alert_users(context, request, user, comment, channel) context.reindex() user.set_read_date(channel, datetime.datetime.now(tz=pytz.UTC)) return {}
def update(self): self.execute(None) try: navbars = generate_navbars(self.request, self.context) except ObjectRemovedException: return HTTPFound(self.request.resource_url(getSite(), '')) user = get_current() subfolders = [sf for sf in self.context.children if can_access(user, sf)] subfolders = sorted(subfolders, key=lambda e: e.get_order()) result_body, result = render_listing_objs( self.request, subfolders, user) values = {'object': self.context, 'subfolders': result_body, 'navbar_body': navbars['navbar_body'], 'body_actions': navbars['body_actions'] } body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) item['messages'] = navbars['messages'] item['isactive'] = navbars['isactive'] result.update(navbars['resources']) result['coordinates'] = {self.coordinates: [item]} return result
def find_entity(self, interfaces=[], states=['published', 'active'], query=None): name = self.params('q') if name: user = get_current() page_limit, current_page, start, end = self._get_pagin_data() if is_all_values_key(name): result = find_entities(interfaces=interfaces, metadata_filter={'states': states}, user=user, add_query=query) else: result = find_entities(interfaces=interfaces, metadata_filter={'states': states}, user=user, text_filter={'text_to_search': name}, add_query=query) resultlen = len(result) if resultlen < start: start = resultlen result = list(itertools.islice(result, start, end)) entries = [{ 'id': str(get_oid(e)), 'text': e.title, 'icon': getattr(e, 'icon', 'glyphicon glyphicon-question-sign') } for e in result] result = {'items': entries, 'total_count': resultlen} return result return {'items': [], 'total_count': 0}
def start(self, context, request, appstruct, **kw): send_to_me = appstruct['send_to_me'] members = list(appstruct['members']) root = request.root user = get_current(request) if send_to_me: members.append(user) userdata = get_user_data(user, 'my', request) presentation_subject = appstruct['subject'] presentation_message = appstruct['message'] subject = presentation_subject.format(subject_title=context.title) users = [m for m in members if not isinstance(m, str)] alert('internal', [root], users, internal_kind=InternalAlertKind.content_alert, subjects=[context], alert_kind='present') email_data = get_entity_data(context, 'subject', request) email_data.update(userdata) for member in members: email_member_data = get_user_data(member, 'recipient', request) email_member_data.update(email_data) member_email = getattr(member, 'email', '') \ if not isinstance(member, str) else member if member_email: message = presentation_message.format( novaideo_title=root.title, **email_member_data ) alert('email', [root.get_site_sender()], [member_email], subject=subject, body=message) if member is not user and member_email \ and member_email not in context._email_persons_contacted: context._email_persons_contacted.append( member_email) return {}
def send_notification(players_ids, excluded_ids=[]): subject = subjects[0] if subjects else sender request = get_current_request() user = get_current(request) notification_data = alert_class.get_notification_data( subject, user, request, alert) header = { "Content-Type": "application/json", "authorization": "Basic " + app_key } payload = { "app_id": app_id, "headings": { "en": notification_data['title'], "fr": notification_data['title'] }, "contents": { "en": notification_data['message'], "fr": notification_data['message'] }, "url": notification_data['url'] } if players_ids != 'all': payload["include_player_ids"] = players_ids else: payload["included_segments"] = ['All'] # if excluded_ids: # payload["excluded_player_ids"] = excluded_ids try: requests.post("https://onesignal.com/api/v1/notifications", headers=header, data=json.dumps(payload), timeout=0.1) except Exception as error: log.warning(error)
def _render(self, values, bodies, request, folder, **args): template_type = args.get('template_type', 'default') filter_body = args.pop('filter_body', None) inverse_substitutions = args.get('inverse_substitutions', {}) if self.subclassification: result = [(key, ([self.subclassification._render( items, bodies, request, folder, **args)], len_items)) for key, (items, len_items) in values if items] else: def _to_set(objects): substitutions = [] for obj in objects: sub = inverse_substitutions.get(obj, None) if sub not in substitutions: substitutions.append(sub) yield obj result = [(key, ([bodies[obj] for obj in _to_set(items)], len_items)) for key, (items, len_items) in values] user = get_current() values = {'items': self.sort(result), 'folder': folder, 'current_user': user, 'current_date': datetime.datetime.now(), 'filter_parameters': args.get('filters', []), 'classification': self} if filter_body: values.update({'filter_body': filter_body}) template = self.templates.get(template_type, 'default') body = renderers.render(template, values, request) return body
def __call__(self): user = get_current() guide_tour_data = getattr(user, 'guide_tour_data', {}) guide_state = guide_tour_data.get('guide_state', 'first_start') if guide_state in ('pending', 'first_start'): page_resources = get_guide_tour_page(self.request, self.context, user, self.request.view_name) if page_resources: page_resources = merge_dicts(self.resources, page_resources) page_resources['request'] = self.request # if user is not an anonymous if self.request.user: root = getSite() page_resources['update_url'] = self.request.resource_url( root, 'novaideoapi', query={'op': 'update_guide_tour_data'}) guide = page_resources.get('guide', None) page = page_resources.get('page', None) if guide is not None and page is not None: guide_data = guide_tour_data.get( guide + '_' + page, {}) page_state = guide_data.get('page_state', 'pending') if page_state == 'pending': page_resources['guide'] = guide page_resources['page'] = page page_resources['guide_value'] = guide_data.get( 'guide', -1) page_resources['page_value'] = guide_data.get( 'page', 0) page_resources['guide_state'] = guide_state else: return {} return page_resources return {}
def update(self): self.execute(None) try: navbars = generate_listing_menu( self.request, self.context, template=DEFAUL_LISTING_ACTIONS_TEMPLATE) except ObjectRemovedException: #Log in if the invitation is accepted if hasattr(self.context, 'person'): person = self.context.person headers = remember(self.request, get_oid(person)) self.request.registry.notify( LoggedIn(person.email, person, self.context, self.request)) root = getSite() return HTTPFound(location=self.request.resource_url(root), headers=headers) return HTTPFound(self.request.resource_url(getSite(), '')) user = get_current() values = { 'invitation': self.context, 'menu_body': navbars['menu_body'], 'primary_menu_body': navbars['primary_menu_body'], 'state': get_states_mapping(user, self.context, self.context.state[0]), } result = {} body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) item['messages'] = navbars['messages'] item['isactive'] = navbars['isactive'] result.update(navbars['resources']) result['coordinates'] = {self.coordinates: [item]} return result
def send_request_quotation(newadvertising, request): site = get_site_folder(True) managers = get_users_with_role(role=('AdvertisingManager', site)) if not managers: managers = get_users_with_role(role=('SiteAdmin', site)) if managers: localizer = request.localizer url = request.resource_url(newadvertising, "@@index") author = get_current() mail_template = site.get_mail_template('request_quotation') subject = mail_template['subject'].format( advertising_title=newadvertising.title) message = mail_template['template'].format( author=getattr(author, 'title', author.name), user_title=localizer.translate( _(getattr(author, 'user_title', 'The user'))), url=url, lac_title=request.root.title) for manager in managers: alert('email', [getattr(author, 'email', None)], [manager.email], { 'subject': subject, 'body': message })
def update(self): result = {} site = get_site_folder(True, self.request) user = get_current(self.request) is_manager = has_any_roles( user=user, roles=('Admin', ('SiteAdmin', site))) or\ is_site_moderator(self.request) duplicates = find_duplicates_artist(self.context, self.duplicates_state) diff_bodies = {} context_view = self.content(args={'object': self.context}, template=self.context.templates.get( 'diff', None))['body'] for duplicate in duplicates: duplicate_view = self.content(args={'object': duplicate}, template=duplicate.templates.get( 'diff', None))['body'] soupt, textdiff = html_diff_wrapper.render_html_diff( context_view, duplicate_view) diff_bodies[duplicate] = (textdiff, get_oid(duplicate)) values = { 'context': self.context, 'oid': get_oid(self.context), 'context_view': context_view, 'contents': diff_bodies, 'row_len': math.ceil(len(diff_bodies) / 2), 'is_manager': is_manager, 'view': self } body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]} return result
def start(self, context, request, appstruct, **kw): user = get_current() artists, new_artists = extract_artists(appstruct.pop('artists', []), request) directors, new_directors = extract_artists(appstruct.pop( 'directors', []), request, is_directors=True) appstruct.pop('artists_ids') appstruct.pop('directors_ids') if appstruct.get('picture', None) is not None and \ OBJECT_DATA in appstruct['picture']: appstruct['picture'] = appstruct['picture'][OBJECT_DATA] if not getattr(appstruct['picture'], '__name__', None): appstruct['picture'].__name__ = 'picture' context.set_metadata(appstruct) context.set_data(appstruct) context.setproperty('artists', artists) context.setproperty('directors', directors) context.modified_at = datetime.datetime.now(tz=pytz.UTC) if 'published' in context.state: not_published_artists = [ a for a in context.artists if 'published' not in a.state ] not_published_artists.extend( [a for a in context.directors if 'published' not in a.state]) for artist in not_published_artists: publish_artist(artist, request, user) context.reindex() new_objects = new_artists new_objects.extend(new_directors) new_objects.append(context) request.registry.notify(ActivityExecuted(self, new_objects, user)) return {}
def update(self): self.execute(None) # root = getSite() # folders = root.site_folders folders = find_entities(user=get_current(), interfaces=[ISiteFolder], sort_on='modified_at', reverse=True) result = {} len_result = len(folders) index = str(len_result) if len_result > 1: index = '*' self.title = _(CONTENTS_MESSAGES[index], mapping={'nember': len_result}) values = { 'folders': list(folders), 'row_len': math.ceil(len_result / 6) } body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]} return result
def __call__(self): if not self.request.cookies.get('contextual_help', True): return {'condition': False} user = get_current() messages = [ CONTEXTUAL_HELP_MESSAGES.get( (self.context.__class__, s, self.request.view_name), None) for s in self.context.state ] messages.append( CONTEXTUAL_HELP_MESSAGES.get( (self.context.__class__, 'any', self.request.view_name), None)) messages = [m for m in messages if m is not None] messages = [item for sublist in messages for item in sublist] messages = sorted(messages, key=lambda m: m[2]) messages = [ renderers.render(m[1], { 'context': self.context, 'user': user }, self.request) for m in messages if m[0] is None or m[0](self.context, user) ] return {'messages': messages, 'condition': True}
def update(self): self.execute(None) user = get_current() objects = find_entities(user=user, interfaces=[IInvitation]) batch = Batch(objects, self.request, default_size=BATCH_DEFAULT_SIZE) batch.target = "#results_invitations" len_result = batch.seqlen index = str(len_result) if len_result > 1: index = '*' self.title = _(CONTENTS_MESSAGES[index], mapping={'number': len_result}) result_body, result = render_listing_objs(self.request, batch, user) values = { 'bodies': result_body, 'length': len_result, 'batch': batch, } body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]} return result
def update(self): self.execute(None) user = get_current() objects = [ obj for obj in self.context.get_sub_nodes() if can_access(user, obj) ] objects = sorted(objects, key=lambda e: getattr(e, 'modified_at'), reverse=True) url = self.request.resource_url(self.context, self.name) batch = Batch(objects, self.request, url=url, default_size=BATCH_DEFAULT_SIZE) batch.target = "#results_node_dependencies_" + str( self.context.__oid__) len_result = batch.seqlen index = str(len_result) if len_result > 1: index = '*' self.title = _(WG_MESSAGES[index], mapping={'number': len_result}) result = {} result_body = render_small_listing_objs(self.request, batch, user) values = { 'bodies': result_body, 'batch': batch, 'empty_message': _("No association"), 'empty_icon': 'glyphicon glyphicon-link' } body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]} return result
def note_processsecurity_validation(process, context): user = get_current() report = process.ballot.report elector = report.get_elector(user) return elector and not report.he_voted(elector) and \ global_user_processsecurity()
def bind(self): user = get_current(self.request) root = self.request.root mail_template = root.get_mail_template('presentation_challenge', user.user_locale) return {'mail_template': mail_template}
def _get_step3_informations(self, context, request): time_delta = None working_group = context.working_group process = working_group.improvement_cycle_proc is_closed = 'closed' in working_group.state user = get_current() working_group_states = [ _(get_states_mapping(user, working_group, s)) for s in working_group.state ] if 'amendable' in context.state and process: subprocesses = process['work'].sub_processes date_iteration = None if subprocesses: date_iteration = subprocesses[-1]['timer'].eventKind.time_date today = datetime.datetime.now() if date_iteration is not None and date_iteration > today: time_delta = date_iteration - today time_delta = days_hours_minutes(time_delta) return renderers.render( self.step3_1_template, { 'context': context, 'working_group_states': working_group_states, 'is_closed': is_closed, 'duration': time_delta, 'process': process }, request) elif 'votes for publishing' in context.state: ballot = working_group.vp_ballot today = datetime.datetime.now(tz=pytz.UTC) if ballot.finished_at is not None and ballot.finished_at > today: time_delta = ballot.finished_at - today time_delta = days_hours_minutes(time_delta) return renderers.render( self.step3_3_template, { 'context': context, 'working_group_states': working_group_states, 'is_closed': is_closed, 'duration': time_delta, 'process': process, 'ballot_report': ballot.report }, request) elif 'votes for amendments' in context.state: voters = [] [ voters.extend(b.report.voters) for b in working_group.amendments_ballots ] voters = list(set(voters)) ballot = working_group.amendments_ballots[-1] today = datetime.datetime.now(tz=pytz.UTC) if ballot.finished_at is not None and ballot.finished_at > today: time_delta = ballot.finished_at - today time_delta = days_hours_minutes(time_delta) return renderers.render( self.step3_2_template, { 'context': context, 'working_group_states': working_group_states, 'is_closed': is_closed, 'duration': time_delta, 'process': process, 'ballot_report': ballot.report, 'voters': voters }, request) elif 'open to a working group' in context.state: participants_mini = getSite().participants_mini work_mode = getattr(working_group, 'work_mode', None) if work_mode: participants_mini = work_mode.participants_mini return renderers.render( self.step3_0_template, { 'context': context, 'process': process, 'min_members': participants_mini }, request) return _('Information unvailable.')
def start(self, context, request, appstruct, **kw): root = getSite() user = get_current() appstruct.pop('_csrf_token_') artists, new_artists = extract_artists(appstruct.pop('artists', []), request) appstruct.pop('artists_ids') schedules = [] new_venues = [] for schedule_data in appstruct['schedules']: schedule = schedule_data[OBJECT_DATA] venue_data = schedule_data.get('venue', None) if venue_data: venue, is_new = extract_venue(venue_data, request) if is_new: new_venues.append(venue) schedule.setproperty('venue', venue) schedules.append(schedule) appstruct['schedules'] = schedules schedules_to_remove = [ s for s in context.schedules if s not in appstruct['schedules'] ] for schedule in appstruct['schedules']: schedule.state = PersistentList(['created']) if not getattr(schedule, '__parent__', None): root.addtoproperty('schedules', schedule) schedule.reindex_dates() if schedule_expired(schedule): schedule.state.append('archived') schedule.reindex() group_venues(new_venues, request) if 'picture' in appstruct and appstruct['picture'] and \ OBJECT_DATA in appstruct['picture']: appstruct['picture'] = appstruct['picture'][OBJECT_DATA] if not getattr(appstruct['picture'], '__name__', None): appstruct['picture'].__name__ = 'picture' context.set_metadata(appstruct) context.set_data(appstruct) for schedule in schedules_to_remove: root.delfromproperty('schedules', schedule) context.setproperty('artists', artists) #context.modified_at = datetime.datetime.now(tz=pytz.UTC) remove_addresses_coordinates(new_venues) if 'published' in context.state: not_published_venues = [ s.venue for s in context.schedules if s.venue and 'published' not in s.venue.state ] for venue in not_published_venues: publish_venue(venue, request, user) not_published_artists = [ a for a in context.artists if 'published' not in a.state ] for artist in not_published_artists: publish_artist(artist, request, user) context.reindex() new_objects = new_venues new_objects.extend(new_artists) new_objects.append(context) request.registry.notify(ActivityExecuted(self, new_objects, user)) return {}
def see_processsecurity_validation(process, context): source = context.source targets = context.targets user = get_current() return can_access(user, source) and \ not any(not can_access(user, target) for target in targets)
def update(self): self.execute(None) user = get_current() filter_form, filter_data = self._add_filter(user) content_types = ['cultural_event', 'venue', 'artist'] args = {'metadata_filter': {'content_types': content_types}} args = merge_with_filter_view(self, args) args['request'] = self.request if not args.get('metadata_filter', {}).get('content_types', []): metadata_filter = args.get('metadata_filter', {}) metadata_filter['content_types'] = content_types args['metadata_filter'] = metadata_filter args['metadata_filter']['states'] = ['published'] objects = find_entities(user=user, sort_on='object_title', reverse=False, include_site=True, **args) url = self.request.resource_url(self.context, 'allduplicates') def condition(obj): """Batch condition""" return obj.get_duplicates() batch = ConditionalBatch(condition, objects, self.request, url=url, default_size=15) batch.target = "#results_contents" len_result = batch.seqlen index = str(len_result) if len_result > 1: index = '*' self.title = _(CONTENTS_MESSAGES[index], mapping={'nember': len_result}) filter_data['filter_message'] = self.title filter_body = self.filter_instance.get_body(filter_data) result_body = [] for obj in batch: render_dict = { 'object': obj, 'current_user': user, 'state': get_states_mapping(user, obj, getattr(obj, 'state_or_none', [None])[0]) } body = self.content(args=render_dict, template=obj.templates['duplicates'])['body'] result_body.append(body) result = {} values = { 'bodies': result_body, 'batch': batch, 'filter_body': filter_body } body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]} result['css_links'] = filter_form['css_links'] result['js_links'] = filter_form['js_links'] return result
def default_data(self): return {'reaction': self.context.get_user_emoji(get_current(self.request))}
def contents_nb(self, request, context): user = get_current() participations = user.get_participations(user) \ if hasattr(user, 'get_participations') else [] return len(participations)
def start(self, context, request, appstruct, **kw): user = get_current() author = getattr(context, 'author', user) site_ids = [] #@TODO Start current_site = request.get_site_folder sites = [current_site] sites.extend(current_site.get_group()) sites = [ s for s in sites if visible_in_site(s, context, request=request) ] #@TODO End # can_publish_data = can_publish_in_periodic(current_site, context) # can_publish = can_publish_data[0] # has_extraction = can_publish_data[3] # if can_publish or not has_extraction: mail_template = current_site.get_mail_template( 'validation_confirmation') subject = mail_template['subject'].format() mail = mail_template['template'].format( member=getattr(author, 'name', ''), url=request.resource_url(context, '@@index')) alert('email', [current_site.get_site_sender()], [author.email], { 'subject': subject, 'body': mail }) # elif has_extraction: # mail_template = current_site.get_mail_template('validation_confirmation_date') # subject = mail_template['subject'].format() # mail = mail_template['template'].format( # member=getattr(author, 'name', ''), # url=request.resource_url(context, '@@index')) # mailer_send(subject=subject, body=mail, # recipients=[author.email], # sender=current_site.get_site_sender()) for site in sites: #appstruct['sites']: site_ids.append(get_oid(site)) site_services = site.get_all_services(validate=False, delegation=False) if 'moderation' in site_services: moderations = site_services['moderation'] for moderation in list(set(moderations)): service = moderation.get_unit() service.configure(context, author) service.subscribe(context, author, service=moderation) order = update_orders(context, author) remove_empty_orders(author) is_paid = 'paid' in order.state submited_objects = [context] if is_paid: context.state = PersistentList(['submitted']) submit_cultural_event(context) submited_objects.extend(submit_artists(context.artists)) submited_objects.extend( submit_venues([s.venue for s in context.schedules if s.venue])) else: context.state = PersistentList(['to pay']) context.sumited_to = PersistentList(site_ids) context.modified_at = datetime.datetime.now(tz=pytz.UTC) context.reindex() request.registry.notify(ActivityExecuted(self, submited_objects, user)) return {'is_paid': is_paid}
def creat_home_question(self): try: view_name = self.params('source_path') view_name = view_name if view_name else '' is_mycontents_view = view_name.endswith('seemycontents') context = self.context try: source_path = '/'.join(view_name.split('/')[:-1]) context = find_resource(self.context, source_path) except Exception as error: log.warning(error) is_challenge = isinstance(context, Challenge) redirect = False for action_id in self.behaviors_instances: if action_id in self.request.POST: button = action_id break add_question_action = self.behaviors_instances[button] add_question_view = DEFAULTMAPPING_ACTIONS_VIEWS[ add_question_action.__class__] add_question_view_instance = add_question_view( self.context, self.request, behaviors=[add_question_action]) add_question_view_instance.setviewid('formaskquestionhome') add_question_view_result = add_question_view_instance() if add_question_view_instance.finished_successfully: result = get_components_data( **get_all_updated_data(add_question_action, self.request, self.context, self, view_data=( add_question_view_instance, add_question_view_result))) user = get_current() body = '' if not redirect: question = sorted(user.get_questions(user), key=lambda w: w.created_at)[-1] if not is_mycontents_view and \ 'published' not in question.state: redirect = True else: if is_mycontents_view: result['item_target'] = 'results_contents' elif is_challenge: result[ 'item_target'] = 'results-challenge-questions' else: result['item_target'] = 'results-home-questions' body += render_listing_obj(self.request, question, user) if not redirect: result['redirect_url'] = None result['new_obj_body'] = body result['status'] = True return result except Exception as error: log.warning(error) return {'status': False} return {'status': False}
def update(self): self.execute(None) user = get_current() validated = getattr(self, 'validated', {}) posted = self.request.POST or self.request.GET or {} posted = posted.copy() clear_posted = False if not validated: if posted: clear_posted = True searcinstance = SearchView(self.context, self.request, filter_result=True) if searcinstance.validated: validated = searcinstance.validated objects = find_entities(user=user, sort_on='release_date', reverse=True, include_site=True, **validated) url = self.request.resource_url(self.context, self.request.view_name, query=posted) batch = Batch(objects, self.request, default_size=core.BATCH_DEFAULT_SIZE, url=url) #clear posted values: See usermenu panel if clear_posted: if self.request.POST: self.request.POST.clear() elif self.request.GET: self.request.GET.clear() batch.target = "#results_contents" len_result = batch.seqlen index = str(len_result) if len_result > 1: index = '*' self.title = _(CONTENTS_MESSAGES[index], mapping={'nember': len_result}) result_body = [] for obj in batch: render_dict = { 'object': obj, 'current_user': user, 'state': get_states_mapping(user, obj, getattr(obj, 'state_or_none', [None])[0]) } body = self.content(args=render_dict, template=obj.templates['default'])['body'] result_body.append(body) result = {} values = {'bodies': result_body, 'batch': batch} body = self.content(args=values, template=self.template)['body'] item = self.adapt_item(body, self.viewid) result['coordinates'] = {self.coordinates: [item]} return result
def default_data(self): user = get_current() return { 'name': getattr(user, 'first_name', ''), 'email': getattr(user, 'email', '') }
def seemys_processsecurity_validation(process, context): user = get_current() selections = [ o for o in getattr(user, 'selections', []) if 'archived' not in o.state ] return selections and global_user_processsecurity()
def contents_nb(self): user = get_current() return len([o for o in getattr(user, 'contents', [])])
def start(self, context, request, appstruct, **kw): user = get_current() for alert in user.alerts: alert.unsubscribe(user) return {}
def seemyc_processsecurity_validation(process, context): user = get_current() contents = user.get_contents(user) \ if hasattr(user, 'get_contents') else [] return contents and global_user_processsecurity()
def _get_step4_informations(self, context, request): user = get_current() return renderers.render(self.step4_0_template, { 'context': context, 'support': context.evaluation(user) }, request)