1# grid.py - functions for handling Global Release Identifier (GRid) numbers
2#
3# Copyright (C) 2010, 2011, 2012, 2013 Arthur de Jong
4#
5# This library is free software; you can redistribute it and/or
6# modify it under the terms of the GNU Lesser General Public
7# License as published by the Free Software Foundation; either
8# version 2.1 of the License, or (at your option) any later version.
9#
10# This library is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13# Lesser General Public License for more details.
14#
15# You should have received a copy of the GNU Lesser General Public
16# License along with this library; if not, write to the Free Software
17# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18# 02110-1301 USA
19
20"""GRid (Global Release Identifier).
21
22The Global Release Identifier is used to identify releases of digital
23sound recordings and uses the ISO 7064 Mod 37, 36 algorithm to verify the
24correctness of the number.
25
26>>> validate('A12425GABC1234002M')
27'A12425GABC1234002M'
28>>> validate('Grid: A1-2425G-ABC1234002-M')
29'A12425GABC1234002M'
30>>> validate('A1-2425G-ABC1234002-Q') # incorrect check digit
31Traceback (most recent call last):
32    ...
33InvalidChecksum: ...
34>>> compact('A1-2425G-ABC1234002-M')
35'A12425GABC1234002M'
36>>> format('A12425GABC1234002M')
37'A1-2425G-ABC1234002-M'
38"""
39
40from stdnum.exceptions import *
41from stdnum.util import clean
42
43
44def compact(number):
45    """Convert the GRid to the minimal representation. This strips the
46    number of any valid separators and removes surrounding whitespace."""
47    number = clean(number, ' -').strip().upper()
48    if number.startswith('GRID:'):
49        number = number[5:]
50    return number
51
52
53def validate(number):
54    """Check if the number is a valid GRid."""
55    from stdnum.iso7064 import mod_37_36
56    number = compact(number)
57    if len(number) != 18:
58        raise InvalidLength()
59    return mod_37_36.validate(number)
60
61
62def is_valid(number):
63    """Check if the number is a valid GRid."""
64    try:
65        return bool(validate(number))
66    except ValidationError:
67        return False
68
69
70def format(number, separator='-'):
71    """Reformat the number to the standard presentation format."""
72    number = compact(number)
73    number = (number[0:2], number[2:7], number[7:17], number[17:])
74    return separator.join(x for x in number if x)
75