diff --git a/allianceauth/analytics/migrations/0001_initial.py b/allianceauth/analytics/migrations/0001_initial.py index c5a1f33a..e6385469 100644 --- a/allianceauth/analytics/migrations/0001_initial.py +++ b/allianceauth/analytics/migrations/0001_initial.py @@ -1,8 +1,9 @@ # Generated by Django 3.1.4 on 2020-12-30 13:11 -from django.db import migrations, models import uuid +from django.db import migrations, models + class Migration(migrations.Migration): diff --git a/allianceauth/analytics/migrations/0002_add_AA_Team_Token.py b/allianceauth/analytics/migrations/0002_add_AA_Team_Token.py index 13071b8a..4acb725f 100644 --- a/allianceauth/analytics/migrations/0002_add_AA_Team_Token.py +++ b/allianceauth/analytics/migrations/0002_add_AA_Team_Token.py @@ -21,7 +21,7 @@ def remove_aa_team_token(apps, schema_editor): # Have to define some code to remove this identifier # In case of migration rollback? Tokens = apps.get_model('analytics', 'AnalyticsTokens') - token = Tokens.objects.filter(token="UA-186249766-2").delete() + Tokens.objects.filter(token="UA-186249766-2").delete() class Migration(migrations.Migration): diff --git a/allianceauth/analytics/migrations/0003_Generate_Identifier.py b/allianceauth/analytics/migrations/0003_Generate_Identifier.py index 5c4daba8..08df9ca8 100644 --- a/allianceauth/analytics/migrations/0003_Generate_Identifier.py +++ b/allianceauth/analytics/migrations/0003_Generate_Identifier.py @@ -1,6 +1,5 @@ # Generated by Django 3.1.4 on 2020-12-30 08:53 -from uuid import uuid4 from django.db import migrations diff --git a/allianceauth/analytics/migrations/0008_add_AA_GA-4_Team_Token .py b/allianceauth/analytics/migrations/0008_add_AA_GA-4_Team_Token .py index efc816ac..db7e8afd 100644 --- a/allianceauth/analytics/migrations/0008_add_AA_GA-4_Team_Token .py +++ b/allianceauth/analytics/migrations/0008_add_AA_GA-4_Team_Token .py @@ -1,7 +1,7 @@ # Generated by Django 3.1.4 on 2020-12-30 08:53 -from django.db import migrations from django.core.exceptions import ObjectDoesNotExist +from django.db import migrations def add_aa_team_token(apps, schema_editor): @@ -51,7 +51,7 @@ def remove_aa_team_token(apps, schema_editor): # Have to define some code to remove this identifier # In case of migration rollback? Tokens = apps.get_model('analytics', 'AnalyticsTokens') - token = Tokens.objects.filter(token="G-6LYSMYK8DE").delete() + Tokens.objects.filter(token="G-6LYSMYK8DE").delete() class Migration(migrations.Migration): diff --git a/allianceauth/analytics/models.py b/allianceauth/analytics/models.py index ddee495a..72d11abe 100644 --- a/allianceauth/analytics/models.py +++ b/allianceauth/analytics/models.py @@ -1,9 +1,9 @@ -from django.db import models -from django.core.exceptions import ValidationError -from django.utils.translation import gettext_lazy as _ - from uuid import uuid4 +from django.core.exceptions import ValidationError +from django.db import models +from django.utils.translation import gettext_lazy as _ + class AnalyticsIdentifier(models.Model): @@ -11,6 +11,9 @@ class AnalyticsIdentifier(models.Model): default=uuid4, editable=False) + def __str__(self) -> str: + return f"{self.identifier}" + def save(self, *args, **kwargs): if not self.pk and AnalyticsIdentifier.objects.exists(): # Force a single object @@ -31,3 +34,6 @@ class AnalyticsTokens(models.Model): token = models.CharField(max_length=254, blank=False) secret = models.CharField(max_length=254, blank=True) send_stats = models.BooleanField(default=False) + + def __str__(self) -> str: + return self.name diff --git a/allianceauth/analytics/tasks.py b/allianceauth/analytics/tasks.py index cc9ef160..00ed8202 100644 --- a/allianceauth/analytics/tasks.py +++ b/allianceauth/analytics/tasks.py @@ -1,16 +1,16 @@ -import requests import logging -from django.conf import settings -from django.apps import apps + +import requests from celery import shared_task -from .models import AnalyticsTokens, AnalyticsIdentifier -from .utils import ( - install_stat_addons, - install_stat_tokens, - install_stat_users) + +from django.apps import apps +from django.conf import settings from allianceauth import __version__ +from .models import AnalyticsIdentifier, AnalyticsTokens +from .utils import install_stat_addons, install_stat_tokens, install_stat_users + logger = logging.getLogger(__name__) BASE_URL = "https://www.google-analytics.com" diff --git a/allianceauth/analytics/tests/test_models.py b/allianceauth/analytics/tests/test_models.py index 452c4eaa..b430f03d 100644 --- a/allianceauth/analytics/tests/test_models.py +++ b/allianceauth/analytics/tests/test_models.py @@ -1,10 +1,9 @@ -from allianceauth.analytics.models import AnalyticsIdentifier -from django.core.exceptions import ValidationError - -from django.test.testcases import TestCase - from uuid import UUID, uuid4 +from django.core.exceptions import ValidationError +from django.test.testcases import TestCase + +from allianceauth.analytics.models import AnalyticsIdentifier # Identifiers uuid_1 = "ab33e241fbf042b6aa77c7655a768af7" diff --git a/allianceauth/analytics/tests/test_tasks.py b/allianceauth/analytics/tests/test_tasks.py index 0a542e23..08a5676a 100644 --- a/allianceauth/analytics/tests/test_tasks.py +++ b/allianceauth/analytics/tests/test_tasks.py @@ -2,12 +2,9 @@ import requests_mock from django.test.utils import override_settings -from allianceauth.analytics.tasks import ( - analytics_event, - send_ga_tracking_celery_event) +from allianceauth.analytics.tasks import analytics_event, send_ga_tracking_celery_event from allianceauth.utils.testing import NoSocketsTestCase - GOOGLE_ANALYTICS_DEBUG_URL = 'https://www.google-analytics.com/debug/mp/collect' diff --git a/allianceauth/analytics/tests/test_utils.py b/allianceauth/analytics/tests/test_utils.py index b9a22329..838513d8 100644 --- a/allianceauth/analytics/tests/test_utils.py +++ b/allianceauth/analytics/tests/test_utils.py @@ -1,10 +1,9 @@ from django.apps import apps -from allianceauth.authentication.models import User -from esi.models import Token -from allianceauth.analytics.utils import install_stat_users, install_stat_tokens, install_stat_addons - from django.test.testcases import TestCase +from allianceauth.analytics.utils import install_stat_addons, install_stat_users +from allianceauth.authentication.models import User + def create_testdata(): User.objects.all().delete() diff --git a/allianceauth/analytics/utils.py b/allianceauth/analytics/utils.py index e8c57927..d09cc65c 100644 --- a/allianceauth/analytics/utils.py +++ b/allianceauth/analytics/utils.py @@ -1,7 +1,9 @@ from django.apps import apps -from allianceauth.authentication.models import User + from esi.models import Token +from allianceauth.authentication.models import User + def install_stat_users() -> int: """Count and Return the number of User accounts diff --git a/allianceauth/apps.py b/allianceauth/apps.py index 098f50ba..1191fed9 100644 --- a/allianceauth/apps.py +++ b/allianceauth/apps.py @@ -1,5 +1,4 @@ from django.apps import AppConfig -from django.core.checks import Warning, Error, register class AllianceAuthConfig(AppConfig): diff --git a/allianceauth/authentication/admin.py b/allianceauth/authentication/admin.py index 6da117e2..9729e200 100644 --- a/allianceauth/authentication/admin.py +++ b/allianceauth/authentication/admin.py @@ -1,43 +1,21 @@ from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin -from django.contrib.auth.models import Group -from django.contrib.auth.models import Permission as BasePermission -from django.contrib.auth.models import User as BaseUser +from django.contrib.auth.models import Group, Permission as BasePermission, User as BaseUser from django.db.models import Count, Q from django.db.models.functions import Lower -from django.db.models.signals import ( - m2m_changed, - post_delete, - post_save, - pre_delete, - pre_save -) +from django.db.models.signals import m2m_changed, post_delete, post_save, pre_delete, pre_save from django.dispatch import receiver from django.urls import reverse from django.utils.html import format_html from django.utils.text import slugify -from allianceauth.authentication.models import ( - CharacterOwnership, - OwnershipRecord, - State, - UserProfile, - get_guest_state -) -from allianceauth.eveonline.models import ( - EveAllianceInfo, - EveCharacter, - EveCorporationInfo, - EveFactionInfo -) +from allianceauth.authentication.models import CharacterOwnership, OwnershipRecord, State, UserProfile, get_guest_state +from allianceauth.eveonline.models import EveAllianceInfo, EveCharacter, EveCorporationInfo, EveFactionInfo from allianceauth.eveonline.tasks import update_character from allianceauth.hooks import get_hooks from allianceauth.services.hooks import ServicesHook -from .app_settings import ( - AUTHENTICATION_ADMIN_USERS_MAX_CHARS, - AUTHENTICATION_ADMIN_USERS_MAX_GROUPS -) +from .app_settings import AUTHENTICATION_ADMIN_USERS_MAX_CHARS, AUTHENTICATION_ADMIN_USERS_MAX_GROUPS from .forms import UserChangeForm, UserProfileForm @@ -132,10 +110,7 @@ def user_username(obj): To be used for all user based admin lists """ link = reverse( - 'admin:{}_{}_change'.format( - obj._meta.app_label, - type(obj).__name__.lower() - ), + f'admin:{obj._meta.app_label}_{type(obj).__name__.lower()}_change', args=(obj.pk,) ) user_obj = obj.user if hasattr(obj, 'user') else obj @@ -548,7 +523,7 @@ class BaseOwnershipAdmin(admin.ModelAdmin): def get_readonly_fields(self, request, obj=None): if obj and obj.pk: return 'owner_hash', 'character' - return tuple() + return () @admin.register(OwnershipRecord) diff --git a/allianceauth/authentication/app_settings.py b/allianceauth/authentication/app_settings.py index 449bef08..e06d1eb8 100644 --- a/allianceauth/authentication/app_settings.py +++ b/allianceauth/authentication/app_settings.py @@ -25,7 +25,7 @@ def _clean_setting( if not required_type: required_type = type(default_value) - if min_value is None and required_type == int: + if min_value is None and required_type is int: min_value = 0 if (hasattr(settings, name) diff --git a/allianceauth/authentication/apps.py b/allianceauth/authentication/apps.py index 30e5a4f2..db52502c 100644 --- a/allianceauth/authentication/apps.py +++ b/allianceauth/authentication/apps.py @@ -1,5 +1,5 @@ from django.apps import AppConfig -from django.core.checks import register, Tags +from django.core.checks import Tags, register class AuthenticationConfig(AppConfig): diff --git a/allianceauth/authentication/auth_hooks.py b/allianceauth/authentication/auth_hooks.py index b29a3300..34d62fc3 100644 --- a/allianceauth/authentication/auth_hooks.py +++ b/allianceauth/authentication/auth_hooks.py @@ -1,6 +1,7 @@ -from allianceauth.hooks import DashboardItemHook from allianceauth import hooks -from .views import dashboard_characters, dashboard_esi_check, dashboard_groups, dashboard_admin +from allianceauth.hooks import DashboardItemHook + +from .views import dashboard_admin, dashboard_characters, dashboard_esi_check, dashboard_groups class UserCharactersHook(DashboardItemHook): diff --git a/allianceauth/authentication/backends.py b/allianceauth/authentication/backends.py index 260dd293..7c3b00a3 100644 --- a/allianceauth/authentication/backends.py +++ b/allianceauth/authentication/backends.py @@ -1,10 +1,9 @@ import logging from django.contrib.auth.backends import ModelBackend -from django.contrib.auth.models import User, Permission - -from .models import UserProfile, CharacterOwnership, OwnershipRecord +from django.contrib.auth.models import Permission, User +from .models import CharacterOwnership, OwnershipRecord, UserProfile logger = logging.getLogger(__name__) diff --git a/allianceauth/authentication/checks.py b/allianceauth/authentication/checks.py index 1a687b62..88ea1219 100644 --- a/allianceauth/authentication/checks.py +++ b/allianceauth/authentication/checks.py @@ -1,5 +1,5 @@ -from django.core.checks import Error from django.conf import settings +from django.core.checks import Error def check_login_scopes_setting(*args, **kwargs): diff --git a/allianceauth/authentication/core/celery_workers.py b/allianceauth/authentication/core/celery_workers.py index ceb1f40d..c1e91bfe 100644 --- a/allianceauth/authentication/core/celery_workers.py +++ b/allianceauth/authentication/core/celery_workers.py @@ -2,7 +2,6 @@ import itertools import logging -from typing import Optional from amqp.exceptions import ChannelError from celery import current_app diff --git a/allianceauth/authentication/decorators.py b/allianceauth/authentication/decorators.py index 81403615..e54f34b0 100644 --- a/allianceauth/authentication/decorators.py +++ b/allianceauth/authentication/decorators.py @@ -1,15 +1,11 @@ -from django.urls import include -from django.contrib.auth.decorators import user_passes_test -from django.core.exceptions import PermissionDenied -from functools import wraps -from typing import Optional from collections.abc import Callable, Iterable +from functools import wraps -from django.urls import include from django.contrib import messages from django.contrib.auth.decorators import login_required, user_passes_test from django.core.exceptions import PermissionDenied from django.shortcuts import redirect +from django.urls import include from django.utils.translation import gettext_lazy as _ diff --git a/allianceauth/authentication/forms.py b/allianceauth/authentication/forms.py index fabff9d9..a4959abd 100644 --- a/allianceauth/authentication/forms.py +++ b/allianceauth/authentication/forms.py @@ -60,7 +60,7 @@ class UserChangeForm(BaseUserChangeForm): { "groups": _( "You are not allowed to add or remove these " - "restricted groups: %s" % restricted_names + "restricted groups: {}".format(restricted_names) ) } ) diff --git a/allianceauth/authentication/hmac_urls.py b/allianceauth/authentication/hmac_urls.py index 61bcd99b..9538582a 100644 --- a/allianceauth/authentication/hmac_urls.py +++ b/allianceauth/authentication/hmac_urls.py @@ -1,5 +1,6 @@ +from django.urls import include, path, re_path + from allianceauth.authentication import views -from django.urls import include, re_path, path urlpatterns = [ path('activate/complete/', views.activation_complete, name='registration_activation_complete'), diff --git a/allianceauth/authentication/management/commands/checkmains.py b/allianceauth/authentication/management/commands/checkmains.py index 5605687b..fad33078 100644 --- a/allianceauth/authentication/management/commands/checkmains.py +++ b/allianceauth/authentication/management/commands/checkmains.py @@ -1,4 +1,5 @@ from django.core.management.base import BaseCommand + from allianceauth.authentication.models import UserProfile @@ -11,8 +12,7 @@ class Command(BaseCommand): if profiles.exists(): for profile in profiles: self.stdout.write(self.style.ERROR( - '{} does not have an ownership. Resetting user {} main character.'.format(profile.main_character, - profile.user))) + f'{profile.main_character} does not have an ownership. Resetting user {profile.user} main character.')) profile.main_character = None profile.save() self.stdout.write(self.style.WARNING(f'Reset {profiles.count()} main characters.')) diff --git a/allianceauth/authentication/managers.py b/allianceauth/authentication/managers.py index 5959db96..3e16b3c2 100644 --- a/allianceauth/authentication/managers.py +++ b/allianceauth/authentication/managers.py @@ -1,7 +1,7 @@ import logging from django.db import transaction -from django.db.models import Manager, QuerySet, Q +from django.db.models import Manager, Q, QuerySet from allianceauth.eveonline.models import EveCharacter diff --git a/allianceauth/authentication/middleware.py b/allianceauth/authentication/middleware.py index ca28d92f..15f0b431 100644 --- a/allianceauth/authentication/middleware.py +++ b/allianceauth/authentication/middleware.py @@ -1,8 +1,8 @@ +import logging + from django.conf import settings from django.utils.deprecation import MiddlewareMixin -import logging - logger = logging.getLogger(__name__) diff --git a/allianceauth/authentication/migrations/0001_initial.py b/allianceauth/authentication/migrations/0001_initial.py index a7d3ff64..1c3a8842 100644 --- a/allianceauth/authentication/migrations/0001_initial.py +++ b/allianceauth/authentication/migrations/0001_initial.py @@ -1,8 +1,8 @@ # Generated by Django 1.10.1 on 2016-09-05 21:38 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/authentication/migrations/0004_create_permissions.py b/allianceauth/authentication/migrations/0004_create_permissions.py index 1f938d21..7b2042f9 100644 --- a/allianceauth/authentication/migrations/0004_create_permissions.py +++ b/allianceauth/authentication/migrations/0004_create_permissions.py @@ -2,6 +2,7 @@ from django.db import migrations + def create_permissions(apps, schema_editor): User = apps.get_model('auth', 'User') ContentType = apps.get_model('contenttypes', 'ContentType') diff --git a/allianceauth/authentication/migrations/0005_delete_perms.py b/allianceauth/authentication/migrations/0005_delete_perms.py index e870b8cd..d61a27af 100644 --- a/allianceauth/authentication/migrations/0005_delete_perms.py +++ b/allianceauth/authentication/migrations/0005_delete_perms.py @@ -2,6 +2,7 @@ from django.db import migrations + def delete_permissions(apps, schema_editor): User = apps.get_model('auth', 'User') ContentType = apps.get_model('contenttypes', 'ContentType') diff --git a/allianceauth/authentication/migrations/0010_only_one_authservicesinfo.py b/allianceauth/authentication/migrations/0010_only_one_authservicesinfo.py index a88bb301..86d6175c 100644 --- a/allianceauth/authentication/migrations/0010_only_one_authservicesinfo.py +++ b/allianceauth/authentication/migrations/0010_only_one_authservicesinfo.py @@ -2,6 +2,7 @@ from django.db import migrations + def count_completed_fields(model): return len([True for key, value in model.__dict__.items() if bool(value)]) diff --git a/allianceauth/authentication/migrations/0011_authservicesinfo_user_onetoonefield.py b/allianceauth/authentication/migrations/0011_authservicesinfo_user_onetoonefield.py index d12f2875..e1c28b19 100644 --- a/allianceauth/authentication/migrations/0011_authservicesinfo_user_onetoonefield.py +++ b/allianceauth/authentication/migrations/0011_authservicesinfo_user_onetoonefield.py @@ -1,8 +1,8 @@ # Generated by Django 1.10.1 on 2017-01-07 07:11 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/authentication/migrations/0012_remove_add_delete_authservicesinfo_permissions.py b/allianceauth/authentication/migrations/0012_remove_add_delete_authservicesinfo_permissions.py index 60fcc189..7949ab59 100644 --- a/allianceauth/authentication/migrations/0012_remove_add_delete_authservicesinfo_permissions.py +++ b/allianceauth/authentication/migrations/0012_remove_add_delete_authservicesinfo_permissions.py @@ -1,6 +1,7 @@ # Generated by Django 1.10.5 on 2017-01-12 00:59 -from django.db import migrations, models +from django.db import migrations + def remove_permissions(apps, schema_editor): ContentType = apps.get_model('contenttypes', 'ContentType') diff --git a/allianceauth/authentication/migrations/0013_service_modules.py b/allianceauth/authentication/migrations/0013_service_modules.py index f046905c..871e070b 100644 --- a/allianceauth/authentication/migrations/0013_service_modules.py +++ b/allianceauth/authentication/migrations/0013_service_modules.py @@ -1,9 +1,9 @@ # Generated by Django 1.10.2 on 2016-12-11 23:14 -from django.db import migrations - import logging +from django.db import migrations + logger = logging.getLogger(__name__) diff --git a/allianceauth/authentication/migrations/0015_user_profiles.py b/allianceauth/authentication/migrations/0015_user_profiles.py index 10ba691c..48ecdefb 100644 --- a/allianceauth/authentication/migrations/0015_user_profiles.py +++ b/allianceauth/authentication/migrations/0015_user_profiles.py @@ -1,11 +1,12 @@ # Generated by Django 1.10.5 on 2017-03-22 23:09 -import allianceauth.authentication.models import django.db.models.deletion from django.conf import settings from django.contrib.auth.hashers import make_password from django.db import migrations, models +import allianceauth.authentication.models + def create_guest_state(apps, schema_editor): State = apps.get_model('authentication', 'State') diff --git a/allianceauth/authentication/migrations/0016_ownershiprecord.py b/allianceauth/authentication/migrations/0016_ownershiprecord.py index b2df6d8d..91887454 100644 --- a/allianceauth/authentication/migrations/0016_ownershiprecord.py +++ b/allianceauth/authentication/migrations/0016_ownershiprecord.py @@ -1,8 +1,8 @@ # Generated by Django 2.0.4 on 2018-04-14 18:28 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion def create_initial_records(apps, schema_editor): diff --git a/allianceauth/authentication/models.py b/allianceauth/authentication/models.py index 714f1934..dd22883d 100644 --- a/allianceauth/authentication/models.py +++ b/allianceauth/authentication/models.py @@ -1,11 +1,11 @@ import logging -from django.contrib.auth.models import User, Permission +from django.contrib.auth.models import Permission, User from django.db import models, transaction from django.utils.translation import gettext_lazy as _ -from allianceauth.eveonline.models import EveCharacter, EveCorporationInfo, EveAllianceInfo, EveFactionInfo + +from allianceauth.eveonline.models import EveAllianceInfo, EveCharacter, EveCorporationInfo, EveFactionInfo from allianceauth.notifications import notify -from django.conf import settings from .managers import CharacterOwnershipManager, StateManager @@ -60,8 +60,7 @@ def get_guest_state_pk(): class UserProfile(models.Model): - class Meta: - default_permissions = ('change',) + class Language(models.TextChoices): """ @@ -108,10 +107,15 @@ class UserProfile(models.Model): _("Theme"), max_length=200, blank=True, - null=True, help_text="Bootstrap 5 Themes from https://bootswatch.com/ or Community Apps" ) + class Meta: + default_permissions = ('change',) + + def __str__(self) -> str: + return str(self.user) + def assign_state(self, state=None, commit=True): if not state: state = State.objects.get_for_user(self.user) @@ -122,7 +126,7 @@ class UserProfile(models.Model): self.save(update_fields=['state']) notify( self.user, - _('State changed to: %s' % state), + _('State changed to: {}'.format(state)), _('Your user\'s state is now: %(state)s') % ({'state': state}), 'info' @@ -137,19 +141,18 @@ class UserProfile(models.Model): sender=self.__class__, user=self.user, state=self.state ) - def __str__(self): - return str(self.user) + class CharacterOwnership(models.Model): - class Meta: - default_permissions = ('change', 'delete') - ordering = ['user', 'character__character_name'] + character = models.OneToOneField(EveCharacter, on_delete=models.CASCADE, related_name='character_ownership') owner_hash = models.CharField(max_length=28, unique=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='character_ownerships') objects = CharacterOwnershipManager() - + class Meta: + default_permissions = ('change', 'delete') + ordering = ['user', 'character__character_name'] def __str__(self): return f"{self.user}: {self.character}" diff --git a/allianceauth/authentication/signals.py b/allianceauth/authentication/signals.py index dfb9ba1b..10c278a0 100644 --- a/allianceauth/authentication/signals.py +++ b/allianceauth/authentication/signals.py @@ -1,19 +1,16 @@ import logging -from .models import ( - CharacterOwnership, - UserProfile, - get_guest_state, - State, - OwnershipRecord) from django.contrib.auth.models import User from django.db.models import Q -from django.db.models.signals import pre_save, post_save, pre_delete, post_delete, m2m_changed -from django.dispatch import receiver, Signal +from django.db.models.signals import m2m_changed, post_delete, post_save, pre_delete, pre_save +from django.dispatch import Signal, receiver + from esi.models import Token from allianceauth.eveonline.models import EveCharacter +from .models import CharacterOwnership, OwnershipRecord, State, UserProfile, get_guest_state + logger = logging.getLogger(__name__) state_changed = Signal() @@ -108,8 +105,7 @@ def record_character_ownership(sender, instance, created, *args, **kwargs): def validate_main_character(sender, instance, *args, **kwargs): try: if instance.user.profile.main_character == instance.character: - logger.info("Ownership of a main character {} has been revoked. Resetting {} main character.".format( - instance.character, instance.user)) + logger.info(f"Ownership of a main character {instance.character} has been revoked. Resetting {instance.user} main character.") # clear main character as user no longer owns them instance.user.profile.main_character = None instance.user.profile.save() diff --git a/allianceauth/authentication/task_statistics/counters.py b/allianceauth/authentication/task_statistics/counters.py index 6d1f6175..3d146343 100644 --- a/allianceauth/authentication/task_statistics/counters.py +++ b/allianceauth/authentication/task_statistics/counters.py @@ -1,7 +1,7 @@ """Counters for Task Statistics.""" import datetime as dt -from typing import NamedTuple, Optional +from typing import NamedTuple from .event_series import EventSeries diff --git a/allianceauth/authentication/task_statistics/event_series.py b/allianceauth/authentication/task_statistics/event_series.py index 3eb96abe..b602ef04 100644 --- a/allianceauth/authentication/task_statistics/event_series.py +++ b/allianceauth/authentication/task_statistics/event_series.py @@ -2,7 +2,6 @@ import datetime as dt import logging -from typing import List, Optional from pytz import utc from redis import Redis diff --git a/allianceauth/authentication/task_statistics/signals.py b/allianceauth/authentication/task_statistics/signals.py index e9d7babc..5f12bfac 100644 --- a/allianceauth/authentication/task_statistics/signals.py +++ b/allianceauth/authentication/task_statistics/signals.py @@ -1,7 +1,11 @@ """Signals for Task Statistics.""" from celery.signals import ( - task_failure, task_internal_error, task_retry, task_success, worker_ready, + task_failure, + task_internal_error, + task_retry, + task_success, + worker_ready, ) from django.conf import settings diff --git a/allianceauth/authentication/task_statistics/tests/test_counters.py b/allianceauth/authentication/task_statistics/tests/test_counters.py index 2d2555aa..96494b4c 100644 --- a/allianceauth/authentication/task_statistics/tests/test_counters.py +++ b/allianceauth/authentication/task_statistics/tests/test_counters.py @@ -4,7 +4,10 @@ from django.test import TestCase from django.utils.timezone import now from allianceauth.authentication.task_statistics.counters import ( - dashboard_results, failed_tasks, retried_tasks, succeeded_tasks, + dashboard_results, + failed_tasks, + retried_tasks, + succeeded_tasks, ) diff --git a/allianceauth/authentication/task_statistics/tests/test_helpers.py b/allianceauth/authentication/task_statistics/tests/test_helpers.py index 51dae201..45edffd7 100644 --- a/allianceauth/authentication/task_statistics/tests/test_helpers.py +++ b/allianceauth/authentication/task_statistics/tests/test_helpers.py @@ -4,7 +4,8 @@ from unittest.mock import patch from redis import RedisError from allianceauth.authentication.task_statistics.helpers import ( - _RedisStub, get_redis_client_or_stub, + _RedisStub, + get_redis_client_or_stub, ) MODULE_PATH = "allianceauth.authentication.task_statistics.helpers" diff --git a/allianceauth/authentication/task_statistics/tests/test_signals.py b/allianceauth/authentication/task_statistics/tests/test_signals.py index 1e1634bd..d04f11e2 100644 --- a/allianceauth/authentication/task_statistics/tests/test_signals.py +++ b/allianceauth/authentication/task_statistics/tests/test_signals.py @@ -10,8 +10,8 @@ from allianceauth.authentication.task_statistics.counters import ( succeeded_tasks, ) from allianceauth.authentication.task_statistics.signals import ( - reset_counters, is_enabled, + reset_counters, ) from allianceauth.eveonline.tasks import update_character diff --git a/allianceauth/authentication/tasks.py b/allianceauth/authentication/tasks.py index eaf3c59a..ff5f7e63 100644 --- a/allianceauth/authentication/tasks.py +++ b/allianceauth/authentication/tasks.py @@ -1,9 +1,10 @@ import logging -from esi.errors import TokenExpiredError, TokenInvalidError, IncompleteResponseError -from esi.models import Token from celery import shared_task +from esi.errors import IncompleteResponseError, TokenExpiredError, TokenInvalidError +from esi.models import Token + from allianceauth.authentication.models import CharacterOwnership logger = logging.getLogger(__name__) @@ -22,8 +23,7 @@ def check_character_ownership(owner_hash): continue except (KeyError, IncompleteResponseError): # We can't validate the hash hasn't changed but also can't assume it has. Abort for now. - logger.warning("Failed to validate owner hash of {} due to problems contacting SSO servers.".format( - tokens[0].character_name)) + logger.warning(f"Failed to validate owner hash of {tokens[0].character_name} due to problems contacting SSO servers.") break if not t.character_owner_hash == old_hash: @@ -33,7 +33,7 @@ def check_character_ownership(owner_hash): break if not Token.objects.filter(character_owner_hash=owner_hash).exists(): - logger.info('No tokens found with owner hash %s. Revoking ownership.' % owner_hash) + logger.info(f'No tokens found with owner hash {owner_hash}. Revoking ownership.') CharacterOwnership.objects.filter(owner_hash=owner_hash).delete() diff --git a/allianceauth/authentication/tests/__init__.py b/allianceauth/authentication/tests/__init__.py index 13410df4..55fd9fe9 100644 --- a/allianceauth/authentication/tests/__init__.py +++ b/allianceauth/authentication/tests/__init__.py @@ -1,12 +1,7 @@ -from django.db.models.signals import ( - m2m_changed, - post_save, - pre_delete, - pre_save -) -from django.urls import reverse from unittest import mock +from django.urls import reverse + MODULE_PATH = 'allianceauth.authentication' @@ -17,9 +12,7 @@ def patch(target, *args, **kwargs): def get_admin_change_view_url(obj: object) -> str: """returns URL to admin change view for given object""" return reverse( - 'admin:{}_{}_change'.format( - obj._meta.app_label, type(obj).__name__.lower() - ), + f'admin:{obj._meta.app_label}_{type(obj).__name__.lower()}_change', args=(obj.pk,) ) diff --git a/allianceauth/authentication/tests/core/test_celery_workers.py b/allianceauth/authentication/tests/core/test_celery_workers.py index 95bec08d..5551c318 100644 --- a/allianceauth/authentication/tests/core/test_celery_workers.py +++ b/allianceauth/authentication/tests/core/test_celery_workers.py @@ -5,7 +5,8 @@ from amqp.exceptions import ChannelError from django.test import TestCase from allianceauth.authentication.core.celery_workers import ( - active_tasks_count, queued_tasks_count, + active_tasks_count, + queued_tasks_count, ) MODULE_PATH = "allianceauth.authentication.core.celery_workers" diff --git a/allianceauth/authentication/tests/test_admin.py b/allianceauth/authentication/tests/test_admin.py index 0f43a14c..26d389b7 100644 --- a/allianceauth/authentication/tests/test_admin.py +++ b/allianceauth/authentication/tests/test_admin.py @@ -1,42 +1,37 @@ -from bs4 import BeautifulSoup +from unittest.mock import MagicMock, patch from urllib.parse import quote -from unittest.mock import patch, MagicMock +from bs4 import BeautifulSoup from django_webtest import WebTest from django.contrib.admin.sites import AdminSite from django.contrib.auth.models import Group -from django.test import TestCase, RequestFactory, Client +from django.test import Client, RequestFactory, TestCase -from allianceauth.authentication.models import ( - CharacterOwnership, State, OwnershipRecord -) -from allianceauth.eveonline.models import ( - EveCharacter, EveCorporationInfo, EveAllianceInfo, EveFactionInfo -) +from allianceauth.authentication.models import CharacterOwnership, OwnershipRecord, State +from allianceauth.eveonline.models import EveAllianceInfo, EveCharacter, EveCorporationInfo, EveFactionInfo from allianceauth.services.hooks import ServicesHook from allianceauth.tests.auth_utils import AuthUtils from ..admin import ( BaseUserAdmin, CharacterOwnershipAdmin, - StateAdmin, - MainCorporationsFilter, MainAllianceFilter, + MainCorporationsFilter, MainFactionFilter, OwnershipRecordAdmin, + StateAdmin, User, UserAdmin, + make_service_hooks_sync_nickname_action, + make_service_hooks_update_groups_action, + update_main_character_model, user_main_organization, user_profile_pic, user_username, - update_main_character_model, - make_service_hooks_update_groups_action, - make_service_hooks_sync_nickname_action ) from . import get_admin_change_view_url, get_admin_search_url - MODULE_PATH = 'allianceauth.authentication.admin' @@ -327,15 +322,15 @@ class TestUserAdmin(TestCaseWithTestData): def test_user_username_u1(self): expected = ( - '' - 'Bruce_Wayne
Bruce Wayne'.format(self.user_1.pk) + f'' + 'Bruce_Wayne
Bruce Wayne' ) self.assertEqual(user_username(self.user_1), expected) def test_user_username_u3(self): expected = ( - '' - 'Lex_Luthor'.format(self.user_3.pk) + f'' + 'Lex_Luthor' ) self.assertEqual(user_username(self.user_3), expected) diff --git a/allianceauth/authentication/tests/test_app_settings.py b/allianceauth/authentication/tests/test_app_settings.py index 8fa9d368..5dd62930 100644 --- a/allianceauth/authentication/tests/test_app_settings.py +++ b/allianceauth/authentication/tests/test_app_settings.py @@ -1,4 +1,5 @@ from unittest.mock import Mock, patch + from django.test import TestCase from .. import app_settings @@ -83,7 +84,7 @@ class TestSetAppSetting(TestCase): self.assertEqual(result, 50) @patch(MODULE_PATH + '.app_settings.settings') - def test_default_for_invalid_type_int(self, mock_settings): + def test_default_for_outofrange_int(self, mock_settings): mock_settings.TEST_SETTING_DUMMY = 1000 result = app_settings._clean_setting( 'TEST_SETTING_DUMMY', @@ -96,7 +97,7 @@ class TestSetAppSetting(TestCase): def test_default_is_none_needs_required_type(self, mock_settings): mock_settings.TEST_SETTING_DUMMY = 'invalid type' with self.assertRaises(ValueError): - result = app_settings._clean_setting( + app_settings._clean_setting( 'TEST_SETTING_DUMMY', default_value=None ) diff --git a/allianceauth/authentication/tests/test_backend.py b/allianceauth/authentication/tests/test_backend.py index 92936355..d4969877 100644 --- a/allianceauth/authentication/tests/test_backend.py +++ b/allianceauth/authentication/tests/test_backend.py @@ -1,13 +1,13 @@ -from django.contrib.auth.models import User, Group +from django.contrib.auth.models import Group, User from django.test import TestCase +from esi.models import Token + from allianceauth.eveonline.models import EveCharacter from allianceauth.tests.auth_utils import AuthUtils -from esi.models import Token - from ..backends import StateBackend -from ..models import CharacterOwnership, UserProfile, OwnershipRecord +from ..models import CharacterOwnership, OwnershipRecord, UserProfile MODULE_PATH = 'allianceauth.authentication' diff --git a/allianceauth/authentication/tests/test_decorators.py b/allianceauth/authentication/tests/test_decorators.py index 5b729d01..5a2fd39c 100644 --- a/allianceauth/authentication/tests/test_decorators.py +++ b/allianceauth/authentication/tests/test_decorators.py @@ -6,12 +6,11 @@ from django.contrib.auth.models import AnonymousUser from django.http.response import HttpResponse from django.test import TestCase from django.test.client import RequestFactory -from django.urls import reverse, URLPattern +from django.urls import URLPattern, reverse from allianceauth.eveonline.models import EveCharacter from allianceauth.tests.auth_utils import AuthUtils - from ..decorators import decorate_url_patterns, main_character_required from ..models import CharacterOwnership @@ -47,7 +46,7 @@ class DecoratorTestCase(TestCase): @mock.patch(MODULE_PATH + '.decorators.messages') def test_login_redirect(self, m): - setattr(self.request, 'user', AnonymousUser()) + self.request.user = AnonymousUser() response = self.dummy_view(self.request) self.assertEqual(response.status_code, 302) url = getattr(response, 'url', None) @@ -55,7 +54,7 @@ class DecoratorTestCase(TestCase): @mock.patch(MODULE_PATH + '.decorators.messages') def test_main_character_redirect(self, m): - setattr(self.request, 'user', self.no_main_user) + self.request.user = self.no_main_user response = self.dummy_view(self.request) self.assertEqual(response.status_code, 302) url = getattr(response, 'url', None) @@ -63,7 +62,7 @@ class DecoratorTestCase(TestCase): @mock.patch(MODULE_PATH + '.decorators.messages') def test_successful_request(self, m): - setattr(self.request, 'user', self.main_user) + self.request.user = self.main_user response = self.dummy_view(self.request) self.assertEqual(response.status_code, 200) diff --git a/allianceauth/authentication/tests/test_middleware.py b/allianceauth/authentication/tests/test_middleware.py index 70335e58..5f94abbd 100644 --- a/allianceauth/authentication/tests/test_middleware.py +++ b/allianceauth/authentication/tests/test_middleware.py @@ -1,10 +1,10 @@ -from unittest import mock -from allianceauth.authentication.middleware import UserSettingsMiddleware from unittest.mock import Mock -from django.http import HttpResponse +from django.http import HttpResponse from django.test.testcases import TestCase +from allianceauth.authentication.middleware import UserSettingsMiddleware + class TestUserSettingsMiddlewareSaveLang(TestCase): @@ -39,7 +39,7 @@ class TestUserSettingsMiddlewareSaveLang(TestCase): of a non-existent (anonymous) user """ self.request.user.is_anonymous = True - response = self.middleware.process_response( + self.middleware.process_response( self.request, self.response ) @@ -52,7 +52,7 @@ class TestUserSettingsMiddlewareSaveLang(TestCase): does the middleware change a language not set in the DB """ self.request.user.profile.language = None - response = self.middleware.process_response( + self.middleware.process_response( self.request, self.response ) @@ -64,7 +64,7 @@ class TestUserSettingsMiddlewareSaveLang(TestCase): """ Tests the middleware will change a language setting """ - response = self.middleware.process_response( + self.middleware.process_response( self.request, self.response ) @@ -158,7 +158,7 @@ class TestUserSettingsMiddlewareLoginFlow(TestCase): tests the middleware will set night_mode if not set """ self.request.session = {} - response = self.middleware.process_response( + self.middleware.process_response( self.request, self.response ) @@ -168,7 +168,7 @@ class TestUserSettingsMiddlewareLoginFlow(TestCase): """ tests the middleware will set night_mode if set. """ - response = self.middleware.process_response( + self.middleware.process_response( self.request, self.response ) diff --git a/allianceauth/authentication/tests/test_models.py b/allianceauth/authentication/tests/test_models.py index 4dca31ff..2f963708 100644 --- a/allianceauth/authentication/tests/test_models.py +++ b/allianceauth/authentication/tests/test_models.py @@ -3,12 +3,12 @@ from unittest import mock from django.contrib.auth.models import User from django.test import TestCase -from allianceauth.eveonline.models import EveCharacter, EveCorporationInfo,\ - EveAllianceInfo, EveFactionInfo -from allianceauth.tests.auth_utils import AuthUtils from esi.errors import IncompleteResponseError from esi.models import Token +from allianceauth.eveonline.models import EveAllianceInfo, EveCharacter, EveCorporationInfo, EveFactionInfo +from allianceauth.tests.auth_utils import AuthUtils + from ..models import CharacterOwnership, State, get_guest_state from ..tasks import check_character_ownership diff --git a/allianceauth/authentication/tests/test_signals.py b/allianceauth/authentication/tests/test_signals.py index 8f7ba716..3336677e 100644 --- a/allianceauth/authentication/tests/test_signals.py +++ b/allianceauth/authentication/tests/test_signals.py @@ -1,19 +1,11 @@ + +from django.db.models.signals import post_save +from django.test.testcases import TestCase + from allianceauth.authentication.models import User, UserProfile -from allianceauth.eveonline.models import ( - EveCharacter, - EveCorporationInfo, - EveAllianceInfo -) -from django.db.models.signals import ( - pre_save, - post_save, - pre_delete, - m2m_changed -) +from allianceauth.eveonline.models import EveAllianceInfo, EveCharacter, EveCorporationInfo from allianceauth.tests.auth_utils import AuthUtils -from django.test.testcases import TestCase -from unittest.mock import Mock from . import patch diff --git a/allianceauth/authentication/tests/test_templatetags.py b/allianceauth/authentication/tests/test_templatetags.py index 450da33e..7f42f830 100644 --- a/allianceauth/authentication/tests/test_templatetags.py +++ b/allianceauth/authentication/tests/test_templatetags.py @@ -9,8 +9,12 @@ from django.core.cache import cache from django.test import TestCase from allianceauth.templatetags.admin_status import ( - _current_notifications, _current_version_summary, _fetch_list_from_gitlab, - _fetch_notification_issues_from_gitlab, _latests_versions, status_overview, + _current_notifications, + _current_version_summary, + _fetch_list_from_gitlab, + _fetch_notification_issues_from_gitlab, + _latests_versions, + status_overview, ) MODULE_PATH = 'allianceauth.templatetags' @@ -127,7 +131,7 @@ class TestNotifications(TestCase): # when result = _current_notifications() # then - self.assertEqual(result['notifications'], list()) + self.assertEqual(result['notifications'], []) @patch(MODULE_PATH + '.admin_status.cache') def test_current_notifications_is_none(self, mock_cache): @@ -136,7 +140,7 @@ class TestNotifications(TestCase): # when result = _current_notifications() # then - self.assertEqual(result['notifications'], list()) + self.assertEqual(result['notifications'], []) class TestCeleryQueueLength(TestCase): diff --git a/allianceauth/authentication/tests/test_views.py b/allianceauth/authentication/tests/test_views.py index ec7601a9..14394938 100644 --- a/allianceauth/authentication/tests/test_views.py +++ b/allianceauth/authentication/tests/test_views.py @@ -1,12 +1,13 @@ import json -import requests_mock from unittest.mock import patch +import requests_mock + from django.test import RequestFactory, TestCase -from allianceauth.authentication.views import task_counts, esi_check -from allianceauth.tests.auth_utils import AuthUtils from allianceauth.authentication.constants import ESI_ERROR_MESSAGE_OVERRIDES +from allianceauth.authentication.views import esi_check, task_counts +from allianceauth.tests.auth_utils import AuthUtils MODULE_PATH = "allianceauth.authentication.views" diff --git a/allianceauth/authentication/views.py b/allianceauth/authentication/views.py index 2e8f4e2c..392a0a44 100644 --- a/allianceauth/authentication/views.py +++ b/allianceauth/authentication/views.py @@ -1,11 +1,6 @@ import logging import requests -from django_registration.backends.activation.views import ( - REGISTRATION_SALT, ActivationView as BaseActivationView, - RegistrationView as BaseRegistrationView, -) -from django_registration.signals import user_registered from django.conf import settings from django.contrib import messages @@ -18,6 +13,12 @@ from django.shortcuts import redirect, render from django.template.loader import render_to_string from django.urls import reverse, reverse_lazy from django.utils.translation import gettext_lazy as _ +from django_registration.backends.activation.views import ( + REGISTRATION_SALT, + ActivationView as BaseActivationView, + RegistrationView as BaseRegistrationView, +) +from django_registration.signals import user_registered from esi.decorators import token_required from esi.models import Token @@ -32,7 +33,7 @@ from .models import CharacterOwnership if 'allianceauth.eveonline.autogroups' in settings.INSTALLED_APPS: _has_auto_groups = True - from allianceauth.eveonline.autogroups.models import * # noqa: F401, F403 + from allianceauth.eveonline.autogroups.models import * # noqa: F403 else: _has_auto_groups = False @@ -87,7 +88,7 @@ def dashboard_esi_check(request): @login_required def dashboard(request): - _dash_items = list() + _dash_items = [] hooks = get_hooks('dashboard_hook') items = [fn() for fn in hooks] items.sort(key=lambda i: i.order) @@ -164,9 +165,7 @@ def main_character_change(request, token): request.user.profile.save(update_fields=['main_character']) messages.success(request, _('Changed main character to %s') % co.character) logger.info( - 'Changed user {user} main character to {char}'.format( - user=request.user, char=co.character - ) + f'Changed user {request.user} main character to {co.character}' ) return redirect("authentication:dashboard") @@ -176,10 +175,9 @@ def add_character(request, token): if CharacterOwnership.objects.filter(character__character_id=token.character_id).filter( owner_hash=token.character_owner_hash).filter(user=request.user).exists(): messages.success(request, _( - 'Added %(name)s to your account.' % ({'name': token.character_name}))) + 'Added {name} to your account.'.format(name=token.character_name))) else: - messages.error(request, _('Failed to add %(name)s to your account: they already have an account.' % ( - {'name': token.character_name}))) + messages.error(request, _('Failed to add {name} to your account: they already have an account.'.format(name=token.character_name))) return redirect('authentication:dashboard') @@ -294,7 +292,7 @@ class RegistrationView(BaseRegistrationView): return redirect(settings.LOGIN_URL) if not getattr(settings, 'REGISTRATION_VERIFY_EMAIL', True): # Keep the request so the user can be automagically logged in. - setattr(self, 'request', request) + self.request = request return super().dispatch(request, *args, **kwargs) def register(self, form): diff --git a/allianceauth/bin/allianceauth.py b/allianceauth/bin/allianceauth.py index 20cfb53d..cd400526 100644 --- a/allianceauth/bin/allianceauth.py +++ b/allianceauth/bin/allianceauth.py @@ -2,6 +2,7 @@ import os import shutil from optparse import OptionParser + from django.core.management import call_command from django.core.management.commands.startproject import Command as BaseStartProject @@ -43,7 +44,7 @@ def create_project(parser, options, args): # Call the command with extra context call_command(StartProject(), *args, **command_options) - print(f"Success! {args[0]} has been created.") # noqa + print(f"Success! {args[0]} has been created.") def update_settings(parser, options, args): @@ -62,7 +63,7 @@ def update_settings(parser, options, args): # next check if given path is to the project, so the app is within it settings_path = os.path.join(project_path, project_name, 'settings/base.py') if not os.path.exists(settings_path): - parser.error("Unable to locate the Alliance Auth project at %s" % project_path) + parser.error(f"Unable to locate the Alliance Auth project at {project_path}") # first find the path to the Alliance Auth template settings import allianceauth diff --git a/allianceauth/checks.py b/allianceauth/checks.py index 704f6e6e..e6d0319d 100644 --- a/allianceauth/checks.py +++ b/allianceauth/checks.py @@ -1,12 +1,16 @@ -from django import db -from django.core.checks import CheckMessage, Error, register, Warning -from allianceauth.utils.cache import get_redis_client -from django.utils import timezone -from packaging.version import InvalidVersion, Version as Pep440Version -from celery import current_app -from django.conf import settings -from sqlite3.dbapi2 import sqlite_version_info import datetime +from sqlite3.dbapi2 import sqlite_version_info + +from celery import current_app +from packaging.version import InvalidVersion, Version as Pep440Version + +from django import db +from django.conf import settings +from django.core.checks import CheckMessage, Error, Warning, register +from django.utils import timezone + +from allianceauth.utils.cache import get_redis_client + """ A = System Packages B = Configuration @@ -101,8 +105,7 @@ def system_package_mariadb(app_configs, **kwargs) -> list[CheckMessage]: errors.append(Error(f"MariaDB {mariadb_version.public} EOL", hint="https://mariadb.org/download/?t=repo-config", id="allianceauth.checks.A011")) elif mariadb_version.major == 11 and mariadb_version.minor == 1: errors.append(Warning(f"MariaDB {mariadb_version.public} Non LTS", hint="https://mariadb.org/download/?t=repo-config", id="allianceauth.checks.A019")) - if timezone.now() > timezone.datetime(year=2024, month=8, day=21, tzinfo=datetime.timezone.utc): - errors.append(Error(f"MariaDB {mariadb_version.public} EOL", hint="https://mariadb.org/download/?t=repo-config", id="allianceauth.checks.A012")) + errors.append(Error(f"MariaDB {mariadb_version.public} EOL", hint="https://mariadb.org/download/?t=repo-config", id="allianceauth.checks.A012")) elif mariadb_version.major == 11 and mariadb_version.minor in [0, 3]: # Demote versions down here once EOL errors.append(Error(f"MariaDB {mariadb_version.public} EOL", hint="https://mariadb.org/download/?t=repo-config.", id="allianceauth.checks.A013")) @@ -168,7 +171,7 @@ def celery_settings(app_configs, **kwargs) -> list[CheckMessage]: errors.append(Error("Celery Priorities are not set", hint="https://gitlab.com/allianceauth/allianceauth/-/commit/8861ec0a61790eca0261f1adc1cc04ca5f243cbc", id="allianceauth.checks.B003")) try: - if current_app.conf.broker_connection_retry_on_startup != True: + if current_app.conf.broker_connection_retry_on_startup is not True: errors.append(Error("Celery broker_connection_retry_on_startup not set correctly", hint="https://gitlab.com/allianceauth/allianceauth/-/commit/380c41400b535447839e5552df2410af35a75280", id="allianceauth.checks.B004")) except KeyError: errors.append(Error("Celery broker_connection_retry_on_startup not set", hint="https://gitlab.com/allianceauth/allianceauth/-/commit/380c41400b535447839e5552df2410af35a75280", id="allianceauth.checks.B004")) diff --git a/allianceauth/context_processors.py b/allianceauth/context_processors.py index 4feb243e..cbc75a0e 100644 --- a/allianceauth/context_processors.py +++ b/allianceauth/context_processors.py @@ -1,4 +1,5 @@ from django.conf import settings + from .views import NightModeRedirectView diff --git a/allianceauth/corputils/admin.py b/allianceauth/corputils/admin.py index e0cdda66..c0a8de55 100644 --- a/allianceauth/corputils/admin.py +++ b/allianceauth/corputils/admin.py @@ -1,6 +1,6 @@ from django.contrib import admin -from .models import CorpStats, CorpMember +from .models import CorpMember, CorpStats admin.site.register(CorpStats) admin.site.register(CorpMember) diff --git a/allianceauth/corputils/auth_hooks.py b/allianceauth/corputils/auth_hooks.py index 4dd3e8ce..4414898c 100644 --- a/allianceauth/corputils/auth_hooks.py +++ b/allianceauth/corputils/auth_hooks.py @@ -1,8 +1,9 @@ -from allianceauth.menu.hooks import MenuItemHook -from allianceauth.services.hooks import UrlHook from django.utils.translation import gettext_lazy as _ + from allianceauth import hooks from allianceauth.corputils import urls +from allianceauth.menu.hooks import MenuItemHook +from allianceauth.services.hooks import UrlHook class CorpStats(MenuItemHook): diff --git a/allianceauth/corputils/managers.py b/allianceauth/corputils/managers.py index 87b2ffdd..f7bca4f9 100644 --- a/allianceauth/corputils/managers.py +++ b/allianceauth/corputils/managers.py @@ -1,6 +1,7 @@ -from django.db import models import logging +from django.db import models + logger = logging.getLogger(__name__) @@ -8,7 +9,7 @@ class CorpStatsQuerySet(models.QuerySet): def visible_to(self, user): # superusers get all visible if user.is_superuser: - logger.debug('Returning all corpstats for superuser %s.' % user) + logger.debug(f'Returning all corpstats for superuser {user}.') return self try: @@ -36,7 +37,7 @@ class CorpStatsQuerySet(models.QuerySet): query |= q return self.filter(query) except AssertionError: - logger.debug('User %s has no main character. No corpstats visible.' % user) + logger.debug(f'User {user} has no main character. No corpstats visible.') return self.none() diff --git a/allianceauth/corputils/migrations/0001_initial.py b/allianceauth/corputils/migrations/0001_initial.py index 49d71b75..e7439525 100644 --- a/allianceauth/corputils/migrations/0001_initial.py +++ b/allianceauth/corputils/migrations/0001_initial.py @@ -1,7 +1,7 @@ # Generated by Django 1.10.1 on 2016-12-14 21:36 -from django.db import migrations, models import django.db.models.deletion +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/allianceauth/corputils/migrations/0002_migrate_permissions.py b/allianceauth/corputils/migrations/0002_migrate_permissions.py index fce155e4..cd75c9dc 100644 --- a/allianceauth/corputils/migrations/0002_migrate_permissions.py +++ b/allianceauth/corputils/migrations/0002_migrate_permissions.py @@ -66,7 +66,7 @@ def forward(apps, schema_editor): g.permissions.add(perm_dict['corpstats']['alliance_apis'].pk) g.permissions.add(perm_dict['corpstats']['view_alliance_corpstats'].pk) - for name, perm in perm_dict['user'].items(): + for _name, perm in perm_dict['user'].items(): perm.delete() diff --git a/allianceauth/corputils/migrations/0004_member_models.py b/allianceauth/corputils/migrations/0004_member_models.py index b8e2e291..8359669b 100644 --- a/allianceauth/corputils/migrations/0004_member_models.py +++ b/allianceauth/corputils/migrations/0004_member_models.py @@ -1,9 +1,10 @@ # Generated by Django 1.10.5 on 2017-03-26 20:13 -from django.db import migrations, models -import django.db.models.deletion import json +import django.db.models.deletion +from django.db import migrations, models + def convert_json_to_members(apps, schema_editor): CorpStats = apps.get_model('corputils', 'CorpStats') diff --git a/allianceauth/corputils/models.py b/allianceauth/corputils/models.py index 7ac03b7e..a98ec5cb 100644 --- a/allianceauth/corputils/models.py +++ b/allianceauth/corputils/models.py @@ -1,15 +1,17 @@ import logging import os -from allianceauth.authentication.models import CharacterOwnership, UserProfile from bravado.exception import HTTPForbidden + from django.db import models + from esi.errors import TokenError from esi.models import Token -from allianceauth.eveonline.models import EveCorporationInfo, EveCharacter, EveAllianceInfo -from allianceauth.notifications import notify +from allianceauth.authentication.models import CharacterOwnership, UserProfile from allianceauth.corputils.managers import CorpStatsManager +from allianceauth.eveonline.models import EveAllianceInfo, EveCharacter, EveCorporationInfo +from allianceauth.notifications import notify SWAGGER_SPEC_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'swagger.json') """ @@ -31,6 +33,7 @@ class CorpStats(models.Model): corp = models.OneToOneField(EveCorporationInfo, on_delete=models.CASCADE) last_update = models.DateTimeField(auto_now=True) + objects = CorpStatsManager() class Meta: permissions = ( ('view_corp_corpstats', 'Can view corp stats of their corporation.'), @@ -40,7 +43,7 @@ class CorpStats(models.Model): verbose_name = "corp stats" verbose_name_plural = "corp stats" - objects = CorpStatsManager() + def __str__(self): return f"{self.__class__.__name__} for {self.corp}" @@ -76,21 +79,21 @@ class CorpStats(models.Model): logger.warning(f"{self} failed to update: {e}") if self.token.user: notify( - self.token.user, "%s failed to update with your ESI token." % self, + self.token.user, f"{self} failed to update with your ESI token.", message="Your token has expired or is no longer valid. Please add a new one to create a new CorpStats.", level="error") self.delete() except HTTPForbidden as e: logger.warning(f"{self} failed to update: {e}") if self.token.user: - notify(self.token.user, "%s failed to update with your ESI token." % self, message=f"{e.status_code}: {e.message}", level="error") + notify(self.token.user, f"{self} failed to update with your ESI token.", message=f"{e.status_code}: {e.message}", level="error") self.delete() except AssertionError: - logger.warning("%s token character no longer in corp." % self) + logger.warning(f"{self} token character no longer in corp.") if self.token.user: notify( - self.token.user, "%s cannot update with your ESI token." % self, - message="%s cannot update with your ESI token as you have left corp." % self, level="error") + self.token.user, f"{self} cannot update with your ESI token.", + message=f"{self} cannot update with your ESI token as you have left corp.", level="error") self.delete() @property diff --git a/allianceauth/corputils/tasks.py b/allianceauth/corputils/tasks.py index 6cc016fa..fda7c5fb 100644 --- a/allianceauth/corputils/tasks.py +++ b/allianceauth/corputils/tasks.py @@ -1,4 +1,5 @@ from celery import shared_task + from allianceauth.corputils.models import CorpStats diff --git a/allianceauth/corputils/tests.py b/allianceauth/corputils/tests.py index 43e1f720..176541b3 100644 --- a/allianceauth/corputils/tests.py +++ b/allianceauth/corputils/tests.py @@ -1,14 +1,18 @@ from unittest import mock -from django.test import TestCase -from allianceauth.tests.auth_utils import AuthUtils -from .models import CorpStats, CorpMember -from allianceauth.eveonline.models import EveCorporationInfo, EveAllianceInfo, EveCharacter -from esi.models import Token -from esi.errors import TokenError from bravado.exception import HTTPForbidden + from django.contrib.auth.models import Permission +from django.test import TestCase + +from esi.errors import TokenError +from esi.models import Token + from allianceauth.authentication.models import CharacterOwnership +from allianceauth.eveonline.models import EveAllianceInfo, EveCharacter, EveCorporationInfo +from allianceauth.tests.auth_utils import AuthUtils + +from .models import CorpMember, CorpStats class CorpStatsManagerTestCase(TestCase): diff --git a/allianceauth/corputils/urls.py b/allianceauth/corputils/urls.py index 5f66c48e..7729d721 100644 --- a/allianceauth/corputils/urls.py +++ b/allianceauth/corputils/urls.py @@ -1,4 +1,5 @@ from django.urls import path + from . import views app_name = 'corputils' diff --git a/allianceauth/corputils/views.py b/allianceauth/corputils/views.py index 98367aef..d0e62690 100644 --- a/allianceauth/corputils/views.py +++ b/allianceauth/corputils/views.py @@ -1,16 +1,19 @@ import os from bravado.exception import HTTPError + from django.contrib import messages from django.contrib.auth.decorators import login_required, permission_required, user_passes_test -from django.core.exceptions import PermissionDenied, ObjectDoesNotExist +from django.core.exceptions import ObjectDoesNotExist, PermissionDenied from django.db import IntegrityError -from django.shortcuts import render, redirect, get_object_or_404 +from django.shortcuts import get_object_or_404, redirect, render from django.utils.translation import gettext_lazy as _ + from esi.decorators import token_required + from allianceauth.eveonline.models import EveCharacter, EveCorporationInfo -from .models import CorpStats, CorpMember +from .models import CorpMember, CorpStats SWAGGER_SPEC_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'swagger.json') """ diff --git a/allianceauth/custom_css/admin.py b/allianceauth/custom_css/admin.py index 093e18e8..e7af932d 100644 --- a/allianceauth/custom_css/admin.py +++ b/allianceauth/custom_css/admin.py @@ -3,14 +3,15 @@ Admin classes for custom_css app """ # Django -from django.contrib import admin - # Django Solos from solo.admin import SingletonModelAdmin +from django.contrib import admin + +from allianceauth.custom_css.forms import CustomCSSAdminForm + # Alliance Auth Custom CSS from allianceauth.custom_css.models import CustomCSS -from allianceauth.custom_css.forms import CustomCSSAdminForm @admin.register(CustomCSS) diff --git a/allianceauth/custom_css/forms.py b/allianceauth/custom_css/forms.py index 6823b204..1b3f5955 100644 --- a/allianceauth/custom_css/forms.py +++ b/allianceauth/custom_css/forms.py @@ -3,12 +3,12 @@ Forms for custom_css app """ # Alliance Auth Custom CSS -from allianceauth.custom_css.models import CustomCSS -from allianceauth.custom_css.widgets import CssEditorWidget - # Django from django import forms +from allianceauth.custom_css.models import CustomCSS +from allianceauth.custom_css.widgets import CssEditorWidget + class CustomCSSAdminForm(forms.ModelForm): """ diff --git a/allianceauth/custom_css/models.py b/allianceauth/custom_css/models.py index c831cf6b..2b116fb4 100644 --- a/allianceauth/custom_css/models.py +++ b/allianceauth/custom_css/models.py @@ -21,7 +21,6 @@ class CustomCSS(SingletonModel): css = models.TextField( blank=True, - null=True, verbose_name=_("Your custom CSS"), help_text=_("This CSS will be added to the site after the default CSS."), ) diff --git a/allianceauth/custom_css/templatetags/custom_css.py b/allianceauth/custom_css/templatetags/custom_css.py index 3c01602f..1234c587 100644 --- a/allianceauth/custom_css/templatetags/custom_css.py +++ b/allianceauth/custom_css/templatetags/custom_css.py @@ -3,7 +3,7 @@ Custom template tags for custom_css app """ # Alliance Auth Custom CSS -from allianceauth.custom_css.models import CustomCSS +from pathlib import Path # Django from django.conf import settings @@ -11,7 +11,7 @@ from django.template.defaulttags import register from django.templatetags.static import static from django.utils.safestring import mark_safe -from pathlib import Path +from allianceauth.custom_css.models import CustomCSS @register.simple_tag diff --git a/allianceauth/custom_css/widgets.py b/allianceauth/custom_css/widgets.py index 32ed07dd..1c3a6290 100644 --- a/allianceauth/custom_css/widgets.py +++ b/allianceauth/custom_css/widgets.py @@ -6,7 +6,6 @@ Form widgets for custom_css app from django import forms # Alliance Auth -from allianceauth.custom_css.models import CustomCSS class CssEditorWidget(forms.Textarea): diff --git a/allianceauth/eveonline/admin.py b/allianceauth/eveonline/admin.py index e37e8aaa..69d428df 100644 --- a/allianceauth/eveonline/admin.py +++ b/allianceauth/eveonline/admin.py @@ -1,12 +1,9 @@ from django import forms from django.contrib import admin from django.core.exceptions import ObjectDoesNotExist -from .providers import ObjectNotFound -from .models import EveAllianceInfo -from .models import EveCharacter -from .models import EveCorporationInfo -from .models import EveFactionInfo +from .models import EveAllianceInfo, EveCharacter, EveCorporationInfo, EveFactionInfo +from .providers import ObjectNotFound class EveEntityExistsError(forms.ValidationError): diff --git a/allianceauth/eveonline/autogroups/admin.py b/allianceauth/eveonline/autogroups/admin.py index 240d4578..e202de92 100644 --- a/allianceauth/eveonline/autogroups/admin.py +++ b/allianceauth/eveonline/autogroups/admin.py @@ -1,9 +1,9 @@ -from django.contrib import admin -from django.db import models -from .models import AutogroupsConfig, ManagedCorpGroup, ManagedAllianceGroup - import logging +from django.contrib import admin +from django.db import models + +from .models import AutogroupsConfig, ManagedAllianceGroup, ManagedCorpGroup logger = logging.getLogger(__name__) diff --git a/allianceauth/eveonline/autogroups/apps.py b/allianceauth/eveonline/autogroups/apps.py index 69ca1b22..61d4bbe2 100644 --- a/allianceauth/eveonline/autogroups/apps.py +++ b/allianceauth/eveonline/autogroups/apps.py @@ -6,4 +6,4 @@ class EveAutogroupsConfig(AppConfig): label = 'eve_autogroups' def ready(self): - import allianceauth.eveonline.autogroups.signals + pass diff --git a/allianceauth/eveonline/autogroups/migrations/0001_initial.py b/allianceauth/eveonline/autogroups/migrations/0001_initial.py index 33c1ab42..9716d3af 100644 --- a/allianceauth/eveonline/autogroups/migrations/0001_initial.py +++ b/allianceauth/eveonline/autogroups/migrations/0001_initial.py @@ -1,7 +1,7 @@ # Generated by Django 1.11.6 on 2017-12-23 04:30 -from django.db import migrations, models import django.db.models.deletion +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/allianceauth/eveonline/autogroups/models.py b/allianceauth/eveonline/autogroups/models.py index 88bc3ece..3f28f313 100644 --- a/allianceauth/eveonline/autogroups/models.py +++ b/allianceauth/eveonline/autogroups/models.py @@ -1,10 +1,11 @@ import logging -from django.db import models, transaction + from django.contrib.auth.models import Group, User from django.core.exceptions import ObjectDoesNotExist +from django.db import models, transaction from allianceauth.authentication.models import State -from allianceauth.eveonline.models import EveCorporationInfo, EveAllianceInfo +from allianceauth.eveonline.models import EveAllianceInfo, EveCorporationInfo logger = logging.getLogger(__name__) @@ -80,15 +81,15 @@ class AutogroupsConfig(models.Model): objects = AutogroupsConfigManager() + def __str__(self): + return 'States: ' + (' '.join(list(self.states.all().values_list('name', flat=True))) if self.pk else str(None)) + def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def __repr__(self): return self.__class__.__name__ - def __str__(self): - return 'States: ' + (' '.join(list(self.states.all().values_list('name', flat=True))) if self.pk else str(None)) - def update_all_states_group_membership(self): list(map(self.update_group_membership_for_state, self.states.all())) @@ -235,7 +236,7 @@ class ManagedGroup(models.Model): abstract = True def __str__(self): - return "Managed Group: %s" % self.group.name + return f"Managed Group: {self.group.name}" class ManagedCorpGroup(ManagedGroup): corp = models.ForeignKey(EveCorporationInfo, on_delete=models.CASCADE) diff --git a/allianceauth/eveonline/autogroups/signals.py b/allianceauth/eveonline/autogroups/signals.py index c2b8c11a..9b920d1b 100644 --- a/allianceauth/eveonline/autogroups/signals.py +++ b/allianceauth/eveonline/autogroups/signals.py @@ -1,7 +1,9 @@ import logging + +from django.db.models.signals import m2m_changed, post_save, pre_delete, pre_save from django.dispatch import receiver -from django.db.models.signals import pre_save, post_save, pre_delete, m2m_changed -from allianceauth.authentication.models import UserProfile, State + +from allianceauth.authentication.models import State, UserProfile from allianceauth.eveonline.models import EveCharacter from .models import AutogroupsConfig diff --git a/allianceauth/eveonline/autogroups/tests/__init__.py b/allianceauth/eveonline/autogroups/tests/__init__.py index cd1c4d68..8af31c2c 100644 --- a/allianceauth/eveonline/autogroups/tests/__init__.py +++ b/allianceauth/eveonline/autogroups/tests/__init__.py @@ -1,7 +1,10 @@ from unittest import mock -from django.db.models.signals import pre_save, post_save, pre_delete, m2m_changed + +from django.db.models.signals import m2m_changed, post_save, pre_delete, pre_save + from allianceauth.authentication.models import UserProfile from allianceauth.authentication.signals import reassess_on_profile_save + from .. import signals from ..models import AutogroupsConfig diff --git a/allianceauth/eveonline/autogroups/tests/test_managers.py b/allianceauth/eveonline/autogroups/tests/test_managers.py index e4e42ef0..e3afec8f 100644 --- a/allianceauth/eveonline/autogroups/tests/test_managers.py +++ b/allianceauth/eveonline/autogroups/tests/test_managers.py @@ -1,4 +1,5 @@ from django.test import TestCase + from allianceauth.tests.auth_utils import AuthUtils from ..models import AutogroupsConfig diff --git a/allianceauth/eveonline/autogroups/tests/test_models.py b/allianceauth/eveonline/autogroups/tests/test_models.py index f9c59389..7b6f8f89 100644 --- a/allianceauth/eveonline/autogroups/tests/test_models.py +++ b/allianceauth/eveonline/autogroups/tests/test_models.py @@ -1,15 +1,11 @@ -from django.test import TestCase from django.contrib.auth.models import Group -from django.db import transaction +from django.test import TestCase +from allianceauth.eveonline.models import EveAllianceInfo, EveCharacter, EveCorporationInfo from allianceauth.tests.auth_utils import AuthUtils -from allianceauth.eveonline.models import EveCharacter, EveCorporationInfo, EveAllianceInfo - from ..models import AutogroupsConfig, get_users_for_state - - -from . import patch, connect_signals, disconnect_signals +from . import connect_signals, disconnect_signals, patch class AutogroupsConfigTestCase(TestCase): diff --git a/allianceauth/eveonline/autogroups/tests/test_signals.py b/allianceauth/eveonline/autogroups/tests/test_signals.py index 0ff3aa4c..6911b68c 100644 --- a/allianceauth/eveonline/autogroups/tests/test_signals.py +++ b/allianceauth/eveonline/autogroups/tests/test_signals.py @@ -1,13 +1,11 @@ -from django.test import TestCase from django.contrib.auth.models import User +from django.test import TestCase +from allianceauth.eveonline.models import EveAllianceInfo, EveCharacter, EveCorporationInfo from allianceauth.tests.auth_utils import AuthUtils -from allianceauth.eveonline.models import EveCharacter, EveCorporationInfo, EveAllianceInfo - from ..models import AutogroupsConfig - -from . import patch, disconnect_signals, connect_signals +from . import connect_signals, disconnect_signals, patch class SignalsTestCase(TestCase): diff --git a/allianceauth/eveonline/evelinks/dotlan.py b/allianceauth/eveonline/evelinks/dotlan.py index b782eabd..b067b338 100644 --- a/allianceauth/eveonline/evelinks/dotlan.py +++ b/allianceauth/eveonline/evelinks/dotlan.py @@ -1,14 +1,8 @@ # this module generates profile URLs for dotlan -from urllib.parse import urljoin, quote - -from . import ( - _ESI_CATEGORY_ALLIANCE, - _ESI_CATEGORY_CORPORATION, - _ESI_CATEGORY_REGION, - _ESI_CATEGORY_SOLARSYSTEM -) +from urllib.parse import quote, urljoin +from . import _ESI_CATEGORY_ALLIANCE, _ESI_CATEGORY_CORPORATION, _ESI_CATEGORY_REGION, _ESI_CATEGORY_SOLARSYSTEM _BASE_URL = 'http://evemaps.dotlan.net' diff --git a/allianceauth/eveonline/evelinks/eveimageserver.py b/allianceauth/eveonline/evelinks/eveimageserver.py index 172c1bbc..aa0570a2 100644 --- a/allianceauth/eveonline/evelinks/eveimageserver.py +++ b/allianceauth/eveonline/evelinks/eveimageserver.py @@ -1,10 +1,4 @@ -from . import ( - _ESI_CATEGORY_ALLIANCE, - _ESI_CATEGORY_CHARACTER, - _ESI_CATEGORY_CORPORATION, - _ESI_CATEGORY_INVENTORYTYPE -) - +from . import _ESI_CATEGORY_ALLIANCE, _ESI_CATEGORY_CHARACTER, _ESI_CATEGORY_CORPORATION, _ESI_CATEGORY_INVENTORYTYPE _EVE_IMAGE_SERVER_URL = 'https://images.evetech.net' _DEFAULT_IMAGE_SIZE = 32 @@ -70,10 +64,7 @@ def _eve_entity_image_url( if variant: if variant not in categories[category]['variants']: - raise ValueError('Invalid variant {} for category {}'.format( - variant, - category - )) + raise ValueError(f'Invalid variant {variant} for category {category}') else: variant = categories[category]['variants'][0] @@ -81,13 +72,7 @@ def _eve_entity_image_url( raise ValueError(f'Invalid tenant {tenant}') # compose result URL - result = '{}/{}/{}/{}?size={}'.format( - _EVE_IMAGE_SERVER_URL, - endpoint, - entity_id, - variant, - size - ) + result = f'{_EVE_IMAGE_SERVER_URL}/{endpoint}/{entity_id}/{variant}?size={size}' if tenant: result += f'&tenant={tenant}' diff --git a/allianceauth/eveonline/evelinks/evewho.py b/allianceauth/eveonline/evelinks/evewho.py index 6fd05b14..52385953 100644 --- a/allianceauth/eveonline/evelinks/evewho.py +++ b/allianceauth/eveonline/evelinks/evewho.py @@ -4,11 +4,10 @@ from urllib.parse import urljoin from . import ( _ESI_CATEGORY_ALLIANCE, - _ESI_CATEGORY_CORPORATION, _ESI_CATEGORY_CHARACTER, + _ESI_CATEGORY_CORPORATION, ) - _BASE_URL = 'https://evewho.com' diff --git a/allianceauth/eveonline/evelinks/tests/test_evelinks.py b/allianceauth/eveonline/evelinks/tests/test_evelinks.py index 32f79f05..955854cf 100644 --- a/allianceauth/eveonline/evelinks/tests/test_evelinks.py +++ b/allianceauth/eveonline/evelinks/tests/test_evelinks.py @@ -1,8 +1,6 @@ from django.test import TestCase -from ...models import EveCharacter, EveCorporationInfo, EveAllianceInfo -from .. import dotlan, zkillboard, evewho, eveimageserver -from ...templatetags import evelinks +from .. import dotlan, eveimageserver, evewho, zkillboard class TestEveWho(TestCase): diff --git a/allianceauth/eveonline/evelinks/tests/test_templatetags.py b/allianceauth/eveonline/evelinks/tests/test_templatetags.py index db5c8178..2e96f278 100644 --- a/allianceauth/eveonline/evelinks/tests/test_templatetags.py +++ b/allianceauth/eveonline/evelinks/tests/test_templatetags.py @@ -1,8 +1,8 @@ from django.test import TestCase -from ...models import EveCharacter, EveCorporationInfo, EveAllianceInfo -from .. import eveimageserver, evewho, dotlan, zkillboard +from ...models import EveAllianceInfo, EveCharacter, EveCorporationInfo from ...templatetags import evelinks +from .. import dotlan, eveimageserver, evewho, zkillboard class TestTemplateTags(TestCase): diff --git a/allianceauth/eveonline/evelinks/zkillboard.py b/allianceauth/eveonline/evelinks/zkillboard.py index 3bba9833..4ce84bb2 100644 --- a/allianceauth/eveonline/evelinks/zkillboard.py +++ b/allianceauth/eveonline/evelinks/zkillboard.py @@ -4,13 +4,12 @@ from urllib.parse import urljoin from . import ( _ESI_CATEGORY_ALLIANCE, - _ESI_CATEGORY_CORPORATION, _ESI_CATEGORY_CHARACTER, + _ESI_CATEGORY_CORPORATION, _ESI_CATEGORY_REGION, - _ESI_CATEGORY_SOLARSYSTEM + _ESI_CATEGORY_SOLARSYSTEM, ) - _BASE_URL = 'https://zkillboard.com' diff --git a/allianceauth/eveonline/managers.py b/allianceauth/eveonline/managers.py index 5e849edc..eff9b31e 100644 --- a/allianceauth/eveonline/managers.py +++ b/allianceauth/eveonline/managers.py @@ -1,6 +1,7 @@ import logging from django.db import models + from . import providers logger = logging.getLogger(__name__) diff --git a/allianceauth/eveonline/migrations/0001_initial.py b/allianceauth/eveonline/migrations/0001_initial.py index a647ca0b..d45d329c 100644 --- a/allianceauth/eveonline/migrations/0001_initial.py +++ b/allianceauth/eveonline/migrations/0001_initial.py @@ -1,8 +1,8 @@ # Generated by Django 1.10.1 on 2016-09-05 21:39 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/eveonline/migrations/0003_auto_20161026_0149.py b/allianceauth/eveonline/migrations/0003_auto_20161026_0149.py index 0dda48fa..9cfdef65 100644 --- a/allianceauth/eveonline/migrations/0003_auto_20161026_0149.py +++ b/allianceauth/eveonline/migrations/0003_auto_20161026_0149.py @@ -1,8 +1,8 @@ # Generated by Django 1.10.2 on 2016-10-26 01:49 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/eveonline/migrations/0009_on_delete.py b/allianceauth/eveonline/migrations/0009_on_delete.py index d47b068b..668ca3da 100644 --- a/allianceauth/eveonline/migrations/0009_on_delete.py +++ b/allianceauth/eveonline/migrations/0009_on_delete.py @@ -1,7 +1,7 @@ # Generated by Django 1.11.5 on 2017-09-28 02:16 -from django.db import migrations, models import django.db.models.deletion +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/allianceauth/eveonline/models.py b/allianceauth/eveonline/models.py index 85993cbd..6c9e621d 100644 --- a/allianceauth/eveonline/models.py +++ b/allianceauth/eveonline/models.py @@ -1,8 +1,8 @@ import logging -from typing import Union from django.core.exceptions import ObjectDoesNotExist from django.db import models + from esi.models import Token from allianceauth.notifications import notify @@ -80,7 +80,8 @@ class EveAllianceInfo(models.Model): class Meta: indexes = [models.Index(fields=['executor_corp_id',])] - + def __str__(self): + return self.alliance_name def populate_alliance(self): alliance = self.provider.get_alliance(self.alliance_id) for corp_id in alliance.corp_ids: @@ -100,8 +101,7 @@ class EveAllianceInfo(models.Model): self.save() return self - def __str__(self): - return self.alliance_name + @staticmethod def generic_logo_url( @@ -152,7 +152,8 @@ class EveCorporationInfo(models.Model): class Meta: indexes = [models.Index(fields=['ceo_id',]),] - + def __str__(self): + return self.corporation_name def update_corporation(self, corp: providers.Corporation = None): if corp is None: corp = self.provider.get_corporation(self.corporation_id) @@ -165,8 +166,7 @@ class EveCorporationInfo(models.Model): self.save() return self - def __str__(self): - return self.corporation_name + @staticmethod def generic_logo_url( @@ -209,10 +209,10 @@ class EveCharacter(models.Model): corporation_name = models.CharField(max_length=254) corporation_ticker = models.CharField(max_length=5) alliance_id = models.PositiveIntegerField(blank=True, null=True, default=None) - alliance_name = models.CharField(max_length=254, blank=True, null=True, default='') - alliance_ticker = models.CharField(max_length=5, blank=True, null=True, default='') - faction_id = models.PositiveIntegerField(blank=True, null=True, default=None) - faction_name = models.CharField(max_length=254, blank=True, null=True, default='') + alliance_name = models.CharField(max_length=254, blank=True, default='') + alliance_ticker = models.CharField(max_length=5, blank=True, default='') + faction_id = models.PositiveIntegerField(blank=True, default=None) + faction_name = models.CharField(max_length=254, blank=True, default='') objects = EveCharacterManager() provider = EveCharacterProviderManager() diff --git a/allianceauth/eveonline/providers.py b/allianceauth/eveonline/providers.py index d8c30604..9ba2db92 100644 --- a/allianceauth/eveonline/providers.py +++ b/allianceauth/eveonline/providers.py @@ -1,16 +1,16 @@ import logging import os -from bravado.exception import HTTPNotFound, HTTPUnprocessableEntity, HTTPError +from bravado.exception import HTTPError, HTTPNotFound, HTTPUnprocessableEntity from jsonschema.exceptions import RefResolutionError from django.conf import settings + from esi.clients import esi_client_factory from allianceauth import __version__ from allianceauth.utils.django import StartupCommand - SWAGGER_SPEC_PATH = os.path.join(os.path.dirname( os.path.abspath(__file__)), 'swagger.json' ) diff --git a/allianceauth/eveonline/tasks.py b/allianceauth/eveonline/tasks.py index ce2b4219..e753ab93 100644 --- a/allianceauth/eveonline/tasks.py +++ b/allianceauth/eveonline/tasks.py @@ -2,9 +2,8 @@ import logging from celery import shared_task -from .models import EveAllianceInfo, EveCharacter, EveCorporationInfo from . import providers - +from .models import EveAllianceInfo, EveCharacter, EveCorporationInfo logger = logging.getLogger(__name__) diff --git a/allianceauth/eveonline/templatetags/evelinks.py b/allianceauth/eveonline/templatetags/evelinks.py index e5f44440..4ca6b022 100644 --- a/allianceauth/eveonline/templatetags/evelinks.py +++ b/allianceauth/eveonline/templatetags/evelinks.py @@ -14,8 +14,8 @@ from django import template -from ..models import EveCharacter, EveCorporationInfo, EveAllianceInfo -from ..evelinks import eveimageserver, evewho, dotlan, zkillboard +from ..evelinks import dotlan, eveimageserver, evewho, zkillboard +from ..models import EveAllianceInfo, EveCharacter, EveCorporationInfo register = template.Library() @@ -30,7 +30,7 @@ def _generic_character_url( eve_obj: EveCharacter ) -> str: """returns character URL for given provider and object""" - my_func = getattr(provider, 'character_url') + my_func = provider.character_url if isinstance(eve_obj, EveCharacter): return my_func(getattr(eve_obj, obj_prop)) @@ -47,8 +47,8 @@ def _generic_corporation_url( eve_obj: object ) -> str: """returns corporation URL for given provider and object""" - my_func = getattr(provider, 'corporation_url') - if isinstance(eve_obj, (EveCharacter, EveCorporationInfo)): + my_func = provider.corporation_url + if isinstance(eve_obj, EveCharacter | EveCorporationInfo): return my_func(getattr(eve_obj, obj_prop)) elif eve_obj is None: @@ -64,7 +64,7 @@ def _generic_alliance_url( eve_obj: object ) -> str: """returns alliance URL for given provider and object""" - my_func = getattr(provider, 'alliance_url') + my_func = provider.alliance_url if isinstance(eve_obj, EveCharacter): if eve_obj.alliance_id: diff --git a/allianceauth/eveonline/tests/esi_client_stub.py b/allianceauth/eveonline/tests/esi_client_stub.py index 1eadfbd3..9382355c 100644 --- a/allianceauth/eveonline/tests/esi_client_stub.py +++ b/allianceauth/eveonline/tests/esi_client_stub.py @@ -10,7 +10,7 @@ class BravadoResponseStub: self.reason = reason self.status_code = status_code self.text = text - self.headers = headers if headers else dict() + self.headers = headers if headers else {} self.raw_bytes = raw_bytes def __str__(self): diff --git a/allianceauth/eveonline/tests/test_managers.py b/allianceauth/eveonline/tests/test_managers.py index 5bab0771..61512ae5 100644 --- a/allianceauth/eveonline/tests/test_managers.py +++ b/allianceauth/eveonline/tests/test_managers.py @@ -2,8 +2,8 @@ from unittest import mock from django.test import TestCase -from ..models import EveCharacter, EveCorporationInfo, EveAllianceInfo -from ..providers import Character, Corporation, Alliance +from ..models import EveAllianceInfo, EveCharacter, EveCorporationInfo +from ..providers import Alliance, Character, Corporation class EveCharacterProviderManagerTestCase(TestCase): @@ -58,7 +58,7 @@ class EveCharacterManagerTestCase(TestCase): @mock.patch('allianceauth.eveonline.managers.providers.provider') def test_update_character(self, provider): # Also covers Model.update_character - existing = EveCharacter.objects.create( + EveCharacter.objects.create( character_id=1234, character_name='character.name', corporation_id=23457, diff --git a/allianceauth/eveonline/tests/test_models.py b/allianceauth/eveonline/tests/test_models.py index 94c9614a..e4124718 100644 --- a/allianceauth/eveonline/tests/test_models.py +++ b/allianceauth/eveonline/tests/test_models.py @@ -2,6 +2,7 @@ from unittest.mock import Mock, patch from django.core.exceptions import ObjectDoesNotExist from django.test import TestCase + from esi.models import Token from allianceauth.tests.auth_utils import AuthUtils @@ -62,7 +63,7 @@ class EveCharacterTestCase(TestCase): ) with self.assertRaises(EveCorporationInfo.DoesNotExist): - character.corporation + _ = character.corporation def test_alliance_prop(self): """ @@ -111,7 +112,7 @@ class EveCharacterTestCase(TestCase): ) with self.assertRaises(EveAllianceInfo.DoesNotExist): - character.alliance + _ = character.alliance def test_alliance_prop_none(self): """ @@ -169,7 +170,7 @@ class EveCharacterTestCase(TestCase): ) with self.assertRaises(EveFactionInfo.DoesNotExist): - character.faction + _ = character.faction def test_faction_prop_none(self): """ diff --git a/allianceauth/eveonline/tests/test_providers.py b/allianceauth/eveonline/tests/test_providers.py index 95f4f069..3110979f 100644 --- a/allianceauth/eveonline/tests/test_providers.py +++ b/allianceauth/eveonline/tests/test_providers.py @@ -6,20 +6,20 @@ from jsonschema.exceptions import RefResolutionError from django.test import TestCase -from . import set_logger -from .esi_client_stub import EsiClientStub from ..providers import ( - ObjectNotFound, - Entity, + Alliance, AllianceMixin, - FactionMixin, Character, Corporation, - Alliance, - ItemType, + Entity, EveProvider, - EveSwaggerProvider + EveSwaggerProvider, + FactionMixin, + ItemType, + ObjectNotFound, ) +from . import set_logger +from .esi_client_stub import EsiClientStub MODULE_PATH = 'allianceauth.eveonline.providers' SWAGGER_OLD_SPEC_PATH = os.path.join(os.path.dirname( @@ -544,7 +544,7 @@ class TestEveSwaggerProvider(TestCase): } mock_result = Mock() if isinstance(characters, list): - characters_result = list() + characters_result = [] for character_id in characters: if character_id in character_data: characters_result.append(character_data[character_id]) diff --git a/allianceauth/fleetactivitytracking/admin.py b/allianceauth/fleetactivitytracking/admin.py index 6ac8ca30..88d3d8f4 100644 --- a/allianceauth/fleetactivitytracking/admin.py +++ b/allianceauth/fleetactivitytracking/admin.py @@ -1,6 +1,6 @@ from django.contrib import admin -from allianceauth.fleetactivitytracking.models import Fatlink, Fat +from allianceauth.fleetactivitytracking.models import Fat, Fatlink admin.site.register(Fatlink) admin.site.register(Fat) diff --git a/allianceauth/fleetactivitytracking/auth_hooks.py b/allianceauth/fleetactivitytracking/auth_hooks.py index fc5821b2..57b0362d 100644 --- a/allianceauth/fleetactivitytracking/auth_hooks.py +++ b/allianceauth/fleetactivitytracking/auth_hooks.py @@ -1,9 +1,11 @@ -from allianceauth.menu.hooks import MenuItemHook -from . import urls from django.utils.translation import gettext_lazy as _ + from allianceauth import hooks +from allianceauth.menu.hooks import MenuItemHook from allianceauth.services.hooks import UrlHook +from . import urls + @hooks.register('menu_item_hook') def register_menu(): diff --git a/allianceauth/fleetactivitytracking/migrations/0002_auto_20160905_2220.py b/allianceauth/fleetactivitytracking/migrations/0002_auto_20160905_2220.py index 813a7f84..5241d390 100644 --- a/allianceauth/fleetactivitytracking/migrations/0002_auto_20160905_2220.py +++ b/allianceauth/fleetactivitytracking/migrations/0002_auto_20160905_2220.py @@ -1,6 +1,7 @@ # Generated by Django 1.10.1 on 2016-09-05 22:20 import datetime + from django.db import migrations, models diff --git a/allianceauth/fleetactivitytracking/migrations/0003_auto_20160906_2354.py b/allianceauth/fleetactivitytracking/migrations/0003_auto_20160906_2354.py index 435f0a9a..cc14b7ea 100644 --- a/allianceauth/fleetactivitytracking/migrations/0003_auto_20160906_2354.py +++ b/allianceauth/fleetactivitytracking/migrations/0003_auto_20160906_2354.py @@ -1,7 +1,7 @@ # Generated by Django 1.10.1 on 2016-09-06 23:54 -from django.db import migrations, models import django.utils.timezone +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/allianceauth/fleetactivitytracking/models.py b/allianceauth/fleetactivitytracking/models.py index 3cbd3d63..b4041efc 100644 --- a/allianceauth/fleetactivitytracking/models.py +++ b/allianceauth/fleetactivitytracking/models.py @@ -29,4 +29,4 @@ class Fat(models.Model): unique_together = (('character', 'fatlink'),) def __str__(self): - return "Fat-link for %s" % self.character.character_name + return f"Fat-link for {self.character.character_name}" diff --git a/allianceauth/fleetactivitytracking/urls.py b/allianceauth/fleetactivitytracking/urls.py index 41603150..e38f9154 100644 --- a/allianceauth/fleetactivitytracking/urls.py +++ b/allianceauth/fleetactivitytracking/urls.py @@ -1,6 +1,7 @@ from django.urls import path from . import views + app_name = 'fleetactivitytracking' urlpatterns = [ diff --git a/allianceauth/fleetactivitytracking/views.py b/allianceauth/fleetactivitytracking/views.py index 232fa456..d7c3ee07 100644 --- a/allianceauth/fleetactivitytracking/views.py +++ b/allianceauth/fleetactivitytracking/views.py @@ -2,24 +2,23 @@ import datetime import logging import os -from allianceauth.authentication.models import CharacterOwnership from django.contrib import messages -from django.contrib.auth.decorators import login_required -from django.contrib.auth.decorators import permission_required +from django.contrib.auth.decorators import login_required, permission_required from django.contrib.auth.models import User -from django.core.exceptions import ValidationError, ObjectDoesNotExist -from django.shortcuts import render, redirect, get_object_or_404, Http404 +from django.core.exceptions import ObjectDoesNotExist, ValidationError +from django.shortcuts import get_object_or_404, redirect, render from django.utils import timezone -from django.utils.translation import gettext_lazy as _ -from esi.decorators import token_required -from allianceauth.eveonline.providers import provider -from .forms import FatlinkForm -from .models import Fatlink, Fat from django.utils.crypto import get_random_string +from django.utils.translation import gettext_lazy as _ -from allianceauth.eveonline.models import EveAllianceInfo -from allianceauth.eveonline.models import EveCharacter -from allianceauth.eveonline.models import EveCorporationInfo +from esi.decorators import token_required + +from allianceauth.authentication.models import CharacterOwnership +from allianceauth.eveonline.models import EveAllianceInfo, EveCharacter, EveCorporationInfo +from allianceauth.eveonline.providers import provider + +from .forms import FatlinkForm +from .models import Fat, Fatlink SWAGGER_SPEC_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'swagger.json') """ @@ -50,7 +49,7 @@ class CorpStat: try: return "%.2f" % (float(self.n_fats) / float(self.corp.member_count)) except ZeroDivisionError: - return "%.2f" % 0 + return f"{0:.2f}" class MemberStat: @@ -72,7 +71,7 @@ class MemberStat: try: return "%.2f" % (float(self.n_fats) / float(self.n_chars)) except ZeroDivisionError: - return "%.2f" % 0 + return f"{0:.2f}" def first_day_of_next_month(year, month): @@ -95,7 +94,7 @@ def fatlink_view(request): # If the user has the right privileges the site will also show the latest fatlinks with the options to add VIPs and # manually add players. user = request.user - logger.debug("fatlink_view called by user %s" % request.user) + logger.debug(f"fatlink_view called by user {request.user}") latest_fats = Fat.objects.select_related('character', 'fatlink').filter(user=user).order_by('-id')[:5] if user.has_perm('auth.fleetactivitytracking'): @@ -182,7 +181,7 @@ def fatlink_personal_statistics_view(request, year=datetime.date.today().year): logger.debug("Personal statistics view for year %i called by %s" % (year, request.user)) user = request.user - logger.debug("fatlink_personal_statistics_view called by user %s" % request.user) + logger.debug(f"fatlink_personal_statistics_view called by user {request.user}") personal_fats = Fat.objects.select_related('fatlink').filter(user=user).order_by('id') @@ -227,7 +226,7 @@ def fatlink_monthly_personal_statistics_view(request, year, month, char_id=None) personal_fats = Fat.objects.filter(user=user)\ .filter(fatlink__fatdatetime__gte=start_of_month).filter(fatlink__fatdatetime__lt=start_of_next_month) - ship_statistics = dict() + ship_statistics = {} n_fats = 0 for fat in personal_fats: ship_statistics[fat.shiptype] = ship_statistics.setdefault(fat.shiptype, 0) + 1 @@ -300,7 +299,7 @@ def click_fatlink_view(request, token, fat_hash=None): except ValidationError as e: err_messages = [] - for errorname, message in e.message_dict.items(): + for _errorname, message in e.message_dict.items(): err_messages.append(message[0]) messages.error(request, ' '.join(err_messages)) @@ -330,12 +329,12 @@ def click_fatlink_view(request, token, fat_hash=None): @login_required @permission_required('auth.fleetactivitytracking') def create_fatlink_view(request): - logger.debug("create_fatlink_view called by user %s" % request.user) + logger.debug(f"create_fatlink_view called by user {request.user}") if request.method == 'POST': - logger.debug("Post request to create_fatlink_view by user %s" % request.user) + logger.debug(f"Post request to create_fatlink_view by user {request.user}") form = FatlinkForm(request.POST) if 'submit_fat' in request.POST: - logger.debug("Submitting fleetactivitytracking by user %s" % request.user) + logger.debug(f"Submitting fleetactivitytracking by user {request.user}") if form.is_valid(): fatlink = Fatlink() fatlink.fleet = form.cleaned_data["fleet"] @@ -349,7 +348,7 @@ def create_fatlink_view(request): except ValidationError as e: form = FatlinkForm() messages = [] - for errorname, message in e.message_dict.items(): + for _errorname, message in e.message_dict.items(): messages.append(message[0].decode()) context = {'form': form, 'errormessages': messages} return render(request, 'fleetactivitytracking/fatlinkcreate.html', context=context) @@ -361,7 +360,7 @@ def create_fatlink_view(request): else: form = FatlinkForm() - logger.debug("Returning empty form to user %s" % request.user) + logger.debug(f"Returning empty form to user {request.user}") context = {'form': form} @@ -371,7 +370,7 @@ def create_fatlink_view(request): @login_required @permission_required('auth.fleetactivitytracking') def modify_fatlink_view(request, fat_hash=None): - logger.debug("modify_fatlink_view called by user %s" % request.user) + logger.debug(f"modify_fatlink_view called by user {request.user}") fatlink = get_object_or_404(Fatlink, hash=fat_hash) if request.GET.get('removechar', None): @@ -382,7 +381,7 @@ def modify_fatlink_view(request, fat_hash=None): Fat.objects.filter(fatlink=fatlink).filter(character=character).delete() if request.GET.get('deletefat', None): - logger.debug("Removing fleetactivitytracking %s" % fatlink) + logger.debug(f"Removing fleetactivitytracking {fatlink}") fatlink.delete() return redirect('fatlink:view') diff --git a/allianceauth/framework/api/evecharacter.py b/allianceauth/framework/api/evecharacter.py index d6a77f05..539f326b 100644 --- a/allianceauth/framework/api/evecharacter.py +++ b/allianceauth/framework/api/evecharacter.py @@ -2,7 +2,6 @@ Alliance Auth Evecharacter API """ -from typing import Optional from django.contrib.auth.models import User diff --git a/allianceauth/framework/api/user.py b/allianceauth/framework/api/user.py index e1597e72..1be7fbd4 100644 --- a/allianceauth/framework/api/user.py +++ b/allianceauth/framework/api/user.py @@ -2,7 +2,6 @@ Alliance Auth User API """ -from typing import Optional from django.contrib.auth.models import User diff --git a/allianceauth/framework/tests/test_api_user.py b/allianceauth/framework/tests/test_api_user.py index 1b43b75c..47398063 100644 --- a/allianceauth/framework/tests/test_api_user.py +++ b/allianceauth/framework/tests/test_api_user.py @@ -10,9 +10,9 @@ from django.test import TestCase # Alliance Auth from allianceauth.framework.api.user import ( - get_sentinel_user, get_main_character_from_user, - get_main_character_name_from_user + get_main_character_name_from_user, + get_sentinel_user, ) from allianceauth.tests.auth_utils import AuthUtils diff --git a/allianceauth/groupmanagement/admin.py b/allianceauth/groupmanagement/admin.py index d51cf7d2..90d83506 100644 --- a/allianceauth/groupmanagement/admin.py +++ b/allianceauth/groupmanagement/admin.py @@ -1,16 +1,9 @@ from django.apps import apps from django.contrib import admin - from django.contrib.auth.models import Group as BaseGroup, Permission, User from django.db.models import Count, Exists, OuterRef from django.db.models.functions import Lower -from django.db.models.signals import ( - m2m_changed, - post_delete, - post_save, - pre_delete, - pre_save -) +from django.db.models.signals import m2m_changed, post_delete, post_save, pre_delete, pre_save from django.dispatch import receiver from .forms import GroupAdminForm, ReservedGroupNameAdminForm @@ -172,7 +165,7 @@ class GroupAdmin(admin.ModelAdmin): return obj.has_leader or obj.has_leader_groups def _properties(self, obj): - properties = list() + properties = [] if _has_auto_groups and (obj.is_autogroup_corp or obj.is_autogroup_alliance): properties.append('Auto Group') elif obj.authgroup.internal: diff --git a/allianceauth/groupmanagement/auth_hooks.py b/allianceauth/groupmanagement/auth_hooks.py index 318d2095..1d46e64e 100644 --- a/allianceauth/groupmanagement/auth_hooks.py +++ b/allianceauth/groupmanagement/auth_hooks.py @@ -1,8 +1,8 @@ from django.utils.translation import gettext_lazy as _ -from allianceauth.menu.hooks import MenuItemHook -from allianceauth.services.hooks import UrlHook from allianceauth import hooks +from allianceauth.menu.hooks import MenuItemHook +from allianceauth.services.hooks import UrlHook from . import urls from .managers import GroupManager diff --git a/allianceauth/groupmanagement/managers.py b/allianceauth/groupmanagement/managers.py index ad8db92e..93e7789f 100644 --- a/allianceauth/groupmanagement/managers.py +++ b/allianceauth/groupmanagement/managers.py @@ -4,8 +4,8 @@ from django.contrib.auth.models import Group, User from django.db.models import Q, QuerySet from allianceauth.authentication.models import State -from .models import GroupRequest +from .models import GroupRequest logger = logging.getLogger(__name__) diff --git a/allianceauth/groupmanagement/migrations/0001_initial.py b/allianceauth/groupmanagement/migrations/0001_initial.py index c6112559..00ca959b 100644 --- a/allianceauth/groupmanagement/migrations/0001_initial.py +++ b/allianceauth/groupmanagement/migrations/0001_initial.py @@ -1,8 +1,8 @@ # Generated by Django 1.10.1 on 2016-09-05 21:39 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/groupmanagement/migrations/0002_auto_20160906_2354.py b/allianceauth/groupmanagement/migrations/0002_auto_20160906_2354.py index 76cef366..74574d76 100644 --- a/allianceauth/groupmanagement/migrations/0002_auto_20160906_2354.py +++ b/allianceauth/groupmanagement/migrations/0002_auto_20160906_2354.py @@ -1,7 +1,7 @@ # Generated by Django 1.10.1 on 2016-09-06 23:54 -from django.db import migrations, models import django.db.models.deletion +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/allianceauth/groupmanagement/migrations/0003_default_groups.py b/allianceauth/groupmanagement/migrations/0003_default_groups.py index afe1bed0..84472518 100644 --- a/allianceauth/groupmanagement/migrations/0003_default_groups.py +++ b/allianceauth/groupmanagement/migrations/0003_default_groups.py @@ -1,7 +1,7 @@ # Generated by Django 1.10.1 on 2016-09-09 23:22 from django.db import migrations -from django.conf import settings + class Migration(migrations.Migration): diff --git a/allianceauth/groupmanagement/migrations/0004_authgroup.py b/allianceauth/groupmanagement/migrations/0004_authgroup.py index e3c8848e..9aacb71f 100644 --- a/allianceauth/groupmanagement/migrations/0004_authgroup.py +++ b/allianceauth/groupmanagement/migrations/0004_authgroup.py @@ -1,9 +1,9 @@ # Generated by Django 1.10.2 on 2016-12-04 10:25 -from django.conf import settings -from django.db import migrations, models -from django.core.exceptions import ObjectDoesNotExist import django.db.models.deletion +from django.conf import settings +from django.core.exceptions import ObjectDoesNotExist +from django.db import migrations, models def internal_group(group): diff --git a/allianceauth/groupmanagement/migrations/0006_request_groups_perm.py b/allianceauth/groupmanagement/migrations/0006_request_groups_perm.py index 69544c9c..83a4a554 100644 --- a/allianceauth/groupmanagement/migrations/0006_request_groups_perm.py +++ b/allianceauth/groupmanagement/migrations/0006_request_groups_perm.py @@ -1,12 +1,9 @@ # Generated by Django 1.10.5 on 2017-02-04 07:17 -from django.db import migrations -from django.conf import settings -from django.core.exceptions import ObjectDoesNotExist -from django.contrib.auth.management import create_permissions - import logging +from django.db import migrations + logger = logging.getLogger(__name__) diff --git a/allianceauth/groupmanagement/migrations/0009_requestlog.py b/allianceauth/groupmanagement/migrations/0009_requestlog.py index aaff4927..d81d4ae4 100644 --- a/allianceauth/groupmanagement/migrations/0009_requestlog.py +++ b/allianceauth/groupmanagement/migrations/0009_requestlog.py @@ -1,8 +1,8 @@ # Generated by Django 2.0.6 on 2018-06-04 02:45 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/groupmanagement/migrations/0011_requestlog_date.py b/allianceauth/groupmanagement/migrations/0011_requestlog_date.py index fbe535ce..23f8157c 100644 --- a/allianceauth/groupmanagement/migrations/0011_requestlog_date.py +++ b/allianceauth/groupmanagement/migrations/0011_requestlog_date.py @@ -1,6 +1,7 @@ # Generated by Django 2.0.8 on 2018-12-07 08:56 import datetime + from django.db import migrations, models diff --git a/allianceauth/groupmanagement/migrations/0018_reservedgroupname.py b/allianceauth/groupmanagement/migrations/0018_reservedgroupname.py index 0349b9e2..0d0aa83e 100644 --- a/allianceauth/groupmanagement/migrations/0018_reservedgroupname.py +++ b/allianceauth/groupmanagement/migrations/0018_reservedgroupname.py @@ -1,7 +1,7 @@ # Generated by Django 3.2.9 on 2021-11-25 18:38 -from django.db import migrations, models import django.utils.timezone +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/allianceauth/groupmanagement/models.py b/allianceauth/groupmanagement/models.py index 19e15c72..23bba04b 100644 --- a/allianceauth/groupmanagement/models.py +++ b/allianceauth/groupmanagement/models.py @@ -1,4 +1,4 @@ -from typing import Set + from django.conf import settings from django.contrib.auth.models import Group, User @@ -52,6 +52,9 @@ class RequestLog(models.Model): request_actor = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) + def __str__(self): + return self.pk + def requestor(self): return self.request_info.split(":")[0] @@ -176,7 +179,7 @@ class AuthGroup(models.Model): permissions = ( ("request_groups", _("Can request non-public groups")), ) - default_permissions = tuple() + default_permissions = () def __str__(self): return self.group.name diff --git a/allianceauth/groupmanagement/signals.py b/allianceauth/groupmanagement/signals.py index 60bbeb80..951e9980 100644 --- a/allianceauth/groupmanagement/signals.py +++ b/allianceauth/groupmanagement/signals.py @@ -1,6 +1,7 @@ import logging + from django.contrib.auth.models import Group -from django.db.models.signals import pre_save, post_save +from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from allianceauth.authentication.signals import state_changed diff --git a/allianceauth/groupmanagement/tests/__init__.py b/allianceauth/groupmanagement/tests/__init__.py index 1446ef49..aa4816f5 100644 --- a/allianceauth/groupmanagement/tests/__init__.py +++ b/allianceauth/groupmanagement/tests/__init__.py @@ -3,9 +3,6 @@ from django.urls import reverse def get_admin_change_view_url(obj: object) -> str: return reverse( - 'admin:{}_{}_change'.format( - obj._meta.app_label, - type(obj).__name__.lower() - ), + f'admin:{obj._meta.app_label}_{type(obj).__name__.lower()}_change', args=(obj.pk,) ) diff --git a/allianceauth/groupmanagement/tests/test_admin.py b/allianceauth/groupmanagement/tests/test_admin.py index 3b9605a1..0f7a1ed1 100644 --- a/allianceauth/groupmanagement/tests/test_admin.py +++ b/allianceauth/groupmanagement/tests/test_admin.py @@ -10,7 +10,9 @@ from django.test import Client, RequestFactory, TestCase, override_settings from allianceauth.authentication.models import CharacterOwnership, State from allianceauth.eveonline.models import ( - EveAllianceInfo, EveCharacter, EveCorporationInfo, + EveAllianceInfo, + EveCharacter, + EveCorporationInfo, ) from allianceauth.tests.auth_utils import AuthUtils diff --git a/allianceauth/groupmanagement/tests/test_managers.py b/allianceauth/groupmanagement/tests/test_managers.py index f656d99e..2e7ddcb9 100644 --- a/allianceauth/groupmanagement/tests/test_managers.py +++ b/allianceauth/groupmanagement/tests/test_managers.py @@ -1,14 +1,14 @@ from django.contrib.auth.models import Group, User from django.test import TestCase -from allianceauth.eveonline.models import EveCorporationInfo, EveAllianceInfo +from allianceauth.eveonline.models import EveAllianceInfo, EveCorporationInfo from allianceauth.tests.auth_utils import AuthUtils -from ..models import GroupRequest from ..managers import GroupManager +from ..models import GroupRequest -class MockUserNotAuthenticated(): +class MockUserNotAuthenticated: def __init__(self): self.is_authenticated = False diff --git a/allianceauth/groupmanagement/tests/test_signals.py b/allianceauth/groupmanagement/tests/test_signals.py index efa35dda..f398f288 100644 --- a/allianceauth/groupmanagement/tests/test_signals.py +++ b/allianceauth/groupmanagement/tests/test_signals.py @@ -1,11 +1,10 @@ +from django.contrib.auth.models import Group, User from django.test import TestCase -from django.contrib.auth.models import User, Group -from allianceauth.eveonline.models import EveCorporationInfo from allianceauth.eveonline.autogroups.models import AutogroupsConfig +from allianceauth.eveonline.models import EveCorporationInfo from allianceauth.tests.auth_utils import AuthUtils - from ..models import ReservedGroupName diff --git a/allianceauth/groupmanagement/urls.py b/allianceauth/groupmanagement/urls.py index 5b27821b..a2d78830 100644 --- a/allianceauth/groupmanagement/urls.py +++ b/allianceauth/groupmanagement/urls.py @@ -1,4 +1,5 @@ from django.urls import path + from . import views app_name = "groupmanagement" diff --git a/allianceauth/groupmanagement/views.py b/allianceauth/groupmanagement/views.py index 1d1bba87..1c736573 100644 --- a/allianceauth/groupmanagement/views.py +++ b/allianceauth/groupmanagement/views.py @@ -21,7 +21,7 @@ logger = logging.getLogger(__name__) @login_required @user_passes_test(GroupManager.can_manage_groups) def group_management(request): - logger.debug("group_management called by user %s" % request.user) + logger.debug(f"group_management called by user {request.user}") acceptrequests = [] leaverequests = [] @@ -40,8 +40,7 @@ def group_management(request): else: acceptrequests.append(grouprequest) - logger.debug("Providing user {} with {} acceptrequests and {} leaverequests.".format( - request.user, len(acceptrequests), len(leaverequests))) + logger.debug(f"Providing user {request.user} with {len(acceptrequests)} acceptrequests and {len(leaverequests)} leaverequests.") show_leave_tab = ( getattr(settings, 'GROUPMANAGEMENT_AUTO_LEAVE', False) @@ -60,7 +59,7 @@ def group_management(request): @login_required @user_passes_test(GroupManager.can_manage_groups) def group_membership(request): - logger.debug("group_membership called by user %s" % request.user) + logger.debug(f"group_membership called by user {request.user}") # Get all open and closed groups if GroupManager.has_management_permission(request.user): # Full access @@ -79,7 +78,7 @@ def group_membership(request): @login_required @user_passes_test(GroupManager.can_manage_groups) def group_membership_audit(request, group_id): - logger.debug("group_management_audit called by user %s" % request.user) + logger.debug(f"group_management_audit called by user {request.user}") group = get_object_or_404(Group, id=group_id) try: # Check its a joinable group i.e. not corp or internal @@ -101,8 +100,8 @@ def group_membership_audit(request, group_id): @user_passes_test(GroupManager.can_manage_groups) def group_membership_list(request, group_id): logger.debug( - "group_membership_list called by user %s " - "for group id %s" % (request.user, group_id) + f"group_membership_list called by user {request.user} " + f"for group id {group_id}" ) group = get_object_or_404(Group, id=group_id) try: @@ -113,8 +112,8 @@ def group_membership_list(request, group_id): or not GroupManager.can_manage_group(request.user, group) ): logger.warning( - "User %s attempted to view the membership of group %s " - "but permission was denied" % (request.user, group_id) + f"User {request.user} attempted to view the membership of group {group_id} " + "but permission was denied" ) raise PermissionDenied @@ -122,7 +121,7 @@ def group_membership_list(request, group_id): raise Http404("Group does not exist") group_leaders = group.authgroup.group_leaders.all() - members = list() + members = [] for member in \ group.user_set\ .all()\ @@ -190,20 +189,18 @@ def group_accept_request(request, group_request_id): log = RequestLog(request_type=group_request.leave_request,group=group,request_info=group_request.__str__(),action=1,request_actor=request.user) log.save() group_request.delete() - logger.info("User {} accepted group request from user {} to group {}".format( - request.user, group_request.user, group_request.group.name)) + logger.info(f"User {request.user} accepted group request from user {group_request.user} to group {group_request.group.name}") notify(group_request.user, "Group Application Accepted", level="success", - message="Your application to %s has been accepted." % group_request.group) + message=f"Your application to {group_request.group} has been accepted.") messages.success(request, _('Accepted application from %(mainchar)s to %(group)s.') % {"mainchar": group_request.main_char, "group": group_request.group}) except PermissionDenied as p: logger.warning(f"User {request.user} attempted to accept group join request {group_request_id} but permission was denied") raise p - except: + except Exception: messages.error(request, _('An unhandled error occurred while processing the application from %(mainchar)s to %(group)s.') % {"mainchar": group_request.main_char, "group": group_request.group}) - logger.exception("Unhandled exception occurred while user {} attempting to accept grouprequest id {}.".format( - request.user, group_request_id)) + logger.exception(f"Unhandled exception occurred while user {request.user} attempting to accept grouprequest id {group_request_id}.") pass return redirect("groupmanagement:management") @@ -219,22 +216,20 @@ def group_reject_request(request, group_request_id): raise PermissionDenied if group_request: - logger.info("User {} rejected group request from user {} to group {}".format( - request.user, group_request.user, group_request.group.name)) + logger.info(f"User {request.user} rejected group request from user {group_request.user} to group {group_request.group.name}") log = RequestLog(request_type=group_request.leave_request,group=group_request.group,request_info=group_request.__str__(),action=0,request_actor=request.user) log.save() group_request.delete() - notify(group_request.user, "Group Application Rejected", level="danger", message="Your application to %s has been rejected." % group_request.group) + notify(group_request.user, "Group Application Rejected", level="danger", message=f"Your application to {group_request.group} has been rejected.") messages.success(request, _('Rejected application from %(mainchar)s to %(group)s.') % {"mainchar": group_request.main_char, "group": group_request.group}) except PermissionDenied as p: logger.warning(f"User {request.user} attempted to reject group join request {group_request_id} but permission was denied") raise p - except: + except Exception: messages.error(request, _('An unhandled error occurred while processing the application from %(mainchar)s to %(group)s.') % {"mainchar": group_request.main_char, "group": group_request.group}) - logger.exception("Unhandled exception occurred while user {} attempting to reject group request id {}".format( - request.user, group_request_id)) + logger.exception(f"Unhandled exception occurred while user {request.user} attempting to reject group request id {group_request_id}") pass return redirect("groupmanagement:management") @@ -256,20 +251,18 @@ def group_leave_accept_request(request, group_request_id): log = RequestLog(request_type=group_request.leave_request,group=group_request.group,request_info=group_request.__str__(),action=1,request_actor=request.user) log.save() group_request.delete() - logger.info("User {} accepted group leave request from user {} to group {}".format( - request.user, group_request.user, group_request.group.name)) + logger.info(f"User {request.user} accepted group leave request from user {group_request.user} to group {group_request.group.name}") notify(group_request.user, "Group Leave Request Accepted", level="success", - message="Your request to leave %s has been accepted." % group_request.group) + message=f"Your request to leave {group_request.group} has been accepted.") messages.success(request, _('Accepted application from %(mainchar)s to leave %(group)s.') % {"mainchar": group_request.main_char, "group": group_request.group}) except PermissionDenied as p: logger.warning(f"User {request.user} attempted to accept group leave request {group_request_id} but permission was denied") raise p - except: + except Exception: messages.error(request, _('An unhandled error occurred while processing the application from %(mainchar)s to leave %(group)s.') % { "mainchar": group_request.main_char, "group": group_request.group}) - logger.exception("Unhandled exception occurred while user {} attempting to accept group leave request id {}".format( - request.user, group_request_id)) + logger.exception(f"Unhandled exception occurred while user {request.user} attempting to accept group leave request id {group_request_id}") pass return redirect("groupmanagement:management") @@ -289,19 +282,17 @@ def group_leave_reject_request(request, group_request_id): log = RequestLog(request_type=group_request.leave_request,group=group_request.group,request_info=group_request.__str__(),action=0,request_actor=request.user) log.save() group_request.delete() - logger.info("User {} rejected group leave request from user {} for group {}".format( - request.user, group_request.user, group_request.group.name)) - notify(group_request.user, "Group Leave Request Rejected", level="danger", message="Your request to leave %s has been rejected." % group_request.group) + logger.info(f"User {request.user} rejected group leave request from user {group_request.user} for group {group_request.group.name}") + notify(group_request.user, "Group Leave Request Rejected", level="danger", message=f"Your request to leave {group_request.group} has been rejected.") messages.success(request, _('Rejected application from %(mainchar)s to leave %(group)s.') % { "mainchar": group_request.main_char, "group": group_request.group}) except PermissionDenied as p: logger.warning(f"User {request.user} attempted to reject group leave request {group_request_id} but permission was denied") raise p - except: + except Exception: messages.error(request, _('An unhandled error occurred while processing the application from %(mainchar)s to leave %(group)s.') % { "mainchar": group_request.main_char, "group": group_request.group}) - logger.exception("Unhandled exception occurred while user {} attempting to reject group leave request id {}".format( - request.user, group_request_id)) + logger.exception(f"Unhandled exception occurred while user {request.user} attempting to reject group leave request id {group_request_id}") pass return redirect("groupmanagement:management") @@ -309,7 +300,7 @@ def group_leave_reject_request(request, group_request_id): @login_required def groups_view(request): - logger.debug("groups_view called by user %s" % request.user) + logger.debug(f"groups_view called by user {request.user}") groups_qs = GroupManager.get_joinable_groups_for_user( request.user, include_hidden=False diff --git a/allianceauth/hooks.py b/allianceauth/hooks.py index 0a91942b..7262f53e 100644 --- a/allianceauth/hooks.py +++ b/allianceauth/hooks.py @@ -30,13 +30,12 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Based on https://github.com/torchbox/wagtail/blob/master/wagtail/wagtailcore/hooks.py """ +import logging from importlib import import_module from django.apps import apps from django.utils.module_loading import module_has_submodule -import logging - logger = logging.getLogger(__name__) _hooks = {} # Dict of Name: Fn's of registered hooks @@ -64,7 +63,7 @@ def register(name, fn=None): """ def _hook_add(func): if name not in _hooks: - logger.debug("Creating new hook %s" % name) + logger.debug(f"Creating new hook {name}") _hooks[name] = [] logger.debug(f'Registering hook {name} for function {fn}') @@ -110,7 +109,7 @@ def register_all_hooks(): if not _all_hooks_registered: logger.debug("Searching for hooks") hooks = list(get_app_submodules('auth_hooks')) - logger.debug("Got %s hooks" % len(hooks)) + logger.debug(f"Got {len(hooks)} hooks") _all_hooks_registered = True @@ -133,6 +132,6 @@ class DashboardItemHook: try: logger.debug(f"Rendering {self.view_function} to dashboard") return self.view_function(request) - except Exception as e: + except Exception: logger.exception(f"Rendering {self.view_function} failed!") return "" diff --git a/allianceauth/hrapplications/admin.py b/allianceauth/hrapplications/admin.py index f1075da7..3381da0f 100644 --- a/allianceauth/hrapplications/admin.py +++ b/allianceauth/hrapplications/admin.py @@ -1,7 +1,13 @@ from django.contrib import admin -from .models import Application, ApplicationChoice, ApplicationComment, ApplicationForm, ApplicationQuestion, \ - ApplicationResponse +from .models import ( + Application, + ApplicationChoice, + ApplicationComment, + ApplicationForm, + ApplicationQuestion, + ApplicationResponse, +) class ChoiceInline(admin.TabularInline): diff --git a/allianceauth/hrapplications/managers.py b/allianceauth/hrapplications/managers.py index 7c518520..4e41e5c9 100644 --- a/allianceauth/hrapplications/managers.py +++ b/allianceauth/hrapplications/managers.py @@ -1,6 +1,6 @@ + from django.contrib.auth.models import User from django.db import models -from typing import Optional class ApplicationManager(models.Manager): diff --git a/allianceauth/hrapplications/migrations/0001_initial.py b/allianceauth/hrapplications/migrations/0001_initial.py index 466e8b18..7b094c65 100644 --- a/allianceauth/hrapplications/migrations/0001_initial.py +++ b/allianceauth/hrapplications/migrations/0001_initial.py @@ -1,8 +1,8 @@ # Generated by Django 1.10.1 on 2016-09-05 21:39 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/hrapplications/migrations/0002_choices_for_questions.py b/allianceauth/hrapplications/migrations/0002_choices_for_questions.py index 4687a7d6..01815ff7 100644 --- a/allianceauth/hrapplications/migrations/0002_choices_for_questions.py +++ b/allianceauth/hrapplications/migrations/0002_choices_for_questions.py @@ -1,7 +1,7 @@ # Generated by Django 1.11.4 on 2017-08-23 19:46 -from django.db import migrations, models import django.db.models.deletion +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/allianceauth/hrapplications/migrations/0005_sorted_questions.py b/allianceauth/hrapplications/migrations/0005_sorted_questions.py index 7e32e458..5eabae54 100644 --- a/allianceauth/hrapplications/migrations/0005_sorted_questions.py +++ b/allianceauth/hrapplications/migrations/0005_sorted_questions.py @@ -1,9 +1,10 @@ # Generated by Django 1.10.5 on 2017-03-27 03:29 -from django.db import migrations import sortedm2m.fields from sortedm2m.operations import AlterSortedManyToManyField +from django.db import migrations + class Migration(migrations.Migration): diff --git a/allianceauth/hrapplications/models.py b/allianceauth/hrapplications/models.py index 4767ec7f..2b3414d6 100644 --- a/allianceauth/hrapplications/models.py +++ b/allianceauth/hrapplications/models.py @@ -1,6 +1,7 @@ +from sortedm2m.fields import SortedManyToManyField + from django.contrib.auth.models import User from django.db import models -from sortedm2m.fields import SortedManyToManyField from allianceauth.eveonline.models import EveCharacter, EveCorporationInfo @@ -9,7 +10,7 @@ from .managers import ApplicationManager class ApplicationQuestion(models.Model): title = models.CharField(max_length=254, verbose_name='Question') - help_text = models.CharField(max_length=254, blank=True, null=True) + help_text = models.CharField(max_length=254, blank=True) multi_select = models.BooleanField(default=False) def __str__(self): @@ -42,8 +43,6 @@ class Application(models.Model): objects = ApplicationManager() - def __str__(self): - return str(self.user) + " Application To " + str(self.form) class Meta: permissions = ( @@ -51,6 +50,9 @@ class Application(models.Model): ('view_apis', 'Can view applicant APIs'),) unique_together = ('form', 'user') + def __str__(self): + return str(self.user) + " Application To " + str(self.form) + @property def main_character(self): return self.user.profile.main_character @@ -73,12 +75,12 @@ class ApplicationResponse(models.Model): question = models.ForeignKey(ApplicationQuestion, on_delete=models.CASCADE) application = models.ForeignKey(Application, on_delete=models.CASCADE, related_name='responses') answer = models.TextField() - + class Meta: + unique_together = ('question', 'application') def __str__(self): return str(self.application) + " Answer To " + str(self.question) - class Meta: - unique_together = ('question', 'application') + class ApplicationComment(models.Model): diff --git a/allianceauth/hrapplications/tests.py b/allianceauth/hrapplications/tests.py index 7dab4cd1..b9b8ff1e 100644 --- a/allianceauth/hrapplications/tests.py +++ b/allianceauth/hrapplications/tests.py @@ -4,7 +4,7 @@ from django.test import TestCase from allianceauth.eveonline.models import EveCorporationInfo from allianceauth.tests.auth_utils import AuthUtils -from .models import Application, ApplicationForm, ApplicationQuestion, ApplicationChoice +from .models import Application, ApplicationChoice, ApplicationForm, ApplicationQuestion class TestApplicationManagersPendingRequestsCountForUser(TestCase): diff --git a/allianceauth/hrapplications/views.py b/allianceauth/hrapplications/views.py index 789428e2..2102b663 100644 --- a/allianceauth/hrapplications/views.py +++ b/allianceauth/hrapplications/views.py @@ -1,18 +1,13 @@ import logging -from django.contrib.auth.decorators import login_required -from django.contrib.auth.decorators import permission_required -from django.contrib.auth.decorators import user_passes_test -from django.shortcuts import render, get_object_or_404, redirect, Http404 +from django.contrib.auth.decorators import login_required, permission_required, user_passes_test from django.db.models import Q -from .models import Application -from .models import ApplicationComment -from .models import ApplicationForm -from .models import ApplicationResponse +from django.shortcuts import Http404, get_object_or_404, redirect, render + from allianceauth.notifications import notify -from .forms import HRApplicationCommentForm -from .forms import HRApplicationSearchForm +from .forms import HRApplicationCommentForm, HRApplicationSearchForm +from .models import Application, ApplicationComment, ApplicationForm, ApplicationResponse logger = logging.getLogger(__name__) @@ -23,7 +18,7 @@ def create_application_test(user): @login_required def hr_application_management_view(request): - logger.debug("hr_application_management_view called by user %s" % request.user) + logger.debug(f"hr_application_management_view called by user {request.user}") corp_applications = [] finished_corp_applications = [] main_char = request.user.profile.main_character @@ -38,8 +33,7 @@ def hr_application_management_view(request): corp_applications = base_app_query.filter(form=app_form).filter(approved=None).order_by('-created') finished_corp_applications = base_app_query.filter(form=app_form).filter( approved__in=[True, False]).order_by('-created') - logger.debug("Retrieved {} personal, {} corp applications for {}".format( - len(request.user.applications.all()), len(corp_applications), request.user)) + logger.debug(f"Retrieved {len(request.user.applications.all())} personal, {len(corp_applications)} corp applications for {request.user}") context = { 'personal_apps': request.user.applications.all(), 'applications': corp_applications, @@ -122,7 +116,7 @@ def hr_application_view(request, app_id): if request.method == 'POST': if request.user.has_perm('hrapplications.add_applicationcomment'): form = HRApplicationCommentForm(request.POST) - logger.debug("Request type POST contains form valid: %s" % form.is_valid()) + logger.debug(f"Request type POST contains form valid: {form.is_valid()}") if form.is_valid(): comment = ApplicationComment() comment.application = app @@ -132,7 +126,7 @@ def hr_application_view(request, app_id): logger.info(f"Saved comment by user {request.user} to {app}") return redirect('hrapplications:view', app_id) else: - logger.warning("User %s does not have permission to add ApplicationComments" % request.user) + logger.warning(f"User {request.user} does not have permission to add ApplicationComments") return redirect('hrapplications:view', app_id) else: logger.debug("Returning blank HRApplication comment form.") @@ -155,7 +149,7 @@ def hr_application_remove(request, app_id): app = get_object_or_404(Application, pk=app_id) logger.info(f"User {request.user} deleting {app}") app.delete() - notify(app.user, "Application Deleted", message="Your application to %s was deleted." % app.form.corp) + notify(app.user, "Application Deleted", message=f"Your application to {app.form.corp} was deleted.") return redirect('hrapplications:index') @@ -169,7 +163,7 @@ def hr_application_approve(request, app_id): logger.info(f"User {request.user} approving {app}") app.approved = True app.save() - notify(app.user, "Application Accepted", message="Your application to %s has been approved." % app.form.corp, level="success") + notify(app.user, "Application Accepted", message=f"Your application to {app.form.corp} has been approved.", level="success") else: logger.warning(f"User {request.user} not authorized to approve {app}") return redirect('hrapplications:index') @@ -185,7 +179,7 @@ def hr_application_reject(request, app_id): logger.info(f"User {request.user} rejecting {app}") app.approved = False app.save() - notify(app.user, "Application Rejected", message="Your application to %s has been rejected." % app.form.corp, level="danger") + notify(app.user, "Application Rejected", message=f"Your application to {app.form.corp} has been rejected.", level="danger") else: logger.warning(f"User {request.user} not authorized to reject {app}") return redirect('hrapplications:index') @@ -194,10 +188,10 @@ def hr_application_reject(request, app_id): @login_required @permission_required('auth.human_resources') def hr_application_search(request): - logger.debug("hr_application_search called by user %s" % request.user) + logger.debug(f"hr_application_search called by user {request.user}") if request.method == 'POST': form = HRApplicationSearchForm(request.POST) - logger.debug("Request type POST contains form valid: %s" % form.is_valid()) + logger.debug(f"Request type POST contains form valid: {form.is_valid()}") if form.is_valid(): searchstring = form.cleaned_data['search_string'].lower() applications = set() @@ -209,7 +203,7 @@ def hr_application_search(request): form__corp__corporation_id=request.user.profile.main_character.corporation_id) except AttributeError: logger.warning( - "User %s missing main character model: unable to filter applications to search" % request.user) + f"User {request.user} missing main character model: unable to filter applications to search") applications = app_list.filter( Q(user__profile__main_character__character_name__icontains=searchstring) | @@ -225,12 +219,12 @@ def hr_application_search(request): return render(request, 'hrapplications/searchview.html', context=context) else: - logger.debug("Form invalid - returning for user %s to retry." % request.user) + logger.debug(f"Form invalid - returning for user {request.user} to retry.") context = {'applications': None, 'search_form': form} return render(request, 'hrapplications/searchview.html', context=context) else: - logger.debug("Returning empty search form for user %s" % request.user) + logger.debug(f"Returning empty search form for user {request.user}") return redirect("hrapplications:view") diff --git a/allianceauth/menu/admin.py b/allianceauth/menu/admin.py index 7df1c250..381fb206 100644 --- a/allianceauth/menu/admin.py +++ b/allianceauth/menu/admin.py @@ -1,6 +1,5 @@ """Admin site for menu app.""" -from typing import Optional from django.contrib import admin from django.http import HttpRequest, HttpResponse diff --git a/allianceauth/menu/core/menu_item_hooks.py b/allianceauth/menu/core/menu_item_hooks.py index 2114569e..c0d26e5b 100644 --- a/allianceauth/menu/core/menu_item_hooks.py +++ b/allianceauth/menu/core/menu_item_hooks.py @@ -1,7 +1,7 @@ """Logic for handling MenuItemHook objects.""" import hashlib -from typing import List, NamedTuple, Optional +from typing import NamedTuple from allianceauth.menu.hooks import MenuItemHook diff --git a/allianceauth/menu/hooks.py b/allianceauth/menu/hooks.py index 9341415c..8a1fe5d9 100644 --- a/allianceauth/menu/hooks.py +++ b/allianceauth/menu/hooks.py @@ -1,6 +1,5 @@ """Menu item hooks.""" -from typing import List, Optional from django.template.loader import render_to_string diff --git a/allianceauth/menu/migrations/0001_initial.py b/allianceauth/menu/migrations/0001_initial.py index 1594566b..bf25eebb 100644 --- a/allianceauth/menu/migrations/0001_initial.py +++ b/allianceauth/menu/migrations/0001_initial.py @@ -1,7 +1,7 @@ # Generated by Django 4.2.9 on 2024-02-15 00:01 -from django.db import migrations, models import django.db.models.deletion +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/allianceauth/menu/models.py b/allianceauth/menu/models.py index b2984842..40c91aab 100644 --- a/allianceauth/menu/models.py +++ b/allianceauth/menu/models.py @@ -48,8 +48,13 @@ class MenuItem(models.Model): # app related properties hook_hash = models.CharField( - max_length=64, default=None, null=True, unique=True, editable=False - ) # hash of a menu item hook. Must be nullable for unique comparison. + max_length=64, + default=None, + null=True, + unique=True, + editable=False, + help_text="hash of a menu item hook. Must be nullable for unique comparison." + ) # user defined properties classes = models.CharField( diff --git a/allianceauth/menu/templatetags/menu_menu_items.py b/allianceauth/menu/templatetags/menu_menu_items.py index 2049e56d..6f93b9fb 100644 --- a/allianceauth/menu/templatetags/menu_menu_items.py +++ b/allianceauth/menu/templatetags/menu_menu_items.py @@ -24,7 +24,6 @@ which is used to render the complete menu. """ from dataclasses import dataclass, field -from typing import Dict, List, Optional from django import template from django.db.models import QuerySet diff --git a/allianceauth/menu/tests/templatetags/test_menu_menu_items.py b/allianceauth/menu/tests/templatetags/test_menu_menu_items.py index ff48a49a..beae2da4 100644 --- a/allianceauth/menu/tests/templatetags/test_menu_menu_items.py +++ b/allianceauth/menu/tests/templatetags/test_menu_menu_items.py @@ -1,4 +1,4 @@ -from typing import List, NamedTuple, Optional +from typing import NamedTuple from unittest.mock import patch from bs4 import BeautifulSoup diff --git a/allianceauth/notifications/admin.py b/allianceauth/notifications/admin.py index 3fb3242a..b2afd02b 100644 --- a/allianceauth/notifications/admin.py +++ b/allianceauth/notifications/admin.py @@ -1,4 +1,5 @@ from django.contrib import admin + from .models import Notification diff --git a/allianceauth/notifications/handlers.py b/allianceauth/notifications/handlers.py index b42aa09f..34d15da5 100644 --- a/allianceauth/notifications/handlers.py +++ b/allianceauth/notifications/handlers.py @@ -5,8 +5,9 @@ logger = logging.getLogger(__name__) class NotificationHandler(logging.Handler): def emit(self, record): - from django.contrib.auth.models import User, Permission + from django.contrib.auth.models import Permission, User from django.db.models import Q + from . import notify from .models import Notification diff --git a/allianceauth/notifications/managers.py b/allianceauth/notifications/managers.py index 3798428e..42bbc01e 100644 --- a/allianceauth/notifications/managers.py +++ b/allianceauth/notifications/managers.py @@ -1,9 +1,9 @@ import logging from django.conf import settings +from django.contrib.auth.models import User from django.core.cache import cache from django.db import models -from django.contrib.auth.models import User logger = logging.getLogger(__name__) diff --git a/allianceauth/notifications/migrations/0001_initial.py b/allianceauth/notifications/migrations/0001_initial.py index 867ca680..21cdcf0e 100644 --- a/allianceauth/notifications/migrations/0001_initial.py +++ b/allianceauth/notifications/migrations/0001_initial.py @@ -1,8 +1,8 @@ # Generated by Django 1.10.1 on 2016-09-05 21:40 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/notifications/models.py b/allianceauth/notifications/models.py index dd77d0ff..6d75ff43 100644 --- a/allianceauth/notifications/models.py +++ b/allianceauth/notifications/models.py @@ -1,7 +1,7 @@ import logging -from django.db import models from django.contrib.auth.models import User +from django.db import models from django.utils.translation import gettext_lazy as _ from .managers import NotificationManager @@ -73,7 +73,7 @@ class Notification(models.Model): def mark_viewed(self) -> None: """Mark notification as viewed.""" - logger.info("Marking notification as viewed: %s" % self) + logger.info(f"Marking notification as viewed: {self}") self.viewed = True self.save() diff --git a/allianceauth/notifications/templatetags/auth_notifications.py b/allianceauth/notifications/templatetags/auth_notifications.py index 6ebce070..dcdf35ea 100644 --- a/allianceauth/notifications/templatetags/auth_notifications.py +++ b/allianceauth/notifications/templatetags/auth_notifications.py @@ -12,7 +12,6 @@ from django.contrib.auth.models import User from allianceauth.notifications.models import Notification - logger = logging.getLogger(__name__) register = template.Library() diff --git a/allianceauth/notifications/tests/test_handlers.py b/allianceauth/notifications/tests/test_handlers.py index f90a4726..aa3c0bc3 100644 --- a/allianceauth/notifications/tests/test_handlers.py +++ b/allianceauth/notifications/tests/test_handlers.py @@ -1,7 +1,8 @@ -from logging import LogRecord, DEBUG +from logging import DEBUG, LogRecord -from django.contrib.auth.models import Permission, Group, User +from django.contrib.auth.models import Group, Permission, User from django.test import TestCase + from allianceauth.tests.auth_utils import AuthUtils from ..handlers import NotificationHandler diff --git a/allianceauth/notifications/tests/test_init.py b/allianceauth/notifications/tests/test_init.py index e09e1ee7..3cab1ed7 100644 --- a/allianceauth/notifications/tests/test_init.py +++ b/allianceauth/notifications/tests/test_init.py @@ -1,4 +1,5 @@ from django.test import TestCase + from allianceauth.tests.auth_utils import AuthUtils from .. import notify diff --git a/allianceauth/notifications/tests/test_managers.py b/allianceauth/notifications/tests/test_managers.py index a74ca2b9..e21c6aa2 100644 --- a/allianceauth/notifications/tests/test_managers.py +++ b/allianceauth/notifications/tests/test_managers.py @@ -5,8 +5,8 @@ from django.contrib.auth.models import User from django.test import TestCase, override_settings from allianceauth.tests.auth_utils import AuthUtils -from ..models import Notification +from ..models import Notification MODULE_PATH = 'allianceauth.notifications.models' diff --git a/allianceauth/notifications/tests/test_models.py b/allianceauth/notifications/tests/test_models.py index b291f2c8..320a3c45 100644 --- a/allianceauth/notifications/tests/test_models.py +++ b/allianceauth/notifications/tests/test_models.py @@ -1,11 +1,11 @@ from unittest.mock import patch from django.test import TestCase + from allianceauth.tests.auth_utils import AuthUtils from ..models import Notification - MODULE_PATH = 'allianceauth.notifications.models' diff --git a/allianceauth/notifications/tests/test_templatetags.py b/allianceauth/notifications/tests/test_templatetags.py index 587970be..f31a9a45 100644 --- a/allianceauth/notifications/tests/test_templatetags.py +++ b/allianceauth/notifications/tests/test_templatetags.py @@ -1,11 +1,10 @@ -from unittest.mock import patch, Mock +from unittest.mock import patch from django.test import TestCase, override_settings from allianceauth.tests.auth_utils import AuthUtils -from ..templatetags.auth_notifications import ( - user_unread_notification_count, notifications_refresh_time -) + +from ..templatetags.auth_notifications import notifications_refresh_time, user_unread_notification_count MODULE_PATH = 'allianceauth.notifications.templatetags.auth_notifications' diff --git a/allianceauth/notifications/tests/test_views.py b/allianceauth/notifications/tests/test_views.py index 7fa95bc8..ca6212f4 100644 --- a/allianceauth/notifications/tests/test_views.py +++ b/allianceauth/notifications/tests/test_views.py @@ -1,15 +1,13 @@ import json +from unittest.mock import patch -from unittest.mock import patch, Mock - -from django.test import TestCase, RequestFactory +from django.test import RequestFactory, TestCase from django.urls import reverse from allianceauth.tests.auth_utils import AuthUtils from ..views import user_notifications_count - MODULE_PATH = 'allianceauth.notifications.views' diff --git a/allianceauth/notifications/urls.py b/allianceauth/notifications/urls.py index 694a700b..be8f7073 100644 --- a/allianceauth/notifications/urls.py +++ b/allianceauth/notifications/urls.py @@ -1,4 +1,5 @@ from django.urls import path + from . import views app_name = 'notifications' diff --git a/allianceauth/notifications/views.py b/allianceauth/notifications/views.py index 40bc88f5..3d3a586f 100644 --- a/allianceauth/notifications/views.py +++ b/allianceauth/notifications/views.py @@ -1,9 +1,9 @@ import logging -from django.contrib.auth.decorators import login_required from django.contrib import messages +from django.contrib.auth.decorators import login_required from django.http import JsonResponse -from django.shortcuts import render, get_object_or_404, redirect +from django.shortcuts import get_object_or_404, redirect, render from django.utils.translation import gettext_lazy as _ from .models import Notification @@ -13,7 +13,7 @@ logger = logging.getLogger(__name__) @login_required def notification_list(request): - logger.debug("notification_list called by user %s" % request.user) + logger.debug(f"notification_list called by user {request.user}") notifications_qs = Notification.objects.filter(user=request.user).order_by("-timestamp") new_notifs = notifications_qs.filter(viewed=False) old_notifs = notifications_qs.filter(viewed=True) diff --git a/allianceauth/optimer/auth_hooks.py b/allianceauth/optimer/auth_hooks.py index b14a41b5..e0fefb16 100644 --- a/allianceauth/optimer/auth_hooks.py +++ b/allianceauth/optimer/auth_hooks.py @@ -1,8 +1,10 @@ +from django.utils.translation import gettext_lazy as _ + +from allianceauth import hooks from allianceauth.menu.hooks import MenuItemHook from allianceauth.optimer.views import dashboard_ops from allianceauth.services.hooks import UrlHook -from django.utils.translation import gettext_lazy as _ -from allianceauth import hooks + from . import urls diff --git a/allianceauth/optimer/form_widgets.py b/allianceauth/optimer/form_widgets.py index e639e18b..b52dad0e 100644 --- a/allianceauth/optimer/form_widgets.py +++ b/allianceauth/optimer/form_widgets.py @@ -18,7 +18,7 @@ class DataListWidget(forms.TextInput): self._name = name self._list = data_list - self.attrs.update({"list": "list__%s" % self._name}) + self.attrs.update({"list": f"list__{self._name}"}) def render(self, name, value, attrs=None, renderer=None): """ @@ -36,10 +36,10 @@ class DataListWidget(forms.TextInput): """ text_html = super().render(name, value, attrs=attrs) - data_list = '' % self._name + data_list = f'' for item in self._list: - data_list += '" diff --git a/allianceauth/optimer/migrations/0001_initial.py b/allianceauth/optimer/migrations/0001_initial.py index 7e57fa8a..29aeeeb6 100644 --- a/allianceauth/optimer/migrations/0001_initial.py +++ b/allianceauth/optimer/migrations/0001_initial.py @@ -1,9 +1,10 @@ # Generated by Django 1.10.1 on 2016-09-05 21:40 import datetime -from django.db import migrations, models + import django.db.models.deletion import django.utils.timezone +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/allianceauth/optimer/migrations/0004_on_delete.py b/allianceauth/optimer/migrations/0004_on_delete.py index f07883c3..26565539 100644 --- a/allianceauth/optimer/migrations/0004_on_delete.py +++ b/allianceauth/optimer/migrations/0004_on_delete.py @@ -1,7 +1,7 @@ # Generated by Django 1.11.5 on 2017-09-28 02:16 -from django.db import migrations, models import django.db.models.deletion +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/allianceauth/optimer/migrations/0005_add_type_and_description.py b/allianceauth/optimer/migrations/0005_add_type_and_description.py index c8fee43d..533417e1 100644 --- a/allianceauth/optimer/migrations/0005_add_type_and_description.py +++ b/allianceauth/optimer/migrations/0005_add_type_and_description.py @@ -1,7 +1,7 @@ # Generated by Django 3.2.8 on 2021-10-26 16:20 -from django.db import migrations, models import django.db.models.deletion +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/allianceauth/optimer/models.py b/allianceauth/optimer/models.py index 02139a93..daa7a80e 100644 --- a/allianceauth/optimer/models.py +++ b/allianceauth/optimer/models.py @@ -13,18 +13,17 @@ class OpTimerType(models.Model): type = models.CharField(max_length=254, default="") - def __str__(self): - return self.type + class Meta: ordering = ['type'] default_permissions = () + def __str__(self): + return self.type class OpTimer(models.Model): - class Meta: - ordering = ['start'] - default_permissions = () + doctrine = models.CharField(max_length=254, default="") system = models.CharField(max_length=254, default="") @@ -37,6 +36,8 @@ class OpTimer(models.Model): on_delete=models.SET_NULL) description = models.TextField(blank=True, default="") type = models.ForeignKey(OpTimerType, null=True, on_delete=models.SET_NULL) - + class Meta: + ordering = ['start'] + default_permissions = () def __str__(self): return self.operation_name diff --git a/allianceauth/optimer/views.py b/allianceauth/optimer/views.py index 760879e6..1b815e7b 100644 --- a/allianceauth/optimer/views.py +++ b/allianceauth/optimer/views.py @@ -1,10 +1,8 @@ import logging from django.contrib import messages -from django.contrib.auth.decorators import login_required -from django.contrib.auth.decorators import permission_required -from django.shortcuts import get_object_or_404 -from django.shortcuts import render, redirect +from django.contrib.auth.decorators import login_required, permission_required +from django.shortcuts import get_object_or_404, redirect, render from django.template.loader import render_to_string from django.utils import timezone from django.utils.translation import gettext_lazy as _ @@ -29,7 +27,7 @@ def optimer_view(request): :rtype: """ - logger.debug("optimer_view called by user %s" % request.user) + logger.debug(f"optimer_view called by user {request.user}") base_query = OpTimer.objects.select_related('eve_character', 'type') render_items = {'optimer': base_query.all(), 'future_timers': base_query.filter( @@ -52,11 +50,11 @@ def add_optimer_view(request): :rtype: """ - logger.debug("add_optimer_view called by user %s" % request.user) + logger.debug(f"add_optimer_view called by user {request.user}") if request.method == 'POST': form = OpForm(request.POST, data_list=OpTimerType.objects.all()) - logger.debug("Request type POST contains form valid: %s" % form.is_valid()) + logger.debug(f"Request type POST contains form valid: {form.is_valid()}") if form.is_valid(): optimer_type = None @@ -141,7 +139,7 @@ def edit_optimer(request, optimer_id): if request.method == 'POST': form = OpForm(request.POST, data_list=OpTimerType.objects.all()) - logger.debug("Received POST request containing update optimer form, is valid: %s" % form.is_valid()) + logger.debug(f"Received POST request containing update optimer form, is valid: {form.is_valid()}") if form.is_valid(): character = request.user.profile.main_character diff --git a/allianceauth/permissions_tool/auth_hooks.py b/allianceauth/permissions_tool/auth_hooks.py index f89444d5..4171f14c 100644 --- a/allianceauth/permissions_tool/auth_hooks.py +++ b/allianceauth/permissions_tool/auth_hooks.py @@ -1,9 +1,9 @@ -from allianceauth.menu.hooks import MenuItemHook -from . import urls - from allianceauth import hooks +from allianceauth.menu.hooks import MenuItemHook from allianceauth.services.hooks import UrlHook +from . import urls + class PermissionsTool(MenuItemHook): def __init__(self): diff --git a/allianceauth/permissions_tool/models.py b/allianceauth/permissions_tool/models.py index 3a93f94b..bce74dc9 100644 --- a/allianceauth/permissions_tool/models.py +++ b/allianceauth/permissions_tool/models.py @@ -10,3 +10,6 @@ class PermissionsTool(models.Model): permissions = ( ('audit_permissions', 'Can audit permissions'), ) + + def __str__(self) -> str: + return f"{self.pk}" diff --git a/allianceauth/permissions_tool/tests.py b/allianceauth/permissions_tool/tests.py index 9354a0e3..0fe8e4b5 100644 --- a/allianceauth/permissions_tool/tests.py +++ b/allianceauth/permissions_tool/tests.py @@ -1,9 +1,11 @@ from django_webtest import WebTest + from django import urls from django.contrib.auth.models import Group, Permission from allianceauth.tests.auth_utils import AuthUtils + class PermissionsToolViewsTestCase(WebTest): def setUp(self): self.member = AuthUtils.create_member('auth_member') diff --git a/allianceauth/permissions_tool/urls.py b/allianceauth/permissions_tool/urls.py index 7a66c19a..0cced253 100644 --- a/allianceauth/permissions_tool/urls.py +++ b/allianceauth/permissions_tool/urls.py @@ -1,5 +1,4 @@ -from django.urls import re_path -from django.urls import path +from django.urls import path, re_path from . import views diff --git a/allianceauth/permissions_tool/views.py b/allianceauth/permissions_tool/views.py index e845a466..de4cc281 100644 --- a/allianceauth/permissions_tool/views.py +++ b/allianceauth/permissions_tool/views.py @@ -1,10 +1,9 @@ import logging from django.contrib.auth.decorators import login_required, permission_required -from django.contrib.auth.models import Permission, User +from django.contrib.auth.models import Permission from django.db.models import Count -from django.shortcuts import render, Http404 - +from django.shortcuts import Http404, render logger = logging.getLogger(__name__) @@ -12,7 +11,7 @@ logger = logging.getLogger(__name__) @login_required @permission_required('permissions_tool.audit_permissions') def permissions_overview(request): - logger.debug("permissions_overview called by user %s" % request.user) + logger.debug(f"permissions_overview called by user {request.user}") perms = Permission.objects.select_related('content_type').all()\ .annotate(Count('user', distinct=True))\ .annotate(Count('group', distinct=True)) \ diff --git a/allianceauth/project_template/manage.py b/allianceauth/project_template/manage.py index 843d8a7d..acf38748 100644 --- a/allianceauth/project_template/manage.py +++ b/allianceauth/project_template/manage.py @@ -6,17 +6,17 @@ if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name}}.settings.local") try: from django.core.management import execute_from_command_line - except ImportError: + except ImportError as err: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: - import django + import django # noqa: F401 except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" - ) + ) from err raise execute_from_command_line(sys.argv) diff --git a/allianceauth/project_template/project_name/__init__.py b/allianceauth/project_template/project_name/__init__.py index cf2e85f6..dfa885c1 100644 --- a/allianceauth/project_template/project_name/__init__.py +++ b/allianceauth/project_template/project_name/__init__.py @@ -1 +1 @@ -from .celery import app as celery_app +from .celery import app as celery_app # noqa:F401 diff --git a/allianceauth/project_template/project_name/celery.py b/allianceauth/project_template/project_name/celery.py index 35ec18dd..bfa29c89 100644 --- a/allianceauth/project_template/project_name/celery.py +++ b/allianceauth/project_template/project_name/celery.py @@ -1,11 +1,12 @@ import os + from celery import Celery from celery.app import trace # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', '{{ project_name }}.settings.local') -from django.conf import settings # noqa +from django.conf import settings app = Celery('{{ project_name }}') diff --git a/allianceauth/project_template/project_name/settings/base.py b/allianceauth/project_template/project_name/settings/base.py index fb18e4de..bed938ae 100644 --- a/allianceauth/project_template/project_name/settings/base.py +++ b/allianceauth/project_template/project_name/settings/base.py @@ -11,7 +11,6 @@ import os from celery.schedules import crontab from django.contrib import messages - from django.utils.translation import gettext_lazy as _ INSTALLED_APPS = [ diff --git a/allianceauth/project_template/project_name/urls.py b/allianceauth/project_template/project_name/urls.py index 58d40642..a098e831 100644 --- a/allianceauth/project_template/project_name/urls.py +++ b/allianceauth/project_template/project_name/urls.py @@ -1,6 +1,7 @@ -from allianceauth import urls from django.urls import include, path +from allianceauth import urls + urlpatterns = [ path('', include(urls)), ] diff --git a/allianceauth/services/abstract.py b/allianceauth/services/abstract.py index d6e500e0..034d1dfc 100644 --- a/allianceauth/services/abstract.py +++ b/allianceauth/services/abstract.py @@ -7,22 +7,22 @@ to use these views. You are free to build the internal structure of the service as you like. """ +import logging from collections import OrderedDict -from django.views import View -from django.urls import reverse_lazy -from django.views.generic import UpdateView, DeleteView -from django.views.generic.detail import SingleObjectMixin + from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin -from django.db import models, IntegrityError from django.core.exceptions import ObjectDoesNotExist -from django.shortcuts import render, Http404, redirect +from django.db import IntegrityError, models +from django.shortcuts import Http404, redirect, render +from django.urls import reverse_lazy from django.utils.translation import gettext_lazy as _ +from django.views import View +from django.views.generic import DeleteView, UpdateView +from django.views.generic.detail import SingleObjectMixin from .forms import ServicePasswordModelForm -import logging - logger = logging.getLogger(__name__) @@ -33,6 +33,10 @@ class AbstractServiceModel(models.Model): related_name='%(app_label)s' ) + + class Meta: + abstract = True + def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.credentials = OrderedDict() @@ -44,10 +48,6 @@ class AbstractServiceModel(models.Model): def reset_password(self): pass - class Meta: - abstract = True - - class BaseServiceView(LoginRequiredMixin, PermissionRequiredMixin, View): """ Define: diff --git a/allianceauth/services/apps.py b/allianceauth/services/apps.py index 5160ce48..4412f394 100644 --- a/allianceauth/services/apps.py +++ b/allianceauth/services/apps.py @@ -6,4 +6,4 @@ class ServicesConfig(AppConfig): label = 'services' def ready(self): - from . import signals + pass diff --git a/allianceauth/services/auth_hooks.py b/allianceauth/services/auth_hooks.py index cda56f58..030860b5 100644 --- a/allianceauth/services/auth_hooks.py +++ b/allianceauth/services/auth_hooks.py @@ -1,6 +1,7 @@ -from allianceauth import hooks from django.utils.translation import gettext_lazy as _ +from allianceauth import hooks + from ..menu.hooks import MenuItemHook from .hooks import ServicesHook diff --git a/allianceauth/services/hooks.py b/allianceauth/services/hooks.py index 458f9266..108932f9 100644 --- a/allianceauth/services/hooks.py +++ b/allianceauth/services/hooks.py @@ -1,20 +1,13 @@ -from string import Formatter -from django.urls import include, re_path -from typing import Optional from collections.abc import Iterable +from string import Formatter from django.conf import settings from django.core.exceptions import ObjectDoesNotExist -from django.template.loader import render_to_string from django.urls import include, re_path from django.utils.functional import cached_property from allianceauth.hooks import get_hooks from allianceauth.menu.hooks import MenuItemHook -from django.conf import settings -from django.urls import include, re_path -from django.core.exceptions import ObjectDoesNotExist -from django.utils.functional import cached_property from .models import NameFormatConfig diff --git a/allianceauth/services/modules/discord/admin.py b/allianceauth/services/modules/discord/admin.py index 4db920bf..acc0c57d 100644 --- a/allianceauth/services/modules/discord/admin.py +++ b/allianceauth/services/modules/discord/admin.py @@ -4,9 +4,9 @@ from django.contrib import admin from ...admin import ServicesUserAdmin from . import __title__ +from .auth_hooks import DiscordService from .models import DiscordUser from .utils import LoggerAddTag -from .auth_hooks import DiscordService logger = LoggerAddTag(logging.getLogger(__name__), __title__) diff --git a/allianceauth/services/modules/discord/api.py b/allianceauth/services/modules/discord/api.py index 5805d730..c5cf6d55 100644 --- a/allianceauth/services/modules/discord/api.py +++ b/allianceauth/services/modules/discord/api.py @@ -18,12 +18,11 @@ Here is an example for using the api to fetch the current roles from the configu The docs for the client class can be found here: :py:class:`~allianceauth.services.modules.discord.discord_client.client.DiscordClient` """ -from typing import Optional from .app_settings import DISCORD_GUILD_ID -from .core import create_bot_client, group_to_role, server_name # noqa -from .discord_client.models import Role # noqa -from .models import DiscordUser # noqa +from .core import create_bot_client, group_to_role, server_name +from .discord_client.models import Role +from .models import DiscordUser __all__ = ["create_bot_client", "group_to_role", "server_name", "DiscordUser", "Role"] diff --git a/allianceauth/services/modules/discord/app_settings.py b/allianceauth/services/modules/discord/app_settings.py index 52f85f80..60a9072c 100644 --- a/allianceauth/services/modules/discord/app_settings.py +++ b/allianceauth/services/modules/discord/app_settings.py @@ -1,6 +1,5 @@ from .utils import clean_setting - DISCORD_APP_ID = clean_setting('DISCORD_APP_ID', '') """App ID for the AA bot on Discord. Needs to be set.""" diff --git a/allianceauth/services/modules/discord/auth_hooks.py b/allianceauth/services/modules/discord/auth_hooks.py index 37385a37..7ce3da2d 100644 --- a/allianceauth/services/modules/discord/auth_hooks.py +++ b/allianceauth/services/modules/discord/auth_hooks.py @@ -6,15 +6,12 @@ from django.template.loader import render_to_string from allianceauth import hooks from allianceauth.services.hooks import ServicesHook +from . import __title__, tasks +from .app_settings import DISCORD_SYNC_NAMES from .core import server_name, user_formatted_nick from .models import DiscordUser from .urls import urlpatterns from .utils import LoggerAddTag -from . import tasks, __title__ -from .app_settings import ( - DISCORD_SYNC_NAMES -) - logger = LoggerAddTag(logging.getLogger(__name__), __title__) diff --git a/allianceauth/services/modules/discord/core.py b/allianceauth/services/modules/discord/core.py index 7b1f76e7..406b6291 100644 --- a/allianceauth/services/modules/discord/core.py +++ b/allianceauth/services/modules/discord/core.py @@ -1,7 +1,6 @@ """Core functionality of the Discord service not directly related to models.""" import logging -from typing import List, Optional, Tuple from requests.exceptions import HTTPError @@ -12,7 +11,7 @@ from allianceauth.services.hooks import NameFormatter from . import __title__ from .app_settings import DISCORD_BOT_TOKEN, DISCORD_GUILD_ID -from .discord_client import DiscordClient, RolesSet, Role +from .discord_client import DiscordClient, Role, RolesSet from .discord_client.exceptions import DiscordClientException from .utils import LoggerAddTag diff --git a/allianceauth/services/modules/discord/discord_client/app_settings.py b/allianceauth/services/modules/discord/discord_client/app_settings.py index c6ff7711..99dc078d 100644 --- a/allianceauth/services/modules/discord/discord_client/app_settings.py +++ b/allianceauth/services/modules/discord/discord_client/app_settings.py @@ -9,7 +9,6 @@ To overwrite a default set the variable in your local Django settings, e.g: from ..utils import clean_setting - DISCORD_API_BASE_URL = clean_setting( 'DISCORD_API_BASE_URL', 'https://discord.com/api/' ) diff --git a/allianceauth/services/modules/discord/discord_client/client.py b/allianceauth/services/modules/discord/discord_client/client.py index 73710270..490a7f4d 100644 --- a/allianceauth/services/modules/discord/discord_client/client.py +++ b/allianceauth/services/modules/discord/discord_client/client.py @@ -2,24 +2,21 @@ import json import logging +from collections.abc import Iterable from enum import IntEnum from hashlib import md5 from http import HTTPStatus from time import sleep -from typing import List, Optional, Set, Tuple -from collections.abc import Iterable from urllib.parse import urljoin from uuid import uuid1 import requests -from requests.exceptions import HTTPError from redis import Redis +from requests.exceptions import HTTPError +from allianceauth import __title__ as AUTH_TITLE, __url__, __version__ from allianceauth.utils.cache import get_redis_client -from allianceauth import __title__ as AUTH_TITLE -from allianceauth import __url__, __version__ - from .. import __title__ from ..utils import LoggerAddTag from .app_settings import ( @@ -347,7 +344,7 @@ class DiscordClient: Returns: List of tuple of Role and created flag """ - roles = list() + roles = [] guild_roles = RolesSet(self.guild_roles(guild_id)) role_names_cleaned = {Role.sanitize_name(name) for name in role_names} for role_name in role_names_cleaned: @@ -483,7 +480,7 @@ class DiscordClient: if role_ids and not isinstance(role_ids, list): raise TypeError('role_ids must be a list type') - data = dict() + data = {} if role_ids: data['roles'] = self._sanitize_role_ids(role_ids) @@ -639,7 +636,7 @@ class DiscordClient: uid = uuid1().hex if not hasattr(requests, method): - raise ValueError('Invalid method: %s' % method) + raise ValueError(f'Invalid method: {method}') if not authorization: authorization = f'Bot {self.access_token}' diff --git a/allianceauth/services/modules/discord/discord_client/helpers.py b/allianceauth/services/modules/discord/discord_client/helpers.py index 2932e3c5..2bcca64d 100644 --- a/allianceauth/services/modules/discord/discord_client/helpers.py +++ b/allianceauth/services/modules/discord/discord_client/helpers.py @@ -1,6 +1,5 @@ -from copy import copy -from typing import List, Optional, Set, Tuple from collections.abc import Iterable +from copy import copy from .models import Role @@ -17,19 +16,19 @@ class RolesSet: roles_lst: List of dicts, each defining a role """ def __init__(self, roles_lst: Iterable[Role]) -> None: - if not isinstance(roles_lst, (list, set, tuple)): + if not isinstance(roles_lst, list | set | tuple): raise TypeError('roles_lst must be of type list, set or tuple') - self._roles = dict() - self._roles_by_name = dict() + self._roles = {} + self._roles_by_name = {} for role in list(roles_lst): if not isinstance(role, Role): - raise TypeError('Roles must be of type Role: %s' % role) + raise TypeError(f'Roles must be of type Role: {role}') self._roles[role.id] = role self._roles_by_name[role.name] = role def __repr__(self) -> str: if self._roles_by_name: - roles = '"' + '", "'.join(sorted(list(self._roles_by_name.keys()))) + '"' + roles = '"' + '", "'.join(sorted(self._roles_by_name.keys())) + '"' else: roles = "" return f'{self.__class__.__name__}([{roles}])' diff --git a/allianceauth/services/modules/discord/discord_client/models.py b/allianceauth/services/modules/discord/discord_client/models.py index 2f8f230a..f38d3ac6 100644 --- a/allianceauth/services/modules/discord/discord_client/models.py +++ b/allianceauth/services/modules/discord/discord_client/models.py @@ -7,7 +7,6 @@ Discord's snowflake type (used by Discord IDs) is implemented as int. """ from dataclasses import asdict, dataclass -from typing import FrozenSet @dataclass(frozen=True) diff --git a/allianceauth/services/modules/discord/discord_client/tests/factories.py b/allianceauth/services/modules/discord/discord_client/tests/factories.py index a11548bf..4f63bb92 100644 --- a/allianceauth/services/modules/discord/discord_client/tests/factories.py +++ b/allianceauth/services/modules/discord/discord_client/tests/factories.py @@ -103,7 +103,7 @@ def next_number(key: str = None) -> int: try: return next_number._counter[key].__next__() except AttributeError: - next_number._counter = dict() + next_number._counter = {} except KeyError: pass next_number._counter[key] = count(start=1) diff --git a/allianceauth/services/modules/discord/discord_client/tests/piloting_concurrency.py b/allianceauth/services/modules/discord/discord_client/tests/piloting_concurrency.py index b3202d66..8d9b73da 100644 --- a/allianceauth/services/modules/discord/discord_client/tests/piloting_concurrency.py +++ b/allianceauth/services/modules/discord/discord_client/tests/piloting_concurrency.py @@ -14,14 +14,14 @@ alliance Discord server for this. """ import os -from random import random import threading +from random import random from time import sleep + from django.test import TestCase -from .. import DiscordClient, DiscordApiBackoff - from ...utils import set_logger_to_file +from .. import DiscordApiBackoff, DiscordClient logger = set_logger_to_file( 'allianceauth.services.modules.discord.discord_client.client', __file__ diff --git a/allianceauth/services/modules/discord/discord_client/tests/piloting_functionality.py b/allianceauth/services/modules/discord/discord_client/tests/piloting_functionality.py index ad729b8b..dd74cee2 100644 --- a/allianceauth/services/modules/discord/discord_client/tests/piloting_functionality.py +++ b/allianceauth/services/modules/discord/discord_client/tests/piloting_functionality.py @@ -14,13 +14,13 @@ Since this may cause lots of 429s we'd recommend NOT to use your alliance Discord server for this. """ -from uuid import uuid1 import os -from unittest import TestCase from time import sleep +from unittest import TestCase +from uuid import uuid1 -from .. import DiscordClient from ...utils import set_logger_to_file +from .. import DiscordClient logger = set_logger_to_file( 'allianceauth.services.modules.discord.discord_self.client.client', __file__ diff --git a/allianceauth/services/modules/discord/discord_client/tests/test_client.py b/allianceauth/services/modules/discord/discord_client/tests/test_client.py index 5c7a5bf4..044cb97a 100644 --- a/allianceauth/services/modules/discord/discord_client/tests/test_client.py +++ b/allianceauth/services/modules/discord/discord_client/tests/test_client.py @@ -7,8 +7,7 @@ import requests_mock from redis import Redis from requests.exceptions import HTTPError -from allianceauth import __title__ as AUTH_TITLE -from allianceauth import __url__, __version__ +from allianceauth import __title__ as AUTH_TITLE, __url__, __version__ from allianceauth.utils.testing import NoSocketsTestCase from ...utils import set_logger_to_file @@ -85,7 +84,7 @@ class TestBasicsAndHelpers(NoSocketsTestCase): def test_should_raise_error_when_trying_to_create_object_without_token(self): # when/then - with self.assertRaises(Exception): + with self.assertRaises(ValueError): DiscordClient("", mock_redis) def test_repr(self): diff --git a/allianceauth/services/modules/discord/discord_client/tests/test_exceptions.py b/allianceauth/services/modules/discord/discord_client/tests/test_exceptions.py index 25f412f3..eb3323d2 100644 --- a/allianceauth/services/modules/discord/discord_client/tests/test_exceptions.py +++ b/allianceauth/services/modules/discord/discord_client/tests/test_exceptions.py @@ -4,7 +4,7 @@ from ..exceptions import ( DiscordApiBackoff, DiscordClientException, DiscordRateLimitExhausted, - DiscordTooManyRequestsError + DiscordTooManyRequestsError, ) diff --git a/allianceauth/services/modules/discord/managers.py b/allianceauth/services/modules/discord/managers.py index 2dbdbb9f..2b7e6ea6 100644 --- a/allianceauth/services/modules/discord/managers.py +++ b/allianceauth/services/modules/discord/managers.py @@ -16,10 +16,13 @@ from .app_settings import ( DISCORD_GUILD_ID, DISCORD_SYNC_NAMES, ) -from .core import calculate_roles_for_user, create_bot_client -from .core import group_to_role as core_group_to_role -from .core import server_name as core_server_name -from .core import user_formatted_nick +from .core import ( + calculate_roles_for_user, + create_bot_client, + group_to_role as core_group_to_role, + server_name as core_server_name, + user_formatted_nick, +) from .discord_client import ( DISCORD_OAUTH_BASE_URL, DISCORD_OAUTH_TOKEN_URL, @@ -175,7 +178,7 @@ class DiscordUserManager(models.Manager): - empty dict if no matching role found """ role = core_group_to_role(group) - return role.asdict() if role else dict() + return role.asdict() if role else {} @staticmethod def server_name(use_cache: bool = True) -> str: diff --git a/allianceauth/services/modules/discord/migrations/0001_initial.py b/allianceauth/services/modules/discord/migrations/0001_initial.py index 932bb5fc..5241dbdd 100644 --- a/allianceauth/services/modules/discord/migrations/0001_initial.py +++ b/allianceauth/services/modules/discord/migrations/0001_initial.py @@ -1,8 +1,8 @@ # Generated by Django 1.10.2 on 2016-12-12 03:14 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/services/modules/discord/migrations/0002_service_permissions.py b/allianceauth/services/modules/discord/migrations/0002_service_permissions.py index f10a1cf6..9592cbd4 100644 --- a/allianceauth/services/modules/discord/migrations/0002_service_permissions.py +++ b/allianceauth/services/modules/discord/migrations/0002_service_permissions.py @@ -1,12 +1,12 @@ # Generated by Django 1.10.5 on 2017-02-02 05:59 -from django.db import migrations -from django.conf import settings -from django.core.exceptions import ObjectDoesNotExist -from django.contrib.auth.management import create_permissions - import logging +from django.conf import settings +from django.contrib.auth.management import create_permissions +from django.core.exceptions import ObjectDoesNotExist +from django.db import migrations + logger = logging.getLogger(__name__) diff --git a/allianceauth/services/modules/discord/migrations/0003_big_overhaul.py b/allianceauth/services/modules/discord/migrations/0003_big_overhaul.py index b809fd6b..f63ab2db 100644 --- a/allianceauth/services/modules/discord/migrations/0003_big_overhaul.py +++ b/allianceauth/services/modules/discord/migrations/0003_big_overhaul.py @@ -1,8 +1,8 @@ # Generated by Django 2.2.12 on 2020-05-10 19:59 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/services/modules/discord/models.py b/allianceauth/services/modules/discord/models.py index 4d74b247..a3b0966c 100644 --- a/allianceauth/services/modules/discord/models.py +++ b/allianceauth/services/modules/discord/models.py @@ -1,5 +1,4 @@ import logging -from typing import Optional from requests.exceptions import HTTPError @@ -11,17 +10,11 @@ from allianceauth.notifications import notify from . import __title__ from .app_settings import DISCORD_GUILD_ID -from .core import ( - create_bot_client, - default_bot_client, - calculate_roles_for_user, - user_formatted_nick -) +from .core import calculate_roles_for_user, create_bot_client, default_bot_client, user_formatted_nick from .discord_client import DiscordApiBackoff from .managers import DiscordUserManager from .utils import LoggerAddTag - logger = LoggerAddTag(logging.getLogger(__name__), __title__) diff --git a/allianceauth/services/modules/discord/tasks.py b/allianceauth/services/modules/discord/tasks.py index 1dcc087e..15e6319a 100644 --- a/allianceauth/services/modules/discord/tasks.py +++ b/allianceauth/services/modules/discord/tasks.py @@ -1,7 +1,7 @@ import logging from typing import Any -from celery import shared_task, chain +from celery import chain, shared_task from requests.exceptions import HTTPError from django.contrib.auth.models import User @@ -10,14 +10,11 @@ from django.db.models.query import QuerySet from allianceauth.services.tasks import QueueOnce from . import __title__ -from .app_settings import ( - DISCORD_TASKS_MAX_RETRIES, DISCORD_TASKS_RETRY_PAUSE, DISCORD_SYNC_NAMES -) +from .app_settings import DISCORD_SYNC_NAMES, DISCORD_TASKS_MAX_RETRIES, DISCORD_TASKS_RETRY_PAUSE from .discord_client import DiscordApiBackoff from .models import DiscordUser from .utils import LoggerAddTag - logger = LoggerAddTag(logging.getLogger(__name__), __title__) # task priority of bulk tasks @@ -152,7 +149,7 @@ def _bulk_update_groups_for_users(discord_users_qs: QuerySet) -> None: logger.info( "Starting to bulk update discord roles for %d users", discord_users_qs.count() ) - update_groups_chain = list() + update_groups_chain = [] for discord_user in discord_users_qs: update_groups_chain.append(update_groups.si(discord_user.user.pk)) @@ -180,7 +177,7 @@ def _bulk_update_nicknames_for_users(discord_users_qs: QuerySet) -> None: "Starting to bulk update discord nicknames for %d users", discord_users_qs.count() ) - update_nicknames_chain = list() + update_nicknames_chain = [] for discord_user in discord_users_qs: update_nicknames_chain.append(update_nickname.si(discord_user.user.pk)) @@ -257,7 +254,7 @@ def _bulk_update_usernames_for_users(discord_users_qs: QuerySet) -> None: "Starting to bulk update discord usernames for %d users", discord_users_qs.count() ) - update_usernames_chain = list() + update_usernames_chain = [] for discord_user in discord_users_qs: update_usernames_chain.append(update_username.si(discord_user.user.pk)) @@ -271,7 +268,7 @@ def update_all() -> None: logger.info( 'Starting to bulk update all for %s Discord users', discord_users_qs.count() ) - update_all_chain = list() + update_all_chain = [] for discord_user in discord_users_qs: update_all_chain.append(update_groups.si(discord_user.user.pk)) update_all_chain.append(update_username.si(discord_user.user.pk)) diff --git a/allianceauth/services/modules/discord/tests/test_admin.py b/allianceauth/services/modules/discord/tests/test_admin.py index 03de74bd..7b236ac4 100644 --- a/allianceauth/services/modules/discord/tests/test_admin.py +++ b/allianceauth/services/modules/discord/tests/test_admin.py @@ -188,17 +188,15 @@ class TestColumnRendering(TestDataMixin, NoSocketsTestCase): def test_user_username_u1(self): expected = ( - '' - 'Bruce_Wayne
Bruce Wayne'.format( - self.user_1.discord.pk - ) + f'' + 'Bruce_Wayne
Bruce Wayne' ) self.assertEqual(user_username(self.user_1.discord), expected) def test_user_username_u3(self): expected = ( - '' - 'Lex_Luthor'.format(self.user_3.discord.pk) + f'' + 'Lex_Luthor' ) self.assertEqual(user_username(self.user_3.discord), expected) diff --git a/allianceauth/services/modules/discord/tests/test_integration.py b/allianceauth/services/modules/discord/tests/test_integration.py index 7fd9a954..fa869245 100644 --- a/allianceauth/services/modules/discord/tests/test_integration.py +++ b/allianceauth/services/modules/discord/tests/test_integration.py @@ -11,12 +11,12 @@ from unittest.mock import Mock, patch from uuid import uuid1 import requests_mock +from django_webtest import WebTest from requests.exceptions import HTTPError from django.contrib.auth.models import Group, User from django.test import TransactionTestCase, override_settings from django.urls import reverse -from django_webtest import WebTest from allianceauth.authentication.models import State from allianceauth.eveonline.models import EveCharacter @@ -224,7 +224,7 @@ class TestServiceFeatures(TransactionTestCase): requests_made = [ DiscordRequest(r.method, r.url) for r in requests_mocker.request_history ] - self.assertListEqual(requests_made, list()) + self.assertListEqual(requests_made, []) def test_when_member_is_demoted_to_guest_then_his_account_is_deleted( self, requests_mocker @@ -428,12 +428,12 @@ class StateTestCase(NoSocketsTestCase): self._refresh_user() self.assertEqual(higher_state, self.user.profile.state) with self.assertRaises(DiscordUser.DoesNotExist): - self.user.discord + _ = self.user.discord higher_state.member_characters.clear() self._refresh_user() self.assertEqual(self.member_state, self.user.profile.state) with self.assertRaises(DiscordUser.DoesNotExist): - self.user.discord + _ = self.user.discord def test_perm_changes_to_lower_priority_state_creation(self, requests_mocker): mock_url = DiscordRequest( @@ -455,12 +455,12 @@ class StateTestCase(NoSocketsTestCase): self._refresh_user() self.assertEqual(lower_state, self.user.profile.state) with self.assertRaises(DiscordUser.DoesNotExist): - self.user.discord + _ = self.user.discord self.member_state.member_characters.add(self.test_character) self._refresh_user() self.assertEqual(self.member_state, self.user.profile.state) with self.assertRaises(DiscordUser.DoesNotExist): - self.user.discord + _ = self.user.discord @patch(MODULE_PATH + '.core.DISCORD_GUILD_ID', TEST_GUILD_ID) @@ -534,7 +534,7 @@ class TestUserFeatures(WebTest): self.assertTrue(mock_messages.success.called) self.assertFalse(mock_messages.error.called) - requests_made = list() + requests_made = [] for r in requests_mocker.request_history: obj = DiscordRequest(r.method, r.url) requests_made.append(obj) @@ -662,7 +662,7 @@ class TestUserFeatures(WebTest): self.assertFalse(mock_messages.success.called) self.assertTrue(mock_messages.error.called) - requests_made = list() + requests_made = [] for r in requests_mocker.request_history: obj = DiscordRequest(r.method, r.url) requests_made.append(obj) @@ -694,7 +694,7 @@ class TestUserFeatures(WebTest): self.assertTrue(mock_messages.success.called) self.assertFalse(mock_messages.error.called) - requests_made = list() + requests_made = [] for r in requests_mocker.request_history: obj = DiscordRequest(r.method, r.url) requests_made.append(obj) @@ -730,7 +730,7 @@ class TestUserFeatures(WebTest): self.assertFalse(mock_messages.success.called) self.assertTrue(mock_messages.error.called) - requests_made = list() + requests_made = [] for r in requests_mocker.request_history: obj = DiscordRequest(r.method, r.url) requests_made.append(obj) diff --git a/allianceauth/services/modules/discord/tests/test_managers.py b/allianceauth/services/modules/discord/tests/test_managers.py index 8b65fd26..b081c3e9 100644 --- a/allianceauth/services/modules/discord/tests/test_managers.py +++ b/allianceauth/services/modules/discord/tests/test_managers.py @@ -3,8 +3,6 @@ from unittest.mock import Mock, patch from requests.exceptions import HTTPError -from django.contrib.auth.models import User - from allianceauth.tests.auth_utils import AuthUtils from allianceauth.utils.testing import NoSocketsTestCase diff --git a/allianceauth/services/modules/discord/tests/test_models.py b/allianceauth/services/modules/discord/tests/test_models.py index c7e73218..3e919356 100644 --- a/allianceauth/services/modules/discord/tests/test_models.py +++ b/allianceauth/services/modules/discord/tests/test_models.py @@ -11,8 +11,8 @@ from ..discord_client.tests.factories import ( TEST_USER_NAME, create_guild_member, create_role, + create_user as create_guild_user, ) -from ..discord_client.tests.factories import create_user as create_guild_user from ..models import DiscordUser from ..utils import set_logger_to_file from . import MODULE_PATH, TEST_MAIN_ID, TEST_MAIN_NAME diff --git a/allianceauth/services/modules/discord/utils.py b/allianceauth/services/modules/discord/utils.py index 26ffbe00..79a5525a 100644 --- a/allianceauth/services/modules/discord/utils.py +++ b/allianceauth/services/modules/discord/utils.py @@ -3,7 +3,6 @@ import os from django.conf import settings - logger = logging.getLogger(__name__) @@ -41,7 +40,7 @@ def clean_setting( if not required_type: required_type = type(default_value) - if min_value is None and required_type == int: + if min_value is None and required_type is int: min_value = 0 if not hasattr(settings, name): diff --git a/allianceauth/services/modules/discord/views.py b/allianceauth/services/modules/discord/views.py index 8cc5fcdd..8a4272fd 100644 --- a/allianceauth/services/modules/discord/views.py +++ b/allianceauth/services/modules/discord/views.py @@ -1,9 +1,7 @@ import logging from django.contrib import messages -from django.contrib.auth.decorators import login_required -from django.contrib.auth.decorators import permission_required -from django.contrib.auth.decorators import user_passes_test +from django.contrib.auth.decorators import login_required, permission_required, user_passes_test from django.shortcuts import redirect from django.utils.translation import gettext_lazy as _ @@ -13,7 +11,6 @@ from . import __title__ from .models import DiscordUser from .utils import LoggerAddTag - logger = LoggerAddTag(logging.getLogger(__name__), __title__) ACCESS_PERM = 'discord.access_discord' diff --git a/allianceauth/services/modules/discourse/admin.py b/allianceauth/services/modules/discourse/admin.py index b4efc18b..b29bdbbe 100644 --- a/allianceauth/services/modules/discourse/admin.py +++ b/allianceauth/services/modules/discourse/admin.py @@ -1,7 +1,7 @@ from django.contrib import admin -from .models import DiscourseUser from ...admin import ServicesUserAdmin +from .models import DiscourseUser @admin.register(DiscourseUser) diff --git a/allianceauth/services/modules/discourse/auth_hooks.py b/allianceauth/services/modules/discourse/auth_hooks.py index 744dbe4c..66b2553e 100644 --- a/allianceauth/services/modules/discourse/auth_hooks.py +++ b/allianceauth/services/modules/discourse/auth_hooks.py @@ -1,10 +1,11 @@ import logging -from django.template.loader import render_to_string from django.conf import settings +from django.template.loader import render_to_string from allianceauth import hooks from allianceauth.services.hooks import ServicesHook + from .tasks import DiscourseTasks from .urls import urlpatterns @@ -35,7 +36,7 @@ class DiscourseService(ServicesHook): self.delete_user(user, notify_user=True) def update_all_groups(self): - logger.debug('Update all %s groups called' % self.name) + logger.debug(f'Update all {self.name} groups called') DiscourseTasks.update_all_groups.delay() def service_active_for_user(self, user): diff --git a/allianceauth/services/modules/discourse/manager.py b/allianceauth/services/modules/discourse/manager.py index 03cbbdee..95f9084d 100644 --- a/allianceauth/services/modules/discourse/manager.py +++ b/allianceauth/services/modules/discourse/manager.py @@ -1,10 +1,12 @@ import logging -import requests import re +from hashlib import md5 + from django.conf import settings from django.core.cache import cache -from hashlib import md5 + from . import providers + logger = logging.getLogger(__name__) GROUP_CACHE_MAX_AGE = getattr(settings, 'DISCOURSE_GROUP_CACHE_MAX_AGE', 2 * 60 * 60) # default 2 hours @@ -39,11 +41,11 @@ class DiscourseManager: @staticmethod def _generate_cache_group_name_key(name): - return 'DISCOURSE_GROUP_NAME__%s' % md5(name.encode('utf-8')).hexdigest() + return 'DISCOURSE_GROUP_NAME__{}'.format(md5(name.encode('utf-8')).hexdigest()) @staticmethod def _generate_cache_group_id_key(g_id): - return 'DISCOURSE_GROUP_ID__%s' % g_id + return f'DISCOURSE_GROUP_ID__{g_id}' @staticmethod def __group_name_to_id(name): @@ -66,7 +68,7 @@ class DiscourseManager: for g in groups: if g['id'] == g_id: return g['name'] - raise KeyError("Group ID %s not found on Discourse" % g_id) + raise KeyError(f"Group ID {g_id} not found on Discourse") return cache.get_or_set(DiscourseManager._generate_cache_group_id_key(g_id), get_group_name, GROUP_CACHE_MAX_AGE) @@ -183,7 +185,7 @@ class DiscourseManager: username = discord_user['username'] uid = discord_user['id'] user_groups = DiscourseManager.__get_user_groups(username) - add_groups = [group_dict[x] for x in group_dict if not group_dict[x] in user_groups] + add_groups = [group_dict[x] for x in group_dict if group_dict[x] not in user_groups] rem_groups = [x for x in user_groups if x not in inv_group_dict] if add_groups: logger.info( @@ -198,8 +200,8 @@ class DiscourseManager: @staticmethod def disable_user(user): - logger.debug("Disabling user %s Discourse access." % user) + logger.debug(f"Disabling user {user} Discourse access.") d_user = DiscourseManager.__get_user_by_external(user.pk) DiscourseManager.__logout(d_user['user']['id']) - logger.info("Disabled user %s Discourse access." % user) + logger.info(f"Disabled user {user} Discourse access.") return True diff --git a/allianceauth/services/modules/discourse/migrations/0001_initial.py b/allianceauth/services/modules/discourse/migrations/0001_initial.py index f9e0139c..74cd7be3 100644 --- a/allianceauth/services/modules/discourse/migrations/0001_initial.py +++ b/allianceauth/services/modules/discourse/migrations/0001_initial.py @@ -1,8 +1,8 @@ # Generated by Django 1.10.2 on 2016-12-12 03:15 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/services/modules/discourse/migrations/0002_service_permissions.py b/allianceauth/services/modules/discourse/migrations/0002_service_permissions.py index bde79988..2e3e3fee 100644 --- a/allianceauth/services/modules/discourse/migrations/0002_service_permissions.py +++ b/allianceauth/services/modules/discourse/migrations/0002_service_permissions.py @@ -1,12 +1,12 @@ # Generated by Django 1.10.5 on 2017-02-02 05:59 -from django.db import migrations -from django.conf import settings -from django.core.exceptions import ObjectDoesNotExist -from django.contrib.auth.management import create_permissions - import logging +from django.conf import settings +from django.contrib.auth.management import create_permissions +from django.core.exceptions import ObjectDoesNotExist +from django.db import migrations + logger = logging.getLogger(__name__) diff --git a/allianceauth/services/modules/discourse/models.py b/allianceauth/services/modules/discourse/models.py index 22014cf9..8f121c81 100644 --- a/allianceauth/services/modules/discourse/models.py +++ b/allianceauth/services/modules/discourse/models.py @@ -9,10 +9,12 @@ class DiscourseUser(models.Model): related_name='discourse') enabled = models.BooleanField() - def __str__(self): - return self.user.username + class Meta: permissions = ( ("access_discourse", "Can access the Discourse service"), ) + + def __str__(self): + return self.user.username diff --git a/allianceauth/services/modules/discourse/providers.py b/allianceauth/services/modules/discourse/providers.py index 276d82da..39f45c99 100644 --- a/allianceauth/services/modules/discourse/providers.py +++ b/allianceauth/services/modules/discourse/providers.py @@ -1,7 +1,9 @@ from pydiscourse import DiscourseClient + from django.conf import settings -class DiscourseAPIClient(): + +class DiscourseAPIClient: _client = None def __init__(self): diff --git a/allianceauth/services/modules/discourse/tasks.py b/allianceauth/services/modules/discourse/tasks.py index d115211a..48487e1f 100644 --- a/allianceauth/services/modules/discourse/tasks.py +++ b/allianceauth/services/modules/discourse/tasks.py @@ -1,12 +1,14 @@ import logging +from celery import shared_task + from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist -from celery import shared_task from allianceauth.notifications import notify from allianceauth.services.hooks import NameFormatter from allianceauth.services.tasks import QueueOnce + from .manager import DiscourseManager from .models import DiscourseUser @@ -20,7 +22,7 @@ class DiscourseTasks: @classmethod def delete_user(cls, user, notify_user=False): if cls.has_account(user) and user.discourse.enabled: - logger.debug("User %s has a Discourse account. Disabling login." % user) + logger.debug(f"User {user} has a Discourse account. Disabling login.") if DiscourseManager.disable_user(user): user.discourse.delete() if notify_user: @@ -44,14 +46,14 @@ class DiscourseTasks: @shared_task(bind=True, name='discourse.update_groups', base=QueueOnce) def update_groups(self, pk): user = User.objects.get(pk=pk) - logger.debug("Updating discourse groups for user %s" % user) + logger.debug(f"Updating discourse groups for user {user}") try: DiscourseManager.update_groups(user) except Exception as e: logger.exception(e) - logger.warning("Discourse group sync failed for %s, retrying in 10 mins" % user) + logger.warning(f"Discourse group sync failed for {user}, retrying in 10 mins") raise self.retry(countdown=60 * 10) - logger.debug("Updated user %s discourse groups." % user) + logger.debug(f"Updated user {user} discourse groups.") @staticmethod @shared_task(name='discourse.update_all_groups') diff --git a/allianceauth/services/modules/discourse/tests.py b/allianceauth/services/modules/discourse/tests.py index 38eda84f..19d7c361 100644 --- a/allianceauth/services/modules/discourse/tests.py +++ b/allianceauth/services/modules/discourse/tests.py @@ -1,9 +1,9 @@ from unittest import mock -from django.test import TestCase, RequestFactory -from django.contrib.auth.models import User, Group, Permission -from django.core.exceptions import ObjectDoesNotExist from django.conf import settings +from django.contrib.auth.models import Group, Permission, User +from django.core.exceptions import ObjectDoesNotExist +from django.test import RequestFactory, TestCase from allianceauth.tests.auth_utils import AuthUtils @@ -27,7 +27,7 @@ class DiscourseHooksTestCase(TestCase): member = AuthUtils.create_member(self.member) DiscourseUser.objects.create(user=member, enabled=True) self.none_user = 'none_user' - none_user = AuthUtils.create_user(self.none_user) + AuthUtils.create_user(self.none_user) self.service = DiscourseService add_permissions() @@ -85,7 +85,7 @@ class DiscourseHooksTestCase(TestCase): service.validate_user(none_user) self.assertTrue(manager.disable_user.called) with self.assertRaises(ObjectDoesNotExist): - none_discourse = User.objects.get(username=self.none_user).discourse + _ = User.objects.get(username=self.none_user).discourse @mock.patch(MODULE_PATH + '.tasks.DiscourseManager') def test_delete_user(self, manager): @@ -97,7 +97,7 @@ class DiscourseHooksTestCase(TestCase): self.assertTrue(result) self.assertTrue(manager.disable_user.called) with self.assertRaises(ObjectDoesNotExist): - discourse_user = User.objects.get(username=self.member).discourse + _ = User.objects.get(username=self.member).discourse def test_render_services_ctrl(self): service = self.service() @@ -107,7 +107,7 @@ class DiscourseHooksTestCase(TestCase): response = service.render_services_ctrl(request) self.assertTemplateUsed(service.service_ctrl_template) - self.assertIn('href="%s"' % settings.DISCOURSE_URL, response) + self.assertIn(f'href="{settings.DISCOURSE_URL}"', response) class DiscourseViewsTestCase(TestCase): diff --git a/allianceauth/services/modules/discourse/views.py b/allianceauth/services/modules/discourse/views.py index a777fbb7..3e42b2f4 100644 --- a/allianceauth/services/modules/discourse/views.py +++ b/allianceauth/services/modules/discourse/views.py @@ -1,20 +1,18 @@ +import base64 +import hashlib +import hmac +import logging +from urllib.parse import parse_qs, unquote, urlencode + from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators import login_required -from django.shortcuts import render, redirect +from django.shortcuts import redirect from django.utils.translation import gettext_lazy as _ from .manager import DiscourseManager -from .tasks import DiscourseTasks from .models import DiscourseUser - -import base64 -import hmac -import hashlib - -from urllib.parse import unquote, urlencode, parse_qs - -import logging +from .tasks import DiscourseTasks logger = logging.getLogger(__name__) @@ -27,12 +25,12 @@ def discourse_sso(request): # Check if user has access if not request.user.has_perm(ACCESS_PERM): messages.error(request, _('You are not authorized to access Discourse.')) - logger.warning('User %s attempted to access Discourse but does not have permission.' % request.user) + logger.warning(f'User {request.user} attempted to access Discourse but does not have permission.') return redirect('authentication:dashboard') if not request.user.profile.main_character: messages.error(request, _("You must have a main character set to access Discourse.")) - logger.warning('User %s attempted to access Discourse but does not have a main character.' % request.user) + logger.warning(f'User {request.user} attempted to access Discourse but does not have a main character.') return redirect('authentication:characters') main_char = request.user.profile.main_character @@ -92,5 +90,5 @@ def discourse_sso(request): DiscourseTasks.update_groups.apply_async(args=[request.user.pk], countdown=30) # Redirect back to Discourse - url = '%s/session/sso_login' % settings.DISCOURSE_URL + url = f'{settings.DISCOURSE_URL}/session/sso_login' return redirect(f'{url}?{query_string}') diff --git a/allianceauth/services/modules/example/auth_hooks.py b/allianceauth/services/modules/example/auth_hooks.py index 5469b3af..bc2c7b0f 100644 --- a/allianceauth/services/modules/example/auth_hooks.py +++ b/allianceauth/services/modules/example/auth_hooks.py @@ -2,6 +2,7 @@ from django.template.loader import render_to_string from allianceauth import hooks from allianceauth.services.hooks import ServicesHook + from .urls import urlpatterns diff --git a/allianceauth/services/modules/ips4/admin.py b/allianceauth/services/modules/ips4/admin.py index 38ad5f50..3e45cea3 100644 --- a/allianceauth/services/modules/ips4/admin.py +++ b/allianceauth/services/modules/ips4/admin.py @@ -1,4 +1,5 @@ from django.contrib import admin + from .models import Ips4User diff --git a/allianceauth/services/modules/ips4/auth_hooks.py b/allianceauth/services/modules/ips4/auth_hooks.py index 83a9855b..d475ab10 100644 --- a/allianceauth/services/modules/ips4/auth_hooks.py +++ b/allianceauth/services/modules/ips4/auth_hooks.py @@ -3,6 +3,7 @@ from django.template.loader import render_to_string from allianceauth import hooks from allianceauth.services.hooks import ServicesHook + from .tasks import Ips4Tasks from .urls import urlpatterns diff --git a/allianceauth/services/modules/ips4/manager.py b/allianceauth/services/modules/ips4/manager.py index 40b1cad9..cc14bf38 100644 --- a/allianceauth/services/modules/ips4/manager.py +++ b/allianceauth/services/modules/ips4/manager.py @@ -1,10 +1,12 @@ import logging import random -import string import re -from django.db import connections +import string + from passlib.hash import bcrypt + from django.conf import settings +from django.db import connections logger = logging.getLogger(__name__) @@ -13,17 +15,17 @@ TABLE_PREFIX = getattr(settings, 'IPS4_TABLE_PREFIX', '') class Ips4Manager: - SQL_ADD_USER = r"INSERT INTO %score_members (name, email, members_pass_hash, members_pass_salt, " \ - r"member_group_id) VALUES (%%s, %%s, %%s, %%s, %%s)" % TABLE_PREFIX - SQL_GET_ID = r"SELECT member_id FROM %score_members WHERE name = %%s" % TABLE_PREFIX - SQL_UPDATE_PASSWORD = r"UPDATE %score_members SET members_pass_hash = %%s, members_pass_salt = %%s WHERE name = %%s" % TABLE_PREFIX - SQL_DEL_USER = r"DELETE FROM %score_members WHERE member_id = %%s" % TABLE_PREFIX + SQL_ADD_USER = rf"INSERT INTO {TABLE_PREFIX}core_members (name, email, members_pass_hash, members_pass_salt, " \ + r"member_group_id) VALUES (%s, %s, %s, %s, %s)" + SQL_GET_ID = rf"SELECT member_id FROM {TABLE_PREFIX}core_members WHERE name = %s" + SQL_UPDATE_PASSWORD = rf"UPDATE {TABLE_PREFIX}core_members SET members_pass_hash = %s, members_pass_salt = %s WHERE name = %s" + SQL_DEL_USER = rf"DELETE FROM {TABLE_PREFIX}core_members WHERE member_id = %s" MEMBER_GROUP_ID = 3 @classmethod def add_user(cls, username, email): - logger.debug("Adding new IPS4 user %s" % username) + logger.debug(f"Adding new IPS4 user {username}") plain_password = cls.__generate_random_pass() hash = cls._gen_pwhash(plain_password) salt = cls._get_salt(hash) @@ -42,7 +44,7 @@ class Ips4Manager: logger.debug(f"Got user id {row[0]} for username {username}") return row[0] else: - logger.error("username %s not found. Unable to determine id." % username) + logger.error(f"username {username} not found. Unable to determine id.") return None @staticmethod @@ -61,19 +63,19 @@ class Ips4Manager: @staticmethod def delete_user(id): - logger.debug("Deleting IPS4 user id %s" % id) + logger.debug(f"Deleting IPS4 user id {id}") try: cursor = connections['ips4'].cursor() cursor.execute(Ips4Manager.SQL_DEL_USER, [id]) - logger.info("Deleted IPS4 user %s" % id) + logger.info(f"Deleted IPS4 user {id}") return True - except: - logger.exception("Failed to delete IPS4 user id %s" % id) + except Exception: + logger.exception(f"Failed to delete IPS4 user id {id}") return False @classmethod def update_user_password(cls, username): - logger.debug("Updating IPS4 user id %s password" % id) + logger.debug(f"Updating IPS4 user id {id} password") if cls.check_user(username): plain_password = Ips4Manager.__generate_random_pass() hash = cls._gen_pwhash(plain_password) @@ -82,24 +84,24 @@ class Ips4Manager: cursor.execute(cls.SQL_UPDATE_PASSWORD, [hash, salt, username]) return plain_password else: - logger.error("Unable to update ips4 user %s password" % username) + logger.error(f"Unable to update ips4 user {username} password") return "" @staticmethod def check_user(username): - logger.debug("Checking IPS4 username %s" % username) + logger.debug(f"Checking IPS4 username {username}") cursor = connections['ips4'].cursor() cursor.execute(Ips4Manager.SQL_GET_ID, [username]) row = cursor.fetchone() if row: - logger.debug("Found user %s on IPS4" % username) + logger.debug(f"Found user {username} on IPS4") return True - logger.debug("User %s not found on IPS4" % username) + logger.debug(f"User {username} not found on IPS4") return False @classmethod def update_custom_password(cls, username, plain_password): - logger.debug("Updating IPS4 user id %s password" % id) + logger.debug(f"Updating IPS4 user id {id} password") if cls.check_user(username): hash = cls._gen_pwhash(plain_password) salt = cls._get_salt(hash) @@ -107,5 +109,5 @@ class Ips4Manager: cursor.execute(cls.SQL_UPDATE_PASSWORD, [hash, salt, username]) return plain_password else: - logger.error("Unable to update ips4 user %s password" % username) + logger.error(f"Unable to update ips4 user {username} password") return "" diff --git a/allianceauth/services/modules/ips4/migrations/0001_initial.py b/allianceauth/services/modules/ips4/migrations/0001_initial.py index 83f3159f..adb8b3a5 100644 --- a/allianceauth/services/modules/ips4/migrations/0001_initial.py +++ b/allianceauth/services/modules/ips4/migrations/0001_initial.py @@ -1,8 +1,8 @@ # Generated by Django 1.10.2 on 2016-12-12 03:27 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/services/modules/ips4/migrations/0002_service_permissions.py b/allianceauth/services/modules/ips4/migrations/0002_service_permissions.py index 17c0fc09..b184f88b 100644 --- a/allianceauth/services/modules/ips4/migrations/0002_service_permissions.py +++ b/allianceauth/services/modules/ips4/migrations/0002_service_permissions.py @@ -1,12 +1,12 @@ # Generated by Django 1.10.5 on 2017-02-02 05:59 -from django.db import migrations -from django.conf import settings -from django.core.exceptions import ObjectDoesNotExist -from django.contrib.auth.management import create_permissions - import logging +from django.conf import settings +from django.contrib.auth.management import create_permissions +from django.core.exceptions import ObjectDoesNotExist +from django.db import migrations + logger = logging.getLogger(__name__) diff --git a/allianceauth/services/modules/ips4/models.py b/allianceauth/services/modules/ips4/models.py index 56d83263..545a107c 100644 --- a/allianceauth/services/modules/ips4/models.py +++ b/allianceauth/services/modules/ips4/models.py @@ -10,10 +10,11 @@ class Ips4User(models.Model): username = models.CharField(max_length=254) id = models.CharField(max_length=254) - def __str__(self): - return self.username class Meta: permissions = ( ("access_ips4", "Can access the IPS4 service"), ) + + def __str__(self): + return self.username diff --git a/allianceauth/services/modules/ips4/tasks.py b/allianceauth/services/modules/ips4/tasks.py index b6c5dce8..3cb4d1d7 100644 --- a/allianceauth/services/modules/ips4/tasks.py +++ b/allianceauth/services/modules/ips4/tasks.py @@ -1,12 +1,12 @@ -from django.conf import settings +import logging + from django.core.exceptions import ObjectDoesNotExist from allianceauth.services.hooks import NameFormatter + from .manager import Ips4Manager from .models import Ips4User -import logging - logger = logging.getLogger(__name__) @@ -16,10 +16,10 @@ class Ips4Tasks: @classmethod def delete_user(cls, user): - logging.debug("Attempting to delete IPS4 account for %s" % user) + logging.debug(f"Attempting to delete IPS4 account for {user}") if cls.has_account(user) and Ips4Manager.delete_user(user.ips4.id): user.ips4.delete() - logger.info("Successfully deactivated IPS4 for user %s" % user) + logger.info(f"Successfully deactivated IPS4 for user {user}") return True return False diff --git a/allianceauth/services/modules/ips4/tests.py b/allianceauth/services/modules/ips4/tests.py index 48e7ffa4..09f2484e 100644 --- a/allianceauth/services/modules/ips4/tests.py +++ b/allianceauth/services/modules/ips4/tests.py @@ -1,9 +1,9 @@ from unittest import mock -from django.test import TestCase, RequestFactory from django import urls -from django.contrib.auth.models import User, Group, Permission +from django.contrib.auth.models import Group, Permission, User from django.core.exceptions import ObjectDoesNotExist +from django.test import RequestFactory, TestCase from allianceauth.tests.auth_utils import AuthUtils @@ -27,7 +27,7 @@ class Ips4HooksTestCase(TestCase): member = AuthUtils.create_member(self.member) Ips4User.objects.create(user=member, id='12345', username=self.member) self.none_user = 'none_user' - none_user = AuthUtils.create_user(self.none_user) + AuthUtils.create_user(self.none_user) self.service = Ips4Service add_permissions() @@ -107,7 +107,8 @@ class Ips4ViewsTestCase(TestCase): self.assertTrue(manager.delete_user.called) self.assertRedirects(response, expected_url=urls.reverse('services:services'), target_status_code=200) with self.assertRaises(ObjectDoesNotExist): - ips4_user = User.objects.get(pk=self.member.pk).ips4 + user = User.objects.get(pk=self.member.pk) + _ = user.ips4 @mock.patch(MODULE_PATH + '.views.Ips4Manager') def test_set_password(self, manager): diff --git a/allianceauth/services/modules/ips4/views.py b/allianceauth/services/modules/ips4/views.py index 9e806430..ea1b6284 100644 --- a/allianceauth/services/modules/ips4/views.py +++ b/allianceauth/services/modules/ips4/views.py @@ -2,10 +2,11 @@ import logging from django.contrib import messages from django.contrib.auth.decorators import login_required, permission_required -from django.shortcuts import render, redirect +from django.shortcuts import redirect, render from django.utils.translation import gettext_lazy as _ from allianceauth.services.forms import ServicePasswordForm + from .manager import Ips4Manager from .models import Ips4User from .tasks import Ips4Tasks @@ -18,16 +19,16 @@ ACCESS_PERM = 'ips4.access_ips4' @login_required @permission_required(ACCESS_PERM) def activate_ips4(request): - logger.debug("activate_ips4 called by user %s" % request.user) + logger.debug(f"activate_ips4 called by user {request.user}") character = request.user.profile.main_character logger.debug(f"Adding IPS4 user for user {request.user} with main character {character}") result = Ips4Manager.add_user(Ips4Tasks.get_username(request.user), request.user.email) # if empty we failed if result[0] != "" and not Ips4Tasks.has_account(request.user): - ips_user = Ips4User.objects.create(user=request.user, id=result[2], username=result[0]) - logger.debug("Updated authserviceinfo for user %s with IPSuite4 credentials." % request.user) + Ips4User.objects.create(user=request.user, id=result[2], username=result[0]) + logger.debug(f"Updated authserviceinfo for user {request.user} with IPSuite4 credentials.") # update_ips4_groups.delay(request.user.pk) - logger.info("Successfully activated IPSuite4 for user %s" % request.user) + logger.info(f"Successfully activated IPSuite4 for user {request.user}") messages.success(request, _('Activated IPSuite4 account.')) credentials = { 'username': result[0], @@ -35,7 +36,7 @@ def activate_ips4(request): } return render(request, 'services/service_credentials.html', context={'credentials': credentials, 'service': 'IPSuite4'}) else: - logger.error("Unsuccessful attempt to activate IPSuite4 for user %s" % request.user) + logger.error(f"Unsuccessful attempt to activate IPSuite4 for user {request.user}") messages.error(request, _('An error occurred while processing your IPSuite4 account.')) return redirect("services:services") @@ -43,12 +44,12 @@ def activate_ips4(request): @login_required @permission_required(ACCESS_PERM) def reset_ips4_password(request): - logger.debug("reset_ips4_password called by user %s" % request.user) + logger.debug(f"reset_ips4_password called by user {request.user}") if Ips4Tasks.has_account(request.user): result = Ips4Manager.update_user_password(request.user.ips4.username) # false we failed if result != "": - logger.info("Successfully reset IPSuite4 password for user %s" % request.user) + logger.info(f"Successfully reset IPSuite4 password for user {request.user}") messages.success(request, _('Reset IPSuite4 password.')) credentials = { 'username': request.user.ips4.username, @@ -56,7 +57,7 @@ def reset_ips4_password(request): } return render(request, 'services/service_credentials.html', context={'credentials': credentials, 'service': 'IPSuite4'}) - logger.error("Unsuccessful attempt to reset IPSuite4 password for user %s" % request.user) + logger.error(f"Unsuccessful attempt to reset IPSuite4 password for user {request.user}") messages.error(request, _('An error occurred while processing your IPSuite4 account.')) return redirect("services:services") @@ -64,27 +65,27 @@ def reset_ips4_password(request): @login_required @permission_required(ACCESS_PERM) def set_ips4_password(request): - logger.debug("set_ips4_password called by user %s" % request.user) + logger.debug(f"set_ips4_password called by user {request.user}") if request.method == 'POST': logger.debug("Received POST request with form.") form = ServicePasswordForm(request.POST) - logger.debug("Form is valid: %s" % form.is_valid()) + logger.debug(f"Form is valid: {form.is_valid()}") if form.is_valid() and Ips4Tasks.has_account(request.user): password = form.cleaned_data['password'] - logger.debug("Form contains password of length %s" % len(password)) + logger.debug(f"Form contains password of length {len(password)}") result = Ips4Manager.update_custom_password(request.user.ips4.username, plain_password=password) if result != "": - logger.info("Successfully set IPSuite4 password for user %s" % request.user) + logger.info(f"Successfully set IPSuite4 password for user {request.user}") messages.success(request, _('Set IPSuite4 password.')) else: - logger.error("Failed to install custom IPSuite4 password for user %s" % request.user) + logger.error(f"Failed to install custom IPSuite4 password for user {request.user}") messages.error(request, _('An error occurred while processing your IPSuite4 account.')) return redirect('services:services') else: logger.debug("Request is not type POST - providing empty form.") form = ServicePasswordForm() - logger.debug("Rendering form for user %s" % request.user) + logger.debug(f"Rendering form for user {request.user}") context = {'form': form, 'service': 'IPS4'} return render(request, 'services/service_password.html', context=context) @@ -92,11 +93,11 @@ def set_ips4_password(request): @login_required @permission_required(ACCESS_PERM) def deactivate_ips4(request): - logger.debug("deactivate_ips4 called by user %s" % request.user) + logger.debug(f"deactivate_ips4 called by user {request.user}") if Ips4Tasks.delete_user(request.user): - logger.info("Successfully deactivated IPSuite4 for user %s" % request.user) + logger.info(f"Successfully deactivated IPSuite4 for user {request.user}") messages.success(request, _('Deactivated IPSuite4 account.')) else: - logger.error("Unsuccessful attempt to deactivate IPSuite4 for user %s" % request.user) + logger.error(f"Unsuccessful attempt to deactivate IPSuite4 for user {request.user}") messages.error(request, _('An error occurred while processing your IPSuite4 account.')) return redirect("services:services") diff --git a/allianceauth/services/modules/mumble/admin.py b/allianceauth/services/modules/mumble/admin.py index ecc8328d..33034d30 100644 --- a/allianceauth/services/modules/mumble/admin.py +++ b/allianceauth/services/modules/mumble/admin.py @@ -1,7 +1,7 @@ from django.contrib import admin -from .models import MumbleUser from ...admin import ServicesUserAdmin +from .models import MumbleUser @admin.register(MumbleUser) diff --git a/allianceauth/services/modules/mumble/auth_hooks.py b/allianceauth/services/modules/mumble/auth_hooks.py index efc8df33..3bf3d25e 100644 --- a/allianceauth/services/modules/mumble/auth_hooks.py +++ b/allianceauth/services/modules/mumble/auth_hooks.py @@ -3,12 +3,13 @@ import urllib from django.conf import settings from django.template.loader import render_to_string -from allianceauth.notifications import notify from allianceauth import hooks +from allianceauth.notifications import notify from allianceauth.services.hooks import ServicesHook -from .tasks import MumbleTasks + from .models import MumbleUser +from .tasks import MumbleTasks from .urls import urlpatterns logger = logging.getLogger(__name__) @@ -50,7 +51,7 @@ class MumbleService(ServicesHook): self.delete_user(user, notify_user=True) def update_all_groups(self): - logger.debug("Updating all %s groups" % self.name) + logger.debug(f"Updating all {self.name} groups") MumbleTasks.update_all_groups.delay() def service_active_for_user(self, user): diff --git a/allianceauth/services/modules/mumble/migrations/0001_squashed_0011_auto_20201011_1009.py b/allianceauth/services/modules/mumble/migrations/0001_squashed_0011_auto_20201011_1009.py index 4ef869f9..6b6d96f6 100644 --- a/allianceauth/services/modules/mumble/migrations/0001_squashed_0011_auto_20201011_1009.py +++ b/allianceauth/services/modules/mumble/migrations/0001_squashed_0011_auto_20201011_1009.py @@ -1,9 +1,10 @@ # Generated by Django 3.1.2 on 2021-01-08 13:54 -from django.conf import settings -from django.db import migrations, models import django.db.migrations.operations.special import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + class Migration(migrations.Migration): diff --git a/allianceauth/services/modules/mumble/migrations/0003_mumbleuser_user.py b/allianceauth/services/modules/mumble/migrations/0003_mumbleuser_user.py index 9745e67e..f5f98351 100644 --- a/allianceauth/services/modules/mumble/migrations/0003_mumbleuser_user.py +++ b/allianceauth/services/modules/mumble/migrations/0003_mumbleuser_user.py @@ -1,8 +1,8 @@ # Generated by Django 1.10.2 on 2016-12-12 03:31 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/services/modules/mumble/migrations/0004_auto_20161214_1024.py b/allianceauth/services/modules/mumble/migrations/0004_auto_20161214_1024.py index b74ebd46..20ec8679 100644 --- a/allianceauth/services/modules/mumble/migrations/0004_auto_20161214_1024.py +++ b/allianceauth/services/modules/mumble/migrations/0004_auto_20161214_1024.py @@ -1,8 +1,8 @@ # Generated by Django 1.10.4 on 2016-12-14 10:24 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/services/modules/mumble/migrations/0006_service_permissions.py b/allianceauth/services/modules/mumble/migrations/0006_service_permissions.py index 1b64ecc9..171915c1 100644 --- a/allianceauth/services/modules/mumble/migrations/0006_service_permissions.py +++ b/allianceauth/services/modules/mumble/migrations/0006_service_permissions.py @@ -1,12 +1,12 @@ # Generated by Django 1.10.5 on 2017-02-02 05:59 -from django.db import migrations -from django.conf import settings -from django.core.exceptions import ObjectDoesNotExist -from django.contrib.auth.management import create_permissions - import logging +from django.conf import settings +from django.contrib.auth.management import create_permissions +from django.core.exceptions import ObjectDoesNotExist +from django.db import migrations + logger = logging.getLogger(__name__) diff --git a/allianceauth/services/modules/mumble/migrations/0007_not_null_user.py b/allianceauth/services/modules/mumble/migrations/0007_not_null_user.py index df12bd95..14d4bd03 100644 --- a/allianceauth/services/modules/mumble/migrations/0007_not_null_user.py +++ b/allianceauth/services/modules/mumble/migrations/0007_not_null_user.py @@ -1,8 +1,8 @@ # Generated by Django 1.11.6 on 2017-10-09 09:19 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/services/modules/mumble/migrations/0008_mumbleuser_display_name.py b/allianceauth/services/modules/mumble/migrations/0008_mumbleuser_display_name.py index 4a4a679d..5d89878e 100644 --- a/allianceauth/services/modules/mumble/migrations/0008_mumbleuser_display_name.py +++ b/allianceauth/services/modules/mumble/migrations/0008_mumbleuser_display_name.py @@ -2,6 +2,7 @@ from django.db import migrations, models + class Migration(migrations.Migration): dependencies = [ diff --git a/allianceauth/services/modules/mumble/migrations/0009_set_mumble_dissplay_names.py b/allianceauth/services/modules/mumble/migrations/0009_set_mumble_dissplay_names.py index c81f54dc..4048f61d 100644 --- a/allianceauth/services/modules/mumble/migrations/0009_set_mumble_dissplay_names.py +++ b/allianceauth/services/modules/mumble/migrations/0009_set_mumble_dissplay_names.py @@ -1,7 +1,10 @@ from django.db import migrations, models -from ..auth_hooks import MumbleService + from allianceauth.services.hooks import NameFormatter +from ..auth_hooks import MumbleService + + def fwd_func(apps, schema_editor): MumbleUser = apps.get_model("mumble", "MumbleUser") db_alias = schema_editor.connection.alias diff --git a/allianceauth/services/modules/mumble/models.py b/allianceauth/services/modules/mumble/models.py index 72ab63fc..a7837689 100644 --- a/allianceauth/services/modules/mumble/models.py +++ b/allianceauth/services/modules/mumble/models.py @@ -1,12 +1,14 @@ +import logging import random import string + from passlib.hash import bcrypt_sha256 -from django.db import models from django.contrib.auth.models import Group -from allianceauth.services.hooks import NameFormatter +from django.db import models + from allianceauth.services.abstract import AbstractServiceModel -import logging +from allianceauth.services.hooks import NameFormatter logger = logging.getLogger(__name__) @@ -43,8 +45,7 @@ class MumbleManager(models.Manager): display_name = self.get_display_name(user) password = self.generate_random_pass() pwhash = self.gen_pwhash(password) - logger.debug("Proceeding with mumble user creation: clean username {}, pwhash starts with {}".format( - username_clean, pwhash[0:5])) + logger.debug(f"Proceeding with mumble user creation: clean username {username_clean}, pwhash starts with {pwhash[0:5]}") logger.info(f"Creating mumble user {username_clean}") result = super().create(user=user, username=username_clean, @@ -71,12 +72,11 @@ class MumbleUser(AbstractServiceModel): username = models.CharField(max_length=254, unique=True) pwhash = models.CharField(max_length=90) hashfn = models.CharField(max_length=20, default='sha1') - groups = models.TextField(blank=True, null=True) + groups = models.TextField(blank=True) certhash = models.CharField( verbose_name="Certificate Hash", max_length=254, blank=True, - null=True, editable=False, help_text="Hash of Mumble client certificate as presented when user authenticates" ) @@ -88,7 +88,6 @@ class MumbleUser(AbstractServiceModel): verbose_name="Mumble Release", max_length=254, blank=True, - null=True, editable=False, help_text="The Mumble Release the user last authenticated with" ) @@ -123,12 +122,11 @@ class MumbleUser(AbstractServiceModel): def update_password(self, password=None): init_password = password - logger.debug(f"Updating mumble user %s password.") + logger.debug("Updating mumble user %s password.") if not password: password = MumbleManager.generate_random_pass() pwhash = MumbleManager.gen_pwhash(password) - logger.debug("Proceeding with mumble user {} password update - pwhash starts with {}".format( - self.user, pwhash[0:5])) + logger.debug(f"Proceeding with mumble user {self.user} password update - pwhash starts with {pwhash[0:5]}") self.pwhash = pwhash self.hashfn = MumbleManager.HASH_FN self.save() diff --git a/allianceauth/services/modules/mumble/tasks.py b/allianceauth/services/modules/mumble/tasks.py index 5ce7c9c4..967abd9f 100644 --- a/allianceauth/services/modules/mumble/tasks.py +++ b/allianceauth/services/modules/mumble/tasks.py @@ -1,9 +1,12 @@ import logging +from celery import shared_task + from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist -from celery import shared_task + from allianceauth.services.tasks import QueueOnce + from .models import MumbleUser logger = logging.getLogger(__name__) @@ -29,40 +32,40 @@ class MumbleTasks: @shared_task(bind=True, name="mumble.update_groups", base=QueueOnce) def update_groups(self, pk): user = User.objects.get(pk=pk) - logger.debug("Updating mumble groups for user %s" % user) + logger.debug(f"Updating mumble groups for user {user}") if MumbleTasks.has_account(user): try: if not user.mumble.update_groups(): raise Exception("Group sync failed") - logger.debug("Updated user %s mumble groups." % user) + logger.debug(f"Updated user {user} mumble groups.") return True except MumbleUser.DoesNotExist: logger.info(f"Mumble group sync failed for {user}, user does not have a mumble account") - except: - logger.exception("Mumble group sync failed for %s, retrying in 10 mins" % user) + except Exception: + logger.exception(f"Mumble group sync failed for {user}, retrying in 10 mins") raise self.retry(countdown=60 * 10) else: - logger.debug("User %s does not have a mumble account, skipping" % user) + logger.debug(f"User {user} does not have a mumble account, skipping") return False @staticmethod @shared_task(bind=True, name="mumble.update_display_name", base=QueueOnce) def update_display_name(self, pk): user = User.objects.get(pk=pk) - logger.debug("Updating mumble groups for user %s" % user) + logger.debug(f"Updating mumble groups for user {user}") if MumbleTasks.has_account(user): try: if not user.mumble.update_display_name(): raise Exception("Display Name Sync failed") - logger.debug("Updated user %s mumble display name." % user) + logger.debug(f"Updated user {user} mumble display name.") return True except MumbleUser.DoesNotExist: logger.info(f"Mumble display name sync failed for {user}, user does not have a mumble account") - except: - logger.exception("Mumble display name sync failed for %s, retrying in 10 mins" % user) + except Exception: + logger.exception(f"Mumble display name sync failed for {user}, retrying in 10 mins") raise self.retry(countdown=60 * 10) else: - logger.debug("User %s does not have a mumble account, skipping" % user) + logger.debug(f"User {user} does not have a mumble account, skipping") return False @staticmethod diff --git a/allianceauth/services/modules/mumble/tests.py b/allianceauth/services/modules/mumble/tests.py index e17d0267..3387938a 100644 --- a/allianceauth/services/modules/mumble/tests.py +++ b/allianceauth/services/modules/mumble/tests.py @@ -1,9 +1,9 @@ from unittest import mock -from django.test import TestCase, RequestFactory from django import urls -from django.contrib.auth.models import User, Group, Permission +from django.contrib.auth.models import Group, Permission, User from django.core.exceptions import ObjectDoesNotExist +from django.test import RequestFactory, TestCase from allianceauth.tests.auth_utils import AuthUtils @@ -29,7 +29,7 @@ class MumbleHooksTestCase(TestCase): member = User.objects.get(pk=member.pk) MumbleUser.objects.create(user=member) self.none_user = 'none_user' - none_user = AuthUtils.create_user(self.none_user) + AuthUtils.create_user(self.none_user) self.service = MumbleService add_permissions() @@ -85,7 +85,7 @@ class MumbleHooksTestCase(TestCase): MumbleUser.objects.create(user=none_user) service.validate_user(none_user) with self.assertRaises(ObjectDoesNotExist): - none_mumble = User.objects.get(username=self.none_user).mumble + _ = User.objects.get(username=self.none_user).mumble def test_delete_user(self): member = User.objects.get(username=self.member) @@ -95,7 +95,7 @@ class MumbleHooksTestCase(TestCase): self.assertTrue(result) with self.assertRaises(ObjectDoesNotExist): - mumble_user = User.objects.get(username=self.member).mumble + _ = User.objects.get(username=self.member).mumble def test_render_services_ctrl(self): service = self.service() @@ -162,7 +162,6 @@ class MumbleViewsTestCase(TestCase): self.assertIn('Member', mumble_user.groups) self.assertIn(',', mumble_user.groups) - def test_deactivate_post(self): self.login() MumbleUser.objects.create(user=self.member) @@ -171,7 +170,7 @@ class MumbleViewsTestCase(TestCase): self.assertRedirects(response, expected_url=urls.reverse('services:services'), target_status_code=200) with self.assertRaises(ObjectDoesNotExist): - mumble_user = User.objects.get(pk=self.member.pk).mumble + _ = User.objects.get(pk=self.member.pk).mumble def test_set_password(self): self.login() diff --git a/allianceauth/services/modules/mumble/views.py b/allianceauth/services/modules/mumble/views.py index ba8904fd..cb13aca2 100644 --- a/allianceauth/services/modules/mumble/views.py +++ b/allianceauth/services/modules/mumble/views.py @@ -1,8 +1,12 @@ import logging +from allianceauth.services.abstract import ( + BaseCreatePasswordServiceAccountView, + BaseDeactivateServiceAccountView, + BaseResetPasswordServiceAccountView, + BaseSetPasswordServiceAccountView, +) from allianceauth.services.forms import ServicePasswordModelForm -from allianceauth.services.abstract import BaseCreatePasswordServiceAccountView, BaseDeactivateServiceAccountView, \ - BaseResetPasswordServiceAccountView, BaseSetPasswordServiceAccountView from .models import MumbleUser diff --git a/allianceauth/services/modules/openfire/admin.py b/allianceauth/services/modules/openfire/admin.py index 6485c6b8..1c95ca41 100644 --- a/allianceauth/services/modules/openfire/admin.py +++ b/allianceauth/services/modules/openfire/admin.py @@ -1,7 +1,7 @@ from django.contrib import admin -from .models import OpenfireUser from ...admin import ServicesUserAdmin +from .models import OpenfireUser @admin.register(OpenfireUser) diff --git a/allianceauth/services/modules/openfire/auth_hooks.py b/allianceauth/services/modules/openfire/auth_hooks.py index ed4e2b88..5b45ae82 100644 --- a/allianceauth/services/modules/openfire/auth_hooks.py +++ b/allianceauth/services/modules/openfire/auth_hooks.py @@ -7,6 +7,7 @@ from django.utils.translation import gettext_lazy as _ from allianceauth import hooks from allianceauth.menu.hooks import MenuItemHook from allianceauth.services.hooks import ServicesHook + from .tasks import OpenfireTasks from .urls import urlpatterns @@ -41,7 +42,7 @@ class OpenfireService(ServicesHook): OpenfireTasks.update_groups.delay(user.pk) def update_all_groups(self): - logger.debug('Update all %s groups called' % self.name) + logger.debug(f'Update all {self.name} groups called') OpenfireTasks.update_all_groups.delay() def service_active_for_user(self, user): diff --git a/allianceauth/services/modules/openfire/manager.py b/allianceauth/services/modules/openfire/manager.py index 1e9215be..89573a97 100644 --- a/allianceauth/services/modules/openfire/manager.py +++ b/allianceauth/services/modules/openfire/manager.py @@ -1,14 +1,14 @@ -import re +import logging import random +import re import string from urllib.parse import urlparse import slixmpp -from django.conf import settings -from ofrestapi.users import Users as ofUsers from ofrestapi import exception +from ofrestapi.users import Users as ofUsers -import logging +from django.conf import settings logger = logging.getLogger(__name__) @@ -60,58 +60,58 @@ class OpenfireManager: @staticmethod def add_user(username): - logger.debug("Adding username %s to openfire." % username) + logger.debug(f"Adding username {username} to openfire.") try: sanitized_username = OpenfireManager.__sanitize_username(username) password = OpenfireManager.__generate_random_pass() api = ofUsers(settings.OPENFIRE_ADDRESS, settings.OPENFIRE_SECRET_KEY) api.add_user(sanitized_username, password) - logger.info("Added openfire user %s" % username) + logger.info(f"Added openfire user {username}") except exception.UserAlreadyExistsException: # User exist - logger.error("Attempting to add a user %s to openfire which already exists on server." % username) + logger.error(f"Attempting to add a user {username} to openfire which already exists on server.") return "", "" return sanitized_username, password @staticmethod def delete_user(username): - logger.debug("Deleting user %s from openfire." % username) + logger.debug(f"Deleting user {username} from openfire.") try: api = ofUsers(settings.OPENFIRE_ADDRESS, settings.OPENFIRE_SECRET_KEY) api.delete_user(username) - logger.info("Deleted user %s from openfire." % username) + logger.info(f"Deleted user {username} from openfire.") return True except exception.UserNotFoundException: - logger.error("Attempting to delete a user %s from openfire which was not found on server." % username) + logger.error(f"Attempting to delete a user {username} from openfire which was not found on server.") return False @staticmethod def lock_user(username): - logger.debug("Locking openfire user %s" % username) + logger.debug(f"Locking openfire user {username}") api = ofUsers(settings.OPENFIRE_ADDRESS, settings.OPENFIRE_SECRET_KEY) api.lock_user(username) - logger.info("Locked openfire user %s" % username) + logger.info(f"Locked openfire user {username}") @staticmethod def unlock_user(username): - logger.debug("Unlocking openfire user %s" % username) + logger.debug(f"Unlocking openfire user {username}") api = ofUsers(settings.OPENFIRE_ADDRESS, settings.OPENFIRE_SECRET_KEY) api.unlock_user(username) - logger.info("Unlocked openfire user %s" % username) + logger.info(f"Unlocked openfire user {username}") @staticmethod def update_user_pass(username, password=None): - logger.debug("Updating openfire user %s password." % username) + logger.debug(f"Updating openfire user {username} password.") try: if not password: password = OpenfireManager.__generate_random_pass() api = ofUsers(settings.OPENFIRE_ADDRESS, settings.OPENFIRE_SECRET_KEY) api.update_user(username, password=password) - logger.info("Updated openfire user %s password." % username) + logger.info(f"Updated openfire user {username} password.") return password except exception.UserNotFoundException: - logger.error("Unable to update openfire user %s password - user not found on server." % username) + logger.error(f"Unable to update openfire user {username} password - user not found on server.") return "" @classmethod @@ -161,7 +161,7 @@ class OpenfireManager: xmpp.process(block=True) message = None if xmpp.message_sent: - logger.debug("Sent jabber ping to group %s" % group_name) + logger.debug(f"Sent jabber ping to group {group_name}") return else: message = "Failed to send Openfire broadcast message." diff --git a/allianceauth/services/modules/openfire/migrations/0001_initial.py b/allianceauth/services/modules/openfire/migrations/0001_initial.py index 7d705897..30656fcb 100644 --- a/allianceauth/services/modules/openfire/migrations/0001_initial.py +++ b/allianceauth/services/modules/openfire/migrations/0001_initial.py @@ -1,8 +1,8 @@ # Generated by Django 1.10.2 on 2016-12-12 03:27 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/services/modules/openfire/migrations/0002_service_permissions.py b/allianceauth/services/modules/openfire/migrations/0002_service_permissions.py index 7570cb4e..59a9aec9 100644 --- a/allianceauth/services/modules/openfire/migrations/0002_service_permissions.py +++ b/allianceauth/services/modules/openfire/migrations/0002_service_permissions.py @@ -1,12 +1,12 @@ # Generated by Django 1.10.5 on 2017-02-02 05:59 -from django.db import migrations -from django.conf import settings -from django.core.exceptions import ObjectDoesNotExist -from django.contrib.auth.management import create_permissions - import logging +from django.conf import settings +from django.contrib.auth.management import create_permissions +from django.core.exceptions import ObjectDoesNotExist +from django.db import migrations + logger = logging.getLogger(__name__) diff --git a/allianceauth/services/modules/openfire/models.py b/allianceauth/services/modules/openfire/models.py index 5299ed8d..672b9cb8 100644 --- a/allianceauth/services/modules/openfire/models.py +++ b/allianceauth/services/modules/openfire/models.py @@ -8,10 +8,11 @@ class OpenfireUser(models.Model): related_name='openfire') username = models.CharField(max_length=254) - def __str__(self): - return self.username + class Meta: permissions = ( ("access_openfire", "Can access the Openfire service"), ) + def __str__(self): + return self.username diff --git a/allianceauth/services/modules/openfire/tasks.py b/allianceauth/services/modules/openfire/tasks.py index 92948d62..6c246d37 100644 --- a/allianceauth/services/modules/openfire/tasks.py +++ b/allianceauth/services/modules/openfire/tasks.py @@ -1,12 +1,15 @@ import logging +from celery import shared_task + from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist + from allianceauth.notifications import notify -from celery import shared_task -from allianceauth.services.tasks import QueueOnce -from allianceauth.services.modules.openfire.manager import OpenfireManager from allianceauth.services.hooks import NameFormatter +from allianceauth.services.modules.openfire.manager import OpenfireManager +from allianceauth.services.tasks import QueueOnce + from .models import OpenfireUser logger = logging.getLogger(__name__) @@ -43,7 +46,7 @@ class OpenfireTasks: @shared_task(bind=True, name="openfire.update_groups", base=QueueOnce) def update_groups(self, pk): user = User.objects.get(pk=pk) - logger.debug("Updating jabber groups for user %s" % user) + logger.debug(f"Updating jabber groups for user {user}") if OpenfireTasks.has_account(user): groups = [user.profile.state.name] for group in user.groups.all(): @@ -51,10 +54,10 @@ class OpenfireTasks: logger.debug(f"Updating user {user} jabber groups to {groups}") try: OpenfireManager.update_user_groups(user.openfire.username, groups) - except: - logger.exception("Jabber group sync failed for %s, retrying in 10 mins" % user) + except Exception: + logger.exception(f"Jabber group sync failed for {user}, retrying in 10 mins") raise self.retry(countdown=60 * 10) - logger.debug("Updated user %s jabber groups." % user) + logger.debug(f"Updated user {user} jabber groups.") else: logger.debug("User does not have an openfire account") diff --git a/allianceauth/services/modules/openfire/tests.py b/allianceauth/services/modules/openfire/tests.py index ed1c3fe3..a6bc9da9 100644 --- a/allianceauth/services/modules/openfire/tests.py +++ b/allianceauth/services/modules/openfire/tests.py @@ -1,9 +1,9 @@ from unittest import mock -from django.test import TestCase, RequestFactory from django import urls -from django.contrib.auth.models import User, Group, Permission +from django.contrib.auth.models import Group, Permission, User from django.core.exceptions import ObjectDoesNotExist +from django.test import RequestFactory, TestCase from allianceauth.tests.auth_utils import AuthUtils @@ -27,7 +27,7 @@ class OpenfireHooksTestCase(TestCase): member = AuthUtils.create_member(self.member) OpenfireUser.objects.create(user=member, username=self.member) self.none_user = 'none_user' - none_user = AuthUtils.create_user(self.none_user) + AuthUtils.create_user(self.none_user) self.service = OpenfireService add_permissions() @@ -86,7 +86,7 @@ class OpenfireHooksTestCase(TestCase): service.validate_user(none_user) self.assertTrue(manager.delete_user.called) with self.assertRaises(ObjectDoesNotExist): - none_openfire = User.objects.get(username=self.none_user).openfire + _ = User.objects.get(username=self.none_user).openfire @mock.patch(MODULE_PATH + '.tasks.OpenfireManager') def test_delete_user(self, manager): @@ -98,7 +98,7 @@ class OpenfireHooksTestCase(TestCase): self.assertTrue(result) self.assertTrue(manager.delete_user.called) with self.assertRaises(ObjectDoesNotExist): - openfire_user = User.objects.get(username=self.member).openfire + _ = User.objects.get(username=self.member).openfire def test_render_services_ctrl(self): service = self.service() @@ -158,7 +158,7 @@ class OpenfireViewsTestCase(TestCase): self.assertTrue(manager.delete_user.called) self.assertRedirects(response, expected_url=urls.reverse('services:services'), target_status_code=200) with self.assertRaises(ObjectDoesNotExist): - openfire_user = User.objects.get(pk=self.member.pk).openfire + _ = User.objects.get(pk=self.member.pk).openfire @mock.patch(MODULE_PATH + '.views.OpenfireManager') def test_set_password(self, manager): diff --git a/allianceauth/services/modules/openfire/views.py b/allianceauth/services/modules/openfire/views.py index b07e12fa..c22f62ab 100644 --- a/allianceauth/services/modules/openfire/views.py +++ b/allianceauth/services/modules/openfire/views.py @@ -4,7 +4,7 @@ import logging from django.contrib import messages from django.contrib.auth.decorators import login_required, permission_required from django.contrib.auth.models import Group -from django.shortcuts import render, redirect +from django.shortcuts import redirect, render from django.utils.translation import gettext_lazy as _ from allianceauth.services.forms import ServicePasswordForm @@ -22,16 +22,16 @@ ACCESS_PERM = 'openfire.access_openfire' @login_required @permission_required(ACCESS_PERM) def activate_jabber(request): - logger.debug("activate_jabber called by user %s" % request.user) + logger.debug(f"activate_jabber called by user {request.user}") character = request.user.profile.main_character logger.debug(f"Adding Jabber user for user {request.user} with main character {character}") info = OpenfireManager.add_user(OpenfireTasks.get_username(request.user)) # If our username is blank means we already had a user if info[0] != "": OpenfireUser.objects.update_or_create(user=request.user, defaults={'username': info[0]}) - logger.debug("Updated authserviceinfo for user %s with Jabber credentials. Updating groups." % request.user) + logger.debug(f"Updated authserviceinfo for user {request.user} with Jabber credentials. Updating groups.") OpenfireTasks.update_groups.delay(request.user.pk) - logger.info("Successfully activated Jabber for user %s" % request.user) + logger.info(f"Successfully activated Jabber for user {request.user}") messages.success(request, _('Activated Jabber account.')) credentials = { 'username': info[0], @@ -39,7 +39,7 @@ def activate_jabber(request): } return render(request, 'services/service_credentials.html', context={'credentials': credentials, 'service': 'Jabber'}) else: - logger.error("Unsuccessful attempt to activate Jabber for user %s" % request.user) + logger.error(f"Unsuccessful attempt to activate Jabber for user {request.user}") messages.error(request, _('An error occurred while processing your Jabber account.')) return redirect("services:services") @@ -47,12 +47,12 @@ def activate_jabber(request): @login_required @permission_required(ACCESS_PERM) def deactivate_jabber(request): - logger.debug("deactivate_jabber called by user %s" % request.user) + logger.debug(f"deactivate_jabber called by user {request.user}") if OpenfireTasks.has_account(request.user) and OpenfireTasks.delete_user(request.user): - logger.info("Successfully deactivated Jabber for user %s" % request.user) + logger.info(f"Successfully deactivated Jabber for user {request.user}") messages.success(request, 'Deactivated Jabber account.') else: - logger.error("Unsuccessful attempt to deactivate Jabber for user %s" % request.user) + logger.error(f"Unsuccessful attempt to deactivate Jabber for user {request.user}") messages.error(request, _('An error occurred while processing your Jabber account.')) return redirect("services:services") @@ -60,19 +60,19 @@ def deactivate_jabber(request): @login_required @permission_required(ACCESS_PERM) def reset_jabber_password(request): - logger.debug("reset_jabber_password called by user %s" % request.user) + logger.debug(f"reset_jabber_password called by user {request.user}") if OpenfireTasks.has_account(request.user): result = OpenfireManager.update_user_pass(request.user.openfire.username) # If our username is blank means we failed if result != "": - logger.info("Successfully reset Jabber password for user %s" % request.user) + logger.info(f"Successfully reset Jabber password for user {request.user}") messages.success(request, _('Reset Jabber password.')) credentials = { 'username': request.user.openfire.username, 'password': result, } return render(request, 'services/service_credentials.html', context={'credentials': credentials, 'service': 'Jabber'}) - logger.error("Unsuccessful attempt to reset Jabber for user %s" % request.user) + logger.error(f"Unsuccessful attempt to reset Jabber for user {request.user}") messages.error(request, _('An error occurred while processing your Jabber account.')) return redirect("services:services") @@ -80,7 +80,7 @@ def reset_jabber_password(request): @login_required @permission_required('auth.jabber_broadcast') def jabber_broadcast_view(request): - logger.debug("jabber_broadcast_view called by user %s" % request.user) + logger.debug(f"jabber_broadcast_view called by user {request.user}") allchoices = [] if request.user.has_perm('auth.jabber_broadcast_all'): allchoices.append(('all', 'all')) @@ -92,7 +92,7 @@ def jabber_broadcast_view(request): if request.method == 'POST': form = JabberBroadcastForm(request.POST) form.fields['group'].choices = allchoices - logger.debug("Received POST request containing form, valid: %s" % form.is_valid()) + logger.debug(f"Received POST request containing form, valid: {form.is_valid()}") if form.is_valid(): main_char = request.user.profile.main_character logger.debug(f"Processing Jabber broadcast for user {request.user} with main character {main_char}") @@ -112,8 +112,8 @@ def jabber_broadcast_view(request): OpenfireManager.send_broadcast_message(group_to_send, message_to_send) - messages.success(request, _('Sent Jabber broadcast to %s' % group_to_send)) - logger.info("Sent Jabber broadcast on behalf of user %s" % request.user) + messages.success(request, _('Sent Jabber broadcast to {}'.format(group_to_send))) + logger.info(f"Sent Jabber broadcast on behalf of user {request.user}") except PingBotException as e: messages.error(request, e) @@ -130,26 +130,26 @@ def jabber_broadcast_view(request): @login_required @permission_required(ACCESS_PERM) def set_jabber_password(request): - logger.debug("set_jabber_password called by user %s" % request.user) + logger.debug(f"set_jabber_password called by user {request.user}") if request.method == 'POST': logger.debug("Received POST request with form.") form = ServicePasswordForm(request.POST) - logger.debug("Form is valid: %s" % form.is_valid()) + logger.debug(f"Form is valid: {form.is_valid()}") if form.is_valid() and OpenfireTasks.has_account(request.user): password = form.cleaned_data['password'] - logger.debug("Form contains password of length %s" % len(password)) + logger.debug(f"Form contains password of length {len(password)}") result = OpenfireManager.update_user_pass(request.user.openfire.username, password=password) if result != "": - logger.info("Successfully set Jabber password for user %s" % request.user) + logger.info(f"Successfully set Jabber password for user {request.user}") messages.success(request, _('Set jabber password.')) else: - logger.error("Failed to install custom Jabber password for user %s" % request.user) + logger.error(f"Failed to install custom Jabber password for user {request.user}") messages.error(request, _('An error occurred while processing your Jabber account.')) return redirect("services:services") else: logger.debug("Request is not type POST - providing empty form.") form = ServicePasswordForm() - logger.debug("Rendering form for user %s" % request.user) + logger.debug(f"Rendering form for user {request.user}") context = {'form': form, 'service': 'Jabber'} return render(request, 'services/service_password.html', context=context) diff --git a/allianceauth/services/modules/phpbb3/admin.py b/allianceauth/services/modules/phpbb3/admin.py index 0e97132d..25c1f019 100644 --- a/allianceauth/services/modules/phpbb3/admin.py +++ b/allianceauth/services/modules/phpbb3/admin.py @@ -1,6 +1,7 @@ from django.contrib import admin -from .models import Phpbb3User + from ...admin import ServicesUserAdmin +from .models import Phpbb3User @admin.register(Phpbb3User) diff --git a/allianceauth/services/modules/phpbb3/auth_hooks.py b/allianceauth/services/modules/phpbb3/auth_hooks.py index 9b45694e..c8081818 100644 --- a/allianceauth/services/modules/phpbb3/auth_hooks.py +++ b/allianceauth/services/modules/phpbb3/auth_hooks.py @@ -5,6 +5,7 @@ from django.template.loader import render_to_string from allianceauth import hooks from allianceauth.services.hooks import ServicesHook + from .tasks import Phpbb3Tasks from .urls import urlpatterns @@ -39,7 +40,7 @@ class Phpbb3Service(ServicesHook): Phpbb3Tasks.update_groups.delay(user.pk) def update_all_groups(self): - logger.debug('Update all %s groups called' % self.name) + logger.debug(f'Update all {self.name} groups called') Phpbb3Tasks.update_all_groups.delay() def service_active_for_user(self, user): diff --git a/allianceauth/services/modules/phpbb3/manager.py b/allianceauth/services/modules/phpbb3/manager.py index 7e6120a6..addac2ee 100644 --- a/allianceauth/services/modules/phpbb3/manager.py +++ b/allianceauth/services/modules/phpbb3/manager.py @@ -1,16 +1,16 @@ -import random -import string import calendar +import logging +import random import re +import string from datetime import datetime from passlib.apps import phpbb3_context -from django.db import connections -from allianceauth.eveonline.models import EveCharacter - -import logging from django.conf import settings +from django.db import connections + +from allianceauth.eveonline.models import EveCharacter logger = logging.getLogger(__name__) @@ -19,39 +19,39 @@ TABLE_PREFIX = getattr(settings, 'PHPBB3_TABLE_PREFIX', 'phpbb_') class Phpbb3Manager: - SQL_ADD_USER = r"INSERT INTO %susers (username, username_clean, " \ + SQL_ADD_USER = rf"INSERT INTO {TABLE_PREFIX}users (username, username_clean, " \ r"user_password, user_email, group_id, user_regdate, user_permissions, " \ - r"user_sig, user_lang) VALUES (%%s, %%s, %%s, %%s, %%s, %%s, %%s, %%s, 'en')" % TABLE_PREFIX + r"user_sig, user_lang) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'en')" - SQL_DEL_USER = r"DELETE FROM %susers where username = %%s" % TABLE_PREFIX + SQL_DEL_USER = rf"DELETE FROM {TABLE_PREFIX}users where username = %s" - SQL_DIS_USER = r"UPDATE %susers SET user_email= %%s, user_password=%%s WHERE username = %%s" % TABLE_PREFIX + SQL_DIS_USER = rf"UPDATE {TABLE_PREFIX}users SET user_email= %s, user_password=%s WHERE username = %s" - SQL_USER_ID_FROM_USERNAME = r"SELECT user_id from %susers WHERE username = %%s" % TABLE_PREFIX + SQL_USER_ID_FROM_USERNAME = rf"SELECT user_id from {TABLE_PREFIX}users WHERE username = %s" - SQL_ADD_USER_GROUP = r"INSERT INTO %suser_group (group_id, user_id, user_pending) VALUES (%%s, %%s, %%s)" % TABLE_PREFIX + SQL_ADD_USER_GROUP = rf"INSERT INTO {TABLE_PREFIX}user_group (group_id, user_id, user_pending) VALUES (%s, %s, %s)" - SQL_GET_GROUP_ID = r"SELECT group_id from %sgroups WHERE group_name = %%s" % TABLE_PREFIX + SQL_GET_GROUP_ID = rf"SELECT group_id from {TABLE_PREFIX}groups WHERE group_name = %s" - SQL_ADD_GROUP = r"INSERT INTO %sgroups (group_name,group_desc,group_legend) VALUES (%%s,%%s,0)" % TABLE_PREFIX + SQL_ADD_GROUP = rf"INSERT INTO {TABLE_PREFIX}groups (group_name,group_desc,group_legend) VALUES (%s,%s,0)" - SQL_UPDATE_USER_PASSWORD = r"UPDATE %susers SET user_password = %%s WHERE username = %%s" % TABLE_PREFIX + SQL_UPDATE_USER_PASSWORD = rf"UPDATE {TABLE_PREFIX}users SET user_password = %s WHERE username = %s" - SQL_REMOVE_USER_GROUP = r"DELETE FROM %suser_group WHERE user_id=%%s AND group_id=%%s " % TABLE_PREFIX + SQL_REMOVE_USER_GROUP = rf"DELETE FROM {TABLE_PREFIX}user_group WHERE user_id=%s AND group_id=%s " - SQL_GET_ALL_GROUPS = r"SELECT group_id, group_name FROM %sgroups" % TABLE_PREFIX + SQL_GET_ALL_GROUPS = rf"SELECT group_id, group_name FROM {TABLE_PREFIX}groups" - SQL_GET_USER_GROUPS = r"SELECT %(prefix)sgroups.group_name FROM %(prefix)sgroups , %(prefix)suser_group WHERE " \ - r"%(prefix)suser_group.group_id = %(prefix)sgroups.group_id AND user_id=%%s" % {'prefix': TABLE_PREFIX} + SQL_GET_USER_GROUPS = rf"SELECT {TABLE_PREFIX}groups.group_name FROM {TABLE_PREFIX}groups , {TABLE_PREFIX}user_group WHERE " \ + rf"{TABLE_PREFIX}user_group.group_id = {TABLE_PREFIX}groups.group_id AND user_id=%s" - SQL_ADD_USER_AVATAR = r"UPDATE %susers SET user_avatar_type=2, user_avatar_width=64, user_avatar_height=64, " \ - "user_avatar=%%s WHERE user_id = %%s" % TABLE_PREFIX + SQL_ADD_USER_AVATAR = rf"UPDATE {TABLE_PREFIX}users SET user_avatar_type=2, user_avatar_width=64, user_avatar_height=64, " \ + "user_avatar=%s WHERE user_id = %s" - SQL_CLEAR_USER_PERMISSIONS = r"UPDATE %susers SET user_permissions = '' WHERE user_id = %%s" % TABLE_PREFIX + SQL_CLEAR_USER_PERMISSIONS = rf"UPDATE {TABLE_PREFIX}users SET user_permissions = '' WHERE user_id = %s" - SQL_DEL_SESSION = r"DELETE FROM %ssessions where session_user_id = %%s" % TABLE_PREFIX + SQL_DEL_SESSION = rf"DELETE FROM {TABLE_PREFIX}sessions where session_user_id = %s" - SQL_DEL_AUTOLOGIN = r"DELETE FROM %ssessions_keys where user_id = %%s" % TABLE_PREFIX + SQL_DEL_AUTOLOGIN = rf"DELETE FROM {TABLE_PREFIX}sessions_keys where user_id = %s" def __init__(self): pass @@ -85,7 +85,7 @@ class Phpbb3Manager: @staticmethod def __get_group_id(groupname): - logger.debug("Getting phpbb3 group id for groupname %s" % groupname) + logger.debug(f"Getting phpbb3 group id for groupname {groupname}") cursor = connections['phpbb3'].cursor() cursor.execute(Phpbb3Manager.SQL_GET_GROUP_ID, [groupname]) row = cursor.fetchone() @@ -94,7 +94,7 @@ class Phpbb3Manager: @staticmethod def __get_user_id(username): - logger.debug("Getting phpbb3 user id for username %s" % username) + logger.debug(f"Getting phpbb3 user id for username {username}") cursor = connections['phpbb3'].cursor() cursor.execute(Phpbb3Manager.SQL_USER_ID_FROM_USERNAME, [username]) row = cursor.fetchone() @@ -102,7 +102,7 @@ class Phpbb3Manager: logger.debug(f"Got phpbb user id {row[0]} for username {username}") return row[0] else: - logger.error("Username %s not found on phpbb. Unable to determine user id." % username) + logger.error(f"Username {username} not found on phpbb. Unable to determine user id.") return None @staticmethod @@ -114,12 +114,12 @@ class Phpbb3Manager: out = {} for row in rows: out[row[1]] = row[0] - logger.debug("Got phpbb groups %s" % out) + logger.debug(f"Got phpbb groups {out}") return out @staticmethod def __get_user_groups(userid): - logger.debug("Getting phpbb3 user id %s groups" % userid) + logger.debug(f"Getting phpbb3 user id {userid} groups") cursor = connections['phpbb3'].cursor() cursor.execute(Phpbb3Manager.SQL_GET_USER_GROUPS, [userid]) out = [row[0] for row in cursor.fetchall()] @@ -134,10 +134,10 @@ class Phpbb3Manager: @staticmethod def __create_group(groupname): - logger.debug("Creating phpbb3 group %s" % groupname) + logger.debug(f"Creating phpbb3 group {groupname}") cursor = connections['phpbb3'].cursor() cursor.execute(Phpbb3Manager.SQL_ADD_GROUP, [groupname, groupname]) - logger.info("Created phpbb group %s" % groupname) + logger.info(f"Created phpbb group {groupname}") return Phpbb3Manager.__get_group_id(groupname) @staticmethod @@ -148,7 +148,7 @@ class Phpbb3Manager: cursor.execute(Phpbb3Manager.SQL_ADD_USER_GROUP, [groupid, userid, 0]) cursor.execute(Phpbb3Manager.SQL_CLEAR_USER_PERMISSIONS, [userid]) logger.info(f"Added phpbb user id {userid} to group id {groupid}") - except: + except Exception: logger.exception(f"Unable to add phpbb user id {userid} to group id {groupid}") pass @@ -160,14 +160,13 @@ class Phpbb3Manager: cursor.execute(Phpbb3Manager.SQL_REMOVE_USER_GROUP, [userid, groupid]) cursor.execute(Phpbb3Manager.SQL_CLEAR_USER_PERMISSIONS, [userid]) logger.info(f"Removed phpbb user id {userid} from group id {groupid}") - except: + except Exception: logger.exception(f"Unable to remove phpbb user id {userid} from group id {groupid}") pass @staticmethod def add_user(username, email, groups, characterid): - logger.debug("Adding phpbb user with username {}, email {}, groups {}, characterid {}".format( - username, email, groups, characterid)) + logger.debug(f"Adding phpbb user with username {username}, email {email}, groups {groups}, characterid {characterid}") cursor = connections['phpbb3'].cursor() username_clean = Phpbb3Manager.__santatize_username(username) @@ -176,7 +175,7 @@ class Phpbb3Manager: logger.debug(f"Proceeding to add phpbb user {username_clean} and pwhash starting with {pwhash[0:5]}") # check if the username was simply revoked if Phpbb3Manager.check_user(username_clean): - logger.warning("Unable to add phpbb user with username %s - already exists. Updating user instead." % username) + logger.warning(f"Unable to add phpbb user with username {username} - already exists. Updating user instead.") Phpbb3Manager.__update_user_info(username_clean, email, pwhash) else: try: @@ -186,16 +185,16 @@ class Phpbb3Manager: "", ""]) Phpbb3Manager.update_groups(username_clean, groups) Phpbb3Manager.__add_avatar(username_clean, characterid) - logger.info("Added phpbb user %s" % username_clean) - except: - logger.exception("Unable to add phpbb user %s" % username_clean) + logger.info(f"Added phpbb user {username_clean}") + except Exception: + logger.exception(f"Unable to add phpbb user {username_clean}") pass return username_clean, password @staticmethod def disable_user(username): - logger.debug("Disabling phpbb user %s" % username) + logger.debug(f"Disabling phpbb user {username}") cursor = connections['phpbb3'].cursor() password = Phpbb3Manager.__gen_hash(Phpbb3Manager.__generate_random_pass()) @@ -207,22 +206,22 @@ class Phpbb3Manager: cursor.execute(Phpbb3Manager.SQL_DEL_AUTOLOGIN, [userid]) cursor.execute(Phpbb3Manager.SQL_DEL_SESSION, [userid]) Phpbb3Manager.update_groups(username, []) - logger.info("Disabled phpbb user %s" % username) + logger.info(f"Disabled phpbb user {username}") return True except TypeError: - logger.exception("TypeError occured while disabling user %s - failed to disable." % username) + logger.exception(f"TypeError occured while disabling user {username} - failed to disable.") return False @staticmethod def delete_user(username): - logger.debug("Deleting phpbb user %s" % username) + logger.debug(f"Deleting phpbb user {username}") cursor = connections['phpbb3'].cursor() if Phpbb3Manager.check_user(username): cursor.execute(Phpbb3Manager.SQL_DEL_USER, [username]) - logger.info("Deleted phpbb user %s" % username) + logger.info(f"Deleted phpbb user {username}") return True - logger.error("Unable to delete phpbb user %s - user not found on phpbb." % username) + logger.error(f"Unable to delete phpbb user {username} - user not found on phpbb.") return False @staticmethod @@ -237,7 +236,7 @@ class Phpbb3Manager: remgroups = user_groups - act_groups logger.info(f"Updating phpbb user {username} groups - adding {addgroups}, removing {remgroups}") for g in addgroups: - if not g in forum_groups: + if g not in forum_groups: forum_groups[g] = Phpbb3Manager.__create_group(g) Phpbb3Manager.__add_user_to_group(userid, forum_groups[g]) @@ -257,27 +256,26 @@ class Phpbb3Manager: try: cursor.execute(Phpbb3Manager.SQL_REMOVE_USER_GROUP, [userid, groupid]) logger.info(f"Removed phpbb user {username} from group {group}") - except: + except Exception: logger.exception( - "Exception prevented removal of phpbb user {} with id {} from group {} with id {}".format( - username, userid, group, groupid)) + f"Exception prevented removal of phpbb user {username} with id {userid} from group {group} with id {groupid}") pass @staticmethod def check_user(username): - logger.debug("Checking phpbb username %s" % username) + logger.debug(f"Checking phpbb username {username}") cursor = connections['phpbb3'].cursor() cursor.execute(Phpbb3Manager.SQL_USER_ID_FROM_USERNAME, [Phpbb3Manager.__santatize_username(username)]) row = cursor.fetchone() if row: - logger.debug("Found user %s on phpbb" % username) + logger.debug(f"Found user {username} on phpbb") return True - logger.debug("User %s not found on phpbb" % username) + logger.debug(f"User {username} not found on phpbb") return False @staticmethod def update_user_password(username, characterid, password=None): - logger.debug("Updating phpbb user %s password" % username) + logger.debug(f"Updating phpbb user {username} password") cursor = connections['phpbb3'].cursor() if not password: password = Phpbb3Manager.__generate_random_pass() @@ -287,9 +285,9 @@ class Phpbb3Manager: f"Proceeding to update phpbb user {username} password with pwhash starting with {pwhash[0:5]}") cursor.execute(Phpbb3Manager.SQL_UPDATE_USER_PASSWORD, [pwhash, username]) Phpbb3Manager.__add_avatar(username, characterid) - logger.info("Updated phpbb user %s password." % username) + logger.info(f"Updated phpbb user {username} password.") return password - logger.error("Unable to update phpbb user %s password - user not found on phpbb." % username) + logger.error(f"Unable to update phpbb user {username} password - user not found on phpbb.") return "" @staticmethod @@ -299,7 +297,7 @@ class Phpbb3Manager: cursor = connections['phpbb3'].cursor() try: cursor.execute(Phpbb3Manager.SQL_DIS_USER, [email, password, username]) - logger.info("Updated phpbb user %s info" % username) - except: - logger.exception("Unable to update phpbb user %s info." % username) + logger.info(f"Updated phpbb user {username} info") + except Exception: + logger.exception(f"Unable to update phpbb user {username} info.") pass diff --git a/allianceauth/services/modules/phpbb3/migrations/0001_initial.py b/allianceauth/services/modules/phpbb3/migrations/0001_initial.py index 151aa380..a822d713 100644 --- a/allianceauth/services/modules/phpbb3/migrations/0001_initial.py +++ b/allianceauth/services/modules/phpbb3/migrations/0001_initial.py @@ -1,8 +1,8 @@ # Generated by Django 1.10.2 on 2016-12-12 03:28 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/services/modules/phpbb3/migrations/0002_service_permissions.py b/allianceauth/services/modules/phpbb3/migrations/0002_service_permissions.py index 6757c2df..cb28e494 100644 --- a/allianceauth/services/modules/phpbb3/migrations/0002_service_permissions.py +++ b/allianceauth/services/modules/phpbb3/migrations/0002_service_permissions.py @@ -1,12 +1,12 @@ # Generated by Django 1.10.5 on 2017-02-02 05:59 -from django.db import migrations -from django.conf import settings -from django.core.exceptions import ObjectDoesNotExist -from django.contrib.auth.management import create_permissions - import logging +from django.conf import settings +from django.contrib.auth.management import create_permissions +from django.core.exceptions import ObjectDoesNotExist +from django.db import migrations + logger = logging.getLogger(__name__) diff --git a/allianceauth/services/modules/phpbb3/tasks.py b/allianceauth/services/modules/phpbb3/tasks.py index 53cf1331..88d9d3bb 100644 --- a/allianceauth/services/modules/phpbb3/tasks.py +++ b/allianceauth/services/modules/phpbb3/tasks.py @@ -1,11 +1,14 @@ import logging +from celery import shared_task + from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist -from celery import shared_task -from allianceauth.services.tasks import QueueOnce + from allianceauth.notifications import notify from allianceauth.services.hooks import NameFormatter +from allianceauth.services.tasks import QueueOnce + from .manager import Phpbb3Manager from .models import Phpbb3User @@ -38,7 +41,7 @@ class Phpbb3Tasks: @shared_task(bind=True, name="phpbb3.update_groups", base=QueueOnce) def update_groups(self, pk): user = User.objects.get(pk=pk) - logger.debug("Updating phpbb3 groups for user %s" % user) + logger.debug(f"Updating phpbb3 groups for user {user}") if Phpbb3Tasks.has_account(user): groups = [user.profile.state.name] for group in user.groups.all(): @@ -46,10 +49,10 @@ class Phpbb3Tasks: logger.debug(f"Updating user {user} phpbb3 groups to {groups}") try: Phpbb3Manager.update_groups(user.phpbb3.username, groups) - except: - logger.exception("Phpbb group sync failed for %s, retrying in 10 mins" % user) + except Exception: + logger.exception(f"Phpbb group sync failed for {user}, retrying in 10 mins") raise self.retry(countdown=60 * 10) - logger.debug("Updated user %s phpbb3 groups." % user) + logger.debug(f"Updated user {user} phpbb3 groups.") else: logger.debug("User does not have a Phpbb3 account") diff --git a/allianceauth/services/modules/phpbb3/tests.py b/allianceauth/services/modules/phpbb3/tests.py index f6d250bf..ff013eb1 100644 --- a/allianceauth/services/modules/phpbb3/tests.py +++ b/allianceauth/services/modules/phpbb3/tests.py @@ -1,9 +1,9 @@ from unittest import mock -from django.test import TestCase, RequestFactory from django import urls -from django.contrib.auth.models import User, Group, Permission +from django.contrib.auth.models import Group, Permission, User from django.core.exceptions import ObjectDoesNotExist +from django.test import RequestFactory, TestCase from allianceauth.tests.auth_utils import AuthUtils @@ -27,7 +27,7 @@ class Phpbb3HooksTestCase(TestCase): member = AuthUtils.create_member(self.member) Phpbb3User.objects.create(user=member, username=self.member) self.none_user = 'none_user' - none_user = AuthUtils.create_user(self.none_user) + AuthUtils.create_user(self.none_user) self.service = Phpbb3Service add_permissions() @@ -86,7 +86,8 @@ class Phpbb3HooksTestCase(TestCase): service.validate_user(none_user) self.assertTrue(manager.disable_user.called) with self.assertRaises(ObjectDoesNotExist): - none_phpbb3 = User.objects.get(username=self.none_user).phpbb3 + user = User.objects.get(username=self.none_user) + _ = user.phpbb3 @mock.patch(MODULE_PATH + '.tasks.Phpbb3Manager') def test_delete_user(self, manager): @@ -98,7 +99,8 @@ class Phpbb3HooksTestCase(TestCase): self.assertTrue(result) self.assertTrue(manager.disable_user.called) with self.assertRaises(ObjectDoesNotExist): - phpbb3_user = User.objects.get(username=self.member).phpbb3 + user = User.objects.get(username=self.member) + _ = user.phpbb3 def test_render_services_ctrl(self): service = self.service() @@ -158,7 +160,8 @@ class Phpbb3ViewsTestCase(TestCase): self.assertTrue(manager.disable_user.called) self.assertRedirects(response, expected_url=urls.reverse('services:services'), target_status_code=200) with self.assertRaises(ObjectDoesNotExist): - phpbb3_user = User.objects.get(pk=self.member.pk).phpbb3 + user = User.objects.get(pk=self.member.pk) + _ = user.phpbb3 @mock.patch(MODULE_PATH + '.views.Phpbb3Manager') def test_set_password(self, manager): diff --git a/allianceauth/services/modules/phpbb3/views.py b/allianceauth/services/modules/phpbb3/views.py index b847c8af..ba1ceb84 100644 --- a/allianceauth/services/modules/phpbb3/views.py +++ b/allianceauth/services/modules/phpbb3/views.py @@ -2,7 +2,7 @@ import logging from django.contrib import messages from django.contrib.auth.decorators import login_required, permission_required -from django.shortcuts import render, redirect +from django.shortcuts import redirect, render from django.utils.translation import gettext_lazy as _ from allianceauth.services.forms import ServicePasswordForm @@ -19,7 +19,7 @@ ACCESS_PERM = 'phpbb3.access_phpbb3' @login_required @permission_required(ACCESS_PERM) def activate_forum(request): - logger.debug("activate_forum called by user %s" % request.user) + logger.debug(f"activate_forum called by user {request.user}") # Valid now we get the main characters character = request.user.profile.main_character logger.debug(f"Adding phpbb user for user {request.user} with main character {character}") @@ -28,9 +28,9 @@ def activate_forum(request): # if empty we failed if result[0] != "": Phpbb3User.objects.update_or_create(user=request.user, defaults={'username': result[0]}) - logger.debug("Updated authserviceinfo for user %s with forum credentials. Updating groups." % request.user) + logger.debug(f"Updated authserviceinfo for user {request.user} with forum credentials. Updating groups.") Phpbb3Tasks.update_groups.delay(request.user.pk) - logger.info("Successfully activated forum for user %s" % request.user) + logger.info(f"Successfully activated forum for user {request.user}") messages.success(request, _('Activated forum account.')) credentials = { 'username': result[0], @@ -38,7 +38,7 @@ def activate_forum(request): } return render(request, 'services/service_credentials.html', context={'credentials': credentials, 'service': 'Forum'}) else: - logger.error("Unsuccessful attempt to activate forum for user %s" % request.user) + logger.error(f"Unsuccessful attempt to activate forum for user {request.user}") messages.error(request, _('An error occurred while processing your forum account.')) return redirect("services:services") @@ -46,13 +46,13 @@ def activate_forum(request): @login_required @permission_required(ACCESS_PERM) def deactivate_forum(request): - logger.debug("deactivate_forum called by user %s" % request.user) + logger.debug(f"deactivate_forum called by user {request.user}") # false we failed if Phpbb3Tasks.delete_user(request.user): - logger.info("Successfully deactivated forum for user %s" % request.user) + logger.info(f"Successfully deactivated forum for user {request.user}") messages.success(request, _('Deactivated forum account.')) else: - logger.error("Unsuccessful attempt to activate forum for user %s" % request.user) + logger.error(f"Unsuccessful attempt to activate forum for user {request.user}") messages.error(request, _('An error occurred while processing your forum account.')) return redirect("services:services") @@ -60,13 +60,13 @@ def deactivate_forum(request): @login_required @permission_required(ACCESS_PERM) def reset_forum_password(request): - logger.debug("reset_forum_password called by user %s" % request.user) + logger.debug(f"reset_forum_password called by user {request.user}") if Phpbb3Tasks.has_account(request.user): character = request.user.profile.main_character result = Phpbb3Manager.update_user_password(request.user.phpbb3.username, character.character_id) # false we failed if result != "": - logger.info("Successfully reset forum password for user %s" % request.user) + logger.info(f"Successfully reset forum password for user {request.user}") messages.success(request, _('Reset forum password.')) credentials = { 'username': request.user.phpbb3.username, @@ -74,7 +74,7 @@ def reset_forum_password(request): } return render(request, 'services/service_credentials.html', context={'credentials': credentials, 'service': 'Forum'}) - logger.error("Unsuccessful attempt to reset forum password for user %s" % request.user) + logger.error(f"Unsuccessful attempt to reset forum password for user {request.user}") messages.error(request, _('An error occurred while processing your forum account.')) return redirect("services:services") @@ -82,28 +82,28 @@ def reset_forum_password(request): @login_required @permission_required(ACCESS_PERM) def set_forum_password(request): - logger.debug("set_forum_password called by user %s" % request.user) + logger.debug(f"set_forum_password called by user {request.user}") if request.method == 'POST': logger.debug("Received POST request with form.") form = ServicePasswordForm(request.POST) - logger.debug("Form is valid: %s" % form.is_valid()) + logger.debug(f"Form is valid: {form.is_valid()}") if form.is_valid() and Phpbb3Tasks.has_account(request.user): password = form.cleaned_data['password'] - logger.debug("Form contains password of length %s" % len(password)) + logger.debug(f"Form contains password of length {len(password)}") character = request.user.profile.main_character result = Phpbb3Manager.update_user_password(request.user.phpbb3.username, character.character_id, password=password) if result != "": - logger.info("Successfully set forum password for user %s" % request.user) + logger.info(f"Successfully set forum password for user {request.user}") messages.success(request, _('Set forum password.')) else: - logger.error("Failed to install custom forum password for user %s" % request.user) + logger.error(f"Failed to install custom forum password for user {request.user}") messages.error(request, _('An error occurred while processing your forum account.')) return redirect("services:services") else: logger.debug("Request is not type POST - providing empty form.") form = ServicePasswordForm() - logger.debug("Rendering form for user %s" % request.user) + logger.debug(f"Rendering form for user {request.user}") context = {'form': form, 'service': 'Forum'} return render(request, 'services/service_password.html', context=context) diff --git a/allianceauth/services/modules/smf/admin.py b/allianceauth/services/modules/smf/admin.py index db2dcae2..dc17f1a4 100644 --- a/allianceauth/services/modules/smf/admin.py +++ b/allianceauth/services/modules/smf/admin.py @@ -1,7 +1,7 @@ from django.contrib import admin -from .models import SmfUser from ...admin import ServicesUserAdmin +from .models import SmfUser @admin.register(SmfUser) diff --git a/allianceauth/services/modules/smf/auth_hooks.py b/allianceauth/services/modules/smf/auth_hooks.py index 8065e935..99859277 100644 --- a/allianceauth/services/modules/smf/auth_hooks.py +++ b/allianceauth/services/modules/smf/auth_hooks.py @@ -5,6 +5,7 @@ from django.template.loader import render_to_string from allianceauth import hooks from allianceauth.services.hooks import ServicesHook + from .tasks import SmfTasks from .urls import urlpatterns @@ -45,7 +46,7 @@ class SmfService(ServicesHook): SmfTasks.update_display_name.apply_async(args=[user.pk], countdown=5) # cooldown on this task to ensure DB clean when syncing def update_all_groups(self): - logger.debug('Update all %s groups called' % self.name) + logger.debug(f'Update all {self.name} groups called') SmfTasks.update_all_groups.delay() def service_active_for_user(self, user): diff --git a/allianceauth/services/modules/smf/manager.py b/allianceauth/services/modules/smf/manager.py index d0f52617..4113bfe1 100644 --- a/allianceauth/services/modules/smf/manager.py +++ b/allianceauth/services/modules/smf/manager.py @@ -1,17 +1,16 @@ -import random -import string import calendar -from datetime import datetime import hashlib import logging +import random import re -from typing import Tuple +import string +from datetime import datetime from packaging import version -from django.db import connections from django.conf import settings from django.contrib.auth.models import User +from django.db import connections from allianceauth.eveonline.models import EveCharacter @@ -26,43 +25,43 @@ class SmfManager: pass # For SMF < 2.1 - SQL_ADD_USER_SMF_20 = r"INSERT INTO %smembers (member_name, passwd, email_address, date_registered, real_name," \ + SQL_ADD_USER_SMF_20 = rf"INSERT INTO {TABLE_PREFIX}members (member_name, passwd, email_address, date_registered, real_name," \ r" buddy_list, message_labels, openid_uri, signature, ignore_boards) " \ - r"VALUES (%%s, %%s, %%s, %%s, %%s, 0, 0, 0, 0, 0)" % TABLE_PREFIX + r"VALUES (%s, %s, %s, %s, %s, 0, 0, 0, 0, 0)" # For SMF >= 2.1 - SQL_ADD_USER_SMF_21 = r"INSERT INTO %smembers (member_name, passwd, email_address, date_registered, real_name," \ + SQL_ADD_USER_SMF_21 = rf"INSERT INTO {TABLE_PREFIX}members (member_name, passwd, email_address, date_registered, real_name," \ r" buddy_list, signature, ignore_boards) " \ - r"VALUES (%%s, %%s, %%s, %%s, %%s, 0, 0, 0)" % TABLE_PREFIX + r"VALUES (%s, %s, %s, %s, %s, 0, 0, 0)" # returns something like »window.smfVersion = "SMF 2.0.19";« - SQL_GET_CURRENT_SMF_VERSION = r"SELECT data FROM %sadmin_info_files WHERE filename = %%s" % TABLE_PREFIX + SQL_GET_CURRENT_SMF_VERSION = rf"SELECT data FROM {TABLE_PREFIX}admin_info_files WHERE filename = %s" - SQL_DEL_USER = r"DELETE FROM %smembers where member_name = %%s" % TABLE_PREFIX + SQL_DEL_USER = rf"DELETE FROM {TABLE_PREFIX}members where member_name = %s" - SQL_UPD_USER = r"UPDATE %smembers SET email_address = %%s, passwd = %%s, real_name = %%s WHERE member_name = %%s" % TABLE_PREFIX + SQL_UPD_USER = rf"UPDATE {TABLE_PREFIX}members SET email_address = %s, passwd = %s, real_name = %s WHERE member_name = %s" - SQL_UPD_DISPLAY_NAME = r"UPDATE %smembers SET real_name = %%s WHERE member_name = %%s" % TABLE_PREFIX + SQL_UPD_DISPLAY_NAME = rf"UPDATE {TABLE_PREFIX}members SET real_name = %s WHERE member_name = %s" - SQL_DIS_USER = r"UPDATE %smembers SET email_address = %%s, passwd = %%s WHERE member_name = %%s" % TABLE_PREFIX + SQL_DIS_USER = rf"UPDATE {TABLE_PREFIX}members SET email_address = %s, passwd = %s WHERE member_name = %s" - SQL_USER_ID_FROM_USERNAME = r"SELECT id_member from %smembers WHERE member_name = %%s" % TABLE_PREFIX + SQL_USER_ID_FROM_USERNAME = rf"SELECT id_member from {TABLE_PREFIX}members WHERE member_name = %s" - SQL_ADD_USER_GROUP = r"UPDATE %smembers SET additional_groups = %%s WHERE id_member = %%s" % TABLE_PREFIX + SQL_ADD_USER_GROUP = rf"UPDATE {TABLE_PREFIX}members SET additional_groups = %s WHERE id_member = %s" - SQL_GET_GROUP_ID = r"SELECT id_group from %smembergroups WHERE group_name = %%s" % TABLE_PREFIX + SQL_GET_GROUP_ID = rf"SELECT id_group from {TABLE_PREFIX}membergroups WHERE group_name = %s" - SQL_ADD_GROUP = r"INSERT INTO %smembergroups (group_name,description) VALUES (%%s,%%s)" % TABLE_PREFIX + SQL_ADD_GROUP = rf"INSERT INTO {TABLE_PREFIX}membergroups (group_name,description) VALUES (%s,%s)" - SQL_UPDATE_USER_PASSWORD = r"UPDATE %smembers SET passwd = %%s WHERE member_name = %%s" % TABLE_PREFIX + SQL_UPDATE_USER_PASSWORD = rf"UPDATE {TABLE_PREFIX}members SET passwd = %s WHERE member_name = %s" - SQL_REMOVE_USER_GROUP = r"UPDATE %smembers SET additional_groups = %%s WHERE id_member = %%s" % TABLE_PREFIX + SQL_REMOVE_USER_GROUP = rf"UPDATE {TABLE_PREFIX}members SET additional_groups = %s WHERE id_member = %s" - SQL_GET_ALL_GROUPS = r"SELECT id_group, group_name FROM %smembergroups" % TABLE_PREFIX + SQL_GET_ALL_GROUPS = rf"SELECT id_group, group_name FROM {TABLE_PREFIX}membergroups" - SQL_GET_USER_GROUPS = r"SELECT additional_groups FROM %smembers WHERE id_member = %%s" % TABLE_PREFIX + SQL_GET_USER_GROUPS = rf"SELECT additional_groups FROM {TABLE_PREFIX}members WHERE id_member = %s" - SQL_ADD_USER_AVATAR = r"UPDATE %smembers SET avatar = %%s WHERE id_member = %%s" % TABLE_PREFIX + SQL_ADD_USER_AVATAR = rf"UPDATE {TABLE_PREFIX}members SET avatar = %s WHERE id_member = %s" @classmethod def _get_current_smf_version(cls) -> str: diff --git a/allianceauth/services/modules/smf/migrations/0001_initial.py b/allianceauth/services/modules/smf/migrations/0001_initial.py index b4ce2f34..a0626fca 100644 --- a/allianceauth/services/modules/smf/migrations/0001_initial.py +++ b/allianceauth/services/modules/smf/migrations/0001_initial.py @@ -1,8 +1,8 @@ # Generated by Django 1.10.2 on 2016-12-12 03:28 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/services/modules/smf/migrations/0002_service_permissions.py b/allianceauth/services/modules/smf/migrations/0002_service_permissions.py index 611111eb..780dee84 100644 --- a/allianceauth/services/modules/smf/migrations/0002_service_permissions.py +++ b/allianceauth/services/modules/smf/migrations/0002_service_permissions.py @@ -1,12 +1,12 @@ # Generated by Django 1.10.5 on 2017-02-02 05:59 -from django.db import migrations -from django.conf import settings -from django.core.exceptions import ObjectDoesNotExist -from django.contrib.auth.management import create_permissions - import logging +from django.conf import settings +from django.contrib.auth.management import create_permissions +from django.core.exceptions import ObjectDoesNotExist +from django.db import migrations + logger = logging.getLogger(__name__) diff --git a/allianceauth/services/modules/smf/migrations/0003_set_smf_displayed_names.py b/allianceauth/services/modules/smf/migrations/0003_set_smf_displayed_names.py index ea4f82a9..ede12672 100644 --- a/allianceauth/services/modules/smf/migrations/0003_set_smf_displayed_names.py +++ b/allianceauth/services/modules/smf/migrations/0003_set_smf_displayed_names.py @@ -1,6 +1,8 @@ from django.db import migrations + from ..manager import SmfManager + def on_migrate(apps, schema_editor): SmfUser = apps.get_model("smf", "SmfUser") db_alias = schema_editor.connection.alias @@ -9,7 +11,7 @@ def on_migrate(apps, schema_editor): for smf_user in all_smf_users: try: auth_user = smf_user.user - except: + except Exception: pass else: SmfManager.update_display_name(auth_user) diff --git a/allianceauth/services/modules/smf/models.py b/allianceauth/services/modules/smf/models.py index 4e44821d..f8cd257e 100644 --- a/allianceauth/services/modules/smf/models.py +++ b/allianceauth/services/modules/smf/models.py @@ -8,10 +8,10 @@ class SmfUser(models.Model): related_name='smf') username = models.CharField(max_length=254) - def __str__(self): - return self.username - class Meta: permissions = ( ("access_smf", "Can access the SMF service"), ) + + def __str__(self) -> str: + return self.username diff --git a/allianceauth/services/modules/smf/tasks.py b/allianceauth/services/modules/smf/tasks.py index 3f6392e0..9cac03a3 100644 --- a/allianceauth/services/modules/smf/tasks.py +++ b/allianceauth/services/modules/smf/tasks.py @@ -1,11 +1,14 @@ import logging +from celery import shared_task + from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist -from celery import shared_task -from allianceauth.services.tasks import QueueOnce + from allianceauth.notifications import notify from allianceauth.services.hooks import NameFormatter +from allianceauth.services.tasks import QueueOnce + from .manager import SmfManager from .models import SmfUser @@ -42,7 +45,7 @@ class SmfTasks: @shared_task(bind=True, name="smf.update_groups", base=QueueOnce) def update_groups(self, pk): user = User.objects.get(pk=pk) - logger.debug("Updating smf groups for user %s" % user) + logger.debug(f"Updating smf groups for user {user}") if SmfTasks.has_account(user): groups = [user.profile.state.name] for group in user.groups.all(): @@ -50,10 +53,10 @@ class SmfTasks: logger.debug(f"Updating user {user} smf groups to {groups}") try: SmfManager.update_groups(user.smf.username, groups) - except: - logger.exception("smf group sync failed for %s, retrying in 10 mins" % user) + except Exception: + logger.exception(f"smf group sync failed for {user}, retrying in 10 mins") raise self.retry(countdown=60 * 10) - logger.debug("Updated user %s smf groups." % user) + logger.debug(f"Updated user {user} smf groups.") else: logger.debug("User does not have an smf account") @@ -74,7 +77,7 @@ class SmfTasks: f"SMF displayed name sync failed for {user}, " "user does not have a SMF account" ) - except: + except Exception: logger.exception( f"SMF displayed name sync failed for {user}, retrying in 10 mins" ) diff --git a/allianceauth/services/modules/smf/tests.py b/allianceauth/services/modules/smf/tests.py index b6c20895..c308959c 100644 --- a/allianceauth/services/modules/smf/tests.py +++ b/allianceauth/services/modules/smf/tests.py @@ -1,9 +1,9 @@ from unittest import mock -from django.test import TestCase, RequestFactory from django import urls -from django.contrib.auth.models import User, Group, Permission +from django.contrib.auth.models import Group, Permission, User from django.core.exceptions import ObjectDoesNotExist +from django.test import RequestFactory, TestCase from allianceauth.tests.auth_utils import AuthUtils @@ -27,7 +27,7 @@ class SmfHooksTestCase(TestCase): member = AuthUtils.create_member(self.member) SmfUser.objects.create(user=member, username=self.member) self.none_user = 'none_user' - none_user = AuthUtils.create_user(self.none_user) + AuthUtils.create_user(self.none_user) self.service = SmfService add_permissions() @@ -86,7 +86,8 @@ class SmfHooksTestCase(TestCase): service.validate_user(none_user) self.assertTrue(manager.disable_user.called) with self.assertRaises(ObjectDoesNotExist): - none_smf = User.objects.get(username=self.none_user).smf + user = User.objects.get(username=self.none_user) + _ = user.smf @mock.patch(MODULE_PATH + '.tasks.SmfManager') def test_delete_user(self, manager): @@ -98,7 +99,8 @@ class SmfHooksTestCase(TestCase): self.assertTrue(result) self.assertTrue(manager.disable_user.called) with self.assertRaises(ObjectDoesNotExist): - smf_user = User.objects.get(username=self.member).smf + user = User.objects.get(username=self.member) + _ = user.smf def test_render_services_ctrl(self): service = self.service() @@ -158,7 +160,8 @@ class SmfViewsTestCase(TestCase): self.assertTrue(manager.disable_user.called) self.assertRedirects(response, expected_url=urls.reverse('services:services'), target_status_code=200) with self.assertRaises(ObjectDoesNotExist): - smf_user = User.objects.get(pk=self.member.pk).smf + user =User.objects.get(pk=self.member.pk) + _ = user.smf @mock.patch(MODULE_PATH + '.views.SmfManager') def test_set_password(self, manager): diff --git a/allianceauth/services/modules/smf/views.py b/allianceauth/services/modules/smf/views.py index 7302b936..71460b71 100644 --- a/allianceauth/services/modules/smf/views.py +++ b/allianceauth/services/modules/smf/views.py @@ -2,7 +2,7 @@ import logging from django.contrib import messages from django.contrib.auth.decorators import login_required, permission_required -from django.shortcuts import render, redirect +from django.shortcuts import redirect, render from django.utils.translation import gettext_lazy as _ from allianceauth.services.forms import ServicePasswordForm @@ -70,14 +70,14 @@ def activate_smf(request): @login_required @permission_required(ACCESS_PERM) def deactivate_smf(request): - logger.debug("deactivate_smf called by user %s" % request.user) + logger.debug(f"deactivate_smf called by user {request.user}") result = SmfTasks.delete_user(request.user) # false we failed if result: - logger.info("Successfully deactivated SMF for user %s" % request.user) + logger.info(f"Successfully deactivated SMF for user {request.user}") messages.success(request, _('Deactivated SMF account.')) else: - logger.error("Unsuccessful attempt to activate SMF for user %s" % request.user) + logger.error(f"Unsuccessful attempt to activate SMF for user {request.user}") messages.error(request, _('An error occurred while processing your SMF account.')) return redirect("services:services") @@ -85,20 +85,20 @@ def deactivate_smf(request): @login_required @permission_required(ACCESS_PERM) def reset_smf_password(request): - logger.debug("reset_smf_password called by user %s" % request.user) + logger.debug(f"reset_smf_password called by user {request.user}") character = request.user.profile.main_character if SmfTasks.has_account(request.user) and character is not None: result = SmfManager.update_user_password(request.user.smf.username, character.character_id) # false we failed if result != "": - logger.info("Successfully reset SMF password for user %s" % request.user) + logger.info(f"Successfully reset SMF password for user {request.user}") messages.success(request, _('Reset SMF password.')) credentials = { 'username': request.user.smf.username, 'password': result, } return render(request, 'services/service_credentials.html', context={'credentials': credentials, 'service': 'SMF'}) - logger.error("Unsuccessful attempt to reset SMF password for user %s" % request.user) + logger.error(f"Unsuccessful attempt to reset SMF password for user {request.user}") messages.error(request, _('An error occurred while processing your SMF account.')) return redirect("services:services") @@ -106,27 +106,27 @@ def reset_smf_password(request): @login_required @permission_required(ACCESS_PERM) def set_smf_password(request): - logger.debug("set_smf_password called by user %s" % request.user) + logger.debug(f"set_smf_password called by user {request.user}") if request.method == 'POST': logger.debug("Received POST request with form.") form = ServicePasswordForm(request.POST) - logger.debug("Form is valid: %s" % form.is_valid()) + logger.debug(f"Form is valid: {form.is_valid()}") character = request.user.profile.main_character if form.is_valid() and SmfTasks.has_account(request.user) and character is not None: password = form.cleaned_data['password'] - logger.debug("Form contains password of length %s" % len(password)) + logger.debug(f"Form contains password of length {len(password)}") result = SmfManager.update_user_password(request.user.smf.username, character.character_id, password=password) if result != "": - logger.info("Successfully set SMF password for user %s" % request.user) + logger.info(f"Successfully set SMF password for user {request.user}") messages.success(request, _('Set SMF password.')) else: - logger.error("Failed to install custom SMF password for user %s" % request.user) + logger.error(f"Failed to install custom SMF password for user {request.user}") messages.error(request, _('An error occurred while processing your SMF account.')) return redirect("services:services") else: logger.debug("Request is not type POST - providing empty form.") form = ServicePasswordForm() - logger.debug("Rendering form for user %s" % request.user) + logger.debug(f"Rendering form for user {request.user}") context = {'form': form, 'service': 'SMF'} return render(request, 'services/service_password.html', context=context) diff --git a/allianceauth/services/modules/teamspeak3/admin.py b/allianceauth/services/modules/teamspeak3/admin.py index 92a1fcfe..c00a7604 100644 --- a/allianceauth/services/modules/teamspeak3/admin.py +++ b/allianceauth/services/modules/teamspeak3/admin.py @@ -1,9 +1,11 @@ from django.contrib import admin from django.contrib.auth.models import Group -from .models import AuthTS, Teamspeak3User, StateGroup, TSgroup -from ...admin import ServicesUserAdmin + from allianceauth.groupmanagement.models import ReservedGroupName +from ...admin import ServicesUserAdmin +from .models import AuthTS, StateGroup, Teamspeak3User, TSgroup + @admin.register(Teamspeak3User) class Teamspeak3UserAdmin(ServicesUserAdmin): @@ -40,7 +42,7 @@ class AuthTSgroupAdmin(admin.ModelAdmin): description='ts groups' ) def _ts_group(self, obj): - return [x for x in obj.ts_group.all().order_by('ts_group_id')] + return list(obj.ts_group.all().order_by('ts_group_id')) # _ts_group.admin_order_field = 'profile__state' diff --git a/allianceauth/services/modules/teamspeak3/apps.py b/allianceauth/services/modules/teamspeak3/apps.py index f46e3c92..693dec3a 100644 --- a/allianceauth/services/modules/teamspeak3/apps.py +++ b/allianceauth/services/modules/teamspeak3/apps.py @@ -6,4 +6,4 @@ class Teamspeak3ServiceConfig(AppConfig): label = 'teamspeak3' def ready(self): - from . import signals + pass diff --git a/allianceauth/services/modules/teamspeak3/auth_hooks.py b/allianceauth/services/modules/teamspeak3/auth_hooks.py index 20e82326..5c818d86 100644 --- a/allianceauth/services/modules/teamspeak3/auth_hooks.py +++ b/allianceauth/services/modules/teamspeak3/auth_hooks.py @@ -1,10 +1,11 @@ import logging -from django.template.loader import render_to_string from django.conf import settings +from django.template.loader import render_to_string from allianceauth import hooks from allianceauth.services.hooks import ServicesHook + from .tasks import Teamspeak3Tasks from .urls import urlpatterns @@ -34,7 +35,7 @@ class Teamspeak3Service(ServicesHook): self.delete_user(user, notify_user=True) def update_all_groups(self): - logger.debug('Update all %s groups called' % self.name) + logger.debug(f'Update all {self.name} groups called') Teamspeak3Tasks.update_all_groups.delay() def service_active_for_user(self, user): diff --git a/allianceauth/services/modules/teamspeak3/manager.py b/allianceauth/services/modules/teamspeak3/manager.py index 519a8a47..9d5c7b22 100644 --- a/allianceauth/services/modules/teamspeak3/manager.py +++ b/allianceauth/services/modules/teamspeak3/manager.py @@ -2,10 +2,11 @@ import logging from django.conf import settings -from .util.ts3 import TS3Server, TeamspeakError -from .models import TSgroup from allianceauth.groupmanagement.models import ReservedGroupName +from .models import TSgroup +from .util.ts3 import TeamspeakError, TS3Server + logger = logging.getLogger(__name__) @@ -52,7 +53,7 @@ class Teamspeak3Manager: return sanatized def _get_userid(self, uid): - logger.debug("Looking for uid %s on TS3 server." % uid) + logger.debug(f"Looking for uid {uid} on TS3 server.") try: ret = self.server.send_command('customsearch', {'ident': 'sso_uid', 'pattern': uid}) if ret and 'keys' in ret and 'cldbid' in ret['keys']: @@ -64,21 +65,21 @@ class Teamspeak3Manager: return None def _group_id_by_name(self, groupname): - logger.debug("Looking for group %s on TS3 server." % groupname) + logger.debug(f"Looking for group {groupname} on TS3 server.") group_cache = self.server.send_command('servergrouplist') - logger.debug("Received group cache from server: %s" % group_cache) + logger.debug(f"Received group cache from server: {group_cache}") for group in group_cache: if group['keys']['type'] != '1': continue - logger.debug("Checking group %s" % group) + logger.debug(f"Checking group {group}") if group['keys']['name'] == groupname: logger.debug("Found group {}, returning id {}".format(groupname, group['keys']['sgid'])) return group['keys']['sgid'] - logger.debug("Group %s not found on server." % groupname) + logger.debug(f"Group {groupname} not found on server.") return None def _create_group(self, groupname): - logger.debug("Creating group %s on TS3 server." % groupname) + logger.debug(f"Creating group {groupname} on TS3 server.") sgid = self._group_id_by_name(groupname) if not sgid: logger.debug("Group does not yet exist. Proceeding with creation.") @@ -98,8 +99,8 @@ class Teamspeak3Manager: return sgid def _user_group_list(self, cldbid): - logger.debug("Retrieving group list for user with id %s" % cldbid) - server = Teamspeak3Manager.__get_created_server() + logger.debug(f"Retrieving group list for user with id {cldbid}") + Teamspeak3Manager.__get_created_server() try: groups = self.server.send_command('servergroupsbyclientid', {'cldbid': cldbid}) except TeamspeakError as e: @@ -107,23 +108,23 @@ class Teamspeak3Manager: groups = [] else: raise e - logger.debug("Retrieved group list: %s" % groups) + logger.debug(f"Retrieved group list: {groups}") outlist = {} - if type(groups) == list: + if type(groups) is list: logger.debug("Recieved multiple groups. Iterating.") for group in groups: outlist[group['keys']['name']] = group['keys']['sgid'] - elif type(groups) == dict: + elif type(groups) is dict: logger.debug("Recieved single group.") outlist[groups['keys']['name']] = groups['keys']['sgid'] - logger.debug("Returning name/id pairing: %s" % outlist) + logger.debug(f"Returning name/id pairing: {outlist}") return outlist def _group_list(self): logger.debug("Retrieving group list on TS3 server.") group_cache = self.server.send_command('servergrouplist') - logger.debug("Received group cache from server: %s" % group_cache) + logger.debug(f"Received group cache from server: {group_cache}") outlist = {} if group_cache: for group in group_cache: @@ -133,7 +134,7 @@ class Teamspeak3Manager: outlist[group['keys']['name']] = group['keys']['sgid'] else: logger.error("Received empty group cache while retrieving group cache from TS3 server. 1024 error.") - logger.debug("Returning name/id pairing: %s" % outlist) + logger.debug(f"Returning name/id pairing: {outlist}") return outlist def _add_user_to_group(self, uid, groupid): @@ -175,11 +176,11 @@ class Teamspeak3Manager: except TeamspeakError as e: logger.error(f"Error occurred while syncing TS group db: {str(e)}") except Exception: - logger.exception(f"An unhandled exception has occurred while syncing TS groups.") + logger.exception("An unhandled exception has occurred while syncing TS groups.") def add_user(self, user, fmt_name): username_clean = self.__santatize_username(fmt_name[:30]) - logger.debug("Adding user to TS3 server with cleaned username %s" % username_clean) + logger.debug(f"Adding user to TS3 server with cleaned username {username_clean}") server_groups = self._group_list() state = user.profile.state.name @@ -191,16 +192,16 @@ class Teamspeak3Manager: try: ret = self.server.send_command('tokenadd', {'tokentype': 0, 'tokenid1': state_group_id, 'tokenid2': 0, 'tokendescription': username_clean, - 'tokencustomset': "ident=sso_uid value=%s" % username_clean}) + 'tokencustomset': f"ident=sso_uid value={username_clean}"}) except TeamspeakError as e: logger.error(f"Failed to add teamspeak user {username_clean}: {str(e)}") return "","" try: token = ret['keys']['token'] - logger.info("Created permission token for user %s on TS3 server" % username_clean) + logger.info(f"Created permission token for user {username_clean} on TS3 server") return username_clean, token - except: + except Exception: logger.exception(f"Failed to add teamspeak user {username_clean} - received response: {ret}") return "", "" @@ -216,10 +217,10 @@ class Teamspeak3Manager: for client in clients: try: if client['keys']['client_database_id'] == user: - logger.debug("Found user %s on TS3 server - issuing deletion command." % user) + logger.debug(f"Found user {user} on TS3 server - issuing deletion command.") self.server.send_command('clientkick', {'clid': client['keys']['clid'], 'reasonid': 5, 'reasonmsg': 'Auth service deleted'}) - except: + except Exception: logger.exception(f"Failed to delete user id {uid} from TS3 - received response {client}") return False try: @@ -228,13 +229,13 @@ class Teamspeak3Manager: logger.error(f"Failed to delete teamspeak user {uid}: {str(e)}") return False if ret == '0': - logger.info("Deleted user with id %s from TS3 server." % uid) + logger.info(f"Deleted user with id {uid} from TS3 server.") return True else: logger.exception(f"Failed to delete user id {uid} from TS3 - received response {ret}") return False else: - logger.warning("User with id %s not found on TS3 server. Assuming succesful deletion." % uid) + logger.warning(f"User with id {uid} not found on TS3 server. Assuming succesful deletion.") return True def check_user_exists(self, uid): @@ -244,7 +245,7 @@ class Teamspeak3Manager: return False def generate_new_permissionkey(self, uid, user, username): - logger.debug("Re-issuing permission key for user id %s" % uid) + logger.debug(f"Re-issuing permission key for user id {uid}") self.delete_user(uid) return self.add_user(user, username) @@ -255,11 +256,11 @@ class Teamspeak3Manager: remgroups = [] if userid is not None: user_ts_groups = self._user_group_list(userid) - logger.debug("User has groups on TS3 server: %s" % user_ts_groups) + logger.debug(f"User has groups on TS3 server: {user_ts_groups}") for key in user_ts_groups: user_ts_groups[key] = int(user_ts_groups[key]) for ts_group_key in ts_groups: - logger.debug("Checking if user has group %s on TS3 server." % ts_group_key) + logger.debug(f"Checking if user has group {ts_group_key} on TS3 server.") if ts_groups[ts_group_key] not in user_ts_groups.values(): addgroups.append(ts_groups[ts_group_key]) for user_ts_group_key in user_ts_groups: diff --git a/allianceauth/services/modules/teamspeak3/migrations/0001_initial.py b/allianceauth/services/modules/teamspeak3/migrations/0001_initial.py index 3f22e872..d2211c4c 100644 --- a/allianceauth/services/modules/teamspeak3/migrations/0001_initial.py +++ b/allianceauth/services/modules/teamspeak3/migrations/0001_initial.py @@ -1,8 +1,8 @@ # Generated by Django 1.10.2 on 2016-12-12 01:11 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/services/modules/teamspeak3/migrations/0003_teamspeak3user.py b/allianceauth/services/modules/teamspeak3/migrations/0003_teamspeak3user.py index dbe71b6c..382f8d13 100644 --- a/allianceauth/services/modules/teamspeak3/migrations/0003_teamspeak3user.py +++ b/allianceauth/services/modules/teamspeak3/migrations/0003_teamspeak3user.py @@ -1,8 +1,8 @@ # Generated by Django 1.10.2 on 2016-12-12 03:14 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/services/modules/teamspeak3/migrations/0004_service_permissions.py b/allianceauth/services/modules/teamspeak3/migrations/0004_service_permissions.py index 4023cbff..779efad8 100644 --- a/allianceauth/services/modules/teamspeak3/migrations/0004_service_permissions.py +++ b/allianceauth/services/modules/teamspeak3/migrations/0004_service_permissions.py @@ -1,12 +1,12 @@ # Generated by Django 1.10.5 on 2017-02-02 05:59 -from django.db import migrations -from django.conf import settings -from django.core.exceptions import ObjectDoesNotExist -from django.contrib.auth.management import create_permissions - import logging +from django.conf import settings +from django.contrib.auth.management import create_permissions +from django.core.exceptions import ObjectDoesNotExist +from django.db import migrations + logger = logging.getLogger(__name__) diff --git a/allianceauth/services/modules/teamspeak3/migrations/0005_stategroup.py b/allianceauth/services/modules/teamspeak3/migrations/0005_stategroup.py index 0cd994eb..6c043f68 100644 --- a/allianceauth/services/modules/teamspeak3/migrations/0005_stategroup.py +++ b/allianceauth/services/modules/teamspeak3/migrations/0005_stategroup.py @@ -1,7 +1,7 @@ # Generated by Django 1.11.10 on 2018-02-23 06:13 -from django.db import migrations, models import django.db.models.deletion +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/allianceauth/services/modules/teamspeak3/models.py b/allianceauth/services/modules/teamspeak3/models.py index 5569a35c..2cba2e06 100644 --- a/allianceauth/services/modules/teamspeak3/models.py +++ b/allianceauth/services/modules/teamspeak3/models.py @@ -1,5 +1,6 @@ +from django.contrib.auth.models import Group, User from django.db import models -from django.contrib.auth.models import User, Group + from allianceauth.authentication.models import State @@ -11,14 +12,13 @@ class Teamspeak3User(models.Model): uid = models.CharField(max_length=254) perm_key = models.CharField(max_length=254) - def __str__(self): - return self.uid - class Meta: permissions = ( ("access_teamspeak3", "Can access the Teamspeak3 service"), ) + def __str__(self): + return self.uid class TSgroup(models.Model): ts_group_id = models.IntegerField(primary_key=True) @@ -56,3 +56,6 @@ class UserTSgroup(models.Model): class StateGroup(models.Model): state = models.ForeignKey(State, on_delete=models.CASCADE) ts_group = models.ForeignKey(TSgroup, on_delete=models.CASCADE) + + def __str__(self): + return self.pk diff --git a/allianceauth/services/modules/teamspeak3/signals.py b/allianceauth/services/modules/teamspeak3/signals.py index 59054d10..bef0329d 100644 --- a/allianceauth/services/modules/teamspeak3/signals.py +++ b/allianceauth/services/modules/teamspeak3/signals.py @@ -1,13 +1,13 @@ import logging from django.db import transaction -from django.db.models.signals import m2m_changed -from django.db.models.signals import post_delete -from django.db.models.signals import post_save +from django.db.models.signals import m2m_changed, post_delete, post_save from django.dispatch import receiver + from allianceauth.authentication.signals import state_changed -from .tasks import Teamspeak3Tasks + from .models import AuthTS, StateGroup +from .tasks import Teamspeak3Tasks logger = logging.getLogger(__name__) @@ -26,13 +26,13 @@ def m2m_changed_authts_group(sender, instance, action, *args, **kwargs): @receiver(post_save, sender=AuthTS) def post_save_authts(sender, instance, *args, **kwargs): - logger.debug("Received post_save from %s" % instance) + logger.debug(f"Received post_save from {instance}") transaction.on_commit(trigger_all_ts_update) @receiver(post_delete, sender=AuthTS) def post_delete_authts(sender, instance, *args, **kwargs): - logger.debug("Received post_delete signal from %s" % instance) + logger.debug(f"Received post_delete signal from {instance}") transaction.on_commit(trigger_all_ts_update) diff --git a/allianceauth/services/modules/teamspeak3/tasks.py b/allianceauth/services/modules/teamspeak3/tasks.py index c65e123d..61b0792f 100644 --- a/allianceauth/services/modules/teamspeak3/tasks.py +++ b/allianceauth/services/modules/teamspeak3/tasks.py @@ -1,13 +1,16 @@ import logging +from celery import shared_task + from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist -from celery import shared_task -from allianceauth.services.tasks import QueueOnce + from allianceauth.notifications import notify from allianceauth.services.hooks import NameFormatter +from allianceauth.services.tasks import QueueOnce + from .manager import Teamspeak3Manager -from .models import AuthTS, TSgroup, UserTSgroup, Teamspeak3User +from .models import AuthTS, Teamspeak3User, TSgroup, UserTSgroup from .util.ts3 import TeamspeakError logger = logging.getLogger(__name__) @@ -59,7 +62,7 @@ class Teamspeak3Tasks: @shared_task(bind=True, name="teamspeak3.update_groups", base=QueueOnce) def update_groups(self, pk): user = User.objects.get(pk=pk) - logger.debug("Updating user %s teamspeak3 groups" % user) + logger.debug(f"Updating user {user} teamspeak3 groups") if Teamspeak3Tasks.has_account(user): usergroups = user.groups.all() groups = {} @@ -75,7 +78,7 @@ class Teamspeak3Tasks: try: with Teamspeak3Manager() as ts3man: ts3man.update_groups(user.teamspeak3.uid, groups) - logger.debug("Updated user %s teamspeak3 groups." % user) + logger.debug(f"Updated user {user} teamspeak3 groups.") except TeamspeakError as e: logger.error(f"Error occured while syncing TS groups for {user}: {str(e)}") raise self.retry(countdown=60*10) diff --git a/allianceauth/services/modules/teamspeak3/tests.py b/allianceauth/services/modules/teamspeak3/tests.py index 62f9ad85..d6deb2ca 100644 --- a/allianceauth/services/modules/teamspeak3/tests.py +++ b/allianceauth/services/modules/teamspeak3/tests.py @@ -1,22 +1,22 @@ from unittest import mock -from django.test import TestCase, RequestFactory from django import urls -from django.contrib.auth.models import User, Group, Permission +from django.contrib.admin import AdminSite +from django.contrib.auth.models import Group, Permission, User from django.core.exceptions import ObjectDoesNotExist from django.db.models import signals -from django.contrib.admin import AdminSite +from django.test import RequestFactory, TestCase -from allianceauth.tests.auth_utils import AuthUtils -from .auth_hooks import Teamspeak3Service -from .models import Teamspeak3User, AuthTS, TSgroup, StateGroup -from .tasks import Teamspeak3Tasks -from .signals import m2m_changed_authts_group, post_save_authts, post_delete_authts -from .admin import AuthTSgroupAdmin - -from .manager import Teamspeak3Manager -from .util.ts3 import TeamspeakError from allianceauth.groupmanagement.models import ReservedGroupName +from allianceauth.tests.auth_utils import AuthUtils + +from .admin import AuthTSgroupAdmin +from .auth_hooks import Teamspeak3Service +from .manager import Teamspeak3Manager +from .models import AuthTS, StateGroup, Teamspeak3User, TSgroup +from .signals import m2m_changed_authts_group, post_delete_authts, post_save_authts +from .tasks import Teamspeak3Tasks +from .util.ts3 import TeamspeakError MODULE_PATH = 'allianceauth.services.modules.teamspeak3' DEFAULT_AUTH_GROUP = 'Member' @@ -31,7 +31,7 @@ def add_permissions(): class Teamspeak3HooksTestCase(TestCase): def setUp(self): # Inert signals before setup begins - with mock.patch(MODULE_PATH + '.signals.trigger_all_ts_update') as trigger_all_ts_update: + with mock.patch(MODULE_PATH + '.signals.trigger_all_ts_update'): self.member = 'member_user' member = AuthUtils.create_member(self.member) Teamspeak3User.objects.create(user=member, uid=self.member, perm_key='123ABC') @@ -104,7 +104,7 @@ class Teamspeak3HooksTestCase(TestCase): service.validate_user(none_user) self.assertTrue(manager.return_value.__enter__.return_value.delete_user.called) with self.assertRaises(ObjectDoesNotExist): - none_teamspeak3 = User.objects.get(username=self.none_user).teamspeak3 + _ = User.objects.get(username=self.none_user).teamspeak3 @mock.patch(MODULE_PATH + '.tasks.Teamspeak3Manager') def test_delete_user(self, manager): @@ -116,7 +116,8 @@ class Teamspeak3HooksTestCase(TestCase): self.assertTrue(result) self.assertTrue(manager.return_value.__enter__.return_value.delete_user.called) with self.assertRaises(ObjectDoesNotExist): - teamspeak3_user = User.objects.get(username=self.member).teamspeak3 + _ = User.objects.get(username=self.member) + def test_render_services_ctrl(self): service = self.service() @@ -140,7 +141,7 @@ class Teamspeak3HooksTestCase(TestCase): class Teamspeak3ViewsTestCase(TestCase): def setUp(self): # Inert signals before setup begins - with mock.patch(MODULE_PATH + '.signals.trigger_all_ts_update') as trigger_all_ts_update: + with mock.patch(MODULE_PATH + '.signals.trigger_all_ts_update'): self.member = AuthUtils.create_member('auth_member') self.member.email = 'auth_member@example.com' self.member.save() @@ -177,7 +178,6 @@ class Teamspeak3ViewsTestCase(TestCase): @mock.patch(MODULE_PATH + '.tasks.Teamspeak3Manager') def test_verify_submit(self, manager, forms_manager): self.login() - expected_username = 'auth_member' forms_instance = manager.return_value.__enter__.return_value forms_instance._get_userid.return_value = '1234' @@ -200,7 +200,8 @@ class Teamspeak3ViewsTestCase(TestCase): self.assertTrue(manager.return_value.__enter__.return_value.delete_user.called) self.assertRedirects(response, expected_url=urls.reverse('services:services'), target_status_code=200) with self.assertRaises(ObjectDoesNotExist): - teamspeak3_user = User.objects.get(pk=self.member.pk).teamspeak3 + user = User.objects.get(pk=self.member.pk) + _ = user.teamspeak3 @mock.patch(MODULE_PATH + '.tasks.Teamspeak3Manager') @mock.patch(MODULE_PATH + '.views.Teamspeak3Manager') @@ -242,7 +243,7 @@ class Teamspeak3SignalsTestCase(TestCase): self.member = AuthUtils.create_member('auth_member') # Suppress signals action while setting up - with mock.patch(MODULE_PATH + '.signals.trigger_all_ts_update') as trigger_all_ts_update: + with mock.patch(MODULE_PATH + '.signals.trigger_all_ts_update'): ts_member_group = TSgroup.objects.create(ts_group_id=1, ts_group_name='Member') self.m2m_member = AuthTS.objects.create(auth_group=Group.objects.get(name='Member')) self.m2m_member.ts_group.add(ts_member_group) diff --git a/allianceauth/services/modules/teamspeak3/util/ts3.py b/allianceauth/services/modules/teamspeak3/util/ts3.py index 81ae74a6..358a1b58 100644 --- a/allianceauth/services/modules/teamspeak3/util/ts3.py +++ b/allianceauth/services/modules/teamspeak3/util/ts3.py @@ -1,5 +1,5 @@ -import telnetlib import logging +import telnetlib class ConnectionError: @@ -40,7 +40,7 @@ class TS3Proto: try: self._conn = telnetlib.Telnet(host=ip, port=port, timeout=5) self._connected = True - except: + except Exception: # raise ConnectionError(ip, port) raise @@ -55,7 +55,7 @@ class TS3Proto: try: self.send("quit") self._conn.close() - except: + except Exception: self._log.exception('Error while disconnecting') self._connected = False self._log.info('Disconnected') @@ -69,7 +69,7 @@ class TS3Proto: self._conn.read_very_eager() # Send command - self.send('%s\n' % cmd) + self.send(f'{cmd}\n') data = [] @@ -130,7 +130,7 @@ class TS3Proto: # Add in options if opts: for opt in opts: - cstr.append("-%s" % opt) + cstr.append(f"-{opt}") return " ".join(cstr) @@ -205,7 +205,7 @@ class TS3Proto: def send(self, payload): if self._connected: - self._log.debug('Sent: %s' % payload) + self._log.debug(f'Sent: {payload}') self._conn.write(payload.encode('utf-8')) diff --git a/allianceauth/services/modules/teamspeak3/views.py b/allianceauth/services/modules/teamspeak3/views.py index be6d7cd3..1b4bd833 100644 --- a/allianceauth/services/modules/teamspeak3/views.py +++ b/allianceauth/services/modules/teamspeak3/views.py @@ -1,14 +1,14 @@ import logging +from django.conf import settings from django.contrib import messages from django.contrib.admin.views.decorators import staff_member_required from django.contrib.auth.decorators import login_required, permission_required -from django.shortcuts import render, redirect -from django.conf import settings +from django.shortcuts import redirect, render from django.utils.translation import gettext_lazy as _ -from .manager import Teamspeak3Manager from .forms import TeamspeakJoinForm +from .manager import Teamspeak3Manager from .models import Teamspeak3User from .tasks import Teamspeak3Tasks @@ -20,7 +20,7 @@ ACCESS_PERM = 'teamspeak3.access_teamspeak3' @login_required @permission_required(ACCESS_PERM) def activate_teamspeak3(request): - logger.debug("activate_teamspeak3 called by user %s" % request.user) + logger.debug(f"activate_teamspeak3 called by user {request.user}") character = request.user.profile.main_character with Teamspeak3Manager() as ts3man: @@ -30,11 +30,11 @@ def activate_teamspeak3(request): # if its empty we failed if result[0] != "": Teamspeak3User.objects.update_or_create(user=request.user, defaults={'uid': result[0], 'perm_key': result[1]}) - logger.debug("Updated authserviceinfo for user %s with TeamSpeak3 credentials. Updating groups." % request.user) - logger.info("Successfully activated TeamSpeak3 for user %s" % request.user) + logger.debug(f"Updated authserviceinfo for user {request.user} with TeamSpeak3 credentials. Updating groups.") + logger.info(f"Successfully activated TeamSpeak3 for user {request.user}") messages.success(request, _('Activated TeamSpeak3 account.')) return redirect("teamspeak3:verify") - logger.error("Unsuccessful attempt to activate TeamSpeak3 for user %s" % request.user) + logger.error(f"Unsuccessful attempt to activate TeamSpeak3 for user {request.user}") messages.error(request, _('An error occurred while processing your TeamSpeak3 account.')) return redirect("services:services") @@ -42,15 +42,15 @@ def activate_teamspeak3(request): @login_required @permission_required(ACCESS_PERM) def verify_teamspeak3(request): - logger.debug("verify_teamspeak3 called by user %s" % request.user) + logger.debug(f"verify_teamspeak3 called by user {request.user}") if not Teamspeak3Tasks.has_account(request.user): - logger.warning("Unable to validate user %s teamspeak: no teamspeak data" % request.user) + logger.warning(f"Unable to validate user {request.user} teamspeak: no teamspeak data") return redirect("services:services") if request.method == "POST": form = TeamspeakJoinForm(request.POST) if form.is_valid(): Teamspeak3Tasks.update_groups.delay(request.user.pk) - logger.debug("Validated user %s joined TS server" % request.user) + logger.debug(f"Validated user {request.user} joined TS server") return redirect("services:services") else: form = TeamspeakJoinForm(initial={'username': request.user.teamspeak3.uid}) @@ -65,12 +65,12 @@ def verify_teamspeak3(request): @login_required @permission_required(ACCESS_PERM) def deactivate_teamspeak3(request): - logger.debug("deactivate_teamspeak3 called by user %s" % request.user) + logger.debug(f"deactivate_teamspeak3 called by user {request.user}") if Teamspeak3Tasks.has_account(request.user) and Teamspeak3Tasks.delete_user(request.user): - logger.info("Successfully deactivated TeamSpeak3 for user %s" % request.user) + logger.info(f"Successfully deactivated TeamSpeak3 for user {request.user}") messages.success(request, _('Deactivated TeamSpeak3 account.')) else: - logger.error("Unsuccessful attempt to deactivate TeamSpeak3 for user %s" % request.user) + logger.error(f"Unsuccessful attempt to deactivate TeamSpeak3 for user {request.user}") messages.error(request, _('An error occurred while processing your TeamSpeak3 account.')) return redirect("services:services") @@ -78,25 +78,25 @@ def deactivate_teamspeak3(request): @login_required @permission_required(ACCESS_PERM) def reset_teamspeak3_perm(request): - logger.debug("reset_teamspeak3_perm called by user %s" % request.user) + logger.debug(f"reset_teamspeak3_perm called by user {request.user}") if not Teamspeak3Tasks.has_account(request.user): return redirect("services:services") - logger.debug("Deleting TeamSpeak3 user for user %s" % request.user) + logger.debug(f"Deleting TeamSpeak3 user for user {request.user}") with Teamspeak3Manager() as ts3man: ts3man.delete_user(request.user.teamspeak3.uid) - logger.debug("Generating new permission key for user %s" % request.user) + logger.debug(f"Generating new permission key for user {request.user}") result = ts3man.generate_new_permissionkey(request.user.teamspeak3.uid, request.user, Teamspeak3Tasks.get_username(request.user)) # if blank we failed if result[0] != "": Teamspeak3User.objects.update_or_create(user=request.user, defaults={'uid': result[0], 'perm_key': result[1]}) - logger.debug("Updated authserviceinfo for user %s with TeamSpeak3 credentials. Updating groups." % request.user) + logger.debug(f"Updated authserviceinfo for user {request.user} with TeamSpeak3 credentials. Updating groups.") Teamspeak3Tasks.update_groups.delay(request.user.pk) - logger.info("Successfully reset TeamSpeak3 permission key for user %s" % request.user) + logger.info(f"Successfully reset TeamSpeak3 permission key for user {request.user}") messages.success(request, _('Reset TeamSpeak3 permission key.')) else: - logger.error("Unsuccessful attempt to reset TeamSpeak3 permission key for user %s" % request.user) + logger.error(f"Unsuccessful attempt to reset TeamSpeak3 permission key for user {request.user}") messages.error(request, _('An error occurred while processing your TeamSpeak3 account.')) return redirect("services:services") diff --git a/allianceauth/services/modules/xenforo/admin.py b/allianceauth/services/modules/xenforo/admin.py index 20ccbd7e..cdd134dd 100644 --- a/allianceauth/services/modules/xenforo/admin.py +++ b/allianceauth/services/modules/xenforo/admin.py @@ -1,7 +1,7 @@ from django.contrib import admin -from .models import XenforoUser from ...admin import ServicesUserAdmin +from .models import XenforoUser @admin.register(XenforoUser) diff --git a/allianceauth/services/modules/xenforo/auth_hooks.py b/allianceauth/services/modules/xenforo/auth_hooks.py index 0faa23ac..add23b08 100644 --- a/allianceauth/services/modules/xenforo/auth_hooks.py +++ b/allianceauth/services/modules/xenforo/auth_hooks.py @@ -4,6 +4,7 @@ from django.template.loader import render_to_string from allianceauth import hooks from allianceauth.services.hooks import ServicesHook + from .tasks import XenforoTasks from .urls import urlpatterns diff --git a/allianceauth/services/modules/xenforo/manager.py b/allianceauth/services/modules/xenforo/manager.py index 82e7018f..5c58d493 100644 --- a/allianceauth/services/modules/xenforo/manager.py +++ b/allianceauth/services/modules/xenforo/manager.py @@ -1,12 +1,12 @@ +import json +import logging import random import string + import requests -import json from django.conf import settings -import logging - logger = logging.getLogger(__name__) diff --git a/allianceauth/services/modules/xenforo/migrations/0001_initial.py b/allianceauth/services/modules/xenforo/migrations/0001_initial.py index 7bb8dce7..a86d12f4 100644 --- a/allianceauth/services/modules/xenforo/migrations/0001_initial.py +++ b/allianceauth/services/modules/xenforo/migrations/0001_initial.py @@ -1,8 +1,8 @@ # Generated by Django 1.10.2 on 2016-12-12 03:14 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/services/modules/xenforo/migrations/0002_service_permissions.py b/allianceauth/services/modules/xenforo/migrations/0002_service_permissions.py index 4bc03a4a..7bee799b 100644 --- a/allianceauth/services/modules/xenforo/migrations/0002_service_permissions.py +++ b/allianceauth/services/modules/xenforo/migrations/0002_service_permissions.py @@ -1,12 +1,12 @@ # Generated by Django 1.10.5 on 2017-02-02 05:59 -from django.db import migrations -from django.conf import settings -from django.core.exceptions import ObjectDoesNotExist -from django.contrib.auth.management import create_permissions - import logging +from django.conf import settings +from django.contrib.auth.management import create_permissions +from django.core.exceptions import ObjectDoesNotExist +from django.db import migrations + logger = logging.getLogger(__name__) diff --git a/allianceauth/services/modules/xenforo/models.py b/allianceauth/services/modules/xenforo/models.py index fb326d25..8b7ce337 100644 --- a/allianceauth/services/modules/xenforo/models.py +++ b/allianceauth/services/modules/xenforo/models.py @@ -8,10 +8,11 @@ class XenforoUser(models.Model): related_name='xenforo') username = models.CharField(max_length=254) - def __str__(self): - return self.username class Meta: permissions = ( ("access_xenforo", "Can access the XenForo service"), ) + + def __str__(self): + return self.username diff --git a/allianceauth/services/modules/xenforo/tasks.py b/allianceauth/services/modules/xenforo/tasks.py index 78c7748d..5e349f21 100644 --- a/allianceauth/services/modules/xenforo/tasks.py +++ b/allianceauth/services/modules/xenforo/tasks.py @@ -4,6 +4,7 @@ from django.core.exceptions import ObjectDoesNotExist from allianceauth.notifications import notify from allianceauth.services.hooks import NameFormatter + from .manager import XenForoManager from .models import XenforoUser diff --git a/allianceauth/services/modules/xenforo/tests.py b/allianceauth/services/modules/xenforo/tests.py index 5b68f46d..023af261 100644 --- a/allianceauth/services/modules/xenforo/tests.py +++ b/allianceauth/services/modules/xenforo/tests.py @@ -1,9 +1,9 @@ from unittest import mock -from django.test import TestCase, RequestFactory from django import urls -from django.contrib.auth.models import User, Group, Permission +from django.contrib.auth.models import Group, Permission, User from django.core.exceptions import ObjectDoesNotExist +from django.test import RequestFactory, TestCase from allianceauth.tests.auth_utils import AuthUtils @@ -27,7 +27,7 @@ class XenforoHooksTestCase(TestCase): member = AuthUtils.create_member(self.member) XenforoUser.objects.create(user=member, username=self.member) self.none_user = 'none_user' - none_user = AuthUtils.create_user(self.none_user) + AuthUtils.create_user(self.none_user) self.service = XenforoService add_permissions() @@ -61,7 +61,7 @@ class XenforoHooksTestCase(TestCase): service.validate_user(none_user) self.assertTrue(manager.disable_user.called) with self.assertRaises(ObjectDoesNotExist): - none_xenforo = User.objects.get(username=self.none_user).xenforo + _ = User.objects.get(username=self.none_user).xenforo @mock.patch(MODULE_PATH + '.tasks.XenForoManager') def test_delete_user(self, manager): @@ -74,7 +74,7 @@ class XenforoHooksTestCase(TestCase): self.assertTrue(result) self.assertTrue(manager.disable_user.called) with self.assertRaises(ObjectDoesNotExist): - xenforo_user = User.objects.get(username=self.member).xenforo + _ = User.objects.get(username=self.member).xenforo def test_render_services_ctrl(self): service = self.service() @@ -139,7 +139,8 @@ class XenforoViewsTestCase(TestCase): self.assertTrue(manager.disable_user.called) self.assertRedirects(response, expected_url=urls.reverse('services:services'), target_status_code=200) with self.assertRaises(ObjectDoesNotExist): - xenforo_user = User.objects.get(pk=self.member.pk).xenforo + user = User.objects.get(username=self.member.pk) + _ = user.xenoforo @mock.patch(MODULE_PATH + '.views.XenForoManager') def test_set_password(self, manager): diff --git a/allianceauth/services/modules/xenforo/views.py b/allianceauth/services/modules/xenforo/views.py index ac121108..1286e401 100644 --- a/allianceauth/services/modules/xenforo/views.py +++ b/allianceauth/services/modules/xenforo/views.py @@ -2,7 +2,7 @@ import logging from django.contrib import messages from django.contrib.auth.decorators import login_required, permission_required -from django.shortcuts import render, redirect +from django.shortcuts import redirect, render from django.utils.translation import gettext_lazy as _ from allianceauth.services.forms import ServicePasswordForm @@ -19,14 +19,14 @@ ACCESS_PERM = 'xenforo.access_xenforo' @login_required @permission_required(ACCESS_PERM) def activate_xenforo_forum(request): - logger.debug("activate_xenforo_forum called by user %s" % request.user) + logger.debug(f"activate_xenforo_forum called by user {request.user}") character = request.user.profile.main_character logger.debug(f"Adding XenForo user for user {request.user} with main character {character}") result = XenForoManager.add_user(XenforoTasks.get_username(request.user), request.user.email) # Based on XenAPI's response codes if result['response']['status_code'] == 200: XenforoUser.objects.update_or_create(user=request.user, defaults={'username': result['username']}) - logger.info("Updated user %s with XenForo credentials. Updating groups." % request.user) + logger.info(f"Updated user {request.user} with XenForo credentials. Updating groups.") messages.success(request, _('Activated XenForo account.')) credentials = { 'username': result['username'], @@ -36,7 +36,7 @@ def activate_xenforo_forum(request): context={'credentials': credentials, 'service': 'XenForo'}) else: - logger.error("Unsuccessful attempt to activate XenForo for user %s" % request.user) + logger.error(f"Unsuccessful attempt to activate XenForo for user {request.user}") messages.error(request, _('An error occurred while processing your XenForo account.')) return redirect("services:services") @@ -44,9 +44,9 @@ def activate_xenforo_forum(request): @login_required @permission_required(ACCESS_PERM) def deactivate_xenforo_forum(request): - logger.debug("deactivate_xenforo_forum called by user %s" % request.user) + logger.debug(f"deactivate_xenforo_forum called by user {request.user}") if XenforoTasks.delete_user(request.user): - logger.info("Successfully deactivated XenForo for user %s" % request.user) + logger.info(f"Successfully deactivated XenForo for user {request.user}") messages.success(request, _('Deactivated XenForo account.')) else: messages.error(request, _('An error occurred while processing your XenForo account.')) @@ -56,12 +56,12 @@ def deactivate_xenforo_forum(request): @login_required @permission_required(ACCESS_PERM) def reset_xenforo_password(request): - logger.debug("reset_xenforo_password called by user %s" % request.user) + logger.debug(f"reset_xenforo_password called by user {request.user}") if XenforoTasks.has_account(request.user): result = XenForoManager.reset_password(request.user.xenforo.username) # Based on XenAPI's response codes if result['response']['status_code'] == 200: - logger.info("Successfully reset XenForo password for user %s" % request.user) + logger.info(f"Successfully reset XenForo password for user {request.user}") messages.success(request, _('Reset XenForo account password.')) credentials = { 'username': request.user.xenforo.username, @@ -69,7 +69,7 @@ def reset_xenforo_password(request): } return render(request, 'services/service_credentials.html', context={'credentials': credentials, 'service': 'XenForo'}) - logger.error("Unsuccessful attempt to reset XenForo password for user %s" % request.user) + logger.error(f"Unsuccessful attempt to reset XenForo password for user {request.user}") messages.error(request, _('An error occurred while processing your XenForo account.')) return redirect("services:services") @@ -77,26 +77,26 @@ def reset_xenforo_password(request): @login_required @permission_required(ACCESS_PERM) def set_xenforo_password(request): - logger.debug("set_xenforo_password called by user %s" % request.user) + logger.debug(f"set_xenforo_password called by user {request.user}") if request.method == 'POST': logger.debug("Received POST request with form.") form = ServicePasswordForm(request.POST) - logger.debug("Form is valid: %s" % form.is_valid()) + logger.debug(f"Form is valid: {form.is_valid()}") if form.is_valid() and XenforoTasks.has_account(request.user): password = form.cleaned_data['password'] - logger.debug("Form contains password of length %s" % len(password)) + logger.debug(f"Form contains password of length {len(password)}") result = XenForoManager.update_user_password(request.user.xenforo.username, password) if result['response']['status_code'] == 200: - logger.info("Successfully reset XenForo password for user %s" % request.user) + logger.info(f"Successfully reset XenForo password for user {request.user}") messages.success(request, _('Changed XenForo password.')) else: - logger.error("Failed to install custom XenForo password for user %s" % request.user) + logger.error(f"Failed to install custom XenForo password for user {request.user}") messages.error(request, _('An error occurred while processing your XenForo account.')) return redirect('services:services') else: logger.debug("Request is not type POST - providing empty form.") form = ServicePasswordForm() - logger.debug("Rendering form for user %s" % request.user) + logger.debug(f"Rendering form for user {request.user}") context = {'form': form, 'service': 'Forum'} return render(request, 'services/service_password.html', context=context) diff --git a/allianceauth/services/signals.py b/allianceauth/services/signals.py index 773f8ab6..167aadd8 100644 --- a/allianceauth/services/signals.py +++ b/allianceauth/services/signals.py @@ -1,20 +1,19 @@ import logging from functools import partial -from django.contrib.auth.models import User, Group, Permission +from django.contrib.auth.models import Group, Permission, User from django.core.exceptions import ObjectDoesNotExist from django.db import transaction -from django.db.models.signals import m2m_changed -from django.db.models.signals import pre_delete -from django.db.models.signals import pre_save +from django.db.models.signals import m2m_changed, pre_delete, pre_save from django.dispatch import receiver -from .hooks import ServicesHook -from .tasks import disable_user, update_groups_for_user from allianceauth.authentication.models import State, UserProfile from allianceauth.authentication.signals import state_changed from allianceauth.eveonline.models import EveCharacter +from .hooks import ServicesHook +from .tasks import disable_user, update_groups_for_user + logger = logging.getLogger(__name__) @@ -46,7 +45,7 @@ def m2m_changed_user_groups(sender, instance, action, *args, **kwargs): @receiver(m2m_changed, sender=User.user_permissions.through) def m2m_changed_user_permissions(sender, instance, action, *args, **kwargs): logger.debug(f"Received m2m_changed from user {instance} permissions with action {action}") - logger.debug('sender: %s' % sender) + logger.debug(f'sender: {sender}') if instance.pk and (action == "post_remove" or action == "post_clear"): logger.debug(f"Permissions changed for user {instance}, re-validating services") # Checking permissions for a single user is quite fast, so we don't need to validate @@ -57,7 +56,7 @@ def m2m_changed_user_permissions(sender, instance, action, *args, **kwargs): for svc in ServicesHook.get_services(): try: svc.validate_user(instance) - except: + except Exception: logger.exception( f'Exception running validate_user for services module {svc} on user {instance}') @@ -138,13 +137,13 @@ def check_service_accounts_state_changed(sender, user, state, **kwargs): @receiver(pre_delete, sender=User) def pre_delete_user(sender, instance, *args, **kwargs): - logger.debug("Received pre_delete from %s" % instance) + logger.debug(f"Received pre_delete from {instance}") disable_user(instance) @receiver(pre_save, sender=User) def disable_services_on_inactive(sender, instance, *args, **kwargs): - logger.debug("Received pre_save from %s" % instance) + logger.debug(f"Received pre_save from {instance}") # check if user is being marked active/inactive if not instance.pk: # new model being created @@ -152,7 +151,7 @@ def disable_services_on_inactive(sender, instance, *args, **kwargs): try: old_instance = User.objects.get(pk=instance.pk) if old_instance.is_active and not instance.is_active: - logger.info("Disabling services for inactivation of user %s" % instance) + logger.info(f"Disabling services for inactivation of user {instance}") disable_user(instance) except User.DoesNotExist: pass @@ -183,7 +182,7 @@ def process_main_character_change(sender, instance, *args, **kwargs): try: svc.validate_user(instance.user) svc.sync_nickname(instance.user) - except: + except Exception: logger.exception( "Exception running sync_nickname for services module %s " "on user %s", @@ -213,7 +212,7 @@ def process_main_character_update(sender, instance, *args, **kwargs): try: svc.validate_user(instance.userprofile.user) svc.sync_nickname(instance.userprofile.user) - except: + except Exception: logger.exception(f'Exception running sync_nickname for services module {svc} on user {instance}') except ObjectDoesNotExist: # not a main char ignore diff --git a/allianceauth/services/tasks.py b/allianceauth/services/tasks.py index 58947577..ac0c8c2f 100644 --- a/allianceauth/services/tasks.py +++ b/allianceauth/services/tasks.py @@ -1,11 +1,12 @@ import logging from celery import shared_task +from celery_once import AlreadyQueued, QueueOnce as BaseTask + from django.contrib.auth.models import User -from .hooks import ServicesHook -from celery_once import QueueOnce as BaseTask, AlreadyQueued from django.core.cache import cache +from .hooks import ServicesHook logger = logging.getLogger(__name__) @@ -38,12 +39,12 @@ def validate_services(self, pk): for svc in ServicesHook.get_services(): try: svc.validate_user(user) - except: + except Exception: logger.exception(f'Exception running validate_user for services module {svc} on user {user}') def disable_user(user): - logger.debug('Disabling all services for user %s' % user) + logger.debug(f'Disabling all services for user {user}') for svc in ServicesHook.get_services(): if svc.service_active_for_user(user): svc.delete_user(user) diff --git a/allianceauth/services/tests/test_hooks.py b/allianceauth/services/tests/test_hooks.py index dd3d787b..ba3d125d 100644 --- a/allianceauth/services/tests/test_hooks.py +++ b/allianceauth/services/tests/test_hooks.py @@ -1,7 +1,7 @@ from unittest import TestCase -from allianceauth.services.hooks import UrlHook from allianceauth.groupmanagement import urls +from allianceauth.services.hooks import UrlHook class TestUrlHook(TestCase): diff --git a/allianceauth/services/tests/test_models.py b/allianceauth/services/tests/test_models.py index f03f58c6..05488a6e 100644 --- a/allianceauth/services/tests/test_models.py +++ b/allianceauth/services/tests/test_models.py @@ -1,4 +1,5 @@ from django.test import TestCase + from allianceauth.tests.auth_utils import AuthUtils from ..models import NameFormatConfig diff --git a/allianceauth/services/tests/test_nameformatter.py b/allianceauth/services/tests/test_nameformatter.py index 2b448bc7..e221cf40 100644 --- a/allianceauth/services/tests/test_nameformatter.py +++ b/allianceauth/services/tests/test_nameformatter.py @@ -1,8 +1,10 @@ from django.test import TestCase + +from allianceauth.eveonline.models import EveAllianceInfo, EveCharacter, EveCorporationInfo from allianceauth.tests.auth_utils import AuthUtils -from allianceauth.eveonline.models import EveAllianceInfo, EveCorporationInfo, EveCharacter -from ..models import NameFormatConfig + from ..hooks import NameFormatter +from ..models import NameFormatConfig from ..modules.example.auth_hooks import ExampleService diff --git a/allianceauth/services/tests/test_signals.py b/allianceauth/services/tests/test_signals.py index e8cfdc57..50c36d9c 100644 --- a/allianceauth/services/tests/test_signals.py +++ b/allianceauth/services/tests/test_signals.py @@ -1,14 +1,13 @@ from copy import deepcopy from unittest import mock -from django.test import override_settings, TestCase, TransactionTestCase from django.contrib.auth.models import Group, Permission +from django.test import TestCase, TransactionTestCase, override_settings from allianceauth.authentication.models import State from allianceauth.eveonline.models import EveCharacter from allianceauth.tests.auth_utils import AuthUtils - MODULE_PATH = 'allianceauth.services.signals' diff --git a/allianceauth/services/tests/test_tasks.py b/allianceauth/services/tests/test_tasks.py index 06257a1f..2d8eaf07 100644 --- a/allianceauth/services/tests/test_tasks.py +++ b/allianceauth/services/tests/test_tasks.py @@ -3,10 +3,10 @@ from unittest import mock from celery_once import AlreadyQueued from django.core.cache import cache -from django.test import override_settings, TestCase +from django.test import TestCase, override_settings +from allianceauth.services.tasks import update_groups_for_user, validate_services from allianceauth.tests.auth_utils import AuthUtils -from allianceauth.services.tasks import validate_services, update_groups_for_user from ..tasks import DjangoBackend @@ -55,7 +55,7 @@ class TestDjangoBackend(TestCase): def setUp(self) -> None: cache.delete(self.TEST_KEY) - self.backend = DjangoBackend(dict()) + self.backend = DjangoBackend({}) def test_can_get_lock(self): """ diff --git a/allianceauth/services/urls.py b/allianceauth/services/urls.py index 9c8a8141..72a52e12 100644 --- a/allianceauth/services/urls.py +++ b/allianceauth/services/urls.py @@ -1,6 +1,6 @@ -from django.urls import include +from django.urls import include, path + from allianceauth.hooks import get_hooks -from django.urls import path from . import views diff --git a/allianceauth/services/views.py b/allianceauth/services/views.py index b99604a3..8f8a14ff 100644 --- a/allianceauth/services/views.py +++ b/allianceauth/services/views.py @@ -4,6 +4,7 @@ from django.contrib.auth.decorators import login_required from django.shortcuts import render from allianceauth.hooks import get_hooks + from .forms import FleetFormatterForm logger = logging.getLogger(__name__) @@ -11,11 +12,11 @@ logger = logging.getLogger(__name__) @login_required def fleet_formatter_view(request): - logger.debug("fleet_formatter_view called by user %s" % request.user) + logger.debug(f"fleet_formatter_view called by user {request.user}") generated = "" if request.method == 'POST': form = FleetFormatterForm(request.POST) - logger.debug("Received POST request containing form, valid: %s" % form.is_valid()) + logger.debug(f"Received POST request containing form, valid: {form.is_valid()}") if form.is_valid(): generated = "Fleet Name: " + form.cleaned_data['fleet_name'] + "\n" generated = generated + "FC: " + form.cleaned_data['fleet_commander'] + "\n" @@ -29,10 +30,10 @@ def fleet_formatter_view(request): generated = generated + "Important: " + form.cleaned_data['important'] + "\n" if form.cleaned_data['comments'] != "": generated = generated + "Why: " + form.cleaned_data['comments'] + "\n" - logger.info("Formatted fleet broadcast for user %s" % request.user) + logger.info(f"Formatted fleet broadcast for user {request.user}") else: form = FleetFormatterForm() - logger.debug("Returning empty form to user %s" % request.user) + logger.debug(f"Returning empty form to user {request.user}") context = {'form': form, 'generated': generated} @@ -41,8 +42,7 @@ def fleet_formatter_view(request): @login_required def services_view(request): - logger.debug("services_view called by user %s" % request.user) - char = request.user.profile.main_character + logger.debug(f"services_view called by user {request.user}") context = {'service_ctrls': []} for fn in get_hooks('services_hook'): # Render hooked services controls diff --git a/allianceauth/srp/admin.py b/allianceauth/srp/admin.py index 9a6685b8..b40a6761 100644 --- a/allianceauth/srp/admin.py +++ b/allianceauth/srp/admin.py @@ -1,7 +1,6 @@ from django.contrib import admin -from allianceauth.srp.models import SrpFleetMain -from allianceauth.srp.models import SrpUserRequest +from allianceauth.srp.models import SrpFleetMain, SrpUserRequest admin.site.register(SrpFleetMain) admin.site.register(SrpUserRequest) diff --git a/allianceauth/srp/managers.py b/allianceauth/srp/managers.py index b37d26b2..cc7cb059 100644 --- a/allianceauth/srp/managers.py +++ b/allianceauth/srp/managers.py @@ -22,7 +22,7 @@ class SRPManager: @staticmethod def get_kill_data(kill_id): - url = ("https://zkillboard.com/api/killID/%s/" % kill_id) + url = (f"https://zkillboard.com/api/killID/{kill_id}/") headers = { 'User-Agent': NAME, 'Content-Type': 'application/json', diff --git a/allianceauth/srp/migrations/0001_initial.py b/allianceauth/srp/migrations/0001_initial.py index db51307b..ba66d1c9 100644 --- a/allianceauth/srp/migrations/0001_initial.py +++ b/allianceauth/srp/migrations/0001_initial.py @@ -1,8 +1,8 @@ # Generated by Django 1.10.1 on 2016-09-05 21:40 -from django.db import migrations, models import django.db.models.deletion import django.utils.timezone +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/allianceauth/srp/migrations/0004_on_delete.py b/allianceauth/srp/migrations/0004_on_delete.py index 3dbd2083..dd32f3cb 100644 --- a/allianceauth/srp/migrations/0004_on_delete.py +++ b/allianceauth/srp/migrations/0004_on_delete.py @@ -1,7 +1,7 @@ # Generated by Django 1.11.5 on 2017-09-28 02:16 -from django.db import migrations, models import django.db.models.deletion +from django.db import migrations, models class Migration(migrations.Migration): diff --git a/allianceauth/srp/models.py b/allianceauth/srp/models.py index bb4f8280..58369e89 100644 --- a/allianceauth/srp/models.py +++ b/allianceauth/srp/models.py @@ -13,6 +13,11 @@ class SrpFleetMain(models.Model): fleet_commander = models.ForeignKey(EveCharacter, null=True, on_delete=models.SET_NULL) fleet_srp_aar_link = models.CharField(max_length=254, default="") + + + class Meta: + permissions = (('access_srp', 'Can access SRP module'),) + def __str__(self): return self.fleet_name @@ -23,11 +28,6 @@ class SrpFleetMain(models.Model): @property def pending_requests(self): return self.srpuserrequest_set.filter(srp_status='Pending').count() - - class Meta: - permissions = (('access_srp', 'Can access SRP module'),) - - class SrpUserRequest(models.Model): SRP_STATUS_CHOICES = ( ('Pending', 'Pending'), diff --git a/allianceauth/srp/providers.py b/allianceauth/srp/providers.py index f7bf26e3..ac57ec1e 100644 --- a/allianceauth/srp/providers.py +++ b/allianceauth/srp/providers.py @@ -1,4 +1,5 @@ import os + from esi.clients import EsiClientProvider from allianceauth import __version__ diff --git a/allianceauth/srp/tests/test_managers.py b/allianceauth/srp/tests/test_managers.py index 50eac10b..417f762f 100644 --- a/allianceauth/srp/tests/test_managers.py +++ b/allianceauth/srp/tests/test_managers.py @@ -4,13 +4,13 @@ import os from unittest.mock import patch from django.contrib.auth.models import User -from django.utils.timezone import now from django.test import TestCase +from django.utils.timezone import now from allianceauth.tests.auth_utils import AuthUtils from ..managers import SRPManager -from ..models import SrpUserRequest, SrpFleetMain +from ..models import SrpFleetMain, SrpUserRequest MODULE_PATH = 'allianceauth.srp.managers' @@ -22,7 +22,7 @@ currentdir = os.path.dirname(os.path.abspath(inspect.getfile( def load_data(filename): """loads given JSON file from `testdata` sub folder and returns content""" with open( - currentdir + '/testdata/%s.json' % filename, encoding='utf-8' + currentdir + f'/testdata/{filename}.json', encoding='utf-8' ) as f: data = json.load(f) diff --git a/allianceauth/srp/views.py b/allianceauth/srp/views.py index 99f795e9..d8568c4c 100644 --- a/allianceauth/srp/views.py +++ b/allianceauth/srp/views.py @@ -2,23 +2,21 @@ import logging import uuid from django.contrib import messages -from django.contrib.auth.decorators import login_required -from django.contrib.auth.decorators import permission_required +from django.contrib.auth.decorators import login_required, permission_required from django.contrib.humanize.templatetags.humanize import intcomma -from django.http import JsonResponse, Http404 -from django.shortcuts import render, redirect, get_object_or_404 +from django.db.models import Sum +from django.http import Http404, JsonResponse +from django.shortcuts import get_object_or_404, redirect, render from django.utils import timezone from django.utils.translation import gettext_lazy as _ -from django.db.models import Sum + from allianceauth.authentication.decorators import permissions_required -from allianceauth.srp.providers import esi from allianceauth.notifications import notify -from .form import SrpFleetMainForm -from .form import SrpFleetMainUpdateForm -from .form import SrpFleetUserRequestForm -from .models import SrpFleetMain -from .models import SrpUserRequest +from allianceauth.srp.providers import esi + +from .form import SrpFleetMainForm, SrpFleetMainUpdateForm, SrpFleetUserRequestForm from .managers import SRPManager +from .models import SrpFleetMain, SrpUserRequest logger = logging.getLogger(__name__) @@ -34,7 +32,7 @@ def random_string(string_length=10): @login_required @permission_required('srp.access_srp') def srp_management(request, all=False): - logger.debug("srp_management called by user %s" % request.user) + logger.debug(f"srp_management called by user {request.user}") fleets = SrpFleetMain.objects.select_related('fleet_commander').prefetch_related('srpuserrequest_set').all() if not all: fleets = fleets.filter(fleet_srp_status="") @@ -44,14 +42,15 @@ def srp_management(request, all=False): context = {"srpfleets": fleets, "totalcost": totalcost} return render(request, 'srp/management.html', context=context) + @login_required @permission_required('srp.access_srp') def srp_fleet_view(request, fleet_id): logger.debug(f"srp_fleet_view called by user {request.user} for fleet id {fleet_id}") try: fleet_main = SrpFleetMain.objects.get(id=fleet_id) - except SrpFleetMain.DoesNotExist: - raise Http404 + except SrpFleetMain.DoesNotExist as e: + raise Http404 from e context = {"fleet_id": fleet_id, "fleet_status": fleet_main.fleet_srp_status, "srpfleetrequests": fleet_main.srpuserrequest_set.select_related('character'), "totalcost": fleet_main.total_cost} @@ -62,13 +61,13 @@ def srp_fleet_view(request, fleet_id): @login_required @permissions_required(('auth.srp_management', 'srp.add_srpfleetmain')) def srp_fleet_add_view(request): - logger.debug("srp_fleet_add_view called by user %s" % request.user) + logger.debug(f"srp_fleet_add_view called by user {request.user}") completed = False completed_srp_code = "" if request.method == 'POST': form = SrpFleetMainForm(request.POST) - logger.debug("Request type POST contains form valid: %s" % form.is_valid()) + logger.debug(f"Request type POST contains form valid: {form.is_valid()}") if form.is_valid(): srp_fleet_main = SrpFleetMain() srp_fleet_main.fleet_name = form.cleaned_data['fleet_name'] @@ -167,7 +166,7 @@ def srp_request_view(request, fleet_srp): if request.method == 'POST': form = SrpFleetUserRequestForm(request.POST) - logger.debug("Request type POST contains form valid: %s" % form.is_valid()) + logger.debug(f"Request type POST contains form valid: {form.is_valid()}") if form.is_valid(): request_killboard_link = form.cleaned_data['killboard_link'] @@ -193,8 +192,7 @@ def srp_request_view(request, fleet_srp): srp_kill_link = SRPManager.get_kill_id(srp_request.killboard_link) (ship_type_id, ship_value, victim_id) = SRPManager.get_kill_data(srp_kill_link) except ValueError: - logger.debug("User {} Submitted Invalid Killmail Link {} or server could not be reached".format( - request.user, srp_request.killboard_link)) + logger.debug(f"User {request.user} Submitted Invalid Killmail Link {srp_request.killboard_link} or server could not be reached") # THIS SHOULD BE IN FORM VALIDATION messages.error(request, _("Your SRP request Killmail link is invalid. Please make sure you are using zKillboard.")) @@ -206,8 +204,7 @@ def srp_request_view(request, fleet_srp): srp_request.kb_total_loss = ship_value srp_request.post_time = post_time srp_request.save() - logger.info("Created SRP Request on behalf of user {} for fleet name {}".format( - request.user, srp_fleet_main.fleet_name)) + logger.info(f"Created SRP Request on behalf of user {request.user} for fleet name {srp_fleet_main.fleet_name}") messages.success(request, _('Submitted SRP request for your %(ship)s.') % {"ship": srp_request.srp_ship_name}) return redirect("srp:management") @@ -243,7 +240,7 @@ def srp_request_remove(request): srpuserrequest.delete() logger.info(f"Deleted SRP request id {srp_request_id} for user {request.user}") if stored_fleet_view is None: - logger.error("Unable to delete srp requests for user %s - request matching id not found." % (request.user)) + logger.error(f"Unable to delete srp requests for user {request.user} - request matching id not found.") messages.error(request, _('Unable to locate selected SRP request.')) return redirect("srp:management") else: @@ -270,18 +267,15 @@ def srp_request_approve(request): if srpuserrequest.srp_total_amount == 0: srpuserrequest.srp_total_amount = srpuserrequest.kb_total_loss srpuserrequest.save() - logger.info("Approved SRP request id {} for character {} by user {}".format( - srp_request_id, srpuserrequest.character, request.user)) + logger.info(f"Approved SRP request id {srp_request_id} for character {srpuserrequest.character} by user {request.user}") notify( srpuserrequest.character.character_ownership.user, 'SRP Request Approved', level='success', - message='Your SRP request for a {} lost during {} has been approved for {} ISK.'.format( - srpuserrequest.srp_ship_name, srpuserrequest.srp_fleet_main.fleet_name, - intcomma(srpuserrequest.srp_total_amount)) + message=f'Your SRP request for a {srpuserrequest.srp_ship_name} lost during {srpuserrequest.srp_fleet_main.fleet_name} has been approved for {intcomma(srpuserrequest.srp_total_amount)} ISK.' ) if stored_fleet_view is None: - logger.error("Unable to approve srp request on behalf of user %s - request matching id not found." % (request.user)) + logger.error(f"Unable to approve srp request on behalf of user {request.user} - request matching id not found.") messages.error(request, _('Unable to locate selected SRP request.')) return redirect("srp:management") else: @@ -306,17 +300,15 @@ def srp_request_reject(request): stored_fleet_view = srpuserrequest.srp_fleet_main.id srpuserrequest.srp_status = "Rejected" srpuserrequest.save() - logger.info("SRP request id {} for character {} rejected by {}".format( - srp_request_id, srpuserrequest.character, request.user)) + logger.info(f"SRP request id {srp_request_id} for character {srpuserrequest.character} rejected by {request.user}") notify( srpuserrequest.character.character_ownership.user, 'SRP Request Rejected', level='danger', - message='Your SRP request for a {} lost during {} has been rejected.'.format( - srpuserrequest.srp_ship_name, srpuserrequest.srp_fleet_main.fleet_name) + message=f'Your SRP request for a {srpuserrequest.srp_ship_name} lost during {srpuserrequest.srp_fleet_main.fleet_name} has been rejected.' ) if stored_fleet_view is None: - logger.error("Unable to reject SRP request on behalf of user %s - request matching id not found." % (request.user)) + logger.error(f"Unable to reject SRP request on behalf of user {request.user} - request matching id not found.") messages.error(request, _('Unable to locate selected SRP request')) return redirect("srp:management") else: @@ -327,8 +319,7 @@ def srp_request_reject(request): @login_required @permission_required('auth.srp_management') def srp_request_update_amount(request, fleet_srp_request_id): - logger.debug("srp_request_update_amount called by user {} for fleet srp request id {}".format( - request.user, fleet_srp_request_id)) + logger.debug(f"srp_request_update_amount called by user {request.user} for fleet srp request id {fleet_srp_request_id}") if SrpUserRequest.objects.filter(id=fleet_srp_request_id).exists() is False: logger.error(f"Unable to locate SRP request id {fleet_srp_request_id} for user {request.user}") @@ -351,7 +342,7 @@ def srp_fleet_edit_view(request, fleet_id): srpfleetmain = get_object_or_404(SrpFleetMain, id=fleet_id) if request.method == 'POST': form = SrpFleetMainUpdateForm(request.POST) - logger.debug("Request type POST contains form valid: %s" % form.is_valid()) + logger.debug(f"Request type POST contains form valid: {form.is_valid()}") if form.is_valid(): srpfleetmain.fleet_srp_aar_link = form.cleaned_data['fleet_aar_link'] srpfleetmain.save() diff --git a/allianceauth/templatetags/admin_status.py b/allianceauth/templatetags/admin_status.py index f9f8347b..d7084dc5 100644 --- a/allianceauth/templatetags/admin_status.py +++ b/allianceauth/templatetags/admin_status.py @@ -44,7 +44,7 @@ def decimal_widthratio(this_value, max_value, max_width) -> str: @register.inclusion_tag('allianceauth/admin-status/overview.html') def status_overview() -> dict: response = { - "notifications": list(), + "notifications": [], "current_version": __version__, "tasks_succeeded": 0, "tasks_retried": 0, @@ -144,8 +144,8 @@ def _latests_versions(tags: list) -> tuple: Non-compliant tags will be ignored """ - versions = list() - betas = list() + versions = [] + betas = [] for tag in tags: try: version = Pep440Version(tag.get('name')) @@ -167,7 +167,7 @@ def _latests_versions(tags: list) -> tuple: def _fetch_list_from_gitlab(url: str, max_pages: int = MAX_PAGES) -> list: """returns a list from the GitLab API. Supports paging""" - result = list() + result = [] for page in range(1, max_pages + 1): try: diff --git a/allianceauth/tests/auth_utils.py b/allianceauth/tests/auth_utils.py index 06bfb314..bec16bcb 100644 --- a/allianceauth/tests/auth_utils.py +++ b/allianceauth/tests/auth_utils.py @@ -1,31 +1,29 @@ -from typing import List -from django.contrib.auth.models import User, Group, Permission -from django.db.models.signals import m2m_changed, pre_save, post_save +from django.contrib.auth.models import Group, Permission, User +from django.db.models.signals import m2m_changed, post_save, pre_save from django.test import TestCase from esi.models import Token -from allianceauth.authentication.models import ( - UserProfile, State, get_guest_state -) -from allianceauth.eveonline.models import EveCharacter +from allianceauth.authentication.models import State, UserProfile, get_guest_state from allianceauth.authentication.signals import ( + assign_state_on_active_change, + check_state_on_character_update, + reassess_on_profile_save, state_member_alliances_changed, state_member_characters_changed, state_member_corporations_changed, state_saved, - reassess_on_profile_save, - assign_state_on_active_change, - check_state_on_character_update ) +from allianceauth.eveonline.models import EveCharacter from allianceauth.services.signals import ( + disable_services_on_inactive, m2m_changed_group_permissions, - m2m_changed_user_permissions, m2m_changed_state_permissions, - m2m_changed_user_groups, disable_services_on_inactive, + m2m_changed_user_groups, + m2m_changed_user_permissions, process_main_character_change, - process_main_character_update + process_main_character_update, ) diff --git a/allianceauth/tests/test_auth_utils.py b/allianceauth/tests/test_auth_utils.py index 2fa5215c..62a06bd7 100644 --- a/allianceauth/tests/test_auth_utils.py +++ b/allianceauth/tests/test_auth_utils.py @@ -1,19 +1,14 @@ -from unittest import mock -from django.contrib.auth.models import User, Group, Permission +from django.contrib.auth.models import Group, Permission, User from django.test import TestCase -from allianceauth.eveonline.models import ( - EveCorporationInfo, EveAllianceInfo, EveCharacter -) - from .auth_utils import AuthUtils class TestAuthUtils(TestCase): def test_can_create_user(self): - user = AuthUtils.create_user('Bruce Wayne') + AuthUtils.create_user('Bruce Wayne') self.assertTrue(User.objects.filter(username='Bruce Wayne').exists()) def test_can_add_main_character_2(self): diff --git a/allianceauth/tests/test_urls.py b/allianceauth/tests/test_urls.py index 95315b8d..621ce0ed 100644 --- a/allianceauth/tests/test_urls.py +++ b/allianceauth/tests/test_urls.py @@ -1,5 +1,6 @@ from unittest import TestCase -from unittest.mock import patch, MagicMock +from unittest.mock import MagicMock, patch + from django.urls import URLPattern from allianceauth.services.hooks import UrlHook diff --git a/allianceauth/theme/bootstrap/auth_hooks.py b/allianceauth/theme/bootstrap/auth_hooks.py index 72fe265a..0ac2de3a 100644 --- a/allianceauth/theme/bootstrap/auth_hooks.py +++ b/allianceauth/theme/bootstrap/auth_hooks.py @@ -1,7 +1,6 @@ from allianceauth import hooks from allianceauth.theme.hooks import ThemeHook - CSS_STATICS = [{ "url": "https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css", "integrity": "sha512-jnSuA4Ss2PkkikSOLtYs8BlYIeeIK1h99ty4YfvRPAlzr377vr3CXDb7sb7eEEBYjDtcYj+AjBH3FLv5uSJuXg==" diff --git a/allianceauth/theme/templatetags/theme_tags.py b/allianceauth/theme/templatetags/theme_tags.py index 68a7ab4e..503482b9 100644 --- a/allianceauth/theme/templatetags/theme_tags.py +++ b/allianceauth/theme/templatetags/theme_tags.py @@ -58,7 +58,7 @@ def theme_html_tags(context): def header_padding_size(context): request = context['request'] theme = get_theme(request) - return getattr(theme, "header_padding") + return theme.header_padding @register.inclusion_tag('theme/theme_imports_js.html', takes_context=True) diff --git a/allianceauth/thirdparty/navhelper/templatetags/navactive.py b/allianceauth/thirdparty/navhelper/templatetags/navactive.py index f9b34610..d54028b4 100644 --- a/allianceauth/thirdparty/navhelper/templatetags/navactive.py +++ b/allianceauth/thirdparty/navhelper/templatetags/navactive.py @@ -21,11 +21,12 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ +import re + +from django.conf import settings from django.template import Library from django.urls import resolve from django.urls.exceptions import Resolver404 -from django.conf import settings -import re register = Library() diff --git a/allianceauth/thirdparty/navhelper/tests.py b/allianceauth/thirdparty/navhelper/tests.py index afe9d878..4b580195 100644 --- a/allianceauth/thirdparty/navhelper/tests.py +++ b/allianceauth/thirdparty/navhelper/tests.py @@ -24,7 +24,7 @@ THE SOFTWARE. # -*- coding: utf-8 -*- from django.template import Context, Template -from django.test import TestCase, RequestFactory +from django.test import RequestFactory, TestCase class NavhelperTemplateTagTests(TestCase): diff --git a/allianceauth/timerboard/auth_hooks.py b/allianceauth/timerboard/auth_hooks.py index 68bb2a6f..2fa01acb 100644 --- a/allianceauth/timerboard/auth_hooks.py +++ b/allianceauth/timerboard/auth_hooks.py @@ -1,8 +1,8 @@ +from allianceauth import hooks from allianceauth.menu.hooks import MenuItemHook from allianceauth.services.hooks import UrlHook - -from allianceauth import hooks from allianceauth.timerboard.views import dashboard_timers + from . import urls diff --git a/allianceauth/timerboard/form.py b/allianceauth/timerboard/form.py index 52aab92d..2bab4051 100644 --- a/allianceauth/timerboard/form.py +++ b/allianceauth/timerboard/form.py @@ -23,7 +23,7 @@ class TimerForm(forms.ModelForm): # for appropriate fields current_time = timezone.now() td = kwargs['instance'].eve_time - current_time - initial = kwargs.pop('initial', dict()) + initial = kwargs.pop('initial', {}) if 'days_left' not in initial: initial.update({'days_left': td.days}) if 'hours_left' not in initial: diff --git a/allianceauth/timerboard/migrations/0001_initial.py b/allianceauth/timerboard/migrations/0001_initial.py index 6f8d5e1c..6f434eb3 100644 --- a/allianceauth/timerboard/migrations/0001_initial.py +++ b/allianceauth/timerboard/migrations/0001_initial.py @@ -1,8 +1,8 @@ # Generated by Django 1.10.1 on 2016-09-05 21:40 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/timerboard/migrations/0003_on_delete.py b/allianceauth/timerboard/migrations/0003_on_delete.py index 1a3013b0..765afc34 100644 --- a/allianceauth/timerboard/migrations/0003_on_delete.py +++ b/allianceauth/timerboard/migrations/0003_on_delete.py @@ -1,8 +1,8 @@ # Generated by Django 1.11.5 on 2017-09-28 02:16 +import django.db.models.deletion from django.conf import settings from django.db import migrations, models -import django.db.models.deletion class Migration(migrations.Migration): diff --git a/allianceauth/timerboard/models.py b/allianceauth/timerboard/models.py index d4127c9b..075f1383 100644 --- a/allianceauth/timerboard/models.py +++ b/allianceauth/timerboard/models.py @@ -2,8 +2,7 @@ from django.contrib.auth.models import User from django.db import models from django.utils.translation import gettext as _ -from allianceauth.eveonline.models import EveCharacter -from allianceauth.eveonline.models import EveCorporationInfo +from allianceauth.eveonline.models import EveCharacter, EveCorporationInfo class Timer(models.Model): @@ -70,8 +69,8 @@ class Timer(models.Model): corp_timer = models.BooleanField(default=False) user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) - def __str__(self) -> str: - return str(self.system) + ' ' + str(self.details) - class Meta: ordering = ['eve_time'] + + def __str__(self) -> str: + return str(self.system) + ' ' + str(self.details) diff --git a/allianceauth/timerboard/tests.py b/allianceauth/timerboard/tests.py index 26e7ef00..98a54678 100644 --- a/allianceauth/timerboard/tests.py +++ b/allianceauth/timerboard/tests.py @@ -1,25 +1,26 @@ -from django_webtest import WebTest -from django.utils import timezone -from django.urls import reverse -from django.contrib.auth.models import Permission, User -from django.conf import settings - from datetime import timedelta -from allianceauth.tests.auth_utils import AuthUtils -from allianceauth.eveonline.models import EveCorporationInfo +from django_webtest import WebTest + +from django.conf import settings +from django.contrib.auth.models import Permission, User +from django.urls import reverse +from django.utils import timezone + +from allianceauth.eveonline.models import EveCorporationInfo +from allianceauth.tests.auth_utils import AuthUtils -from .models import Timer from .form import TimerForm +from .models import Timer class TimerboardViewsTestCase(WebTest): csrf_checks = False def setUp(self): - corp = EveCorporationInfo.objects.create(corporation_id='2345', corporation_name='test corp', + EveCorporationInfo.objects.create(corporation_id='2345', corporation_name='test corp', corporation_ticker='testc', member_count=24) - other_corp = EveCorporationInfo.objects.create(corporation_id='9345', corporation_name='other test corp', + EveCorporationInfo.objects.create(corporation_id='9345', corporation_name='other test corp', corporation_ticker='testd', member_count=1) self.user = AuthUtils.create_user('test_user') AuthUtils.add_main_character(self.user, 'test character', '1234', '2345', 'test corp', 'testc') diff --git a/allianceauth/timerboard/views.py b/allianceauth/timerboard/views.py index 93c877c8..b4695f73 100644 --- a/allianceauth/timerboard/views.py +++ b/allianceauth/timerboard/views.py @@ -1,12 +1,12 @@ -import datetime import logging from django.contrib import messages from django.contrib.auth.mixins import ( - LoginRequiredMixin, PermissionRequiredMixin, + LoginRequiredMixin, + PermissionRequiredMixin, ) from django.db.models import Q -from django.shortcuts import get_object_or_404, redirect, render +from django.shortcuts import get_object_or_404, render from django.template.loader import render_to_string from django.urls import reverse_lazy from django.utils import timezone diff --git a/allianceauth/urls.py b/allianceauth/urls.py index a2505f4d..6d1cc12d 100644 --- a/allianceauth/urls.py +++ b/allianceauth/urls.py @@ -1,13 +1,12 @@ -from typing import List -from collections.abc import Iterable, Callable +from collections.abc import Callable, Iterable -from django.urls import include -import esi.urls from django.conf import settings from django.contrib import admin from django.urls import URLPattern, include, path from django.views.generic.base import TemplateView +import esi.urls + import allianceauth.authentication.urls import allianceauth.authentication.views import allianceauth.groupmanagement.urls @@ -15,10 +14,7 @@ import allianceauth.notifications.urls import allianceauth.services.urls from allianceauth import NAME, views from allianceauth.authentication import hmac_urls -from allianceauth.authentication.decorators import ( - decorate_url_patterns, - main_character_required -) +from allianceauth.authentication.decorators import decorate_url_patterns, main_character_required from allianceauth.hooks import get_hooks admin.site.site_header = NAME diff --git a/allianceauth/utils/counters.py b/allianceauth/utils/counters.py index c84c5527..ed28b134 100644 --- a/allianceauth/utils/counters.py +++ b/allianceauth/utils/counters.py @@ -1,6 +1,5 @@ """Counters.""" -from typing import Optional from redis import Redis diff --git a/allianceauth/utils/testing.py b/allianceauth/utils/testing.py index 43afdf58..5b4bbb13 100644 --- a/allianceauth/utils/testing.py +++ b/allianceauth/utils/testing.py @@ -1,4 +1,5 @@ import socket + from django.test import TestCase diff --git a/allianceauth/utils/tests/test_testing.py b/allianceauth/utils/tests/test_testing.py index ee8ccbbc..2b569aaa 100644 --- a/allianceauth/utils/tests/test_testing.py +++ b/allianceauth/utils/tests/test_testing.py @@ -1,4 +1,5 @@ import requests + from allianceauth.utils.testing import NoSocketsTestCase, SocketAccessError diff --git a/docker/conf/celery.py b/docker/conf/celery.py index 5129f00a..6d0c5a8e 100644 --- a/docker/conf/celery.py +++ b/docker/conf/celery.py @@ -1,11 +1,12 @@ import os + from celery import Celery from celery.app import trace # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myauth.settings.local') -from django.conf import settings # noqa +from django.conf import settings app = Celery('myauth') diff --git a/docker/conf/urls.py b/docker/conf/urls.py index 58d40642..a098e831 100644 --- a/docker/conf/urls.py +++ b/docker/conf/urls.py @@ -1,6 +1,7 @@ -from allianceauth import urls from django.urls import include, path +from allianceauth import urls + urlpatterns = [ path('', include(urls)), ] diff --git a/docs/conf.py b/docs/conf.py index 78f8c63b..8fca5e2e 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -12,9 +12,11 @@ # import os import sys -import django + import sphinx_rtd_theme # noqa +import django + sys.path.insert(0, os.path.abspath('..')) os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings_all' django.setup() diff --git a/manage.py b/manage.py index 6afed5b2..69124cd4 100644 --- a/manage.py +++ b/manage.py @@ -1,22 +1,20 @@ #!/usr/bin/env python -import os import sys if __name__ == "__main__": - os.environ.setdefault("DJANGO_SETTINGS_MODULE", "allianceauth.project_template.project_name.settings.base") try: from django.core.management import execute_from_command_line - except ImportError: + except ImportError as err: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: - import django + import django # noqa: F401 except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" - ) + ) from err raise execute_from_command_line(sys.argv) diff --git a/pyproject.toml b/pyproject.toml index 18b47caa..65061af6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -107,6 +107,9 @@ lint.select = [ lint.ignore = [ "E501", # Line too long, WIP across repo. ] + +lint.per-file-ignores = { "*local.py" = [ "F405", "F403" ] } + lint.isort.combine-as-imports = true # profile=django lint.isort.section-order = [ "future", @@ -166,6 +169,9 @@ select = [ ignore = [ "E501", # Line too long, WIP across repo. ] +per-file-ignores = [ + "docker/conf/local.py:F405", +] [tool.djlint] max_attribute_length = 119 diff --git a/runtests.py b/runtests.py index 35d797b7..7aadd287 100644 --- a/runtests.py +++ b/runtests.py @@ -1,21 +1,21 @@ #!/usr/bin/env python -import os import sys if __name__ == "__main__": try: from django.core.management import execute_from_command_line - except ImportError: + except ImportError as err: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: - import django + import django # noqa: F401 except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" - ) - raise - execute_from_command_line(sys.argv.insert(1, 'test')) + ) from err # Provide context for the original error + raise # Re-raise original exception with context + + execute_from_command_line(sys.argv.insert(1, "test")) diff --git a/tests/celery.py b/tests/celery.py index dfbc2779..ed1c7996 100644 --- a/tests/celery.py +++ b/tests/celery.py @@ -5,7 +5,7 @@ from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings') -from django.conf import settings # noqa +from django.conf import settings app = Celery('devauth') diff --git a/tests/settings_all.py b/tests/settings_all.py index 5bddee70..2c6f6d14 100644 --- a/tests/settings_all.py +++ b/tests/settings_all.py @@ -4,12 +4,12 @@ Alliance Auth Test Suite Django settings Testing all services and plug-in apps """ -from allianceauth.project_template.project_name.settings.base import * +from allianceauth.project_template.project_name.settings.base import * # noqa:F403 # Celery configuration CELERY_ALWAYS_EAGER = True # Forces celery to run locally for testing -INSTALLED_APPS += [ +INSTALLED_APPS += [ # noqa:F405 "allianceauth.eveonline.autogroups", "allianceauth.hrapplications", "allianceauth.timerboard", diff --git a/tests/settings_core.py b/tests/settings_core.py index 6403cfa8..ed72dd13 100644 --- a/tests/settings_core.py +++ b/tests/settings_core.py @@ -4,7 +4,7 @@ Alliance Auth Test Suite Django settings Testing core packages only """ -from allianceauth.project_template.project_name.settings.base import * +from allianceauth.project_template.project_name.settings.base import * # noqa:F403 # Celery configuration CELERY_ALWAYS_EAGER = True # Forces celery to run locally for testing diff --git a/tests/urls.py b/tests/urls.py index ba840b33..d271ad7c 100644 --- a/tests/urls.py +++ b/tests/urls.py @@ -1,5 +1,7 @@ -import allianceauth.urls from django.urls import path + +import allianceauth.urls + from . import views urlpatterns = allianceauth.urls.urlpatterns