Util Init
import urllib
from google.appengine.api import users
from db import Pagedb, Userdb
from page import findPage
 
def loginout_url(dest_url):    
    '''
    取得登入或登出的連結
    若已登入,則得到登出連結
    若未登入,則得到登入連結
    '''
    if users.get_current_user():
        return logout_url(dest_url)
    else:
        return login_url(dest_url)
 
def login_url(dest_url):
    '''取得登入的連結'''
    return {'loginout_url':users.create_login_url(dest_url),'loginout_label':"登入"}
 
def logout_url(dest_url):
    '''取得登出的連結'''
    return {'loginout_url':users.create_logout_url(dest_url),'loginout_label':"登出"}
 
def newestlist(count = 100, include_system_page = False):
    list = Pagedb.gql('where isnew = :1 ORDER BY date DESC',True).fetch(count)
    if not include_system_page:    
        if len(list) < count:
            count = 0
        while True:
            lost_count = 0
            #raise Exception, list
            for page in list:
                if page.pagetitle == 'mylist':
                    list.remove(page)
                    lost_count += 1
            #if len(list) >= count:
            #    break
            break
            #list.extend(Pagedb.gql('where isnew = :1 and date < :2 ORDER BY date DESC', True, list[-1].date).fetch(lost_count))
 
    return list
 
def checkHasInit(user = None):
    '''
    檢查此使用者是否初始化.
    若不投入參數則檢察現在登入的使用者.
    '''
    if not user:
        user = users.get_current_user()
        if not user:
            raise ValueError, 'user not login.'
    if isinstance(user, users.User):
        user = user.nickname()
    elif not isinstance(user, basestring):
        raise TypeError, 'argument must be str or users.User object'
    return not not Userdb.get_by_key_name(user)
 
def findUsedUser(user):
    ''' 尋找使用者 '''
    if isinstance(user, users.User):
        db = Userdb.gql("where user = :1",user).get()
    elif isinstance(user, basestring):
        db = Userdb.get_by_key_name(user)
    else:
        raise TypeError, 'user type error'
    if db:
        return db.user
 
def find_css(user):
    if isinstance(user, users.User):
        return Userdb.get_by_key_name(user.nickname()).get_css()
    else:
        return Userdb.get_by_key_name(user).get_css()
 
def quote(url):
        return urllib.quote(url.encode('utf-8'))
 
def unquote(url):
        return urllib.unquote(url).decode('utf-8')