def all(cls):
   instances = []
   for record in dbview.users(db).rows:
     instance = User(record)
     cls.IDCache[instance.id] = cls.SlugCache[instance.slug] = instance
     instances.append(instance)
   return instances  
  def POST(self):
    you = require_you()
    params = web.input(name='')

    unique = True
    name = params['name']
    if name and name != you.get('name',None):
      from helper import slugify
      slug = slugify(name)
      for row in dbview.users(db, startkey=slug, endkey=slug):
        if slug == row.key:
          unique = False
          break
    
      if unique:
        you['name'] = name
        you['slug'] = slug
    elif not name and 'name' in you:
      # blanking your name makes you anonymous, and makes your page inaccessible
      del you['name']
      del you['slug']

    db[you.id] = you

    if unique:
      web.redirect('/')
    else:
      return render('settings', errors="Sorry, that name's taken!", you=you)
  def get(cls, slug=None, id=None):
    if id:
      if not id in db:
        raise web.notfound()
      record = db[id]
      if record['type'] != "user":
        raise web.notfound()
    if slug:
      records = dbview.users(db, startkey=slug, endkey=slug).rows
      if not len(records):
        raise web.notfound()
      record = records[0]

    instance = User(record)
    cls.SlugCache[instance.slug] = cls.IDCache[instance.id] = instance
    return instance
  def POST(self):
    you = require_you()
    params = web.input()

    if not params["user"]:
      return web.notfound()
    
    user = dbview.users(db, startkey=params['user'], endkey=params['user']).rows
    if not len(user):
      return web.notfound()
    else:
      user = user[0]
    
    from setup_board import board
    game = {"type":"game", "board":board, "timestamp":make_timestamp(), "turn":0, 
            "players":{"red":you.id,"blue":user.id}, "order":["red","blue"]}
    game_id = db.create(game)
    web.seeother("/games/%s" % game_id)
def get_you():
  openid = web.openid.status()
  if openid:
    key = "user-%s" % openid
    if key in db:
      return db[key]
    else:
      from random_name import random_name
      from time import time
      while True:
        unique = True
        name = random_name("%s-%d" % (openid,time()))
        slug = slugify(name)
        for row in dbview.users(db, startkey=slug, endkey=slug):
          if slug == row.key:
            unique = False
            break
    
        if unique:
          break
      
      you = {'type':'user', 'openids':[openid], "name":name, "slug":slug}
      db[key] = you
      return you