Example #1
0
    def read(self, nbytes=None):
        '''
        @see: Content.read
        '''
        if not self._response:
            try: self._response = urlopen(self._url)
            except (HTTPError, socket.error) as e:
                log.error('Can not read icon image data %s' % e)
                raise InputError(Ref(_('Can not open icon URL'),))
            if not self._response:
                log.error('Can not read icon image data %s' % e)
                raise InputError(Ref(_('Can not open icon URL'),))
            if str(self._response.status) != '200':
                raise InputError(Ref(_('Can not open icon URL'),))

            self.type = self._response.getheader('Content-Type')
            if not self.type:
                self.type = 'image'
            self.length = self._response.getheader('Content-Length')
            if not self.length:
                self.length = 0

        if (not self._response) or self._response.closed:
            return ''

        try:
            if nbytes:
                return self._response.read(nbytes)
            return self._response.read()
        except (HTTPError, socket.error) as e:
            log.error('Can not read icon image data %s' % e)
            raise InputError(Ref(_('Can not read from icon URL'),))
Example #2
0
    def _toPatternInput(self, match, req):
        '''
        Processes the match as a pattern input.
        '''
        assert isinstance(req, Request)
        inp = Input()
        inp.Id = self._inputId
        self._inputs[self._inputId] = inp

        self._inputId += 1

        inp.Mandatory = True
        inp.ForRequest = req.Id

        if isinstance(match, MatchProperty):
            assert isinstance(match, MatchProperty)
            assert isinstance(match.node, NodeProperty)
            typ = next(iter(match.node.typesProperties))
            assert isinstance(typ, TypeModelProperty)
            inp.Description = _('The %(type)s of %(model)s %(description)s') % \
                        dict(type=_(typ.property), model=_(typ.container.name),
                        description=re.sub('[\s]+', ' ', getdoc(typ.parent.clazz) or '...'))
        else:
            raise DevelError('Unknown match %s' % match)

        return inp
Example #3
0
    def addCollaborator(self, blogId, collaboratorId, typeName):
        '''
        @see: IBlogCollaboratorService.addCollaborator
        '''
        typeId = self.collaboratorTypeIds()[typeName]
        if typeId is None: raise InputError(Ref(_('Invalid collaborator type'), ref=BlogCollaborator.Type))

        sql = self.session().query(BlogCollaboratorEntry)
        sql = sql.filter(BlogCollaboratorEntry.Blog == blogId)
        sql = sql.filter(BlogCollaboratorEntry.blogCollaboratorId == collaboratorId)
        if sql.update({BlogCollaboratorEntry.typeId: typeId}) > 0: return

        sql = self.session().query(BlogCollaboratorMapped.Id)
        sql = sql.join(BlogMapped)
        sql = sql.filter(BlogCollaboratorMapped.User == BlogMapped.Creator)
        sql = sql.filter(BlogMapped.Id == blogId)
        sql = sql.filter(BlogCollaboratorMapped.Id == collaboratorId)
        if sql.count() > 0: raise InputError(_('The blog creator cannot be assigned as a collaborator'))

        bgc = BlogCollaboratorEntry()
        bgc.Blog = blogId
        bgc.blogCollaboratorId = collaboratorId
        bgc.typeId = typeId
        self.session().add(bgc)
        self.session().flush((bgc,))
Example #4
0
    def exchange(self, firstId, secondId):
        '''
        @see: IBlogMediaService.exchange
        '''
        firstMedia = self.session().query(BlogMediaMapped).get(firstId)
        if not firstMedia: raise InputError(Ref(_('Unknown blog media id'), ref=BlogMedia.Id))
        assert isinstance(firstMedia, BlogMediaMapped), 'Invalid blog media %s' % firstMedia

        secondMedia = self.session().query(BlogMediaMapped).get(secondId)
        if not secondMedia: raise InputError(Ref(_('Unknown blog media id'), ref=BlogMedia.Id))
        assert isinstance(secondMedia, BlogMediaMapped), 'Invalid blog media %s' % secondMedia

        if firstMedia.Blog != secondMedia.Blog:
            raise InputError(Ref(_('Blog media have to be of the same blog'),))

        if firstMedia.Type != secondMedia.Type:
            raise InputError(Ref(_('Blog media have to be of the same type'),))

        firstRank, secondRank = secondMedia.Rank, firstMedia.Rank

        try:
            firstMedia.Rank = 0
            self.session().flush((firstMedia,))

            firstMedia.Rank, secondMedia.Rank = firstRank, secondRank
            self.session().flush((secondMedia,))
            self.session().flush((firstMedia,))
        except SQLAlchemyError as e: handle(e, mediaDb)
Example #5
0
def handle(e, entity):
    '''
    Handles the SQL alchemy exception while inserting or updating.
    '''
    if isinstance(e, IntegrityError):
        raise InputError(Ref(_('Cannot persist, failed unique constraints on entity'), model=typeFor(entity).container))
    if isinstance(e, OperationalError):
        raise InputError(Ref(_('A foreign key is not valid'), model=typeFor(entity).container))
    raise e
Example #6
0
    def addSource(self, blogId, source):
        '''
        @see: IBlogSourceService.addSource
        NB: The source must have the correct type set in.
            This way, we can reuse it for other purposes, apart from the chained blogs.
        '''
        assert isinstance(blogId, int), 'Invalid blog identifier %s' % blogId
        assert isinstance(source, Source), 'Invalid source %s' % source

        # insert source if it didn't exist yet
        q = QSource(name=source.Name, uri=source.URI)
        sources = self.sourceService.getAll(typeKey=source.Type, q=q)
        if not sources: sourceId = self.sourceService.insert(source)
        else:
            source.Id = sourceId = sources[0].Id
            self.sourceService.update(source)

        ent = BlogSourceDB()
        ent.blog = blogId
        ent.source = sourceId
        try:
            self.session().add(ent)
            self.session().flush((ent,))
        except SQLAlchemyError:
            raise InputError(Ref(_('Cannot add blog-source link.'),))
        return sourceId
Example #7
0
def onPropertyForeignKey(mapped, foreignColumn, prop, obj, errors):
    '''
    Validation of a sql alchemy fpreign key property.
    
    @param mapped: class
        The mapped model class.
    @param foreignColumn: Column
        The foreign column used for checking.
    @param prop: string
        The property name tthat contains the foreign key.
    @param obj: object
        The entity to check for the property value.
    @param errors: list[Ref]
        The list of errors.
    '''
    assert isclass(mapped), 'Invalid class %s' % mapped
    assert isinstance(foreignColumn, Column), 'Invalid foreign column %s' % foreignColumn
    assert isinstance(prop, str), 'Invalid property name %s' % prop
    assert obj is not None, 'None is not a valid object'
    assert isinstance(errors, list), 'Invalid errors list %s' % errors

    propRef = getattr(mapped, prop)
    if propRef in obj:
        val = getattr(obj, prop)
        if val is not None:
            count = openSession().query(foreignColumn).filter(foreignColumn == val).count()
            if count == 0:
                errors.append(Ref(_('Unknown foreign id'), ref=propRef))
                return False
Example #8
0
 def authenticate(self, session):
     '''
     @see: IAuthenticationService.authenticate
     '''
     olderThan = self.session().query(current_timestamp()).scalar()
     olderThan -= self._sessionTimeOut
     sql = self.session().query(LoginMapped)
     sql = sql.filter(LoginMapped.Session == session)
     sql = sql.filter(LoginMapped.AccessedOn > olderThan)
     try: login = sql.one()
     except NoResultFound: raise InputError(Ref(_('Invalid session'), ref=Login.Session))
     assert isinstance(login, LoginMapped), 'Invalid login %s' % login
     login.AccessedOn = current_timestamp()
     self.session().flush((login,))
     self.session().expunge(login)
     commitNow()
     
     # We need to fore the commit because if there is an exception while processing the request we need to make
     # sure that the last access has been updated.
     proc = self._processing
     assert isinstance(proc, Processing), 'Invalid processing %s' % proc
     
     solicitation = proc.ctx.solicitation()
     assert isinstance(solicitation, Solicitation), 'Invalid solicitation %s' % solicitation
     solicitation.userId = login.User
     solicitation.types = self.acl.types
     
     chain = Chain(proc)
     chain.process(**proc.fillIn(solicitation=solicitation, reply=proc.ctx.reply())).doAll()
     
     reply = chain.arg.reply
     assert isinstance(reply, Reply), 'Invalid reply %s' % reply
     if reply.gateways is None: return ()
     
     return sorted(reply.gateways, key=lambda gateway: (gateway.Pattern, gateway.Methods))
Example #9
0
 def getById(self, guid):
     '''
     Implementation for @see: IItemService.getById
     '''
     item = self.session().query(ItemMapped).get(guid)
     if not item: raise InputError(Ref(_('Unknown id'), ref=ItemMapped.GUId))
     return item
Example #10
0
def onPropertyUnique(mapped, prop, obj, errors):
    '''
    Validation of a sql alchemy unique property.
    
    @param mapped: class
        The mapped model class.
    @param prop: string
        The property name to be checked if unique.
    @param obj: object
        The entity to check for the property value.
    @param errors: list[Ref]
        The list of errors.
    '''
    assert isclass(mapped), 'Invalid class %s' % mapped
    assert isinstance(prop, str), 'Invalid property name %s' % prop
    assert obj is not None, 'None is not a valid object'
    assert isinstance(errors, list), 'Invalid errors list %s' % errors

    propRef = getattr(mapped, prop)
    if propRef in obj:
        try:
            db = openSession().query(mapped).filter(propRef == getattr(obj, prop)).one()
        except NoResultFound:
            return
        propId = typeFor(mapped).container.propertyId
        if getattr(obj, propId) != getattr(db, propId):
            errors.append(Ref(_('Already an entry with this value'), ref=propRef))
            return False
Example #11
0
    def insert(self, content):
        '''
        @see: IMetaDataService.insert
        '''
        assert isinstance(content, Content), 'Invalid content %s' % content
        if not content.getName(): raise InputError(_('No name specified for content'))

        metaData = MetaDataMapped()
        metaData.CreatedOn = datetime.now()
        metaData.Name = content.getName()
        metaData.Type = self._metaType.Key
        metaData.typeId = self._metaType.id
        metaData.thumbnailId = self._thumbnail.id
        try:
            self.session().add(metaData)
            self.session().flush((metaData,))

            path = abspath(join(self.processing_dir_path, '.'.join((str(metaData.Id), metaData.Name))))
            with open(path, 'w+b') as fobj: pipe(content, fobj)
            metaData.SizeInBytes = getsize(path)

            self.session().flush((metaData,))

            with open(path, 'rb') as fobj: self.cdmArchive.publishFromFile(self._reference(metaData), fobj)

            for handler in self.metaDataHandlers:
                assert isinstance(handler, IMetaDataHandler), 'Invalid handler %s' % handler
                if handler.process(metaData.Id, path): break
            else:
                remove(path)

        except SQLAlchemyError as e: handle(e, metaData)

        return metaData.Id
Example #12
0
    def addSource(self, blogId, source):
        '''
        @see: IBlogSourceService.addSource
        '''
        assert isinstance(blogId, int), 'Invalid blog identifier %s' % blogId
        assert isinstance(source, Source), 'Invalid source %s' % source

        # insert source if it didn't exist yet for the given blog
        sql = self.session().query(SourceMapped)
        sql = sql.join(BlogSyncMapped, SourceMapped.Id == BlogSyncMapped.Source)
        sql = sql.filter(BlogSyncMapped.Blog == blogId)
        sql = sql.filter(and_(SourceMapped.Name == source.Name, SourceMapped.URI == source.URI))
        
        try:
            sourceId = source.Id = sql.one().Id
            self.sourceService.update(source)
        except NoResultFound:
            sourceId = self.sourceService.insert(source)    
           
            blogSync = BlogSyncMapped()
            blogSync.Blog = blogId
            blogSync.Source = sourceId
            blogSync.CId = 0
            blogSync.Auto = False
            self.blogSyncService.insert(blogSync)  
                  
        ent = BlogSourceDB()
        ent.blog = blogId
        ent.source = sourceId
        try:
            self.session().add(ent)
            self.session().flush((ent,))
        except SQLAlchemyError:
            raise InputError(Ref(_('Cannot add blog-source link.'),))
        return sourceId
Example #13
0
 def getRequest(self, id):
     '''
     @see: IRequestService.getRequest
     '''
     self._refresh()
     if id not in self._requests: raise InputError(Ref(_('Invalid request id'), ref=Request.Id))
     return self._requests[id]
Example #14
0
 def authenticate(self, session):
     '''
     @see: IAuthenticationService.authenticate
     '''
     olderThan = self.session().query(current_timestamp()).scalar()
     olderThan -= self._sessionTimeOut
     sql = self.session().query(LoginMapped)
     sql = sql.filter(LoginMapped.Session == session)
     sql = sql.filter(LoginMapped.AccessedOn > olderThan)
     try: login = sql.one()
     except NoResultFound: raise InputError(Ref(_('Invalid session'), ref=Login.Session))
     assert isinstance(login, LoginMapped), 'Invalid login %s' % login
     login.AccessedOn = current_timestamp()
     self.session().flush((login,))
     self.session().expunge(login)
     commitNow()
     # We need to fore the commit because if there is an exception while processing the request we need to make
     # sure that the last access has been updated.
     
     userId = str(login.User)
     rights = (right.Name for right in self.userRbacService.getRights(login.User))
     accesses = self.aclAccessService.accessFor(self.aclAccessService.rightsFor(rights))
     allowed = []
     for access in accesses:
         assert isinstance(access, AclAccess), 'Invalid access %s' % access
         for propertyType, mark in access.markers.items():
             assert isinstance(propertyType, TypeProperty), 'Invalid property type %s' % propertyType
             assert isinstance(propertyType.parent, TypeModel)
             if propertyType.parent.clazz == User or issubclass(propertyType.parent.clazz, User):
                 for k in range(len(access.Filter)): access.Filter[k] = access.Filter[k].replace(mark, userId)
         allowed.append(access)
     return allowed
Example #15
0
 def getById(self, id, scheme, thumbSize=None):
     '''
     @see: IMetaDataService.getById
     '''
     metaData = self.session().query(self.MetaData).get(id)
     if metaData is None: raise InputError(Ref(_('Unknown meta data'), ref=self.MetaData.Id))
     return self.referencer.populate(metaData, scheme, thumbSize)
Example #16
0
 def asValue(self, strValue, objType):
     '''
     @see: Converter.asValue
     '''
     assert isinstance(objType, Type), 'Invalid object type %s' % objType
     if strValue is None: return None
     if isinstance(objType, TypeModel): # If type model is provided we consider the model property type 
         assert isinstance(objType, TypeModel)
         container = objType.container
         assert isinstance(container, Model)
         objType = container.properties[container.propertyId]
     if objType.isOf(str):
         return strValue
     if objType.isOf(Boolean):
         return strValue.strip().lower() == _('true').lower()
     if objType.isOf(Percentage):
         return float(strValue) / 100
     if objType.isOf(int):
         return int(strValue)
     if objType.isOf(Number):
         return bn.parse_decimal(strValue, self.locale)
     if objType.isOf(Date):
         return datetime.strptime(strValue, '%Y-%m-%d').date()
     if objType.isOf(Time):
         return datetime.strptime(strValue, '%H:%M:%S').time()
     if objType.isOf(DateTime):
         return datetime.strptime(strValue, '%Y-%m-%d %H:%M:%S')
     raise TypeError('Invalid object type %s for Babel converter' % objType)
Example #17
0
 def getById(self, id):
     '''
     @see: IEntityGetService.getById
     '''
     entity = self.session().query(self.Entity).get(id)
     if not entity: raise InputError(Ref(_('Unknown id'), ref=self.Entity.Id))
     return entity
Example #18
0
 def getByCode(self, code, locales):
     '''
     @see: ILanguageService.getByCode
     '''
     locale = self._localeOf(code)
     if not locale: raise InputError(Ref(_('Unknown language code'), ref=Language.Code))
     return self._populate(Language(code), self._translator(locale, self._localesOf(locales)))
    def getComponentJSONFile(self, component, locale, scheme):
        """
        @see: IPOService.getComponentPOFile
        """
        self.componentService.getById(component)
        path = self._cdmPath(locale, component=component)
        try:
            try:
                cdmFileTimestamp = self.cdmLocale.getTimestamp(path)
            except PathNotFound:
                republish = True
            else:
                mngFileTimestamp = max(
                    self.poFileManager.getGlobalPOTimestamp(locale) or datetime.min,
                    self.poFileManager.getComponentPOTimestamp(component, locale) or datetime.min,
                )
                republish = False if mngFileTimestamp is None else cdmFileTimestamp < mngFileTimestamp

            if republish:
                jsonString = JSONEncoder(ensure_ascii=False).encode(
                    self.poFileManager.getComponentAsDict(component, locale)
                )
                self.cdmLocale.publishContent(path, BytesIO(bytes(jsonString, getdefaultencoding())))
        except InvalidLocaleError:
            raise InputError(_("Invalid locale %(locale)s") % dict(locale=locale))
        return self.cdmLocale.getURI(path, scheme)
Example #20
0
    def reorder(self, blogId, postId, refPostId, before=True):
        '''
        @see: IBlogPostService.reorder
        '''
        sql = self.session().query(BlogPostMapped.Order)
        sql = sql.filter(BlogPostMapped.Blog == blogId)
        sql = sql.filter(BlogPostMapped.Id == refPostId)
        order = sql.scalar()

        if not order: raise InputError(Ref(_('Invalid before post')))

        sql = self.session().query(BlogPostMapped.Order)
        sql = sql.filter(BlogPostMapped.Blog == blogId)
        sql = sql.filter(BlogPostMapped.Id != postId)
        if before:
            sql = sql.filter(BlogPostMapped.Order > order)
            sql = sql.order_by(BlogPostMapped.Order)
        else:
            sql = sql.filter(BlogPostMapped.Order < order)
            sql = sql.order_by(desc_op(BlogPostMapped.Order))

        sql = sql.limit(1)

        orderPrev = sql.scalar()

        if orderPrev: order = (order + orderPrev) / 2
        elif before: order += 1
        else: order -= 1

        post = self.getById(blogId, postId)
        assert isinstance(post, BlogPostMapped)

        post.Order = order
        post.CId = self._nextCId()
        self.session().merge(post)
Example #21
0
    def reorder(self, blogTypeId, postId, refPostId, before=True):
        '''
        @see: IBlogPostService.reorder
        '''
        sql = self.session().query(BlogTypePostMapped.Order)
        sql = sql.filter(BlogTypePostMapped.BlogType == blogTypeId)
        sql = sql.filter(BlogTypePostMapped.Id == refPostId)
        order = sql.scalar()

        if order is None: raise InputError(Ref(_('Invalid before post')))

        sql = self.session().query(BlogTypePostMapped.Order)
        sql = sql.filter(BlogTypePostMapped.BlogType == blogTypeId)
        sql = sql.filter(BlogTypePostMapped.Id != postId)
        if before:
            sql = sql.filter(BlogTypePostMapped.Order < order)
            sql = sql.order_by(desc_op(BlogTypePostMapped.Order))
        else:
            sql = sql.filter(BlogTypePostMapped.Order > order)
            sql = sql.order_by(BlogTypePostMapped.Order)
        sql = sql.limit(1)
        orderPrev = sql.scalar()

        if orderPrev is not None: order = (order + orderPrev) / 2
        else: order = order - 1 if before else order + 1

        post = self.getById(blogTypeId, postId)
        assert isinstance(post, BlogTypePostMapped)

        post.Order = order
        self.session().merge(post)
        self.session().flush((post,))
Example #22
0
 def getMethod(self, id):
     '''
     @see: IRequestService.getMethod
     '''
     self._refresh()
     if id not in self._methods: raise InputError(Ref(_('Invalid method id'), ref=Method.Id))
     return self._methods[id]
Example #23
0
 def getByCode(self, code, locales):
     """
     @see: ICountryService.getByCode
     """
     if code not in self.countries:
         raise InputError(Ref(_("Unknown country code"), ref=Country.Code))
     return Country(code, self._translate(code, self._localesOf(locales)))
Example #24
0
    def performLogin(self, authentication):
        '''
        @see: IAuthenticationService.performLogin
        '''
        assert isinstance(authentication, Authentication), 'Invalid authentication %s' % authentication

        if authentication.Token is None:
            raise InputError(Ref(_('The login token is required'), ref=Authentication.Token))
        if authentication.HashedToken is None:
            raise InputError(Ref(_('The hashed login token is required'), ref=Authentication.HashedToken))
        if authentication.UserName is None:
            raise InputError(Ref(_('A user name is required for authentication'), ref=Authentication.UserName))

        olderThan = self.session().query(current_timestamp()).scalar()
        olderThan -= self._authenticationTimeOut
        sql = self.session().query(TokenMapped)
        sql = sql.filter(TokenMapped.Token == authentication.Token)
        sql = sql.filter(TokenMapped.requestedOn > olderThan)
        if sql.delete() > 0:
            commitNow()  # We make sure that the delete has been performed

            try: user = self.session().query(UserMapped).filter(UserMapped.Name == authentication.UserName).filter(UserMapped.DeletedOn == None).one()
            except NoResultFound: user = None

            if user is not None:
                assert isinstance(user, UserMapped), 'Invalid user %s' % user

                hashedToken = hmac.new(bytes(user.Name, 'utf8'),
                                       bytes(user.password, 'utf8'), hashlib.sha512).hexdigest()
                hashedToken = hmac.new(bytes(hashedToken, 'utf8'),
                                       bytes(authentication.Token, 'utf8'), hashlib.sha512).hexdigest()

                if authentication.HashedToken == hashedToken:
                    hash = hashlib.sha512()
                    hash.update(urandom(self.authentication_token_size))

                    login = LoginMapped()
                    login.Session = hash.hexdigest()
                    login.User = user.Id
                    login.CreatedOn = login.AccessedOn = current_timestamp()

                    try: self.session().add(login)
                    except SQLAlchemyError as e: handle(e, login)

                    return login

        raise InputError(_('Invalid credentials'))
Example #25
0
 def getById(self, id, locales):
     '''
     @see: ILanguageService.getById
     '''
     locales = self._localesOf(locales)
     language = self.session().query(LanguageEntity).get(id)
     if not language: raise InputError(Ref(_('Unknown language id'), ref=LanguageEntity.Id))
     return self._populate(language, self._translator(self._localeOf(language.Code), locales))
Example #26
0
 def getById(self, id):
     '''
     @see: IComponentService.getById
     '''
     assert isinstance(id, str), 'Invalid id %s' % id
     modules = modulesIn('%s.%s' % (self.package, id)).asList()
     if len(modules) != 1: raise InputError(Ref(_('Invalid component id'), ref=Component.Id))
     return self.componentFor(modules[0])
Example #27
0
 def delete(self, id):
     """
     @see: IEntityCRUDService.delete
     """
     try:
         return self.session().query(self.Entity).filter(self.Entity.Id == id).delete() > 0
     except OperationalError:
         raise InputError(Ref(_("Cannot delete because is in use"), model=self.model))
Example #28
0
 def getById(self, id):
     '''
     @see: IPluginService.getById
     '''
     assert isinstance(id, str), 'Invalid id %s' % id
     modules = modulesIn('%s.%s' % ('__plugin__', id)).asList()
     if len(modules) != 1: raise InputError(Ref(_('Invalid plugin id'), ref=Plugin.Id))
     return self.pluginFor(modules[0])
Example #29
0
 def getAllInputs(self, id):
     '''
     @see: IRequestService.getAllInputs
     '''
     self._refresh()
     if not id: return self._inputs.values()
     if id not in self._patternInputs: raise InputError(Ref(_('Invalid request id'), ref=Request.Id))
     return (self._inputs[inpId] for inpId in self._patternInputs[id])
Example #30
0
 def getById(self, id):
     '''
     @see: IUserService.getById
     '''
     user = self.session().query(UserMapped).get(id)
     if not user: raise InputError(Ref(_('Unknown user id'), ref=User.Id))
     assert isinstance(user, UserMapped), 'Invalid user %s' % user
     return user
 def removeCollaborator(self, blogId, collaboratorId):
     '''
     @see: IBlogCollaboratorService.removeCollaborator
     '''
     try:
         sql = self.session().query(BlogCollaboratorEntry)
         sql = sql.filter(BlogCollaboratorEntry.Blog == blogId)
         sql = sql.filter(BlogCollaboratorEntry.blogCollaboratorId == collaboratorId)
         return sql.delete() > 0
     except OperationalError:
         raise InputError(Ref(_('Cannot remove'), model=BlogCollaboratorMapped))
Example #32
0
 def _validateCode(self, language, model, prop, errors):
     '''
     Validates the language code on a language instance, this is based on the operator listeners.
     '''
     assert isinstance(language, Language), 'Invalid language %s' % language
     locale = self._localeOf(language.Code)
     if not locale:
         errors.append(Ref(_('Invalid language code'), ref=Language.Code))
         return False
     else:
         language.Code = str(locale)
Example #33
0
 def getById(self, id, locales):
     '''
     @see: ILanguageService.getById
     '''
     locales = self._localesOf(locales)
     language = self.session().query(LanguageEntity).get(id)
     if not language:
         raise InputError(
             Ref(_('Unknown language id'), ref=LanguageEntity.Id))
     return self._populate(
         language, self._translator(self._localeOf(language.Code), locales))
Example #34
0
    def getBlog(self, blogId):
        '''
        @see: IBlogService.getBlog
        '''
        sql = self.session().query(BlogMapped)
        sql = sql.filter(BlogMapped.Id == blogId)

        try:
            return sql.one()
        except NoResultFound:
            raise InputError(Ref(_('Unknown id'), ref=Blog.Id))
Example #35
0
 def getSource(self, blogId, sourceId):
     '''
     @see: IBlogSourceService.getSource
     '''
     source = self.session().query(SourceMapped).get(sourceId)
     if not source:
         raise InputError(Ref(_('Unknown source'), ))
     sql = self.session().query(BlogSourceDB)
     sql = sql.filter(BlogSourceDB.blog == blogId).filter(
         BlogSourceDB.source == sourceId)
     return source
Example #36
0
    def getBySlug(self, slug):
        '''
        @see:
        '''
        sql = self.session().query(ArticleMapped)
        sql = sql.filter(ArticleMapped.Slug == slug)

        try:
            return sql.one()
        except NoResultFound:
            raise InputError(Ref(_('Unknown id'), ref=Article.Id))
Example #37
0
    def update(self, source):
        '''
        @see: ISourceService.update
        '''
        assert isinstance(source, Source), 'Invalid source %s' % source
        sourceDb = self.session().query(SourceMapped).get(source.Id)
        if not sourceDb: raise InputError(Ref(_('Unknown source id'), ref=Source.Id))
        if Source.Type in source: sourceDb.typeId = self._typeId(source.Type)

        try:
            self.session().flush((copy(source, sourceDb, exclude=('Type',)),))
        except SQLAlchemyError as e: handle(e, SourceMapped)
Example #38
0
    def update(self, post):
        '''
        @see: IPostService.update
        '''
        assert isinstance(post, Post), 'Invalid post %s' % post
        postDb = self.session().query(PostMapped).get(post.Id)
        if not postDb or postDb.DeletedOn is not None: raise InputError(Ref(_('Unknown post id'), ref=Post.Id))

        if Post.Type in post: postDb.typeId = self._typeId(post.Type)
        if post.UpdatedOn is None: postDb.UpdatedOn = current_timestamp()

        self.session().flush((copy(post, postDb, exclude=COPY_EXCLUDE),))
Example #39
0
 def _typeId(self, key):
     '''
     Provides the post type id that has the provided key.
     '''
     try:
         sql = self.session().query(
             PostTypeMapped.id).filter(PostTypeMapped.Key == key)
         return sql.one()[0]
     except NoResultFound:
         raise InputError(
             Ref(_('Invalid post type %(type)s') % dict(type=key),
                 ref=Post.Type))
Example #40
0
 def getByPersonId(self, id, scheme='http', thumbSize=None):
     '''
     @see: IPersonIconService.getById
     '''
     personIcon = self.session().query(PersonIconMapped).get(id)
     if not personIcon:
         raise InputError(
             Ref(_('Invalid person icon'), ref=PersonIconMapped.Id))
     assert isinstance(personIcon, PersonIconMapped)
     assert isinstance(self.metaDataService, IMetaDataService)
     metaData = self.metaDataService.getById(personIcon.MetaData, scheme,
                                             thumbSize)
     return metaData
Example #41
0
    def getById(self, blogTypeId, postId):
        '''
        @see: IBlogPostService.getById
        '''
        sql = self.session().query(BlogTypePostMapped)
        sql = sql.filter(BlogTypePostMapped.BlogType == blogTypeId)
        sql = sql.filter(BlogTypePostMapped.Id == postId)

        try:
            return sql.one()
        except NoResultFound:
            raise InputError(
                Ref(_('No such blog post'), ref=BlogTypePostMapped.Id))
Example #42
0
 def changePassword(self, adminId, user):
     '''
     @see: IUserService.changePassword
     '''
     userDb = self.session().query(UserMapped).get(user.Id)
     if not userDb or userDb.DeletedOn is not None:
         assert isinstance(userDb, UserMapped), 'Invalid user %s' % userDb
         raise InputError(Ref(_('Unknown user id'), ref=User.Id))
     try:
         userDb.password = user.Password
         self.session().flush((userDb, ))
     except SQLAlchemyError as e:
         handle(e, userDb)
Example #43
0
    def getById(self, blogId, collaboratorId):
        '''
        @see: IBlogCollaboratorService.getById
        '''
        sql = self.session().query(BlogCollaboratorMapped)
        sql = sql.filter(BlogCollaboratorMapped.Blog == blogId)
        sql = sql.filter(BlogCollaboratorMapped.Id == collaboratorId)

        try:
            return sql.one()
        except NoResultFound:
            raise InputError(
                Ref(_('No collaborator'), ref=BlogCollaboratorMapped.Id))
Example #44
0
    def getById(self, blogId, postId, thumbSize=None):
        '''
        @see: IBlogPostService.getById
        '''
        sql = self.session().query(BlogPostMapped)
        sql = sql.filter(BlogPostMapped.Blog == blogId)
        sql = sql.filter(BlogPostMapped.Id == postId)

        try:
            return self._addImage(sql.one(), thumbSize)
        except NoResultFound:
            raise InputError(Ref(_('No such blog post'),
                                 ref=BlogPostMapped.Id))
Example #45
0
    def putLive(self, adminId, blogId):
        '''
        @see: IBlogService.putLive
        '''
        sql = self._buildQuery(adminId=adminId)
        sql = sql.filter(BlogMapped.Id == blogId)

        try:
            blog = sql.one()
        except NoResultFound:
            raise InputError(_('Invalid blog or credentials'))
        assert isinstance(blog, Blog), 'Invalid blog %s' % blog
        blog.LiveOn = current_timestamp() if blog.LiveOn is None else None
        return self.session().merge(blog)
Example #46
0
    def delete(self, parentId, name):
        '''
        @see: IConfigurationService.delete
        '''
        assert isinstance(parentId, int), 'Invalid parentId'
        assert isinstance(name, str), 'Invalid configuration name'

        sql = self.session().query(self.ConfigurationMapped)
        sql = sql.filter(self.ConfigurationMapped.parent == parentId)
        sql = sql.filter(self.ConfigurationMapped.Name == name)
        try:
            return sql.delete() > 0
        except OperationalError:
            raise InputError(Ref(_('Cannot delete the configuration'), ))
Example #47
0
 def delete(self, guid):
     '''
     @see: IItemService.delete
     '''
     try:
         return self.session().query(ItemMapped).filter(
             ItemMapped.GUId == guid).delete() > 0
     except OperationalError:
         assert log.debug('Could not delete item %s with id \'%s\'',
                          ItemMapped,
                          guid,
                          exc_info=True) or True
         raise InputError(
             Ref(_('Cannot delete because is in use'), model=self.model))
Example #48
0
    def _userTypeId(self, key):
        '''
        Provides the user type id that has the provided key.
        '''
        if not key: key = self.default_user_type_key

        try:
            sql = self.session().query(
                UserTypeMapped.id).filter(UserTypeMapped.Key == key)
            return sql.one()[0]
        except NoResultFound:
            raise InputError(
                Ref(_('Invalid user type %(userType)s') % dict(userType=key),
                    ref=User.Type))
Example #49
0
    def insert(self, userId, content):
        '''
        @see: IMetaDataService.insert
        '''
        assert isinstance(content, Content), 'Invalid content %s' % content
        if not content.name:
            raise InputError(_('No name specified for content'))

        metaData = MetaDataMapped()
        metaData.CreatedOn = current_timestamp()
        metaData.Creator = userId
        metaData.Name = content.name

        metaData.typeId = self._metaType.Id
        metaData.thumbnailFormatId = self._thumbnailFormat.id

        try:
            self.session().add(metaData)
            self.session().flush((metaData, ))

            path = self.format_file_name % {
                'id': metaData.Id,
                'name': metaData.Name
            }
            path = ''.join((META_TYPE_KEY, '/',
                            self.generateIdPath(metaData.Id), '/', path))
            contentPath = self.cdmArchive.getURI(path, 'file')

            self.cdmArchive.publishContent(path, content)
            metaData.content = path
            metaData.SizeInBytes = getsize(contentPath)

            for handler in self.metaDataHandlers:
                assert isinstance(
                    handler, IMetaDataHandler), 'Invalid handler %s' % handler
                if handler.processByInfo(metaData, contentPath, content.type):
                    break
            else:
                for handler in self.metaDataHandlers:
                    if handler.process(metaData, contentPath): break

            self.session().merge(metaData)
            self.session().flush((metaData, ))
        except SQLAlchemyError as e:
            handle(e, metaData)

        if metaData.content != path:
            self.cdmArchive.republish(path, metaData.content)

        return metaData.Id
Example #50
0
    def update(self, user):
        '''
        @see: IUserService.update
        '''
        assert isinstance(user, User), 'Invalid user %s' % user

        userDb = self.session().query(UserMapped).get(user.Id)
        if not userDb or userDb.DeletedOn is not None:
            assert isinstance(userDb, UserMapped), 'Invalid user %s' % userDb
            raise InputError(Ref(_('Unknown user id'), ref=User.Id))
        try:
            sql = self.session().query(UserMapped)
            sql = sql.filter(UserMapped.Id != user.Id)
            sql = sql.filter(UserMapped.Name == user.Name)
            sql = sql.filter(UserMapped.DeletedOn == None)
            if sql.count() > 0:
                raise InputError(
                    Ref(_('There is already a user with this name'),
                        ref=User.Name))

            self.session().flush((copy(user, userDb), ))
        except SQLAlchemyError as e:
            handle(e, userDb)
Example #51
0
 def delete(self, id):
     '''
     @see: IEntityCRUDService.delete
     '''
     try:
         return self.session().query(
             self.Entity).filter(self.Entity.Id == id).delete() > 0
     except (OperationalError, IntegrityError):
         assert log.debug('Could not delete entity %s with id \'%s\'',
                          self.Entity,
                          id,
                          exc_info=True) or True
         raise InputError(
             Ref(_('Cannot delete because is in use'), model=self.model))
Example #52
0
 def delete(self, key):
     '''
     @see: IEntityCRUDService.delete
     '''
     try:
         return self.session().query(
             self.Entity).filter(self.Entity.Key == key).delete() > 0
     except OperationalError:
         assert log.debug('Could not delete entity %s with key \'%s\'',
                          self.Entity,
                          key,
                          exc_info=True) or True
         raise InputError(
             Ref(_('Cannot delete because is in use'), model=self.model))
Example #53
0
    def getByName(self, nameType, name):
        '''
        @see: IRightService.getByName
        '''
        assert isinstance(nameType, str), 'Invalid type name %s' % nameType
        assert isinstance(name, str), 'Invalid name %s' % name

        sql = self.session().query(RightMapped).join(RightTypeMapped)
        sql = sql.filter(RightTypeMapped.Name == nameType).filter(
            RightMapped.Name == name)

        try:
            return sql.one()
        except NoResultFound:
            raise InputError(Ref(_('Invalid names for right'), ref=Right.Name))
Example #54
0
    def addAdmin(self, blogId, userId):
        '''
        @see: IBlogAdminService.addAdmin
        '''
        sql = self.session().query(AdminEntry)
        sql = sql.filter(AdminEntry.Blog == blogId)
        sql = sql.filter(AdminEntry.adminId == userId)
        if sql.count() > 0: raise InputError(Ref(_('Already an administrator'), ref=AdminMapped.Id))

        bge = AdminEntry()
        bge.Blog = blogId
        bge.adminId = userId
        self.session().add(bge)
        self.session().flush((bge,))
        return bge.adminId
    def addCollaborator(self, blogId, collaboratorId):
        '''
        @see: IBlogCollaboratorService.addCollaborator
        '''
        sql = self.session().query(BlogCollaboratorEntry)
        sql = sql.filter(BlogCollaboratorEntry.Blog == blogId)
        sql = sql.filter(BlogCollaboratorEntry.blogCollaboratorId == collaboratorId)
        if sql.count() > 0: raise InputError(_('Already a collaborator for this blog'))

        bgc = BlogCollaboratorEntry()
        bgc.Blog = blogId
        bgc.blogCollaboratorId = collaboratorId
        self.session().add(bgc)
        self.session().flush((bgc,))
        return bgc.blogCollaboratorId
Example #56
0
    def exchange(self, firstId, secondId):
        '''
        @see: IBlogMediaService.exchange
        '''
        firstMedia = self.session().query(BlogMediaMapped).get(firstId)
        if not firstMedia:
            raise InputError(Ref(_('Unknown blog media id'), ref=BlogMedia.Id))
        assert isinstance(
            firstMedia, BlogMediaMapped), 'Invalid blog media %s' % firstMedia

        secondMedia = self.session().query(BlogMediaMapped).get(secondId)
        if not secondMedia:
            raise InputError(Ref(_('Unknown blog media id'), ref=BlogMedia.Id))
        assert isinstance(
            secondMedia,
            BlogMediaMapped), 'Invalid blog media %s' % secondMedia

        if firstMedia.Blog != secondMedia.Blog:
            raise InputError(Ref(
                _('Blog media have to be of the same blog'), ))

        if firstMedia.Type != secondMedia.Type:
            raise InputError(Ref(
                _('Blog media have to be of the same type'), ))

        firstRank, secondRank = secondMedia.Rank, firstMedia.Rank

        try:
            firstMedia.Rank = 0
            self.session().flush((firstMedia, ))

            firstMedia.Rank, secondMedia.Rank = firstRank, secondRank
            self.session().flush((secondMedia, ))
            self.session().flush((firstMedia, ))
        except SQLAlchemyError as e:
            handle(e)
Example #57
0
    def _adjustTexts(self, postDb):
        '''
        Corrects the Meta, Content, ContentPlain fields
        '''
        # TODO: implement the proper fix using SQLAlchemy compilation rules
        nohigh = {i: None for i in range(0x10000, 0x110000)}
        if postDb.Meta:
            postDb.Meta = postDb.Meta.translate(nohigh)
            if self.meta_max_size and (len(postDb.Meta) > self.meta_max_size):
                raise InputError(Ref(
                    _('Too long Meta part'), ))  # can not truncate json data
        if postDb.Content:
            postDb.Content = postDb.Content.translate(nohigh)
            if self.content_max_size and (len(postDb.Content) >
                                          self.content_max_size):
                raise InputError(Ref(_('Too long Content part'),
                                     ))  # can not truncate structured data
        if postDb.ContentPlain:
            postDb.ContentPlain = postDb.ContentPlain.translate(nohigh)
            if self.content_plain_max_size:
                postDb.ContentPlain = postDb.ContentPlain[:self.
                                                          content_plain_max_size]

        return postDb
Example #58
0
 def handle(self, execution):
     '''
     @see: IProxyHandler.handle
     '''
     assert isinstance(execution, Execution), 'Invalid execution %s' % execution
     assert isinstance(execution.proxyCall, ProxyCall), 'Invalid proxy call %s' % execution.proxyCall
     assert isinstance(execution.proxyCall.proxyMethod, ProxyMethod), \
     'Invalid proxy method %s' % execution.proxyCall.proxyMethod
     
     invoker = self.invokers.get(execution.proxyCall.proxyMethod.name)
     if not invoker: return execution.invoke()
     
     assert isinstance(invoker, Invoker), 'Invalid invoker %s' % invoker
     
     try: return execution.invoke()
     except SQLAlchemyError as exc:
         iexc = None
         
         if isinstance(exc, NoResultFound):
             iexc = IdError()
         
         elif isinstance(exc, IntegrityError):
             iexc = InputError(_('There is already an entity having this unique properties'))
             
         elif isinstance(exc, OperationalError):
             if invoker.method == DELETE: iexc = InputError(_('Cannot delete because is used'))
             elif invoker.method != GET: iexc = InputError(_('An entity relation identifier is not valid'))
         
         if iexc is not None:
             if invoker.target: iexc.update(invoker.target)
             log.info('SQL Alchemy handled exception occurred', exc_info=(type(exc), exc, exc.__traceback__))
             iexc.with_traceback(exc.__traceback__)
             exc = iexc
         else: log.warn('Unknown SQL Alchemy error', exc_info=(type(exc), exc, exc.__traceback__))
             
         raise exc
Example #59
0
 def update(self, entity):
     '''
     @see: IEntityCRUDService.update
     '''
     assert self.modelType.isValid(
         entity), 'Invalid entity %s, expected %s' % (entity, self.Entity)
     entityDb = self.session().query(self.Entity).get(entity.Id)
     if not entityDb:
         raise InputError(Ref(_('Unknown id'), ref=self.Entity.Id))
     try:
         for prop in self.model.properties:
             if getattr(entity.__class__, prop) in entity:
                 setattr(entityDb, prop, getattr(entity, prop))
         self.session().flush((entityDb, ))
     except SQLAlchemyError as e:
         handle(e, self.Entity)
Example #60
0
 def update(self, entity):
     '''
     @see: IEntityCRUDService.update
     '''
     assert self.modelType.isValid(
         entity), 'Invalid entity %s, expected %s' % (entity, self.Entity)
     assert isinstance(
         entity.Id,
         int), 'Invalid entity %s, with id %s' % (entity, entity.Id)
     entityDb = self.session().query(self.Entity).get(entity.Id)
     if not entityDb:
         raise InputError(Ref(_('Unknown id'), ref=self.Entity.Id))
     try:
         self.session().flush((copy(entity, entityDb), ))
     except SQLAlchemyError as e:
         handle(e, self.Entity)