| Total Complexity | 15 |
| Total Lines | 63 |
| Duplicated Lines | 0 % |
| Coverage | 97.56% |
| Changes | 0 | ||
| 1 | 1 | import yorm |
|
|
|
|||
| 2 | from yorm.types import List, Object |
||
| 3 | 1 | import profanityfilter |
|
| 4 | 1 | import log |
|
| 5 | 1 | ||
| 6 | |||
| 7 | @yorm.attr(items=List.of_type(Object)) |
||
| 8 | 1 | @yorm.sync("data/cache/{self.name}.yml", auto_resolve=True) |
|
| 9 | class Cache: |
||
| 10 | |||
| 11 | 1 | SIZE = 100 |
|
| 12 | 1 | ||
| 13 | def __init__(self, filtered=True): |
||
| 14 | self.items = [] |
||
| 15 | 1 | self.disabled = False |
|
| 16 | self.filtered = filtered |
||
| 17 | 1 | ||
| 18 | 1 | @property |
|
| 19 | 1 | def name(self): |
|
| 20 | 1 | return 'filtered' if self.filtered else 'unfiltered' |
|
| 21 | |||
| 22 | 1 | def add(self, **kwargs): |
|
| 23 | if self._skip_cache(kwargs): |
||
| 24 | 1 | return |
|
| 25 | |||
| 26 | 1 | log.info("Caching: %s", kwargs) |
|
| 27 | 1 | ||
| 28 | 1 | self.items.insert(0, kwargs) |
|
| 29 | while len(self.items) > self.SIZE: |
||
| 30 | 1 | self.items.pop() |
|
| 31 | |||
| 32 | 1 | def get(self, index): |
|
| 33 | 1 | log.info("Getting cache index: %s", index) |
|
| 34 | |||
| 35 | try: |
||
| 36 | 1 | data = self.items[index] |
|
| 37 | 1 | except IndexError: |
|
| 38 | data = {} |
||
| 39 | 1 | ||
| 40 | 1 | log.info("Retrieved cache: %s", data) |
|
| 41 | 1 | ||
| 42 | 1 | return data |
|
| 43 | |||
| 44 | 1 | def _skip_cache(self, kwargs): |
|
| 45 | if self.disabled: |
||
| 46 | 1 | log.debug("Caching disabled") |
|
| 47 | return True |
||
| 48 | 1 | ||
| 49 | 1 | if kwargs in self.items: |
|
| 50 | 1 | log.debug("Already cached: %s", kwargs) |
|
| 51 | 1 | return True |
|
| 52 | |||
| 53 | 1 | if self.filtered: |
|
| 54 | 1 | ||
| 55 | 1 | if kwargs['key'] == 'custom' or kwargs.get('alt'): |
|
| 56 | log.debug("Skipped caching of custom background: %s", kwargs) |
||
| 57 | 1 | return True |
|
| 58 | if profanityfilter.is_profane(kwargs['path']): |
||
| 59 | 1 | log.debug("Skipped caching of profane content: %s", kwargs) |
|
| 60 | 1 | return True |
|
| 61 | 1 | ||
| 62 | return False |
||
| 63 |