1# Copyright (c) 2012-2016 Seafile Ltd.
2import logging
3from django.conf import settings
4from seahub.utils import is_pro_version
5
6from seaserv import ccnet_api
7
8logger = logging.getLogger(__name__)
9
10def get_license_path():
11    return settings.LICENSE_PATH
12
13def parse_license():
14    """Parse license file and return dict.
15
16    Arguments:
17    - `license_path`:
18
19    Returns:
20    e.g.
21
22    {'Hash': 'fdasfjl',
23    'Name': 'seafile official',
24    'Licencetype': 'User',
25    'LicenceKEY': '123',
26    'Expiration': '2016-3-2',
27    'MaxUsers': '1000000',
28    'ProductID': 'Seafile server for Windows'
29    }
30
31    """
32    ret = {}
33    lines = []
34    try:
35        with open(get_license_path(), encoding='utf-8') as f:
36            lines = f.readlines()
37    except Exception as e:
38        logger.warn(e)
39        return {}
40
41    for line in lines:
42        if len(line.split('=')) == 2:
43            k, v = line.split('=')
44            ret[k.strip()] = v.strip().strip('"')
45
46    return ret
47
48def user_number_over_limit(new_users=0):
49    logger = logging.getLogger(__name__)
50    if is_pro_version():
51        try:
52            # get license user limit
53            license_dict = parse_license()
54            max_users = int(license_dict.get('MaxUsers', 3))
55
56            # get active user number
57            active_db_users = ccnet_api.count_emailusers('DB')
58            active_ldap_users = ccnet_api.count_emailusers('LDAP')
59            active_users = active_db_users + active_ldap_users if \
60                           active_ldap_users > 0 else active_db_users
61
62            if new_users < 0:
63                logger.debug('`new_users` must be greater or equal to 0.')
64                return False
65            elif new_users == 0:
66                return active_users >= max_users
67            else:
68                return active_users + new_users > max_users
69
70        except Exception as e:
71            logger.error(e)
72            return False
73    else:
74        return False
75