Mypage
from . import BaseHTML
from google.appengine.ext import webapp
from google.appengine.api import users
import py.util as siteutil
from db import Userdb
 
class Mypage(webapp.RequestHandler):
    '''
    view format: /{{username}}/user
    edit format: /mypage
    '''
    html = BaseHTML('mypage.html')
 
    def get(self,username = None):
        u = users.get_current_user()
        self.html.content.update({
                'nowuser' : u,
                'ismylist' : True,
                'login' : u,
                'username' : u.nickname()
 
            })
        if username:
            if not self.viewpage(username):
                return
        else:
            self.editpage()
        self.html.render(self)
 
    def post(self):
        userdb = Userdb.get_by_key_name(users.get_current_user().nickname())
        userdb.css_filename = self.request.POST['newfile'].filename
        userdb.css = self.request.POST['newfile'].value.decode('UTF-8')
        userdb.using_way = 'file'
        userdb.put()
        self.get()
 
    def viewpage(self, username):
        '''檢查是否為正確使用者名稱'''
        user = siteutil.findUsedUser(username)
        if not user:
            self.response.set_status(404,"can't find content.maybe is wrong name.")
            return False
        self.html.content.update(siteutil.loginout_url(self.request.uri))
        self.html.content['user'] = user
        return True
 
    def editpage(self):
        '''提供編輯的設定'''
        self.html.content.update(siteutil.logout_url('/'))
        self.html.content['user'] = users.get_current_user()
        userdb = Userdb.get_by_key_name(users.get_current_user().nickname())
        if userdb:
            self.html.content.update({
                'css_filename' : userdb.css_filename,
                'css_url' :  userdb.cssurl,
                'css_way' : userdb.using_way
                })
        if self.request.get('upload'):
            self.html.content['uploaded'] = True
 
class CssCache(webapp.RequestHandler):
    '''
        (r'/usercss/(.+)\.css' @import
        (r'/usercss/(.+)/(main)\.css' main css
    '''
    def get(self, username):
        self.response.headers['Content-Type'] = 'text/css'
        self.response.headers['X-Content-Type-Options'] = 'nosniff'
        self.response.headers['Cache-Control'] = 'public, max-age=600'
        self.response.out.write(Userdb.get_by_key_name(username).css)