예제 #1
0
class PostAdmin(sqla.ModelView):
    # Visible columns in the list view
    column_exclude_list = ['text']

    # List of columns that can be sorted. For 'user' column, use User.username as
    # a column.
    column_sortable_list = ('title', ('user', User.username), 'date')

    # Rename 'title' columns to 'Post Title' in list view
    column_labels = dict(title='Post Title')

    column_searchable_list = ('title', User.username)

    column_filters = ('user', 'title', 'date',
                      filters.FilterLike(Post.title,
                                         'Fixed Title',
                                         options=(('test1', 'Test 1'),
                                                  ('test2', 'Test 2'))))

    # Pass arguments to WTForms. In this case, change label for text field to
    # be 'Big Text' and add required() validator.
    form_args = dict(
        text=dict(label='Big Text', validators=[validators.required()]))

    form_ajax_refs = {
        'user': (User.username, User.email),
        'tags': (Tag.name, )
    }

    def __init__(self, session):
        # Just call parent class with predefined model.
        super(PostAdmin, self).__init__(Post, session)
예제 #2
0
class PostAdmin(sqla.ModelView):

    def is_accessible(self):
        is_accessible = login.current_user and login.current_user.is_authenticated()
        self._create_form_class = self.get_create_form(is_accessible)
        self._edit_form_class = self.get_edit_form(is_accessible)
        return is_accessible;

    list_template = 'post_list.html'

    column_exclude_list = ['text']
    column_sortable_list = ('title', 'author', 'publish', 'date', 'promoted', ('priority', Post.priority))
    column_labels = dict(title='Post Title', link='URL')

    column_searchable_list = ('title', Type.name)

    column_filters = ('author',
                      'title',
                      'date',
                      filters.FilterLike(Post.title, 'Fixed Title', options=(('test1', 'Test 1'), ('test2', 'Test 2'))))

    form_args = dict(
                    text=dict(label='Big Text', validators=[validators.required()]),
                    url=dict(label='URL')
                )

    @expose('/lastnewsletter/', methods=('GET', 'POST'))
    def last_newsletter(self):
        newsletter = self.session.query(Newsletter).order_by(Newsletter.date.desc()).first()
        date = str(newsletter.date) if newsletter != None else ''
        return date

    def get_edit_form(self, is_accessible = None):
        form = self.scaffold_form()
        form.priority = SelectField(u'Priority', coerce = int, choices = [(i, i) for i in range(0, 11) ])
        if not is_accessible:
            delattr(form, 'date')
            delattr(form, 'publish')
            delattr(form, 'promoted')
            delattr(form, 'priority')

        return form

    def get_create_form(self, is_accessible = None):
        form = self.scaffold_form()
        form.priority = SelectField(u'Priority', coerce = int, choices = [(i, i) for i in range(0, 11) ])
        if not is_accessible:
            delattr(form, 'date')
            delattr(form, 'publish')
            delattr(form, 'promoted')
            delattr(form, 'priority')
        return form

    def __init__(self, session):
        super(PostAdmin, self).__init__(Post, session)
예제 #3
0
class UserDetailAdmin(sqla.ModelView):
    column_sortable_list = ('name', 'uid', 'date', 'website')
    column_labels = dict(title='Comment Title')
    column_searchable_list = ('website', UserDetail.website)
    column_filters = ('uid', 'website', 'date', 'name',
                      filters.FilterLike(UserDetail.website,
                                         'Fixed Title',
                                         options=(('test1', 'Test 1'),
                                                  ('test2', 'Test 2'))))
    form_args = dict(text=dict(label='Big Text', validators=[]))

    def __init__(self, session):
        super(UserDetailAdmin, self).__init__(UserDetail, session)

    def is_accessible(self):
        if current_user.get_role() == '0':
            return current_user.is_authenticated()
예제 #4
0
class EmailPreview(sqla.ModelView):
    def get_query(self):
        today = datetime.date.today()
        # chamge this if you want weekly.. 
        last_month = today - relativedelta(months=1)
        query = self.session.query(Post)
        query = query.join(Type, Type.id == Post.type_id)
        return query.filter(and_(Post.publish, Post.date <= today, Post.date >= last_month)).order_by(Type.priority.desc()).order_by(Post.priority.desc()).order_by(Post.date.asc())

    def get_count_query(self):
        today = datetime.date.today()
        last_month = today - relativedelta(months=1)
        return self.session.query(func.count('*')).filter(and_(Post.publish, Post.date <= today, Post.date >= last_month))

    def is_accessible(self):
        return login.current_user.is_authenticated()

    list_template = 'email_preview_list.html'

    can_create = False
    can_edit = False
    can_delete = False
    list_row_actions_header = None
    column_descriptions = None
    page_size = -1

    column_exclude_list = ['text', 'publish', 'edit', 'promoted', 'priority']
    column_sortable_list = ('type', 'title', 'author', 'date')
    column_labels = dict(title='Post Title')
    column_searchable_list = ('title', Type.name)

    column_filters = ('author',
                      'title',
                      'date',
                      filters.FilterLike(Post.title, 'Fixed Title', options=(('test1', 'Test 1'), ('test2', 'Test 2'))))

    form_args = dict(
                    text=dict(label='Big Text', validators=[validators.required()])
                )

    @expose('/preview/', methods=('GET', 'POST'))
    def email_preview_action(self):
        title = request.form['title']
        spoiler = request.form['spoiler']
        preamble = request.form['preamble']
        ids = [int(i) for i in request.form.getlist('rowid')]

        models = Post.query.filter(Post.id.in_(ids)).join(Post.type).order_by(Type.priority.desc()).order_by(Post.priority.desc()).order_by(Post.date.asc()).all()

        groups = defaultdict(list)
        priorityList = []
        for obj in models:
            # to remove the p tags. not probably the best way.. 
			obj.text = markdown.markdown(obj.text)[3:-4]
			if obj.author is None:
				obj.author = ''
			if obj.link is None:
				obj.link = ''
				obj.link_name = ''
			else:
				obj.link_name = urlparse(obj.link).netloc
			author = obj.author
			if author.startswith('@'):
				m = re.compile('@([A-Za-z]+[A-Za-z0-9]+)')
				obj.author = m.sub('<a href="http://twitter.com/\g<1>">@\g<1></a>',author)
			elif re.match(EMAIL_REGEX, author):
				obj.author = '<a href="mailto:%s">%s</a>' % (author,author)
			groups[obj.type.name].append( obj )
			if obj.type.name not in priorityList:
				priorityList.append(obj.type.name)

        posts_map = []
        for key in priorityList:
            entry = {}
            entry['type'] = key
            entry['posts'] = groups[key]
            posts_map.append(entry)


        campaign_name = app.config['MAILCHIMP_CAMPAIGN_NAME']
        backup_campaign_name = app.config['MAILCHIMP_BACKUP_CAMPAIGN_NAME']
        mailchimp_client = get_mailchimp_api()

        campaign = mailchimp_client.campaigns.list({ 'title' : campaign_name, 'exact' : True })
        backup_campaign = mailchimp_client.campaigns.list({ 'title' : backup_campaign_name, 'exact' : True })

        if backup_campaign['data']:
            backup_cid = backup_campaign['data'][0]['id']
            mailchimp_client.campaigns.delete(backup_cid)

        cid = campaign['data'][0]['id']
        backup_campaign = mailchimp_client.campaigns.replicate(cid)
        mailchimp_client.campaigns.update(backup_campaign['id'], 'options', {'title' : backup_campaign_name})

        html = mailchimp_client.campaigns.content(backup_campaign['id'])['html']

        template = Template(html)
        html = template.render(preamble  = markdown.markdown(preamble), title = title, spoiler = spoiler,
            posts_map = posts_map)

        mailchimp_client.campaigns.update(backup_campaign['id'], 'content', {'html' : html})

        return self.render('email_preview_action.html', template_content = html, title = title,
            spoiler = spoiler, preamble = preamble, cid = backup_campaign['id'], ids = ids)


    @expose('/send/', methods = ['GET', 'POST'])
    def email_send_action(self):
        title = request.form['title']
        spoiler = request.form['spoiler']
        preamble = request.form['preamble']
        content = request.form['content']
        cid = request.form['cid']
        ids = [int(i) for i in request.form['ids'].encode('utf').replace("[","").replace("]","").split(",")]

        mailchimp_client = get_mailchimp_api()
        campaign_name = '[' + app.config['MAILCHIMP_CAMPAIGN_NAME'] + '] - ' + title
        mailchimp_client.campaigns.update(cid, 'options', {'title' : campaign_name, 'subject' : campaign_name})
        mailchimp_client.campaigns.send(cid)

        posts = self.session.query(Post).filter(Post.id.in_(ids)).all()
        
        for post in posts:
            t = threading.Thread(target=addPostToDelicious, args=(post.link, post.title, post.text,post.author,post.type.name))
            t.setDaemon(True)
            t.start()
            post.publish = False

        newsletter = Newsletter()
        newsletter.title = title
        newsletter.date = datetime.datetime.now()
        newsletter.preamble = preamble.replace('<br>','')
        newsletter.spoiler = spoiler

        newsletter.html = content

        self.session.add(newsletter)
        self.session.commit()

        return "completed"

    @expose('/cancel/', methods = ['GET', 'POST'])
    def email_cancel_action(self):
        cid = request.form['cid']

        mailchimp_client = get_mailchimp_api()
        mailchimp_client.campaigns.delete(cid)

        return redirect(url_for('.index_view'))