Use full-caps name for user link URLs.
[zzz-spline-users.git] / spline / plugins / users / model / __init__.py
1 import colorsys
2 import random
3
4 from sqlalchemy import Column, ForeignKey
5 from sqlalchemy.orm import relation
6 from sqlalchemy.types import Integer, Unicode
7
8 from spline.model.meta import TableBase
9
10 class User(TableBase):
11 __tablename__ = 'users'
12 id = Column(Integer, primary_key=True)
13 name = Column(Unicode(length=20), nullable=False)
14 unique_identifier = Column(Unicode(length=32), nullable=False)
15
16 def __init__(self, *args, **kwargs):
17 # Generate a unique hash if one isn't provided (which it shouldn't be)
18 if 'unique_identifier' not in kwargs:
19 ident = u''.join(random.choice(u'0123456789abcdef')
20 for _ in range(32))
21 kwargs['unique_identifier'] = ident
22
23 super(User, self).__init__(*args, **kwargs)
24
25 @property
26 def unique_colors(self):
27 """Returns a list of (width, '#rrggbb') tuples that semi-uniquely
28 identify this user.
29 """
30
31 width_blob, colors_blob = self.unique_identifier[0:8], \
32 self.unique_identifier[8:32]
33
34 widths = []
35 for i in range(4):
36 width_hex = width_blob[i*2:i*2+2]
37 widths.append(int(width_hex, 16))
38 total_width = sum(widths)
39
40 ret = []
41 for i in range(4):
42 h = int(colors_blob[i*6:i*6+2], 16) / 256.0
43 l = int(colors_blob[i*6+2:i*6+4], 16) / 256.0
44 s = int(colors_blob[i*6+4:i*6+6], 16) / 256.0
45
46 # Cap lightness to 0.25 to 0.75, so it's not too close to white or
47 # black
48 l = l * 0.5 + 0.25
49
50 # Cap saturation to 0.5 to 1.0, so the color isn't too gray
51 s = s * 0.5 + 0.5
52
53 r, g, b = colorsys.hls_to_rgb(h, l, s)
54 color = "#{0:02x}{1:02x}{2:02x}".format(
55 int(r * 256),
56 int(g * 256),
57 int(b * 256),
58 )
59
60 ret.append((1.0 * widths[i] / total_width, color))
61
62 return ret
63
64
65 class OpenID(TableBase):
66 __tablename__ = 'openid'
67 openid = Column(Unicode(length=255), primary_key=True)
68 user_id = Column(Integer, ForeignKey('users.id'))
69 user = relation(User, lazy=False, backref='openids')
70