1# Copyright (c) 2012-2016 Seafile Ltd. 2 3import logging 4logger = logging.getLogger(__name__) 5 6UNIT_KB = 'kb' 7UNIT_MB = 'mb' 8UNIT_GB = 'gb' 9UNIT_TB = 'tb' 10UNIT_PB = 'pb' 11 12UNIT_KIB = 'kib' 13UNIT_MIB = 'mib' 14UNIT_GIB = 'gib' 15UNIT_TIB = 'tib' 16UNIT_PIB = 'pib' 17 18def get_file_size_unit(unit_type): 19 """ 20 File size unit according to https://en.wikipedia.org/wiki/Kibibyte. 21 """ 22 table = { 23 # decimal 24 UNIT_KB: 10 ** 3, 25 UNIT_MB: 10 ** 6, 26 UNIT_GB: 10 ** 9, 27 UNIT_TB: 10 ** 12, 28 UNIT_PB: 10 ** 15, 29 # binary 30 UNIT_KIB: 1 << 10, 31 UNIT_MIB: 1 << 20, 32 UNIT_GIB: 1 << 30, 33 UNIT_TIB: 1 << 40, 34 UNIT_PIB: 1 << 50, 35 } 36 37 unit_type = unit_type.lower() 38 if unit_type not in list(table.keys()): 39 raise TypeError('Invalid unit type') 40 41 return table.get(unit_type) 42 43def get_quota_from_string(quota_str): 44 quota_str = quota_str.lower() 45 if quota_str.endswith('g'): 46 quota = int(quota_str[:-1]) * get_file_size_unit('gb') 47 elif quota_str.endswith('m'): 48 quota = int(quota_str[:-1]) * get_file_size_unit('mb') 49 else: 50 return None 51 52 return quota 53 54def byte_to_mb(byte): 55 56 if byte < 0: 57 return '' 58 59 try: 60 unit = get_file_size_unit(UNIT_MB) 61 return round(float(byte)/unit, 2) 62 except Exception as e: 63 logger.error(e) 64 return '' 65