def __call__(self): self.request.response.setHeader('Content-type', 'application/json') cutils = Utils(self.context, self.request) data = { 'title': self.context.title, 'id': self.context.id, 'has_image': utils.has_image(self.context), 'youtube_url': None } rendered = None if self.context.portal_type in ('Image',): pass elif self.context.portal_type == 'Video': fi = getattr(self.context, 'file', None) data.update({ 'youtube_url': cutils.get_youtube_url(self.context), 'content_type': getattr( fi, 'original_content_type', getattr(fi, 'contentType', None)) }) else: feed = SearchFeed(api.portal.get()) adapter = queryMultiAdapter((self.context, feed), IFeedItem) if adapter is not None: rendered = adapter.render_content_core().strip() return json.dumps({ 'portal_type': self.context.portal_type, 'url': self.context.absolute_url(), 'data': data, 'rendered': rendered })
def send_email_to_subscribers(subject, html, categories=None): _utils = Utils(api.portal.get(), getRequest()) public_url = _utils.get_public_url() check_categories = (categories is not None and len(categories) != 0) for subscriber in subscribe.all(): if check_categories: # If there's no chosen categories, they recieve everything if 'categories' in subscriber and len( subscriber['categories']) > 0: # make sure that this message falls under one of their categories if len(categories.intersection(subscriber['categories'])) == 0: return query = urlencode({ 'email': subscriber.get('email'), 'code': subscriber.get('code') }) unsubscribe_url = '%s/@@unsubscribe?%s' % (public_url.rstrip('/'), query) change_url = '%s/@@changesubscription?%s' % (public_url.rstrip('/'), query) unsubscribe_url = unsubscribe_url.encode('utf8') change_url = change_url.encode('utf8') html = html.replace('{{unsubscribe_url}}', unsubscribe_url) html = html.replace('{{change_url}}', change_url) utils.send_email([subscriber.get('email')], subject, html)
def handle_send2(self, action): data, errors = self.extractData() if not errors: utils = Utils(self.context, self.request) public_url = utils.get_public_url() html = data['body'].output filters = [ f for _, f in getAdapters((self.context, self.request), IFilter) ] html = apply_filters(filters, html) html = html.replace(self.context.absolute_url(), public_url.encode('utf8')) categories = set() if 'form.widgets.send_to_categories' in self.request.form: categories = set(data['send_to_categories']) sender = None if 'form.widgets.send_from' in self.request.form: sender = data['send_from'] send_email_to_subscribers.delay(data['subject'], html=html, categories=categories, sender=sender) api.portal.show_message('Sending emails', request=self.request, type='info') self.request.response.redirect('%s/@@announcements-controlpanel' % (self.context.absolute_url()))
def handle_send(self, action): data, errors = self.extractData() if not errors: addresses = data['send_to_custom'] or [] for group in data['send_to_groups'] or []: for user in api.user.get_users(groupname=group): email = user.getProperty('email') if email: addresses.append(email) for username in data['send_to_users'] or []: user = api.user.get(username=username) if user: email = user.getProperty('email') if email: addresses.append(email) try: sender = data['send_from'] except Exception: sender = None utils = Utils(self.context, self.request) public_url = utils.get_public_url() html = data['body'].output filters = [f for _, f in getAdapters((self.context, self.request), IFilter)] html = apply_filters(filters, html) html = html.replace(self.context.absolute_url(), public_url.encode('utf8')) send_email.delay(list(set(addresses)), data['subject'], html=html, sender=sender) self.request.response.redirect('%s/@@announcements-controlpanel' % ( self.context.absolute_url()))
def breadcrumbs(self): context = aq_inner(self.context) view_utils = Utils(self.context, self.request) crumbs = [] while context is not None: if ISiteRoot.providedBy(context): break try: if utils.isDefaultPage(context, self.request): context = utils.parent(context) continue except AttributeError: break # Some things want to be hidden from the breadcrumbs if IHideFromBreadcrumbs.providedBy(context): context = utils.parent(context) continue item_url = view_utils.get_object_url(context) try: state = api.content.get_state(obj=context) except WorkflowException: state = None label = getattr(context, 'navigation_label', None) if not label: label = utils.pretty_title_or_id(context, context) crumbs.append({ 'absolute_url': item_url, 'Title': label, 'state': state }) context = utils.parent(context) return list(reversed(crumbs))
def get_data(self): registry = getUtility(IRegistry) btype = registry.get('castle.business_type', None) bname = registry.get('castle.business_name', None) utils = Utils(self.context, getRequest()) if not btype and bname: # return subset that uses site name, org type registry = getUtility(IRegistry) site_settings = registry.forInterface(ISiteSchema, prefix="plone", check=False) return { "@context": "http://schema.org", "@type": 'Organization', "name": site_settings.site_title, "url": utils.get_public_url(), "logo": { "@type": "ImageObject", "url": getSiteLogo() } } data = { "@context": "http://schema.org", "@type": btype, "name": bname, "url": utils.get_public_url(), 'telephone': registry.get('castle.business_telephone', ''), "logo": { "@type": "ImageObject", "url": getSiteLogo() } } address = registry.get('castle.business_address', None) if address: data['address'] = { '@type': 'PostalAddress', 'streetAddress': address, 'addressLocality': registry.get('castle.business_city', ''), 'addressRegion': registry.get('castle.business_state', ''), 'postalCode': registry.get('castle.business_postal_code', ''), 'addressCountry': registry.get('castle.business_country', '') } coordinates = registry.get('castle.business_coordinates', '') if coordinates: try: coordinates = json.loads(coordinates) except Exception: coordinates = None if coordinates: data['geo'] = { '@type': 'GeoCoordinates', 'latitude': coordinates.get('lat', ''), 'longitude': coordinates.get('lng', '') } days = registry.get('castle.business_days_of_week', []) hours = [] if days: hours.append({ '@type': "OpeningHoursSpecification", 'dayOfWeek': days, 'opens': registry.get('castle.business_opens', ''), 'closes': registry.get('castle.business_closes', ''), }) for special in registry.get('castle.business_special_hours', []) or []: if special.count('|') != 2: continue day, opens, closes = special.split('|') hours.append({ '@type': "OpeningHoursSpecification", 'dayOfWeek': day, 'opens': opens, 'closes': closes }) if hours: data['openingHoursSpecification'] = hours menu = registry.get('castle.business_menu_link', None) if menu: data["menu"] = menu if registry.get('castle.business_accepts_reservations', False): data["acceptsReservations"] = "True" try: data.update(json.loads( registry.get( 'castle.business_additional_configuration', '{}'))) except Exception: pass return data
def setUp(self): self.portal = self.layer['portal'] self.request = self.layer['request'] self.utils = Utils(self.portal, self.request)
class TestUtils(unittest.TestCase): layer = CASTLE_PLONE_INTEGRATION_TESTING def setUp(self): self.portal = self.layer['portal'] self.request = self.layer['request'] self.utils = Utils(self.portal, self.request) def test_main_links(self): login(self.portal, TEST_USER_NAME) setRoles(self.portal, TEST_USER_ID, ('Member', 'Manager')) if 'front-page' not in self.portal: api.content.create(type='Document', id='front-page', container=self.portal) self.portal.setDefaultPage('front-page') data = self.utils.get_main_links() self.assertEquals(data['selected_portal_tab'], 'index_html') self.assertEquals(len(data['portal_tabs']), 1) def test_truncate_text(self): self.assertEqual( len(utils.truncate_text('foo bar foo bar', 2).split(' ')), 2) def test_truncate_text_with_html(self): result = utils.truncate_text('foo <b>bar</b> <span>foo bar</span>', 2) self.assertEqual('foo <b>bar…</b>', result) def test_random_functions(self): self.assertEqual(len(utils.get_random_string(15)), 15) self.assertEqual(len(utils.make_random_key(15)), 15) def test_get_paste_data(self): login(self.portal, TEST_USER_NAME) setRoles(self.portal, TEST_USER_ID, ('Member', 'Manager')) newpage = api.content.create(type='Document', id='newpage', container=self.portal) api.content.transition(obj=newpage, to_state='published') cp = (0, [('', 'plone', 'newpage')]) cp = _cb_encode(cp) self.request['__cp'] = cp data = utils.get_paste_data(self.request) self.assertEqual(data['count'], 1) self.assertEqual(data['op'], 0) self.assertEqual(data['paths'], ['/plone/newpage']) def test_recursive_create_path(self): login(self.portal, TEST_USER_NAME) setRoles(self.portal, TEST_USER_ID, ('Member', 'Manager')) folder = utils.recursive_create_path(self.portal, '/foo/bar/blah') self.assertEqual('/'.join(folder.getPhysicalPath()), '/plone/foo/bar/blah') def test_retriable(self): count = [] @utils.retriable(reraise=False) def dosomething(): count.append(1) raise ConflictError() dosomething() self.assertEqual(len(count), 3)
def do_redirect(self, context): utils = Utils(self.context, self.request) target = utils.get_object_url(context) return self.request.response.redirect(target)
def handle_cancel(self, action): utils = Utils(self.context, self.request) target = utils.get_object_url(self.context) return self.request.response.redirect(target)