Ejemplo n.º 1
0
def add_points_add_comment(user,
                           point_event,
                           timestamp=None,
                           comment_id=None,
                           **kwargs):
    # Feature: limit to 15 points per day and per user for comments
    # Since we have ADD_COMMENT and REMOVE_COMMENT events that change the bonus points
    # acquired for comments this day we must make sure that if a user has exceeded
    # today's limit and he removes some comments, we must not remove points for the
    # comments that did not credited some points to the user. In fact, we must count
    # the number N of comments that did not credit points (including the previous days),
    # and the N first REMOVE_COMMENT events should not remove points. So we should remember
    # the ADD_COMMENT events that credited 0 points, that why we call the user.add_points
    # with 0 points credit.

    # Max 2 points per day, 1 point per comment
    credited_today = _nb_comments_points_credited_today(user, timestamp)
    if credited_today < 2:
        points_credited = _comment_points_by_date(timestamp)
    else:
        points_credited = 0

    # Log it for further debugging
    log.info("Comment added by %s (credited_today=%s, points_credited=%s)" %
             (user, credited_today, points_credited))

    user.add_points(PointCategory.ADD_COMMENT,
                    nb_points=points_credited,
                    timestamp=timestamp,
                    subject_id=comment_id)
Ejemplo n.º 2
0
 def handle_event(self, event):
     if event.is_(events.BoardLeft) or event.is_(events.BoardArchived):
         return self.select_last_board()
     elif event.is_(events.NewTemplateRequested):
         return self.boards_manager.create_template_from_board(
             event.emitter, *event.data)
     log.info('Ignoring event %s', event)
Ejemplo n.º 3
0
    def remove_board_member(self, member):
        """Remove member from board

        Remove member from board. If member is PendingUser then remove
        invitation.

        Children must be loaded for propagation to the cards.

        In:
            - ``member`` -- Board Member instance to remove
        """
        if self.last_manager(member):
            # Can't remove last manager
            raise exceptions.KanshaException(_("Can't remove last manager"))

        log.info('Removing member %s' % (member,))
        remove_method = {'pending': self.remove_pending,
                         'manager': self.remove_manager,
                         'member': self.remove_member}
        remove_method[member.role](member)

        # remove member from columns
        # FIXME: this function should live in a board extension that has its own data and
        # should not rely on a full component tree.
        if not self.columns:
            self.load_children()
        for c in self.columns:
            c().remove_board_member(member)
Ejemplo n.º 4
0
def add_points_add_comment(user, point_event, timestamp=None,
                           comment_id=None, **kwargs):
    # Feature: limit to 15 points per day and per user for comments
    # Since we have ADD_COMMENT and REMOVE_COMMENT events that change the bonus points
    # acquired for comments this day we must make sure that if a user has exceeded
    # today's limit and he removes some comments, we must not remove points for the
    # comments that did not credited some points to the user. In fact, we must count
    # the number N of comments that did not credit points (including the previous days),
    # and the N first REMOVE_COMMENT events should not remove points. So we should remember
    # the ADD_COMMENT events that credited 0 points, that why we call the user.add_points
    # with 0 points credit.

    # Max 2 points per day, 1 point per comment
    credited_today = _nb_comments_points_credited_today(user, timestamp)
    if credited_today < 2:
        points_credited = _comment_points_by_date(timestamp)
    else:
        points_credited = 0

    # Log it for further debugging
    log.info(
        "Comment added by %s (credited_today=%s, points_credited=%s)" % (
            user, credited_today, points_credited))

    user.add_points(
        PointCategory.ADD_COMMENT,
        nb_points=points_credited,
        timestamp=timestamp,
        subject_id=comment_id
    )
Ejemplo n.º 5
0
def main():
    global apps
    app = apps[APP_NAME]  # @UndefinedVariable

    user1 = user.User("user1")
    local.request.user = user1
    assets_manager = app._services["assets_manager"]
    card1 = card.Card(user1.data.boards[0].columns[1].cards[2].id, None, assets_manager)
    gal = gallery.Gallery(card1, assets_manager)

    package = pkg_resources.Requirement.parse("kansha")
    for i, (fname, ftype) in enumerate(
        (
            ("tie.jpg", "image/jpeg"),
            ("baseball_game.jpg", "image/jpeg"),
            ("LICENSE.txt", "text/plain"),
            ("swimming_pool.jpg", "image/jpeg"),
        )
    ):
        fullname = pkg_resources.resource_filename(package, "kansha/services/dummyassetsmanager/%s" % fname)
        with open(fullname, "r") as f:
            data = f.read()
        asset = gal.add_asset(FakeFile(data, fname, ftype))
        if i == 0:
            gal.make_cover(asset, 0, 0, 399, 250)

    log.info('Added image to card "%s" belonging to user "%s"' % (card1.get_title(), user1.username))

    session.commit()  # @UndefinedVariable
Ejemplo n.º 6
0
    def save(self, data, file_id=None, metadata={}, THUMB_SIZE=()):
        if file_id is None:
            file_id = unicode(uuid.uuid4())
        with open(self._get_filename(file_id), "w") as f:
            f.write(data)
        # Store metadata
        with open(self._get_metadata_filename(file_id), "w") as f:
            f.write(json.dumps(metadata))

        img = None
        try:
            img = Image.open(self._get_filename(file_id))
        except IOError:
            log.info('Not an image file, skipping medium & thumbnail generation')
        else:
            # Store thumbnail & medium
            kw = {}
            if 'transparency' in img.info:
                kw['transparency'] = img.info["transparency"]

            orig_width, orig_height = img.size

            medium_size = self.MEDIUM_WIDTH, int(float(self.MEDIUM_WIDTH) * orig_height / orig_width)
            medium = img.copy()

            medium.thumbnail(medium_size, Image.ANTIALIAS)
            medium.save(self._get_filename(file_id, 'medium'), img.format, quality=75, **kw)  # 'JPEG')

            thumb = ImageOps.fit(img, THUMB_SIZE if THUMB_SIZE else self.THUMB_SIZE, Image.ANTIALIAS)
            thumb.save(self._get_filename(file_id, 'thumb'), img.format, quality=75, **kw)  # 'JPEG')
        return file_id
Ejemplo n.º 7
0
    def remove_board_member(self, member):
        """Remove member from board

        Remove member from board. If member is PendingUser then remove
        invitation.

        Children must be loaded for propagation to the cards.

        In:
            - ``member`` -- Board Member instance to remove
        """
        if self.last_manager(member):
            # Can't remove last manager
            raise exceptions.KanshaException(_("Can't remove last manager"))

        log.info('Removing member %s' % (member, ))
        remove_method = {
            'pending': self.remove_pending,
            'manager': self.remove_manager,
            'member': self.remove_member
        }
        remove_method[member.role](member)

        # remove member from columns
        # FIXME: this function should live in a board extension that has its own data and
        # should not rely on a full component tree.
        if not self.columns:
            self.load_children()
        for c in self.columns:
            c().remove_board_member(member)
Ejemplo n.º 8
0
    def goto(self, title):
        page = PageData.get_by(pagename=title)
        if page is None:
            log.info('New wiki page: [%s]' % title)
            PageData(pagename=title, data=u'')

        self.content.becomes(Page(title))
Ejemplo n.º 9
0
def main():
    global apps
    app = apps[APP_NAME]  # @UndefinedVariable

    user1 = user.User('user1')
    local.request.user = user1
    assets_manager = app._services['assets_manager']
    card1 = card.Card(user1.data.boards[0].columns[1].cards[2].id, None,
                      assets_manager)
    gal = gallery.Gallery(card1, assets_manager)

    package = pkg_resources.Requirement.parse('kansha')
    for i, (fname, ftype) in enumerate((
        ('tie.jpg', 'image/jpeg'),
        ('baseball_game.jpg', 'image/jpeg'),
        ('LICENSE.txt', 'text/plain'),
        ('swimming_pool.jpg', 'image/jpeg'),
    )):
        fullname = pkg_resources.resource_filename(
            package, 'kansha/services/dummyassetsmanager/%s' % fname)
        with open(fullname, 'r') as f:
            data = f.read()
        asset = gal.add_asset(FakeFile(data, fname, ftype))
        if i == 0:
            gal.make_cover(asset, 0, 0, 399, 250)

    log.info('Added image to card "%s" belonging to user "%s"' %
             (card1.get_title(), user1.username))

    session.commit()  # @UndefinedVariable
Ejemplo n.º 10
0
    def goto(self, title):
        page = PageData.get_by(pagename=title)
        if page is None:
            log.info('New wiki page: [%s]' % title)
            PageData(pagename=title, data=u'')

        self.content.becomes(Page(title))
Ejemplo n.º 11
0
def populate():
    """Populate database
    """
    usermanager.UserManager().populate()

    app_path = 'kansha'
    nagare_admin = os.path.join(os.path.dirname(sys.executable), 'nagare-admin')
    batch_file = os.path.join(app_path, 'batch', 'populate_demo_images.py')
    log.info('Run ``%s batch %s %s`` if you want to create demo images.' % (nagare_admin, app_path, batch_file))
Ejemplo n.º 12
0
def populate():
    """Populate database
    """
    usermanager.UserManager().populate()

    app_path = 'kansha'
    nagare_admin = os.path.join(os.path.dirname(sys.executable),
                                'nagare-admin')
    batch_file = os.path.join(app_path, 'batch', 'populate_demo_images.py')
    log.info('Run ``%s batch %s %s`` if you want to create demo images.' %
             (nagare_admin, app_path, batch_file))
Ejemplo n.º 13
0
    def send(self,
             subject,
             to,
             content,
             html_content=None,
             from_='',
             cc=[],
             bcc=[],
             type='plain',
             mpart_type='alternative'):
        """Sends an email

        In:
         - ``subject`` -- email subject
         - ``to`` -- list of recipients' emails
         - ``content`` --  email content
         - ``from_`` -- email sender adress
         - ``cc`` --  list of CC emails
         - ``bcc`` -- list of BCC emails
         - ``type`` --  email type ('plain' or 'html')
         - ``mpart_type`` -- email part type

        """
        from_ = from_ if from_ else self.default_sender
        # create the message envelop
        msg = MIMEMultipart(mpart_type)
        msg['Subject'] = subject
        msg['Date'] = formatdate(localtime=True)
        msg['From'] = from_
        msg['To'] = COMMASPACE.join(to)

        if cc:
            msg['Cc'] = COMMASPACE.join(cc)

        # attach the mail content
        charset = 'us-ascii'
        if isinstance(content, unicode):
            content = content.encode('UTF-8')
            charset = 'UTF-8'
        msg.attach(MIMEText(content, type, charset))
        if html_content:
            msg.attach(MIMEText(html_content, 'html', charset))

        # log
        log.info(
            '%s mail:\n  subject=%s\n  from=%s\n  to=%s\n  cc=%s\n  bcc=%s',
            'sending' if self.activated else 'ignoring', subject, from_, to,
            cc, bcc)
        log.debug('Mail content:\n' + content)

        # post the email to the SMTP server
        if self.activated:
            self._smtp_send(from_, to + cc + bcc, msg.as_string())
Ejemplo n.º 14
0
    def change_role(self, member, new_role):
        """Change member's role

        In:
            - ``member`` -- Board member instance
            - ``new_role`` -- new role
        """
        log.info('Changing role of %s to %s' % (member, new_role))
        if self.last_manager(member):
            raise exceptions.KanshaException(_("Can't remove last manager"))

        self.data.change_role(member, new_role)
        self.update_members()
Ejemplo n.º 15
0
    def change_role(self, member, new_role):
        """Change member's role

        In:
            - ``member`` -- Board member instance
            - ``new_role`` -- new role
        """
        log.info('Changing role of %s to %s' % (member, new_role))
        if self.last_manager(member):
            raise exceptions.KanshaException(_("Can't remove last manager"))

        self.data.change_role(member, new_role)
        self.update_members()
Ejemplo n.º 16
0
    def edit(self, comp):
        content = comp.call(PageEditor(self))

        if content is not None:
            log.info('New content for page [%s]: [%s...]' % (self.title, content[:50]))
            security.check_permissions('wiki.editor', self)
            page = PageData.get_by(pagename=self.title)
            page.data = content

            # If the creator of the page is not already set, set it with the
            # current user
            if page.creator is None:
                page.creator = security.get_user().id
                log.debug('New creator for page [%s]: [%s]' % (page.pagename, page.creator))
Ejemplo n.º 17
0
    def edit(self, comp):
        content = comp.call(PageEditor(self))

        if content is not None:
            log.info('New content for page [%s]: [%s...]' % (self.title, content[:50]))
            security.check_permissions('wiki.editor', self)
            page = PageData.get_by(pagename=self.title)
            page.data = content

            # If the creator of the page is not already set, set it with the
            # current user
            if page.creator is None:
                page.creator = security.get_user().id
                log.debug('New creator for page [%s]: [%s]' % (page.pagename, page.creator))
Ejemplo n.º 18
0
Archivo: mail.py Proyecto: bcroq/kansha
    def send(self, subject, to, content, html_content=None, from_='', cc=[], bcc=[],
             type='plain', mpart_type='alternative'):
        """Sends an email

        In:
         - ``subject`` -- email subject
         - ``to`` -- list of recipients' emails
         - ``content`` --  email content
         - ``from_`` -- email sender adress
         - ``cc`` --  list of CC emails
         - ``bcc`` -- list of BCC emails
         - ``type`` --  email type ('plain' or 'html')
         - ``mpart_type`` -- email part type

        """
        from_ = from_ if from_ else self.default_sender
        # create the message envelop
        msg = MIMEMultipart(mpart_type)
        msg['Subject'] = subject
        msg['Date'] = formatdate(localtime=True)
        msg['From'] = from_
        msg['To'] = COMMASPACE.join(to)

        if cc:
            msg['Cc'] = COMMASPACE.join(cc)

        # attach the mail content
        charset = 'us-ascii'
        if isinstance(content, unicode):
            content = content.encode('UTF-8')
            charset = 'UTF-8'
        msg.attach(MIMEText(content, type, charset))
        if html_content:
            msg.attach(MIMEText(html_content, 'html', charset))

        # log
        log.info('%s mail:\n  subject=%s\n  from=%s\n  to=%s\n  cc=%s\n  bcc=%s',
                 'sending' if self.activated else 'ignoring', subject, from_, to, cc, bcc)
        log.debug('Mail content:\n' + content)

        # post the email to the SMTP server
        if self.activated:
            self._smtp_send(from_, to + cc + bcc, msg.as_string())
Ejemplo n.º 19
0
    def remove_board_member(self, member):
        """Remove member from board

        Remove member from board. If member is PendingUser then remove
        invitation.

        In:
            - ``member`` -- Board Member instance to remove
        """
        if self.last_manager(member):
            # Can't remove last manager
            raise exceptions.KanshaException(_("Can't remove last manager"))

        log.info("Removing member %s" % (member,))
        remove_method = {"pending": self.remove_pending, "manager": self.remove_manager, "member": self.remove_member}
        remove_method[member.role](member)

        # remove member from columns
        for c in self.columns:
            c().remove_board_member(member)
Ejemplo n.º 20
0
    def check_password(self, uid, password):
        """Check if the specified couple user/password is correct

        In:
           - ``uid`` -- the user id
           - ``password`` -- the user password
        Return:
            - True if password is checked
        """
        c = self.connect()
        # Try to authenticate
        try:
            c.simple_bind_s(uid, password)
            return True
        except ldap.INVALID_CREDENTIALS:
            log.info("Bad credentials for uid %r" % uid)
        except ldap.SERVER_DOWN:
            log.critical("LDAP server down")
        finally:
            c.unbind()
Ejemplo n.º 21
0
    def check_password(self, uid, password):
        """Check if the specified couple user/password is correct

        In:
           - ``uid`` -- the user id
           - ``password`` -- the user password
        Return:
            - True if password is checked
        """
        c = self.connect()
        # Try to authenticate
        try:
            c.simple_bind_s(uid, password)
            return True
        except ldap.INVALID_CREDENTIALS:
            log.info("Bad credentials for uid %r" % uid)
        except ldap.SERVER_DOWN:
            log.critical("LDAP server down")
        finally:
            c.unbind()
Ejemplo n.º 22
0
    def remove_board_member(self, member):
        """Remove member from board

        Remove member from board. If member is PendingUser then remove
        invitation.

        Children must be loaded for propagation to the cards.

        In:
            - ``member`` -- Board Member instance to remove
        """
        if self.last_manager(member):
            # Can't remove last manager
            raise exceptions.KanshaException(_("Can't remove last manager"))

        log.info('Removing member %s' % (member, ))
        remove_method = {
            'pending': self.remove_pending,
            'manager': self.remove_manager,
            'member': self.remove_member
        }
        remove_method[member.role](member)
Ejemplo n.º 23
0
    def remove_board_member(self, member):
        """Remove member from board

        Remove member from board. If member is PendingUser then remove
        invitation.

        In:
            - ``member`` -- Board Member instance to remove
        """
        if self.last_manager(member):
            # Can't remove last manager
            raise exceptions.KanshaException(_("Can't remove last manager"))

        log.info('Removing member %s' % (member,))
        remove_method = {'pending': self.remove_pending,
                         'manager': self.remove_manager,
                         'member': self.remove_member}
        remove_method[member.role](member)

        # remove member from columns
        for c in self.columns:
            c().remove_board_member(member)
Ejemplo n.º 24
0
def main():

    before_date = datetime.now() - UserConfirmationTimeout
    log.info('Clearing users that did not confirm their'
             ' email since %s...' % before_date)

    unconfirmed_users = list(
        usermanager.UserManager.get_unconfirmed_users(before_date))

    if not unconfirmed_users:
        log.info("No user found")
    else:
        for user in unconfirmed_users:
            for vote in user.votes:
                vote.delete()
            user.delete()
            log.info('- %s (%s) removed' % (user.fullname, user.username))

    session.commit()  # @UndefinedVariable
Ejemplo n.º 25
0
 def delete(self, uid):
     if self.with_delete:
         log.info('User %r deleted by %r', uid, security.get_user().uid)
         UserRepository().delete(uid)
Ejemplo n.º 26
0
 def delete(self, uid):
     if self.with_delete:
         log.info('User %r deleted by %r', uid, security.get_user().uid)
         UserRepository().delete(uid)
Ejemplo n.º 27
0
 def handle_event(self, event):
     if event.is_(events.BoardLeft) or event.is_(events.BoardArchived):
         return self.select_last_board()
     elif event.is_(events.NewTemplateRequested):
         return self.boards_manager.create_template_from_board(event.emitter, *event.data)
     log.info('Ignoring event %s', event)
Ejemplo n.º 28
0
 def refresh(self):
     log.info('sync')
     self._data = None
     self.load_children()