def PUT(self): """ Modifies the community itself. """ params = {} params['title'] = self.params.pop('title', None) params['community_type'] = self.params.pop('community_type', None) params['description'] = self.params.pop('description', None) params['image'] = self.params.pop('image', None) params['activity_view'] = self.params.pop('activity_view', None) params['twitter_hashtag'] = self.params.pop('twitter_hashtag', None) params['notify_activity_via_push'] = self.params.pop('notify_activity_via_push', None) params['notify_activity_via_push_comments_too'] = self.params.pop('notify_activity_via_push_comments_too', None) if params['community_type']: # We are changing the type of the community # Check if it's a legit change if params['community_type'] in ['Open', 'Closed', 'Organizative']: adapter = self.target.adapted(name=params['community_type']) else: return ApiResponse.from_string({"error": "Bad request, wrong community type"}, code=400) if params['community_type'] == self.target.community_type: return ApiResponse.from_string({"error": "Bad request, already that community type"}, code=400) # Everything is ok, proceed adapter.update_community_type() modified = self.update_community(params) if modified: success_response = 'Updated community "{}"'.format(self.target.absolute_url()) else: success_response = 'Error with change values "{}".'.format(self.target.absolute_url()) logger.info(success_response) return ApiResponse.from_string(success_response)
def create_user(self, username, email, password, **properties): existing_user = api.user.get(username=username) maxclient, settings = getUtility(IMAXClient)() maxclient.setActor(settings.max_restricted_username) maxclient.setToken(settings.max_restricted_token) avatar = properties.pop('avatar', None) if not existing_user: args = dict(email=email, username=username, properties=properties) if password: args['password'] = password api.user.create(**args) maxclient.people[username].put(displayName=properties['fullname']) # Save the image into the Plone user profile if provided if avatar: portal = api.portal.get() membership_tool = getToolByName(portal, 'portal_membership') imgName = (avatar.split('/')[-1]).decode('utf-8') imgData = requests.get(avatar).content image = StringIO(imgData) image.filename = imgName execute_under_special_role(portal, "Manager", changeMemberPortrait, membership_tool, image, username) status = 201 else: # Update portal membership user properties has_email = existing_user.getProperty('email', False) if not has_email: properties.update({'email': email}) existing_user.setMemberProperties(properties) # Update MAX properties maxclient.people[username].post( ) # Just to make sure user exists (in case it was only on ldap) status = maxclient.last_response_code maxclient.people[username].put(displayName=properties['fullname']) if avatar: portal = api.portal.get() membership_tool = getToolByName(portal, 'portal_membership') imgName = (avatar.split('/')[-1]).decode('utf-8') imgData = requests.get(avatar).content image = StringIO(imgData) image.filename = imgName execute_under_special_role(portal, "Manager", changeMemberPortrait, membership_tool, image, username) if status == 201: return ApiResponse.from_string('User {} created'.format(username), code=status) else: return ApiResponse.from_string('User {} updated'.format(username), code=200)
def POST(self): params = {} params['nom'] = self.params.pop('title') params['community_type'] = self.params.pop('community_type') params['description'] = self.params.pop('description', None) params['image'] = self.params.pop('image', None) params['activity_view'] = self.params.pop('activity_view', None) params['twitter_hashtag'] = self.params.pop('twitter_hashtag', None) params['notify_activity_via_push'] = self.params.pop( 'notify_activity_via_push', None) params['notify_activity_via_push_comments_too'] = self.params.pop( 'notify_activity_via_push_comments_too', None) pc = api.portal.get_tool('portal_catalog') nom = safe_unicode(params['nom']) util = queryUtility(IIDNormalizer) id_normalized = util.normalize(nom, max_length=500) result = pc.unrestrictedSearchResults(portal_type='ulearn.community', id=id_normalized) imageObj = '' if params['image']: mime = MimeTypes() mime_type = mime.guess_type(params['image']) imgName = (params['image'].split('/')[-1]).decode('utf-8') imgData = requests.get(params['image']).content imageObj = NamedBlobImage(data=imgData, filename=imgName, contentType=mime_type[0]) if result: # community = result[0].getObject() success_response = 'Community already exists.' status = 200 else: new_community_id = self.context.invokeFactory( 'ulearn.community', id_normalized, title=params['nom'], description=params['description'], image=imageObj, community_type=params['community_type'], activity_view=params['activity_view'], twitter_hashtag=params['twitter_hashtag'], notify_activity_via_push=True if params['notify_activity_via_push'] == 'True' else None, notify_activity_via_push_comments_too=True if params['notify_activity_via_push_comments_too'] == 'True' else None, checkConstraints=False) new_community = self.context[new_community_id] success_response = 'Created community "{}" with hash "{}".'.format( new_community.absolute_url(), sha1(new_community.absolute_url()).hexdigest()) status = 201 logger.info(success_response) return ApiResponse.from_string(success_response, code=status)
def PUT(self): """ Modify displayName user /api/people/{username} data = {'displayName':'Nom Cognom'} """ existing_user = api.user.get(username=self.params['username'].lower()) maxclient, settings = getUtility(IMAXClient)() maxclient.setActor(settings.max_restricted_username) maxclient.setToken(settings.max_restricted_token) if existing_user: if 'displayName' in self.params: # Update portal membership user properties existing_user.setMemberProperties( {'fullname': self.params['displayName']}) properties = get_all_user_properties(existing_user) add_user_to_catalog(existing_user, properties, overwrite=True) username = self.params['username'].lower() # Update max maxclient.people[username].put( displayName=properties['fullname']) status = maxclient.last_response_code else: status = 500 else: status = 404 if status == 404: return ApiResponse.from_string('User {} not found'.format( self.params['username'].lower()), code=status) elif status == 200: return ApiResponse.from_string('User {} updated'.format( self.params['username'].lower()), code=status) elif status == 500: return ApiResponse.from_string( 'User {} not updated. Not displayName.'.format( self.params['username'].lower()), code=status)
def PUT(self): """ Modifies the community itself. """ params = {} params['title'] = self.params.pop('title', None) params['community_type'] = self.params.pop('community_type', None) params['description'] = self.params.pop('description', None) params['image'] = self.params.pop('image', None) params['activity_view'] = self.params.pop('activity_view', None) params['twitter_hashtag'] = self.params.pop('twitter_hashtag', None) params['notify_activity_via_push'] = self.params.pop( 'notify_activity_via_push', None) params['notify_activity_via_push_comments_too'] = self.params.pop( 'notify_activity_via_push_comments_too', None) if params['community_type']: # We are changing the type of the community # Check if it's a legit change if params['community_type'] in ['Open', 'Closed', 'Organizative']: adapter = self.target.adapted(name=params['community_type']) else: return ApiResponse.from_string( {"error": "Bad request, wrong community type"}, code=400) if params['community_type'] == self.target.community_type: return ApiResponse.from_string( {"error": "Bad request, already that community type"}, code=400) # Everything is ok, proceed adapter.update_community_type() modified = self.update_community(params) if modified: success_response = 'Updated community "{}"'.format( self.target.absolute_url()) else: success_response = 'Error with change values "{}".'.format( self.target.absolute_url()) logger.info(success_response) return ApiResponse.from_string(success_response)
def create_event(self, eventid, title, desc, body, date_start, date_end): date_start = date_start.split('/') time_start = date_start[3].split(':') date_end = date_end.split('/') time_end = date_end[3].split(':') portal_url = api.portal.get() news_url = portal_url['events'] pc = api.portal.get_tool('portal_catalog') brains = pc.unrestrictedSearchResults(portal_type='Event', id=eventid) if not brains: new_event = createContentInContainer(news_url, 'Event', title=eventid, start=datetime(int(date_start[2]), int(date_start[1]), int(date_start[0]), int(time_start[0]), int(time_start[1]) ), end=datetime(int(date_end[2]), int(date_end[1]), int(date_end[0]), int(time_end[0]), int(time_end[1]) ), timezone="Europe/Madrid", checkConstraints=False) new_event.title = title new_event.description = desc new_event.text = IRichText['text'].fromUnicode(body) new_event.reindexObject() resp = ApiResponse.from_string('Event {} created'.format(eventid), code=201) else: event = brains[0].getObject() event.title = title event.text = IRichText['text'].fromUnicode(body) event.reindexObject() resp = ApiResponse.from_string('Event {} updated'.format(eventid)) return resp
def PUT(self): """ Subscribes a bunch of users to a community the security is given an initial soft check for authenticated users at the view level and then by checking explicitly if the requester user has permission on the target community. """ self.update_subscriptions() # Response successful success_response = 'Updated community "{}" subscriptions'.format(self.target.absolute_url()) logger.info(success_response) return ApiResponse.from_string(success_response)
def PUT(self): """ Subscribes a bunch of users to a community the security is given an initial soft check for authenticated users at the view level and then by checking explicitly if the requester user has permission on the target community. """ self.update_subscriptions() # Response successful success_response = 'Updated community "{}" subscriptions'.format( self.target.absolute_url()) logger.info(success_response) return ApiResponse.from_string(success_response)
def create_event(self, eventid, title, desc, body, date_start, date_end): date_start = date_start.split('/') time_start = date_start[3].split(':') date_end = date_end.split('/') time_end = date_end[3].split(':') portal_url = api.portal.get() news_url = portal_url['events'] pc = api.portal.get_tool('portal_catalog') brains = pc.unrestrictedSearchResults(portal_type='Event', id=eventid) if not brains: new_event = createContentInContainer( news_url, 'Event', title=eventid, start=datetime(int(date_start[2]), int(date_start[1]), int(date_start[0]), int(time_start[0]), int(time_start[1])), end=datetime(int(date_end[2]), int(date_end[1]), int(date_end[0]), int(time_end[0]), int(time_end[1])), timezone="Europe/Madrid", checkConstraints=False) new_event.title = title new_event.description = desc new_event.text = IRichText['text'].fromUnicode(body) new_event.reindexObject() resp = ApiResponse.from_string('Event {} created'.format(eventid), code=201) else: event = brains[0].getObject() event.title = title event.text = IRichText['text'].fromUnicode(body) event.reindexObject() resp = ApiResponse.from_string('Event {} updated'.format(eventid)) return resp
def POST(self): params = {} params['nom'] = self.params.pop('title') params['community_type'] = self.params.pop('community_type') params['description'] = self.params.pop('description', None) params['image'] = self.params.pop('image', None) params['activity_view'] = self.params.pop('activity_view', None) params['twitter_hashtag'] = self.params.pop('twitter_hashtag', None) params['notify_activity_via_push'] = self.params.pop('notify_activity_via_push', None) params['notify_activity_via_push_comments_too'] = self.params.pop('notify_activity_via_push_comments_too', None) pc = api.portal.get_tool('portal_catalog') nom = safe_unicode(params['nom']) util = queryUtility(IIDNormalizer) id_normalized = util.normalize(nom, max_length=500) result = pc.unrestrictedSearchResults(portal_type='ulearn.community', id=id_normalized) imageObj = '' if params['image']: mime = MimeTypes() mime_type = mime.guess_type(params['image']) imgName = (params['image'].split('/')[-1]).decode('utf-8') imgData = requests.get(params['image']).content imageObj = NamedBlobImage(data=imgData, filename=imgName, contentType=mime_type[0]) if result: # community = result[0].getObject() success_response = 'Community already exists.' status = 200 else: new_community_id = self.context.invokeFactory('ulearn.community', id_normalized, title=params['nom'], description=params['description'], image=imageObj, community_type=params['community_type'], activity_view=params['activity_view'], twitter_hashtag=params['twitter_hashtag'], notify_activity_via_push=True if params['notify_activity_via_push'] == 'True' else None, notify_activity_via_push_comments_too=True if params['notify_activity_via_push_comments_too'] == 'True' else None, checkConstraints=False) new_community = self.context[new_community_id] success_response = 'Created community "{}" with hash "{}".'.format(new_community.absolute_url(), sha1(new_community.absolute_url()).hexdigest()) status = 201 logger.info(success_response) return ApiResponse.from_string(success_response, code=status)
def DELETE(self): # # Check if there's a valid community with the requested hash # lookedup_obj = self.lookup_community() # if lookedup_obj is not True: # return lookedup_obj # # # Hard security validation as the view is soft checked # check_permission = self.check_roles(self.community, ['Owner', 'Manager']) # if check_permission is not True: # return check_permission self.remove_subscriptions() # Response successful success_response = 'Unsubscription to the requested community done.' logger.info(success_response) return ApiResponse.from_string(success_response, code=200)
def POST(self): """ Subscribes a bunch of users to a community the security is given an initial soft check for authenticated users at the view level and then by checking explicitly if the requester user has permission on the target community. """ # Lookup for object # lookedup_obj = self.lookup_community() # if lookedup_obj is not True: # return lookedup_obj # Hard security validation as the view is soft checked # check_permission = self.check_roles(self.community, ['Owner', 'Manager']) # if check_permission is not True: # return check_permission self.set_subscriptions() # Response successful success_response = 'Updated community "{}" subscriptions'.format(self.target.absolute_url()) logger.info(success_response) return ApiResponse.from_string(success_response)
def POST(self): """ Subscribes a bunch of users to a community the security is given an initial soft check for authenticated users at the view level and then by checking explicitly if the requester user has permission on the target community. """ # Lookup for object # lookedup_obj = self.lookup_community() # if lookedup_obj is not True: # return lookedup_obj # Hard security validation as the view is soft checked # check_permission = self.check_roles(self.community, ['Owner', 'Manager']) # if check_permission is not True: # return check_permission self.set_subscriptions() # Response successful success_response = 'Updated community "{}" subscriptions'.format( self.target.absolute_url()) logger.info(success_response) return ApiResponse.from_string(success_response)
def GET(self): show_news_in_app = api.portal.get_registry_record(name='ulearn.core.controlpanel.IUlearnControlPanelSettings.show_news_in_app') if show_news_in_app: newid = self.params['newid'] mountpoint_id = self.context.getPhysicalPath()[1] if mountpoint_id == self.context.id: default_path = api.portal.get().absolute_url_path() + '/news' else: default_path = '/' + mountpoint_id + '/' + api.portal.get().id + '/news' item = api.content.find(portal_type="News Item", path=default_path, id=newid) if item: newitem = item[0] value = newitem.getObject() if value.effective_date: date = value.effective_date.strftime("%d/%m/%Y") else: date = value.creation_date.strftime("%d/%m/%Y") if value.text: text = value.text.output else: text = '' is_inapp = None is_outoflist = None is_flash = None is_important = None filename = None contentType = None raw_image = None if getattr(newitem, 'is_inapp', None): is_inapp = newitem.is_inapp if getattr(newitem, 'is_outoflist', None): is_outoflist = newitem.is_outoflist if getattr(newitem, 'is_flash', None): is_flash = newitem.is_flash if getattr(newitem, 'is_important', None): is_important = newitem.is_important if getattr(value, 'image', None): filename = value.image.filename contentType = value.image.contentType raw_image = value.absolute_url() + '/thumbnail-image' new = dict(title=value.title, id=value.id, description=value.description, path=value.absolute_url(), absolute_url=value.absolute_url_path(), text=text, filename=filename, caption=value.image_caption, is_inapp=is_inapp, is_outoflist=is_outoflist, is_flash=is_flash, is_important=is_important, effective_date=date, creators=value.creators, content_type=contentType, raw_image=raw_image, ) else: raise ObjectNotFound('News Item not found') return ApiResponse(new) else: return ApiResponse.from_string('Show in App not enabled on this site', code=404)
def create_new(self, newid, title, desc, body, imgData, imgName, date_start, date_end): date_start = date_start.split('/') time_start = date_start[3].split(':') portal_url = api.portal.get() news_url = portal_url['news'] pc = api.portal.get_tool('portal_catalog') brains = pc.unrestrictedSearchResults(portal_type='News Item', id=newid) if not brains: if imgName != '': new_new = createContentInContainer(news_url, 'News Item', title=newid, image=NamedBlobImage(data=imgData, filename=imgName, contentType='image/jpeg'), description=desc, timezone="Europe/Madrid", checkConstraints=False) else: new_new = createContentInContainer(news_url, 'News Item', title=newid, description=desc, timezone="Europe/Madrid", checkConstraints=False) new_new.title = title new_new.setEffectiveDate(datetime(int(date_start[2]), int(date_start[1]), int(date_start[0]), int(time_start[0]), int(time_start[1]) ) ) if date_end: date_end = date_end.split('/') time_end = date_end[3].split(':') new_new.setExpirationDate(datetime(int(date_end[2]), int(date_end[1]), int(date_end[0]), int(time_end[0]), int(time_end[1]) ) ) new_new.text = IRichText['text'].fromUnicode(body) new_new.reindexObject() resp = ApiResponse.from_string('News Item {} created'.format(newid), code=201) else: new = brains[0].getObject() new.title = title new.description = desc new.setEffectiveDate(datetime(int(date_start[2]), int(date_start[1]), int(date_start[0]), int(time_start[0]), int(time_start[1]) ) ) if date_end: new.setExpirationDate(datetime(int(date_end[2]), int(date_end[1]), int(date_end[0]), int(time_end[0]), int(time_end[1]) ) ) if imgName != '': new.image = NamedBlobImage(data=imgData, filename=imgName, contentType='image/jpeg') new.text = IRichText['text'].fromUnicode(body) new.reindexObject() resp = ApiResponse.from_string('News Item {} updated'.format(newid), code=200) return resp