Source

reddish / reddish / model / __init__.py

Full commit
   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
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
"""The application's model objects"""
import bson
import datetime
from pylons import app_globals as g, request
from pylons.controllers.util import abort
import logging
import random
import re

from . import exc
from .meta import Session
from ..lib import captcha, helpers as h, mongo
from ..lib.errors import ClientError

log = logging.getLogger(__name__)

class ModelBase(object):
    '''
    Base class for all model types, providing convenience functions on top of
    mongo.Document operations.

    MUST be inherited before mongo.Document in order to override methods.
    '''

    FALSE = { '$ne': True }
    NON_NULL = { '$ne': None }

    @classmethod
    def by(cls, **kws):
        return Session.find_one(cls, kws)

    @classmethod
    def by_id(cls, _id):
        return cls.by(_id = _id)

    @classmethod
    def by_name(cls, name):
        return cls.by(name_lc = name.lower())

    @classmethod
    def find(cls, **kws):
        return Session.find(cls, kws)

    @classmethod
    def get(cls, _id):
        return Session.get(cls, _id)

    def _commit(self):
        if self._session is None and self._parent is None:
            Session.add(self)
        super(ModelBase, self)._commit()

    def find_and_remove(self):
        Session.find_and_modify(type(self),
            { '_id': self._id }, remove = True)

class Renderable(object):
    '''
    Abstract type inherited by model types which can be serialized
    '''

    def render(self, user):
        '''
        Return a representation of the object as one or more instances of
        primitive types; e.g. (dict, list, str, unicode, int, or datetime)

        user:
            Logged-in User requesting the object, None if no user is logged in
        '''
        raise NotImplementedError

def init_model(engine, config):
    """Call me before using any of the tables or classes in the model"""
    cfg = mongo.parse_uri(config['mongodb.host'])
    Session.configure(engine, cfg['database'])

def post_sort(res, user = None, sort = 'latest'):
    # TODO: Hide posts from banned and inaccessible communities
    # in a way that isn't horrendously slow.

    if sort == 'top':
        res.sort([('total_value', -1), ('created', -1)])
    elif sort == 'new':
        res.sort('created', -1)
    else: # elif sort == 'latest':
        res.sort([('last_reply', -1), ('created', -1)])

    return res

def unique_id(name):
    return h.to36(int(Session['unique_id'].find_and_modify({ '_id': name },
        { '$inc': { 'value': 1 } }, upsert = True, new = True)['value']))

class Preferences(ModelBase, mongo.Document, Renderable):

    n_items = mongo.Field(int, default = 10)
    new_window = mongo.Field(bool)
    no_crawl = mongo.Field(bool)
    view_nsfw = mongo.Field(bool)

    @classmethod
    def default(cls):
        return cls()

    def render(self, user):
        return {
            'n_items': self.n_items,
            'new_window': self.new_window or False,
            'no_crawl': self.no_crawl or False,
            'view_nsfw': self.view_nsfw or False,
        }

class User(ModelBase, mongo.Document, Renderable):
    _collection = 'user'
    _id_factory = lambda o: unique_id('user')

    MAX_NAME_LENGTH = 32

    ## Uniquely identifying name
    name = mongo.Field(unicode, required = True)
    ## Name field in lower case, used for search operations
    name_lc = mongo.Field(unicode, required = True, unique = True)
    ## Hashed password
    password = mongo.Field(str, required = True)
    ## Email address used for password reset
    email_address = mongo.Field(unicode)
    ## Time of last request
    last_activity = mongo.Field(datetime.datetime, required = True)
    ## _id of the admin who banned this user
    banned = mongo.Field(str)
    ## Time of account creation
    created = mongo.Field(datetime.datetime, required = True)
    ## Subscribed communities
    subscribed = mongo.ListField(str)
    ## Communities moderated by this User
    moderated = mongo.ListField(str)
    ## Saved posts
    saved = mongo.ListField(str, hidden = True)
    ## Friended Users
    friends = mongo.ListField(str, hidden = True)
    ## Ignored Users
    ignored = mongo.ListField(str, hidden = True)
    ## Configured preferences
    prefs = mongo.Field(Preferences)

    def __init__(self, name, **kws):
        super(User, self).__init__(**kws)
        self.set_name(name)
        self.prefs = Preferences()
        self.created = self.last_activity = datetime.datetime.utcnow()

    @classmethod
    def by_name(cls, name):
        return cls.name_cache.get(name.lower())

    @classmethod
    def login(cls, name, password):
        try:
            user = cls.by_name(name)

            if user.check_password(password):
                return user
        except exc.NotFound:
            pass

        raise ClientError('Incorrect username/password')

    @property
    def admin(self):
        return self.name_lc in g.admins

    def ban(self, user):
        if self.admin:
            raise ClientError('Cannot ban another admin')
        try:
            Session.find_and_modify(User,
                { '_id': self._id, 'banned': None },
                { '$set': { 'banned': user._id } })
        except exc.NotFound:
            raise ClientError('User is already banned')

        AdminLog.log(user, 'ban', user = self._id)

    def unban(self, user):
        try:
            Session.find_and_modify(User,
                { '_id': self._id, 'banned': self.NON_NULL },
                { '$unset': { 'banned': 1 } })
        except exc.NotFound:
            raise ClientError('User is not banned')

        AdminLog.log(user, 'unban', user = self._id)

    def get_banned_by(self):
        if self.banned:
            return User.get(self.banned)

    def check_password(self, password):
        '''
        Checks the given plaintext password against the user's stored
        password hash. If the user record contains an outdated password and
        the given password is correct, the stored hash will be updated.
        '''
        if self.password.startswith('vb:'):
            if h.vb_hash(password, self.password) == self.password:
                try:
                    Session.find_and_modify(User,
                        { '_id': self._id, 'password': self.password },
                        { '$set': { 'password': h.hash_password(password) } },
                        fields = { 'password': 1 })
                except exc.NotFound:
                    return False
                return True
            return False

        return h.hash_password(password, self.password) == self.password

    def add_friend(self, user):
        if self is user:
            raise ClientError('You cannot friend yourself')
        Session.modify(self, { '$addToSet': { 'friends': user._id } },
            fields = { 'friends': 1 })

    def get_friends(self):
        return User.find(_id = { '$in': self.friends }).sort('name_lc')

    def has_friend(self, user):
        if not hasattr(self, '_friends'):
            self._friends = frozenset(self.friends)

        return user._id in self._friends

    def remove_friend(self, user):
        Session.modify(self, { '$pull': { 'friends': user._id } },
            fields = { 'friends': 1 })

    def ignore(self, user):
        if self is user:
            raise ClientError('You cannot ignore yourself')

        Session.update_one(self, { '$addToSet': { 'ignored': user._id } })

    def get_ignored(self):
        return User.find(_id = { '$in': self.ignored }).sort('name_lc')

    def has_ignored(self, user):
        if not hasattr(self, '_ignored'):
            self._ignored = frozenset(self.ignored)
        return user._id in self._ignored

    def unignore(self, user):
        Session.update_one(self, { '$pull': { 'ignored': user._id } })

    def can_message(self, user):
        '''
        Return whether the given user may message this user
        '''
        return user.admin or not (user.banned or self.has_ignored(user))

    def add_message(self, sender, message):
        '''
        Commit the given message and address it to this User
        '''
        message.owner = self._id
        if message.delivered is None:
            message.delivered = datetime.datetime.utcnow()
        if not sender or self.can_message(sender):
            message._commit()

    def send_message(self, recipient, message):
        '''
        Send the given message to the given recipient and address it from
        this User, returning a Message as confirmation
        '''
        message.other = self._id
        recipient.add_message(self, message)

        if self is not recipient:
            sent = SentMessage.from_message(message)
            self.add_message(None, sent)
            return sent

        return message

    def get_contributor(self):
        return Community.find(contributors = self._id,
            banned = None).sort('num_subscribers', -1)

    def get_comments(self, user = None):
        return post_sort(Comment.find(author = self._id,
            deleted = None), user, 'new')

    def get_posts(self, user = None):
        return post_sort(Post.find(author = self._id,
            deleted = None, removed = None), user, 'new')

    def get_messages(self, **kws):
        return Message.find(owner = self._id, **kws).sort('delivered', -1)

    def get_moderator_messages(self, **kws):
        if not self.moderated:
            return Message.find(_id = None)
        return Message.find(owner_mod = { '$in': self.moderated }, **kws) \
            .sort('delivered', -1)

    def get_sent(self):
        return SentMessage.find(owner = self._id).sort('delivered', -1)

    def get_unread(self):
        return Message.find(owner = self._id, unread = True).sort('delivered', -1)

    def get_moderated(self):
        return Community.find(_id = { '$in': self.moderated },
            banned = None).sort('num_subscribers', -1)

    def is_moderator(self, cmty):
        '''
        Return whether the User has moderator authority over a Community;
        i.e. whether they are an approved moderator or a global admin.
        '''
        return self.admin or self.true_moderator(cmty)

    def true_moderator(self, cmty):
        '''
        Return whether the User is truly a moderator of a Community;
        i.e. is among the approved moderators for the given Community.
        '''
        if not hasattr(self, '_moderated'):
            self._moderated = frozenset(self.moderated)
        return cmty._id in self._moderated

    def add_saved(self, post):
        Session.update(User, { '_id': self._id },
            { '$addToSet': { 'saved': post._id } })

    def get_saved(self):
        return Post.find(_id = { '$in': self.saved }).sort('created', -1)

    def has_saved(self, post):
        if not hasattr(self, '_saved'):
            self._saved = frozenset(self.saved)
        return post._id in self._saved

    def remove_saved(self, post):
        Session.update(User, { '_id': self._id },
            { '$pull': { 'saved': post._id } },
            fields = { 'saved': 1 })

    def get_subscribed(self):
        return Community.find(_id = { '$in': self.subscribed }, banned = None) \
            .sort([('num_subscribers', -1), ('created', 1)]).limit(50)

    def has_unread(self):
        return self.unread_count() != 0

    def is_subscribed(self, cmty_id):
        s = getattr(self, '_subscribed_set', ())
        if len(s) != len(self.subscribed):
            self._subscribed_set = s = frozenset(self.subscribed)

        return cmty_id in s

    def set_default_communities(self):
        for name in g.default_communities:
            try:
                self.subscribe(Community.by_name(name))
            except exc.NotFound:
                pass

    def set_email(self, email):
        self.email_address = email
        self.email_confirmed = None

    def set_name(self, name):
        self.name = name = h.valid_name(name, max_len = self.MAX_NAME_LENGTH)
        self.name_lc = name.lower()

    def set_password(self, password):
        if len(password) < 6:
            raise ClientError('Password must be at least 6 characters')

        if self._id:
            try:
                Session.find_and_modify(User,
                    { '_id': self._id, 'password': self.password },
                    { '$set': { 'password': h.hash_password(password) } },
                    fields = { 'password': 1 })
            except exc.NotFound:
                raise ClientError('Incorrect password')
        else:
            self.password = h.hash_password(password)

    def register(self):
        self._commit()
        self.set_default_communities()

    def render(self, user):
        r = {
            'name': self.name,
            'created': self.created,
        }

        if self is user:
            r['unread_mail'] = self.unread_count()
            if self.moderated:
                r['unread_mod_mail'] = self.mod_unread_count()

        if user.admin and self.banned:
            r['banned'] = self.get_banned_by().name

        return r

    def subscribe(self, cmty):
        try:
            Session.find_and_modify(User,
                { '_id': self._id, 'subscribed': { '$ne': cmty._id } },
                { '$addToSet': { 'subscribed': cmty._id } },
                fields = { 'subscribed': 1 })
            Session.update(Community, { '_id': cmty._id },
                { '$inc': { 'num_subscribers': 1 } })
        except exc.NotFound:
            pass

    def unsubscribe(self, cmty):
        try:
            Session.find_and_modify(User,
                { '_id': self._id, 'subscribed': cmty._id },
                { '$pull': { 'subscribed': cmty._id } },
                fields = { 'subscribed': 1 })
            Session.update(Community, { '_id': cmty._id },
                { '$inc': { 'num_subscribers': -1 } })
        except exc.NotFound:
            pass

    def mod_unread_count(self):
        if not self.moderated:
            return 0
        return Message.find(owner_mod = { '$in': self.moderated },
            unread = True).count()

    def unread_count(self):
        return Message.find(owner = self._id, unread = True).count()

User.name_cache = mongo.InstanceCache(Session, User, 'name_lc')

mongo.Index(User, 'subscribed')

class UserSession(ModelBase, mongo.Document):
    _collection = 'session'

    user_id = mongo.Field(str)
    key = mongo.Field(str, required = True, unique = True)
    token = mongo.Field(str, required = True)
    created = mongo.Field(datetime.datetime, required = True)
    access = mongo.Field(datetime.datetime, required = True)

    def get_access(self):
        return SessionAccess.find(user_id = self.user_id).sort('last_access', -1)

    def log_access(self, environ = None):
        '''
        Log access to this session by a client.
        environ must be provided if pylons.request has not been initialized.

        environ:
            WSGI environ dict
        '''
        if self.user_id:
            Session.update(UserSession, { '_id': self._id },
                { '$set': { 'access': datetime.datetime.utcnow() } })
            SessionAccess.update(self, environ or request.environ)
            Session.update(User, { '_id': self.user_id },
                { '$set': { 'last_activity': datetime.datetime.utcnow() } })

    def remove(self):
        if self._id:
            self._remove()
            self.unset_cookie = True
            # Reset document fields
            self.__init__()
            self._dirty.clear()

    def reset(self):
        self.key = h.make_key()
        self.token = h.make_key()
        self.set_cookie = True

    def save(self):
        if self._id is None:
            self.reset()
        if self.created is None:
            self.created = self.access = datetime.datetime.utcnow()
        self._commit()

mongo.Index(UserSession, 'access')

class SessionAccess(ModelBase, mongo.Document, Renderable):
    _collection = 'session_access'

    address = mongo.Field(str, required = True)
    user_id = mongo.Field(str, required = True)
    last_access = mongo.Field(datetime.datetime, required = True)

    @classmethod
    def update(cls, sess, environ):
        addr = environ['REMOTE_ADDR']
        user_id = sess.user_id
        Session.update(cls,
            { 'address': addr, 'user_id': user_id },
            { 'address': addr, 'user_id': user_id,
                'last_access': sess.access }, upsert = True)

    def render(self, user):
        return {
            'address': self.address,
            'last_access': self.last_access,
        }

mongo.Index(SessionAccess, 'user_id')

class ResetToken(ModelBase, mongo.Document):
    _collection = 'reset_token'

    key = mongo.Field(str, required = True, unique = True)
    expires = mongo.Field(datetime.datetime, required = True)
    user = mongo.Field(str, required = True, unique = True)

    EXPIRES = datetime.timedelta(hours = 24)

    def __init__(self, user):
        super(ResetToken, self).__init__()
        self.user = user._id
        self.key = h.make_key()
        self.expires = datetime.datetime.utcnow() + self.EXPIRES

    @classmethod
    def by_key(cls, key):
        try:
            return Session.find_one(cls, { 'key': key,
                'expires': { '$gt': datetime.datetime.utcnow() } })
        except exc.NotFound:
            raise ClientError('reset token has expired')

    @classmethod
    def create(cls, user):
        Session.remove(cls, { 'user': user._id,
            'expires': { '$lte': datetime.datetime.utcnow() } })
        try:
            reset = cls(user)
            reset._commit()
        except exc.DuplicateKeyError:
            raise ClientError('try again later')

        ResetPasswordEmail.mail(user = user._id, key = reset.key)

    def consume(self):
        try:
            now = datetime.datetime.utcnow()
            Session.find_and_modify(ResetToken, { '_id': self._id,
                'expires': { '$gt': now } }, remove = True)
        except exc.NotFound:
            raise ClientError('reset token has expired')

    def get_user(self):
        return User.get(self.user)

mongo.Index(ResetToken, 'key', unique = True)

class Email(ModelBase, mongo.Document):
    _collection = 'email'
    _polymorphic = 'type'

    type = mongo.Field(str)
    created = mongo.Field(datetime.datetime, required = True)

    @classmethod
    def mail(cls, **kws):
        try:
            email = cls(**kws)
            if not email.created:
                email.created = datetime.datetime.utcnow()
            email._commit()
        except Exception as e:
            log.error(u'Failed to queue email: {type} {kws}: {error}'
                .format(type = cls, kws = kws, error = e))

    def __repr__(self):
        '''Return a string representation, used for error logs'''
        raise NotImplementedError

    def can_send(self):
        return True

    def from_address(self):
        '''Return a str or unicode representing the From address'''
        raise NotImplementedError

    def to_address(self):
        '''
        Return a str, unicode or list of str and unicode representing
        the To address(es)
        '''
        raise NotImplementedError

    def subject(self):
        '''Return a str or unicode representing the Subject line'''
        raise NotImplementedError

    def body(self):
        '''Return the rendered message body'''
        return g.mako_lookup.get_template(self.TEMPLATE).render(email = self)

class ResetPasswordEmail(Email):
    _polymorphic_identity = 'reset'

    TEMPLATE = 'email/reset.mako'

    user = mongo.Field(str, required = True)
    key = mongo.Field(str, required = True)

    def get_user(self):
        return User.get(self.user)

    def __repr__(self):
        return '<ResetPasswordEmail to {user}>'.format(user = self.user)

    def can_send(self):
        return self.get_user().email_address is not None

    def from_address(self):
        return 'resetpassword@' + g.email_domain

    def to_address(self):
        u = self.get_user()
        return '"%s" <%s>' % (u.name, u.email_address)

    def subject(self):
        return 'Reset password token'

class Captcha(ModelBase, mongo.Document):
    _collection = 'captcha'

    solution = mongo.Field(str, required = True)
    expires = mongo.Field(datetime.datetime, required = True)
    key = mongo.Field(str, required = True, unique = True)

    EXPIRES = datetime.timedelta(minutes = 10)

    def __init__(self, key, solution):
        self.solution = solution
        self.key = key
        self.expires = datetime.datetime.utcnow() + self.EXPIRES

    @classmethod
    def by_key(cls, key):
        return cls.by(key = key, expires = { '$gt': datetime.datetime.utcnow() })

    @classmethod
    def create(cls, key):
        cptcha = cls(key, captcha.random_solution())
        return Session.find_and_modify(cls, { 'key': key },
            cptcha, upsert = True)

    @classmethod
    def solve(cls, key, solution):
        now = datetime.datetime.utcnow()
        try:
            captcha = Session.find_and_modify(cls, { 'key': key }, remove = True)
            return captcha.expires > now and \
                captcha.solution == solution.strip().upper()
        except exc.NotFound:
            return False

mongo.Index(Captcha, 'key', unique = True)

class Moderator(ModelBase, mongo.Document, Renderable):
    _collection = 'moderator'

    community = mongo.Field(str, required = True)
    user = mongo.Field(str, required = True)
    created = mongo.Field(datetime.datetime, required = True)

    def __init__(self, cmty, user, when = None):
        self.community = cmty._id
        self.user = user._id
        self.created = when or datetime.datetime.utcnow()

    @classmethod
    def fake_mod(cls):
        '''
        Returns an instance representing the imaginary Moderator instance
        belonging to any User with the admin flag.
        '''
        mod = cls.__new__(cls)
        super(Moderator, mod).__init__(created = datetime.datetime(1970, 1, 1))
        return mod

    def get_user(self):
        return User.get(self.user)

    def render(self, user):
        return {
            'name': self.get_user().name,
            'created': self.created,
        }

mongo.Index(Moderator, ('community', 'user'), unique = True)

class Community(ModelBase, mongo.Document, Renderable):
    _collection = 'community'
    _id_factory = lambda o: unique_id('community')

    MAX_NAME_LENGTH = 32
    MAX_TITLE_LENGTH = 128
    MAX_SIDEBAR_LENGTH = 1 << 10

    ## Unique name of community
    name = mongo.Field(unicode, required = True)
    ## Lowercase version of name field
    name_lc = mongo.Field(unicode, required = True, unique = True)
    ## Title presented on community page
    title = mongo.Field(unicode, required = True)
    ## Sidebar text on community page
    sidebar = mongo.Field(unicode)
    ## Access to users, one of:
    # public: Visible to all, all may post
    # restricted: Visible to all, only approved users may post
    # private: Visible to only approved users
    access = mongo.EnumField(('public', 'private', 'restricted'), default = 'public')
    ## User _ids of approved posters/viewers
    contributors = mongo.ListField(str)
    ## User _id of the administrator who has banned the community
    banned = mongo.Field(str)
    ## User _ids of banned users
    bans = mongo.ListField(str, hidden = True)
    ## Whether the community's posts will be automatically marked nsfw
    nsfw = mongo.Field(bool)
    ## Whether the community is not allowed within the default set
    no_default = mongo.Field(bool)
    ## Time of creation
    created = mongo.Field(datetime.datetime, required = True)
    ## Community creator
    creator = mongo.Field(str)
    ## Number of subscribers
    num_subscribers = mongo.Field(int, default = 0)
    ## Number of user-submitted violation reports
    num_reports = mongo.Field(int)

    def __init__(self, name, title, **kws):
        super(Community, self).__init__(**kws)
        self.set_name(name)
        self.set_title(title)
        self.created = datetime.datetime.utcnow()

    @classmethod
    def by_name(cls, name):
        return cls.name_cache.get(name.lower())

    @classmethod
    def get_default(cls):
        if g.default_communities:
            return cls.find(name_lc = { '$in': g.default_communities }) \
                .sort([('num_subscribers', -1), ('created', 1)])
        return cls.get_top().filter({ 'no_default': cls.FALSE })

    @classmethod
    def find_visible(cls, user = None):
        res = Session.find(cls)

        if user is None:
            res.filter({ 'access': { '$ne': 'private' },
                'banned': None })
        elif not user.admin:
            res.filter({ 'banned': None,
                '$or': [{ 'access': { '$ne': 'private' } },
                    { 'contributors': user._id }] })

        return res

    @classmethod
    def get_banned(cls):
        return cls.find(banned = cls.NON_NULL).sort('created', -1)

    @classmethod
    def get_top(cls, user = None):
        return cls.find_visible(user).sort(
            [('num_subscribers', -1), ('created', 1)])

    @classmethod
    def get_new(cls, user = None):
        return cls.find_visible(user).sort('created', -1)

    @classmethod
    def get_subscribed(cls, user = None):
        if user is None or not user.subscribed:
            return cls.get_default()

        return user.get_subscribed()

    @classmethod
    def random(cls):
        cmties = cls.find_visible()
        n = cmties.count()
        if not n:
            raise exc.NotFound

        return cmties.limit(1).skip(random.randrange(n))[0]

    def ban(self, user):
        try:
            Session.find_and_modify(Community,
                { '_id': self._id, 'banned': None },
                { '$set': { 'banned': user._id } })
        except exc.NotFound:
            raise ClientError('Community is already banned')

        AdminLog.log(user, 'ban', community = self._id)

    def unban(self, user):
        try:
            Session.find_and_modify(Community,
                { '_id': self._id, 'banned': self.NON_NULL },
                { '$unset': { 'banned': 1 } })
        except exc.NotFound:
            raise ClientError('Community is not banned')

        AdminLog.log(user, 'unban', community = self._id)

    def add_ban(self, mod, user, reason):
        try:
            Session.find_and_modify(Community,
                { '_id': self._id, 'bans': { '$ne': user._id } },
                { '$push': { 'bans': user._id } })
        except exc.NotFound:
            raise ClientError('User is already banned')
        else:
            CommunityBan(self, mod, user, reason)._commit()
            self.log(mod, 'ban', user = user._id)

    def get_ban(self, user):
        return CommunityBan.by(community = self._id, user = user._id)

    def has_ban(self, user):
        return user is not None and user._id in self.bans

    def remove_ban(self, mod, user):
        try:
            ban = self.get_ban(user)
            Session.find_and_modify(Community,
                { '_id': self._id, 'bans': user._id },
                { '$pull': { 'bans': user._id } })
            ban._remove()
            self.log(mod, 'unban', user = user._id)
        except exc.NotFound:
            raise ClientError('User is not banned')

    def get_banned_by(self):
        if self.banned:
            return User.get(self.banned)

    def create(self, user):
        self.creator = user._id
        self._commit()
        user.subscribe(self)
        self.add_moderator(None, user, self.created)

    def can_submit(self, user):
        return (user is not None and user.admin) or (
            not self.has_ban(user) and
            (self.access == 'public' or
            (user is not None and self.has_contributor(user))))

    def can_comment(self, user):
        return (user is not None and user.admin) or (
            not self.has_ban(user) and
            (self.access != 'private' or
            (user is not None and self.has_contributor(user))))

    def get_bans(self):
        return CommunityBan.find(community = self._id).sort('created', -1)

    def get_creator(self):
        if self.creator:
            try:
                return User.get(self.creator)
            except exc.NotFound:
                pass

    def get_logs(self):
        return CommunityLog.find(community = self._id).sort('created', -1)

    def get_messages(self, **kws):
        return Message.find(owner_mod = self._id, **kws).sort('delivered', -1)

    def get_removed_comments(self):
        return Comment.find(community = self._id, removed = self.NON_NULL) \
            .sort('created', -1)

    def get_removed_posts(self):
        return Post.find(community = self._id, removed = self.NON_NULL) \
            .sort('created', -1)

    @classmethod
    def get_reported(cls):
        return cls.find(num_reports = { '$gt': 0 }).sort('created', -1)

    def get_reports(self):
        return CommunityReport.find(community = self._id).sort('created', -1)

    def get_reported_comments(self):
        return Comment.find(community = self._id, num_reports = { '$gt': 0 },
            approved = None, removed = None).sort('created', -1)

    def get_reported_posts(self):
        return Post.find(community = self._id, num_reports = { '$gt': 0 },
            approved = None, removed = None).sort('created', -1)

    def is_visible(self, user = None):
        return (user is not None and user.admin) or \
            self.access != 'private' or \
            (user is not None and user._id in self.contributors)

    def add_moderator(self, mod, user, when = None):
        try:
            Moderator(self, user, when)._commit()

            Session.update(User, { '_id': user._id },
                { '$push': { 'moderated': self._id } })

            self.add_contributor(None, user)
        except exc.DuplicateKeyError:
            raise ClientError('User is already a moderator')

        if mod:
            self.log(mod, 'mod', user = user._id)

    def remove_moderator(self, mod, user):
        '''
        Remove a Moderator from this Community

        mod:
            User performing the removal

        user:
            User whose moderator status to be removed
        '''
        try:
            umod = self.get_moderator(mod)
        except exc.NotFound:
            abort(403)

        if user is mod:
            umod.find_and_remove()
        else:
            try:
                omod = self.get_moderator(user)

                if not umod.created < omod.created:
                    raise ClientError('Cannot remove this moderator')

                omod.find_and_remove()
            except exc.NotFound:
                raise ClientError('User is not a moderator')

        Session.update(User, { '_id': user._id },
            { '$pull': { 'moderated': self._id } })

        self.log(mod, 'unmod', user = user._id)

    def add_contributor(self, mod, user):
        try:
            Session.update(Community, { '_id': self._id },
                { '$addToSet': { 'contributors': user._id } })

            if mod:
                self.log(mod, 'contrib', user = user._id)
        except exc.NotFound:
            pass

    def get_contributors(self):
        return [User.get(u) for u in self.contributors]

    def has_contributor(self, user):
        return user is not None and user._id in self.contributors

    def remove_contributor(self, mod, user):
        try:
            Session.find_and_modify(Community,
                { '_id': self._id, 'contributors': user._id },
                { '$pull': { 'contributors': user._id } },
                fields = { 'contributors': 1 })
            self.log(mod, 'uncontrib', user = user._id)
        except exc.NotFound:
            raise ClientError('User is not a contributor')

    def get_moderator(self, user):
        if user.admin:
            return Moderator.fake_mod()
        return Moderator.by(community = self._id, user = user._id)

    def get_moderators(self):
        return Moderator.find(community = self._id).sort('created')

    def get_posts(self, user = None, sort = 'latest'):
        return post_sort(Post.find(community = self._id,
            deleted = None, removed = None, hidden = self.FALSE), user, sort)

    def log(self, mod, action, **kws):
        l = CommunityLog(community = self._id,
            mod = mod._id, action = action, **kws)

        if not l.created:
            l.created = datetime.datetime.utcnow()
        try:
            l._commit()
        except Exception as e:
            log.error(u'Failed to commit moderator log entry: error={e} '
                'mod={mod} community={cmty} action={action} kws={kws}'
                    .format(e = e, cmty = self._id, mod = mod._id,
                        action = action, kws = kws))

        # Admins using override power also go to the Admin log
        if mod.admin and not mod.true_moderator(self):
            kws.setdefault('created', l.created)
            AdminLog.log(mod, 'override', community = self._id, modlog = l._id)

    @property
    def permalink(self):
        if not hasattr(self, '_permalink'):
            self._permalink = h.url('/g/' + self.name)
        return self._permalink

    def report(self, user, report):
        try:
            CommunityReport(self, user, report)._commit()
        except exc.DuplicateKeyError:
            raise ClientError('You have already reported this community')

        Session.update(Community, { '_id': self._id },
            { '$inc': { 'num_reports': 1 } })

    def require_moderator(self, user):
        if user is None or not user.is_moderator(self):
            abort(403)

    def can_message(self, user):
        '''
        Return whether the given User may message this Community
        '''
        return user.admin or not (user.banned or self.has_ban(user))

    def add_message(self, sender, message):
        '''
        Commit the given message and address it to this Community
        '''
        if sender and not self.can_message(sender):
            raise ClientError('You are banned from messaging this community')
        message.owner_mod = self._id
        if message.delivered is None:
            message.delivered = datetime.datetime.utcnow()
        message._commit()

    def send_message(self, sender, recipient, message):
        '''
        Send the given message to the given recipient and address it from
        this Community, returning a Message as confirmation
        '''
        message.other = sender._id
        message.other_mod = self._id
        recipient.add_message(sender, message)

        sent = SentMessage.from_message(message)
        self.add_message(None, sent)

        return sent

    def set_name(self, name):
        self.name = name = h.valid_name(name, max_len = self.MAX_NAME_LENGTH)
        self.name_lc = name.lower()

    def set_title(self, title):
        if len(title) > self.MAX_TITLE_LENGTH:
            raise ClientError('Title must be no more than {max} characters'
                .format(max = self.MAX_TITLE_LENGTH))
        self.title = title

    def set_sidebar(self, sidebar):
        if len(sidebar) > self.MAX_SIDEBAR_LENGTH:
            raise ClientError('Sidebar must be no more than {max} characters'
                .format(max = self.MAX_SIDEBAR_LENGTH))

        self.sidebar = sidebar

    def submit_post(self, user, post):
        if not self.can_submit(user):
            raise ClientError('You cannot submit posts to this community')

        post.community = self._id
        post.set_value()
        if self.nsfw:
            post.nsfw = post.force_nsfw = True
        post._commit()

    def render(self, user):
        r = {
            'name': self.name,
            'title': self.title,
            'created': self.created,
            'sidebar': self.sidebar or '',
            'sidebar_html': h.markdown(self.sidebar),
            'num_subscribers': self.num_subscribers,
        }

        if user is not None and user.admin:
            if self.banned:
                r['banned'] = self.get_banned_by().name
            if self.num_reports:
                r['num_reports'] = self.num_reports

        return r

Community.name_cache = mongo.InstanceCache(Session, Community, 'name_lc')

mongo.Index(Community, 'access')
mongo.Index(Community, 'contributors', sparse = True)
mongo.Index(Community, 'created')
mongo.Index(Community, 'creator')
mongo.Index(Community, 'num_subscribers')

class CommunityBan(ModelBase, mongo.Document, Renderable):
    _collection = 'community_ban'

    MAX_LENGTH = 2 << 10

    community = mongo.Field(str, required = True)
    user = mongo.Field(str, required = True)
    mod = mongo.Field(str, required = True)
    created = mongo.Field(datetime.datetime, required = True)
    reason = mongo.Field(unicode, required = True)

    def __init__(self, cmty, mod, user, reason, now = None):
        super(CommunityBan, self).__init__()
        self.community = cmty._id
        self.mod = mod._id
        self.user = user._id
        self.set_reason(reason)
        self.created = now or datetime.datetime.utcnow()

    def get_moderator(self):
        return User.get(self.mod)

    def get_user(self):
        return User.get(self.user)

    def render(self, user):
        return {
            'user': User.get(self.user).name,
            'reason': self.reason
        }

    def set_reason(self, reason):
        if len(reason) > self.MAX_LENGTH:
            raise ClientError('Reason must be no more than {max} characters'
                .format(max = self.MAX_LENGTH))

        self.reason = reason

mongo.Index(CommunityBan, 'community')
mongo.Index(CommunityBan, ('user', 'community'), unique = True)

class CommunityLog(ModelBase, mongo.Document, Renderable):
    _collection = 'community_log'

    community = mongo.Field(str, required = True)
    mod = mongo.Field(str, required = True)
    action = mongo.EnumField(('approve', 'ban', 'contrib',
        'edit', 'mod', 'remove', 'unban', 'uncontrib', 'unmod'), required = True)
    created = mongo.Field(datetime.datetime, required = True)
    post = mongo.Field(str)
    comment = mongo.Field(str)
    user = mongo.Field(str)

    def get_moderator(self):
        return User.get(self.mod)

    def get_post(self):
        if self.post:
            return Post.get(self.post)

    def get_comment(self):
        if self.comment:
            return Comment.get(self.comment)

    def get_user(self):
        if self.user:
            return User.get(self.user)

    def render(self, user):
        r = {
            'mod': self.get_moderator().name,
            'action': self.action,
            'created': self.created,
        }

        if self.comment:
            r['comment'] = self.comment
        if self.post:
            r['post'] = self.post
        if self.user:
            r['user'] = self.get_user().name

        return r

mongo.Index(CommunityLog, 'action')
mongo.Index(CommunityLog, 'community')
mongo.Index(CommunityLog, 'mod')
mongo.Index(CommunityLog, 'comment', sparse = True)
mongo.Index(CommunityLog, 'post', sparse = True)
mongo.Index(CommunityLog, 'user', sparse = True)

class AdminLog(ModelBase, mongo.Document, Renderable):
    _collection = 'admin_log'

    admin = mongo.Field(str, required = True)
    action = mongo.EnumField(CommunityLog.action.values |
        frozenset(('ban', 'delete', 'unban', 'override')),
        required = True)
    created = mongo.Field(datetime.datetime, required = True)
    community = mongo.Field(str)
    post = mongo.Field(str)
    comment = mongo.Field(str)
    user = mongo.Field(str)
    ## If action is override, refers to the event in a CommunityLog
    modlog = mongo.Field(bson.ObjectId)

    @classmethod
    def get_logs(cls):
        return cls.find().sort('created', -1)

    @classmethod
    def log(cls, admin, action, **kws):
        l = cls(admin = admin._id, action = action, **kws)

        if not l.created:
            l.created = datetime.datetime.utcnow()

        try:
            l._commit()
        except Exception as e:
            log.error(u'Failed to commit admin log entry: error={e} '
                'admin={admin} action={action} kws={kws}'.format(
                    e = e, admin = admin._id, action = action, kws = kws))

    def get_admin(self):
        return User.get(self.admin)

    def get_community(self):
        if self.community:
            return Community.get(self.community)

    def get_post(self):
        if self.post:
            return Post.get(self.post)

    def get_comment(self):
        if self.comment:
            return Comment.get(self.comment)

    def get_user(self):
        if self.user:
            return User.get(self.user)

    def get_modlog(self):
        if self.modlog:
            return CommunityLog.get(self.modlog)

    def render(self, user):
        r = {
            'admin': self.get_admin().name,
            'action': self.action,
            'created': self.created,
        }

        if self.community:
            r['community'] = self.get_community().name
        if self.comment:
            r['comment'] = self.comment
        if self.post:
            r['post'] = self.post
        if self.user:
            r['user'] = self.get_user().name
        if self.modlog:
            r['override'] = self.get_modlog().render(user)

        return r

mongo.Index(AdminLog, 'action')
mongo.Index(AdminLog, 'admin')
mongo.Index(AdminLog, 'community', sparse = True)
mongo.Index(AdminLog, 'comment', sparse = True)
mongo.Index(AdminLog, 'post', sparse = True)
mongo.Index(AdminLog, 'user', sparse = True)

def value_text(text, NONLETTER = re.compile(r'[^\d\w]+', re.UNICODE)):
    if not text:
        return 0

    # Prevent exploitation of invisible whitespace
    n = len(NONLETTER.sub('', text))

    return min((n // 200) + 1, 10)

def decorate(item, user, decoration):
    if not item.is_author(user):
        raise ClientError('You cannot decorate this post')

    if decoration == 'admin':
        if not user.admin:
            raise ClientError('You are not an administrator')
    elif decoration == 'mod':
        if not user.is_moderator(item.get_community()):
            raise ClientError('You are not a moderator')

    try:
        update = { '$set': { 'decoration': decoration } } if decoration else \
            { '$unset': { 'decoration': 1 } }

        Session.find_and_modify(type(item),
            { '_id': item._id, 'author': user._id, 'deleted': None },
            update, fields = { 'decoration': 1 })
    except exc.NotFound:
        raise ClientError('You cannot decorate this item')

class Post(ModelBase, mongo.Document, Renderable):
    _collection = 'post'
    _id_factory = lambda o: unique_id('post')

    MAX_TITLE_LENGTH = 512
    MAX_URL_TITLE_LENGTH = 50
    MAX_LINK_LENGTH = 2 << 10
    MAX_LENGTH = 10 << 10

    ## _id of Community containing the post
    community = mongo.Field(str, required = True)
    ## User _id of author
    author = mongo.Field(str, required = True)
    ## Post decoration
    decoration = mongo.EnumField(('admin', 'mod'))
    ## User who deleted the Post
    deleted = mongo.Field(str)
    ## Time of creation
    created = mongo.Field(datetime.datetime, required = True)
    ## Post title
    title = mongo.Field(unicode, required = True)
    ## Search terms from title
    keywords = mongo.ListField(unicode, hidden = True)
    ## Simplified title present in URLs
    url_title = mongo.Field(unicode, required = True)
    ## Post link
    link = mongo.Field(unicode)
    ## Link domain
    domain = mongo.Field(unicode)
    ## Link domain name, in reverse order
    r_domain = mongo.Field(unicode)
    ## Text of post
    text = mongo.Field(unicode)
    ## Value of post
    value = mongo.Field(int, required = True)
    ## Value of post and all contained comments
    total_value = mongo.Field(int, required = True)
    ## True if the post was submitted by a banned User
    hidden = mongo.Field(bool)
    ## Time of last reply, or time of original posting
    last_reply = mongo.Field(datetime.datetime, required = True)
    ## Number of comments
    num_comments = mongo.Field(int, default = 0)
    ## Whether the post has been flagged NSFW (Not Safe For Work)
    nsfw = mongo.Field(bool)
    ## When set, the author may not remove the nsfw flag
    force_nsfw = mongo.Field(bool)
    ## User _id of the moderator who approved the Post
    approved = mongo.Field(str)
    ## User _id of the moderator who removed the Post
    removed = mongo.Field(str)
    ## Number of user-submitted violation reports
    num_reports = mongo.Field(int)

    def __init__(self, title):
        super(Post, self).__init__()
        self.set_title(title)
        self.created = self.last_reply = datetime.datetime.utcnow()

    @classmethod
    def by_link(cls, link, user = None):
        return post_sort(cls.find(link = unicode(link)), user, 'new')

    @classmethod
    def links_by_domain(cls, domain, user = None, sort = 'latest'):
        return post_sort(cls.find(r_domain = h.match_domain(domain)), user, sort)

    @classmethod
    def search(cls, keywords, user, sort = 'new', any = False):
        return post_sort(cls.find(keywords =
            (keywords[0] if len(keywords) == 1 else
                { ('$in' if any else '$all'): keywords }),
            deleted = None, removed = None), user, sort)

    def is_author(self, user):
        return not self.deleted and user is not None and self.author == user._id

    def belongs_to(self, cmty):
        if self.community != cmty._id:
            abort(404)

    def can_nsfw(self, user, value):
        return (user is not None and
            ((not self.deleted and not self.force_nsfw and
                user._id == self.author) or
            (user.is_moderator(self.get_community()))))

    @classmethod
    def get_all(cls, user = None, sort = 'latest'):
        return post_sort(cls.find(deleted = None, removed = None), user, sort)

    @classmethod
    def get_frontpage(cls, user = None, sort = 'latest'):
        if user is None:
            cmties = [cmty._id for cmty in
                Community.find(name_lc = { '$in': g.default_communities })]
        else:
            cmties = user.subscribed

        return post_sort(cls.find(community = { '$in': cmties },
            deleted = None, removed = None, hidden = cls.FALSE), user, sort)

    def decorate(self, user, decoration):
        decorate(self, user, decoration)

    def edit(self, user, text):
        if not self.is_author(user):
            raise ClientError('You cannot edit this post')
        self.set_text(text)
        self._commit()
        self.set_value()

    def can_delete(self, user):
        return self.is_author(user) or (user is not None and user.admin)

    def delete(self, user):
        '''
        Mark a Post as deleted, it will be rendered hereafter with
        the author field as '[deleted]'.

        user:
            User attempting to delete the Post
            A ClientError will be raised if they are not the author
        '''
        if not self.can_delete(user):
            raise ClientError('You cannot delete this post')

        is_admin = not self.is_author(user)

        try:
            Session.find_and_modify(Post,
                { '_id': self._id, 'deleted': None },
                { '$set': { 'deleted': user._id } })
        except exc.NotFound:
            raise ClientError('You cannot delete this post')

        self.set_value()

        if is_admin:
            AdminLog.log(user, 'delete',
                community = self.community, post = self._id)

    def get_author(self, override = False):
        if self.author and (override or not self.deleted):
            try:
                return User.get(self.author)
            except exc.NotFound:
                pass

    def get_approved(self):
        if self.approved:
            return User.get(self.approved)

    def get_deleted(self):
        if self.deleted:
            return User.get(self.deleted)

    def get_removed(self):
        if self.removed:
            return User.get(self.removed)

    def get_comments(self, user = None, limit = 500):
        # TODO: Sort by 'new' or 'latest'
        return Comment.comment_tree(user,
            Comment.find(post = self._id, depth = { '$lt': 10 })
                .sort([('total_value', -1), ('created', 1)]).limit(limit))

    def get_community(self):
        return Community.get(self.community)

    def get_reports(self):
        return PostReport.find(post = self._id).sort('created', -1)

    def approve(self, mod):
        try:
            Session.find_and_modify(Post,
                { '_id': self._id, 'approved': None },
                { '$unset': { 'removed': 1 },
                    '$set': { 'approved': mod._id } })
        except exc.NotFound:
            return

        self.set_value()
        self.get_community().log(mod, 'approve', post = self._id)

    def remove(self, mod):
        try:
            Session.find_and_modify(Post,
                { '_id': self._id, 'removed': None },
                { '$set': { 'removed': mod._id }, '$unset': { 'approved': 1 } })
        except exc.NotFound:
            return

        self.get_community().log(mod, 'remove', post = self._id)

    def mark_nsfw(self, user, force = False):
        if not self.can_nsfw(user, True):
            raise ClientError('You cannot mark this post NSFW')

        if not self.is_author(user):
            # Moderators force NSFW to prevent the author from removing it
            self.nsfw = self.force_nsfw = True
            self._commit()
        else:
            try:
                Session.find_and_modify(Post,
                    { '_id': self._id, 'force_nsfw': self.FALSE },
                    { '$set': { 'nsfw': True } })
            except exc.NotFound:
                raise ClientError('You cannot mark this post NSFW')

    def unmark_nsfw(self, user):
        if not self.can_nsfw(user, False):
            raise ClientError('You cannot unmark this post NSFW')
        self.nsfw = self.force_nsfw = None
        self._commit()

    @property
    def permalink(self):
        if not hasattr(self, '_permalink'):
            self._permalink = self.get_link()
        return self._permalink

    def get_link(self, action = 'comments', **kws):
        cmty = self.get_community()
        return h.url(u'/g/{cmty}/{action}/{post}/{title}'.format(
            cmty = cmty.name, action = action, post = self._id,
            title = self.url_title), **kws)

    def get_other_discussions(self, user = None):
        if self.link:
            return Post.by_link(self.link, user).filter(
                { '_id': { '$ne': self._id } })
        else:
            # It's just easier to always return a ResultSet.
            # This one should always be empty.
            return Post.find(_id = None)

    def post_comment(self, author, comment):
        if not self.get_community().can_comment(author):
            raise ClientError('You cannot submit comments to this community')

        if not comment.hidden:
            Session.modify(self, { '$inc': { 'num_comments': 1 } })

        try:
            comment.community = self.community
            comment.post = self._id
            comment.set_value()
            comment._commit()
        except Exception:
            if not comment.hidden:
                Session.update(Post, { '_id': self._id },
                    { '$inc': { 'num_comments': -1 } })
            raise

        if not comment.hidden:
            Session.update(Post,
                { '_id': self._id, 'last_reply': { '$lt': comment.created } },
                { '$set': { 'last_reply': comment.created } })

        if self.author and not (self.deleted or comment.hidden) and self.author != comment.author:
            try:
                user = self.get_author()
                user.add_message(author, ReplyMessage(other = author._id,
                    community = self.community,
                    post = self._id, reply = comment._id))
            except Exception as e:
                # Let the error be known, but don't give the client
                # the impression that their comment has not posted.
                log.error(u'Error while delivering ReplyMessage to {user} '
                    'for root comment {comment}: {error}'.format(
                        user = self.author, comment = comment._id, error = e))

    def render(self, user):
        cmty = Community.get(self.community)
        author = self.get_author()

        r = {
            'id': self._id,
            'community': cmty.name,
            'author': '[deleted]' if author is None else author.name,
            'created': self.created,
            'title': self.title,
            'permalink': self.permalink,
            'nsfw': self.nsfw or False,
        }

        is_admin = user is not None and user.admin
        is_mod = user is not None and user.is_moderator(self.get_community())

        if self.link:
            r['link'] = self.link
            r['domain'] = self.domain
        if self.text:
            r['text'] = self.text
            r['text_html'] = h.markdown(self.text)
        if self.decoration:
            r['decoration'] = self.decoration
        if is_admin and self.deleted:
            r['deleted'] = self.get_deleted().name
        if is_mod:
            if self.approved:
                r['approved'] = self.get_approved().name
            elif self.removed:
                r['removed'] = self.get_removed().name

        return r

    def report(self, user, report):
        if not self.get_community().can_submit(user):
            raise ClientError('You may not submit reports to this community')

        try:
            PostReport(self, user, report)._commit()
        except exc.DuplicateKeyError:
            raise ClientError('You have already reported this post')

        Session.update(Post, { '_id': self._id },
            { '$inc': { 'num_reports': 1 } })

    def set_link(self, link):
        self.link = unicode(link)
        self.domain = link.hostname
        self.r_domain = link.reverse_domain()

    def set_text(self, text):
        if len(text) > self.MAX_LENGTH:
            raise ClientError('Text must be no more than {max} characters'
                .format(max = self.MAX_LENGTH))
        self.text = text

    def set_title(self, title):
        if not title:
            raise ClientError('Missing title')
        if len(title) > self.MAX_TITLE_LENGTH:
            raise ClientError('Title must be no more than {max} characters'
                .format(max = self.MAX_TITLE_LENGTH))

        self.title = title
        self.keywords = h.keywords(title)
        self.set_url_title()

    def set_value(self):
        if self.hidden:
            value = 0
        elif self.link and not self.text:
            value = 1
        else:
            value = value_text(self.text)

        if self._id is None:
            self.value = self.total_value = value
        else:
            old = Session.find_and_modify(Post, { '_id': self._id },
                { '$set': { 'value': value } },
                fields = { 'value': 1 }, new = False)

            diff = value - old['value']
            if diff:
                Session.modify(self, { '$inc': { 'total_value': diff } },
                    fields = { 'total_value': 1 })

    def set_url_title(self, NONLETTER = re.compile(r'([^\d\w\s]|_)+', re.UNICODE),
            WHITESPACE = re.compile(r'\s+', re.UNICODE)):
        t = NONLETTER.sub('', self.title.lower())

        if not t:
            self.url_title = '_'
            return

        words = WHITESPACE.split(t)

        MAX = self.MAX_URL_TITLE_LENGTH

        if len(words[0]) >= MAX:
            return words[0][:MAX]

        res = []
        n = -1

        for w in words:
            n += len(w) + 1
            if n > MAX:
                break
            res.append(w)

        self.url_title = '_'.join(res)

mongo.Index(Post, 'author')
mongo.Index(Post, 'community')
mongo.Index(Post, 'created')
mongo.Index(Post, 'keywords', sparse = True)
mongo.Index(Post, 'link', sparse = True)
mongo.Index(Post, 'r_domain', sparse = True)

class Comment(ModelBase, mongo.Document, Renderable):
    _collection = 'comment'
    _id_factory = lambda o: unique_id('comment')

    MAX_LENGTH = 10 << 10

    ## Community containing the Comment
    community = mongo.Field(str, required = True)
    ## _id of Post containing the Comment
    post = mongo.Field(str, required = True)
    ## User _id of author
    author = mongo.Field(str, required = True)
    ## Comment decoration
    decoration = mongo.EnumField(('admin', 'mod'))
    ## User who deleted the Comment
    deleted = mongo.Field(str)
    ## Whether the Comment has been edited
    edited = mongo.Field(bool)
    ## Time of creation
    created = mongo.Field(datetime.datetime, required = True)
    ## Text of comment
    text = mongo.Field(unicode, required = True)
    ## Value of this comment
    value = mongo.Field(int, required = True)
    ## Value of comment and replies
    total_value = mongo.Field(int, required = True)
    ## True if the post was submitted by a banned User
    hidden = mongo.Field(bool)
    ## List of parent Comment _ids, beginning with root comment;
    # empty for root comments
    parents = mongo.ListField(str)
    ## Number of parent Comments
    depth = mongo.Field(int, default = 0)
    ## Number of direct replies
    num_replies = mongo.Field(int, default = 0)
    ## Number of descendant comments
    num_children = mongo.Field(int, default = 0)
    ## Moderator _id who approved the Comment
    approved = mongo.Field(str)
    ## Whether the Comment has been removed by a moderator
    removed = mongo.Field(str)
    ## Number of user-submitted violation reports
    num_reports = mongo.Field(int)

    def __init__(self, text):
        super(Comment, self).__init__()
        self.set_text(text)
        self.created = datetime.datetime.utcnow()

    @classmethod
    def comment_tree(cls, user, comments, start_depth = 0):
        '''
        Given a list of Comments, assumed to be sorted by total_value,
        return a list of root comments whose added 'replies' attributes
        contain child comments.

        user:
            User requesting comments

        comments:
            List of Comments, MUST be sorted in descending order by total_value

        start_depth:
            Initial depth of given comments; i.e. returned "root" comments
            will have start_depth parents which will not be present in the input.
        '''
        roots = []
        roots_d = {}

        ignored_comments = set()

        for c in comments:
            if c.deleted and not c.num_replies:
                continue
            if c.hidden and (user is None or (not c.deleted and user._id != c.author)):
                ignored_comments.add(c._id)
                continue

            tree = roots
            tree_d = roots_d

            for p in c.parents[start_depth:]:
                if p in ignored_comments:
                    break
                if p not in tree_d:
                    log.error('Orphaned comment {comment}'.format(comment = c._id))
                    break

                tree, tree_d = tree_d[p]
            else:
                c._replies = replies = []
                tree.append(c)
                tree_d[c._id] = (replies, {})

        roots.sort(key = lambda cm: (cm.total_value, cm.created), reverse = True)

        return roots

    @classmethod
    def get_new(cls, user = None):
        return post_sort(cls.find(deleted = None, removed = None,
            hidden = cls.FALSE), user, 'new')

    def is_author(self, user):
        return not self.deleted and user is not None and self.author == user._id

    def belongs_to(self, cmty):
        if self.community != cmty._id:
            abort(404)

    def get_context(self, user = None, context = 0,
            max_context = 9, limit = 500):
        '''
        Populate Comment context, fetching replies and possibly parents.
        The topmost ancestor of the context will be returned.

        user:
            User viewing the Comment

        context:
            Number of parents to include in context
        '''
        comments = [self]
        comments.extend(Comment.find(parents = self._id,
            depth = { '$lt': max(10 + self.depth - context, 0) })
            .sort([('total_value', -1), ('created', 1)]).limit(limit))
        self.comment_tree(user, comments, self.depth)

        if context:
            for pid in reversed(self.parents[-context:]):
                cm = Comment.get(pid)
                cm._replies = [self]
                self = cm

        return self

    def decorate(self, user, decoration):
        decorate(self, user, decoration)

    def edit(self, user, text):
        if not self.is_author(user):
            raise ClientError('You cannot edit this comment')
        self.set_text(text)
        self.edited = True
        self._commit()
        self.set_value()

    def can_delete(self, user):
        return self.is_author(user) or (user is not None and user.admin)

    def delete(self, user):
        '''
        Mark a Comment as deleted. It will be rendered hereafter with
        the author field as '[deleted]'.

        user:
            User attempting to delete Comment
            A ClientError is raised if they are not the author
        '''
        if not self.can_delete(user):
            raise ClientError('You cannot delete this comment')

        is_admin = not self.is_author(user)

        try:
            Session.find_and_modify(Comment,
                { '_id': self._id, 'deleted': None },
                { '$set': { 'deleted': user._id } })
        except exc.NotFound:
            raise ClientError('You cannot delete this comment')

        if not (self.removed or self.hidden):
            self.set_value()
            self.update_counts(-1)

        if is_admin:
            AdminLog.log(user, 'delete',
                community = self.community, comment = self._id)

    def get_author(self, override = False):
        if self.author and (override or not self.deleted):
            try:
                return User.get(self.author)
            except exc.NotFound:
                pass

    def get_approved(self):
        if self.approved:
            return User.get(self.approved)

    def get_deleted(self):
        if self.deleted:
            return User.get(self.deleted)

    def get_removed(self):
        if self.removed:
            return User.get(self.removed)

    def get_post(self):
        return Post.get(self.post)

    def get_community(self):
        return Community.get(self.community)

    def get_reports(self):
        return CommentReport.find(comment = self._id).sort('created', -1)

    @property
    def permalink(self):
        if not hasattr(self, '_permalink'):
            self._permalink = self.get_post().permalink + '/' + self._id
        return self._permalink

    def get_link(self, **kws):
        return self.get_post().get_link(**kws) + '/' + self._id

    def approve(self, mod):
        try:
            Session.find_and_modify(Comment,
                { '_id': self._id, 'approved': None, 'removed': self.NON_NULL },
                { '$unset': { 'removed': 1 },
                    '$set': { 'approved': mod._id } })
        except exc.NotFound:
            return

        if not (self.deleted or self.hidden):
            self.update_counts(1)

        self.get_community().log(mod, 'approve', comment = self._id)

    def remove(self, mod):
        try:
            Session.find_and_modify(Comment,
                { '_id': self._id, 'removed': None },
                { '$set': { 'removed': mod._id }, '$unset': { 'approved': 1 } })
        except exc.NotFound:
            return

        if not (self.deleted or self.hidden):
            self.set_value()
            self.update_counts(-1)

        self.get_community().log(mod, 'remove', comment = self._id)

    def report(self, user, report):
        if not self.get_community().can_comment(user):
            raise ClientError('You may not submit reports to this community')

        try:
            CommentReport(self, user, report)._commit()
        except exc.DuplicateKeyError:
            raise ClientError('You have already reported this comment')

        Session.update(Comment, { '_id': self._id },
            { '$inc': { 'num_reports': 1 } })

    def post_reply(self, author, reply):
        if not self.get_community().can_comment(author):
            raise ClientError('You cannot submit comments to this community')

        reply.community = self.community
        reply.post = self.post
        reply.parents = self.parents + [self._id]
        reply.depth = self.depth + 1
        reply.set_value()
        reply._commit()

        if not reply.hidden:
            Session.update(Post, { '_id': self.post,
                'last_reply': { '$lt': reply.created } },
                { '$set': { 'last_reply': reply.created } })

            reply.update_counts(1)

        if self.author and not (self.deleted or reply.hidden) and self.author != reply.author:
            try:
                user = self.get_author()
                user.add_message(author, ReplyMessage(other = author._id,
                    community = self.community,
                    post = self.post, comment = self._id, reply = reply._id))
            except Exception as e:
                # Let the error be known, but don't give the client
                # the impression that their comment has not posted.
                log.error(u'Error while delivering ReplyMessage to {user} '
                    'for reply comment {comment}: {error}'.format(
                        user = self.author, comment = reply._id, error = e))

    def set_text(self, text):
        if len(text) > self.MAX_LENGTH:
            raise ClientError('Text must be no more than {max} characters'
                .format(max = self.MAX_LENGTH))
        self.text = text

    def set_value(self):
        if self.deleted or self.removed or self.hidden:
            value = 0
        else:
            value = value_text(self.text)

        if self._id is None:
            self.value = self.total_value = diff = value
        else:
            old = Session.find_and_modify(Comment, { '_id': self._id },
                { '$set': { 'value': value } },
                fields = { 'value': 1 }, new = False)

            diff = value - old['value']

            Session.modify(self, { '$inc': { 'total_value': diff } },
                fields = { 'total_value': 1 })

        if diff:
            Session.update(Post, { '_id': self.post },
                { '$inc': { 'total_value': diff } })
            if self.parents:
                Session.update(Comment, { '_id': { '$in': self.parents } },
                    { '$inc': { 'total_value': diff } }, multi = True)

    def render(self, user):
        author = self.get_author()

        r = {
            'id': self._id,
            'author': author.name if author else '[deleted]',
            'created': self.created,
            'text': self.text,
        }

        is_admin = user is not None and user.admin
        is_mod = user is not None and user.is_moderator(self.get_community())

        if self.deleted and not is_admin:
            r['author'] = '[deleted]'
            r['text'] = ''
        if self.removed and not is_mod:
            r['author'] = '[comment removed]'
            r['text'] = ''
        else:
            if self.edited:
                r['edited'] = True
            if self.decoration:
                r['decoration'] = self.decoration
            if is_admin and self.deleted:
                r['deleted'] = self.get_deleted().name
            if is_mod:
                if self.approved:
                    r['approved'] = self.get_approved().name
                elif self.removed:
                    r['removed'] = self.get_removed().name

        r['text_html'] = h.markdown(r['text'])

        return r

    @property
    def replies(self):
        return getattr(self, '_replies', ())

    def update_counts(self, value):
        '''
        Update fields in parent Post and Comments counting this Comment

        value:
            Value to add to counting fields. Either 1 or -1.
        '''
        Session.update(Post, { '_id': self.post },
            { '$inc': { 'num_comments': value } })

        if self.parents:
            Session.update(Comment, { '_id': self.parents[-1] },
                { '$inc': { 'num_replies': value } })
            Session.update(Comment, { '_id': { '$in': self.parents } },
                { '$inc': { 'num_children': value } }, multi = True)

    @classmethod
    def walk_list(cls, comments):
        [(yield i) for cmt in comments
            for i in cmt.walk()]

    def walk(self):
        yield self

        for r in self.replies:
            [(yield i) for i in r.walk()]

mongo.Index(Comment, 'author')
mongo.Index(Comment, 'created')
mongo.Index(Comment, 'depth')
mongo.Index(Comment, 'parents')

class Report(ModelBase, mongo.Document, Renderable):

    MAX_LENGTH = 2 << 10

    user = mongo.Field(str, required = True)
    text = mongo.Field(unicode)
    created = mongo.Field(datetime.datetime, required = True)

    def __init__(self, user, text):
        super(Report, self).__init__()
        self.user = user._id
        self.set_text(text)
        self.created = datetime.datetime.utcnow()

    def get_user(self):
        return User.get(self.user)

    def render(self, user):
        text = self.text or ''
        return {
            'id': self._id,
            'reported_by': User.get(self.user).name,
            'text': text,
            'text_html': h.markdown(text),
        }

    def set_text(self, text):
        if len(text) > self.MAX_LENGTH:
            raise ClientError('Text must be no more than {max} characters'
                .format(max = self.MAX_LENGTH))
        self.text = text

class CommentReport(Report):
    _collection = 'comment_report'

    community = mongo.Field(str, required = True)
    comment = mongo.Field(str, required = True)

    def __init__(self, comment, user, text):
        super(CommentReport, self).__init__(user, text)
        self.comment = comment._id
        self.community = comment.community

    def render(self, user):
        return h.merge(super(CommentReport, self).render(user), {
            'comment': Comment.get(self.comment).render(user),
        })

mongo.Index(CommentReport, 'comment')
mongo.Index(CommentReport, 'community')
mongo.Index(CommentReport, ('user', 'comment'), unique = True)

class CommunityReport(Report):
    _collection = 'community_report'

    community = mongo.Field(str, required = True)

    def __init__(self, cmty, user, text):
        super(CommunityReport, self).__init__(user, text)
        self.community = cmty._id

    def render(self, user):
        return h.merge(super(CommunityReport, self).render(user), {
            'community': Community.get(self.community).name,
        })

mongo.Index(CommunityReport, 'community')
mongo.Index(CommunityReport, ('user', 'community'), unique = True)

class PostReport(Report):
    _collection = 'post_report'

    community = mongo.Field(str, required = True)
    post = mongo.Field(str, required = True)

    def __init__(self, post, user, text):
        super(PostReport, self).__init__(user, text)
        self.post = post._id
        self.community = post.community

    def render(self, user):
        return h.merge(super(PostReport, self).render(user), {
            'post': Post.get(self.post).render(user),
        })

mongo.Index(PostReport, 'community')
mongo.Index(PostReport, 'post')
mongo.Index(PostReport, ('user', 'post'), unique = True)

class Message(ModelBase, mongo.Document, Renderable):
    _collection = 'message'
    _polymorphic = 'type'
    _id_factory = lambda o: unique_id('message')

    ## Owner of the message (sender of SentMessage, recipient of all others)
    owner = mongo.Field(str)
    ## Opposite user of the message
    other = mongo.Field(str)
    ## Whether this message has not been seen by the owner
    unread = mongo.Field(bool, default = True)
    ## Time Message was sent
    delivered = mongo.Field(datetime.datetime, required = True)
    ## Type of message
    type = mongo.Field(str, required = True)

    def get_owner(self):
        if self.owner:
            return User.get(self.owner)

    def get_other(self):
        if self.other:
            return User.get(self.other)

    def mark_read(self):
        Session.update(Message, { '_id': self._id },
            { '$unset': { 'unread': 1 } })

    def mark_unread(self):
        Session.update(Message, { '_id': self._id },
            { '$set': { 'unread': True } })

    @property
    def permalink(self):
        if not hasattr(self, '_permalink'):
            self._permalink = h.url('/message/message/' + self._id)
        return self._permalink

    def render(self, user):
        r = {
            'id': self._id,
            'delivered': self.delivered,
            'type': self.type,
        }

        if self.unread:
            r['unread'] = True

        return r

mongo.Index(Message, 'other', sparse = True)
mongo.Index(Message, 'owner', sparse = True)
mongo.Index(Message, 'unread', sparse = True)

class UserMessage(Message):
    _polymorphic_identity = 'pm'

    MAX_SUBJECT_LENGTH = 128
    MAX_LENGTH = 10 << 10

    ## If present, Community whose moderators sent the message
    owner_mod = mongo.Field(str)
    ## If present, Community whose moderators received the message
    other_mod = mongo.Field(str)
    ## Community whose moderators are on the opposite side of the message
    other_community = mongo.Field(str)
    ## Message subject
    subject = mongo.Field(unicode)
    ## Message text
    text = mongo.Field(unicode, required = True)

    def __init__(self, subject, text):
        super(UserMessage, self).__init__()
        self.set_subject(subject)
        self.set_text(text)

    def get_owner_mod(self):
        if self.owner_mod:
            return Community.get(self.owner_mod)

    def get_other_mod(self):
        if self.other_mod:
            return Community.get(self.other_mod)

    def set_subject(self, subject):
        if subject:
            if len(subject) > self.MAX_SUBJECT_LENGTH:
                raise ClientError('Subject must be no more than {max} characters'
                    .format(max = self.MAX_SUBJECT_LENGTH))
        self.subject = subject

    def set_text(self, text):
        if len(text) > self.MAX_LENGTH:
            raise ClientError('Text must be no more than {max} characters'
                .format(max = self.MAX_LENGTH))
        self.text = text

    def render(self, user):
        r = h.merge(super(UserMessage, self).render(user), {
            'sender': self.get_other().name,
            'subject': self.subject or '',
            'text': self.text,
            'text_html': h.markdown(self.text),
        })

        if self.owner_mod:
            r['to_mod'] = self.get_owner_mod().name
        if self.other_mod:
            r['from_mod'] = self.get_other_mod().name

        return r

mongo.Index(UserMessage, 'other_mod', sparse = True)
mongo.Index(UserMessage, 'owner_mod', sparse = True)

class SentMessage(Message):
    _polymorphic_identity = 'sent'

    ## If present, Community whose moderators sent the message
    owner_mod = mongo.Field(str)
    ## If present, Community whose moderators received the message
    other_mod = mongo.Field(str)
    ## Message subject
    subject = mongo.Field(unicode)
    ## Message text
    text = mongo.Field(unicode, required = True)

    @classmethod
    def from_message(cls, message):
        return cls(owner = message.other, other = message.owner,
            owner_mod = message.other_mod, other_mod = message.owner_mod,
            subject = message.subject, text = message.text, unread = None,
            delivered = message.delivered or datetime.datetime.utcnow())

    def get_owner_mod(self):
        if self.owner_mod:
            return Community.get(self.owner_mod)

    def get_other_mod(self):
        if self.other_mod:
            return Community.get(self.other_mod)

    def render(self, user):
        r = h.merge(super(SentMessage, self).render(user), {
            'recipient': self.get_other().name,
            'subject': self.subject or '',
            'text': self.text,
            'text_html': h.markdown(self.text),
        })

        if self.owner_mod:
            r['from_mod'] = self.get_owner_mod().name
        if self.other_mod:
            r['to_mod'] = self.get_other_mod().name

        return r

class ReplyMessage(Message):
    _polymorphic_identity = 'reply'

    ## Community to which post and comment belong
    community = mongo.Field(str, required = True)
    ## Post containing the reply
    post = mongo.Field(str, required = True)
    ## Comment being replied to, None for a root comment
    comment = mongo.Field(str)
    ## Reply to comment or post
    reply = mongo.Field(str, required = True)

    def get_comment(self):
        if self.comment:
            return Comment.get(self.comment)

    def get_community(self):
        return Community.get(self.community)

    def get_post(self):
        return Post.get(self.post)

    def get_reply(self):
        return Comment.get(self.reply)

    def render(self, user):
        r = h.merge(super(ReplyMessage, self).render(user), {
            'post': self.get_post().render(user),
            'reply': self.get_reply().render(user)
        })

        if self.comment:
            r['comment'] = self.get_comment().render(user)

        return r

mongo.Index(ReplyMessage, 'comment')
mongo.Index(ReplyMessage, 'community', sparse = True)