65 lines
2.3 KiB
Python
65 lines
2.3 KiB
Python
"""Base classes for plugin checks"""
|
|
# Copyright © 2020 Brett Smith
|
|
#
|
|
# This program is free software: you can redistribute it and/or modify
|
|
# it under the terms of the GNU Affero General Public License as published by
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
# (at your option) any later version.
|
|
#
|
|
# This program is distributed in the hope that it will be useful,
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
# GNU Affero General Public License for more details.
|
|
#
|
|
# You should have received a copy of the GNU Affero General Public License
|
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
from . import errors as errormod
|
|
|
|
class PostingChecker:
|
|
ACCOUNTS = ('',)
|
|
VALUES_ENUM = {}
|
|
|
|
def _meta_get(self, txn, post, key, default=None):
|
|
try:
|
|
return post.meta[key]
|
|
except (KeyError, TypeError):
|
|
return txn.meta.get(key, default)
|
|
|
|
def _meta_set(self, post, key, value):
|
|
if post.meta is None:
|
|
post.meta = {}
|
|
post.meta[key] = value
|
|
|
|
def _default_value(self, txn, post):
|
|
raise errormod.InvalidMetadataError(txn, post, self.METADATA_KEY)
|
|
|
|
def _should_check(self, txn, post):
|
|
ok = True
|
|
if isinstance(self.ACCOUNTS, tuple):
|
|
ok = ok and post.account.startswith(self.ACCOUNTS)
|
|
else:
|
|
ok = ok and re.search(self.ACCOUNTS, post.account)
|
|
return ok
|
|
|
|
def check(self, txn, post):
|
|
errors = []
|
|
if not self._should_check(txn, post):
|
|
return errors
|
|
source_value = self._meta_get(txn, post, self.METADATA_KEY)
|
|
set_value = source_value
|
|
if source_value is None:
|
|
try:
|
|
set_value = self._default_value(txn, post)
|
|
except errormod._BaseError as error:
|
|
errors.append(error)
|
|
else:
|
|
try:
|
|
set_value = self.VALUES_ENUM[source_value].value
|
|
except KeyError:
|
|
errors.append(errormod.InvalidMetadataError(
|
|
txn, post, self.METADATA_KEY, source_value,
|
|
))
|
|
if not errors:
|
|
self._meta_set(post, self.METADATA_KEY, set_value)
|
|
return errors
|