Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: b27c91d26f
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 264 lines (222 sloc) 8.857 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
import datetime
import logging
import os

from google.appengine.ext import deferred
from google.appengine.ext import webapp

import config
import markup
import models
import post_deploy
import utils
from generators import generator_list

# Bloggart is currently based on Django 0.96
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from google.appengine.dist import use_library
use_library('django', '0.96')
from django import newforms as forms
from google.appengine.ext.db import djangoforms


class PostForm(djangoforms.ModelForm):
  title = forms.CharField(widget=forms.TextInput( attrs={'id':'name'} ));
  body = forms.CharField(widget=forms.Textarea( attrs={'id':'message', 'rows': 10, 'cols': 20} ));
  body_markup = forms.ChoiceField( choices=[(k, v[0]) for k, v in markup.MARKUP_MAP.iteritems()] );
  tags = forms.CharField(widget=forms.Textarea(attrs={'rows': 5, 'cols': 20}));
  draft = forms.BooleanField(required=False);
  class Meta:
    model = models.BlogPost
    fields = [ 'title', 'body', 'tags' ]


class PageForm(djangoforms.ModelForm):
  # Overridden constructor to initialise the Form properly
  def __init__(self, current_page, *args, **kwargs):
    self.base_fields['parent_page'].query = models.Page.all();
    if ( current_page ):
      # Show all the pages, except the one associated with the current form instance
      self.base_fields['parent_page'].query.filter("__key__ != ", current_page.key());

    self.base_fields['parent_page'].widget.choices = self.base_fields['parent_page'].choices;
    super(PageForm, self).__init__(*args, **kwargs);

  title = forms.CharField( widget=forms.TextInput( attrs={'id':'name'} ));
  parent_page = djangoforms.ModelChoiceField( models.Page, None, required=False, initial=None, empty_label="none" );
  body = forms.CharField( widget=forms.Textarea( attrs={'id':'message', 'rows': 10, 'cols': 20} ));
  body_markup = forms.ChoiceField( choices=[(k, v[0]) for k, v in markup.MARKUP_MAP.iteritems()] );
  draft = forms.BooleanField( required=False );
  class Meta:
    model = models.Page
    fields = [ 'title', 'parent_page', 'body' ]


def with_post(fun):
  def decorate(self, post_id=None):
    post = None
    if post_id:
      post = models.BlogPost.get_by_id(int(post_id))
      if not post:
        self.error(404)
        return
    fun(self, post)
  return decorate


def with_page(fun):
  def decorate(self, page_id=None):
    page = None
    if page_id:
      page = models.Page.get_by_id(int(page_id));
      if not page:
        self.error(404);
        return
    fun(self, page)
  return decorate;


class BaseHandler(webapp.RequestHandler):
  def render_to_response(self, template_name, template_vals=None, theme=None):
    if not template_vals:
      template_vals = {}
    template_vals.update({
        'path': self.request.path,
        'handler_class': self.__class__.__name__,
        'is_admin': True,
    })
    template_name = os.path.join("admin", template_name)
    self.response.out.write(utils.render_template(template_name, template_vals,
                                                  theme))


class AdminHandler(BaseHandler):
  def get(self):
    # Entry per page
    entry_per_page = 10

    posts_offset = int(self.request.get('posts_start', 0));
    posts_count = int(self.request.get('posts_count', entry_per_page));
    posts = models.BlogPost.all().order('-published').fetch(posts_count, posts_offset);
    pages_offset = int(self.request.get('pages_start', 0));
    pages_count = int(self.request.get('pages_count', entry_per_page));
    pages = models.Page.all().order('-published').fetch(pages_count, pages_offset);
    template_vals = {
        'posts_offset': posts_offset,
        'posts_count': posts_count,
        'posts_last_post': posts_offset + len(posts) - 1,
        'posts_prev_offset': max(0, posts_offset - posts_count),
        'posts_next_offset': posts_offset + posts_count,
        'posts': posts,
        'pages_offset': pages_offset,
        'pages_count': pages_count,
        'pages_last_page': pages_offset + len(pages) - 1,
        'pages_prev_offset': max(0, pages_offset - pages_count),
        'pages_next_offset': pages_offset + pages_count,
        'pages': pages,
        'generators': [cls.__name__ for cls in generator_list],
    };
    self.render_to_response("index.html", template_vals);


class PostHandler(BaseHandler):
  def render_form(self, form):
    self.render_to_response("edit_post.html", {'form': form})

  @with_post
  def get(self, post):
    self.render_form(PostForm(
        instance=post,
        initial={
          'draft': post and not post.path,
          'body_markup': post and post.body_markup or config.default_markup,
        }))

  @with_post
  def post(self, post):
    form = PostForm(data=self.request.POST, instance=post,
                    initial={'draft': post and post.published is None})
    if form.is_valid():
      post = form.save(commit=False)
      if form.clean_data['draft']:
        # Post is marked as DRAFT
        post.published = datetime.datetime.max
        post.put()
      else:
        # Post is NOT marked as DRAFT - hence, PUBLISH
        if not post.path:
          # Just published
          post.updated = post.published = datetime.datetime.now(utils.tzinfo())
        else:
          # Edited
          post.updated = datetime.datetime.now(utils.tzinfo())

        post.put()
        post.publish()

      self.render_to_response("published.html", {
          'content': post,
          'type' : 'post',
          'draft': form.clean_data['draft']})
    else:
      self.render_form(form)

class DeletePostHandler(BaseHandler):
  @with_post
  def post(self, post):
    # TODO
    if post.path: # Published post
      post.remove();
    else: # Draft
      post.delete();
    self.render_to_response("deleted.html", {'type' : 'post'});


class PreviewPostHandler(BaseHandler):
  @with_post
  def get(self, post):
    # Temporary set a published date iff it's still
    # datetime.max. Django's date filter has a problem with
    # datetime.max and a "real" date looks better.
    if post.published == datetime.datetime.max:
      post.published = datetime.datetime.now(utils.tzinfo());
    self.response.out.write(utils.render_template('post.html', {'post' : post, 'is_admin' : True}));


class PageHandler(BaseHandler):
  def render_form(self, form):
    self.render_to_response("edit_page.html", {'form': form})

  @with_page
  def get(self, page):
    self.render_form(PageForm(instance=page,
      current_page=page,
      initial={
        'draft': page and not page.path,
        'body_markup': page and page.body_markup or config.default_markup
      }));

  @with_page
  def post(self, page):
    form = PageForm(current_page=page, data=self.request.POST, instance=page, initial={'draft': page and page.published is None});
    if form.is_valid():
      page = form.save(commit=False);

      # Ensure that a 'Child Page' is never assigned as 'Parent Page' as well
      page.put();
      for p in page.child_pages:
        if page.parent_page and page.parent_page.key() == p.key():
          page.parent_page = None;
          page.put();
          break;

      if form.clean_data['draft']:
        # Page is marked as DRAFT
        page.published = datetime.datetime.max
        page.put();
      else:
        # Page is NOT marked as DRAFT - hence, PUBLISH
        if not page.path:
          # Just published
          page.updated = page.published = datetime.datetime.now(utils.tzinfo())
        else:
          # Edited
          page.updated = datetime.datetime.now(utils.tzinfo())

        page.put()
        page.publish()
      self.render_to_response("published.html", {'content': page, 'type' : 'page', 'draft': form.clean_data['draft']});
    else:
      self.render_form(form);

class DeletePageHandler(BaseHandler):
  @with_page
  def post(self, page):
    if page.path: # Published page
      page.remove();
    else: # Draft
      page.delete();
    self.render_to_response("deleted.html", {'type' : 'page'});


class PreviewPageHandler(BaseHandler):
  @with_page
  def get(self, page):
    # Temporary set a published date iff it's still
    # datetime.max. Django's date filter has a problem with
    # datetime.max and a "real" date looks better.
    if page.published == datetime.datetime.max:
      page.published = datetime.datetime.now(utils.tzinfo());
    self.response.out.write(utils.render_template('page.html', {'page' : page, 'is_admin' : True}));


class RegenerateHandler(BaseHandler):
  def post(self):
    # Force the regeneration of all the content
    post_deploy.regenerate_all(force=True)

    # Post-Deploy tasks (i.e. regenerate static pages)
    deferred.defer(post_deploy.try_post_deploy, force=True);

    # Render a "regenerating" page
    self.render_to_response("regenerating.html")
Something went wrong with that request. Please try again.