mirror of
https://gitlab.com/allianceauth/allianceauth.git
synced 2026-02-04 14:16:21 +01:00
Compare commits
158 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f8ca4fad2 | ||
|
|
4bb9a7155d | ||
|
|
2ac79954f3 | ||
|
|
585e1f47f3 | ||
|
|
a33c474b35 | ||
|
|
61c3d8964b | ||
|
|
1c927c5820 | ||
|
|
ff0fa0329d | ||
|
|
e51ea439ca | ||
|
|
8f39b50b6d | ||
|
|
95b309c358 | ||
|
|
cf3df3b715 | ||
|
|
d815028c4d | ||
|
|
ac5570abe2 | ||
|
|
84ad571aa4 | ||
|
|
38e7705ae7 | ||
|
|
0b6af014fa | ||
|
|
2401f2299d | ||
|
|
919768c8bb | ||
|
|
24db21463b | ||
|
|
1e029af83a | ||
|
|
53dd8ce606 | ||
|
|
0f4003366d | ||
|
|
ac6f3c267f | ||
|
|
39ad625fa1 | ||
|
|
1db67025bf | ||
|
|
13ab6c072a | ||
|
|
cec1dd84ef | ||
|
|
fae5805322 | ||
|
|
16ea9500be | ||
|
|
18f5dc0f47 | ||
|
|
ba3e941fe8 | ||
|
|
4c416b03b1 | ||
|
|
e2abb64171 | ||
|
|
c66aa13ae1 | ||
|
|
2b31be789d | ||
|
|
bf1b4bb549 | ||
|
|
3b539c8577 | ||
|
|
dd42b807f0 | ||
|
|
542fbafd98 | ||
|
|
37b9f5c882 | ||
|
|
4836559abe | ||
|
|
17b06c8845 | ||
|
|
8dd07b97c7 | ||
|
|
9e139495ac | ||
|
|
5bde9a6952 | ||
|
|
23ad9d02d3 | ||
|
|
f99878cc29 | ||
|
|
e64431b06c | ||
|
|
0b2993c1c3 | ||
|
|
75bccf1b0f | ||
|
|
7fa76d6d37 | ||
|
|
945bc92898 | ||
|
|
ec7d14a839 | ||
|
|
dd1a368ff6 | ||
|
|
a3cce35881 | ||
|
|
54085617dc | ||
|
|
8cdc5af453 | ||
|
|
da93940e13 | ||
|
|
f53b43d9dc | ||
|
|
497a167ca7 | ||
|
|
852c5a3037 | ||
|
|
90f6777a7a | ||
|
|
ed4f71a283 | ||
|
|
13e2f4e27d | ||
|
|
17343dfeae | ||
|
|
4b5978fb58 | ||
|
|
a8d890abaf | ||
|
|
79379b444c | ||
|
|
ace1de5c68 | ||
|
|
0a30eea3b4 | ||
|
|
a15d281c40 | ||
|
|
6846bb7cdc | ||
|
|
1d240a40dd | ||
|
|
5d6128e9ea | ||
|
|
c377bcec5f | ||
|
|
9b74fb4dbd | ||
|
|
6744c0c143 | ||
|
|
131cc5ed0a | ||
|
|
9297bed43f | ||
|
|
b2fddc683a | ||
|
|
1e9f5e6430 | ||
|
|
ceaa064e62 | ||
|
|
1aad3e4512 | ||
|
|
f83c3c2811 | ||
|
|
a23ec6d318 | ||
|
|
ecc53888bc | ||
|
|
9af634d16a | ||
|
|
a68163caa3 | ||
|
|
00770fd034 | ||
|
|
01164777ed | ||
|
|
e54f72091f | ||
|
|
00f5e3e1e0 | ||
|
|
8b2527f408 | ||
|
|
b7500e4e4e | ||
|
|
4f4bd0c419 | ||
|
|
75b5b28804 | ||
|
|
f81a2ed237 | ||
|
|
49e01157e7 | ||
|
|
28420a729e | ||
|
|
52a4cf8d52 | ||
|
|
703c2392a9 | ||
|
|
18c9a66437 | ||
|
|
9687d57de9 | ||
|
|
60c2e57d83 | ||
|
|
b14bff0145 | ||
|
|
9166886665 | ||
|
|
c74010d441 | ||
|
|
640a21e4db | ||
|
|
8ae4e02012 | ||
|
|
cc9a07197d | ||
|
|
fd442a5735 | ||
|
|
c7b99044bc | ||
|
|
234451a7d4 | ||
|
|
ffff904ab1 | ||
|
|
d71a26220c | ||
|
|
beeeb8dc5d | ||
|
|
19244cc4c6 | ||
|
|
cc94ba6b5e | ||
|
|
c9926cc877 | ||
|
|
1d14e1b0af | ||
|
|
297da44a5a | ||
|
|
402ff53a5c | ||
|
|
2d6e4a0df1 | ||
|
|
f18dd1029b | ||
|
|
fd8d43571a | ||
|
|
13e88492f1 | ||
|
|
38df580a56 | ||
|
|
ba39318313 | ||
|
|
d8c6035405 | ||
|
|
2ef3da916b | ||
|
|
d32d8b26ce | ||
|
|
f348b1a34c | ||
|
|
86aaa3edda | ||
|
|
26017056c7 | ||
|
|
e39a3c072b | ||
|
|
827291dda4 | ||
|
|
defcfa3316 | ||
|
|
3209b71b0a | ||
|
|
80b3ca0a1e | ||
|
|
8351bd2fa3 | ||
|
|
255966ed3b | ||
|
|
8d6ebf4770 | ||
|
|
2ca752bf78 | ||
|
|
79e1192f67 | ||
|
|
ff610efc84 | ||
|
|
6b68a739ef | ||
|
|
909bd0ba15 | ||
|
|
05110abc59 | ||
|
|
a64d99eb91 | ||
|
|
0e45403195 | ||
|
|
e16a9ffe65 | ||
|
|
57de122ef8 | ||
|
|
8de2c3bfcb | ||
|
|
6688f73565 | ||
|
|
72740b9e4d | ||
|
|
d11832913d | ||
|
|
dfe62db8ee |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -76,3 +76,4 @@ celerybeat-schedule
|
||||
.flake8
|
||||
.pylintrc
|
||||
Makefile
|
||||
.isort.cfg
|
||||
|
||||
128
.gitlab-ci.yml
128
.gitlab-ci.yml
@@ -5,15 +5,16 @@
|
||||
- merge_requests
|
||||
|
||||
stages:
|
||||
- pre-commit
|
||||
- gitlab
|
||||
- test
|
||||
- deploy
|
||||
- docker
|
||||
- pre-commit
|
||||
- gitlab
|
||||
- test
|
||||
- deploy
|
||||
- docker
|
||||
|
||||
include:
|
||||
- template: Dependency-Scanning.gitlab-ci.yml
|
||||
- template: Security/SAST.gitlab-ci.yml
|
||||
- template: Dependency-Scanning.gitlab-ci.yml
|
||||
- template: Security/SAST.gitlab-ci.yml
|
||||
- template: Security/Secret-Detection.gitlab-ci.yml
|
||||
|
||||
before_script:
|
||||
- apt-get update && apt-get install redis-server -y
|
||||
@@ -24,7 +25,7 @@ before_script:
|
||||
pre-commit-check:
|
||||
<<: *only-default
|
||||
stage: pre-commit
|
||||
image: python:3.6-buster
|
||||
image: python:3.8-bullseye
|
||||
variables:
|
||||
PRE_COMMIT_HOME: ${CI_PROJECT_DIR}/.cache/pre-commit
|
||||
cache:
|
||||
@@ -41,123 +42,150 @@ sast:
|
||||
dependency_scanning:
|
||||
stage: gitlab
|
||||
before_script:
|
||||
- apt-get update && apt-get install redis-server libmariadb-dev -y
|
||||
- redis-server --daemonize yes
|
||||
- python -V
|
||||
- pip install wheel tox
|
||||
- apt-get update && apt-get install redis-server libmariadb-dev -y
|
||||
- redis-server --daemonize yes
|
||||
- python -V
|
||||
- pip install wheel tox
|
||||
|
||||
test-3.7-core:
|
||||
<<: *only-default
|
||||
image: python:3.7-bullseye
|
||||
script:
|
||||
- tox -e py37-core
|
||||
artifacts:
|
||||
when: always
|
||||
reports:
|
||||
cobertura: coverage.xml
|
||||
secret_detection:
|
||||
stage: gitlab
|
||||
before_script: []
|
||||
|
||||
test-3.8-core:
|
||||
<<: *only-default
|
||||
image: python:3.8-bullseye
|
||||
script:
|
||||
- tox -e py38-core
|
||||
- tox -e py38-core
|
||||
artifacts:
|
||||
when: always
|
||||
reports:
|
||||
cobertura: coverage.xml
|
||||
coverage_report:
|
||||
coverage_format: cobertura
|
||||
path: coverage.xml
|
||||
|
||||
test-3.9-core:
|
||||
<<: *only-default
|
||||
image: python:3.9-bullseye
|
||||
script:
|
||||
- tox -e py39-core
|
||||
- tox -e py39-core
|
||||
artifacts:
|
||||
when: always
|
||||
reports:
|
||||
cobertura: coverage.xml
|
||||
coverage_report:
|
||||
coverage_format: cobertura
|
||||
path: coverage.xml
|
||||
|
||||
test-3.10-core:
|
||||
<<: *only-default
|
||||
image: python:3.10-bullseye
|
||||
script:
|
||||
- tox -e py310-core
|
||||
- tox -e py310-core
|
||||
artifacts:
|
||||
when: always
|
||||
reports:
|
||||
cobertura: coverage.xml
|
||||
coverage_report:
|
||||
coverage_format: cobertura
|
||||
path: coverage.xml
|
||||
|
||||
test-3.11-core:
|
||||
<<: *only-default
|
||||
image: python:3.11-rc-bullseye
|
||||
script:
|
||||
- tox -e py311-core
|
||||
- tox -e py311-core
|
||||
artifacts:
|
||||
when: always
|
||||
reports:
|
||||
cobertura: coverage.xml
|
||||
coverage_report:
|
||||
coverage_format: cobertura
|
||||
path: coverage.xml
|
||||
allow_failure: true
|
||||
|
||||
test-3.7-all:
|
||||
<<: *only-default
|
||||
image: python:3.7-bullseye
|
||||
script:
|
||||
- tox -e py37-all
|
||||
artifacts:
|
||||
when: always
|
||||
reports:
|
||||
cobertura: coverage.xml
|
||||
|
||||
test-3.8-all:
|
||||
<<: *only-default
|
||||
image: python:3.8-bullseye
|
||||
script:
|
||||
- tox -e py38-all
|
||||
- tox -e py38-all
|
||||
artifacts:
|
||||
when: always
|
||||
reports:
|
||||
cobertura: coverage.xml
|
||||
coverage_report:
|
||||
coverage_format: cobertura
|
||||
path: coverage.xml
|
||||
|
||||
test-3.9-all:
|
||||
<<: *only-default
|
||||
image: python:3.9-bullseye
|
||||
script:
|
||||
- tox -e py39-all
|
||||
- tox -e py39-all
|
||||
artifacts:
|
||||
when: always
|
||||
reports:
|
||||
cobertura: coverage.xml
|
||||
coverage_report:
|
||||
coverage_format: cobertura
|
||||
path: coverage.xml
|
||||
|
||||
test-3.10-all:
|
||||
<<: *only-default
|
||||
image: python:3.10-bullseye
|
||||
script:
|
||||
- tox -e py310-all
|
||||
- tox -e py310-all
|
||||
artifacts:
|
||||
when: always
|
||||
reports:
|
||||
cobertura: coverage.xml
|
||||
coverage_report:
|
||||
coverage_format: cobertura
|
||||
path: coverage.xml
|
||||
|
||||
test-3.11-all:
|
||||
<<: *only-default
|
||||
image: python:3.11-rc-bullseye
|
||||
script:
|
||||
- tox -e py311-all
|
||||
- tox -e py311-all
|
||||
artifacts:
|
||||
when: always
|
||||
reports:
|
||||
cobertura: coverage.xml
|
||||
coverage_report:
|
||||
coverage_format: cobertura
|
||||
path: coverage.xml
|
||||
allow_failure: true
|
||||
|
||||
build-test:
|
||||
stage: test
|
||||
image: python:3.10-bullseye
|
||||
|
||||
before_script:
|
||||
- python -m pip install --upgrade pip
|
||||
- python -m pip install --upgrade build
|
||||
- python -m pip install --upgrade setuptools wheel
|
||||
|
||||
script:
|
||||
- python -m build
|
||||
|
||||
artifacts:
|
||||
when: always
|
||||
name: "$CI_JOB_NAME-$CI_COMMIT_REF_SLUG"
|
||||
paths:
|
||||
- dist/*
|
||||
expire_in: 1 year
|
||||
|
||||
test-docs:
|
||||
<<: *only-default
|
||||
image: python:3.10-bullseye
|
||||
script:
|
||||
- tox -e docs
|
||||
|
||||
deploy_production:
|
||||
stage: deploy
|
||||
image: python:3.10-bullseye
|
||||
|
||||
before_script:
|
||||
- pip install twine wheel
|
||||
- python -m pip install --upgrade pip
|
||||
- python -m pip install --upgrade build
|
||||
- python -m pip install --upgrade setuptools wheel twine
|
||||
|
||||
script:
|
||||
- python setup.py sdist bdist_wheel
|
||||
- twine upload dist/*
|
||||
- python -m build
|
||||
- python -m twine upload dist/*
|
||||
|
||||
rules:
|
||||
- if: $CI_COMMIT_TAG
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.0.1
|
||||
rev: v4.3.0
|
||||
hooks:
|
||||
- id: check-case-conflict
|
||||
- id: check-json
|
||||
@@ -22,13 +22,18 @@ repos:
|
||||
args: [ '--remove' ]
|
||||
|
||||
- repo: https://github.com/editorconfig-checker/editorconfig-checker.python
|
||||
rev: 2.3.54
|
||||
rev: 2.4.0
|
||||
hooks:
|
||||
- id: editorconfig-checker
|
||||
exclude: ^(LICENSE|allianceauth\/static\/css\/themes\/bootstrap-locals.less|allianceauth\/eveonline\/swagger.json|(.*.po)|(.*.mo))
|
||||
|
||||
- repo: https://github.com/asottile/pyupgrade
|
||||
rev: v2.29.0
|
||||
rev: v2.34.0
|
||||
hooks:
|
||||
- id: pyupgrade
|
||||
args: [ --py37-plus ]
|
||||
args: [ --py38-plus ]
|
||||
|
||||
- repo: https://github.com/asottile/setup-cfg-fmt
|
||||
rev: v1.20.1
|
||||
hooks:
|
||||
- id: setup-cfg-fmt
|
||||
|
||||
@@ -5,19 +5,22 @@
|
||||
# Required
|
||||
version: 2
|
||||
|
||||
# Set the version of Python and other tools you might need
|
||||
build:
|
||||
os: ubuntu-20.04
|
||||
apt_packages:
|
||||
- redis
|
||||
tools:
|
||||
python: "3.10"
|
||||
|
||||
# Build documentation in the docs/ directory with Sphinx
|
||||
sphinx:
|
||||
configuration: docs/conf.py
|
||||
|
||||
# Build documentation with MkDocs
|
||||
#mkdocs:
|
||||
# configuration: mkdocs.yml
|
||||
|
||||
# Optionally build your docs in additional formats such as PDF and ePub
|
||||
formats: all
|
||||
|
||||
# Optionally set the version of Python and requirements required to build your docs
|
||||
python:
|
||||
version: 3.7
|
||||
install:
|
||||
- requirements: docs/requirements.txt
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
# This will make sure the app is always imported when
|
||||
# Django starts so that shared_task will use this app.
|
||||
|
||||
__version__ = '2.9.4'
|
||||
__version__ = '3.0.0b1'
|
||||
__title__ = 'Alliance Auth'
|
||||
__url__ = 'https://gitlab.com/allianceauth/allianceauth'
|
||||
NAME = f'{__title__} v{__version__}'
|
||||
default_app_config = 'allianceauth.apps.AllianceAuthConfig'
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
default_app_config = 'allianceauth.analytics.apps.AnalyticsConfig'
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
from django.conf import settings
|
||||
from django.utils.deprecation import MiddlewareMixin
|
||||
from .models import AnalyticsTokens, AnalyticsIdentifier
|
||||
from .tasks import send_ga_tracking_web_view
|
||||
@@ -10,6 +11,8 @@ import re
|
||||
class AnalyticsMiddleware(MiddlewareMixin):
|
||||
def process_response(self, request, response):
|
||||
"""Django Middleware: Process Page Views and creates Analytics Celery Tasks"""
|
||||
if getattr(settings, "ANALYTICS_DISABLED", False):
|
||||
return response
|
||||
analyticstokens = AnalyticsTokens.objects.all()
|
||||
client_id = AnalyticsIdentifier.objects.get(id=1).identifier.hex
|
||||
try:
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
# Generated by Django 3.1.13 on 2021-10-15 05:02
|
||||
|
||||
from django.core.exceptions import ObjectDoesNotExist
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
def modify_aa_team_token_add_page_ignore_paths(apps, schema_editor):
|
||||
# We can't import the Person model directly as it may be a newer
|
||||
# version than this migration expects. We use the historical version.
|
||||
# Add /admin/ and /user_notifications_count/ path to ignore
|
||||
|
||||
AnalyticsPath = apps.get_model('analytics', 'AnalyticsPath')
|
||||
admin = AnalyticsPath.objects.create(ignore_path=r"^\/admin\/.*")
|
||||
@@ -17,8 +17,19 @@ def modify_aa_team_token_add_page_ignore_paths(apps, schema_editor):
|
||||
|
||||
|
||||
def undo_modify_aa_team_token_add_page_ignore_paths(apps, schema_editor):
|
||||
# nothing should need to migrate away here?
|
||||
return True
|
||||
#
|
||||
AnalyticsPath = apps.get_model('analytics', 'AnalyticsPath')
|
||||
Tokens = apps.get_model('analytics', 'AnalyticsTokens')
|
||||
|
||||
token = Tokens.objects.get(token="UA-186249766-2")
|
||||
try:
|
||||
admin = AnalyticsPath.objects.get(ignore_path=r"^\/admin\/.*", analyticstokens=token)
|
||||
user_notifications_count = AnalyticsPath.objects.get(ignore_path=r"^\/user_notifications_count\/.*", analyticstokens=token)
|
||||
admin.delete()
|
||||
user_notifications_count.delete()
|
||||
except ObjectDoesNotExist:
|
||||
# Its fine if it doesnt exist, we just dont want them building up when re-migrating
|
||||
pass
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
40
allianceauth/analytics/migrations/0006_more_ignore_paths.py
Normal file
40
allianceauth/analytics/migrations/0006_more_ignore_paths.py
Normal file
@@ -0,0 +1,40 @@
|
||||
# Generated by Django 3.2.8 on 2021-10-19 01:47
|
||||
|
||||
from django.core.exceptions import ObjectDoesNotExist
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
def modify_aa_team_token_add_page_ignore_paths(apps, schema_editor):
|
||||
# Add the /account/activate path to ignore
|
||||
|
||||
AnalyticsPath = apps.get_model('analytics', 'AnalyticsPath')
|
||||
account_activate = AnalyticsPath.objects.create(ignore_path=r"^\/account\/activate\/.*")
|
||||
|
||||
Tokens = apps.get_model('analytics', 'AnalyticsTokens')
|
||||
token = Tokens.objects.get(token="UA-186249766-2")
|
||||
token.ignore_paths.add(account_activate)
|
||||
|
||||
|
||||
def undo_modify_aa_team_token_add_page_ignore_paths(apps, schema_editor):
|
||||
#
|
||||
AnalyticsPath = apps.get_model('analytics', 'AnalyticsPath')
|
||||
Tokens = apps.get_model('analytics', 'AnalyticsTokens')
|
||||
|
||||
token = Tokens.objects.get(token="UA-186249766-2")
|
||||
|
||||
try:
|
||||
account_activate = AnalyticsPath.objects.get(ignore_path=r"^\/account\/activate\/.*", analyticstokens=token)
|
||||
account_activate.delete()
|
||||
except ObjectDoesNotExist:
|
||||
# Its fine if it doesnt exist, we just dont want them building up when re-migrating
|
||||
pass
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('analytics', '0005_alter_analyticspath_ignore_path'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RunPython(modify_aa_team_token_add_page_ignore_paths, undo_modify_aa_team_token_add_page_ignore_paths)
|
||||
]
|
||||
@@ -1,7 +1,8 @@
|
||||
from allianceauth.analytics.tasks import analytics_event
|
||||
from celery.signals import task_failure, task_success
|
||||
|
||||
import logging
|
||||
from celery.signals import task_failure, task_success
|
||||
from django.conf import settings
|
||||
from allianceauth.analytics.tasks import analytics_event
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -11,6 +12,8 @@ def process_failure_signal(
|
||||
sender, task_id, signal,
|
||||
args, kwargs, einfo, **kw):
|
||||
logger.debug("Celery task_failure signal %s" % sender.__class__.__name__)
|
||||
if getattr(settings, "ANALYTICS_DISABLED", False):
|
||||
return
|
||||
|
||||
category = sender.__module__
|
||||
|
||||
@@ -30,6 +33,8 @@ def process_failure_signal(
|
||||
@task_success.connect
|
||||
def celery_success_signal(sender, result=None, **kw):
|
||||
logger.debug("Celery task_success signal %s" % sender.__class__.__name__)
|
||||
if getattr(settings, "ANALYTICS_DISABLED", False):
|
||||
return
|
||||
|
||||
category = sender.__module__
|
||||
|
||||
|
||||
@@ -21,8 +21,8 @@ if getattr(settings, "ANALYTICS_ENABLE_DEBUG", False) and settings.DEBUG:
|
||||
# Force sending of analytics data during in a debug/test environemt
|
||||
# Usefull for developers working on this feature.
|
||||
logger.warning(
|
||||
"You have 'ANALYTICS_ENABLE_DEBUG' Enabled! "
|
||||
"This debug instance will send analytics data!")
|
||||
"You have 'ANALYTICS_ENABLE_DEBUG' Enabled! "
|
||||
"This debug instance will send analytics data!")
|
||||
DEBUG_URL = COLLECTION_URL
|
||||
|
||||
ANALYTICS_URL = COLLECTION_URL
|
||||
@@ -40,13 +40,12 @@ def analytics_event(category: str,
|
||||
Send a Google Analytics Event for each token stored
|
||||
Includes check for if its enabled/disabled
|
||||
|
||||
Parameters
|
||||
-------
|
||||
`category` (str): Celery Namespace
|
||||
`action` (str): Task Name
|
||||
`label` (str): Optional, Task Success/Exception
|
||||
`value` (int): Optional, If bulk, Query size, can be a binary True/False
|
||||
`event_type` (str): Optional, Celery or Stats only, Default to Celery
|
||||
Args:
|
||||
`category` (str): Celery Namespace
|
||||
`action` (str): Task Name
|
||||
`label` (str): Optional, Task Success/Exception
|
||||
`value` (int): Optional, If bulk, Query size, can be a binary True/False
|
||||
`event_type` (str): Optional, Celery or Stats only, Default to Celery
|
||||
"""
|
||||
analyticstokens = AnalyticsTokens.objects.all()
|
||||
client_id = AnalyticsIdentifier.objects.get(id=1).identifier.hex
|
||||
@@ -60,20 +59,21 @@ def analytics_event(category: str,
|
||||
|
||||
if allowed is True:
|
||||
tracking_id = token.token
|
||||
send_ga_tracking_celery_event.s(tracking_id=tracking_id,
|
||||
client_id=client_id,
|
||||
category=category,
|
||||
action=action,
|
||||
label=label,
|
||||
value=value).\
|
||||
apply_async(priority=9)
|
||||
send_ga_tracking_celery_event.s(
|
||||
tracking_id=tracking_id,
|
||||
client_id=client_id,
|
||||
category=category,
|
||||
action=action,
|
||||
label=label,
|
||||
value=value).apply_async(priority=9)
|
||||
|
||||
|
||||
@shared_task()
|
||||
def analytics_daily_stats():
|
||||
"""Celery Task: Do not call directly
|
||||
|
||||
Gathers a series of daily statistics and sends analytics events containing them"""
|
||||
Gathers a series of daily statistics and sends analytics events containing them
|
||||
"""
|
||||
users = install_stat_users()
|
||||
tokens = install_stat_tokens()
|
||||
addons = install_stat_addons()
|
||||
|
||||
108
allianceauth/analytics/tests/test_integration.py
Normal file
108
allianceauth/analytics/tests/test_integration.py
Normal file
@@ -0,0 +1,108 @@
|
||||
from unittest.mock import patch
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
import requests_mock
|
||||
|
||||
from django.test import TestCase, override_settings
|
||||
|
||||
from allianceauth.analytics.tasks import ANALYTICS_URL
|
||||
from allianceauth.eveonline.tasks import update_character
|
||||
from allianceauth.tests.auth_utils import AuthUtils
|
||||
|
||||
|
||||
@override_settings(CELERY_ALWAYS_EAGER=True)
|
||||
@requests_mock.mock()
|
||||
class TestAnalyticsForViews(TestCase):
|
||||
@override_settings(ANALYTICS_DISABLED=False)
|
||||
def test_should_run_analytics(self, requests_mocker):
|
||||
# given
|
||||
requests_mocker.post(ANALYTICS_URL)
|
||||
user = AuthUtils.create_user("Bruce Wayne")
|
||||
self.client.force_login(user)
|
||||
# when
|
||||
response = self.client.get("/dashboard/")
|
||||
# then
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertTrue(requests_mocker.called)
|
||||
|
||||
@override_settings(ANALYTICS_DISABLED=True)
|
||||
def test_should_not_run_analytics(self, requests_mocker):
|
||||
# given
|
||||
requests_mocker.post(ANALYTICS_URL)
|
||||
user = AuthUtils.create_user("Bruce Wayne")
|
||||
self.client.force_login(user)
|
||||
# when
|
||||
response = self.client.get("/dashboard/")
|
||||
# then
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertFalse(requests_mocker.called)
|
||||
|
||||
|
||||
@override_settings(CELERY_ALWAYS_EAGER=True)
|
||||
@requests_mock.mock()
|
||||
class TestAnalyticsForTasks(TestCase):
|
||||
@override_settings(ANALYTICS_DISABLED=False)
|
||||
@patch("allianceauth.eveonline.models.EveCharacter.objects.update_character")
|
||||
def test_should_run_analytics_for_successful_task(
|
||||
self, requests_mocker, mock_update_character
|
||||
):
|
||||
# given
|
||||
requests_mocker.post(ANALYTICS_URL)
|
||||
user = AuthUtils.create_user("Bruce Wayne")
|
||||
character = AuthUtils.add_main_character_2(user, "Bruce Wayne", 1001)
|
||||
# when
|
||||
update_character.delay(character.character_id)
|
||||
# then
|
||||
self.assertTrue(mock_update_character.called)
|
||||
self.assertTrue(requests_mocker.called)
|
||||
payload = parse_qs(requests_mocker.last_request.text)
|
||||
self.assertListEqual(payload["el"], ["Success"])
|
||||
|
||||
@override_settings(ANALYTICS_DISABLED=True)
|
||||
@patch("allianceauth.eveonline.models.EveCharacter.objects.update_character")
|
||||
def test_should_not_run_analytics_for_successful_task(
|
||||
self, requests_mocker, mock_update_character
|
||||
):
|
||||
# given
|
||||
requests_mocker.post(ANALYTICS_URL)
|
||||
user = AuthUtils.create_user("Bruce Wayne")
|
||||
character = AuthUtils.add_main_character_2(user, "Bruce Wayne", 1001)
|
||||
# when
|
||||
update_character.delay(character.character_id)
|
||||
# then
|
||||
self.assertTrue(mock_update_character.called)
|
||||
self.assertFalse(requests_mocker.called)
|
||||
|
||||
@override_settings(ANALYTICS_DISABLED=False)
|
||||
@patch("allianceauth.eveonline.models.EveCharacter.objects.update_character")
|
||||
def test_should_run_analytics_for_failed_task(
|
||||
self, requests_mocker, mock_update_character
|
||||
):
|
||||
# given
|
||||
requests_mocker.post(ANALYTICS_URL)
|
||||
mock_update_character.side_effect = RuntimeError
|
||||
user = AuthUtils.create_user("Bruce Wayne")
|
||||
character = AuthUtils.add_main_character_2(user, "Bruce Wayne", 1001)
|
||||
# when
|
||||
update_character.delay(character.character_id)
|
||||
# then
|
||||
self.assertTrue(mock_update_character.called)
|
||||
self.assertTrue(requests_mocker.called)
|
||||
payload = parse_qs(requests_mocker.last_request.text)
|
||||
self.assertNotEqual(payload["el"], ["Success"])
|
||||
|
||||
@override_settings(ANALYTICS_DISABLED=True)
|
||||
@patch("allianceauth.eveonline.models.EveCharacter.objects.update_character")
|
||||
def test_should_not_run_analytics_for_failed_task(
|
||||
self, requests_mocker, mock_update_character
|
||||
):
|
||||
# given
|
||||
requests_mocker.post(ANALYTICS_URL)
|
||||
mock_update_character.side_effect = RuntimeError
|
||||
user = AuthUtils.create_user("Bruce Wayne")
|
||||
character = AuthUtils.add_main_character_2(user, "Bruce Wayne", 1001)
|
||||
# when
|
||||
update_character.delay(character.character_id)
|
||||
# then
|
||||
self.assertTrue(mock_update_character.called)
|
||||
self.assertFalse(requests_mocker.called)
|
||||
@@ -1,5 +1,6 @@
|
||||
from allianceauth.analytics.middleware import AnalyticsMiddleware
|
||||
from unittest.mock import Mock
|
||||
from django.http import HttpResponse
|
||||
|
||||
from django.test.testcases import TestCase
|
||||
|
||||
@@ -7,7 +8,7 @@ from django.test.testcases import TestCase
|
||||
class TestAnalyticsMiddleware(TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.middleware = AnalyticsMiddleware()
|
||||
self.middleware = AnalyticsMiddleware(HttpResponse)
|
||||
self.request = Mock()
|
||||
self.request.headers = {
|
||||
"User-Agent": "AUTOMATED TEST"
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
default_app_config = 'allianceauth.authentication.apps.AuthenticationConfig'
|
||||
|
||||
@@ -1,26 +1,44 @@
|
||||
from django.contrib import admin
|
||||
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
|
||||
from django.contrib.auth.models import User as BaseUser, \
|
||||
Permission as BasePermission, Group
|
||||
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.db.models import Count, Q
|
||||
from allianceauth.services.hooks import ServicesHook
|
||||
from django.db.models.signals import pre_save, post_save, pre_delete, \
|
||||
post_delete, m2m_changed
|
||||
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.dispatch import receiver
|
||||
from django.forms import ModelForm
|
||||
from django.utils.html import format_html
|
||||
from django.urls import reverse
|
||||
from django.utils.html import format_html
|
||||
from django.utils.text import slugify
|
||||
|
||||
from allianceauth.authentication.models import State, get_guest_state,\
|
||||
CharacterOwnership, UserProfile, OwnershipRecord
|
||||
from allianceauth.hooks import get_hooks
|
||||
from allianceauth.eveonline.models import EveCharacter, EveCorporationInfo,\
|
||||
EveAllianceInfo, 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 .app_settings import AUTHENTICATION_ADMIN_USERS_MAX_GROUPS, \
|
||||
AUTHENTICATION_ADMIN_USERS_MAX_CHARS
|
||||
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 .forms import UserChangeForm, UserProfileForm
|
||||
|
||||
|
||||
def make_service_hooks_update_groups_action(service):
|
||||
@@ -59,19 +77,10 @@ def make_service_hooks_sync_nickname_action(service):
|
||||
return sync_nickname
|
||||
|
||||
|
||||
class QuerysetModelForm(ModelForm):
|
||||
# allows specifying FK querysets through kwarg
|
||||
def __init__(self, querysets=None, *args, **kwargs):
|
||||
querysets = querysets or {}
|
||||
super().__init__(*args, **kwargs)
|
||||
for field, qs in querysets.items():
|
||||
self.fields[field].queryset = qs
|
||||
|
||||
|
||||
class UserProfileInline(admin.StackedInline):
|
||||
model = UserProfile
|
||||
readonly_fields = ('state',)
|
||||
form = QuerysetModelForm
|
||||
form = UserProfileForm
|
||||
verbose_name = ''
|
||||
verbose_name_plural = 'Profile'
|
||||
|
||||
@@ -99,6 +108,7 @@ class UserProfileInline(admin.StackedInline):
|
||||
return False
|
||||
|
||||
|
||||
@admin.display(description="")
|
||||
def user_profile_pic(obj):
|
||||
"""profile pic column data for user objects
|
||||
|
||||
@@ -111,13 +121,10 @@ def user_profile_pic(obj):
|
||||
'<img src="{}" class="img-circle">',
|
||||
user_obj.profile.main_character.portrait_url(size=32)
|
||||
)
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
user_profile_pic.short_description = ''
|
||||
return None
|
||||
|
||||
|
||||
@admin.display(description="user / main", ordering="username")
|
||||
def user_username(obj):
|
||||
"""user column data for user objects
|
||||
|
||||
@@ -139,18 +146,17 @@ def user_username(obj):
|
||||
user_obj.username,
|
||||
user_obj.profile.main_character.character_name
|
||||
)
|
||||
else:
|
||||
return format_html(
|
||||
'<strong><a href="{}">{}</a></strong>',
|
||||
link,
|
||||
user_obj.username,
|
||||
)
|
||||
|
||||
|
||||
user_username.short_description = 'user / main'
|
||||
user_username.admin_order_field = 'username'
|
||||
return format_html(
|
||||
'<strong><a href="{}">{}</a></strong>',
|
||||
link,
|
||||
user_obj.username,
|
||||
)
|
||||
|
||||
|
||||
@admin.display(
|
||||
description="Corporation / Alliance (Main)",
|
||||
ordering="profile__main_character__corporation_name"
|
||||
)
|
||||
def user_main_organization(obj):
|
||||
"""main organization column data for user objects
|
||||
|
||||
@@ -159,21 +165,15 @@ def user_main_organization(obj):
|
||||
"""
|
||||
user_obj = obj.user if hasattr(obj, 'user') else obj
|
||||
if not user_obj.profile.main_character:
|
||||
result = ''
|
||||
else:
|
||||
result = user_obj.profile.main_character.corporation_name
|
||||
if user_obj.profile.main_character.alliance_id:
|
||||
result += f'<br>{user_obj.profile.main_character.alliance_name}'
|
||||
elif user_obj.profile.main_character.faction_name:
|
||||
result += f'<br>{user_obj.profile.main_character.faction_name}'
|
||||
return ''
|
||||
result = user_obj.profile.main_character.corporation_name
|
||||
if user_obj.profile.main_character.alliance_id:
|
||||
result += f'<br>{user_obj.profile.main_character.alliance_name}'
|
||||
elif user_obj.profile.main_character.faction_name:
|
||||
result += f'<br>{user_obj.profile.main_character.faction_name}'
|
||||
return format_html(result)
|
||||
|
||||
|
||||
user_main_organization.short_description = 'Corporation / Alliance (Main)'
|
||||
user_main_organization.admin_order_field = \
|
||||
'profile__main_character__corporation_name'
|
||||
|
||||
|
||||
class MainCorporationsFilter(admin.SimpleListFilter):
|
||||
"""Custom filter to filter on corporations from mains only
|
||||
|
||||
@@ -196,15 +196,13 @@ class MainCorporationsFilter(admin.SimpleListFilter):
|
||||
def queryset(self, request, qs):
|
||||
if self.value() is None:
|
||||
return qs.all()
|
||||
else:
|
||||
if qs.model == User:
|
||||
return qs.filter(
|
||||
profile__main_character__corporation_id=self.value()
|
||||
)
|
||||
else:
|
||||
return qs.filter(
|
||||
user__profile__main_character__corporation_id=self.value()
|
||||
)
|
||||
if qs.model == User:
|
||||
return qs.filter(
|
||||
profile__main_character__corporation_id=self.value()
|
||||
)
|
||||
return qs.filter(
|
||||
user__profile__main_character__corporation_id=self.value()
|
||||
)
|
||||
|
||||
|
||||
class MainAllianceFilter(admin.SimpleListFilter):
|
||||
@@ -217,12 +215,14 @@ class MainAllianceFilter(admin.SimpleListFilter):
|
||||
parameter_name = 'main_alliance_id__exact'
|
||||
|
||||
def lookups(self, request, model_admin):
|
||||
qs = EveCharacter.objects\
|
||||
.exclude(alliance_id=None)\
|
||||
.exclude(userprofile=None)\
|
||||
.values('alliance_id', 'alliance_name')\
|
||||
.distinct()\
|
||||
qs = (
|
||||
EveCharacter.objects
|
||||
.exclude(alliance_id=None)
|
||||
.exclude(userprofile=None)
|
||||
.values('alliance_id', 'alliance_name')
|
||||
.distinct()
|
||||
.order_by(Lower('alliance_name'))
|
||||
)
|
||||
return tuple(
|
||||
(x['alliance_id'], x['alliance_name']) for x in qs
|
||||
)
|
||||
@@ -230,13 +230,11 @@ class MainAllianceFilter(admin.SimpleListFilter):
|
||||
def queryset(self, request, qs):
|
||||
if self.value() is None:
|
||||
return qs.all()
|
||||
else:
|
||||
if qs.model == User:
|
||||
return qs.filter(profile__main_character__alliance_id=self.value())
|
||||
else:
|
||||
return qs.filter(
|
||||
user__profile__main_character__alliance_id=self.value()
|
||||
)
|
||||
if qs.model == User:
|
||||
return qs.filter(profile__main_character__alliance_id=self.value())
|
||||
return qs.filter(
|
||||
user__profile__main_character__alliance_id=self.value()
|
||||
)
|
||||
|
||||
|
||||
class MainFactionFilter(admin.SimpleListFilter):
|
||||
@@ -249,12 +247,14 @@ class MainFactionFilter(admin.SimpleListFilter):
|
||||
parameter_name = 'main_faction_id__exact'
|
||||
|
||||
def lookups(self, request, model_admin):
|
||||
qs = EveCharacter.objects\
|
||||
.exclude(faction_id=None)\
|
||||
.exclude(userprofile=None)\
|
||||
.values('faction_id', 'faction_name')\
|
||||
.distinct()\
|
||||
qs = (
|
||||
EveCharacter.objects
|
||||
.exclude(faction_id=None)
|
||||
.exclude(userprofile=None)
|
||||
.values('faction_id', 'faction_name')
|
||||
.distinct()
|
||||
.order_by(Lower('faction_name'))
|
||||
)
|
||||
return tuple(
|
||||
(x['faction_id'], x['faction_name']) for x in qs
|
||||
)
|
||||
@@ -262,15 +262,14 @@ class MainFactionFilter(admin.SimpleListFilter):
|
||||
def queryset(self, request, qs):
|
||||
if self.value() is None:
|
||||
return qs.all()
|
||||
else:
|
||||
if qs.model == User:
|
||||
return qs.filter(profile__main_character__faction_id=self.value())
|
||||
else:
|
||||
return qs.filter(
|
||||
user__profile__main_character__faction_id=self.value()
|
||||
)
|
||||
if qs.model == User:
|
||||
return qs.filter(profile__main_character__faction_id=self.value())
|
||||
return qs.filter(
|
||||
user__profile__main_character__faction_id=self.value()
|
||||
)
|
||||
|
||||
|
||||
@admin.display(description="Update main character model from ESI")
|
||||
def update_main_character_model(modeladmin, request, queryset):
|
||||
tasks_count = 0
|
||||
for obj in queryset:
|
||||
@@ -279,21 +278,48 @@ def update_main_character_model(modeladmin, request, queryset):
|
||||
tasks_count += 1
|
||||
|
||||
modeladmin.message_user(
|
||||
request,
|
||||
f'Update from ESI started for {tasks_count} characters'
|
||||
request, f'Update from ESI started for {tasks_count} characters'
|
||||
)
|
||||
|
||||
|
||||
update_main_character_model.short_description = \
|
||||
'Update main character model from ESI'
|
||||
|
||||
|
||||
class UserAdmin(BaseUserAdmin):
|
||||
"""Extending Django's UserAdmin model
|
||||
|
||||
Behavior of groups and characters columns can be configured via settings
|
||||
"""
|
||||
|
||||
inlines = BaseUserAdmin.inlines + [UserProfileInline]
|
||||
ordering = ('username', )
|
||||
list_select_related = ('profile__state', 'profile__main_character')
|
||||
show_full_result_count = True
|
||||
list_display = (
|
||||
user_profile_pic,
|
||||
user_username,
|
||||
'_state',
|
||||
'_groups',
|
||||
user_main_organization,
|
||||
'_characters',
|
||||
'is_active',
|
||||
'date_joined',
|
||||
'_role'
|
||||
)
|
||||
list_display_links = None
|
||||
list_filter = (
|
||||
'profile__state',
|
||||
'groups',
|
||||
MainCorporationsFilter,
|
||||
MainAllianceFilter,
|
||||
MainFactionFilter,
|
||||
'is_active',
|
||||
'date_joined',
|
||||
'is_staff',
|
||||
'is_superuser'
|
||||
)
|
||||
search_fields = ('username', 'character_ownerships__character__character_name')
|
||||
readonly_fields = ('date_joined', 'last_login')
|
||||
filter_horizontal = ('groups', 'user_permissions',)
|
||||
form = UserChangeForm
|
||||
|
||||
class Media:
|
||||
css = {
|
||||
"all": ("authentication/css/admin.css",)
|
||||
@@ -303,9 +329,21 @@ class UserAdmin(BaseUserAdmin):
|
||||
qs = super().get_queryset(request)
|
||||
return qs.prefetch_related("character_ownerships__character", "groups")
|
||||
|
||||
def get_actions(self, request):
|
||||
actions = super(BaseUserAdmin, self).get_actions(request)
|
||||
def get_form(self, request, obj=None, **kwargs):
|
||||
"""Inject current request into change form object."""
|
||||
|
||||
MyForm = super().get_form(request, obj, **kwargs)
|
||||
if obj:
|
||||
class MyFormInjected(MyForm):
|
||||
def __new__(cls, *args, **kwargs):
|
||||
kwargs['request'] = request
|
||||
return MyForm(*args, **kwargs)
|
||||
|
||||
return MyFormInjected
|
||||
return MyForm
|
||||
|
||||
def get_actions(self, request):
|
||||
actions = super().get_actions(request)
|
||||
actions[update_main_character_model.__name__] = (
|
||||
update_main_character_model,
|
||||
update_main_character_model.__name__,
|
||||
@@ -349,38 +387,6 @@ class UserAdmin(BaseUserAdmin):
|
||||
)
|
||||
return result
|
||||
|
||||
inlines = BaseUserAdmin.inlines + [UserProfileInline]
|
||||
ordering = ('username', )
|
||||
list_select_related = ('profile__state', 'profile__main_character')
|
||||
show_full_result_count = True
|
||||
list_display = (
|
||||
user_profile_pic,
|
||||
user_username,
|
||||
'_state',
|
||||
'_groups',
|
||||
user_main_organization,
|
||||
'_characters',
|
||||
'is_active',
|
||||
'date_joined',
|
||||
'_role'
|
||||
)
|
||||
list_display_links = None
|
||||
list_filter = (
|
||||
'profile__state',
|
||||
'groups',
|
||||
MainCorporationsFilter,
|
||||
MainAllianceFilter,
|
||||
MainFactionFilter,
|
||||
'is_active',
|
||||
'date_joined',
|
||||
'is_staff',
|
||||
'is_superuser'
|
||||
)
|
||||
search_fields = (
|
||||
'username',
|
||||
'character_ownerships__character__character_name'
|
||||
)
|
||||
|
||||
def _characters(self, obj):
|
||||
character_ownerships = list(obj.character_ownerships.all())
|
||||
characters = [obj.character.character_name for obj in character_ownerships]
|
||||
@@ -389,22 +395,16 @@ class UserAdmin(BaseUserAdmin):
|
||||
AUTHENTICATION_ADMIN_USERS_MAX_CHARS
|
||||
)
|
||||
|
||||
_characters.short_description = 'characters'
|
||||
|
||||
@admin.display(ordering="profile__state")
|
||||
def _state(self, obj):
|
||||
return obj.profile.state.name
|
||||
|
||||
_state.short_description = 'state'
|
||||
_state.admin_order_field = 'profile__state'
|
||||
|
||||
def _groups(self, obj):
|
||||
my_groups = sorted(group.name for group in list(obj.groups.all()))
|
||||
return self._list_2_html_w_tooltips(
|
||||
my_groups, AUTHENTICATION_ADMIN_USERS_MAX_GROUPS
|
||||
)
|
||||
|
||||
_groups.short_description = 'groups'
|
||||
|
||||
def _role(self, obj):
|
||||
if obj.is_superuser:
|
||||
role = 'Superuser'
|
||||
@@ -414,8 +414,6 @@ class UserAdmin(BaseUserAdmin):
|
||||
role = 'User'
|
||||
return role
|
||||
|
||||
_role.short_description = 'role'
|
||||
|
||||
def has_change_permission(self, request, obj=None):
|
||||
return request.user.has_perm('auth.change_user')
|
||||
|
||||
@@ -425,12 +423,28 @@ class UserAdmin(BaseUserAdmin):
|
||||
def has_delete_permission(self, request, obj=None):
|
||||
return request.user.has_perm('auth.delete_user')
|
||||
|
||||
def get_object(self, *args , **kwargs):
|
||||
obj = super().get_object(*args , **kwargs)
|
||||
self.obj = obj # storing current object for use in formfield_for_manytomany
|
||||
return obj
|
||||
|
||||
def formfield_for_manytomany(self, db_field, request, **kwargs):
|
||||
"""overriding this formfield to have sorted lists in the form"""
|
||||
if db_field.name == "groups":
|
||||
kwargs["queryset"] = Group.objects.all().order_by(Lower('name'))
|
||||
groups_qs = Group.objects.filter(authgroup__states__isnull=True)
|
||||
obj_state = self.obj.profile.state
|
||||
if obj_state:
|
||||
matching_groups_qs = Group.objects.filter(authgroup__states=obj_state)
|
||||
groups_qs = groups_qs | matching_groups_qs
|
||||
kwargs["queryset"] = groups_qs.order_by(Lower("name"))
|
||||
return super().formfield_for_manytomany(db_field, request, **kwargs)
|
||||
|
||||
def get_readonly_fields(self, request, obj=None):
|
||||
if obj and not request.user.is_superuser:
|
||||
return self.readonly_fields + (
|
||||
"is_staff", "is_superuser", "user_permissions"
|
||||
)
|
||||
return self.readonly_fields
|
||||
|
||||
|
||||
@admin.register(State)
|
||||
class StateAdmin(admin.ModelAdmin):
|
||||
@@ -441,10 +455,9 @@ class StateAdmin(admin.ModelAdmin):
|
||||
qs = super().get_queryset(request)
|
||||
return qs.annotate(user_count=Count("userprofile__id"))
|
||||
|
||||
@admin.display(description="Users", ordering="user_count")
|
||||
def _user_count(self, obj):
|
||||
return obj.user_count
|
||||
_user_count.short_description = 'Users'
|
||||
_user_count.admin_order_field = 'user_count'
|
||||
|
||||
fieldsets = (
|
||||
(None, {
|
||||
@@ -500,13 +513,13 @@ class StateAdmin(admin.ModelAdmin):
|
||||
)
|
||||
return super().get_fieldsets(request, obj=obj)
|
||||
|
||||
def get_readonly_fields(self, request, obj=None):
|
||||
if not request.user.is_superuser:
|
||||
return self.readonly_fields + ("permissions",)
|
||||
return self.readonly_fields
|
||||
|
||||
|
||||
class BaseOwnershipAdmin(admin.ModelAdmin):
|
||||
class Media:
|
||||
css = {
|
||||
"all": ("authentication/css/admin.css",)
|
||||
}
|
||||
|
||||
list_select_related = (
|
||||
'user__profile__state', 'user__profile__main_character', 'character')
|
||||
list_display = (
|
||||
@@ -527,6 +540,11 @@ class BaseOwnershipAdmin(admin.ModelAdmin):
|
||||
MainAllianceFilter,
|
||||
)
|
||||
|
||||
class Media:
|
||||
css = {
|
||||
"all": ("authentication/css/admin.css",)
|
||||
}
|
||||
|
||||
def get_readonly_fields(self, request, obj=None):
|
||||
if obj and obj.pk:
|
||||
return 'owner_hash', 'character'
|
||||
|
||||
@@ -3,10 +3,14 @@ from django.core.checks import register, Tags
|
||||
|
||||
|
||||
class AuthenticationConfig(AppConfig):
|
||||
name = 'allianceauth.authentication'
|
||||
label = 'authentication'
|
||||
name = "allianceauth.authentication"
|
||||
label = "authentication"
|
||||
|
||||
def ready(self):
|
||||
super().ready()
|
||||
from allianceauth.authentication import checks, signals
|
||||
from allianceauth.authentication import checks, signals # noqa: F401
|
||||
from allianceauth.authentication.task_statistics import (
|
||||
signals as celery_signals,
|
||||
)
|
||||
|
||||
register(Tags.security)(checks.check_login_scopes_setting)
|
||||
celery_signals.reset_counters()
|
||||
|
||||
@@ -1,8 +1,66 @@
|
||||
from django import forms
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.contrib.auth.forms import UserChangeForm as BaseUserChangeForm
|
||||
from django.contrib.auth.models import Group
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.forms import ModelForm
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from allianceauth.authentication.models import User
|
||||
|
||||
|
||||
class RegistrationForm(forms.Form):
|
||||
email = forms.EmailField(label=_('Email'), max_length=254, required=True)
|
||||
|
||||
class _meta:
|
||||
model = User
|
||||
|
||||
|
||||
class UserProfileForm(ModelForm):
|
||||
"""Allows specifying FK querysets through kwarg"""
|
||||
|
||||
def __init__(self, querysets=None, *args, **kwargs):
|
||||
querysets = querysets or {}
|
||||
super().__init__(*args, **kwargs)
|
||||
for field, qs in querysets.items():
|
||||
self.fields[field].queryset = qs
|
||||
|
||||
|
||||
class UserChangeForm(BaseUserChangeForm):
|
||||
"""Add custom cleaning to UserChangeForm"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.request = kwargs.pop("request") # Inject current request into form object
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def clean(self):
|
||||
cleaned_data = super().clean()
|
||||
if not self.request.user.is_superuser:
|
||||
if self.instance:
|
||||
current_restricted = set(
|
||||
self.instance.groups.filter(
|
||||
authgroup__restricted=True
|
||||
).values_list("pk", flat=True)
|
||||
)
|
||||
else:
|
||||
current_restricted = set()
|
||||
new_restricted = set(
|
||||
cleaned_data["groups"].filter(
|
||||
authgroup__restricted=True
|
||||
).values_list("pk", flat=True)
|
||||
)
|
||||
if current_restricted != new_restricted:
|
||||
restricted_removed = current_restricted - new_restricted
|
||||
restricted_added = new_restricted - current_restricted
|
||||
restricted_changed = restricted_removed | restricted_added
|
||||
restricted_names_qs = Group.objects.filter(
|
||||
pk__in=restricted_changed
|
||||
).values_list("name", flat=True)
|
||||
restricted_names = ",".join(list(restricted_names_qs))
|
||||
raise ValidationError(
|
||||
{
|
||||
"groups": _(
|
||||
"You are not allowed to add or remove these "
|
||||
"restricted groups: %s" % restricted_names
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
from django.conf.urls import url, include
|
||||
from django.conf.urls import include
|
||||
|
||||
from allianceauth.authentication import views
|
||||
from django.urls import re_path
|
||||
from django.urls import path
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^activate/complete/$', views.activation_complete, name='registration_activation_complete'),
|
||||
path('activate/complete/', views.activation_complete, name='registration_activation_complete'),
|
||||
# The activation key can make use of any character from the
|
||||
# URL-safe base64 alphabet, plus the colon as a separator.
|
||||
url(r'^activate/(?P<activation_key>[-:\w]+)/$', views.ActivationView.as_view(), name='registration_activate'),
|
||||
url(r'^register/$', views.RegistrationView.as_view(), name='registration_register'),
|
||||
url(r'^register/complete/$', views.registration_complete, name='registration_complete'),
|
||||
url(r'^register/closed/$', views.registration_closed, name='registration_disallowed'),
|
||||
url(r'', include('django.contrib.auth.urls')),
|
||||
re_path(r'^activate/(?P<activation_key>[-:\w]+)/$', views.ActivationView.as_view(), name='registration_activate'),
|
||||
path('register/', views.RegistrationView.as_view(), name='registration_register'),
|
||||
path('register/complete/', views.registration_complete, name='registration_complete'),
|
||||
path('register/closed/', views.registration_closed, name='registration_disallowed'),
|
||||
path('', include('django.contrib.auth.urls')),
|
||||
]
|
||||
|
||||
45
allianceauth/authentication/middleware.py
Normal file
45
allianceauth/authentication/middleware.py
Normal file
@@ -0,0 +1,45 @@
|
||||
from django.conf import settings
|
||||
from django.utils.deprecation import MiddlewareMixin
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class UserSettingsMiddleware(MiddlewareMixin):
|
||||
def process_response(self, request, response):
|
||||
"""Django Middleware: User Settings."""
|
||||
|
||||
# Intercept the built in django /setlang/ view and also save it to Database.
|
||||
# Note the annoymous user check, only logged in users will ever hit the DB here
|
||||
if request.path == '/i18n/setlang/' and not request.user.is_anonymous:
|
||||
try:
|
||||
request.user.profile.language = request.POST['language']
|
||||
request.user.profile.save()
|
||||
except Exception as e:
|
||||
logger.exception(e)
|
||||
|
||||
# Only act during the login flow, _after_ user is activated (step 2: post-sso)
|
||||
elif request.path == '/sso/login' and not request.user.is_anonymous:
|
||||
# Set the Language Cookie, if it doesnt match the DB
|
||||
# Null = hasnt been set by the user ever, dont act.
|
||||
try:
|
||||
if request.user.profile.language != request.LANGUAGE_CODE and request.user.profile.language is not None:
|
||||
response.set_cookie(key=settings.LANGUAGE_COOKIE_NAME,
|
||||
value=request.user.profile.language,
|
||||
max_age=settings.LANGUAGE_COOKIE_AGE)
|
||||
except Exception as e:
|
||||
logger.exception(e)
|
||||
|
||||
# Set our Night mode flag from the DB
|
||||
# Null = hasnt been set by the user ever, dont act.
|
||||
#
|
||||
# Night mode intercept is not needed in this middleware.
|
||||
# is saved direct to DB in NightModeRedirectView
|
||||
try:
|
||||
if request.user.profile.night_mode is not None:
|
||||
request.session["NIGHT_MODE"] = request.user.profile.night_mode
|
||||
except Exception as e:
|
||||
logger.exception(e)
|
||||
|
||||
return response
|
||||
@@ -0,0 +1,23 @@
|
||||
# Generated by Django 4.0.2 on 2022-02-26 03:45
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('authentication', '0019_merge_20211026_0919'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='userprofile',
|
||||
name='language',
|
||||
field=models.CharField(blank=True, choices=[('en', 'English'), ('de', 'German'), ('es', 'Spanish'), ('zh-hans', 'Chinese Simplified'), ('ru', 'Russian'), ('ko', 'Korean'), ('fr', 'French'), ('ja', 'Japanese'), ('it', 'Italian')], default='', max_length=10, verbose_name='Language'),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='userprofile',
|
||||
name='night_mode',
|
||||
field=models.BooleanField(blank=True, null=True, verbose_name='Night Mode'),
|
||||
),
|
||||
]
|
||||
@@ -2,9 +2,10 @@ import logging
|
||||
|
||||
from django.contrib.auth.models import User, Permission
|
||||
from django.db import models, transaction
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from allianceauth.eveonline.models import EveCharacter, EveCorporationInfo, EveAllianceInfo, EveFactionInfo
|
||||
from allianceauth.notifications import notify
|
||||
from django.conf import settings
|
||||
|
||||
from .managers import CharacterOwnershipManager, StateManager
|
||||
|
||||
@@ -62,9 +63,39 @@ class UserProfile(models.Model):
|
||||
class Meta:
|
||||
default_permissions = ('change',)
|
||||
|
||||
user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)
|
||||
main_character = models.OneToOneField(EveCharacter, blank=True, null=True, on_delete=models.SET_NULL)
|
||||
state = models.ForeignKey(State, on_delete=models.SET_DEFAULT, default=get_guest_state_pk)
|
||||
user = models.OneToOneField(
|
||||
User,
|
||||
related_name='profile',
|
||||
on_delete=models.CASCADE)
|
||||
main_character = models.OneToOneField(
|
||||
EveCharacter,
|
||||
blank=True,
|
||||
null=True,
|
||||
on_delete=models.SET_NULL)
|
||||
state = models.ForeignKey(
|
||||
State,
|
||||
on_delete=models.SET_DEFAULT,
|
||||
default=get_guest_state_pk)
|
||||
LANGUAGE_CHOICES = [
|
||||
('en', _('English')),
|
||||
('de', _('German')),
|
||||
('es', _('Spanish')),
|
||||
('zh-hans', _('Chinese Simplified')),
|
||||
('ru', _('Russian')),
|
||||
('ko', _('Korean')),
|
||||
('fr', _('French')),
|
||||
('ja', _('Japanese')),
|
||||
('it', _('Italian')),
|
||||
]
|
||||
language = models.CharField(
|
||||
_("Language"), max_length=10,
|
||||
choices=LANGUAGE_CHOICES,
|
||||
blank=True,
|
||||
default='')
|
||||
night_mode = models.BooleanField(
|
||||
_("Night Mode"),
|
||||
blank=True,
|
||||
null=True)
|
||||
|
||||
def assign_state(self, state=None, commit=True):
|
||||
if not state:
|
||||
@@ -93,8 +124,6 @@ class UserProfile(models.Model):
|
||||
|
||||
def __str__(self):
|
||||
return str(self.user)
|
||||
|
||||
|
||||
class CharacterOwnership(models.Model):
|
||||
class Meta:
|
||||
default_permissions = ('change', 'delete')
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import logging
|
||||
|
||||
from .models import CharacterOwnership, UserProfile, get_guest_state, State, OwnershipRecord
|
||||
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
|
||||
@@ -11,7 +16,7 @@ from allianceauth.eveonline.models import EveCharacter
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
state_changed = Signal(providing_args=['user', 'state'])
|
||||
state_changed = Signal()
|
||||
|
||||
|
||||
def trigger_state_check(state):
|
||||
@@ -71,7 +76,7 @@ def reassess_on_profile_save(sender, instance, created, *args, **kwargs):
|
||||
|
||||
@receiver(post_save, sender=User)
|
||||
def create_required_models(sender, instance, created, *args, **kwargs):
|
||||
# ensure all users have a model
|
||||
# ensure all users have our Sub-Models
|
||||
if created:
|
||||
logger.debug(f'User {instance} created. Creating default UserProfile.')
|
||||
UserProfile.objects.get_or_create(user=instance)
|
||||
|
||||
40
allianceauth/authentication/task_statistics/counters.py
Normal file
40
allianceauth/authentication/task_statistics/counters.py
Normal file
@@ -0,0 +1,40 @@
|
||||
from collections import namedtuple
|
||||
import datetime as dt
|
||||
|
||||
from .event_series import EventSeries
|
||||
|
||||
|
||||
"""Global series for counting task events."""
|
||||
succeeded_tasks = EventSeries("SUCCEEDED_TASKS")
|
||||
retried_tasks = EventSeries("RETRIED_TASKS")
|
||||
failed_tasks = EventSeries("FAILED_TASKS")
|
||||
|
||||
|
||||
_TaskCounts = namedtuple(
|
||||
"_TaskCounts", ["succeeded", "retried", "failed", "total", "earliest_task", "hours"]
|
||||
)
|
||||
|
||||
|
||||
def dashboard_results(hours: int) -> _TaskCounts:
|
||||
"""Counts of all task events within the given timeframe."""
|
||||
|
||||
def earliest_if_exists(events: EventSeries, earliest: dt.datetime) -> list:
|
||||
my_earliest = events.first_event(earliest=earliest)
|
||||
return [my_earliest] if my_earliest else []
|
||||
|
||||
earliest = dt.datetime.utcnow() - dt.timedelta(hours=hours)
|
||||
earliest_events = list()
|
||||
succeeded_count = succeeded_tasks.count(earliest=earliest)
|
||||
earliest_events += earliest_if_exists(succeeded_tasks, earliest)
|
||||
retried_count = retried_tasks.count(earliest=earliest)
|
||||
earliest_events += earliest_if_exists(retried_tasks, earliest)
|
||||
failed_count = failed_tasks.count(earliest=earliest)
|
||||
earliest_events += earliest_if_exists(failed_tasks, earliest)
|
||||
return _TaskCounts(
|
||||
succeeded=succeeded_count,
|
||||
retried=retried_count,
|
||||
failed=failed_count,
|
||||
total=succeeded_count + retried_count + failed_count,
|
||||
earliest_task=min(earliest_events) if earliest_events else None,
|
||||
hours=hours,
|
||||
)
|
||||
130
allianceauth/authentication/task_statistics/event_series.py
Normal file
130
allianceauth/authentication/task_statistics/event_series.py
Normal file
@@ -0,0 +1,130 @@
|
||||
import datetime as dt
|
||||
import logging
|
||||
from typing import List, Optional
|
||||
|
||||
from pytz import utc
|
||||
from redis import Redis, RedisError
|
||||
|
||||
from django_redis import get_redis_connection
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _RedisStub:
|
||||
"""Stub of a Redis client.
|
||||
|
||||
It's purpose is to prevent EventSeries objects from trying to access Redis
|
||||
when it is not available. e.g. when the Sphinx docs are rendered by readthedocs.org.
|
||||
"""
|
||||
|
||||
def delete(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def incr(self, *args, **kwargs):
|
||||
return 0
|
||||
|
||||
def zadd(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def zcount(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
def zrangebyscore(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
class EventSeries:
|
||||
"""API for recording and analyzing a series of events."""
|
||||
|
||||
_ROOT_KEY = "ALLIANCEAUTH_EVENT_SERIES"
|
||||
|
||||
def __init__(self, key_id: str, redis: Redis = None) -> None:
|
||||
self._redis = get_redis_connection("default") if not redis else redis
|
||||
try:
|
||||
if not self._redis.ping():
|
||||
raise RuntimeError()
|
||||
except (AttributeError, RedisError, RuntimeError):
|
||||
logger.exception(
|
||||
"Failed to establish a connection with Redis. "
|
||||
"This EventSeries object is disabled.",
|
||||
)
|
||||
self._redis = _RedisStub()
|
||||
self._key_id = str(key_id)
|
||||
self.clear()
|
||||
|
||||
@property
|
||||
def is_disabled(self):
|
||||
"""True when this object is disabled, e.g. Redis was not available at startup."""
|
||||
return isinstance(self._redis, _RedisStub)
|
||||
|
||||
@property
|
||||
def _key_counter(self):
|
||||
return f"{self._ROOT_KEY}_{self._key_id}_COUNTER"
|
||||
|
||||
@property
|
||||
def _key_sorted_set(self):
|
||||
return f"{self._ROOT_KEY}_{self._key_id}_SORTED_SET"
|
||||
|
||||
def add(self, event_time: dt.datetime = None) -> None:
|
||||
"""Add event.
|
||||
|
||||
Args:
|
||||
- event_time: timestamp of event. Will use current time if not specified.
|
||||
"""
|
||||
if not event_time:
|
||||
event_time = dt.datetime.utcnow()
|
||||
id = self._redis.incr(self._key_counter)
|
||||
self._redis.zadd(self._key_sorted_set, {id: event_time.timestamp()})
|
||||
|
||||
def all(self) -> List[dt.datetime]:
|
||||
"""List of all known events."""
|
||||
return [
|
||||
event[1]
|
||||
for event in self._redis.zrangebyscore(
|
||||
self._key_sorted_set,
|
||||
"-inf",
|
||||
"+inf",
|
||||
withscores=True,
|
||||
score_cast_func=self._cast_scores_to_dt,
|
||||
)
|
||||
]
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Clear all events."""
|
||||
self._redis.delete(self._key_sorted_set)
|
||||
self._redis.delete(self._key_counter)
|
||||
|
||||
def count(self, earliest: dt.datetime = None, latest: dt.datetime = None) -> int:
|
||||
"""Count of events, can be restricted to given timeframe.
|
||||
|
||||
Args:
|
||||
- earliest: Date of first events to count(inclusive), or -infinite if not specified
|
||||
- latest: Date of last events to count(inclusive), or +infinite if not specified
|
||||
"""
|
||||
min = "-inf" if not earliest else earliest.timestamp()
|
||||
max = "+inf" if not latest else latest.timestamp()
|
||||
return self._redis.zcount(self._key_sorted_set, min=min, max=max)
|
||||
|
||||
def first_event(self, earliest: dt.datetime = None) -> Optional[dt.datetime]:
|
||||
"""Date/Time of first event. Returns `None` if series has no events.
|
||||
|
||||
Args:
|
||||
- earliest: Date of first events to count(inclusive), or any if not specified
|
||||
"""
|
||||
min = "-inf" if not earliest else earliest.timestamp()
|
||||
event = self._redis.zrangebyscore(
|
||||
self._key_sorted_set,
|
||||
min,
|
||||
"+inf",
|
||||
withscores=True,
|
||||
start=0,
|
||||
num=1,
|
||||
score_cast_func=self._cast_scores_to_dt,
|
||||
)
|
||||
if not event:
|
||||
return None
|
||||
return event[0][1]
|
||||
|
||||
@staticmethod
|
||||
def _cast_scores_to_dt(score) -> dt.datetime:
|
||||
return dt.datetime.fromtimestamp(float(score), tz=utc)
|
||||
54
allianceauth/authentication/task_statistics/signals.py
Normal file
54
allianceauth/authentication/task_statistics/signals.py
Normal file
@@ -0,0 +1,54 @@
|
||||
from celery.signals import (
|
||||
task_failure,
|
||||
task_internal_error,
|
||||
task_retry,
|
||||
task_success,
|
||||
worker_ready
|
||||
)
|
||||
|
||||
from django.conf import settings
|
||||
|
||||
from .counters import failed_tasks, retried_tasks, succeeded_tasks
|
||||
|
||||
|
||||
def reset_counters():
|
||||
"""Reset all counters for the celery status."""
|
||||
succeeded_tasks.clear()
|
||||
failed_tasks.clear()
|
||||
retried_tasks.clear()
|
||||
|
||||
|
||||
def is_enabled() -> bool:
|
||||
return not bool(
|
||||
getattr(settings, "ALLIANCEAUTH_DASHBOARD_TASK_STATISTICS_DISABLED", False)
|
||||
)
|
||||
|
||||
|
||||
@worker_ready.connect
|
||||
def reset_counters_when_celery_restarted(*args, **kwargs):
|
||||
if is_enabled():
|
||||
reset_counters()
|
||||
|
||||
|
||||
@task_success.connect
|
||||
def record_task_succeeded(*args, **kwargs):
|
||||
if is_enabled():
|
||||
succeeded_tasks.add()
|
||||
|
||||
|
||||
@task_retry.connect
|
||||
def record_task_retried(*args, **kwargs):
|
||||
if is_enabled():
|
||||
retried_tasks.add()
|
||||
|
||||
|
||||
@task_failure.connect
|
||||
def record_task_failed(*args, **kwargs):
|
||||
if is_enabled():
|
||||
failed_tasks.add()
|
||||
|
||||
|
||||
@task_internal_error.connect
|
||||
def record_task_internal_error(*args, **kwargs):
|
||||
if is_enabled():
|
||||
failed_tasks.add()
|
||||
@@ -0,0 +1,51 @@
|
||||
import datetime as dt
|
||||
|
||||
from django.test import TestCase
|
||||
from django.utils.timezone import now
|
||||
|
||||
from allianceauth.authentication.task_statistics.counters import (
|
||||
dashboard_results,
|
||||
succeeded_tasks,
|
||||
retried_tasks,
|
||||
failed_tasks,
|
||||
)
|
||||
|
||||
|
||||
class TestDashboardResults(TestCase):
|
||||
def test_should_return_counts_for_given_timeframe_only(self):
|
||||
# given
|
||||
earliest_task = now() - dt.timedelta(minutes=15)
|
||||
succeeded_tasks.clear()
|
||||
succeeded_tasks.add(now() - dt.timedelta(hours=1, seconds=1))
|
||||
succeeded_tasks.add(earliest_task)
|
||||
succeeded_tasks.add()
|
||||
succeeded_tasks.add()
|
||||
retried_tasks.clear()
|
||||
retried_tasks.add(now() - dt.timedelta(hours=1, seconds=1))
|
||||
retried_tasks.add(now() - dt.timedelta(seconds=30))
|
||||
retried_tasks.add()
|
||||
failed_tasks.clear()
|
||||
failed_tasks.add(now() - dt.timedelta(hours=1, seconds=1))
|
||||
failed_tasks.add()
|
||||
# when
|
||||
results = dashboard_results(hours=1)
|
||||
# then
|
||||
self.assertEqual(results.succeeded, 3)
|
||||
self.assertEqual(results.retried, 2)
|
||||
self.assertEqual(results.failed, 1)
|
||||
self.assertEqual(results.total, 6)
|
||||
self.assertEqual(results.earliest_task, earliest_task)
|
||||
|
||||
def test_should_work_with_no_data(self):
|
||||
# given
|
||||
succeeded_tasks.clear()
|
||||
retried_tasks.clear()
|
||||
failed_tasks.clear()
|
||||
# when
|
||||
results = dashboard_results(hours=1)
|
||||
# then
|
||||
self.assertEqual(results.succeeded, 0)
|
||||
self.assertEqual(results.retried, 0)
|
||||
self.assertEqual(results.failed, 0)
|
||||
self.assertEqual(results.total, 0)
|
||||
self.assertIsNone(results.earliest_task)
|
||||
@@ -0,0 +1,168 @@
|
||||
import datetime as dt
|
||||
from unittest.mock import patch
|
||||
|
||||
from pytz import utc
|
||||
from redis import RedisError
|
||||
|
||||
from django.test import TestCase
|
||||
from django.utils.timezone import now
|
||||
|
||||
from allianceauth.authentication.task_statistics.event_series import (
|
||||
EventSeries,
|
||||
_RedisStub,
|
||||
)
|
||||
|
||||
MODULE_PATH = "allianceauth.authentication.task_statistics.event_series"
|
||||
|
||||
|
||||
class TestEventSeries(TestCase):
|
||||
def test_should_abort_without_redis_client(self):
|
||||
# when
|
||||
with patch(MODULE_PATH + ".get_redis_connection") as mock:
|
||||
mock.return_value = None
|
||||
events = EventSeries("dummy")
|
||||
# then
|
||||
self.assertTrue(events._redis, _RedisStub)
|
||||
self.assertTrue(events.is_disabled)
|
||||
|
||||
def test_should_disable_itself_if_redis_not_available_1(self):
|
||||
# when
|
||||
with patch(MODULE_PATH + ".get_redis_connection") as mock_get_redis_connection:
|
||||
mock_get_redis_connection.return_value.ping.side_effect = RedisError
|
||||
events = EventSeries("dummy")
|
||||
# then
|
||||
self.assertIsInstance(events._redis, _RedisStub)
|
||||
self.assertTrue(events.is_disabled)
|
||||
|
||||
def test_should_disable_itself_if_redis_not_available_2(self):
|
||||
# when
|
||||
with patch(MODULE_PATH + ".get_redis_connection") as mock_get_redis_connection:
|
||||
mock_get_redis_connection.return_value.ping.return_value = False
|
||||
events = EventSeries("dummy")
|
||||
# then
|
||||
self.assertIsInstance(events._redis, _RedisStub)
|
||||
self.assertTrue(events.is_disabled)
|
||||
|
||||
def test_should_add_event(self):
|
||||
# given
|
||||
events = EventSeries("dummy")
|
||||
# when
|
||||
events.add()
|
||||
# then
|
||||
result = events.all()
|
||||
self.assertEqual(len(result), 1)
|
||||
self.assertAlmostEqual(result[0], now(), delta=dt.timedelta(seconds=30))
|
||||
|
||||
def test_should_add_event_with_specified_time(self):
|
||||
# given
|
||||
events = EventSeries("dummy")
|
||||
my_time = dt.datetime(2021, 11, 1, 12, 15, tzinfo=utc)
|
||||
# when
|
||||
events.add(my_time)
|
||||
# then
|
||||
result = events.all()
|
||||
self.assertEqual(len(result), 1)
|
||||
self.assertAlmostEqual(result[0], my_time, delta=dt.timedelta(seconds=30))
|
||||
|
||||
def test_should_count_events(self):
|
||||
# given
|
||||
events = EventSeries("dummy")
|
||||
events.add()
|
||||
events.add()
|
||||
# when
|
||||
result = events.count()
|
||||
# then
|
||||
self.assertEqual(result, 2)
|
||||
|
||||
def test_should_count_zero(self):
|
||||
# given
|
||||
events = EventSeries("dummy")
|
||||
# when
|
||||
result = events.count()
|
||||
# then
|
||||
self.assertEqual(result, 0)
|
||||
|
||||
def test_should_count_events_within_timeframe_1(self):
|
||||
# given
|
||||
events = EventSeries("dummy")
|
||||
events.add(dt.datetime(2021, 12, 1, 12, 0, tzinfo=utc))
|
||||
events.add(dt.datetime(2021, 12, 1, 12, 10, tzinfo=utc))
|
||||
events.add(dt.datetime(2021, 12, 1, 12, 15, tzinfo=utc))
|
||||
events.add(dt.datetime(2021, 12, 1, 12, 30, tzinfo=utc))
|
||||
# when
|
||||
result = events.count(
|
||||
earliest=dt.datetime(2021, 12, 1, 12, 8, tzinfo=utc),
|
||||
latest=dt.datetime(2021, 12, 1, 12, 17, tzinfo=utc),
|
||||
)
|
||||
# then
|
||||
self.assertEqual(result, 2)
|
||||
|
||||
def test_should_count_events_within_timeframe_2(self):
|
||||
# given
|
||||
events = EventSeries("dummy")
|
||||
events.add(dt.datetime(2021, 12, 1, 12, 0, tzinfo=utc))
|
||||
events.add(dt.datetime(2021, 12, 1, 12, 10, tzinfo=utc))
|
||||
events.add(dt.datetime(2021, 12, 1, 12, 15, tzinfo=utc))
|
||||
events.add(dt.datetime(2021, 12, 1, 12, 30, tzinfo=utc))
|
||||
# when
|
||||
result = events.count(earliest=dt.datetime(2021, 12, 1, 12, 8))
|
||||
# then
|
||||
self.assertEqual(result, 3)
|
||||
|
||||
def test_should_count_events_within_timeframe_3(self):
|
||||
# given
|
||||
events = EventSeries("dummy")
|
||||
events.add(dt.datetime(2021, 12, 1, 12, 0, tzinfo=utc))
|
||||
events.add(dt.datetime(2021, 12, 1, 12, 10, tzinfo=utc))
|
||||
events.add(dt.datetime(2021, 12, 1, 12, 15, tzinfo=utc))
|
||||
events.add(dt.datetime(2021, 12, 1, 12, 30, tzinfo=utc))
|
||||
# when
|
||||
result = events.count(latest=dt.datetime(2021, 12, 1, 12, 12))
|
||||
# then
|
||||
self.assertEqual(result, 2)
|
||||
|
||||
def test_should_clear_events(self):
|
||||
# given
|
||||
events = EventSeries("dummy")
|
||||
events.add()
|
||||
events.add()
|
||||
# when
|
||||
events.clear()
|
||||
# then
|
||||
self.assertEqual(events.count(), 0)
|
||||
|
||||
def test_should_return_date_of_first_event(self):
|
||||
# given
|
||||
events = EventSeries("dummy")
|
||||
events.add(dt.datetime(2021, 12, 1, 12, 0, tzinfo=utc))
|
||||
events.add(dt.datetime(2021, 12, 1, 12, 10, tzinfo=utc))
|
||||
events.add(dt.datetime(2021, 12, 1, 12, 15, tzinfo=utc))
|
||||
events.add(dt.datetime(2021, 12, 1, 12, 30, tzinfo=utc))
|
||||
# when
|
||||
result = events.first_event()
|
||||
# then
|
||||
self.assertEqual(result, dt.datetime(2021, 12, 1, 12, 0, tzinfo=utc))
|
||||
|
||||
def test_should_return_date_of_first_event_with_range(self):
|
||||
# given
|
||||
events = EventSeries("dummy")
|
||||
events.add(dt.datetime(2021, 12, 1, 12, 0, tzinfo=utc))
|
||||
events.add(dt.datetime(2021, 12, 1, 12, 10, tzinfo=utc))
|
||||
events.add(dt.datetime(2021, 12, 1, 12, 15, tzinfo=utc))
|
||||
events.add(dt.datetime(2021, 12, 1, 12, 30, tzinfo=utc))
|
||||
# when
|
||||
result = events.first_event(
|
||||
earliest=dt.datetime(2021, 12, 1, 12, 8, tzinfo=utc)
|
||||
)
|
||||
# then
|
||||
self.assertEqual(result, dt.datetime(2021, 12, 1, 12, 10, tzinfo=utc))
|
||||
|
||||
def test_should_return_all_events(self):
|
||||
# given
|
||||
events = EventSeries("dummy")
|
||||
events.add()
|
||||
events.add()
|
||||
# when
|
||||
results = events.all()
|
||||
# then
|
||||
self.assertEqual(len(results), 2)
|
||||
@@ -0,0 +1,93 @@
|
||||
from unittest.mock import patch
|
||||
|
||||
from celery.exceptions import Retry
|
||||
|
||||
from django.test import TestCase, override_settings
|
||||
|
||||
from allianceauth.authentication.task_statistics.counters import (
|
||||
failed_tasks,
|
||||
retried_tasks,
|
||||
succeeded_tasks,
|
||||
)
|
||||
from allianceauth.authentication.task_statistics.signals import (
|
||||
reset_counters,
|
||||
is_enabled,
|
||||
)
|
||||
from allianceauth.eveonline.tasks import update_character
|
||||
|
||||
|
||||
@override_settings(
|
||||
CELERY_ALWAYS_EAGER=True,ALLIANCEAUTH_DASHBOARD_TASK_STATISTICS_DISABLED=False
|
||||
)
|
||||
class TestTaskSignals(TestCase):
|
||||
fixtures = ["disable_analytics"]
|
||||
|
||||
def test_should_record_successful_task(self):
|
||||
# given
|
||||
succeeded_tasks.clear()
|
||||
retried_tasks.clear()
|
||||
failed_tasks.clear()
|
||||
# when
|
||||
with patch(
|
||||
"allianceauth.eveonline.tasks.EveCharacter.objects.update_character"
|
||||
) as mock_update:
|
||||
mock_update.return_value = None
|
||||
update_character.delay(1)
|
||||
# then
|
||||
self.assertEqual(succeeded_tasks.count(), 1)
|
||||
self.assertEqual(retried_tasks.count(), 0)
|
||||
self.assertEqual(failed_tasks.count(), 0)
|
||||
|
||||
def test_should_record_retried_task(self):
|
||||
# given
|
||||
succeeded_tasks.clear()
|
||||
retried_tasks.clear()
|
||||
failed_tasks.clear()
|
||||
# when
|
||||
with patch(
|
||||
"allianceauth.eveonline.tasks.EveCharacter.objects.update_character"
|
||||
) as mock_update:
|
||||
mock_update.side_effect = Retry
|
||||
update_character.delay(1)
|
||||
# then
|
||||
self.assertEqual(succeeded_tasks.count(), 0)
|
||||
self.assertEqual(failed_tasks.count(), 0)
|
||||
self.assertEqual(retried_tasks.count(), 1)
|
||||
|
||||
def test_should_record_failed_task(self):
|
||||
# given
|
||||
succeeded_tasks.clear()
|
||||
retried_tasks.clear()
|
||||
failed_tasks.clear()
|
||||
# when
|
||||
with patch(
|
||||
"allianceauth.eveonline.tasks.EveCharacter.objects.update_character"
|
||||
) as mock_update:
|
||||
mock_update.side_effect = RuntimeError
|
||||
update_character.delay(1)
|
||||
# then
|
||||
self.assertEqual(succeeded_tasks.count(), 0)
|
||||
self.assertEqual(retried_tasks.count(), 0)
|
||||
self.assertEqual(failed_tasks.count(), 1)
|
||||
|
||||
def test_should_reset_counters(self):
|
||||
# given
|
||||
succeeded_tasks.add()
|
||||
retried_tasks.add()
|
||||
failed_tasks.add()
|
||||
# when
|
||||
reset_counters()
|
||||
# then
|
||||
self.assertEqual(succeeded_tasks.count(), 0)
|
||||
self.assertEqual(retried_tasks.count(), 0)
|
||||
self.assertEqual(failed_tasks.count(), 0)
|
||||
|
||||
|
||||
class TestIsEnabled(TestCase):
|
||||
@override_settings(ALLIANCEAUTH_DASHBOARD_TASK_STATISTICS_DISABLED=False)
|
||||
def test_enabled(self):
|
||||
self.assertTrue(is_enabled())
|
||||
|
||||
@override_settings(ALLIANCEAUTH_DASHBOARD_TASK_STATISTICS_DISABLED=True)
|
||||
def test_disabled(self):
|
||||
self.assertFalse(is_enabled())
|
||||
@@ -7,8 +7,8 @@
|
||||
<form class="form-signin" role="form" action="" method="POST">
|
||||
{% csrf_token %}
|
||||
{{ form|bootstrap }}
|
||||
<br/>
|
||||
<br>
|
||||
<button class="btn btn-lg btn-primary btn-block" type="submit">{% translate "Submit" %}</button>
|
||||
<br/>
|
||||
<br>
|
||||
</form>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,4 +1,17 @@
|
||||
from django.db.models.signals import (
|
||||
m2m_changed,
|
||||
post_save,
|
||||
pre_delete,
|
||||
pre_save
|
||||
)
|
||||
from django.urls import reverse
|
||||
from unittest import mock
|
||||
|
||||
MODULE_PATH = 'allianceauth.authentication'
|
||||
|
||||
|
||||
def patch(target, *args, **kwargs):
|
||||
return mock.patch(f'{MODULE_PATH}{target}', *args, **kwargs)
|
||||
|
||||
|
||||
def get_admin_change_view_url(obj: object) -> str:
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
from bs4 import BeautifulSoup
|
||||
from urllib.parse import quote
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
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
|
||||
@@ -188,7 +191,7 @@ class TestCaseWithTestData(TestCase):
|
||||
corporation_id=5432,
|
||||
corporation_name="Xavier's School for Gifted Youngsters",
|
||||
corporation_ticker='MUTNT',
|
||||
alliance_id = None,
|
||||
alliance_id=None,
|
||||
faction_id=999,
|
||||
faction_name='The X-Men',
|
||||
)
|
||||
@@ -206,6 +209,7 @@ class TestCaseWithTestData(TestCase):
|
||||
cls.user_4.profile.save()
|
||||
EveFactionInfo.objects.create(faction_id=999, faction_name='The X-Men')
|
||||
|
||||
|
||||
def make_generic_search_request(ModelClass: type, search_term: str):
|
||||
User.objects.create_superuser(
|
||||
username='superuser', password='secret', email='admin@example.com'
|
||||
@@ -218,6 +222,7 @@ def make_generic_search_request(ModelClass: type, search_term: str):
|
||||
|
||||
|
||||
class TestCharacterOwnershipAdmin(TestCaseWithTestData):
|
||||
fixtures = ["disable_analytics"]
|
||||
|
||||
def setUp(self):
|
||||
self.modeladmin = CharacterOwnershipAdmin(
|
||||
@@ -244,6 +249,7 @@ class TestCharacterOwnershipAdmin(TestCaseWithTestData):
|
||||
|
||||
|
||||
class TestOwnershipRecordAdmin(TestCaseWithTestData):
|
||||
fixtures = ["disable_analytics"]
|
||||
|
||||
def setUp(self):
|
||||
self.modeladmin = OwnershipRecordAdmin(
|
||||
@@ -270,11 +276,12 @@ class TestOwnershipRecordAdmin(TestCaseWithTestData):
|
||||
|
||||
|
||||
class TestStateAdmin(TestCaseWithTestData):
|
||||
fixtures = ["disable_analytics"]
|
||||
|
||||
def setUp(self):
|
||||
self.modeladmin = StateAdmin(
|
||||
model=User, admin_site=AdminSite()
|
||||
)
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
super().setUpClass()
|
||||
cls.modeladmin = StateAdmin(model=User, admin_site=AdminSite())
|
||||
|
||||
def test_change_view_loads_normally(self):
|
||||
User.objects.create_superuser(
|
||||
@@ -299,6 +306,7 @@ class TestStateAdmin(TestCaseWithTestData):
|
||||
|
||||
|
||||
class TestUserAdmin(TestCaseWithTestData):
|
||||
fixtures = ["disable_analytics"]
|
||||
|
||||
def setUp(self):
|
||||
self.factory = RequestFactory()
|
||||
@@ -344,7 +352,7 @@ class TestUserAdmin(TestCaseWithTestData):
|
||||
self.assertEqual(user_main_organization(self.user_3), expected)
|
||||
|
||||
def test_user_main_organization_u4(self):
|
||||
expected="Xavier's School for Gifted Youngsters<br>The X-Men"
|
||||
expected = "Xavier's School for Gifted Youngsters<br>The X-Men"
|
||||
self.assertEqual(user_main_organization(self.user_4), expected)
|
||||
|
||||
def test_characters_u1(self):
|
||||
@@ -537,6 +545,229 @@ class TestUserAdmin(TestCaseWithTestData):
|
||||
self.assertEqual(response.status_code, expected)
|
||||
|
||||
|
||||
class TestStateAdminChangeFormSuperuserExclusiveEdits(WebTest):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
super().setUpClass()
|
||||
cls.super_admin = User.objects.create_superuser("super_admin")
|
||||
cls.staff_admin = User.objects.create_user("staff_admin")
|
||||
cls.staff_admin.is_staff = True
|
||||
cls.staff_admin.save()
|
||||
cls.staff_admin = AuthUtils.add_permissions_to_user_by_name(
|
||||
[
|
||||
"authentication.add_state",
|
||||
"authentication.change_state",
|
||||
"authentication.view_state",
|
||||
],
|
||||
cls.staff_admin
|
||||
)
|
||||
cls.superuser_exclusive_fields = ["permissions",]
|
||||
|
||||
def test_should_show_all_fields_to_superuser_for_add(self):
|
||||
# given
|
||||
self.app.set_user(self.super_admin)
|
||||
page = self.app.get("/admin/authentication/state/add/")
|
||||
# when
|
||||
form = page.forms["state_form"]
|
||||
# then
|
||||
for field in self.superuser_exclusive_fields:
|
||||
with self.subTest(field=field):
|
||||
self.assertIn(field, form.fields)
|
||||
|
||||
def test_should_not_show_all_fields_to_staff_admins_for_add(self):
|
||||
# given
|
||||
self.app.set_user(self.staff_admin)
|
||||
page = self.app.get("/admin/authentication/state/add/")
|
||||
# when
|
||||
form = page.forms["state_form"]
|
||||
# then
|
||||
for field in self.superuser_exclusive_fields:
|
||||
with self.subTest(field=field):
|
||||
self.assertNotIn(field, form.fields)
|
||||
|
||||
def test_should_show_all_fields_to_superuser_for_change(self):
|
||||
# given
|
||||
self.app.set_user(self.super_admin)
|
||||
state = AuthUtils.get_member_state()
|
||||
page = self.app.get(f"/admin/authentication/state/{state.pk}/change/")
|
||||
# when
|
||||
form = page.forms["state_form"]
|
||||
# then
|
||||
for field in self.superuser_exclusive_fields:
|
||||
with self.subTest(field=field):
|
||||
self.assertIn(field, form.fields)
|
||||
|
||||
def test_should_not_show_all_fields_to_staff_admin_for_change(self):
|
||||
# given
|
||||
self.app.set_user(self.staff_admin)
|
||||
state = AuthUtils.get_member_state()
|
||||
page = self.app.get(f"/admin/authentication/state/{state.pk}/change/")
|
||||
# when
|
||||
form = page.forms["state_form"]
|
||||
# then
|
||||
for field in self.superuser_exclusive_fields:
|
||||
with self.subTest(field=field):
|
||||
self.assertNotIn(field, form.fields)
|
||||
|
||||
|
||||
class TestUserAdminChangeForm(TestCase):
|
||||
fixtures = ["disable_analytics"]
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
super().setUpClass()
|
||||
cls.modeladmin = UserAdmin(model=User, admin_site=AdminSite())
|
||||
|
||||
def test_should_show_groups_available_to_user_with_blue_state_only(self):
|
||||
# given
|
||||
superuser = User.objects.create_superuser("Super")
|
||||
user = AuthUtils.create_user("bruce_wayne")
|
||||
character = AuthUtils.add_main_character_2(
|
||||
user,
|
||||
name="Bruce Wayne",
|
||||
character_id=1001,
|
||||
corp_id=2001,
|
||||
corp_name="Wayne Technologies"
|
||||
)
|
||||
blue_state = State.objects.get(name="Blue")
|
||||
blue_state.member_characters.add(character)
|
||||
member_state = AuthUtils.get_member_state()
|
||||
group_1 = Group.objects.create(name="Group 1")
|
||||
group_2 = Group.objects.create(name="Group 2")
|
||||
group_2.authgroup.states.add(blue_state)
|
||||
group_3 = Group.objects.create(name="Group 3")
|
||||
group_3.authgroup.states.add(member_state)
|
||||
self.client.force_login(superuser)
|
||||
# when
|
||||
response = self.client.get(f"/admin/authentication/user/{user.pk}/change/")
|
||||
# then
|
||||
self.assertEqual(response.status_code, 200)
|
||||
soup = BeautifulSoup(response.rendered_content, features="html.parser")
|
||||
groups_select = soup.find("select", {"id": "id_groups"}).find_all('option')
|
||||
group_ids = {int(option["value"]) for option in groups_select}
|
||||
self.assertSetEqual(group_ids, {group_1.pk, group_2.pk})
|
||||
|
||||
|
||||
class TestUserAdminChangeFormSuperuserExclusiveEdits(WebTest):
|
||||
fixtures = ["disable_analytics"]
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
super().setUpClass()
|
||||
cls.super_admin = User.objects.create_superuser("super_admin")
|
||||
cls.staff_admin = User.objects.create_user("staff_admin")
|
||||
cls.staff_admin.is_staff = True
|
||||
cls.staff_admin.save()
|
||||
cls.staff_admin = AuthUtils.add_permissions_to_user_by_name(
|
||||
[
|
||||
"auth.change_user",
|
||||
"auth.view_user",
|
||||
"authentication.change_user",
|
||||
"authentication.change_userprofile",
|
||||
"authentication.view_user"
|
||||
],
|
||||
cls.staff_admin
|
||||
)
|
||||
cls.superuser_exclusive_fields = [
|
||||
"is_staff", "is_superuser", "user_permissions"
|
||||
]
|
||||
|
||||
def setUp(self) -> None:
|
||||
self.user = AuthUtils.create_user("bruce_wayne")
|
||||
|
||||
def test_should_show_all_fields_to_superuser_for_change(self):
|
||||
# given
|
||||
self.app.set_user(self.super_admin)
|
||||
|
||||
page = self.app.get(f"/admin/authentication/user/{self.user.pk}/change/")
|
||||
# when
|
||||
form = page.forms["user_form"]
|
||||
# then
|
||||
for field in self.superuser_exclusive_fields:
|
||||
with self.subTest(field=field):
|
||||
self.assertIn(field, form.fields)
|
||||
|
||||
def test_should_not_show_all_fields_to_staff_admin_for_change(self):
|
||||
# given
|
||||
self.app.set_user(self.staff_admin)
|
||||
page = self.app.get(f"/admin/authentication/user/{self.user.pk}/change/")
|
||||
# when
|
||||
form = page.forms["user_form"]
|
||||
# then
|
||||
for field in self.superuser_exclusive_fields:
|
||||
with self.subTest(field=field):
|
||||
self.assertNotIn(field, form.fields)
|
||||
|
||||
def test_should_allow_super_admin_to_add_restricted_group_to_user(self):
|
||||
# given
|
||||
self.app.set_user(self.super_admin)
|
||||
group_restricted = Group.objects.create(name="restricted group")
|
||||
group_restricted.authgroup.restricted = True
|
||||
group_restricted.authgroup.save()
|
||||
page = self.app.get(f"/admin/authentication/user/{self.user.pk}/change/")
|
||||
form = page.forms["user_form"]
|
||||
# when
|
||||
form["groups"].select_multiple(texts=["restricted group"])
|
||||
response = form.submit("save")
|
||||
# then
|
||||
self.assertEqual(response.status_code, 302)
|
||||
self.user.refresh_from_db()
|
||||
self.assertIn(
|
||||
"restricted group", self.user.groups.values_list("name", flat=True)
|
||||
)
|
||||
|
||||
def test_should_not_allow_staff_admin_to_add_restricted_group_to_user(self):
|
||||
# given
|
||||
self.app.set_user(self.staff_admin)
|
||||
group_restricted = Group.objects.create(name="restricted group")
|
||||
group_restricted.authgroup.restricted = True
|
||||
group_restricted.authgroup.save()
|
||||
page = self.app.get(f"/admin/authentication/user/{self.user.pk}/change/")
|
||||
form = page.forms["user_form"]
|
||||
# when
|
||||
form["groups"].select_multiple(texts=["restricted group"])
|
||||
response = form.submit("save")
|
||||
# then
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertIn(
|
||||
"You are not allowed to add or remove these restricted groups",
|
||||
response.text
|
||||
)
|
||||
|
||||
def test_should_not_allow_staff_admin_to_remove_restricted_group_from_user(self):
|
||||
# given
|
||||
self.app.set_user(self.staff_admin)
|
||||
group_restricted = Group.objects.create(name="restricted group")
|
||||
group_restricted.authgroup.restricted = True
|
||||
group_restricted.authgroup.save()
|
||||
self.user.groups.add(group_restricted)
|
||||
page = self.app.get(f"/admin/authentication/user/{self.user.pk}/change/")
|
||||
form = page.forms["user_form"]
|
||||
# when
|
||||
form["groups"].select_multiple(texts=[])
|
||||
response = form.submit("save")
|
||||
# then
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertIn(
|
||||
"You are not allowed to add or remove these restricted groups",
|
||||
response.text
|
||||
)
|
||||
|
||||
def test_should_allow_staff_admin_to_add_normal_group_to_user(self):
|
||||
# given
|
||||
self.app.set_user(self.super_admin)
|
||||
Group.objects.create(name="normal group")
|
||||
page = self.app.get(f"/admin/authentication/user/{self.user.pk}/change/")
|
||||
form = page.forms["user_form"]
|
||||
# when
|
||||
form["groups"].select_multiple(texts=["normal group"])
|
||||
response = form.submit("save")
|
||||
# then
|
||||
self.assertEqual(response.status_code, 302)
|
||||
self.user.refresh_from_db()
|
||||
self.assertIn("normal group", self.user.groups.values_list("name", flat=True))
|
||||
|
||||
|
||||
class TestMakeServicesHooksActions(TestCaseWithTestData):
|
||||
|
||||
class MyServicesHookTypeA(ServicesHook):
|
||||
|
||||
175
allianceauth/authentication/tests/test_middleware.py
Normal file
175
allianceauth/authentication/tests/test_middleware.py
Normal file
@@ -0,0 +1,175 @@
|
||||
from unittest import mock
|
||||
from allianceauth.authentication.middleware import UserSettingsMiddleware
|
||||
from unittest.mock import Mock
|
||||
from django.http import HttpResponse
|
||||
|
||||
from django.test.testcases import TestCase
|
||||
|
||||
|
||||
class TestUserSettingsMiddlewareSaveLang(TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.middleware = UserSettingsMiddleware(HttpResponse)
|
||||
self.request = Mock()
|
||||
self.request.headers = {
|
||||
"User-Agent": "AUTOMATED TEST"
|
||||
}
|
||||
self.request.path = '/i18n/setlang/'
|
||||
self.request.POST = {
|
||||
'language': 'fr'
|
||||
}
|
||||
self.request.user.profile.language = 'de'
|
||||
self.request.user.is_anonymous = False
|
||||
self.response = Mock()
|
||||
self.response.content = 'hello world'
|
||||
|
||||
def test_middleware_passthrough(self):
|
||||
"""
|
||||
Simply tests the middleware runs cleanly
|
||||
"""
|
||||
response = self.middleware.process_response(
|
||||
self.request,
|
||||
self.response
|
||||
)
|
||||
self.assertEqual(self.response, response)
|
||||
|
||||
def test_middleware_save_language_false_anonymous(self):
|
||||
"""
|
||||
Ensures the middleware wont change the usersettings
|
||||
of a non-existent (anonymous) user
|
||||
"""
|
||||
self.request.user.is_anonymous = True
|
||||
response = self.middleware.process_response(
|
||||
self.request,
|
||||
self.response
|
||||
)
|
||||
self.assertEqual(self.request.user.profile.language, 'de')
|
||||
self.assertFalse(self.request.user.profile.save.called)
|
||||
self.assertEqual(self.request.user.profile.save.call_count, 0)
|
||||
|
||||
def test_middleware_save_language_new(self):
|
||||
"""
|
||||
does the middleware change a language not set in the DB
|
||||
"""
|
||||
self.request.user.profile.language = None
|
||||
response = self.middleware.process_response(
|
||||
self.request,
|
||||
self.response
|
||||
)
|
||||
self.assertEqual(self.request.user.profile.language, 'fr')
|
||||
self.assertTrue(self.request.user.profile.save.called)
|
||||
self.assertEqual(self.request.user.profile.save.call_count, 1)
|
||||
|
||||
def test_middleware_save_language_changed(self):
|
||||
"""
|
||||
Tests the middleware will change a language setting
|
||||
"""
|
||||
response = self.middleware.process_response(
|
||||
self.request,
|
||||
self.response
|
||||
)
|
||||
self.assertEqual(self.request.user.profile.language, 'fr')
|
||||
self.assertTrue(self.request.user.profile.save.called)
|
||||
self.assertEqual(self.request.user.profile.save.call_count, 1)
|
||||
|
||||
|
||||
class TestUserSettingsMiddlewareLoginFlow(TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.middleware = UserSettingsMiddleware(HttpResponse)
|
||||
self.request = Mock()
|
||||
self.request.headers = {
|
||||
"User-Agent": "AUTOMATED TEST"
|
||||
}
|
||||
self.request.path = '/sso/login'
|
||||
self.request.session = {
|
||||
'NIGHT_MODE': False
|
||||
}
|
||||
self.request.LANGUAGE_CODE = 'en'
|
||||
self.request.user.profile.language = 'de'
|
||||
self.request.user.profile.night_mode = True
|
||||
self.request.user.is_anonymous = False
|
||||
self.response = Mock()
|
||||
self.response.content = 'hello world'
|
||||
|
||||
def test_middleware_passthrough(self):
|
||||
"""
|
||||
Simply tests the middleware runs cleanly
|
||||
"""
|
||||
middleware_response = self.middleware.process_response(
|
||||
self.request,
|
||||
self.response
|
||||
)
|
||||
self.assertEqual(self.response, middleware_response)
|
||||
|
||||
def test_middleware_sets_language_cookie_true_no_cookie(self):
|
||||
"""
|
||||
tests the middleware will set a cookie, while none is set
|
||||
"""
|
||||
self.request.LANGUAGE_CODE = None
|
||||
middleware_response = self.middleware.process_response(
|
||||
self.request,
|
||||
self.response
|
||||
)
|
||||
self.assertTrue(middleware_response.set_cookie.called)
|
||||
self.assertEqual(middleware_response.set_cookie.call_count, 1)
|
||||
args, kwargs = middleware_response.set_cookie.call_args
|
||||
self.assertEqual(kwargs['value'], 'de')
|
||||
|
||||
def test_middleware_sets_language_cookie_true_wrong_cookie(self):
|
||||
"""
|
||||
tests the middleware will set a cookie, while a different value is set
|
||||
"""
|
||||
middleware_response = self.middleware.process_response(
|
||||
self.request,
|
||||
self.response
|
||||
)
|
||||
self.assertTrue(middleware_response.set_cookie.called)
|
||||
self.assertEqual(middleware_response.set_cookie.call_count, 1)
|
||||
args, kwargs = middleware_response.set_cookie.call_args
|
||||
self.assertEqual(kwargs['value'], 'de')
|
||||
|
||||
def test_middleware_sets_language_cookie_false_anonymous(self):
|
||||
"""
|
||||
ensures the middleware wont set a value for a non existent user (anonymous)
|
||||
"""
|
||||
self.request.user.is_anonymous = True
|
||||
middleware_response = self.middleware.process_response(
|
||||
self.request,
|
||||
self.response
|
||||
)
|
||||
self.assertFalse = middleware_response.set_cookie.called
|
||||
self.assertEqual(middleware_response.set_cookie.call_count, 0)
|
||||
|
||||
def test_middleware_sets_language_cookie_false_already_set(self):
|
||||
"""
|
||||
tests the middleware skips setting the cookie, if its already set correctly
|
||||
"""
|
||||
self.request.user.profile.language = 'en'
|
||||
middleware_response = self.middleware.process_response(
|
||||
self.request,
|
||||
self.response
|
||||
)
|
||||
self.assertFalse = middleware_response.set_cookie.called
|
||||
self.assertEqual(middleware_response.set_cookie.call_count, 0)
|
||||
|
||||
def test_middleware_sets_night_mode_not_set(self):
|
||||
"""
|
||||
tests the middleware will set night_mode if not set
|
||||
"""
|
||||
self.request.session = {}
|
||||
response = self.middleware.process_response(
|
||||
self.request,
|
||||
self.response
|
||||
)
|
||||
self.assertEqual(self.request.session["NIGHT_MODE"], True)
|
||||
|
||||
def test_middleware_sets_night_mode_set(self):
|
||||
"""
|
||||
tests the middleware will set night_mode if set.
|
||||
"""
|
||||
response = self.middleware.process_response(
|
||||
self.request,
|
||||
self.response
|
||||
)
|
||||
self.assertEqual(self.request.session["NIGHT_MODE"], True)
|
||||
94
allianceauth/authentication/tests/test_signals.py
Normal file
94
allianceauth/authentication/tests/test_signals.py
Normal file
@@ -0,0 +1,94 @@
|
||||
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.tests.auth_utils import AuthUtils
|
||||
|
||||
from django.test.testcases import TestCase
|
||||
from unittest.mock import Mock
|
||||
from . import patch
|
||||
|
||||
|
||||
class TestUserProfileSignals(TestCase):
|
||||
|
||||
def setUp(self):
|
||||
state = AuthUtils.get_member_state()
|
||||
|
||||
self.char = EveCharacter.objects.create(
|
||||
character_id='1234',
|
||||
character_name='test character',
|
||||
corporation_id='2345',
|
||||
corporation_name='test corp',
|
||||
corporation_ticker='tickr',
|
||||
alliance_id='3456',
|
||||
alliance_name='alliance name',
|
||||
)
|
||||
|
||||
self.alliance = EveAllianceInfo.objects.create(
|
||||
alliance_id='3456',
|
||||
alliance_name='alliance name',
|
||||
alliance_ticker='TIKR',
|
||||
executor_corp_id='2345',
|
||||
)
|
||||
|
||||
self.corp = EveCorporationInfo.objects.create(
|
||||
corporation_id='2345',
|
||||
corporation_name='corp name',
|
||||
corporation_ticker='TIKK',
|
||||
member_count=10,
|
||||
alliance=self.alliance,
|
||||
)
|
||||
|
||||
state.member_alliances.add(self.alliance)
|
||||
state.member_corporations.add(self.corp)
|
||||
|
||||
self.member = AuthUtils.create_user('test user')
|
||||
self.member.profile.main_character = self.char
|
||||
self.member.profile.save()
|
||||
|
||||
@patch('.signals.create_required_models')
|
||||
def test_create_required_models_triggered_true(
|
||||
self, create_required_models):
|
||||
"""
|
||||
Create a User object here,
|
||||
to generate UserProfile models
|
||||
"""
|
||||
post_save.connect(create_required_models, sender=User)
|
||||
AuthUtils.create_user('test_create_required_models_triggered')
|
||||
self.assertTrue = create_required_models.called
|
||||
self.assertEqual(create_required_models.call_count, 1)
|
||||
|
||||
user = User.objects.get(username='test_create_required_models_triggered')
|
||||
self.assertIsNot(UserProfile.objects.get(user=user), False)
|
||||
|
||||
@patch('.signals.create_required_models')
|
||||
def test_create_required_models_triggered_false(
|
||||
self, create_required_models):
|
||||
"""
|
||||
Only call a User object Update here,
|
||||
which does not need to generate UserProfile models
|
||||
"""
|
||||
post_save.connect(create_required_models, sender=User)
|
||||
char = EveCharacter.objects.create(
|
||||
character_id='1266',
|
||||
character_name='test character2',
|
||||
corporation_id='2345',
|
||||
corporation_name='test corp',
|
||||
corporation_ticker='tickr',
|
||||
alliance_id='3456',
|
||||
alliance_name='alliance name',
|
||||
)
|
||||
self.member.profile.main_character = char
|
||||
self.member.profile.save()
|
||||
|
||||
self.assertTrue = create_required_models.called
|
||||
self.assertEqual(create_required_models.call_count, 0)
|
||||
self.assertIsNot(UserProfile.objects.get(user=self.member), False)
|
||||
@@ -55,7 +55,6 @@ TEST_VERSION = '2.6.5'
|
||||
|
||||
|
||||
class TestStatusOverviewTag(TestCase):
|
||||
|
||||
@patch(MODULE_PATH + '.admin_status.__version__', TEST_VERSION)
|
||||
@patch(MODULE_PATH + '.admin_status._fetch_celery_queue_length')
|
||||
@patch(MODULE_PATH + '.admin_status._current_version_summary')
|
||||
@@ -66,6 +65,7 @@ class TestStatusOverviewTag(TestCase):
|
||||
mock_current_version_info,
|
||||
mock_fetch_celery_queue_length
|
||||
):
|
||||
# given
|
||||
notifications = {
|
||||
'notifications': GITHUB_NOTIFICATION_ISSUES[:5]
|
||||
}
|
||||
@@ -83,22 +83,20 @@ class TestStatusOverviewTag(TestCase):
|
||||
}
|
||||
mock_current_version_info.return_value = version_info
|
||||
mock_fetch_celery_queue_length.return_value = 3
|
||||
|
||||
# when
|
||||
result = status_overview()
|
||||
expected = {
|
||||
'notifications': GITHUB_NOTIFICATION_ISSUES[:5],
|
||||
'latest_major': True,
|
||||
'latest_minor': True,
|
||||
'latest_patch': True,
|
||||
'latest_beta': False,
|
||||
'current_version': TEST_VERSION,
|
||||
'latest_major_version': '2.4.5',
|
||||
'latest_minor_version': '2.4.0',
|
||||
'latest_patch_version': '2.4.5',
|
||||
'latest_beta_version': '2.4.4a1',
|
||||
'task_queue_length': 3,
|
||||
}
|
||||
self.assertEqual(result, expected)
|
||||
# then
|
||||
self.assertEqual(result["notifications"], GITHUB_NOTIFICATION_ISSUES[:5])
|
||||
self.assertTrue(result["latest_major"])
|
||||
self.assertTrue(result["latest_minor"])
|
||||
self.assertTrue(result["latest_patch"])
|
||||
self.assertFalse(result["latest_beta"])
|
||||
self.assertEqual(result["current_version"], TEST_VERSION)
|
||||
self.assertEqual(result["latest_major_version"], '2.4.5')
|
||||
self.assertEqual(result["latest_minor_version"], '2.4.0')
|
||||
self.assertEqual(result["latest_patch_version"], '2.4.5')
|
||||
self.assertEqual(result["latest_beta_version"], '2.4.4a1')
|
||||
self.assertEqual(result["task_queue_length"], 3)
|
||||
|
||||
|
||||
class TestNotifications(TestCase):
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
from django.conf.urls import url
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.urls import path
|
||||
from django.views.generic.base import TemplateView
|
||||
|
||||
from . import views
|
||||
@@ -7,21 +6,21 @@ from . import views
|
||||
app_name = 'authentication'
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^$', views.index, name='index'),
|
||||
url(
|
||||
r'^account/login/$',
|
||||
path('', views.index, name='index'),
|
||||
path(
|
||||
'account/login/',
|
||||
TemplateView.as_view(template_name='public/login.html'),
|
||||
name='login'
|
||||
),
|
||||
url(
|
||||
r'^account/characters/main/$',
|
||||
path(
|
||||
'account/characters/main/',
|
||||
views.main_character_change,
|
||||
name='change_main_character'
|
||||
),
|
||||
url(
|
||||
r'^account/characters/add/$',
|
||||
path(
|
||||
'account/characters/add/',
|
||||
views.add_character,
|
||||
name='add_character'
|
||||
),
|
||||
url(r'^dashboard/$', views.dashboard, name='dashboard'),
|
||||
path('dashboard/', views.dashboard, name='dashboard'),
|
||||
]
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
default_app_config = 'allianceauth.corputils.apps.CorpUtilsConfig'
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from allianceauth.services.hooks import MenuItemHook, UrlHook
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from allianceauth import hooks
|
||||
from allianceauth.corputils import urls
|
||||
|
||||
|
||||
@@ -193,6 +193,8 @@
|
||||
"columnDefs": [
|
||||
{ "sortable": false, "targets": [1] },
|
||||
],
|
||||
"stateSave": true,
|
||||
"stateDuration": 0
|
||||
});
|
||||
$('#table-members').DataTable({
|
||||
"columnDefs": [
|
||||
@@ -200,6 +202,8 @@
|
||||
{ "sortable": false, "targets": [0, 2] },
|
||||
],
|
||||
"order": [[ 1, "asc" ]],
|
||||
"stateSave": true,
|
||||
"stateDuration": 0
|
||||
});
|
||||
$('#table-unregistered').DataTable({
|
||||
"columnDefs": [
|
||||
@@ -207,6 +211,8 @@
|
||||
{ "sortable": false, "targets": [0, 2] },
|
||||
],
|
||||
"order": [[ 1, "asc" ]],
|
||||
"stateSave": true,
|
||||
"stateDuration": 0
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
@@ -43,6 +43,9 @@
|
||||
{% endblock %}
|
||||
{% block extra_script %}
|
||||
$(document).ready(function(){
|
||||
$('#table-search').DataTable();
|
||||
$('#table-search').DataTable({
|
||||
"stateSave": true,
|
||||
"stateDuration": 0
|
||||
});
|
||||
});
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
from django.conf.urls import url
|
||||
|
||||
from django.urls import path
|
||||
from . import views
|
||||
|
||||
app_name = 'corputils'
|
||||
urlpatterns = [
|
||||
url(r'^$', views.corpstats_view, name='view'),
|
||||
url(r'^add/$', views.corpstats_add, name='add'),
|
||||
url(r'^(?P<corp_id>(\d)*)/$', views.corpstats_view, name='view_corp'),
|
||||
url(r'^(?P<corp_id>(\d)+)/update/$', views.corpstats_update, name='update'),
|
||||
url(r'^search/$', views.corpstats_search, name='search'),
|
||||
]
|
||||
path('', views.corpstats_view, name='view'),
|
||||
path('add/', views.corpstats_add, name='add'),
|
||||
path('<int:corp_id>/', views.corpstats_view, name='view_corp'),
|
||||
path('<int:corp_id>/update/', views.corpstats_update, name='update'),
|
||||
path('search/', views.corpstats_search, name='search'),
|
||||
]
|
||||
|
||||
@@ -6,7 +6,7 @@ from django.contrib.auth.decorators import login_required, permission_required,
|
||||
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
|
||||
from django.db import IntegrityError
|
||||
from django.shortcuts import render, redirect, get_object_or_404
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from esi.decorators import token_required
|
||||
from allianceauth.eveonline.models import EveCharacter, EveCorporationInfo
|
||||
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
default_app_config = 'allianceauth.eveonline.apps.EveonlineConfig'
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
default_app_config = 'allianceauth.eveonline.autogroups.apps.EveAutogroupsConfig'
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 3.2.10 on 2022-01-05 18:44
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('eveonline', '0015_factions'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='evecharacter',
|
||||
name='character_name',
|
||||
field=models.CharField(db_index=True, max_length=254),
|
||||
),
|
||||
]
|
||||
@@ -1,16 +1,32 @@
|
||||
from django.db import models
|
||||
import logging
|
||||
from typing import Union
|
||||
|
||||
from .managers import EveCharacterManager, EveCharacterProviderManager
|
||||
from .managers import EveCorporationManager, EveCorporationProviderManager
|
||||
from .managers import EveAllianceManager, EveAllianceProviderManager
|
||||
from django.core.exceptions import ObjectDoesNotExist
|
||||
from django.db import models
|
||||
from esi.models import Token
|
||||
|
||||
from allianceauth.notifications import notify
|
||||
|
||||
from . import providers
|
||||
from .evelinks import eveimageserver
|
||||
from .managers import (
|
||||
EveAllianceManager,
|
||||
EveAllianceProviderManager,
|
||||
EveCharacterManager,
|
||||
EveCharacterProviderManager,
|
||||
EveCorporationManager,
|
||||
EveCorporationProviderManager,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_DEFAULT_IMAGE_SIZE = 32
|
||||
DOOMHEIM_CORPORATION_ID = 1000001
|
||||
|
||||
|
||||
class EveFactionInfo(models.Model):
|
||||
"""A faction in Eve Online."""
|
||||
|
||||
faction_id = models.PositiveIntegerField(unique=True, db_index=True)
|
||||
faction_name = models.CharField(max_length=254, unique=True)
|
||||
|
||||
@@ -52,6 +68,8 @@ class EveFactionInfo(models.Model):
|
||||
|
||||
|
||||
class EveAllianceInfo(models.Model):
|
||||
"""An alliance in Eve Online."""
|
||||
|
||||
alliance_id = models.PositiveIntegerField(unique=True)
|
||||
alliance_name = models.CharField(max_length=254, unique=True)
|
||||
alliance_ticker = models.CharField(max_length=254)
|
||||
@@ -68,13 +86,12 @@ class EveAllianceInfo(models.Model):
|
||||
for corp_id in alliance.corp_ids:
|
||||
if not EveCorporationInfo.objects.filter(corporation_id=corp_id).exists():
|
||||
EveCorporationInfo.objects.create_corporation(corp_id)
|
||||
EveCorporationInfo.objects.filter(
|
||||
corporation_id__in=alliance.corp_ids).update(alliance=self
|
||||
EveCorporationInfo.objects.filter(corporation_id__in=alliance.corp_ids).update(
|
||||
alliance=self
|
||||
)
|
||||
EveCorporationInfo.objects\
|
||||
.filter(alliance=self)\
|
||||
.exclude(corporation_id__in=alliance.corp_ids)\
|
||||
.update(alliance=None)
|
||||
EveCorporationInfo.objects.filter(alliance=self).exclude(
|
||||
corporation_id__in=alliance.corp_ids
|
||||
).update(alliance=None)
|
||||
|
||||
def update_alliance(self, alliance: providers.Alliance = None):
|
||||
if alliance is None:
|
||||
@@ -119,6 +136,8 @@ class EveAllianceInfo(models.Model):
|
||||
|
||||
|
||||
class EveCorporationInfo(models.Model):
|
||||
"""A corporation in Eve Online."""
|
||||
|
||||
corporation_id = models.PositiveIntegerField(unique=True)
|
||||
corporation_name = models.CharField(max_length=254, unique=True)
|
||||
corporation_ticker = models.CharField(max_length=254)
|
||||
@@ -182,8 +201,10 @@ class EveCorporationInfo(models.Model):
|
||||
|
||||
|
||||
class EveCharacter(models.Model):
|
||||
"""A character in Eve Online."""
|
||||
|
||||
character_id = models.PositiveIntegerField(unique=True)
|
||||
character_name = models.CharField(max_length=254, unique=True)
|
||||
character_name = models.CharField(max_length=254, db_index=True)
|
||||
corporation_id = models.PositiveIntegerField()
|
||||
corporation_name = models.CharField(max_length=254)
|
||||
corporation_ticker = models.CharField(max_length=5)
|
||||
@@ -198,12 +219,20 @@ class EveCharacter(models.Model):
|
||||
|
||||
class Meta:
|
||||
indexes = [
|
||||
models.Index(fields=['corporation_id',]),
|
||||
models.Index(fields=['alliance_id',]),
|
||||
models.Index(fields=['corporation_name',]),
|
||||
models.Index(fields=['alliance_name',]),
|
||||
models.Index(fields=['faction_id',]),
|
||||
]
|
||||
models.Index(fields=['corporation_id',]),
|
||||
models.Index(fields=['alliance_id',]),
|
||||
models.Index(fields=['corporation_name',]),
|
||||
models.Index(fields=['alliance_name',]),
|
||||
models.Index(fields=['faction_id',]),
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return self.character_name
|
||||
|
||||
@property
|
||||
def is_biomassed(self) -> bool:
|
||||
"""Whether this character is dead or not."""
|
||||
return self.corporation_id == DOOMHEIM_CORPORATION_ID
|
||||
|
||||
@property
|
||||
def alliance(self) -> Union[EveAllianceInfo, None]:
|
||||
@@ -249,10 +278,36 @@ class EveCharacter(models.Model):
|
||||
self.faction_id = character.faction.id
|
||||
self.faction_name = character.faction.name
|
||||
self.save()
|
||||
if self.is_biomassed:
|
||||
self._remove_tokens_of_biomassed_character()
|
||||
return self
|
||||
|
||||
def __str__(self):
|
||||
return self.character_name
|
||||
def _remove_tokens_of_biomassed_character(self) -> None:
|
||||
"""Remove tokens of this biomassed character."""
|
||||
try:
|
||||
user = self.character_ownership.user
|
||||
except ObjectDoesNotExist:
|
||||
return
|
||||
tokens_to_delete = Token.objects.filter(character_id=self.character_id)
|
||||
tokens_count = tokens_to_delete.count()
|
||||
if not tokens_count:
|
||||
return
|
||||
tokens_to_delete.delete()
|
||||
logger.info(
|
||||
"%d tokens from user %s for biomassed character %s [id:%s] deleted.",
|
||||
tokens_count,
|
||||
user,
|
||||
self,
|
||||
self.character_id,
|
||||
)
|
||||
notify(
|
||||
user=user,
|
||||
title=f"Character {self} biomassed",
|
||||
message=(
|
||||
f"Your former character {self} has been biomassed "
|
||||
"and has been removed from the list of your alts."
|
||||
)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def generic_portrait_url(
|
||||
@@ -336,7 +391,6 @@ class EveCharacter(models.Model):
|
||||
"""image URL for alliance of this character or empty string"""
|
||||
return self.alliance_logo_url(256)
|
||||
|
||||
|
||||
def faction_logo_url(self, size=_DEFAULT_IMAGE_SIZE) -> str:
|
||||
"""image URL for alliance of this character or empty string"""
|
||||
if self.faction_id:
|
||||
|
||||
@@ -170,7 +170,7 @@ class EveProvider:
|
||||
"""
|
||||
:return: an ItemType object for the given ID
|
||||
"""
|
||||
raise NotImplemented()
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
class EveSwaggerProvider(EveProvider):
|
||||
@@ -207,7 +207,8 @@ class EveSwaggerProvider(EveProvider):
|
||||
def __str__(self):
|
||||
return 'esi'
|
||||
|
||||
def get_alliance(self, alliance_id):
|
||||
def get_alliance(self, alliance_id: int) -> Alliance:
|
||||
"""Fetch alliance from ESI."""
|
||||
try:
|
||||
data = self.client.Alliance.get_alliances_alliance_id(alliance_id=alliance_id).result()
|
||||
corps = self.client.Alliance.get_alliances_alliance_id_corporations(alliance_id=alliance_id).result()
|
||||
@@ -223,7 +224,8 @@ class EveSwaggerProvider(EveProvider):
|
||||
except HTTPNotFound:
|
||||
raise ObjectNotFound(alliance_id, 'alliance')
|
||||
|
||||
def get_corp(self, corp_id):
|
||||
def get_corp(self, corp_id: int) -> Corporation:
|
||||
"""Fetch corporation from ESI."""
|
||||
try:
|
||||
data = self.client.Corporation.get_corporations_corporation_id(corporation_id=corp_id).result()
|
||||
model = Corporation(
|
||||
@@ -239,29 +241,43 @@ class EveSwaggerProvider(EveProvider):
|
||||
except HTTPNotFound:
|
||||
raise ObjectNotFound(corp_id, 'corporation')
|
||||
|
||||
def get_character(self, character_id):
|
||||
def get_character(self, character_id: int) -> Character:
|
||||
"""Fetch character from ESI."""
|
||||
try:
|
||||
data = self.client.Character.get_characters_character_id(character_id=character_id).result()
|
||||
character_name = self._fetch_character_name(character_id)
|
||||
affiliation = self.client.Character.post_characters_affiliation(characters=[character_id]).result()[0]
|
||||
|
||||
model = Character(
|
||||
id=character_id,
|
||||
name=data['name'],
|
||||
name=character_name,
|
||||
corp_id=affiliation['corporation_id'],
|
||||
alliance_id=affiliation['alliance_id'] if 'alliance_id' in affiliation else None,
|
||||
faction_id=affiliation['faction_id'] if 'faction_id' in affiliation else None,
|
||||
)
|
||||
return model
|
||||
except (HTTPNotFound, HTTPUnprocessableEntity):
|
||||
except (HTTPNotFound, HTTPUnprocessableEntity, ObjectNotFound):
|
||||
raise ObjectNotFound(character_id, 'character')
|
||||
|
||||
def _fetch_character_name(self, character_id: int) -> str:
|
||||
"""Fetch character name from ESI."""
|
||||
data = self.client.Universe.post_universe_names(ids=[character_id]).result()
|
||||
character = data.pop() if data else None
|
||||
if (
|
||||
not character
|
||||
or character["category"] != "character"
|
||||
or character["id"] != character_id
|
||||
):
|
||||
raise ObjectNotFound(character_id, 'character')
|
||||
return character["name"]
|
||||
|
||||
def get_all_factions(self):
|
||||
"""Fetch all factions from ESI."""
|
||||
if not self._faction_list:
|
||||
self._faction_list = self.client.Universe.get_universe_factions().result()
|
||||
return self._faction_list
|
||||
|
||||
def get_faction(self, faction_id):
|
||||
faction_id=int(faction_id)
|
||||
def get_faction(self, faction_id: int):
|
||||
"""Fetch faction from ESI."""
|
||||
faction_id = int(faction_id)
|
||||
try:
|
||||
if not self._faction_list:
|
||||
_ = self.get_all_factions()
|
||||
@@ -273,7 +289,8 @@ class EveSwaggerProvider(EveProvider):
|
||||
except (HTTPNotFound, HTTPUnprocessableEntity, KeyError):
|
||||
raise ObjectNotFound(faction_id, 'faction')
|
||||
|
||||
def get_itemtype(self, type_id):
|
||||
def get_itemtype(self, type_id: int) -> ItemType:
|
||||
"""Fetch inventory item from ESI."""
|
||||
try:
|
||||
data = self.client.Universe.get_universe_types_type_id(type_id=type_id).result()
|
||||
return ItemType(id=type_id, name=data['name'])
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import logging
|
||||
|
||||
from celery import shared_task
|
||||
from .models import EveAllianceInfo
|
||||
from .models import EveCharacter
|
||||
from .models import EveCorporationInfo
|
||||
|
||||
from .models import EveAllianceInfo, EveCharacter, EveCorporationInfo
|
||||
from . import providers
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TASK_PRIORITY = 7
|
||||
@@ -32,8 +31,8 @@ def update_alliance(alliance_id):
|
||||
|
||||
|
||||
@shared_task
|
||||
def update_character(character_id):
|
||||
"""Update given character from ESI"""
|
||||
def update_character(character_id: int) -> None:
|
||||
"""Update given character from ESI."""
|
||||
EveCharacter.objects.update_character(character_id)
|
||||
|
||||
|
||||
@@ -41,7 +40,7 @@ def update_character(character_id):
|
||||
def run_model_update():
|
||||
"""Update all alliances, corporations and characters from ESI"""
|
||||
|
||||
# update existing corp models
|
||||
#update existing corp models
|
||||
for corp in EveCorporationInfo.objects.all().values('corporation_id'):
|
||||
update_corp.apply_async(args=[corp['corporation_id']], priority=TASK_PRIORITY)
|
||||
|
||||
@@ -65,17 +64,17 @@ def update_character_chunk(character_ids_chunk: list):
|
||||
.post_characters_affiliation(characters=character_ids_chunk).result()
|
||||
character_names = providers.provider.client.Universe\
|
||||
.post_universe_names(ids=character_ids_chunk).result()
|
||||
except:
|
||||
except OSError:
|
||||
logger.info("Failed to bulk update characters. Attempting single updates")
|
||||
for character_id in character_ids_chunk:
|
||||
update_character.apply_async(
|
||||
args=[character_id], priority=TASK_PRIORITY
|
||||
)
|
||||
args=[character_id], priority=TASK_PRIORITY
|
||||
)
|
||||
return
|
||||
|
||||
affiliations = {
|
||||
affiliation.get('character_id'): affiliation
|
||||
for affiliation in affiliations_raw
|
||||
affiliation.get('character_id'): affiliation
|
||||
for affiliation in affiliations_raw
|
||||
}
|
||||
# add character names to affiliations
|
||||
for character in character_names:
|
||||
@@ -108,5 +107,5 @@ def update_character_chunk(character_ids_chunk: list):
|
||||
|
||||
if corp_changed or alliance_changed or name_changed:
|
||||
update_character.apply_async(
|
||||
args=[character.get('character_id')], priority=TASK_PRIORITY
|
||||
)
|
||||
args=[character.get('character_id')], priority=TASK_PRIORITY
|
||||
)
|
||||
|
||||
168
allianceauth/eveonline/tests/esi_client_stub.py
Normal file
168
allianceauth/eveonline/tests/esi_client_stub.py
Normal file
@@ -0,0 +1,168 @@
|
||||
from bravado.exception import HTTPNotFound
|
||||
|
||||
|
||||
class BravadoResponseStub:
|
||||
"""Stub for IncomingResponse in bravado, e.g. for HTTPError exceptions"""
|
||||
|
||||
def __init__(
|
||||
self, status_code, reason="", text="", headers=None, raw_bytes=None
|
||||
) -> None:
|
||||
self.reason = reason
|
||||
self.status_code = status_code
|
||||
self.text = text
|
||||
self.headers = headers if headers else dict()
|
||||
self.raw_bytes = raw_bytes
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.status_code} {self.reason}"
|
||||
|
||||
|
||||
class BravadoOperationStub:
|
||||
"""Stub to simulate the operation object return from bravado via django-esi"""
|
||||
|
||||
class RequestConfig:
|
||||
def __init__(self, also_return_response):
|
||||
self.also_return_response = also_return_response
|
||||
|
||||
class ResponseStub:
|
||||
def __init__(self, headers):
|
||||
self.headers = headers
|
||||
|
||||
def __init__(self, data, headers: dict = None, also_return_response: bool = False):
|
||||
self._data = data
|
||||
self._headers = headers if headers else {"x-pages": 1}
|
||||
self.request_config = BravadoOperationStub.RequestConfig(also_return_response)
|
||||
|
||||
def result(self, **kwargs):
|
||||
if self.request_config.also_return_response:
|
||||
return [self._data, self.ResponseStub(self._headers)]
|
||||
else:
|
||||
return self._data
|
||||
|
||||
def results(self, **kwargs):
|
||||
return self.result(**kwargs)
|
||||
|
||||
|
||||
class EsiClientStub:
|
||||
"""Stub for an ESI client."""
|
||||
class Alliance:
|
||||
@staticmethod
|
||||
def get_alliances_alliance_id(alliance_id):
|
||||
data = {
|
||||
3001: {
|
||||
"name": "Wayne Enterprises",
|
||||
"ticker": "WYE",
|
||||
"executor_corporation_id": 2001
|
||||
}
|
||||
}
|
||||
try:
|
||||
return BravadoOperationStub(data[int(alliance_id)])
|
||||
except KeyError:
|
||||
response = BravadoResponseStub(
|
||||
404, f"Alliance with ID {alliance_id} not found"
|
||||
)
|
||||
raise HTTPNotFound(response)
|
||||
|
||||
@staticmethod
|
||||
def get_alliances_alliance_id_corporations(alliance_id):
|
||||
data = [2001, 2002, 2003]
|
||||
return BravadoOperationStub(data)
|
||||
|
||||
class Character:
|
||||
@staticmethod
|
||||
def get_characters_character_id(character_id):
|
||||
data = {
|
||||
1001: {
|
||||
"corporation_id": 2001,
|
||||
"name": "Bruce Wayne",
|
||||
},
|
||||
1002: {
|
||||
"corporation_id": 2001,
|
||||
"name": "Peter Parker",
|
||||
},
|
||||
1011: {
|
||||
"corporation_id": 2011,
|
||||
"name": "Lex Luthor",
|
||||
}
|
||||
}
|
||||
try:
|
||||
return BravadoOperationStub(data[int(character_id)])
|
||||
except KeyError:
|
||||
response = BravadoResponseStub(
|
||||
404, f"Character with ID {character_id} not found"
|
||||
)
|
||||
raise HTTPNotFound(response)
|
||||
|
||||
@staticmethod
|
||||
def post_characters_affiliation(characters: list):
|
||||
data = [
|
||||
{'character_id': 1001, 'corporation_id': 2001, 'alliance_id': 3001},
|
||||
{'character_id': 1002, 'corporation_id': 2001, 'alliance_id': 3001},
|
||||
{'character_id': 1011, 'corporation_id': 2011},
|
||||
{'character_id': 1666, 'corporation_id': 1000001},
|
||||
]
|
||||
return BravadoOperationStub(
|
||||
[x for x in data if x['character_id'] in characters]
|
||||
)
|
||||
|
||||
class Corporation:
|
||||
@staticmethod
|
||||
def get_corporations_corporation_id(corporation_id):
|
||||
data = {
|
||||
2001: {
|
||||
"ceo_id": 1091,
|
||||
"member_count": 10,
|
||||
"name": "Wayne Technologies",
|
||||
"ticker": "WTE",
|
||||
"alliance_id": 3001
|
||||
},
|
||||
2002: {
|
||||
"ceo_id": 1092,
|
||||
"member_count": 10,
|
||||
"name": "Wayne Food",
|
||||
"ticker": "WFO",
|
||||
"alliance_id": 3001
|
||||
},
|
||||
2003: {
|
||||
"ceo_id": 1093,
|
||||
"member_count": 10,
|
||||
"name": "Wayne Energy",
|
||||
"ticker": "WEG",
|
||||
"alliance_id": 3001
|
||||
},
|
||||
2011: {
|
||||
"ceo_id": 1,
|
||||
"member_count": 3,
|
||||
"name": "LexCorp",
|
||||
"ticker": "LC",
|
||||
},
|
||||
1000001: {
|
||||
"ceo_id": 3000001,
|
||||
"creator_id": 1,
|
||||
"description": "The internal corporation used for characters in graveyard.",
|
||||
"member_count": 6329026,
|
||||
"name": "Doomheim",
|
||||
"ticker": "666",
|
||||
}
|
||||
}
|
||||
try:
|
||||
return BravadoOperationStub(data[int(corporation_id)])
|
||||
except KeyError:
|
||||
response = BravadoResponseStub(
|
||||
404, f"Corporation with ID {corporation_id} not found"
|
||||
)
|
||||
raise HTTPNotFound(response)
|
||||
|
||||
class Universe:
|
||||
@staticmethod
|
||||
def post_universe_names(ids: list):
|
||||
data = [
|
||||
{"category": "character", "id": 1001, "name": "Bruce Wayne"},
|
||||
{"category": "character", "id": 1002, "name": "Peter Parker"},
|
||||
{"category": "character", "id": 1011, "name": "Lex Luthor"},
|
||||
{"category": "character", "id": 1666, "name": "Hal Jordan"},
|
||||
{"category": "corporation", "id": 2001, "name": "Wayne Technologies"},
|
||||
{"category": "corporation","id": 2002, "name": "Wayne Food"},
|
||||
{"category": "corporation","id": 1000001, "name": "Doomheim"},
|
||||
]
|
||||
return BravadoOperationStub([x for x in data if x['id'] in ids])
|
||||
@@ -1,12 +1,15 @@
|
||||
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
|
||||
|
||||
from ..models import (
|
||||
EveCharacter, EveCorporationInfo, EveAllianceInfo, EveFactionInfo
|
||||
)
|
||||
from ..providers import Alliance, Corporation, Character
|
||||
from ..evelinks import eveimageserver
|
||||
from ..models import EveAllianceInfo, EveCharacter, EveCorporationInfo, EveFactionInfo
|
||||
from ..providers import Alliance, Character, Corporation
|
||||
from .esi_client_stub import EsiClientStub
|
||||
|
||||
|
||||
class EveCharacterTestCase(TestCase):
|
||||
@@ -402,8 +405,8 @@ class EveAllianceTestCase(TestCase):
|
||||
my_alliance.save()
|
||||
my_alliance.populate_alliance()
|
||||
|
||||
for corporation in EveCorporationInfo.objects\
|
||||
.filter(corporation_id__in=[2001, 2002]
|
||||
for corporation in (
|
||||
EveCorporationInfo.objects.filter(corporation_id__in=[2001, 2002])
|
||||
):
|
||||
self.assertEqual(corporation.alliance, my_alliance)
|
||||
|
||||
@@ -587,3 +590,98 @@ class EveCorporationTestCase(TestCase):
|
||||
self.my_corp.logo_url_256,
|
||||
'https://images.evetech.net/corporations/2001/logo?size=256'
|
||||
)
|
||||
|
||||
|
||||
@patch('allianceauth.eveonline.providers.esi_client_factory')
|
||||
@patch("allianceauth.eveonline.models.notify")
|
||||
class TestCharacterUpdate(TestCase):
|
||||
def test_should_update_normal_character(self, mock_notify, mock_esi_client_factory):
|
||||
# given
|
||||
mock_esi_client_factory.return_value = EsiClientStub()
|
||||
my_character = EveCharacter.objects.create(
|
||||
character_id=1001,
|
||||
character_name="not my name",
|
||||
corporation_id=2002,
|
||||
corporation_name="Wayne Food",
|
||||
corporation_ticker="WYF",
|
||||
alliance_id=None
|
||||
)
|
||||
# when
|
||||
my_character.update_character()
|
||||
# then
|
||||
my_character.refresh_from_db()
|
||||
self.assertEqual(my_character.character_name, "Bruce Wayne")
|
||||
self.assertEqual(my_character.corporation_id, 2001)
|
||||
self.assertEqual(my_character.corporation_name, "Wayne Technologies")
|
||||
self.assertEqual(my_character.corporation_ticker, "WTE")
|
||||
self.assertEqual(my_character.alliance_id, 3001)
|
||||
self.assertEqual(my_character.alliance_name, "Wayne Enterprises")
|
||||
self.assertEqual(my_character.alliance_ticker, "WYE")
|
||||
self.assertFalse(mock_notify.called)
|
||||
|
||||
def test_should_update_dead_character_with_owner(
|
||||
self, mock_notify, mock_esi_client_factory
|
||||
):
|
||||
# given
|
||||
mock_esi_client_factory.return_value = EsiClientStub()
|
||||
character_1666 = EveCharacter.objects.create(
|
||||
character_id=1666,
|
||||
character_name="Hal Jordan",
|
||||
corporation_id=2002,
|
||||
corporation_name="Wayne Food",
|
||||
corporation_ticker="WYF",
|
||||
alliance_id=None
|
||||
)
|
||||
user = AuthUtils.create_user("Bruce Wayne")
|
||||
token_1666 = Token.objects.create(
|
||||
user=user,
|
||||
character_id=character_1666.character_id,
|
||||
character_name=character_1666.character_name,
|
||||
character_owner_hash="ABC123-1666",
|
||||
)
|
||||
character_1001 = EveCharacter.objects.create(
|
||||
character_id=1001,
|
||||
character_name="Bruce Wayne",
|
||||
corporation_id=2001,
|
||||
corporation_name="Wayne Technologies",
|
||||
corporation_ticker="WYT",
|
||||
alliance_id=None
|
||||
)
|
||||
token_1001 = Token.objects.create(
|
||||
user=user,
|
||||
character_id=character_1001.character_id,
|
||||
character_name=character_1001.character_name,
|
||||
character_owner_hash="ABC123-1001",
|
||||
)
|
||||
# when
|
||||
character_1666.update_character()
|
||||
# then
|
||||
character_1666.refresh_from_db()
|
||||
self.assertTrue(character_1666.is_biomassed)
|
||||
self.assertNotIn(token_1666, user.token_set.all())
|
||||
self.assertIn(token_1001, user.token_set.all())
|
||||
with self.assertRaises(ObjectDoesNotExist):
|
||||
self.assertTrue(character_1666.character_ownership)
|
||||
user.profile.refresh_from_db()
|
||||
self.assertIsNone(user.profile.main_character)
|
||||
self.assertTrue(mock_notify.called)
|
||||
|
||||
def test_should_handle_dead_character_without_owner(
|
||||
self, mock_notify, mock_esi_client_factory
|
||||
):
|
||||
# given
|
||||
mock_esi_client_factory.return_value = EsiClientStub()
|
||||
character_1666 = EveCharacter.objects.create(
|
||||
character_id=1666,
|
||||
character_name="Hal Jordan",
|
||||
corporation_id=1011,
|
||||
corporation_name="LexCorp",
|
||||
corporation_ticker='LC',
|
||||
alliance_id=None
|
||||
)
|
||||
# when
|
||||
character_1666.update_character()
|
||||
# then
|
||||
character_1666.refresh_from_db()
|
||||
self.assertTrue(character_1666.is_biomassed)
|
||||
self.assertFalse(mock_notify.called)
|
||||
|
||||
@@ -7,6 +7,7 @@ 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,
|
||||
@@ -632,13 +633,7 @@ class TestEveSwaggerProvider(TestCase):
|
||||
|
||||
@patch(MODULE_PATH + '.esi_client_factory')
|
||||
def test_get_character(self, mock_esi_client_factory):
|
||||
mock_esi_client_factory.return_value \
|
||||
.Character.get_characters_character_id \
|
||||
= TestEveSwaggerProvider.esi_get_characters_character_id
|
||||
mock_esi_client_factory.return_value \
|
||||
.Character.post_characters_affiliation \
|
||||
= TestEveSwaggerProvider.esi_post_characters_affiliation
|
||||
|
||||
mock_esi_client_factory.return_value = EsiClientStub()
|
||||
my_provider = EveSwaggerProvider()
|
||||
|
||||
# character with alliance
|
||||
@@ -649,8 +644,8 @@ class TestEveSwaggerProvider(TestCase):
|
||||
self.assertEqual(my_character.alliance_id, 3001)
|
||||
|
||||
# character wo/ alliance
|
||||
my_character = my_provider.get_character(1002)
|
||||
self.assertEqual(my_character.id, 1002)
|
||||
my_character = my_provider.get_character(1011)
|
||||
self.assertEqual(my_character.id, 1011)
|
||||
self.assertEqual(my_character.alliance_id, None)
|
||||
|
||||
# character not found
|
||||
|
||||
@@ -1,245 +1,271 @@
|
||||
from unittest.mock import patch, Mock
|
||||
from unittest.mock import patch
|
||||
|
||||
from django.test import TestCase
|
||||
from django.test import TestCase, TransactionTestCase, override_settings
|
||||
|
||||
from ..models import EveCharacter, EveCorporationInfo, EveAllianceInfo
|
||||
from ..models import EveAllianceInfo, EveCharacter, EveCorporationInfo
|
||||
from ..tasks import (
|
||||
run_model_update,
|
||||
update_alliance,
|
||||
update_corp,
|
||||
update_character,
|
||||
run_model_update
|
||||
update_character_chunk,
|
||||
update_corp,
|
||||
)
|
||||
from .esi_client_stub import EsiClientStub
|
||||
|
||||
|
||||
class TestTasks(TestCase):
|
||||
|
||||
@patch('allianceauth.eveonline.tasks.EveCorporationInfo')
|
||||
def test_update_corp(self, mock_EveCorporationInfo):
|
||||
update_corp(42)
|
||||
self.assertEqual(
|
||||
mock_EveCorporationInfo.objects.update_corporation.call_count, 1
|
||||
)
|
||||
self.assertEqual(
|
||||
mock_EveCorporationInfo.objects.update_corporation.call_args[0][0], 42
|
||||
@patch('allianceauth.eveonline.providers.esi_client_factory')
|
||||
class TestUpdateTasks(TestCase):
|
||||
def test_should_update_alliance(self, mock_esi_client_factory):
|
||||
# given
|
||||
mock_esi_client_factory.return_value = EsiClientStub()
|
||||
my_alliance = EveAllianceInfo.objects.create(
|
||||
alliance_id=3001,
|
||||
alliance_name="Wayne Enterprises",
|
||||
alliance_ticker="WYE",
|
||||
executor_corp_id=2003
|
||||
)
|
||||
# when
|
||||
update_alliance(my_alliance.alliance_id)
|
||||
# then
|
||||
my_alliance.refresh_from_db()
|
||||
self.assertEqual(my_alliance.executor_corp_id, 2001)
|
||||
|
||||
@patch('allianceauth.eveonline.tasks.EveAllianceInfo')
|
||||
def test_update_alliance(self, mock_EveAllianceInfo):
|
||||
update_alliance(42)
|
||||
self.assertEqual(
|
||||
mock_EveAllianceInfo.objects.update_alliance.call_args[0][0], 42
|
||||
)
|
||||
self.assertEqual(
|
||||
mock_EveAllianceInfo.objects
|
||||
.update_alliance.return_value.populate_alliance.call_count, 1
|
||||
def test_should_update_character(self, mock_esi_client_factory):
|
||||
# given
|
||||
mock_esi_client_factory.return_value = EsiClientStub()
|
||||
my_character = EveCharacter.objects.create(
|
||||
character_id=1001,
|
||||
character_name="Bruce Wayne",
|
||||
corporation_id=2002,
|
||||
corporation_name="Wayne Food",
|
||||
corporation_ticker="WYF",
|
||||
alliance_id=None
|
||||
)
|
||||
# when
|
||||
update_character(my_character.character_id)
|
||||
# then
|
||||
my_character.refresh_from_db()
|
||||
self.assertEqual(my_character.corporation_id, 2001)
|
||||
|
||||
@patch('allianceauth.eveonline.tasks.EveCharacter')
|
||||
def test_update_character(self, mock_EveCharacter):
|
||||
update_character(42)
|
||||
self.assertEqual(
|
||||
mock_EveCharacter.objects.update_character.call_count, 1
|
||||
def test_should_update_corp(self, mock_esi_client_factory):
|
||||
# given
|
||||
mock_esi_client_factory.return_value = EsiClientStub()
|
||||
EveAllianceInfo.objects.create(
|
||||
alliance_id=3001,
|
||||
alliance_name="Wayne Enterprises",
|
||||
alliance_ticker="WYE",
|
||||
executor_corp_id=2003
|
||||
)
|
||||
self.assertEqual(
|
||||
mock_EveCharacter.objects.update_character.call_args[0][0], 42
|
||||
my_corporation = EveCorporationInfo.objects.create(
|
||||
corporation_id=2003,
|
||||
corporation_name="Wayne Food",
|
||||
corporation_ticker="WFO",
|
||||
member_count=1,
|
||||
alliance=None,
|
||||
ceo_id=1999
|
||||
)
|
||||
# when
|
||||
update_corp(my_corporation.corporation_id)
|
||||
# then
|
||||
my_corporation.refresh_from_db()
|
||||
self.assertEqual(my_corporation.alliance.alliance_id, 3001)
|
||||
|
||||
# @patch('allianceauth.eveonline.tasks.EveCharacter')
|
||||
# def test_update_character(self, mock_EveCharacter):
|
||||
# update_character(42)
|
||||
# self.assertEqual(
|
||||
# mock_EveCharacter.objects.update_character.call_count, 1
|
||||
# )
|
||||
# self.assertEqual(
|
||||
# mock_EveCharacter.objects.update_character.call_args[0][0], 42
|
||||
# )
|
||||
|
||||
|
||||
@patch('allianceauth.eveonline.tasks.update_character')
|
||||
@patch('allianceauth.eveonline.tasks.update_alliance')
|
||||
@patch('allianceauth.eveonline.tasks.update_corp')
|
||||
@patch('allianceauth.eveonline.providers.provider')
|
||||
@override_settings(CELERY_ALWAYS_EAGER=True)
|
||||
@patch('allianceauth.eveonline.providers.esi_client_factory')
|
||||
@patch('allianceauth.eveonline.tasks.providers')
|
||||
@patch('allianceauth.eveonline.tasks.CHUNK_SIZE', 2)
|
||||
class TestRunModelUpdate(TestCase):
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
EveCorporationInfo.objects.all().delete()
|
||||
EveAllianceInfo.objects.all().delete()
|
||||
EveCharacter.objects.all().delete()
|
||||
|
||||
class TestRunModelUpdate(TransactionTestCase):
|
||||
def test_should_run_updates(self, mock_providers, mock_esi_client_factory):
|
||||
# given
|
||||
mock_providers.provider.client = EsiClientStub()
|
||||
mock_esi_client_factory.return_value = EsiClientStub()
|
||||
EveCorporationInfo.objects.create(
|
||||
corporation_id=2345,
|
||||
corporation_name='corp.name',
|
||||
corporation_ticker='c.c.t',
|
||||
corporation_id=2001,
|
||||
corporation_name="Wayne Technologies",
|
||||
corporation_ticker="WTE",
|
||||
member_count=10,
|
||||
alliance=None,
|
||||
)
|
||||
EveAllianceInfo.objects.create(
|
||||
alliance_id=3456,
|
||||
alliance_name='alliance.name',
|
||||
alliance_ticker='a.t',
|
||||
executor_corp_id=5,
|
||||
alliance_3001 = EveAllianceInfo.objects.create(
|
||||
alliance_id=3001,
|
||||
alliance_name="Wayne Enterprises",
|
||||
alliance_ticker="WYE",
|
||||
executor_corp_id=2003
|
||||
)
|
||||
EveCharacter.objects.create(
|
||||
character_id=1,
|
||||
character_name='character.name1',
|
||||
corporation_id=2345,
|
||||
corporation_name='character.corp.name',
|
||||
corporation_ticker='c.c.t', # max 5 chars
|
||||
corporation_2003 = EveCorporationInfo.objects.create(
|
||||
corporation_id=2003,
|
||||
corporation_name="Wayne Energy",
|
||||
corporation_ticker="WEG",
|
||||
member_count=99,
|
||||
alliance=None,
|
||||
)
|
||||
character_1001 = EveCharacter.objects.create(
|
||||
character_id=1001,
|
||||
character_name="Bruce Wayne",
|
||||
corporation_id=2002,
|
||||
corporation_name="Wayne Food",
|
||||
corporation_ticker="WYF",
|
||||
alliance_id=None
|
||||
)
|
||||
EveCharacter.objects.create(
|
||||
character_id=2,
|
||||
character_name='character.name2',
|
||||
corporation_id=9876,
|
||||
corporation_name='character.corp.name',
|
||||
corporation_ticker='c.c.t', # max 5 chars
|
||||
alliance_id=3456,
|
||||
alliance_name='character.alliance.name',
|
||||
)
|
||||
EveCharacter.objects.create(
|
||||
character_id=3,
|
||||
character_name='character.name3',
|
||||
corporation_id=9876,
|
||||
corporation_name='character.corp.name',
|
||||
corporation_ticker='c.c.t', # max 5 chars
|
||||
alliance_id=3456,
|
||||
alliance_name='character.alliance.name',
|
||||
)
|
||||
EveCharacter.objects.create(
|
||||
character_id=4,
|
||||
character_name='character.name4',
|
||||
corporation_id=9876,
|
||||
corporation_name='character.corp.name',
|
||||
corporation_ticker='c.c.t', # max 5 chars
|
||||
alliance_id=3456,
|
||||
alliance_name='character.alliance.name',
|
||||
)
|
||||
"""
|
||||
EveCharacter.objects.create(
|
||||
character_id=5,
|
||||
character_name='character.name5',
|
||||
corporation_id=9876,
|
||||
corporation_name='character.corp.name',
|
||||
corporation_ticker='c.c.t', # max 5 chars
|
||||
alliance_id=3456,
|
||||
alliance_name='character.alliance.name',
|
||||
)
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
self.affiliations = [
|
||||
{'character_id': 1, 'corporation_id': 5},
|
||||
{'character_id': 2, 'corporation_id': 9876, 'alliance_id': 3456},
|
||||
{'character_id': 3, 'corporation_id': 9876, 'alliance_id': 7456},
|
||||
{'character_id': 4, 'corporation_id': 9876, 'alliance_id': 3456}
|
||||
]
|
||||
self.names = [
|
||||
{'id': 1, 'name': 'character.name1'},
|
||||
{'id': 2, 'name': 'character.name2'},
|
||||
{'id': 3, 'name': 'character.name3'},
|
||||
{'id': 4, 'name': 'character.name4_new'}
|
||||
]
|
||||
|
||||
def test_normal_run(
|
||||
self,
|
||||
mock_provider,
|
||||
mock_update_corp,
|
||||
mock_update_alliance,
|
||||
mock_update_character,
|
||||
):
|
||||
def get_affiliations(characters: list):
|
||||
response = [x for x in self.affiliations if x['character_id'] in characters]
|
||||
mock_operator = Mock(**{'result.return_value': response})
|
||||
return mock_operator
|
||||
|
||||
def get_names(ids: list):
|
||||
response = [x for x in self.names if x['id'] in ids]
|
||||
mock_operator = Mock(**{'result.return_value': response})
|
||||
return mock_operator
|
||||
|
||||
mock_provider.client.Character.post_characters_affiliation.side_effect \
|
||||
= get_affiliations
|
||||
|
||||
mock_provider.client.Universe.post_universe_names.side_effect = get_names
|
||||
|
||||
# when
|
||||
run_model_update()
|
||||
|
||||
# then
|
||||
character_1001.refresh_from_db()
|
||||
self.assertEqual(
|
||||
mock_provider.client.Character.post_characters_affiliation.call_count, 2
|
||||
character_1001.corporation_id, 2001 # char has new corp
|
||||
)
|
||||
corporation_2003.refresh_from_db()
|
||||
self.assertEqual(
|
||||
mock_provider.client.Universe.post_universe_names.call_count, 2
|
||||
corporation_2003.alliance.alliance_id, 3001 # corp has new alliance
|
||||
)
|
||||
alliance_3001.refresh_from_db()
|
||||
self.assertEqual(
|
||||
alliance_3001.executor_corp_id, 2001 # alliance has been updated
|
||||
)
|
||||
|
||||
# character 1 has changed corp
|
||||
# character 2 no change
|
||||
# character 3 has changed alliance
|
||||
# character 4 has changed name
|
||||
self.assertEqual(mock_update_corp.apply_async.call_count, 1)
|
||||
self.assertEqual(
|
||||
int(mock_update_corp.apply_async.call_args[1]['args'][0]), 2345
|
||||
)
|
||||
self.assertEqual(mock_update_alliance.apply_async.call_count, 1)
|
||||
self.assertEqual(
|
||||
int(mock_update_alliance.apply_async.call_args[1]['args'][0]), 3456
|
||||
)
|
||||
characters_updated = {
|
||||
x[1]['args'][0] for x in mock_update_character.apply_async.call_args_list
|
||||
|
||||
@override_settings(CELERY_ALWAYS_EAGER=True)
|
||||
@patch('allianceauth.eveonline.tasks.update_character', wraps=update_character)
|
||||
@patch('allianceauth.eveonline.providers.esi_client_factory')
|
||||
@patch('allianceauth.eveonline.tasks.providers')
|
||||
@patch('allianceauth.eveonline.tasks.CHUNK_SIZE', 2)
|
||||
class TestUpdateCharacterChunk(TestCase):
|
||||
@staticmethod
|
||||
def _updated_character_ids(spy_update_character) -> set:
|
||||
"""Character IDs passed to update_character task for update."""
|
||||
return {
|
||||
x[1]["args"][0] for x in spy_update_character.apply_async.call_args_list
|
||||
}
|
||||
excepted = {1, 3, 4}
|
||||
self.assertSetEqual(characters_updated, excepted)
|
||||
|
||||
def test_ignore_character_not_in_affiliations(
|
||||
self,
|
||||
mock_provider,
|
||||
mock_update_corp,
|
||||
mock_update_alliance,
|
||||
mock_update_character,
|
||||
def test_should_update_corp_change(
|
||||
self, mock_providers, mock_esi_client_factory, spy_update_character
|
||||
):
|
||||
def get_affiliations(characters: list):
|
||||
response = [x for x in self.affiliations if x['character_id'] in characters]
|
||||
mock_operator = Mock(**{'result.return_value': response})
|
||||
return mock_operator
|
||||
# given
|
||||
mock_providers.provider.client = EsiClientStub()
|
||||
mock_esi_client_factory.return_value = EsiClientStub()
|
||||
character_1001 = EveCharacter.objects.create(
|
||||
character_id=1001,
|
||||
character_name="Bruce Wayne",
|
||||
corporation_id=2003,
|
||||
corporation_name="Wayne Energy",
|
||||
corporation_ticker="WEG",
|
||||
alliance_id=3001,
|
||||
alliance_name="Wayne Enterprises",
|
||||
alliance_ticker="WYE",
|
||||
)
|
||||
character_1002 = EveCharacter.objects.create(
|
||||
character_id=1002,
|
||||
character_name="Peter Parker",
|
||||
corporation_id=2001,
|
||||
corporation_name="Wayne Technologies",
|
||||
corporation_ticker="WTE",
|
||||
alliance_id=3001,
|
||||
alliance_name="Wayne Enterprises",
|
||||
alliance_ticker="WYE",
|
||||
)
|
||||
# when
|
||||
update_character_chunk([
|
||||
character_1001.character_id, character_1002.character_id
|
||||
])
|
||||
# then
|
||||
character_1001.refresh_from_db()
|
||||
self.assertEqual(character_1001.corporation_id, 2001)
|
||||
self.assertSetEqual(self._updated_character_ids(spy_update_character), {1001})
|
||||
|
||||
def get_names(ids: list):
|
||||
response = [x for x in self.names if x['id'] in ids]
|
||||
mock_operator = Mock(**{'result.return_value': response})
|
||||
return mock_operator
|
||||
|
||||
del self.affiliations[0]
|
||||
|
||||
mock_provider.client.Character.post_characters_affiliation.side_effect \
|
||||
= get_affiliations
|
||||
|
||||
mock_provider.client.Universe.post_universe_names.side_effect = get_names
|
||||
|
||||
run_model_update()
|
||||
characters_updated = {
|
||||
x[1]['args'][0] for x in mock_update_character.apply_async.call_args_list
|
||||
}
|
||||
excepted = {3, 4}
|
||||
self.assertSetEqual(characters_updated, excepted)
|
||||
|
||||
def test_ignore_character_not_in_names(
|
||||
self,
|
||||
mock_provider,
|
||||
mock_update_corp,
|
||||
mock_update_alliance,
|
||||
mock_update_character,
|
||||
def test_should_update_name_change(
|
||||
self, mock_providers, mock_esi_client_factory, spy_update_character
|
||||
):
|
||||
def get_affiliations(characters: list):
|
||||
response = [x for x in self.affiliations if x['character_id'] in characters]
|
||||
mock_operator = Mock(**{'result.return_value': response})
|
||||
return mock_operator
|
||||
# given
|
||||
mock_providers.provider.client = EsiClientStub()
|
||||
mock_esi_client_factory.return_value = EsiClientStub()
|
||||
character_1001 = EveCharacter.objects.create(
|
||||
character_id=1001,
|
||||
character_name="Batman",
|
||||
corporation_id=2001,
|
||||
corporation_name="Wayne Technologies",
|
||||
corporation_ticker="WTE",
|
||||
alliance_id=3001,
|
||||
alliance_name="Wayne Technologies",
|
||||
alliance_ticker="WYT",
|
||||
)
|
||||
# when
|
||||
update_character_chunk([character_1001.character_id])
|
||||
# then
|
||||
character_1001.refresh_from_db()
|
||||
self.assertEqual(character_1001.character_name, "Bruce Wayne")
|
||||
self.assertSetEqual(self._updated_character_ids(spy_update_character), {1001})
|
||||
|
||||
def get_names(ids: list):
|
||||
response = [x for x in self.names if x['id'] in ids]
|
||||
mock_operator = Mock(**{'result.return_value': response})
|
||||
return mock_operator
|
||||
def test_should_update_alliance_change(
|
||||
self, mock_providers, mock_esi_client_factory, spy_update_character
|
||||
):
|
||||
# given
|
||||
mock_providers.provider.client = EsiClientStub()
|
||||
mock_esi_client_factory.return_value = EsiClientStub()
|
||||
character_1001 = EveCharacter.objects.create(
|
||||
character_id=1001,
|
||||
character_name="Bruce Wayne",
|
||||
corporation_id=2001,
|
||||
corporation_name="Wayne Technologies",
|
||||
corporation_ticker="WTE",
|
||||
alliance_id=None,
|
||||
)
|
||||
# when
|
||||
update_character_chunk([character_1001.character_id])
|
||||
# then
|
||||
character_1001.refresh_from_db()
|
||||
self.assertEqual(character_1001.alliance_id, 3001)
|
||||
self.assertSetEqual(self._updated_character_ids(spy_update_character), {1001})
|
||||
|
||||
del self.names[3]
|
||||
def test_should_not_update_when_not_changed(
|
||||
self, mock_providers, mock_esi_client_factory, spy_update_character
|
||||
):
|
||||
# given
|
||||
mock_providers.provider.client = EsiClientStub()
|
||||
mock_esi_client_factory.return_value = EsiClientStub()
|
||||
character_1001 = EveCharacter.objects.create(
|
||||
character_id=1001,
|
||||
character_name="Bruce Wayne",
|
||||
corporation_id=2001,
|
||||
corporation_name="Wayne Technologies",
|
||||
corporation_ticker="WTE",
|
||||
alliance_id=3001,
|
||||
alliance_name="Wayne Technologies",
|
||||
alliance_ticker="WYT",
|
||||
)
|
||||
# when
|
||||
update_character_chunk([character_1001.character_id])
|
||||
# then
|
||||
self.assertSetEqual(self._updated_character_ids(spy_update_character), set())
|
||||
|
||||
mock_provider.client.Character.post_characters_affiliation.side_effect \
|
||||
= get_affiliations
|
||||
|
||||
mock_provider.client.Universe.post_universe_names.side_effect = get_names
|
||||
|
||||
run_model_update()
|
||||
characters_updated = {
|
||||
x[1]['args'][0] for x in mock_update_character.apply_async.call_args_list
|
||||
}
|
||||
excepted = {1, 3}
|
||||
self.assertSetEqual(characters_updated, excepted)
|
||||
def test_should_fall_back_to_single_updates_when_bulk_update_failed(
|
||||
self, mock_providers, mock_esi_client_factory, spy_update_character
|
||||
):
|
||||
# given
|
||||
mock_providers.provider.client.Character.post_characters_affiliation\
|
||||
.side_effect = OSError
|
||||
mock_esi_client_factory.return_value = EsiClientStub()
|
||||
character_1001 = EveCharacter.objects.create(
|
||||
character_id=1001,
|
||||
character_name="Bruce Wayne",
|
||||
corporation_id=2001,
|
||||
corporation_name="Wayne Technologies",
|
||||
corporation_ticker="WTE",
|
||||
alliance_id=3001,
|
||||
alliance_name="Wayne Technologies",
|
||||
alliance_ticker="WYT",
|
||||
)
|
||||
# when
|
||||
update_character_chunk([character_1001.character_id])
|
||||
# then
|
||||
self.assertSetEqual(self._updated_character_ids(spy_update_character), {1001})
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
default_app_config = 'allianceauth.fleetactivitytracking.apps.FatConfig'
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from . import urls
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from allianceauth import hooks
|
||||
from allianceauth.services.hooks import MenuItemHook, UrlHook
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from django import forms
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
|
||||
class FatlinkForm(forms.Form):
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<form class="form-signin" role="form" action="" method="POST">
|
||||
{% csrf_token %}
|
||||
{{ form|bootstrap }}
|
||||
<br/>
|
||||
<br>
|
||||
<button class="btn btn-lg btn-primary btn-block" type="submit" name="submit_fat">{% translate "Create fatlink" %}</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
@@ -1,30 +1,30 @@
|
||||
from django.conf.urls import url
|
||||
from django.urls import path
|
||||
|
||||
from . import views
|
||||
app_name = 'fleetactivitytracking'
|
||||
|
||||
urlpatterns = [
|
||||
# FleetActivityTracking (FAT)
|
||||
url(r'^$', views.fatlink_view, name='view'),
|
||||
url(r'^statistics/$', views.fatlink_statistics_view, name='statistics'),
|
||||
url(r'^statistics/corp/(\w+)$', views.fatlink_statistics_corp_view,
|
||||
path('', views.fatlink_view, name='view'),
|
||||
path('statistics/', views.fatlink_statistics_view, name='statistics'),
|
||||
path('statistics/corp/<int:corpid>/', views.fatlink_statistics_corp_view,
|
||||
name='statistics_corp'),
|
||||
url(r'^statistics/corp/(?P<corpid>\w+)/(?P<year>[0-9]+)/(?P<month>[0-9]+)/',
|
||||
path('statistics/corp/<int:corpid>/<int:year>/<int:month>/',
|
||||
views.fatlink_statistics_corp_view,
|
||||
name='statistics_corp_month'),
|
||||
url(r'^statistics/(?P<year>[0-9]+)/(?P<month>[0-9]+)/$', views.fatlink_statistics_view,
|
||||
path('statistics/<int:year>/<int:month>/', views.fatlink_statistics_view,
|
||||
name='statistics_month'),
|
||||
url(r'^user/statistics/$', views.fatlink_personal_statistics_view,
|
||||
path('user/statistics/', views.fatlink_personal_statistics_view,
|
||||
name='personal_statistics'),
|
||||
url(r'^user/statistics/(?P<year>[0-9]+)/$', views.fatlink_personal_statistics_view,
|
||||
path('user/statistics/<int:year>/', views.fatlink_personal_statistics_view,
|
||||
name='personal_statistics_year'),
|
||||
url(r'^user/statistics/(?P<year>[0-9]+)/(?P<month>[0-9]+)/$',
|
||||
path('user/statistics/<int:year>/<int:month>/',
|
||||
views.fatlink_monthly_personal_statistics_view,
|
||||
name='personal_statistics_month'),
|
||||
url(r'^user/(?P<char_id>[0-9]+)/statistics/(?P<year>[0-9]+)/(?P<month>[0-9]+)/$',
|
||||
path('user/<int:char_id>/statistics/<int:year>/<int:month>/',
|
||||
views.fatlink_monthly_personal_statistics_view,
|
||||
name='user_statistics_month'),
|
||||
url(r'^create/$', views.create_fatlink_view, name='create'),
|
||||
url(r'^modify/(?P<fat_hash>[a-zA-Z0-9_-]+)/$', views.modify_fatlink_view, name='modify'),
|
||||
url(r'^link/(?P<fat_hash>[a-zA-Z0-9]+)/$', views.click_fatlink_view, name='click'),
|
||||
path('create/', views.create_fatlink_view, name='create'),
|
||||
path('modify/<str:fat_hash>/', views.modify_fatlink_view, name='modify'),
|
||||
path('link/<str:fat_hash>/', views.click_fatlink_view, name='click'),
|
||||
]
|
||||
|
||||
@@ -10,7 +10,7 @@ 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.utils import timezone
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from esi.decorators import token_required
|
||||
from allianceauth.eveonline.providers import provider
|
||||
from .forms import FatlinkForm
|
||||
@@ -212,7 +212,14 @@ def fatlink_monthly_personal_statistics_view(request, year, month, char_id=None)
|
||||
start_of_previous_month = first_day_of_previous_month(year, month)
|
||||
|
||||
if request.user.has_perm('auth.fleetactivitytracking_statistics') and char_id:
|
||||
user = EveCharacter.objects.get(character_id=char_id).user
|
||||
try:
|
||||
user = EveCharacter.objects.get(character_id=char_id).character_ownership.user
|
||||
except EveCharacter.DoesNotExist:
|
||||
messages.error(request, _('Character does not exist'))
|
||||
return redirect('fatlink:view')
|
||||
except AttributeError:
|
||||
messages.error(request, _('User does not exist'))
|
||||
return redirect('fatlink:view')
|
||||
else:
|
||||
user = request.user
|
||||
logger.debug(f"Personal monthly statistics view for user {user} called by {request.user}")
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
default_app_config = 'allianceauth.groupmanagement.apps.GroupManagementConfig'
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
from django import forms
|
||||
from django.apps import apps
|
||||
from django.contrib.auth.models import Permission
|
||||
from django.contrib import admin
|
||||
from django.contrib.auth.models import Group as BaseGroup, User
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db.models import Count
|
||||
from django.db.models.functions import Lower
|
||||
from django.db.models.signals import pre_save, post_save, pre_delete, \
|
||||
post_delete, m2m_changed
|
||||
from django.dispatch import receiver
|
||||
from django.utils.timezone import now
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from .models import AuthGroup, ReservedGroupName
|
||||
from .models import GroupRequest
|
||||
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.dispatch import receiver
|
||||
|
||||
from .forms import GroupAdminForm, ReservedGroupNameAdminForm
|
||||
from .models import AuthGroup, GroupRequest, ReservedGroupName
|
||||
from .tasks import remove_users_not_matching_states_from_group
|
||||
|
||||
if 'eve_autogroups' in apps.app_configs:
|
||||
_has_auto_groups = True
|
||||
@@ -28,10 +30,12 @@ class AuthGroupInlineAdmin(admin.StackedInline):
|
||||
'description',
|
||||
'group_leaders',
|
||||
'group_leader_groups',
|
||||
'states', 'internal',
|
||||
'states',
|
||||
'internal',
|
||||
'hidden',
|
||||
'open',
|
||||
'public'
|
||||
'public',
|
||||
'restricted',
|
||||
)
|
||||
verbose_name_plural = 'Auth Settings'
|
||||
verbose_name = ''
|
||||
@@ -50,6 +54,11 @@ class AuthGroupInlineAdmin(admin.StackedInline):
|
||||
def has_change_permission(self, request, obj=None):
|
||||
return request.user.has_perm('auth.change_group')
|
||||
|
||||
def get_readonly_fields(self, request, obj=None):
|
||||
if not request.user.is_superuser:
|
||||
return self.readonly_fields + ("restricted",)
|
||||
return self.readonly_fields
|
||||
|
||||
|
||||
if _has_auto_groups:
|
||||
class IsAutoGroupFilter(admin.SimpleListFilter):
|
||||
@@ -96,27 +105,15 @@ class HasLeaderFilter(admin.SimpleListFilter):
|
||||
return queryset
|
||||
|
||||
|
||||
class GroupAdminForm(forms.ModelForm):
|
||||
def clean_name(self):
|
||||
my_name = self.cleaned_data['name']
|
||||
if ReservedGroupName.objects.filter(name__iexact=my_name).exists():
|
||||
raise ValidationError(
|
||||
_("This name has been reserved and can not be used for groups."),
|
||||
code='reserved_name'
|
||||
)
|
||||
return my_name
|
||||
|
||||
|
||||
class GroupAdmin(admin.ModelAdmin):
|
||||
form = GroupAdminForm
|
||||
list_select_related = ('authgroup',)
|
||||
ordering = ('name',)
|
||||
list_display = (
|
||||
'name',
|
||||
'_description',
|
||||
'_properties',
|
||||
'_member_count',
|
||||
'has_leader'
|
||||
'has_leader',
|
||||
)
|
||||
list_filter = [
|
||||
'authgroup__internal',
|
||||
@@ -132,34 +129,51 @@ class GroupAdmin(admin.ModelAdmin):
|
||||
|
||||
def get_queryset(self, request):
|
||||
qs = super().get_queryset(request)
|
||||
if _has_auto_groups:
|
||||
qs = qs.prefetch_related('managedalliancegroup_set', 'managedcorpgroup_set')
|
||||
qs = qs.prefetch_related('authgroup__group_leaders').select_related('authgroup')
|
||||
qs = qs.annotate(
|
||||
member_count=Count('user', distinct=True),
|
||||
has_leader_qs = (
|
||||
AuthGroup.objects.filter(group=OuterRef('pk'), group_leaders__isnull=False)
|
||||
)
|
||||
has_leader_groups_qs = (
|
||||
AuthGroup.objects.filter(
|
||||
group=OuterRef('pk'), group_leader_groups__isnull=False
|
||||
)
|
||||
)
|
||||
qs = (
|
||||
qs.select_related('authgroup')
|
||||
.annotate(member_count=Count('user', distinct=True))
|
||||
.annotate(has_leader=Exists(has_leader_qs))
|
||||
.annotate(has_leader_groups=Exists(has_leader_groups_qs))
|
||||
)
|
||||
if _has_auto_groups:
|
||||
is_autogroup_corp = (
|
||||
Group.objects.filter(
|
||||
pk=OuterRef('pk'), managedcorpgroup__isnull=False
|
||||
)
|
||||
)
|
||||
is_autogroup_alliance = (
|
||||
Group.objects.filter(
|
||||
pk=OuterRef('pk'), managedalliancegroup__isnull=False
|
||||
)
|
||||
)
|
||||
qs = (
|
||||
qs.annotate(is_autogroup_corp=Exists(is_autogroup_corp))
|
||||
.annotate(is_autogroup_alliance=Exists(is_autogroup_alliance))
|
||||
)
|
||||
return qs
|
||||
|
||||
def _description(self, obj):
|
||||
return obj.authgroup.description
|
||||
|
||||
@admin.display(description='Members', ordering='member_count')
|
||||
def _member_count(self, obj):
|
||||
return obj.member_count
|
||||
|
||||
_member_count.short_description = 'Members'
|
||||
_member_count.admin_order_field = 'member_count'
|
||||
|
||||
@admin.display(boolean=True)
|
||||
def has_leader(self, obj):
|
||||
return obj.authgroup.group_leaders.exists() or obj.authgroup.group_leader_groups.exists()
|
||||
|
||||
has_leader.boolean = True
|
||||
return obj.has_leader or obj.has_leader_groups
|
||||
|
||||
def _properties(self, obj):
|
||||
properties = list()
|
||||
if _has_auto_groups and (
|
||||
obj.managedalliancegroup_set.exists()
|
||||
or obj.managedcorpgroup_set.exists()
|
||||
):
|
||||
if _has_auto_groups and (obj.is_autogroup_corp or obj.is_autogroup_alliance):
|
||||
properties.append('Auto Group')
|
||||
elif obj.authgroup.internal:
|
||||
properties.append('Internal')
|
||||
@@ -172,11 +186,10 @@ class GroupAdmin(admin.ModelAdmin):
|
||||
properties.append('Public')
|
||||
if not properties:
|
||||
properties.append('Default')
|
||||
|
||||
if obj.authgroup.restricted:
|
||||
properties.append('Restricted')
|
||||
return properties
|
||||
|
||||
_properties.short_description = "properties"
|
||||
|
||||
filter_horizontal = ('permissions',)
|
||||
inlines = (AuthGroupInlineAdmin,)
|
||||
|
||||
@@ -190,8 +203,15 @@ class GroupAdmin(admin.ModelAdmin):
|
||||
ag_instance = inline_form.save(commit=False)
|
||||
ag_instance.group = form.instance
|
||||
ag_instance.save()
|
||||
if ag_instance.states.exists():
|
||||
remove_users_not_matching_states_from_group.delay(ag_instance.group.pk)
|
||||
formset.save()
|
||||
|
||||
def get_readonly_fields(self, request, obj=None):
|
||||
if not request.user.is_superuser:
|
||||
return self.readonly_fields + ("permissions",)
|
||||
return self.readonly_fields
|
||||
|
||||
|
||||
class Group(BaseGroup):
|
||||
class Meta:
|
||||
@@ -216,33 +236,10 @@ class GroupRequestAdmin(admin.ModelAdmin):
|
||||
'leave_request',
|
||||
)
|
||||
|
||||
@admin.display(boolean=True, description="is leave request")
|
||||
def _leave_request(self, obj) -> True:
|
||||
return obj.leave_request
|
||||
|
||||
_leave_request.short_description = 'is leave request'
|
||||
_leave_request.boolean = True
|
||||
|
||||
|
||||
class ReservedGroupNameAdminForm(forms.ModelForm):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields['created_by'].initial = self.current_user.username
|
||||
self.fields['created_at'].initial = _("(auto)")
|
||||
|
||||
created_by = forms.CharField(disabled=True)
|
||||
created_at = forms.CharField(disabled=True)
|
||||
|
||||
def clean_name(self):
|
||||
my_name = self.cleaned_data['name'].lower()
|
||||
if Group.objects.filter(name__iexact=my_name).exists():
|
||||
raise ValidationError(
|
||||
_("There already exists a group with that name."), code='already_exists'
|
||||
)
|
||||
return my_name
|
||||
|
||||
def clean_created_at(self):
|
||||
return now()
|
||||
|
||||
|
||||
@admin.register(ReservedGroupName)
|
||||
class ReservedGroupNameAdmin(admin.ModelAdmin):
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from allianceauth.services.hooks import MenuItemHook, UrlHook
|
||||
from allianceauth import hooks
|
||||
|
||||
39
allianceauth/groupmanagement/forms.py
Normal file
39
allianceauth/groupmanagement/forms.py
Normal file
@@ -0,0 +1,39 @@
|
||||
from django import forms
|
||||
from django.contrib.auth.models import Group
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.utils.timezone import now
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from .models import ReservedGroupName
|
||||
|
||||
|
||||
class GroupAdminForm(forms.ModelForm):
|
||||
def clean_name(self):
|
||||
my_name = self.cleaned_data['name']
|
||||
if ReservedGroupName.objects.filter(name__iexact=my_name).exists():
|
||||
raise ValidationError(
|
||||
_("This name has been reserved and can not be used for groups."),
|
||||
code='reserved_name'
|
||||
)
|
||||
return my_name
|
||||
|
||||
|
||||
class ReservedGroupNameAdminForm(forms.ModelForm):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields['created_by'].initial = self.current_user.username
|
||||
self.fields['created_at'].initial = _("(auto)")
|
||||
|
||||
created_by = forms.CharField(disabled=True)
|
||||
created_at = forms.CharField(disabled=True)
|
||||
|
||||
def clean_name(self):
|
||||
my_name = self.cleaned_data['name'].lower()
|
||||
if Group.objects.filter(name__iexact=my_name).exists():
|
||||
raise ValidationError(
|
||||
_("There already exists a group with that name."), code='already_exists'
|
||||
)
|
||||
return my_name
|
||||
|
||||
def clean_created_at(self):
|
||||
return now()
|
||||
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 3.2.10 on 2022-04-08 19:30
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('groupmanagement', '0018_reservedgroupname'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='authgroup',
|
||||
name='restricted',
|
||||
field=models.BooleanField(default=False, help_text='Group is restricted. This means that adding or removing users for this group requires a superuser admin.'),
|
||||
),
|
||||
]
|
||||
@@ -13,6 +13,7 @@ from allianceauth.notifications import notify
|
||||
|
||||
class GroupRequest(models.Model):
|
||||
"""Request from a user for joining or leaving a group."""
|
||||
|
||||
leave_request = models.BooleanField(default=0)
|
||||
user = models.ForeignKey(User, on_delete=models.CASCADE)
|
||||
group = models.ForeignKey(Group, on_delete=models.CASCADE)
|
||||
@@ -44,6 +45,7 @@ class GroupRequest(models.Model):
|
||||
|
||||
class RequestLog(models.Model):
|
||||
"""Log entry about who joined and left a group and who approved it."""
|
||||
|
||||
request_type = models.BooleanField(null=True)
|
||||
group = models.ForeignKey(Group, on_delete=models.CASCADE)
|
||||
request_info = models.CharField(max_length=254)
|
||||
@@ -95,6 +97,7 @@ class AuthGroup(models.Model):
|
||||
Open - Users are automatically accepted into the group
|
||||
Not Open - Users requests must be approved before they are added to the group
|
||||
"""
|
||||
|
||||
group = models.OneToOneField(Group, on_delete=models.CASCADE, primary_key=True)
|
||||
internal = models.BooleanField(
|
||||
default=True,
|
||||
@@ -126,6 +129,13 @@ class AuthGroup(models.Model):
|
||||
"are no longer authenticated."
|
||||
)
|
||||
)
|
||||
restricted = models.BooleanField(
|
||||
default=False,
|
||||
help_text=_(
|
||||
"Group is restricted. This means that adding or removing users "
|
||||
"for this group requires a superuser admin."
|
||||
)
|
||||
)
|
||||
group_leaders = models.ManyToManyField(
|
||||
User,
|
||||
related_name='leads_groups',
|
||||
@@ -179,12 +189,22 @@ class AuthGroup(models.Model):
|
||||
| User.objects.filter(groups__in=list(self.group_leader_groups.all()))
|
||||
)
|
||||
|
||||
def remove_users_not_matching_states(self):
|
||||
"""Remove users not matching defined states from related group."""
|
||||
states_qs = self.states.all()
|
||||
if states_qs.exists():
|
||||
states = list(states_qs)
|
||||
non_compliant_users = self.group.user_set.exclude(profile__state__in=states)
|
||||
for user in non_compliant_users:
|
||||
self.group.user_set.remove(user)
|
||||
|
||||
|
||||
class ReservedGroupName(models.Model):
|
||||
"""Name that can not be used for groups.
|
||||
|
||||
This enables AA to ignore groups on other services (e.g. Discord) with that name.
|
||||
"""
|
||||
|
||||
name = models.CharField(
|
||||
_('name'),
|
||||
max_length=150,
|
||||
|
||||
10
allianceauth/groupmanagement/tasks.py
Normal file
10
allianceauth/groupmanagement/tasks.py
Normal file
@@ -0,0 +1,10 @@
|
||||
from celery import shared_task
|
||||
|
||||
from django.contrib.auth.models import Group
|
||||
|
||||
|
||||
@shared_task
|
||||
def remove_users_not_matching_states_from_group(group_pk: int) -> None:
|
||||
"""Remove users not matching defined states from related group."""
|
||||
group = Group.objects.get(pk=group_pk)
|
||||
group.authgroup.remove_users_not_matching_states()
|
||||
@@ -127,6 +127,8 @@
|
||||
],
|
||||
bootstrap: true
|
||||
},
|
||||
"stateSave": true,
|
||||
"stateDuration": 0
|
||||
});
|
||||
});
|
||||
{% endblock %}
|
||||
|
||||
@@ -104,7 +104,9 @@
|
||||
"sortable": false,
|
||||
"targets": [2]
|
||||
},
|
||||
]
|
||||
],
|
||||
"stateSave": true,
|
||||
"stateDuration": 0
|
||||
});
|
||||
});
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
from unittest.mock import patch
|
||||
|
||||
from django_webtest import WebTest
|
||||
|
||||
from django.conf import settings
|
||||
from django.contrib import admin
|
||||
from django.contrib.admin.sites import AdminSite
|
||||
from django.contrib.auth.models import User
|
||||
from django.test import TestCase, RequestFactory, Client
|
||||
from django.test import TestCase, RequestFactory, Client, override_settings
|
||||
|
||||
from allianceauth.authentication.models import CharacterOwnership, State
|
||||
from allianceauth.eveonline.models import (
|
||||
EveCharacter, EveCorporationInfo, EveAllianceInfo
|
||||
)
|
||||
from ..admin import HasLeaderFilter, GroupAdmin, Group
|
||||
from allianceauth.tests.auth_utils import AuthUtils
|
||||
|
||||
from . import get_admin_change_view_url
|
||||
from ..admin import HasLeaderFilter, GroupAdmin, Group
|
||||
from ..models import ReservedGroupName
|
||||
|
||||
|
||||
@@ -33,7 +37,6 @@ class MockRequest:
|
||||
|
||||
|
||||
class TestGroupAdmin(TestCase):
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
@@ -233,60 +236,104 @@ class TestGroupAdmin(TestCase):
|
||||
self.assertEqual(result, expected)
|
||||
|
||||
def test_member_count(self):
|
||||
expected = 1
|
||||
obj = self.modeladmin.get_queryset(MockRequest(user=self.user_1))\
|
||||
.get(pk=self.group_1.pk)
|
||||
# given
|
||||
request = MockRequest(user=self.user_1)
|
||||
obj = self.modeladmin.get_queryset(request).get(pk=self.group_1.pk)
|
||||
# when
|
||||
result = self.modeladmin._member_count(obj)
|
||||
self.assertEqual(result, expected)
|
||||
# then
|
||||
self.assertEqual(result, 1)
|
||||
|
||||
def test_has_leader_user(self):
|
||||
result = self.modeladmin.has_leader(self.group_1)
|
||||
# given
|
||||
request = MockRequest(user=self.user_1)
|
||||
obj = self.modeladmin.get_queryset(request).get(pk=self.group_1.pk)
|
||||
# when
|
||||
result = self.modeladmin.has_leader(obj)
|
||||
# then
|
||||
self.assertTrue(result)
|
||||
|
||||
def test_has_leader_group(self):
|
||||
result = self.modeladmin.has_leader(self.group_2)
|
||||
# given
|
||||
request = MockRequest(user=self.user_1)
|
||||
obj = self.modeladmin.get_queryset(request).get(pk=self.group_2.pk)
|
||||
# when
|
||||
result = self.modeladmin.has_leader(obj)
|
||||
# then
|
||||
self.assertTrue(result)
|
||||
|
||||
def test_properties_1(self):
|
||||
expected = ['Default']
|
||||
result = self.modeladmin._properties(self.group_1)
|
||||
self.assertListEqual(result, expected)
|
||||
# given
|
||||
request = MockRequest(user=self.user_1)
|
||||
obj = self.modeladmin.get_queryset(request).get(pk=self.group_1.pk)
|
||||
# when
|
||||
result = self.modeladmin._properties(obj)
|
||||
self.assertListEqual(result, ['Default'])
|
||||
|
||||
def test_properties_2(self):
|
||||
expected = ['Internal']
|
||||
result = self.modeladmin._properties(self.group_2)
|
||||
self.assertListEqual(result, expected)
|
||||
# given
|
||||
request = MockRequest(user=self.user_1)
|
||||
obj = self.modeladmin.get_queryset(request).get(pk=self.group_2.pk)
|
||||
# when
|
||||
result = self.modeladmin._properties(obj)
|
||||
self.assertListEqual(result, ['Internal'])
|
||||
|
||||
def test_properties_3(self):
|
||||
expected = ['Hidden']
|
||||
result = self.modeladmin._properties(self.group_3)
|
||||
self.assertListEqual(result, expected)
|
||||
# given
|
||||
request = MockRequest(user=self.user_1)
|
||||
obj = self.modeladmin.get_queryset(request).get(pk=self.group_3.pk)
|
||||
# when
|
||||
result = self.modeladmin._properties(obj)
|
||||
self.assertListEqual(result, ['Hidden'])
|
||||
|
||||
def test_properties_4(self):
|
||||
expected = ['Open']
|
||||
result = self.modeladmin._properties(self.group_4)
|
||||
self.assertListEqual(result, expected)
|
||||
# given
|
||||
request = MockRequest(user=self.user_1)
|
||||
obj = self.modeladmin.get_queryset(request).get(pk=self.group_4.pk)
|
||||
# when
|
||||
result = self.modeladmin._properties(obj)
|
||||
self.assertListEqual(result, ['Open'])
|
||||
|
||||
def test_properties_5(self):
|
||||
expected = ['Public']
|
||||
result = self.modeladmin._properties(self.group_5)
|
||||
self.assertListEqual(result, expected)
|
||||
# given
|
||||
request = MockRequest(user=self.user_1)
|
||||
obj = self.modeladmin.get_queryset(request).get(pk=self.group_5.pk)
|
||||
# when
|
||||
result = self.modeladmin._properties(obj)
|
||||
self.assertListEqual(result, ['Public'])
|
||||
|
||||
def test_properties_6(self):
|
||||
expected = ['Hidden', 'Open', 'Public']
|
||||
result = self.modeladmin._properties(self.group_6)
|
||||
self.assertListEqual(result, expected)
|
||||
# given
|
||||
request = MockRequest(user=self.user_1)
|
||||
obj = self.modeladmin.get_queryset(request).get(pk=self.group_6.pk)
|
||||
# when
|
||||
result = self.modeladmin._properties(obj)
|
||||
self.assertListEqual(result, ['Hidden', 'Open', 'Public'])
|
||||
|
||||
if _has_auto_groups:
|
||||
@patch(MODULE_PATH + '._has_auto_groups', True)
|
||||
def test_properties_7(self):
|
||||
def test_should_show_autogroup_for_corporation(self):
|
||||
# given
|
||||
self._create_autogroups()
|
||||
expected = ['Auto Group']
|
||||
my_group = Group.objects\
|
||||
.filter(managedcorpgroup__isnull=False)\
|
||||
.first()
|
||||
result = self.modeladmin._properties(my_group)
|
||||
self.assertListEqual(result, expected)
|
||||
request = MockRequest(user=self.user_1)
|
||||
queryset = self.modeladmin.get_queryset(request)
|
||||
obj = queryset.filter(managedcorpgroup__isnull=False).first()
|
||||
# when
|
||||
result = self.modeladmin._properties(obj)
|
||||
# then
|
||||
self.assertListEqual(result, ['Auto Group'])
|
||||
|
||||
@patch(MODULE_PATH + '._has_auto_groups', True)
|
||||
def test_should_show_autogroup_for_alliance(self):
|
||||
# given
|
||||
self._create_autogroups()
|
||||
request = MockRequest(user=self.user_1)
|
||||
queryset = self.modeladmin.get_queryset(request)
|
||||
obj = queryset.filter(managedalliancegroup__isnull=False).first()
|
||||
# when
|
||||
result = self.modeladmin._properties(obj)
|
||||
# then
|
||||
self.assertListEqual(result, ['Auto Group'])
|
||||
|
||||
# actions
|
||||
|
||||
@@ -468,6 +515,136 @@ class TestGroupAdmin(TestCase):
|
||||
self.assertFalse(Group.objects.filter(name="new group").exists())
|
||||
|
||||
|
||||
class TestGroupAdminChangeFormSuperuserExclusiveEdits(WebTest):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
super().setUpClass()
|
||||
cls.super_admin = User.objects.create_superuser("super_admin")
|
||||
cls.staff_admin = User.objects.create_user("staff_admin")
|
||||
cls.staff_admin.is_staff = True
|
||||
cls.staff_admin.save()
|
||||
cls.staff_admin = AuthUtils.add_permissions_to_user_by_name(
|
||||
[
|
||||
"auth.add_group",
|
||||
"auth.change_group",
|
||||
"auth.view_group",
|
||||
"groupmanagement.add_group",
|
||||
"groupmanagement.change_group",
|
||||
"groupmanagement.view_group",
|
||||
],
|
||||
cls.staff_admin
|
||||
)
|
||||
cls.superuser_exclusive_fields = ["permissions", "authgroup-0-restricted"]
|
||||
|
||||
def test_should_show_all_fields_to_superuser_for_add(self):
|
||||
# given
|
||||
self.app.set_user(self.super_admin)
|
||||
page = self.app.get("/admin/groupmanagement/group/add/")
|
||||
# when
|
||||
form = page.forms["group_form"]
|
||||
# then
|
||||
for field in self.superuser_exclusive_fields:
|
||||
with self.subTest(field=field):
|
||||
self.assertIn(field, form.fields)
|
||||
|
||||
def test_should_not_show_all_fields_to_staff_admins_for_add(self):
|
||||
# given
|
||||
self.app.set_user(self.staff_admin)
|
||||
page = self.app.get("/admin/groupmanagement/group/add/")
|
||||
# when
|
||||
form = page.forms["group_form"]
|
||||
# then
|
||||
for field in self.superuser_exclusive_fields:
|
||||
with self.subTest(field=field):
|
||||
self.assertNotIn(field, form.fields)
|
||||
|
||||
def test_should_show_all_fields_to_superuser_for_change(self):
|
||||
# given
|
||||
self.app.set_user(self.super_admin)
|
||||
group = Group.objects.create(name="Dummy group")
|
||||
page = self.app.get(f"/admin/groupmanagement/group/{group.pk}/change/")
|
||||
# when
|
||||
form = page.forms["group_form"]
|
||||
# then
|
||||
for field in self.superuser_exclusive_fields:
|
||||
with self.subTest(field=field):
|
||||
self.assertIn(field, form.fields)
|
||||
|
||||
def test_should_not_show_all_fields_to_staff_admin_for_change(self):
|
||||
# given
|
||||
self.app.set_user(self.staff_admin)
|
||||
group = Group.objects.create(name="Dummy group")
|
||||
page = self.app.get(f"/admin/groupmanagement/group/{group.pk}/change/")
|
||||
# when
|
||||
form = page.forms["group_form"]
|
||||
# then
|
||||
for field in self.superuser_exclusive_fields:
|
||||
with self.subTest(field=field):
|
||||
self.assertNotIn(field, form.fields)
|
||||
|
||||
|
||||
@override_settings(CELERY_ALWAYS_EAGER=True, CELERY_EAGER_PROPAGATES_EXCEPTIONS=True)
|
||||
class TestGroupAdmin2(TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
cls.superuser = User.objects.create_superuser("super")
|
||||
|
||||
def test_should_remove_users_from_state_groups(self):
|
||||
# given
|
||||
user_member = AuthUtils.create_user("Bruce Wayne")
|
||||
character_member = AuthUtils.add_main_character_2(
|
||||
user_member,
|
||||
name="Bruce Wayne",
|
||||
character_id=1001,
|
||||
corp_id=2001,
|
||||
corp_name="Wayne Technologies",
|
||||
)
|
||||
user_guest = AuthUtils.create_user("Lex Luthor")
|
||||
AuthUtils.add_main_character_2(
|
||||
user_guest,
|
||||
name="Lex Luthor",
|
||||
character_id=1011,
|
||||
corp_id=2011,
|
||||
corp_name="Luthor Corp",
|
||||
)
|
||||
member_state = AuthUtils.get_member_state()
|
||||
member_state.member_characters.add(character_member)
|
||||
user_member.refresh_from_db()
|
||||
user_guest.refresh_from_db()
|
||||
group = Group.objects.create(name="dummy")
|
||||
user_member.groups.add(group)
|
||||
user_guest.groups.add(group)
|
||||
group.authgroup.states.add(member_state)
|
||||
self.client.force_login(self.superuser)
|
||||
# when
|
||||
response = self.client.post(
|
||||
f"/admin/groupmanagement/group/{group.pk}/change/",
|
||||
data={
|
||||
"name": f"{group.name}",
|
||||
"authgroup-TOTAL_FORMS": "1",
|
||||
"authgroup-INITIAL_FORMS": "1",
|
||||
"authgroup-MIN_NUM_FORMS": "0",
|
||||
"authgroup-MAX_NUM_FORMS": "1",
|
||||
"authgroup-0-description": "",
|
||||
"authgroup-0-states": f"{member_state.pk}",
|
||||
"authgroup-0-internal": "on",
|
||||
"authgroup-0-hidden": "on",
|
||||
"authgroup-0-group": f"{group.pk}",
|
||||
"authgroup-__prefix__-description": "",
|
||||
"authgroup-__prefix__-internal": "on",
|
||||
"authgroup-__prefix__-hidden": "on",
|
||||
"authgroup-__prefix__-group": f"{group.pk}",
|
||||
"_save": "Save"
|
||||
}
|
||||
)
|
||||
# then
|
||||
self.assertEqual(response.status_code, 302)
|
||||
self.assertEqual(response.url, "/admin/groupmanagement/group/")
|
||||
self.assertIn(group, user_member.groups.all())
|
||||
self.assertNotIn(group, user_guest.groups.all())
|
||||
|
||||
|
||||
class TestReservedGroupNameAdmin(TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
|
||||
@@ -232,6 +232,38 @@ class TestAuthGroup(TestCase):
|
||||
expected = 'Superheros'
|
||||
self.assertEqual(str(group.authgroup), expected)
|
||||
|
||||
def test_should_remove_guests_from_group_when_restricted_to_members_only(self):
|
||||
# given
|
||||
user_member = AuthUtils.create_user("Bruce Wayne")
|
||||
character_member = AuthUtils.add_main_character_2(
|
||||
user_member,
|
||||
name="Bruce Wayne",
|
||||
character_id=1001,
|
||||
corp_id=2001,
|
||||
corp_name="Wayne Technologies",
|
||||
)
|
||||
user_guest = AuthUtils.create_user("Lex Luthor")
|
||||
AuthUtils.add_main_character_2(
|
||||
user_guest,
|
||||
name="Lex Luthor",
|
||||
character_id=1011,
|
||||
corp_id=2011,
|
||||
corp_name="Luthor Corp",
|
||||
)
|
||||
member_state = AuthUtils.get_member_state()
|
||||
member_state.member_characters.add(character_member)
|
||||
user_member.refresh_from_db()
|
||||
user_guest.refresh_from_db()
|
||||
group = Group.objects.create(name="dummy")
|
||||
user_member.groups.add(group)
|
||||
user_guest.groups.add(group)
|
||||
group.authgroup.states.add(member_state)
|
||||
# when
|
||||
group.authgroup.remove_users_not_matching_states()
|
||||
# then
|
||||
self.assertIn(group, user_member.groups.all())
|
||||
self.assertNotIn(group, user_guest.groups.all())
|
||||
|
||||
|
||||
class TestAuthGroupRequestApprovers(TestCase):
|
||||
def setUp(self) -> None:
|
||||
|
||||
@@ -1,51 +1,50 @@
|
||||
from django.urls import path
|
||||
from . import views
|
||||
|
||||
from django.conf.urls import url
|
||||
|
||||
app_name = "groupmanagement"
|
||||
|
||||
urlpatterns = [
|
||||
# groups
|
||||
url(r"^groups/$", views.groups_view, name="groups"),
|
||||
url(r"^group/request/join/(\w+)/$", views.group_request_add, name="request_add"),
|
||||
url(
|
||||
r"^group/request/leave/(\w+)/$", views.group_request_leave, name="request_leave"
|
||||
path("groups", views.groups_view, name="groups"),
|
||||
path("group/request/join/<int:group_id>/", views.group_request_add, name="request_add"),
|
||||
path(
|
||||
"group/request/leave/<int:group_id>/", views.group_request_leave, name="request_leave"
|
||||
),
|
||||
# group management
|
||||
url(r"^groupmanagement/requests/$", views.group_management, name="management"),
|
||||
url(r"^groupmanagement/membership/$", views.group_membership, name="membership"),
|
||||
url(
|
||||
r"^groupmanagement/membership/(\w+)/$",
|
||||
path("groupmanagement/requests/", views.group_management, name="management"),
|
||||
path("groupmanagement/membership/", views.group_membership, name="membership"),
|
||||
path(
|
||||
"groupmanagement/membership/<int:group_id>/",
|
||||
views.group_membership_list,
|
||||
name="membership",
|
||||
),
|
||||
url(
|
||||
r"^groupmanagement/membership/(\w+)/audit-log/$",
|
||||
path(
|
||||
"groupmanagement/membership/<int:group_id>/audit-log/",
|
||||
views.group_membership_audit,
|
||||
name="audit_log",
|
||||
),
|
||||
url(
|
||||
r"^groupmanagement/membership/(\w+)/remove/(\w+)/$",
|
||||
path(
|
||||
"groupmanagement/membership/<int:group_id>/remove/<int:user_id>/",
|
||||
views.group_membership_remove,
|
||||
name="membership_remove",
|
||||
),
|
||||
url(
|
||||
r"^groupmanagement/request/join/accept/(\w+)/$",
|
||||
path(
|
||||
"groupmanagement/request/join/accept/<int:group_request_id>/",
|
||||
views.group_accept_request,
|
||||
name="accept_request",
|
||||
),
|
||||
url(
|
||||
r"^groupmanagement/request/join/reject/(\w+)/$",
|
||||
path(
|
||||
"groupmanagement/request/join/reject/<int:group_request_id>/",
|
||||
views.group_reject_request,
|
||||
name="reject_request",
|
||||
),
|
||||
url(
|
||||
r"^groupmanagement/request/leave/accept/(\w+)/$",
|
||||
path(
|
||||
"groupmanagement/request/leave/accept/<int:group_request_id>/",
|
||||
views.group_leave_accept_request,
|
||||
name="leave_accept_request",
|
||||
),
|
||||
url(
|
||||
r"^groupmanagement/request/leave/reject/(\w+)/$",
|
||||
path(
|
||||
"groupmanagement/request/leave/reject/<int:group_request_id>/",
|
||||
views.group_leave_reject_request,
|
||||
name="leave_reject_request",
|
||||
),
|
||||
|
||||
@@ -9,7 +9,7 @@ from django.core.exceptions import ObjectDoesNotExist, PermissionDenied
|
||||
from django.db.models import Count
|
||||
from django.http import Http404
|
||||
from django.shortcuts import render, redirect, get_object_or_404
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from allianceauth.notifications import notify
|
||||
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
default_app_config = 'allianceauth.hrapplications.apps.HRApplicationsConfig'
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from allianceauth import hooks
|
||||
from allianceauth.services.hooks import MenuItemHook, UrlHook
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from django import forms
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
|
||||
class HRApplicationCommentForm(forms.Form):
|
||||
|
||||
@@ -19,8 +19,8 @@
|
||||
<div cass="text-center">{{ question.help_text }}</div>
|
||||
{% endif %}
|
||||
{% for choice in question.choices.all %}
|
||||
<input type={% if question.multi_select == False %}"radio"{% else %}"checkbox"{% endif %} name="{{ question.pk }}" id="id_{{ question.pk }}" value="{{ choice.choice_text }}" />
|
||||
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
|
||||
<input type={% if question.multi_select == False %}"radio"{% else %}"checkbox"{% endif %} name="{{ question.pk }}" id="id_{{ question.pk }}" value="{{ choice.choice_text }}">
|
||||
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br>
|
||||
{% empty %}
|
||||
<textarea class="form-control" cols="30" id="id_{{ question.pk }}" name="{{ question.pk }}" rows="4"></textarea>
|
||||
{% endfor %}
|
||||
|
||||
@@ -181,7 +181,7 @@
|
||||
<form class="form-signin" role="form" action={% url 'hrapplications:search' %} method="POST">
|
||||
{% csrf_token %}
|
||||
{{ search_form|bootstrap }}
|
||||
<br/>
|
||||
<br>
|
||||
<button class="btn btn-lg btn-primary btn-block" type="submit">{% translate "Search" %}</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
<form class="form-signin" role="form" action={% url 'hrapplications:search' %} method="POST">
|
||||
{% csrf_token %}
|
||||
{{ search_form|bootstrap }}
|
||||
<br/>
|
||||
<br>
|
||||
<button class="btn btn-lg btn-primary btn-block" type="submit">{% translate "Search" %}</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
@@ -140,7 +140,7 @@
|
||||
<form class="form-signin" role="form" action="" method="POST">
|
||||
{% csrf_token %}
|
||||
{{ comment_form|bootstrap }}
|
||||
<br/>
|
||||
<br>
|
||||
<button class="btn btn-lg btn-primary btn-block" type="submit">{% translate "Add Comment" %}</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
@@ -1,31 +1,31 @@
|
||||
from django.conf.urls import url
|
||||
from django.urls import path
|
||||
|
||||
from . import views
|
||||
|
||||
app_name = 'hrapplications'
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^$', views.hr_application_management_view,
|
||||
path('', views.hr_application_management_view,
|
||||
name="index"),
|
||||
url(r'^create/$', views.hr_application_create_view,
|
||||
path('create/', views.hr_application_create_view,
|
||||
name="create_view"),
|
||||
url(r'^create/(\d+)', views.hr_application_create_view,
|
||||
path('create/<int:form_id>/', views.hr_application_create_view,
|
||||
name="create_view"),
|
||||
url(r'^remove/(\w+)', views.hr_application_remove,
|
||||
path('remove/<int:app_id>/', views.hr_application_remove,
|
||||
name="remove"),
|
||||
url(r'^view/(\w+)', views.hr_application_view,
|
||||
path('view/<int:app_id>/', views.hr_application_view,
|
||||
name="view"),
|
||||
url(r'^personal/view/(\w+)', views.hr_application_personal_view,
|
||||
path('personal/view/<int:app_id>/', views.hr_application_personal_view,
|
||||
name="personal_view"),
|
||||
url(r'^personal/removal/(\w+)',
|
||||
path('personal/removal/<int:app_id>/',
|
||||
views.hr_application_personal_removal,
|
||||
name="personal_removal"),
|
||||
url(r'^approve/(\w+)', views.hr_application_approve,
|
||||
path('approve/<int:app_id>/', views.hr_application_approve,
|
||||
name="approve"),
|
||||
url(r'^reject/(\w+)', views.hr_application_reject,
|
||||
path('reject/<int:app_id>/', views.hr_application_reject,
|
||||
name="reject"),
|
||||
url(r'^search/', views.hr_application_search,
|
||||
path('search/', views.hr_application_search,
|
||||
name="search"),
|
||||
url(r'^mark_in_progress/(\w+)', views.hr_application_mark_in_progress,
|
||||
path('mark_in_progress/<int:app_id>/', views.hr_application_mark_in_progress,
|
||||
name="mark_in_progress"),
|
||||
]
|
||||
]
|
||||
|
||||
Binary file not shown.
@@ -20,7 +20,7 @@ msgstr ""
|
||||
"Content-Type: text/plain; charset=UTF-8\n"
|
||||
"Content-Transfer-Encoding: 8bit\n"
|
||||
"Language: es\n"
|
||||
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
|
||||
"Plural-Forms: nplurals=3; plural=n == 1 ? 0 : n != 0 && n % 1000000 == 0 ? 1 : 2;\n"
|
||||
|
||||
#: allianceauth/analytics/models.py:29
|
||||
msgid "Google Analytics Universal"
|
||||
@@ -450,6 +450,7 @@ msgid "%(user)s has collected one link this month."
|
||||
msgid_plural "%(user)s has collected %(links)s links this month."
|
||||
msgstr[0] ""
|
||||
msgstr[1] ""
|
||||
msgstr[2] ""
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkpersonalmonthlystatisticsview.html:28
|
||||
msgid "Times used"
|
||||
@@ -461,6 +462,7 @@ msgid "%(user)s has created one link this month."
|
||||
msgid_plural "%(user)s has created %(links)s links this month."
|
||||
msgstr[0] ""
|
||||
msgstr[1] ""
|
||||
msgstr[2] ""
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkpersonalmonthlystatisticsview.html:48
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkview.html:27
|
||||
@@ -2141,6 +2143,7 @@ msgid "%(tasks)s task"
|
||||
msgid_plural "%(tasks)s tasks"
|
||||
msgstr[0] ""
|
||||
msgstr[1] ""
|
||||
msgstr[2] ""
|
||||
|
||||
#: allianceauth/templates/allianceauth/night-toggle.html:6
|
||||
msgid "Night Mode"
|
||||
|
||||
Binary file not shown.
@@ -5,11 +5,11 @@
|
||||
#
|
||||
# Translators:
|
||||
# François LACROIX-DURANT <umbre@fallenstarscreations.com>, 2020
|
||||
# Philippe Querin-Laporte <philippe.querin@hotmail.com>, 2020
|
||||
# Keven D. <theenarki@gmail.com>, 2020
|
||||
# Idea ., 2021
|
||||
# Mickael PATTE, 2021
|
||||
# Geoffrey Fabbro, 2021
|
||||
# Philippe Querin-Laporte <philippe.querin@hotmail.com>, 2022
|
||||
#
|
||||
#, fuzzy
|
||||
msgid ""
|
||||
@@ -18,13 +18,13 @@ msgstr ""
|
||||
"Report-Msgid-Bugs-To: \n"
|
||||
"POT-Creation-Date: 2021-11-29 01:03+1000\n"
|
||||
"PO-Revision-Date: 2020-02-18 03:14+0000\n"
|
||||
"Last-Translator: Geoffrey Fabbro, 2021\n"
|
||||
"Last-Translator: Philippe Querin-Laporte <philippe.querin@hotmail.com>, 2022\n"
|
||||
"Language-Team: French (France) (https://www.transifex.com/alliance-auth/teams/107430/fr_FR/)\n"
|
||||
"MIME-Version: 1.0\n"
|
||||
"Content-Type: text/plain; charset=UTF-8\n"
|
||||
"Content-Transfer-Encoding: 8bit\n"
|
||||
"Language: fr_FR\n"
|
||||
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
|
||||
"Plural-Forms: nplurals=3; plural=(n == 0 || n == 1) ? 0 : n != 0 && n % 1000000 == 0 ? 1 : 2;\n"
|
||||
|
||||
#: allianceauth/analytics/models.py:29
|
||||
msgid "Google Analytics Universal"
|
||||
@@ -460,6 +460,7 @@ msgid "%(user)s has collected one link this month."
|
||||
msgid_plural "%(user)s has collected %(links)s links this month."
|
||||
msgstr[0] "%(user)s a obtenu un lien ce mois."
|
||||
msgstr[1] "%(user)s a obtenu %(links)s liens ce mois."
|
||||
msgstr[2] "%(user)s a obtenu %(links)s liens ce mois."
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkpersonalmonthlystatisticsview.html:28
|
||||
msgid "Times used"
|
||||
@@ -471,6 +472,7 @@ msgid "%(user)s has created one link this month."
|
||||
msgid_plural "%(user)s has created %(links)s links this month."
|
||||
msgstr[0] "%(user)s a créé un lien ce mois."
|
||||
msgstr[1] "%(user)s a créé %(links)s liens ce mois."
|
||||
msgstr[2] "%(user)s a créé %(links)s liens ce mois."
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkpersonalmonthlystatisticsview.html:48
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkview.html:27
|
||||
@@ -2167,6 +2169,7 @@ msgid "%(tasks)s task"
|
||||
msgid_plural "%(tasks)s tasks"
|
||||
msgstr[0] ""
|
||||
msgstr[1] ""
|
||||
msgstr[2] ""
|
||||
|
||||
#: allianceauth/templates/allianceauth/night-toggle.html:6
|
||||
msgid "Night Mode"
|
||||
|
||||
Binary file not shown.
@@ -5,7 +5,7 @@
|
||||
#
|
||||
# Translators:
|
||||
# Alessandro Cresti, 2021
|
||||
# Linus Hope, 2021
|
||||
# Linus Hope, 2022
|
||||
#
|
||||
#, fuzzy
|
||||
msgid ""
|
||||
@@ -14,13 +14,13 @@ msgstr ""
|
||||
"Report-Msgid-Bugs-To: \n"
|
||||
"POT-Creation-Date: 2021-11-29 01:03+1000\n"
|
||||
"PO-Revision-Date: 2020-02-18 03:14+0000\n"
|
||||
"Last-Translator: Linus Hope, 2021\n"
|
||||
"Last-Translator: Linus Hope, 2022\n"
|
||||
"Language-Team: Italian (Italy) (https://www.transifex.com/alliance-auth/teams/107430/it_IT/)\n"
|
||||
"MIME-Version: 1.0\n"
|
||||
"Content-Type: text/plain; charset=UTF-8\n"
|
||||
"Content-Transfer-Encoding: 8bit\n"
|
||||
"Language: it_IT\n"
|
||||
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
|
||||
"Plural-Forms: nplurals=3; plural=n == 1 ? 0 : n != 0 && n % 1000000 == 0 ? 1 : 2;\n"
|
||||
|
||||
#: allianceauth/analytics/models.py:29
|
||||
msgid "Google Analytics Universal"
|
||||
@@ -460,6 +460,7 @@ msgid "%(user)s has collected one link this month."
|
||||
msgid_plural "%(user)s has collected %(links)s links this month."
|
||||
msgstr[0] "%(user)s ha ottenuto un link per questo mese."
|
||||
msgstr[1] "%(user)s ha ottenuto %(links)s links questo mese."
|
||||
msgstr[2] "%(user)s ha ottenuto %(links)s links questo mese."
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkpersonalmonthlystatisticsview.html:28
|
||||
msgid "Times used"
|
||||
@@ -471,6 +472,7 @@ msgid "%(user)s has created one link this month."
|
||||
msgid_plural "%(user)s has created %(links)s links this month."
|
||||
msgstr[0] "%(user)s ha creato un link questo mese."
|
||||
msgstr[1] "%(user)s ha creato %(links)s links questo mese."
|
||||
msgstr[2] "%(user)s ha creato %(links)s links questo mese."
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkpersonalmonthlystatisticsview.html:48
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkview.html:27
|
||||
@@ -2155,6 +2157,7 @@ msgid "%(tasks)s task"
|
||||
msgid_plural "%(tasks)s tasks"
|
||||
msgstr[0] ""
|
||||
msgstr[1] ""
|
||||
msgstr[2] ""
|
||||
|
||||
#: allianceauth/templates/allianceauth/night-toggle.html:6
|
||||
msgid "Night Mode"
|
||||
|
||||
Binary file not shown.
@@ -9,6 +9,7 @@
|
||||
# Olgeda Choi <undead.choi@gmail.com>, 2020
|
||||
# Lahty <js03js70@gmail.com>, 2020
|
||||
# Joel Falknau <ozirascal@gmail.com>, 2020
|
||||
# ThatRagingKid, 2022
|
||||
#
|
||||
#, fuzzy
|
||||
msgid ""
|
||||
@@ -17,7 +18,7 @@ msgstr ""
|
||||
"Report-Msgid-Bugs-To: \n"
|
||||
"POT-Creation-Date: 2021-11-29 01:03+1000\n"
|
||||
"PO-Revision-Date: 2020-02-18 03:14+0000\n"
|
||||
"Last-Translator: Joel Falknau <ozirascal@gmail.com>, 2020\n"
|
||||
"Last-Translator: ThatRagingKid, 2022\n"
|
||||
"Language-Team: Korean (Korea) (https://www.transifex.com/alliance-auth/teams/107430/ko_KR/)\n"
|
||||
"MIME-Version: 1.0\n"
|
||||
"Content-Type: text/plain; charset=UTF-8\n"
|
||||
@@ -27,15 +28,15 @@ msgstr ""
|
||||
|
||||
#: allianceauth/analytics/models.py:29
|
||||
msgid "Google Analytics Universal"
|
||||
msgstr ""
|
||||
msgstr "구글 애널리틱스 유니버설"
|
||||
|
||||
#: allianceauth/analytics/models.py:30
|
||||
msgid "Google Analytics V4"
|
||||
msgstr ""
|
||||
msgstr "구글 애널리틱스 V4"
|
||||
|
||||
#: allianceauth/authentication/decorators.py:37
|
||||
msgid "A main character is required to perform that action. Add one below."
|
||||
msgstr "해당 기능을 수행하려면 주 캐릭터가 요구됨. 아래에 하나를 추가하시오."
|
||||
msgstr "해당 기능을 수행하려면 주 캐릭터가 요구됨. 아래에서 하나를 추가하시오."
|
||||
|
||||
#: allianceauth/authentication/forms.py:5
|
||||
msgid "Email"
|
||||
@@ -65,7 +66,7 @@ msgid ""
|
||||
" "
|
||||
msgstr ""
|
||||
"\n"
|
||||
" 메인 캐릭터 (상태: %(state)s)\n"
|
||||
" 주 캐릭터 (상태: %(state)s)\n"
|
||||
" "
|
||||
|
||||
#: allianceauth/authentication/templates/authentication/dashboard.html:102
|
||||
@@ -103,7 +104,7 @@ msgstr "이름"
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkstatisticsview.html:23
|
||||
#: allianceauth/hrapplications/templates/hrapplications/view.html:46
|
||||
msgid "Corp"
|
||||
msgstr "콥"
|
||||
msgstr "코퍼레이션"
|
||||
|
||||
#: allianceauth/authentication/templates/authentication/dashboard.html:152
|
||||
#: allianceauth/corputils/templates/corputils/corpstats.html:76
|
||||
@@ -118,7 +119,7 @@ msgstr "로그인"
|
||||
|
||||
#: allianceauth/authentication/templates/public/register.html:7
|
||||
msgid "Registration"
|
||||
msgstr ""
|
||||
msgstr "가입"
|
||||
|
||||
#: allianceauth/authentication/templates/public/register.html:22
|
||||
#: allianceauth/authentication/templates/registration/registration_form.html:5
|
||||
@@ -137,7 +138,7 @@ msgstr "계정 패스워드 리셋을 요청하여 이 이메일을 보내드립
|
||||
|
||||
#: allianceauth/authentication/templates/registration/password_reset_email.html:5
|
||||
msgid "Please go to the following page and choose a new password:"
|
||||
msgstr "다음 페이지로 이동하여 새로운 패스워드를 입력하세요."
|
||||
msgstr "다음 페이지로 이동하여 새로운 패스워드를 입력하세요:"
|
||||
|
||||
#: allianceauth/authentication/templates/registration/password_reset_email.html:9
|
||||
msgid "Your username, in case you've forgotten:"
|
||||
@@ -176,7 +177,7 @@ msgstr "계정에 %(name)s를 추가했습니다."
|
||||
#: allianceauth/authentication/views.py:94
|
||||
#, python-format
|
||||
msgid "Failed to add %(name)s to your account: they already have an account."
|
||||
msgstr "계정에 %(name)s를 추가하지 못했습니다. 이미 추가된 계정입니다."
|
||||
msgstr "계정에 %(name)s를 추가하지 못했습니다. 이미 다른 계정에 추가되었습니다."
|
||||
|
||||
#: allianceauth/authentication/views.py:133
|
||||
msgid "Unable to authenticate as the selected character."
|
||||
@@ -184,7 +185,7 @@ msgstr "선택한 캐릭터로 인증을 수행할 수 없음"
|
||||
|
||||
#: allianceauth/authentication/views.py:197
|
||||
msgid "Registration token has expired."
|
||||
msgstr "등록토큰 만료"
|
||||
msgstr "가입 토큰이 만료되었습니다."
|
||||
|
||||
#: allianceauth/authentication/views.py:252
|
||||
msgid ""
|
||||
@@ -202,16 +203,16 @@ msgstr "현재 새로운 계정 등록은 받지않습니다."
|
||||
|
||||
#: allianceauth/corputils/auth_hooks.py:11
|
||||
msgid "Corporation Stats"
|
||||
msgstr "콥 상태"
|
||||
msgstr "코퍼레이션 상태"
|
||||
|
||||
#: allianceauth/corputils/templates/corputils/base.html:3
|
||||
#: allianceauth/corputils/templates/corputils/base.html:6
|
||||
msgid "Corporation Member Data"
|
||||
msgstr "콥 멤버 데이터"
|
||||
msgstr "코퍼레이션 멤버 정보"
|
||||
|
||||
#: allianceauth/corputils/templates/corputils/base.html:12
|
||||
msgid "Corporations"
|
||||
msgstr "콥"
|
||||
msgstr "코퍼레이션"
|
||||
|
||||
#: allianceauth/corputils/templates/corputils/base.html:23
|
||||
msgid "Add"
|
||||
@@ -219,7 +220,7 @@ msgstr "추가"
|
||||
|
||||
#: allianceauth/corputils/templates/corputils/base.html:29
|
||||
msgid "Search all corporations..."
|
||||
msgstr "모든 콥 검색"
|
||||
msgstr "모든 코퍼레이션 검색"
|
||||
|
||||
#: allianceauth/corputils/templates/corputils/corpstats.html:33
|
||||
msgid "Mains"
|
||||
@@ -237,7 +238,7 @@ msgstr "미등록"
|
||||
|
||||
#: allianceauth/corputils/templates/corputils/corpstats.html:38
|
||||
msgid "Last update:"
|
||||
msgstr "마지막 업데이트"
|
||||
msgstr "마지막 업데이트:"
|
||||
|
||||
#: allianceauth/corputils/templates/corputils/corpstats.html:74
|
||||
#: allianceauth/corputils/templates/corputils/corpstats.html:112
|
||||
@@ -260,7 +261,7 @@ msgstr "캐릭터"
|
||||
#: allianceauth/hrapplications/templates/hrapplications/management.html:126
|
||||
#: allianceauth/hrapplications/templates/hrapplications/searchview.html:26
|
||||
msgid "Corporation"
|
||||
msgstr "콥"
|
||||
msgstr "코퍼레이션"
|
||||
|
||||
#: allianceauth/corputils/templates/corputils/corpstats.html:91
|
||||
#: allianceauth/corputils/templates/corputils/corpstats.html:125
|
||||
@@ -268,7 +269,7 @@ msgstr "콥"
|
||||
#: allianceauth/corputils/templates/corputils/corpstats.html:167
|
||||
#: allianceauth/corputils/templates/corputils/search.html:27
|
||||
msgid "Killboard"
|
||||
msgstr "킬보드"
|
||||
msgstr "사살권"
|
||||
|
||||
#: allianceauth/corputils/templates/corputils/corpstats.html:114
|
||||
#: allianceauth/corputils/templates/corputils/search.html:16
|
||||
@@ -283,12 +284,12 @@ msgstr "주 캐릭터"
|
||||
#: allianceauth/corputils/templates/corputils/corpstats.html:115
|
||||
#: allianceauth/corputils/templates/corputils/search.html:17
|
||||
msgid "Main Corporation"
|
||||
msgstr "메인콥"
|
||||
msgstr "주 코퍼레이션"
|
||||
|
||||
#: allianceauth/corputils/templates/corputils/corpstats.html:116
|
||||
#: allianceauth/corputils/templates/corputils/search.html:18
|
||||
msgid "Main Alliance"
|
||||
msgstr "메인 얼라이언스"
|
||||
msgstr "주 얼라이언스"
|
||||
|
||||
#: allianceauth/corputils/templates/corputils/search.html:6
|
||||
msgid "Search Results"
|
||||
@@ -296,28 +297,28 @@ msgstr "검색결과"
|
||||
|
||||
#: allianceauth/corputils/templates/corputils/search.html:15
|
||||
msgid "zKillboard"
|
||||
msgstr "킬보드"
|
||||
msgstr "zKillboard"
|
||||
|
||||
#: allianceauth/corputils/views.py:54
|
||||
msgid "Selected corp already has a statistics module."
|
||||
msgstr "선택한 콥은 이미 통계 모듈을 갖고있습니다."
|
||||
msgstr "선택한 코퍼레이션은 이미 통계 모듈을 갖고 있습니다."
|
||||
|
||||
#: allianceauth/corputils/views.py:56
|
||||
msgid "Failed to gather corporation statistics with selected token."
|
||||
msgstr "선택한 토큰으로 콥 통계 수집 실패"
|
||||
msgstr "선택한 토큰으로 코퍼레이션 통계 수집에 실패했습니다."
|
||||
|
||||
#: allianceauth/fleetactivitytracking/auth_hooks.py:9
|
||||
msgid "Fleet Activity Tracking"
|
||||
msgstr "플릿활동 추적"
|
||||
msgstr "함대 활동"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/forms.py:6 allianceauth/srp/form.py:8
|
||||
#: allianceauth/srp/templates/srp/management.html:37
|
||||
msgid "Fleet Name"
|
||||
msgstr "플릿 이름"
|
||||
msgstr "함대 이름"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/forms.py:7
|
||||
msgid "Duration of fat-link"
|
||||
msgstr "플릿활동추적 링크 주기"
|
||||
msgstr "함대 활동 링크 주기"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/forms.py:7
|
||||
msgid "minutes"
|
||||
@@ -325,7 +326,7 @@ msgstr "분"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/characternotexisting.html:3
|
||||
msgid "Fleet Participation"
|
||||
msgstr "플릿 참여"
|
||||
msgstr "함대 참여"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/characternotexisting.html:7
|
||||
msgid "Character not found!"
|
||||
@@ -337,25 +338,25 @@ msgstr "캐릭터가 등록되지 않음!"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/characternotexisting.html:19
|
||||
msgid "This character is not associated with an auth account."
|
||||
msgstr "해당 캐릭터는 본 계정에 연결되어있지 않음."
|
||||
msgstr "해당 캐릭터는 본 계정에 연결되어 있지 않습니다."
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/characternotexisting.html:19
|
||||
msgid "Add it here"
|
||||
msgstr "여기서 추가"
|
||||
msgstr "여기에 추가하시오"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/characternotexisting.html:19
|
||||
msgid "before attempting to click fleet attendance links."
|
||||
msgstr "플릿 참여 링크를 클릭하기 전에"
|
||||
msgstr "함대 참여 링크를 클릭하기 전"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkformatter.html:6
|
||||
msgid "Create Fatlink"
|
||||
msgstr "플릿활동추적 생성"
|
||||
msgstr "함대 활동 링크 생성"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkformatter.html:10
|
||||
#: allianceauth/optimer/templates/optimer/add.html:14
|
||||
#: allianceauth/optimer/templates/optimer/add.html:23
|
||||
msgid "Create Fleet Operation"
|
||||
msgstr "플릿 옵 생성"
|
||||
msgstr "함대 오퍼레이션 생성"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkformatter.html:14
|
||||
msgid "Bad request!"
|
||||
@@ -364,20 +365,20 @@ msgstr "잘못된 요청!"
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkformatter.html:25
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkview.html:65
|
||||
msgid "Create fatlink"
|
||||
msgstr "플릿활동추적 링크 생성"
|
||||
msgstr "함대 활동 링크 생성"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkmodify.html:5
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkview.html:6
|
||||
msgid "Fatlink view"
|
||||
msgstr "플릿활동추적 링크 보기"
|
||||
msgstr "함대 활동 링크 보기"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkmodify.html:9
|
||||
msgid "Edit fatlink"
|
||||
msgstr "플릿활동추적 수정"
|
||||
msgstr "함대 활동 링크 수정"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkmodify.html:13
|
||||
msgid "Delete fat"
|
||||
msgstr "플릿활동추적 수정"
|
||||
msgstr "함대 활동 링크 삭제"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkmodify.html:19
|
||||
msgid "Registered characters"
|
||||
@@ -401,7 +402,7 @@ msgstr "시스템"
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkpersonalmonthlystatisticsview.html:27
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkview.html:30
|
||||
msgid "Ship"
|
||||
msgstr "배"
|
||||
msgstr "함선"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkmodify.html:27
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkpersonalmonthlystatisticsview.html:50
|
||||
@@ -422,7 +423,7 @@ msgstr "도킹"
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkpersonalmonthlystatisticsview.html:6
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkpersonalstatisticsview.html:6
|
||||
msgid "Personal fatlink statistics"
|
||||
msgstr "개인별 플릿활동추적 통계"
|
||||
msgstr "개인별 함대 활동 링크 통계"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkpersonalmonthlystatisticsview.html:10
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkstatisticscorpview.html:10
|
||||
@@ -492,11 +493,11 @@ msgstr "%(year)s년 동안의 참여 통계자료"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkpersonalstatisticsview.html:12
|
||||
msgid "Previous year"
|
||||
msgstr "지난 해"
|
||||
msgstr "작년"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkpersonalstatisticsview.html:14
|
||||
msgid "Next year"
|
||||
msgstr "다음 해"
|
||||
msgstr "내년"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkpersonalstatisticsview.html:21
|
||||
msgid "Month"
|
||||
@@ -506,20 +507,20 @@ msgstr "달"
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkstatisticscorpview.html:24
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkstatisticsview.html:25
|
||||
msgid "Fats"
|
||||
msgstr "플릿활동추적"
|
||||
msgstr "함대 활동"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkstatisticscorpview.html:6
|
||||
msgid "Fatlink Corp Statistics"
|
||||
msgstr "콥별 플릿활동추적 통계"
|
||||
msgstr "코퍼레이션별 함대 활동 통계"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkstatisticscorpview.html:25
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkstatisticsview.html:26
|
||||
msgid "Average fats"
|
||||
msgstr "평균 플릿활동추적"
|
||||
msgstr "평균 함대 활동"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkstatisticsview.html:6
|
||||
msgid "Fatlink statistics"
|
||||
msgstr "플릿활동추적 통계"
|
||||
msgstr "함대 활동 통계"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkstatisticsview.html:22
|
||||
msgid "Ticker"
|
||||
@@ -531,7 +532,7 @@ msgstr "참여 자료"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkview.html:14
|
||||
msgid "Most recent clicked fatlinks"
|
||||
msgstr "가장 최근에 클릭한 플릿활동추적 링크"
|
||||
msgstr "가장 최근에 클릭한 함대 활동 링크"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkview.html:19
|
||||
msgid "Personal statistics"
|
||||
@@ -539,11 +540,11 @@ msgstr "개인별 통계"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkview.html:48
|
||||
msgid "No fleet activity on record."
|
||||
msgstr "플릿 활동기록이 없음"
|
||||
msgstr "함대 활동 기록이 없음"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkview.html:55
|
||||
msgid "Most recent fatlinks"
|
||||
msgstr "가장 최근의 플릿활동추적 링크"
|
||||
msgstr "가장 최근의 함대 활동 링크"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkview.html:60
|
||||
msgid "View statistics"
|
||||
@@ -551,27 +552,27 @@ msgstr "통계 보기"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/templates/fleetactivitytracking/fatlinkview.html:97
|
||||
msgid "No created fatlinks on record."
|
||||
msgstr "생성된 플릿활동추적 링크 기록이 없음"
|
||||
msgstr "생성된 함대 활동 링크 기록이 없음"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/views.py:280
|
||||
msgid "Fleet participation registered."
|
||||
msgstr "플릿 참여 등록됨"
|
||||
msgstr "함대 참여 등록됨"
|
||||
|
||||
#: allianceauth/fleetactivitytracking/views.py:296
|
||||
msgid "FAT link has expired."
|
||||
msgstr "플릿활동추적 링크 기한만료"
|
||||
msgstr "함대 활동 링크 기한만료"
|
||||
|
||||
#: allianceauth/groupmanagement/admin.py:104
|
||||
msgid "This name has been reserved and can not be used for groups."
|
||||
msgstr ""
|
||||
msgstr "이 이름은 이미 할당되었고 그룹의 이름으로 사용될 수 없습니다."
|
||||
|
||||
#: allianceauth/groupmanagement/admin.py:230
|
||||
msgid "(auto)"
|
||||
msgstr ""
|
||||
msgstr "(자동)"
|
||||
|
||||
#: allianceauth/groupmanagement/admin.py:239
|
||||
msgid "There already exists a group with that name."
|
||||
msgstr ""
|
||||
msgstr "이 이름을 가진 그룹이 이미 있습니다."
|
||||
|
||||
#: allianceauth/groupmanagement/auth_hooks.py:17
|
||||
#: allianceauth/groupmanagement/templates/groupmanagement/menu.html:14
|
||||
@@ -584,10 +585,12 @@ msgid ""
|
||||
"group.<br>Used for groups such as Members, Corp_*, Alliance_* "
|
||||
"etc.<br><b>Overrides Hidden and Open options when selected.</b>"
|
||||
msgstr ""
|
||||
"시스템 그룹, 유저들은 이 그룹을 보거나, 참여하거나, 지원할 수 없습니다. <br>멤버, 코퍼레이션_*, 얼라이언스_* 등에 "
|
||||
"사용됨.<br><b>선택된 경우 비공개와 공개 옵션을 무시함.</b>"
|
||||
|
||||
#: allianceauth/groupmanagement/models.py:110
|
||||
msgid "Group is hidden from users but can still join with the correct link."
|
||||
msgstr ""
|
||||
msgstr "비공개 그룹이지만 링크를 통해 참여할 수 있음."
|
||||
|
||||
#: allianceauth/groupmanagement/models.py:116
|
||||
msgid ""
|
||||
@@ -670,7 +673,7 @@ msgstr "감사 기록"
|
||||
#: allianceauth/permissions_tool/templates/permissions_tool/audit.html:13
|
||||
#: allianceauth/timerboard/templates/timerboard/index_button.html:3
|
||||
msgid "Back"
|
||||
msgstr "돌아가기"
|
||||
msgstr "뒤로"
|
||||
|
||||
#: allianceauth/groupmanagement/templates/groupmanagement/audit.html:28
|
||||
msgid "Date/Time"
|
||||
@@ -984,15 +987,15 @@ msgstr "문자열 검색"
|
||||
#: allianceauth/hrapplications/templates/hrapplications/corpchoice.html:5
|
||||
#: allianceauth/hrapplications/templates/hrapplications/corpchoice.html:8
|
||||
msgid "Choose a Corp"
|
||||
msgstr "콥 선택"
|
||||
msgstr "코퍼레이션 선택"
|
||||
|
||||
#: allianceauth/hrapplications/templates/hrapplications/corpchoice.html:11
|
||||
msgid "Available Corps"
|
||||
msgstr "사용 가능한 콥"
|
||||
msgstr "사용 가능한 코퍼레이션"
|
||||
|
||||
#: allianceauth/hrapplications/templates/hrapplications/corpchoice.html:23
|
||||
msgid "No corps are accepting applications at this time."
|
||||
msgstr "현재 입사지원 가능한 콥이 없습니다."
|
||||
msgstr "현재 입사지원 가능한 코퍼레이션이 없습니다."
|
||||
|
||||
#: allianceauth/hrapplications/templates/hrapplications/create.html:5
|
||||
#: allianceauth/hrapplications/templates/hrapplications/create.html:8
|
||||
@@ -1222,7 +1225,7 @@ msgstr "모든 읽은 알림을 삭제했습니다."
|
||||
|
||||
#: allianceauth/optimer/auth_hooks.py:10
|
||||
msgid "Fleet Operations"
|
||||
msgstr "플릿 옵"
|
||||
msgstr "함대 옵"
|
||||
|
||||
#: allianceauth/optimer/form.py:12
|
||||
#: allianceauth/optimer/templates/optimer/fleetoptable.html:11
|
||||
@@ -1246,7 +1249,7 @@ msgstr ""
|
||||
#: allianceauth/optimer/form.py:17
|
||||
#: allianceauth/srp/templates/srp/management.html:40
|
||||
msgid "Fleet Commander"
|
||||
msgstr "플릿 커맨더"
|
||||
msgstr "함대 커맨더"
|
||||
|
||||
#: allianceauth/optimer/form.py:22 allianceauth/srp/form.py:14
|
||||
#: allianceauth/srp/templates/srp/data.html:93
|
||||
@@ -1279,11 +1282,11 @@ msgstr "FC"
|
||||
|
||||
#: allianceauth/optimer/templates/optimer/management.html:6
|
||||
msgid "Fleet Operation Management"
|
||||
msgstr "플릿 옵 관리"
|
||||
msgstr "함대 옵 관리"
|
||||
|
||||
#: allianceauth/optimer/templates/optimer/management.html:11
|
||||
msgid "Fleet Operation Timers"
|
||||
msgstr "플릿 옵 타이머"
|
||||
msgstr "함대 옵 타이머"
|
||||
|
||||
#: allianceauth/optimer/templates/optimer/management.html:21
|
||||
#: allianceauth/timerboard/templates/timerboard/view.html:23
|
||||
@@ -1312,11 +1315,11 @@ msgstr "최근 지나간 옵 타이머가 없습니다."
|
||||
#: allianceauth/optimer/templates/optimer/update.html:16
|
||||
#: allianceauth/optimer/templates/optimer/update.html:28
|
||||
msgid "Update Fleet Operation"
|
||||
msgstr "플릿 옵 수정"
|
||||
msgstr "함대 옵 수정"
|
||||
|
||||
#: allianceauth/optimer/templates/optimer/update.html:22
|
||||
msgid "Fleet Operation Does Not Exist"
|
||||
msgstr "존재하지 않는 플릿 옵"
|
||||
msgstr "존재하지 않는 함대 옵"
|
||||
|
||||
#: allianceauth/optimer/views.py:69
|
||||
#, python-format
|
||||
@@ -1434,23 +1437,23 @@ msgstr "서드파티"
|
||||
|
||||
#: allianceauth/services/forms.py:6
|
||||
msgid "Name of Fleet:"
|
||||
msgstr "플릿 이름:"
|
||||
msgstr "함대 이름:"
|
||||
|
||||
#: allianceauth/services/forms.py:7
|
||||
msgid "Fleet Commander:"
|
||||
msgstr "플릿 커맨더:"
|
||||
msgstr "함대 커맨더:"
|
||||
|
||||
#: allianceauth/services/forms.py:8
|
||||
msgid "Fleet Comms:"
|
||||
msgstr "플릿 음성 채널:"
|
||||
msgstr "함대 음성 채널:"
|
||||
|
||||
#: allianceauth/services/forms.py:9
|
||||
msgid "Fleet Type:"
|
||||
msgstr "플릿 타입:"
|
||||
msgstr "함대 타입:"
|
||||
|
||||
#: allianceauth/services/forms.py:10
|
||||
msgid "Ship Priorities:"
|
||||
msgstr "플릿 우선도:"
|
||||
msgstr "함대 우선도:"
|
||||
|
||||
#: allianceauth/services/forms.py:11
|
||||
msgid "Formup Location:"
|
||||
@@ -1595,7 +1598,7 @@ msgstr "재버 방송"
|
||||
|
||||
#: allianceauth/services/modules/openfire/auth_hooks.py:94
|
||||
msgid "Fleet Broadcast Formatter"
|
||||
msgstr "플릿 신호 설정"
|
||||
msgstr "함대 신호 설정"
|
||||
|
||||
#: allianceauth/services/modules/openfire/forms.py:7
|
||||
msgid "Message"
|
||||
@@ -1749,11 +1752,11 @@ msgstr "XenForo 비밀번호 변경 완료"
|
||||
|
||||
#: allianceauth/services/templates/services/fleetformattertool.html:6
|
||||
msgid "Fleet Formatter Tool"
|
||||
msgstr "플릿 구성 도구"
|
||||
msgstr "함대 구성 도구"
|
||||
|
||||
#: allianceauth/services/templates/services/fleetformattertool.html:11
|
||||
msgid "Fleet Broadcast Formatter Tool"
|
||||
msgstr "플릿 브로드캐스트 설정 도구"
|
||||
msgstr "함대 브로드캐스트 설정 도구"
|
||||
|
||||
#: allianceauth/services/templates/services/fleetformattertool.html:24
|
||||
msgid "Format"
|
||||
@@ -1814,12 +1817,12 @@ msgstr "SRP"
|
||||
#: allianceauth/srp/form.py:9
|
||||
#: allianceauth/srp/templates/srp/management.html:38
|
||||
msgid "Fleet Time"
|
||||
msgstr "플릿 시간"
|
||||
msgstr "함대 시간"
|
||||
|
||||
#: allianceauth/srp/form.py:10
|
||||
#: allianceauth/srp/templates/srp/management.html:39
|
||||
msgid "Fleet Doctrine"
|
||||
msgstr "플릿 독트린"
|
||||
msgstr "함대 독트린"
|
||||
|
||||
#: allianceauth/srp/form.py:16
|
||||
msgid "Killboard Link (zkillboard.com or kb.evetools.org)"
|
||||
@@ -1839,12 +1842,12 @@ msgstr "사후조치 보고서 링크"
|
||||
|
||||
#: allianceauth/srp/templates/srp/add.html:6
|
||||
msgid "SRP Fleet Create"
|
||||
msgstr "SRP 보상 플릿 생성"
|
||||
msgstr "SRP 보상 함대 생성"
|
||||
|
||||
#: allianceauth/srp/templates/srp/add.html:14
|
||||
#: allianceauth/srp/templates/srp/add.html:24
|
||||
msgid "Create SRP Fleet"
|
||||
msgstr "SRP 보상 플릿 생성"
|
||||
msgstr "SRP 보상 함대 생성"
|
||||
|
||||
#: allianceauth/srp/templates/srp/add.html:27
|
||||
msgid "Give this link to the line members"
|
||||
@@ -1852,7 +1855,7 @@ msgstr "이 링크를 직계 멤버들에게 전달"
|
||||
|
||||
#: allianceauth/srp/templates/srp/data.html:52
|
||||
msgid "SRP Fleet Data"
|
||||
msgstr "SRP 보상 플릿 데이터"
|
||||
msgstr "SRP 보상 함대 데이터"
|
||||
|
||||
#: allianceauth/srp/templates/srp/data.html:57
|
||||
msgid "Mark Incomplete"
|
||||
@@ -1908,7 +1911,7 @@ msgstr "작성 시간"
|
||||
|
||||
#: allianceauth/srp/templates/srp/data.html:178
|
||||
msgid "No SRP requests for this fleet."
|
||||
msgstr "이 플릿에는 SRP 보상 요청이 없습니다."
|
||||
msgstr "이 함대에는 SRP 보상 요청이 없습니다."
|
||||
|
||||
#: allianceauth/srp/templates/srp/management.html:8
|
||||
msgid "Srp Management"
|
||||
@@ -1924,19 +1927,19 @@ msgstr "모두 조회하기"
|
||||
|
||||
#: allianceauth/srp/templates/srp/management.html:23
|
||||
msgid "Add SRP Fleet"
|
||||
msgstr "SRP 보상 플릿 추가"
|
||||
msgstr "SRP 보상 함대 추가"
|
||||
|
||||
#: allianceauth/srp/templates/srp/management.html:41
|
||||
msgid "Fleet AAR"
|
||||
msgstr "플릿 사후처리 보고서"
|
||||
msgstr "함대 사후처리 보고서"
|
||||
|
||||
#: allianceauth/srp/templates/srp/management.html:42
|
||||
msgid "Fleet SRP Code"
|
||||
msgstr "플릿 SRP 보상 코드"
|
||||
msgstr "함대 SRP 보상 코드"
|
||||
|
||||
#: allianceauth/srp/templates/srp/management.html:43
|
||||
msgid "Fleet ISK Cost"
|
||||
msgstr "플릿 ISK 비용"
|
||||
msgstr "함대 ISK 비용"
|
||||
|
||||
#: allianceauth/srp/templates/srp/management.html:44
|
||||
msgid "SRP Status"
|
||||
@@ -1983,37 +1986,37 @@ msgstr "사후처리 보고서 링크 업데이트"
|
||||
|
||||
#: allianceauth/srp/templates/srp/update.html:17
|
||||
msgid "SRP Fleet Does Not Exist"
|
||||
msgstr "SRP 보상 플릿이 존재하지 않습니다."
|
||||
msgstr "SRP 보상 함대이 존재하지 않습니다."
|
||||
|
||||
#: allianceauth/srp/views.py:85
|
||||
#, python-format
|
||||
msgid "Created SRP fleet %(fleetname)s."
|
||||
msgstr "SRP 보상 플릿 %(fleetname)s 생성 완료"
|
||||
msgstr "SRP 보상 함대 %(fleetname)s 생성 완료"
|
||||
|
||||
#: allianceauth/srp/views.py:103
|
||||
#, python-format
|
||||
msgid "Removed SRP fleet %(fleetname)s."
|
||||
msgstr "SRP 보상 플릿 %(fleetname)s삭제 완료"
|
||||
msgstr "SRP 보상 함대 %(fleetname)s삭제 완료"
|
||||
|
||||
#: allianceauth/srp/views.py:115
|
||||
#, python-format
|
||||
msgid "Disabled SRP fleet %(fleetname)s."
|
||||
msgstr "SRP 보상 플릿 %(fleetname)s비활성화 완료"
|
||||
msgstr "SRP 보상 함대 %(fleetname)s비활성화 완료"
|
||||
|
||||
#: allianceauth/srp/views.py:127
|
||||
#, python-format
|
||||
msgid "Enabled SRP fleet %(fleetname)s."
|
||||
msgstr "SRP 보상 플릿 %(fleetname)s 활성화 완료"
|
||||
msgstr "SRP 보상 함대 %(fleetname)s 활성화 완료"
|
||||
|
||||
#: allianceauth/srp/views.py:140
|
||||
#, python-format
|
||||
msgid "Marked SRP fleet %(fleetname)s as completed."
|
||||
msgstr "SRP 보상 플릿 %(fleetname)s 을 완료된 것으로 표시"
|
||||
msgstr "SRP 보상 함대 %(fleetname)s 을 완료된 것으로 표시"
|
||||
|
||||
#: allianceauth/srp/views.py:153
|
||||
#, python-format
|
||||
msgid "Marked SRP fleet %(fleetname)s as incomplete."
|
||||
msgstr "SRP 보상 플릿 %(fleetname)s 을 미완료된 것으로 표시"
|
||||
msgstr "SRP 보상 함대 %(fleetname)s 을 미완료된 것으로 표시"
|
||||
|
||||
#: allianceauth/srp/views.py:165
|
||||
#, python-format
|
||||
@@ -2079,7 +2082,7 @@ msgstr "SRP 보상 요청 %(requestid)s을 찾을 수 없습니다. "
|
||||
#: allianceauth/srp/views.py:360
|
||||
#, python-format
|
||||
msgid "Saved changes to SRP fleet %(fleetname)s"
|
||||
msgstr "SRP 보상 요청 플릿 %(fleetname)s의 변경 사항이 저장되었습니다."
|
||||
msgstr "SRP 보상 요청 함대 %(fleetname)s의 변경 사항이 저장되었습니다."
|
||||
|
||||
#: allianceauth/templates/allianceauth/admin-status/overview.html:6
|
||||
msgid "Alliance Auth Notifications"
|
||||
@@ -2229,7 +2232,7 @@ msgstr "중요"
|
||||
|
||||
#: allianceauth/timerboard/form.py:70
|
||||
msgid "Corp-Restricted"
|
||||
msgstr "콥 제한"
|
||||
msgstr "코퍼레이션 제한"
|
||||
|
||||
#: allianceauth/timerboard/models.py:14
|
||||
msgid "Not Specified"
|
||||
@@ -2294,7 +2297,7 @@ msgstr "스트럭처 타이머"
|
||||
|
||||
#: allianceauth/timerboard/templates/timerboard/view.html:28
|
||||
msgid "Corp Timers"
|
||||
msgstr "콥 타이머"
|
||||
msgstr "코퍼레이션 타이머"
|
||||
|
||||
#: allianceauth/timerboard/templates/timerboard/view.html:35
|
||||
#: allianceauth/timerboard/templates/timerboard/view.html:202
|
||||
|
||||
@@ -1,9 +1,3 @@
|
||||
from .core import notify # noqa: F401
|
||||
|
||||
default_app_config = 'allianceauth.notifications.apps.NotificationsConfig'
|
||||
|
||||
|
||||
def notify(
|
||||
user: object, title: str, message: str = None, level: str = 'info'
|
||||
) -> None:
|
||||
"""Sends a new notification to user. Convenience function to manager pendant."""
|
||||
from .models import Notification
|
||||
Notification.objects.notify_user(user, title, message, level)
|
||||
|
||||
33
allianceauth/notifications/core.py
Normal file
33
allianceauth/notifications/core.py
Normal file
@@ -0,0 +1,33 @@
|
||||
class NotifyApiWrapper:
|
||||
"""Wrapper to create notify API."""
|
||||
|
||||
def __call__(self, *args, **kwargs): # provide old API for backwards compatibility
|
||||
return self._add_notification(*args, **kwargs)
|
||||
|
||||
def danger(self, user: object, title: str, message: str = None) -> None:
|
||||
"""Add danger notification for user."""
|
||||
self._add_notification(user, title, message, level="danger")
|
||||
|
||||
def info(self, user: object, title: str, message: str = None) -> None:
|
||||
"""Add info notification for user."""
|
||||
self._add_notification(user=user, title=title, message=message, level="info")
|
||||
|
||||
def success(self, user: object, title: str, message: str = None) -> None:
|
||||
"""Add success notification for user."""
|
||||
self._add_notification(user, title, message, level="success")
|
||||
|
||||
def warning(self, user: object, title: str, message: str = None) -> None:
|
||||
"""Add warning notification for user."""
|
||||
self._add_notification(user, title, message, level="warning")
|
||||
|
||||
def _add_notification(
|
||||
self, user: object, title: str, message: str = None, level: str = "info"
|
||||
) -> None:
|
||||
from .models import Notification
|
||||
|
||||
Notification.objects.notify_user(
|
||||
user=user, title=title, message=message, level=level
|
||||
)
|
||||
|
||||
|
||||
notify = NotifyApiWrapper()
|
||||
@@ -5,91 +5,34 @@
|
||||
{% block page_title %}{% translate "Notifications" %}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="col-lg-12">
|
||||
<h1 class="page-header text-center">{% translate "Notifications" %}</h1>
|
||||
<div class="col-lg-12 container" id="example">
|
||||
<div class="row">
|
||||
<div class="col-lg-12">
|
||||
<div class="panel panel-default">
|
||||
<div class="panel-heading">
|
||||
<ul class="nav nav-pills">
|
||||
<li class="active"><a data-toggle="pill" href="#unread">{% translate "Unread" %}
|
||||
<b>({{ unread|length }})</b></a></li>
|
||||
<li><a data-toggle="pill" href="#read">{% translate "Read" %} <b>({{ read|length }})</b></a>
|
||||
</li>
|
||||
<div class="pull-right">
|
||||
<a href="{% url 'notifications:mark_all_read' %}" class="btn btn-primary">{% translate "Mark All Read" %}</a>
|
||||
<a href="{% url 'notifications:delete_all_read' %}" class="btn btn-danger">{% translate "Delete All Read" %}</a>
|
||||
</div>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<div class="tab-content">
|
||||
<div id="unread" class="tab-pane fade in active">
|
||||
<div class="table-responsive">
|
||||
{% if unread %}
|
||||
<table class="table table-condensed table-hover table-striped">
|
||||
<tr>
|
||||
<th class="text-center">{% translate "Timestamp" %}</th>
|
||||
<th class="text-center">{% translate "Title" %}</th>
|
||||
<th class="text-center">{% translate "Action" %}</th>
|
||||
</tr>
|
||||
{% for notif in unread %}
|
||||
<tr class="{{ notif.level }}">
|
||||
<td class="text-center">{{ notif.timestamp }}</td>
|
||||
<td class="text-center">{{ notif.title }}</td>
|
||||
<td class="text-center">
|
||||
<a href="{% url 'notifications:view' notif.id %}" class="btn btn-success" title="View">
|
||||
<span class="glyphicon glyphicon-eye-open"></span>
|
||||
</a>
|
||||
<a href="{% url 'notifications:remove' notif.id %}" class="btn btn-danger" title="Remove">
|
||||
<span class="glyphicon glyphicon-remove"></span>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
{% else %}
|
||||
<div class="alert alert-warning text-center">{% translate "No unread notifications." %}</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
<div id="read" class="tab-pane fade">
|
||||
<div class="panel-body">
|
||||
<div class="table-responsive">
|
||||
{% if read %}
|
||||
<table class="table table-condensed table-hover table-striped">
|
||||
<tr>
|
||||
<th class="text-center">{% translate "Timestamp" %}</th>
|
||||
<th class="text-center">{% translate "Title" %}</th>
|
||||
<th class="text-center">{% translate "Action" %}</th>
|
||||
</tr>
|
||||
{% for notif in read %}
|
||||
<tr class="{{ notif.level }}">
|
||||
<td class="text-center">{{ notif.timestamp }}</td>
|
||||
<td class="text-center">{{ notif.title }}</td>
|
||||
<td class="text-center">
|
||||
<a href="{% url 'notifications:view' notif.id %}" class="btn btn-success" title="View">
|
||||
<span class="glyphicon glyphicon-eye-open"></span>
|
||||
</a>
|
||||
<a href="{% url 'notifications:remove' notif.id %}" class="btn btn-danger" title="remove">
|
||||
<span class="glyphicon glyphicon-remove"></span>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
{% else %}
|
||||
<div class="alert alert-warning text-center">{% translate "No read notifications." %}</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<h1 class="page-header text-center">{% translate "Notifications" %}</h1>
|
||||
|
||||
<div class="panel panel-default">
|
||||
|
||||
<div class="panel-heading">
|
||||
<ul class="nav nav-pills">
|
||||
<li class="active"><a data-toggle="tab" href="#unread">{% translate "Unread" %}<b>({{ unread|length }})</b></a></li>
|
||||
<li><a data-toggle="tab" href="#read">{% translate "Read" %} <b>({{ read|length }})</b></a></li>
|
||||
<div class="pull-right">
|
||||
<a href="{% url 'notifications:mark_all_read' %}" class="btn btn-warning">{% translate "Mark All Read" %}</a>
|
||||
<a href="{% url 'notifications:delete_all_read' %}" class="btn btn-danger">{% translate "Delete All Read" %}</a>
|
||||
</div>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="panel-body">
|
||||
<div class="tab-content">
|
||||
|
||||
<div id="unread" class="tab-pane fade in active">
|
||||
{% include "notifications/list_partial.html" with notifications=unread %}
|
||||
</div>
|
||||
|
||||
<div id="read" class="tab-pane fade">
|
||||
{% include "notifications/list_partial.html" with notifications=read %}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
{% load i18n %}
|
||||
|
||||
{% if notifications %}
|
||||
<div class="table-responsive">
|
||||
<table class="table table-condensed table-hover table-striped">
|
||||
<tr>
|
||||
<th class="text-center">{% translate "Timestamp" %}</th>
|
||||
<th class="text-center">{% translate "Title" %}</th>
|
||||
<th class="text-center">{% translate "Action" %}</th>
|
||||
</tr>
|
||||
{% for notif in notifications %}
|
||||
<tr class="{{ notif.level }}">
|
||||
<td class="text-center">{{ notif.timestamp }}</td>
|
||||
<td class="text-center">{{ notif.title }}</td>
|
||||
<td class="text-center">
|
||||
<a href="{% url 'notifications:view' notif.id %}" class="btn btn-primary" title="View">
|
||||
<span class="glyphicon glyphicon-eye-open"></span>
|
||||
</a>
|
||||
<a href="{% url 'notifications:remove' notif.id %}" class="btn btn-danger" title="Remove">
|
||||
<span class="glyphicon glyphicon-remove"></span>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</table>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="alert alert-default text-center">{% translate "No notifications." %}</div>
|
||||
{% endif %}
|
||||
@@ -5,25 +5,22 @@
|
||||
{% block page_title %}{% translate "View Notification" %}{% endblock page_title %}
|
||||
|
||||
{% block content %}
|
||||
<h1 class="page-header text-center">
|
||||
{% translate "View Notification" %}
|
||||
<div class="text-right">
|
||||
<a href="{% url 'notifications:list' %}" class="btn btn-primary btn-lg">
|
||||
<span class="glyphicon glyphicon-arrow-left"></span>
|
||||
</a>
|
||||
</div>
|
||||
</h1>
|
||||
|
||||
<div class="col-lg-12">
|
||||
<h1 class="page-header text-center">
|
||||
{% translate "View Notification" %}
|
||||
<div class="text-right">
|
||||
<a href="{% url 'notifications:list' %}" class="btn btn-primary btn-lg">
|
||||
<span class="glyphicon glyphicon-arrow-left"></span>
|
||||
</a>
|
||||
</div>
|
||||
</h1>
|
||||
<div class="col-lg-12 container">
|
||||
<div class="row">
|
||||
<div class="col-lg-12">
|
||||
<div class="panel panel-{{ notif.level }}">
|
||||
<div class="panel-heading">{{ notif.timestamp }} {{ notif.title }}</div>
|
||||
<div class="panel-body"><pre>{{ notif.message }}</pre></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col-lg-12">
|
||||
<div class="panel panel-{{ notif.level }}">
|
||||
<div class="panel-heading">{{ notif.timestamp }} {{ notif.title }}</div>
|
||||
<div class="panel-body"><pre>{{ notif.message }}</pre></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% endblock %}
|
||||
|
||||
85
allianceauth/notifications/tests/test_core.py
Normal file
85
allianceauth/notifications/tests/test_core.py
Normal file
@@ -0,0 +1,85 @@
|
||||
from django.test import TestCase
|
||||
|
||||
from allianceauth.tests.auth_utils import AuthUtils
|
||||
|
||||
from ..core import NotifyApiWrapper
|
||||
from ..models import Notification
|
||||
|
||||
|
||||
class TestUserNotificationCount(TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls) -> None:
|
||||
super().setUpClass()
|
||||
cls.user = AuthUtils.create_user("bruce_wayne")
|
||||
|
||||
def test_should_add_danger_notification(self):
|
||||
# given
|
||||
notify = NotifyApiWrapper()
|
||||
# when
|
||||
notify.danger(user=self.user, title="title", message="message")
|
||||
# then
|
||||
obj = Notification.objects.first()
|
||||
self.assertEqual(obj.user, self.user)
|
||||
self.assertEqual(obj.title, "title")
|
||||
self.assertEqual(obj.message, "message")
|
||||
self.assertEqual(obj.level, Notification.Level.DANGER)
|
||||
|
||||
def test_should_add_info_notification(self):
|
||||
# given
|
||||
notify = NotifyApiWrapper()
|
||||
# when
|
||||
notify.info(user=self.user, title="title", message="message")
|
||||
# then
|
||||
obj = Notification.objects.first()
|
||||
self.assertEqual(obj.user, self.user)
|
||||
self.assertEqual(obj.title, "title")
|
||||
self.assertEqual(obj.message, "message")
|
||||
self.assertEqual(obj.level, Notification.Level.INFO)
|
||||
|
||||
def test_should_add_success_notification(self):
|
||||
# given
|
||||
notify = NotifyApiWrapper()
|
||||
# when
|
||||
notify.success(user=self.user, title="title", message="message")
|
||||
# then
|
||||
obj = Notification.objects.first()
|
||||
self.assertEqual(obj.user, self.user)
|
||||
self.assertEqual(obj.title, "title")
|
||||
self.assertEqual(obj.message, "message")
|
||||
self.assertEqual(obj.level, Notification.Level.SUCCESS)
|
||||
|
||||
def test_should_add_warning_notification(self):
|
||||
# given
|
||||
notify = NotifyApiWrapper()
|
||||
# when
|
||||
notify.warning(user=self.user, title="title", message="message")
|
||||
# then
|
||||
obj = Notification.objects.first()
|
||||
self.assertEqual(obj.user, self.user)
|
||||
self.assertEqual(obj.title, "title")
|
||||
self.assertEqual(obj.message, "message")
|
||||
self.assertEqual(obj.level, Notification.Level.WARNING)
|
||||
|
||||
def test_should_add_info_notification_via_callable(self):
|
||||
# given
|
||||
notify = NotifyApiWrapper()
|
||||
# when
|
||||
notify(user=self.user, title="title", message="message")
|
||||
# then
|
||||
obj = Notification.objects.first()
|
||||
self.assertEqual(obj.user, self.user)
|
||||
self.assertEqual(obj.title, "title")
|
||||
self.assertEqual(obj.message, "message")
|
||||
self.assertEqual(obj.level, Notification.Level.INFO)
|
||||
|
||||
def test_should_add_danger_notification_via_callable(self):
|
||||
# given
|
||||
notify = NotifyApiWrapper()
|
||||
# when
|
||||
notify(user=self.user, title="title", message="message", level="danger")
|
||||
# then
|
||||
obj = Notification.objects.first()
|
||||
self.assertEqual(obj.user, self.user)
|
||||
self.assertEqual(obj.title, "title")
|
||||
self.assertEqual(obj.message, "message")
|
||||
self.assertEqual(obj.level, Notification.Level.DANGER)
|
||||
@@ -4,11 +4,8 @@ from allianceauth.tests.auth_utils import AuthUtils
|
||||
from .. import notify
|
||||
from ..models import Notification
|
||||
|
||||
MODULE_PATH = 'allianceauth.notifications'
|
||||
|
||||
|
||||
class TestUserNotificationCount(TestCase):
|
||||
|
||||
@classmethod
|
||||
def setUpTestData(cls):
|
||||
cls.user = AuthUtils.create_user('magic_mike')
|
||||
@@ -23,6 +20,18 @@ class TestUserNotificationCount(TestCase):
|
||||
alliance_name='RIDERS'
|
||||
)
|
||||
|
||||
def test_can_notify(self):
|
||||
notify(self.user, 'dummy')
|
||||
def test_can_notify_short(self):
|
||||
# when
|
||||
notify(self.user, "dummy")
|
||||
# then
|
||||
self.assertEqual(Notification.objects.filter(user=self.user).count(), 1)
|
||||
|
||||
def test_can_notify_full(self):
|
||||
# when
|
||||
notify(user=self.user, title="title", message="message", level="danger")
|
||||
# then
|
||||
obj = Notification.objects.first()
|
||||
self.assertEqual(obj.user, self.user)
|
||||
self.assertEqual(obj.title, "title")
|
||||
self.assertEqual(obj.message, "message")
|
||||
self.assertEqual(obj.level, "danger")
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
from django.conf.urls import url
|
||||
from django.urls import path
|
||||
from . import views
|
||||
|
||||
app_name = 'notifications'
|
||||
# Notifications
|
||||
urlpatterns = [
|
||||
url(r'^remove_notifications/(\w+)/$', views.remove_notification, name='remove'),
|
||||
url(r'^notifications/mark_all_read/$', views.mark_all_read, name='mark_all_read'),
|
||||
url(r'^notifications/delete_all_read/$', views.delete_all_read, name='delete_all_read'),
|
||||
url(r'^notifications/$', views.notification_list, name='list'),
|
||||
url(r'^notifications/(\w+)/$', views.notification_view, name='view'),
|
||||
url(
|
||||
r'^user_notifications_count/(?P<user_pk>\d+)/$',
|
||||
path('remove_notifications/<int:notif_id>/', views.remove_notification, name='remove'),
|
||||
path('notifications/mark_all_read/', views.mark_all_read, name='mark_all_read'),
|
||||
path('notifications/delete_all_read/', views.delete_all_read, name='delete_all_read'),
|
||||
path('notifications/', views.notification_list, name='list'),
|
||||
path('notifications/<int:notif_id>/', views.notification_view, name='view'),
|
||||
path(
|
||||
'user_notifications_count/<int:user_pk>/',
|
||||
views.user_notifications_count,
|
||||
name='user_notifications_count'
|
||||
),
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
default_app_config = 'allianceauth.optimer.apps.OptimerConfig'
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from allianceauth.services.hooks import MenuItemHook, UrlHook
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from allianceauth import hooks
|
||||
from . import urls
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from django import forms
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from allianceauth.optimer.form_widgets import DataListWidget
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
<form class="form-signin" role="form" action="" method="POST">
|
||||
{% csrf_token %}
|
||||
{{ form|bootstrap }}
|
||||
<br/>
|
||||
<br>
|
||||
<button class="btn btn-lg btn-primary btn-block" type="submit">{% translate "Create Fleet Operation" %}</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user