mirror of
https://gitlab.com/allianceauth/allianceauth.git
synced 2026-02-04 14:16:21 +01:00
Compare commits
161 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6b932b1188 | ||
|
|
f62153c746 | ||
|
|
88216c3f81 | ||
|
|
dc983c31e3 | ||
|
|
4204c44bde | ||
|
|
8da0122d17 | ||
|
|
c9fcf6e6bf | ||
|
|
36866cc59b | ||
|
|
298bdd98ed | ||
|
|
819018748d | ||
|
|
32e8e0fdd0 | ||
|
|
7625060a12 | ||
|
|
672cb13bfe | ||
|
|
7170f75b89 | ||
|
|
8f60c7a00a | ||
|
|
34ae6e402c | ||
|
|
0905e48994 | ||
|
|
02fcf7d500 | ||
|
|
8d8da50946 | ||
|
|
c1499d173f | ||
|
|
b149baa4e5 | ||
|
|
4807c69b5e | ||
|
|
ebefa0e307 | ||
|
|
468e7433f9 | ||
|
|
3ca313f907 | ||
|
|
820065fc04 | ||
|
|
3eddeefe28 | ||
|
|
82d7d7e3bf | ||
|
|
93194b4f2d | ||
|
|
fa335253d3 | ||
|
|
d1af9416b3 | ||
|
|
f4ac2ea400 | ||
|
|
31c1f8bb7d | ||
|
|
57f7178f1e | ||
|
|
17d4a4c415 | ||
|
|
18ce433fa0 | ||
|
|
1eadb1d934 | ||
|
|
59a8f8a967 | ||
|
|
2dc07b5519 | ||
|
|
3454520dfe | ||
|
|
7a195d4158 | ||
|
|
b73072dec0 | ||
|
|
1ca5e38bd9 | ||
|
|
ecb737c6a5 | ||
|
|
7063f53cdf | ||
|
|
017424b9d4 | ||
|
|
f6c26cf2ec | ||
|
|
9a422bd4ca | ||
|
|
47fec23f2e | ||
|
|
399ef1917d | ||
|
|
9db443ba54 | ||
|
|
0f2f5ea0ba | ||
|
|
1f781c5037 | ||
|
|
36dedfcbd2 | ||
|
|
13a05606fb | ||
|
|
90ad7790e1 | ||
|
|
6b8341ab5a | ||
|
|
d15f42b3fd | ||
|
|
cc60b26f5a | ||
|
|
36ff0af993 | ||
|
|
f17c94a9e1 | ||
|
|
7e3ba476f3 | ||
|
|
dd1313a2a9 | ||
|
|
763003bd7d | ||
|
|
f3217443dd | ||
|
|
a713ae1914 | ||
|
|
5815bac0df | ||
|
|
6154d2c2e7 | ||
|
|
b34661b35d | ||
|
|
a9a7e03b80 | ||
|
|
23c797ef64 | ||
|
|
da102618a0 | ||
|
|
51ee281b14 | ||
|
|
9133232c20 | ||
|
|
9cbabee126 | ||
|
|
4026523a2e | ||
|
|
7fbf96623b | ||
|
|
273bda173e | ||
|
|
7bd5838ea1 | ||
|
|
b232d9ab17 | ||
|
|
a11b870664 | ||
|
|
a27aae5d1c | ||
|
|
117ef63d90 | ||
|
|
1bde3d5672 | ||
|
|
d2355b1ec8 | ||
|
|
191d474a8e | ||
|
|
ec9a9733be | ||
|
|
cf7a8cedf1 | ||
|
|
18cbb994d5 | ||
|
|
663388a0c2 | ||
|
|
7a943591ec | ||
|
|
cd189927fe | ||
|
|
8772349309 | ||
|
|
cf20100cb5 | ||
|
|
9b9c2ddc04 | ||
|
|
34839e8344 | ||
|
|
89ef4f4cbc | ||
|
|
2cc7f46aae | ||
|
|
8d255fb720 | ||
|
|
67cf68ad87 | ||
|
|
db1971d4c2 | ||
|
|
63c1521cba | ||
|
|
ba7ef11505 | ||
|
|
d2e494b9be | ||
|
|
98bab0b180 | ||
|
|
c4efb2a11f | ||
|
|
94e4895f29 | ||
|
|
70eb1b5b50 | ||
|
|
e247a94db3 | ||
|
|
714431c932 | ||
|
|
b026277ab0 | ||
|
|
11855f0b54 | ||
|
|
635fbfe2c8 | ||
|
|
b10233daf0 | ||
|
|
1aa3187491 | ||
|
|
59f17a88f0 | ||
|
|
75db3195d4 | ||
|
|
afe3fea757 | ||
|
|
1072c00a28 | ||
|
|
b221c1ce24 | ||
|
|
1617c775ee | ||
|
|
cc88a02001 | ||
|
|
ae5d0f4a2f | ||
|
|
067e2c424e | ||
|
|
d64675a3b0 | ||
|
|
17a6b3225e | ||
|
|
b83f591dc2 | ||
|
|
be2fbe862b | ||
|
|
f95bee0921 | ||
|
|
2f9ae8b054 | ||
|
|
74651dd30a | ||
|
|
9cdcd8365c | ||
|
|
f5d70a2c48 | ||
|
|
f40ebbfba4 | ||
|
|
2551a9dd64 | ||
|
|
e3b01ccbc9 | ||
|
|
267a392945 | ||
|
|
634d021bf2 | ||
|
|
4e8bfba738 | ||
|
|
297f98f046 | ||
|
|
27dad05927 | ||
|
|
697e9dd772 | ||
|
|
312951ea3f | ||
|
|
e4bf96cfb6 | ||
|
|
3bd6baa8f9 | ||
|
|
06e38dcd93 | ||
|
|
f47b9eee5b | ||
|
|
0d4cab66b2 | ||
|
|
dc23ee8ad2 | ||
|
|
65f2efc890 | ||
|
|
def30900b4 | ||
|
|
d7fabccddd | ||
|
|
45289e1d17 | ||
|
|
e7bafaa4d8 | ||
|
|
ba3f1507be | ||
|
|
7b9bf08aa3 | ||
|
|
360458f574 | ||
|
|
def6431052 | ||
|
|
22a270aedb | ||
|
|
c930f7bbeb | ||
|
|
64ee273953 |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -69,11 +69,7 @@ celerybeat-schedule
|
||||
#gitlab configs
|
||||
.gitlab/
|
||||
|
||||
#transifex
|
||||
.tx/
|
||||
|
||||
#other
|
||||
.flake8
|
||||
.pylintrc
|
||||
Makefile
|
||||
.isort.cfg
|
||||
|
||||
@@ -89,7 +89,7 @@ test-3.10-core:
|
||||
|
||||
test-3.11-core:
|
||||
<<: *only-default
|
||||
image: python:3.11-rc-bullseye
|
||||
image: python:3.11-bullseye
|
||||
script:
|
||||
- tox -e py311-core
|
||||
artifacts:
|
||||
@@ -98,6 +98,18 @@ test-3.11-core:
|
||||
coverage_report:
|
||||
coverage_format: cobertura
|
||||
path: coverage.xml
|
||||
|
||||
test-pvpy-core:
|
||||
<<: *only-default
|
||||
image: pypy:3.9-bullseye
|
||||
script:
|
||||
- tox -e pypy-all
|
||||
artifacts:
|
||||
when: always
|
||||
reports:
|
||||
coverage_report:
|
||||
coverage_format: cobertura
|
||||
path: coverage.xml
|
||||
allow_failure: true
|
||||
|
||||
test-3.8-all:
|
||||
@@ -138,7 +150,7 @@ test-3.10-all:
|
||||
|
||||
test-3.11-all:
|
||||
<<: *only-default
|
||||
image: python:3.11-rc-bullseye
|
||||
image: python:3.11-bullseye
|
||||
script:
|
||||
- tox -e py311-all
|
||||
artifacts:
|
||||
@@ -147,6 +159,19 @@ test-3.11-all:
|
||||
coverage_report:
|
||||
coverage_format: cobertura
|
||||
path: coverage.xml
|
||||
coverage: '/(?i)total.*? (100(?:\.0+)?\%|[1-9]?\d(?:\.\d+)?\%)$/'
|
||||
|
||||
test-pvpy-all:
|
||||
<<: *only-default
|
||||
image: pypy:3.9-bullseye
|
||||
script:
|
||||
- tox -e pypy-all
|
||||
artifacts:
|
||||
when: always
|
||||
reports:
|
||||
coverage_report:
|
||||
coverage_format: cobertura
|
||||
path: coverage.xml
|
||||
allow_failure: true
|
||||
|
||||
build-test:
|
||||
@@ -213,6 +238,8 @@ build-image:
|
||||
docker image push --all-tags $CI_REGISTRY_IMAGE/auth
|
||||
rules:
|
||||
- if: $CI_COMMIT_TAG
|
||||
when: delayed
|
||||
start_in: 10 minutes
|
||||
|
||||
build-image-dev:
|
||||
before_script: []
|
||||
|
||||
6
.isort.cfg
Normal file
6
.isort.cfg
Normal file
@@ -0,0 +1,6 @@
|
||||
[settings]
|
||||
profile=django
|
||||
sections=FUTURE,STDLIB,THIRDPARTY,DJANGO,ESI,FIRSTPARTY,LOCALFOLDER
|
||||
known_esi=esi
|
||||
known_django=django
|
||||
skip_gitignore=true
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.3.0
|
||||
rev: v4.4.0
|
||||
hooks:
|
||||
- id: check-case-conflict
|
||||
- id: check-json
|
||||
@@ -13,27 +13,49 @@ repos:
|
||||
- id: check-yaml
|
||||
- id: fix-byte-order-marker
|
||||
- id: trailing-whitespace
|
||||
exclude: (\.min\.css|\.min\.js|\.mo|\.po|swagger\.json)$
|
||||
exclude: |
|
||||
(?x)(
|
||||
\.min\.css|
|
||||
\.min\.js|
|
||||
\.po|
|
||||
\.mo|
|
||||
swagger\.json
|
||||
)
|
||||
- id: end-of-file-fixer
|
||||
exclude: (\.min\.css|\.min\.js|\.mo|\.po|swagger\.json)$
|
||||
exclude: |
|
||||
(?x)(
|
||||
\.min\.css|
|
||||
\.min\.js|
|
||||
\.po|
|
||||
\.mo|
|
||||
swagger\.json
|
||||
)
|
||||
- id: mixed-line-ending
|
||||
args: [ '--fix=lf' ]
|
||||
- id: fix-encoding-pragma
|
||||
args: [ '--remove' ]
|
||||
|
||||
- repo: https://github.com/editorconfig-checker/editorconfig-checker.python
|
||||
rev: 2.4.0
|
||||
rev: 2.7.1
|
||||
hooks:
|
||||
- id: editorconfig-checker
|
||||
exclude: ^(LICENSE|allianceauth\/static\/allianceauth\/css\/themes\/bootstrap-locals.less|allianceauth\/eveonline\/swagger.json|(.*.po)|(.*.mo))
|
||||
exclude: |
|
||||
(?x)(
|
||||
LICENSE|
|
||||
allianceauth\/static\/allianceauth\/css\/themes\/bootstrap-locals.less|
|
||||
\.po|
|
||||
\.mo|
|
||||
swagger\.json
|
||||
)
|
||||
|
||||
- repo: https://github.com/asottile/pyupgrade
|
||||
rev: v2.34.0
|
||||
rev: v3.3.1
|
||||
hooks:
|
||||
- id: pyupgrade
|
||||
args: [ --py38-plus ]
|
||||
|
||||
- repo: https://github.com/asottile/setup-cfg-fmt
|
||||
rev: v1.20.1
|
||||
rev: v2.2.0
|
||||
hooks:
|
||||
- id: setup-cfg-fmt
|
||||
args: [ --include-version-classifiers ]
|
||||
|
||||
@@ -11,7 +11,7 @@ build:
|
||||
apt_packages:
|
||||
- redis
|
||||
tools:
|
||||
python: "3.10"
|
||||
python: "3.8"
|
||||
|
||||
# Build documentation in the docs/ directory with Sphinx
|
||||
sphinx:
|
||||
|
||||
10
.tx/config
Normal file
10
.tx/config
Normal file
@@ -0,0 +1,10 @@
|
||||
[main]
|
||||
host = https://www.transifex.com
|
||||
lang_map = zh-Hans: zh_Hans
|
||||
|
||||
[o:alliance-auth:p:alliance-auth:r:django-po]
|
||||
file_filter = allianceauth/locale/<lang>/LC_MESSAGES/django.po
|
||||
source_file = allianceauth/locale/en/LC_MESSAGES/django.po
|
||||
source_lang = en
|
||||
type = PO
|
||||
minimum_perc = 0
|
||||
10
.tx/config_20230406134150.bak
Executable file
10
.tx/config_20230406134150.bak
Executable file
@@ -0,0 +1,10 @@
|
||||
[main]
|
||||
host = https://www.transifex.com
|
||||
lang_map = zh-Hans:zh_Hans
|
||||
|
||||
[alliance-auth.django-po]
|
||||
file_filter = allianceauth/locale/<lang>/LC_MESSAGES/django.po
|
||||
minimum_perc = 0
|
||||
source_file = allianceauth/locale/en/LC_MESSAGES/django.po
|
||||
source_lang = en
|
||||
type = PO
|
||||
7
MANIFEST.in
Normal file
7
MANIFEST.in
Normal file
@@ -0,0 +1,7 @@
|
||||
include LICENSE
|
||||
include README.md
|
||||
include MANIFEST.in
|
||||
graft allianceauth
|
||||
|
||||
global-exclude __pycache__
|
||||
global-exclude *.py[co]
|
||||
@@ -36,7 +36,7 @@ Main features:
|
||||
|
||||
- Can be easily extended with additional services and apps. Many are provided by the community and can be found here: [Community Creations](https://gitlab.com/allianceauth/community-creations)
|
||||
|
||||
- English :flag_gb:, Chinese :flag_cn:, German :flag_de:, Spanish :flag_es:, Korean :flag_kr: and Russian :flag_ru: localization
|
||||
- English :flag_gb:, Chinese :flag_cn:, German :flag_de:, Spanish :flag_es:, Korean :flag_kr:, Russian :flag_ru:, Italian :flag_it:, French :flag_fr:, Japanese :flag_jp: and Ukrainian :flag_ua: Localization
|
||||
|
||||
For further details about AA - including an installation guide and a full list of included services and plugin apps - please see the [official documentation](http://allianceauth.rtfd.io).
|
||||
|
||||
@@ -56,13 +56,15 @@ Here is an example of the Alliance Auth web site with some plug-ins apps and ser
|
||||
|
||||
- [Aaron Kable](https://gitlab.com/aaronkable/)
|
||||
- [Ariel Rin](https://gitlab.com/soratidus999/)
|
||||
- [Basraah](https://gitlab.com/basraah/)
|
||||
- [Col Crunch](https://gitlab.com/colcrunch/)
|
||||
- [Erik Kalkoken](https://gitlab.com/ErikKalkoken/)
|
||||
- [Rounon Dax](https://gitlab.com/ppfeufer)
|
||||
- [snipereagle1](https://gitlab.com/mckernanin)
|
||||
|
||||
### Former Developers
|
||||
|
||||
- [Adarnof](https://gitlab.com/adarnof/)
|
||||
- [Basraah](https://gitlab.com/basraah/)
|
||||
|
||||
### Beta Testers / Bug Fixers
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# This will make sure the app is always imported when
|
||||
# Django starts so that shared_task will use this app.
|
||||
|
||||
__version__ = '3.0.0b3'
|
||||
__version__ = '3.4.0'
|
||||
__title__ = 'Alliance Auth'
|
||||
__url__ = 'https://gitlab.com/allianceauth/allianceauth'
|
||||
NAME = f'{__title__} v{__version__}'
|
||||
|
||||
@@ -8,13 +8,13 @@ from uuid import uuid4
|
||||
class AnalyticsIdentifier(models.Model):
|
||||
|
||||
identifier = models.UUIDField(default=uuid4,
|
||||
editable=False)
|
||||
editable=False)
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
if not self.pk and AnalyticsIdentifier.objects.exists():
|
||||
# Force a single object
|
||||
raise ValidationError('There is can be only one \
|
||||
AnalyticsIdentifier instance')
|
||||
AnalyticsIdentifier instance')
|
||||
self.pk = self.id = 1 # If this happens to be deleted and recreated, force it to be 1
|
||||
return super().save(*args, **kwargs)
|
||||
|
||||
|
||||
@@ -3,16 +3,17 @@ from urllib.parse import parse_qs
|
||||
|
||||
import requests_mock
|
||||
|
||||
from django.test import TestCase, override_settings
|
||||
from django.test import override_settings
|
||||
|
||||
from allianceauth.analytics.tasks import ANALYTICS_URL
|
||||
from allianceauth.eveonline.tasks import update_character
|
||||
from allianceauth.tests.auth_utils import AuthUtils
|
||||
from allianceauth.utils.testing import NoSocketsTestCase
|
||||
|
||||
|
||||
@override_settings(CELERY_ALWAYS_EAGER=True)
|
||||
@requests_mock.mock()
|
||||
class TestAnalyticsForViews(TestCase):
|
||||
class TestAnalyticsForViews(NoSocketsTestCase):
|
||||
@override_settings(ANALYTICS_DISABLED=False)
|
||||
def test_should_run_analytics(self, requests_mocker):
|
||||
# given
|
||||
@@ -40,7 +41,7 @@ class TestAnalyticsForViews(TestCase):
|
||||
|
||||
@override_settings(CELERY_ALWAYS_EAGER=True)
|
||||
@requests_mock.mock()
|
||||
class TestAnalyticsForTasks(TestCase):
|
||||
class TestAnalyticsForTasks(NoSocketsTestCase):
|
||||
@override_settings(ANALYTICS_DISABLED=False)
|
||||
@patch("allianceauth.eveonline.models.EveCharacter.objects.update_character")
|
||||
def test_should_run_analytics_for_successful_task(
|
||||
|
||||
@@ -1,12 +1,22 @@
|
||||
import requests_mock
|
||||
|
||||
from django.test.utils import override_settings
|
||||
|
||||
from allianceauth.analytics.tasks import (
|
||||
analytics_event,
|
||||
send_ga_tracking_celery_event,
|
||||
send_ga_tracking_web_view)
|
||||
from django.test.testcases import TestCase
|
||||
from allianceauth.utils.testing import NoSocketsTestCase
|
||||
|
||||
|
||||
class TestAnalyticsTasks(TestCase):
|
||||
def test_analytics_event(self):
|
||||
GOOGLE_ANALYTICS_DEBUG_URL = 'https://www.google-analytics.com/debug/collect'
|
||||
|
||||
|
||||
@override_settings(CELERY_ALWAYS_EAGER=True, CELERY_EAGER_PROPAGATES_EXCEPTIONS=True)
|
||||
@requests_mock.Mocker()
|
||||
class TestAnalyticsTasks(NoSocketsTestCase):
|
||||
def test_analytics_event(self, requests_mocker):
|
||||
requests_mocker.register_uri('POST', GOOGLE_ANALYTICS_DEBUG_URL)
|
||||
analytics_event(
|
||||
category='allianceauth.analytics',
|
||||
action='send_tests',
|
||||
@@ -14,15 +24,19 @@ class TestAnalyticsTasks(TestCase):
|
||||
value=1,
|
||||
event_type='Stats')
|
||||
|
||||
def test_send_ga_tracking_web_view_sent(self):
|
||||
# This test sends if the event SENDS to google
|
||||
# Not if it was successful
|
||||
def test_send_ga_tracking_web_view_sent(self, requests_mocker):
|
||||
"""This test sends if the event SENDS to google.
|
||||
Not if it was successful.
|
||||
"""
|
||||
# given
|
||||
requests_mocker.register_uri('POST', GOOGLE_ANALYTICS_DEBUG_URL)
|
||||
tracking_id = 'UA-186249766-2'
|
||||
client_id = 'ab33e241fbf042b6aa77c7655a768af7'
|
||||
page = '/index/'
|
||||
title = 'Hello World'
|
||||
locale = 'en'
|
||||
useragent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
|
||||
# when
|
||||
response = send_ga_tracking_web_view(
|
||||
tracking_id,
|
||||
client_id,
|
||||
@@ -30,15 +44,23 @@ class TestAnalyticsTasks(TestCase):
|
||||
title,
|
||||
locale,
|
||||
useragent)
|
||||
# then
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_send_ga_tracking_web_view_success(self):
|
||||
def test_send_ga_tracking_web_view_success(self, requests_mocker):
|
||||
# given
|
||||
requests_mocker.register_uri(
|
||||
'POST',
|
||||
GOOGLE_ANALYTICS_DEBUG_URL,
|
||||
json={"hitParsingResult":[{'valid': True}]}
|
||||
)
|
||||
tracking_id = 'UA-186249766-2'
|
||||
client_id = 'ab33e241fbf042b6aa77c7655a768af7'
|
||||
page = '/index/'
|
||||
title = 'Hello World'
|
||||
locale = 'en'
|
||||
useragent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
|
||||
# when
|
||||
json_response = send_ga_tracking_web_view(
|
||||
tracking_id,
|
||||
client_id,
|
||||
@@ -46,15 +68,42 @@ class TestAnalyticsTasks(TestCase):
|
||||
title,
|
||||
locale,
|
||||
useragent).json()
|
||||
# then
|
||||
self.assertTrue(json_response["hitParsingResult"][0]["valid"])
|
||||
|
||||
def test_send_ga_tracking_web_view_invalid_token(self):
|
||||
def test_send_ga_tracking_web_view_invalid_token(self, requests_mocker):
|
||||
# given
|
||||
requests_mocker.register_uri(
|
||||
'POST',
|
||||
GOOGLE_ANALYTICS_DEBUG_URL,
|
||||
json={
|
||||
"hitParsingResult":[
|
||||
{
|
||||
'valid': False,
|
||||
'parserMessage': [
|
||||
{
|
||||
'messageType': 'INFO',
|
||||
'description': 'IP Address from this hit was anonymized to 1.132.110.0.',
|
||||
'messageCode': 'VALUE_MODIFIED'
|
||||
},
|
||||
{
|
||||
'messageType': 'ERROR',
|
||||
'description': "The value provided for parameter 'tid' is invalid. Please see http://goo.gl/a8d4RP#tid for details.",
|
||||
'messageCode': 'VALUE_INVALID', 'parameter': 'tid'
|
||||
}
|
||||
],
|
||||
'hit': '/debug/collect?v=1&tid=UA-IntentionallyBadTrackingID-2&cid=ab33e241fbf042b6aa77c7655a768af7&t=pageview&dp=/index/&dt=Hello World&ul=en&ua=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36&aip=1&an=allianceauth&av=2.9.0a2'
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
tracking_id = 'UA-IntentionallyBadTrackingID-2'
|
||||
client_id = 'ab33e241fbf042b6aa77c7655a768af7'
|
||||
page = '/index/'
|
||||
title = 'Hello World'
|
||||
locale = 'en'
|
||||
useragent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"
|
||||
# when
|
||||
json_response = send_ga_tracking_web_view(
|
||||
tracking_id,
|
||||
client_id,
|
||||
@@ -62,18 +111,25 @@ class TestAnalyticsTasks(TestCase):
|
||||
title,
|
||||
locale,
|
||||
useragent).json()
|
||||
# then
|
||||
self.assertFalse(json_response["hitParsingResult"][0]["valid"])
|
||||
self.assertEqual(json_response["hitParsingResult"][0]["parserMessage"][1]["description"], "The value provided for parameter 'tid' is invalid. Please see http://goo.gl/a8d4RP#tid for details.")
|
||||
self.assertEqual(
|
||||
json_response["hitParsingResult"][0]["parserMessage"][1]["description"],
|
||||
"The value provided for parameter 'tid' is invalid. Please see http://goo.gl/a8d4RP#tid for details."
|
||||
)
|
||||
|
||||
# [{'valid': False, 'parserMessage': [{'messageType': 'INFO', 'description': 'IP Address from this hit was anonymized to 1.132.110.0.', 'messageCode': 'VALUE_MODIFIED'}, {'messageType': 'ERROR', 'description': "The value provided for parameter 'tid' is invalid. Please see http://goo.gl/a8d4RP#tid for details.", 'messageCode': 'VALUE_INVALID', 'parameter': 'tid'}], 'hit': '/debug/collect?v=1&tid=UA-IntentionallyBadTrackingID-2&cid=ab33e241fbf042b6aa77c7655a768af7&t=pageview&dp=/index/&dt=Hello World&ul=en&ua=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36&aip=1&an=allianceauth&av=2.9.0a2'}]
|
||||
|
||||
def test_send_ga_tracking_celery_event_sent(self):
|
||||
def test_send_ga_tracking_celery_event_sent(self, requests_mocker):
|
||||
# given
|
||||
requests_mocker.register_uri('POST', GOOGLE_ANALYTICS_DEBUG_URL)
|
||||
tracking_id = 'UA-186249766-2'
|
||||
client_id = 'ab33e241fbf042b6aa77c7655a768af7'
|
||||
category = 'test'
|
||||
action = 'test'
|
||||
label = 'test'
|
||||
value = '1'
|
||||
# when
|
||||
response = send_ga_tracking_celery_event(
|
||||
tracking_id,
|
||||
client_id,
|
||||
@@ -81,15 +137,23 @@ class TestAnalyticsTasks(TestCase):
|
||||
action,
|
||||
label,
|
||||
value)
|
||||
# then
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_send_ga_tracking_celery_event_success(self):
|
||||
def test_send_ga_tracking_celery_event_success(self, requests_mocker):
|
||||
# given
|
||||
requests_mocker.register_uri(
|
||||
'POST',
|
||||
GOOGLE_ANALYTICS_DEBUG_URL,
|
||||
json={"hitParsingResult":[{'valid': True}]}
|
||||
)
|
||||
tracking_id = 'UA-186249766-2'
|
||||
client_id = 'ab33e241fbf042b6aa77c7655a768af7'
|
||||
category = 'test'
|
||||
action = 'test'
|
||||
label = 'test'
|
||||
value = '1'
|
||||
# when
|
||||
json_response = send_ga_tracking_celery_event(
|
||||
tracking_id,
|
||||
client_id,
|
||||
@@ -97,15 +161,42 @@ class TestAnalyticsTasks(TestCase):
|
||||
action,
|
||||
label,
|
||||
value).json()
|
||||
# then
|
||||
self.assertTrue(json_response["hitParsingResult"][0]["valid"])
|
||||
|
||||
def test_send_ga_tracking_celery_event_invalid_token(self):
|
||||
def test_send_ga_tracking_celery_event_invalid_token(self, requests_mocker):
|
||||
# given
|
||||
requests_mocker.register_uri(
|
||||
'POST',
|
||||
GOOGLE_ANALYTICS_DEBUG_URL,
|
||||
json={
|
||||
"hitParsingResult":[
|
||||
{
|
||||
'valid': False,
|
||||
'parserMessage': [
|
||||
{
|
||||
'messageType': 'INFO',
|
||||
'description': 'IP Address from this hit was anonymized to 1.132.110.0.',
|
||||
'messageCode': 'VALUE_MODIFIED'
|
||||
},
|
||||
{
|
||||
'messageType': 'ERROR',
|
||||
'description': "The value provided for parameter 'tid' is invalid. Please see http://goo.gl/a8d4RP#tid for details.",
|
||||
'messageCode': 'VALUE_INVALID', 'parameter': 'tid'
|
||||
}
|
||||
],
|
||||
'hit': '/debug/collect?v=1&tid=UA-IntentionallyBadTrackingID-2&cid=ab33e241fbf042b6aa77c7655a768af7&t=pageview&dp=/index/&dt=Hello World&ul=en&ua=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36&aip=1&an=allianceauth&av=2.9.0a2'
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
tracking_id = 'UA-IntentionallyBadTrackingID-2'
|
||||
client_id = 'ab33e241fbf042b6aa77c7655a768af7'
|
||||
category = 'test'
|
||||
action = 'test'
|
||||
label = 'test'
|
||||
value = '1'
|
||||
# when
|
||||
json_response = send_ga_tracking_celery_event(
|
||||
tracking_id,
|
||||
client_id,
|
||||
@@ -113,7 +204,9 @@ class TestAnalyticsTasks(TestCase):
|
||||
action,
|
||||
label,
|
||||
value).json()
|
||||
# then
|
||||
self.assertFalse(json_response["hitParsingResult"][0]["valid"])
|
||||
self.assertEqual(json_response["hitParsingResult"][0]["parserMessage"][1]["description"], "The value provided for parameter 'tid' is invalid. Please see http://goo.gl/a8d4RP#tid for details.")
|
||||
|
||||
# [{'valid': False, 'parserMessage': [{'messageType': 'INFO', 'description': 'IP Address from this hit was anonymized to 1.132.110.0.', 'messageCode': 'VALUE_MODIFIED'}, {'messageType': 'ERROR', 'description': "The value provided for parameter 'tid' is invalid. Please see http://goo.gl/a8d4RP#tid for details.", 'messageCode': 'VALUE_INVALID', 'parameter': 'tid'}], 'hit': '/debug/collect?v=1&tid=UA-IntentionallyBadTrackingID-2&cid=ab33e241fbf042b6aa77c7655a768af7&t=pageview&dp=/index/&dt=Hello World&ul=en&ua=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36&aip=1&an=allianceauth&av=2.9.0a2'}]
|
||||
self.assertEqual(
|
||||
json_response["hitParsingResult"][0]["parserMessage"][1]["description"],
|
||||
"The value provided for parameter 'tid' is invalid. Please see http://goo.gl/a8d4RP#tid for details."
|
||||
)
|
||||
|
||||
@@ -2,6 +2,7 @@ import logging
|
||||
|
||||
from django.contrib.auth.backends import ModelBackend
|
||||
from django.contrib.auth.models import User, Permission
|
||||
from django.contrib import messages
|
||||
|
||||
from .models import UserProfile, CharacterOwnership, OwnershipRecord
|
||||
|
||||
@@ -37,7 +38,13 @@ class StateBackend(ModelBackend):
|
||||
ownership = CharacterOwnership.objects.get(character__character_id=token.character_id)
|
||||
if ownership.owner_hash == token.character_owner_hash:
|
||||
logger.debug(f'Authenticating {ownership.user} by ownership of character {token.character_name}')
|
||||
return ownership.user
|
||||
if ownership.user.profile.main_character:
|
||||
if ownership.user.profile.main_character.character_id == token.character_id:
|
||||
return ownership.user
|
||||
else: ## this is an alt, enforce main only.
|
||||
if request:
|
||||
messages.error("Unable to authenticate with this Character, Please log in with the main character associated with this account.")
|
||||
return None
|
||||
else:
|
||||
logger.debug(f'{token.character_name} has changed ownership. Creating new user account.')
|
||||
ownership.delete()
|
||||
@@ -57,13 +64,20 @@ class StateBackend(ModelBackend):
|
||||
if records.exists():
|
||||
# we've seen this character owner before. Re-attach to their old user account
|
||||
user = records[0].user
|
||||
if user.profile.main_character:
|
||||
if ownership.user.profile.main_character.character_id != token.character_id:
|
||||
## this is an alt, enforce main only due to trust issues in SSO.
|
||||
if request:
|
||||
messages.error("Unable to authenticate with this Character, Please log in with the main character associated with this account. Then add this character from the dashboard.")
|
||||
return None
|
||||
|
||||
token.user = user
|
||||
co = CharacterOwnership.objects.create_by_token(token)
|
||||
logger.debug(f'Authenticating {user} by matching owner hash record of character {co.character}')
|
||||
if not user.profile.main_character:
|
||||
# set this as their main by default if they have none
|
||||
user.profile.main_character = co.character
|
||||
user.profile.save()
|
||||
|
||||
# set this as their main by default as they have none
|
||||
user.profile.main_character = co.character
|
||||
user.profile.save()
|
||||
return user
|
||||
logger.debug(f'Unable to authenticate character {token.character_name}. Creating new user.')
|
||||
return self.create_user(token)
|
||||
|
||||
@@ -18,13 +18,13 @@ class State(models.Model):
|
||||
priority = models.IntegerField(unique=True, help_text="Users get assigned the state with the highest priority available to them.")
|
||||
|
||||
member_characters = models.ManyToManyField(EveCharacter, blank=True,
|
||||
help_text="Characters to which this state is available.")
|
||||
help_text="Characters to which this state is available.")
|
||||
member_corporations = models.ManyToManyField(EveCorporationInfo, blank=True,
|
||||
help_text="Corporations to whose members this state is available.")
|
||||
help_text="Corporations to whose members this state is available.")
|
||||
member_alliances = models.ManyToManyField(EveAllianceInfo, blank=True,
|
||||
help_text="Alliances to whose members this state is available.")
|
||||
help_text="Alliances to whose members this state is available.")
|
||||
member_factions = models.ManyToManyField(EveFactionInfo, blank=True,
|
||||
help_text="Factions to whose members this state is available.")
|
||||
help_text="Factions to whose members this state is available.")
|
||||
public = models.BooleanField(default=False, help_text="Make this state available to any character.")
|
||||
|
||||
objects = StateManager()
|
||||
|
||||
@@ -6,24 +6,26 @@ CSS for allianceauth admin site
|
||||
.img-circle {
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.column-user_profile_pic {
|
||||
width: 1px;
|
||||
white-space: nowrap;
|
||||
width: 1px;
|
||||
}
|
||||
|
||||
/* tooltip */
|
||||
.tooltip {
|
||||
position: relative ;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.tooltip:hover::after {
|
||||
content: attr(data-tooltip) ;
|
||||
position: absolute ;
|
||||
top: 1.1em ;
|
||||
left: 1em ;
|
||||
min-width: 200px ;
|
||||
border: 1px #808080 solid ;
|
||||
padding: 8px ;
|
||||
color: black ;
|
||||
background-color: rgb(255, 255, 204) ;
|
||||
z-index: 1 ;
|
||||
background-color: rgb(255 255 204);
|
||||
border: 1px rgb(128 128 128) solid;
|
||||
color: rgb(0 0 0);
|
||||
content: attr(data-tooltip);
|
||||
left: 1em;
|
||||
min-width: 200px;
|
||||
padding: 8px;
|
||||
position: absolute;
|
||||
top: 1.1em;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
@@ -14,9 +14,9 @@
|
||||
<div class="panel panel-primary" style="height:100%">
|
||||
<div class="panel-heading">
|
||||
<h3 class="panel-title">
|
||||
{% blocktrans with state=request.user.profile.state %}
|
||||
{% blocktranslate with state=request.user.profile.state %}
|
||||
Main Character (State: {{ state }})
|
||||
{% endblocktrans %}
|
||||
{% endblocktranslate %}
|
||||
</h3>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
@@ -27,7 +27,7 @@
|
||||
<table class="table">
|
||||
<tr>
|
||||
<td class="text-center">
|
||||
<img class="ra-avatar" src="{{ main.portrait_url_128 }}">
|
||||
<img class="ra-avatar" src="{{ main.portrait_url_128 }}" alt="{{ main.character_name }}">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
@@ -39,7 +39,7 @@
|
||||
<table class="table">
|
||||
<tr>
|
||||
<td class="text-center">
|
||||
<img class="ra-avatar" src="{{ main.corporation_logo_url_128 }}">
|
||||
<img class="ra-avatar" src="{{ main.corporation_logo_url_128 }}" alt="{{ main.corporation_name }}">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
@@ -52,7 +52,7 @@
|
||||
<table class="table">
|
||||
<tr>
|
||||
<td class="text-center">
|
||||
<img class="ra-avatar" src="{{ main.alliance_logo_url_128 }}">
|
||||
<img class="ra-avatar" src="{{ main.alliance_logo_url_128 }}" alt="{{ main.alliance_name }}">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
@@ -63,7 +63,7 @@
|
||||
<table class="table">
|
||||
<tr>
|
||||
<td class="text-center">
|
||||
<img class="ra-avatar" src="{{ main.faction_logo_url_128 }}">
|
||||
<img class="ra-avatar" src="{{ main.faction_logo_url_128 }}" alt="{{ main.faction_name }}">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
@@ -75,13 +75,13 @@
|
||||
</div>
|
||||
<div class="table visible-xs-block">
|
||||
<p>
|
||||
<img class="ra-avatar" src="{{ main.portrait_url_64 }}">
|
||||
<img class="ra-avatar" src="{{ main.corporation_logo_url_64 }}">
|
||||
<img class="ra-avatar" src="{{ main.portrait_url_64 }}" alt="{{ main.corporation_name }}">
|
||||
<img class="ra-avatar" src="{{ main.corporation_logo_url_64 }}" alt="{{ main.corporation_name }}">
|
||||
{% if main.alliance_id %}
|
||||
<img class="ra-avatar" src="{{ main.alliance_logo_url_64 }}">
|
||||
<img class="ra-avatar" src="{{ main.alliance_logo_url_64 }}" alt="{{ main.alliance_name }}">
|
||||
{% endif %}
|
||||
{% if main.faction_id %}
|
||||
<img class="ra-avatar" src="{{ main.faction_logo_url_64 }}">
|
||||
<img class="ra-avatar" src="{{ main.faction_logo_url_64 }}" alt="{{ main.faction_name }}">
|
||||
{% endif %}
|
||||
</p>
|
||||
<p>
|
||||
@@ -103,13 +103,17 @@
|
||||
{% endif %}
|
||||
<div class="clearfix"></div>
|
||||
<div class="row">
|
||||
<div class="col-sm-6 button-wrapper">
|
||||
<a href="{% url 'authentication:add_character' %}" class="btn btn-block btn-info"
|
||||
title="Add Character">{% translate 'Add Character' %}</a>
|
||||
<div class="col-sm-6">
|
||||
<p>
|
||||
<a href="{% url 'authentication:add_character' %}" class="btn btn-block btn-info"
|
||||
title="Add Character">{% translate 'Add Character' %}</a>
|
||||
</p>
|
||||
</div>
|
||||
<div class="col-sm-6 button-wrapper">
|
||||
<a href="{% url 'authentication:change_main_character' %}" class="btn btn-block btn-info"
|
||||
title="Change Main Character">{% translate "Change Main" %}</a>
|
||||
<div class="col-sm-6">
|
||||
<p>
|
||||
<a href="{% url 'authentication:change_main_character' %}" class="btn btn-block btn-info"
|
||||
title="Change Main Character">{% translate "Change Main" %}</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -121,7 +125,7 @@
|
||||
<h3 class="panel-title">{% translate "Group Memberships" %}</h3>
|
||||
</div>
|
||||
<div class="panel-body">
|
||||
<div style="height: 240px;overflow:-moz-scrollbars-vertical;overflow-y:auto;">
|
||||
<div style="height: 240px;overflow-y:auto;">
|
||||
<table class="table table-aa">
|
||||
{% for group in groups %}
|
||||
<tr>
|
||||
@@ -154,11 +158,12 @@
|
||||
<tbody>
|
||||
{% for char in characters %}
|
||||
<tr>
|
||||
<td class="text-center"><img class="ra-avatar img-circle" src="{{ char.portrait_url_32 }}">
|
||||
<td class="text-center">
|
||||
<img class="ra-avatar img-circle" src="{{ char.portrait_url_32 }}" alt="{{ char.character_name }}">
|
||||
</td>
|
||||
<td class="text-center">{{ char.character_name }}</td>
|
||||
<td class="text-center">{{ char.corporation_name }}</td>
|
||||
<td class="text-center">{{ char.alliance_name }}</td>
|
||||
<td class="text-center">{{ char.alliance_name|default:"" }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
@@ -168,7 +173,7 @@
|
||||
{% for char in characters %}
|
||||
<tr>
|
||||
<td class="text-center" style="vertical-align: middle">
|
||||
<img class="ra-avatar img-circle" src="{{ char.portrait_url_32 }}">
|
||||
<img class="ra-avatar img-circle" src="{{ char.portrait_url_32 }}" alt="{{ char.character_name }}">
|
||||
</td>
|
||||
<td class="text-center" style="vertical-align: middle; width: 100%">
|
||||
<strong>{{ char.character_name }}</strong><br>
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
{% extends "allianceauth/base.html" %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block page_title %}{% translate "Dashboard" %}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<h1 class="page-header text-center">{% translate "Token Management" %}</h1>
|
||||
<div class="col-sm-12">
|
||||
<table class="table table-aa" id="table_tokens" style="width:100%">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{% translate "Scopes" %}</th>
|
||||
<th class="text-right">{% translate "Actions" %}</th>
|
||||
<th>{% translate "Character" %}</th>
|
||||
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for t in tokens %}
|
||||
<tr>
|
||||
<td styl="white-space:initial;">{% for s in t.scopes.all %}<span class="label label-default">{{s.name}}</span> {% endfor %}</td>
|
||||
<td nowrap class="text-right"><a href="{% url 'authentication:token_delete' t.id %}" class="btn btn-danger"><i class="fas fa-trash"></i></a> <a href="{% url 'authentication:token_refresh' t.id %}" class="btn btn-success"><i class="fas fa-sync-alt"></i></a></td>
|
||||
<td>{{t.character_name}}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% translate "This page is a best attempt, but backups or database logs can still contain your tokens. Always revoke tokens on https://community.eveonline.com/support/third-party-applications/ where possible."|urlize %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_javascript %}
|
||||
{% include 'bundles/datatables-js.html' %}
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_css %}
|
||||
{% include 'bundles/datatables-css.html' %}
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_script %}
|
||||
$(document).ready(function(){
|
||||
let grp = 2;
|
||||
var table = $('#table_tokens').DataTable({
|
||||
"columnDefs": [{ orderable: false, targets: [0,1] },{ "visible": false, "targets": grp }],
|
||||
"order": [[grp, 'asc']],
|
||||
"drawCallback": function (settings) {
|
||||
var api = this.api();
|
||||
var rows = api.rows({ page: 'current' }).nodes();
|
||||
var last = null;
|
||||
api.column(grp, { page: 'current' })
|
||||
.data()
|
||||
.each(function (group, i) {
|
||||
if (last !== group) {
|
||||
$(rows).eq(i).before('<tr class="info"><td colspan="3">' + group + '</td></tr>');
|
||||
last = group;
|
||||
}
|
||||
});
|
||||
},
|
||||
"stateSave": true,
|
||||
});
|
||||
});
|
||||
{% endblock %}
|
||||
@@ -1,4 +1,5 @@
|
||||
{% load static %}
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
@@ -7,7 +8,7 @@
|
||||
<meta name="description" content="">
|
||||
<meta name="author" content="">
|
||||
<meta property="og:title" content="{{ SITE_NAME }}">
|
||||
<meta property="og:image" content="{{ request.scheme }}://{{ request.get_host }}{% static 'allianceauth/icons/apple-touch-icon.png' %}">
|
||||
<meta property="og:image" content="{{ SITE_URL }}{% static 'allianceauth/icons/apple-touch-icon.png' %}">
|
||||
<meta property="og:description" content="Alliance Auth - An auth system for EVE Online to help in-game organizations manage online service access.">
|
||||
|
||||
{% include 'allianceauth/icons.html' %}
|
||||
@@ -31,6 +32,7 @@
|
||||
.panel-transparent {
|
||||
background: rgba(48, 48, 48, 0.7);
|
||||
color: #ffffff;
|
||||
padding-bottom: 21px;
|
||||
}
|
||||
|
||||
.panel-body {
|
||||
@@ -47,7 +49,7 @@
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container" style="margin-top:150px">
|
||||
<div class="container" style="margin-top:150px;">
|
||||
{% block content %}
|
||||
{% endblock %}
|
||||
</div>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
{% get_language_info_list for LANGUAGES as languages %}
|
||||
{% for language in languages %}
|
||||
<option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}>
|
||||
{{ language.name_local }} ({{ language.code }})
|
||||
{{ language.name_local|capfirst }} ({{ language.code }})
|
||||
</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
|
||||
@@ -7,6 +7,6 @@
|
||||
|
||||
{% block middle_box_content %}
|
||||
<a href="{% url 'auth_sso_login' %}{% if request.GET.next %}?next={{request.GET.next}}{%endif%}">
|
||||
<img class="img-responsive center-block" src="{% static 'allianceauth/authentication/img/sso/EVE_SSO_Login_Buttons_Large_Black.png' %}">
|
||||
<img class="img-responsive center-block" src="{% static 'allianceauth/authentication/img/sso/EVE_SSO_Login_Buttons_Large_Black.png' %}" alt="{% translate 'Login with Eve SSO' %}">
|
||||
</a>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
{% extends 'public/base.html' %}
|
||||
|
||||
{% load i18n %}
|
||||
|
||||
{% block content %}
|
||||
<div class="col-md-4 col-md-offset-4">
|
||||
{% if messages %}
|
||||
@@ -6,6 +9,7 @@
|
||||
<div class="alert alert-{{ message.level_tag}}">{{ message }}</div>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
<div class="panel panel-default panel-transparent">
|
||||
<div class="panel-body">
|
||||
<div class="col-md-12">
|
||||
@@ -13,10 +17,25 @@
|
||||
{% endblock %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% include 'public/lang_select.html' %}
|
||||
|
||||
<p class="text-center" style="margin-top: 2rem;">
|
||||
{% translate "For information on SSO, ESI and security read the CCP Dev Blog" %}<br>
|
||||
<a href="https://www.eveonline.com/article/introducing-esi" target="_blank" rel="noopener noreferrer">
|
||||
{% translate "Introducing ESI - A New API For Eve Online" %}
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<p class="text-center">
|
||||
<a href="https://community.eveonline.com/support/third-party-applications/" target="_blank" rel="noopener noreferrer">
|
||||
{% translate "Manage ESI Applications" %}
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block extra_include %}
|
||||
{% include 'bundles/bootstrap-js.html' %}
|
||||
{% endblock %}
|
||||
|
||||
@@ -116,10 +116,17 @@ class TestAuthenticate(TestCase):
|
||||
user = StateBackend().authenticate(token=t)
|
||||
self.assertEqual(user, self.user)
|
||||
|
||||
""" Alt Login disabled
|
||||
def test_authenticate_alt_character(self):
|
||||
t = Token(character_id=self.alt_character.character_id, character_owner_hash='2')
|
||||
user = StateBackend().authenticate(token=t)
|
||||
self.assertEqual(user, self.user)
|
||||
"""
|
||||
|
||||
def test_authenticate_alt_character_fail(self):
|
||||
t = Token(character_id=self.alt_character.character_id, character_owner_hash='2')
|
||||
user = StateBackend().authenticate(token=t)
|
||||
self.assertEqual(user, None)
|
||||
|
||||
def test_authenticate_unclaimed_character(self):
|
||||
t = Token(character_id=self.unclaimed_character.character_id, character_name=self.unclaimed_character.character_name, character_owner_hash='3')
|
||||
@@ -128,6 +135,7 @@ class TestAuthenticate(TestCase):
|
||||
self.assertEqual(user.username, 'Unclaimed_Character')
|
||||
self.assertEqual(user.profile.main_character, self.unclaimed_character)
|
||||
|
||||
""" Alt Login disabled
|
||||
def test_authenticate_character_record(self):
|
||||
t = Token(character_id=self.unclaimed_character.character_id, character_name=self.unclaimed_character.character_name, character_owner_hash='4')
|
||||
OwnershipRecord.objects.create(user=self.old_user, character=self.unclaimed_character, owner_hash='4')
|
||||
@@ -135,6 +143,15 @@ class TestAuthenticate(TestCase):
|
||||
self.assertEqual(user, self.old_user)
|
||||
self.assertTrue(CharacterOwnership.objects.filter(owner_hash='4', user=self.old_user).exists())
|
||||
self.assertTrue(user.profile.main_character)
|
||||
"""
|
||||
|
||||
def test_authenticate_character_record_fails(self):
|
||||
t = Token(character_id=self.unclaimed_character.character_id, character_name=self.unclaimed_character.character_name, character_owner_hash='4')
|
||||
OwnershipRecord.objects.create(user=self.old_user, character=self.unclaimed_character, owner_hash='4')
|
||||
user = StateBackend().authenticate(token=t)
|
||||
self.assertEqual(user, self.old_user)
|
||||
self.assertTrue(CharacterOwnership.objects.filter(owner_hash='4', user=self.old_user).exists())
|
||||
self.assertTrue(user.profile.main_character)
|
||||
|
||||
def test_iterate_username(self):
|
||||
t = Token(character_id=self.unclaimed_character.character_id,
|
||||
|
||||
@@ -22,5 +22,20 @@ urlpatterns = [
|
||||
views.add_character,
|
||||
name='add_character'
|
||||
),
|
||||
path(
|
||||
'account/tokens/manage/',
|
||||
views.token_management,
|
||||
name='token_management'
|
||||
),
|
||||
path(
|
||||
'account/tokens/delete/<int:token_id>',
|
||||
views.token_delete,
|
||||
name='token_delete'
|
||||
),
|
||||
path(
|
||||
'account/tokens/refresh/<int:token_id>',
|
||||
views.token_refresh,
|
||||
name='token_refresh'
|
||||
),
|
||||
path('dashboard/', views.dashboard, name='dashboard'),
|
||||
]
|
||||
|
||||
@@ -61,6 +61,44 @@ def dashboard(request):
|
||||
}
|
||||
return render(request, 'authentication/dashboard.html', context)
|
||||
|
||||
@login_required
|
||||
def token_management(request):
|
||||
tokens = request.user.token_set.all()
|
||||
|
||||
context = {
|
||||
'tokens': tokens
|
||||
}
|
||||
return render(request, 'authentication/tokens.html', context)
|
||||
|
||||
@login_required
|
||||
def token_delete(request, token_id=None):
|
||||
try:
|
||||
token = Token.objects.get(id=token_id)
|
||||
if request.user == token.user:
|
||||
token.delete()
|
||||
messages.success(request, "Token Deleted.")
|
||||
else:
|
||||
messages.error(request, "This token does not belong to you.")
|
||||
except Token.DoesNotExist:
|
||||
messages.warning(request, "Token does not exist")
|
||||
return redirect('authentication:token_management')
|
||||
|
||||
@login_required
|
||||
def token_refresh(request, token_id=None):
|
||||
try:
|
||||
token = Token.objects.get(id=token_id)
|
||||
if request.user == token.user:
|
||||
try:
|
||||
token.refresh()
|
||||
messages.success(request, "Token refreshed.")
|
||||
except Exception as e:
|
||||
messages.warning(request, f"Failed to refresh token. {e}")
|
||||
else:
|
||||
messages.error(request, "This token does not belong to you.")
|
||||
except Token.DoesNotExist:
|
||||
messages.warning(request, "Token does not exist")
|
||||
return redirect('authentication:token_management')
|
||||
|
||||
|
||||
@login_required
|
||||
@token_required(scopes=settings.LOGIN_TOKEN_SCOPES)
|
||||
|
||||
@@ -5,5 +5,6 @@ from .views import NightModeRedirectView
|
||||
def auth_settings(request):
|
||||
return {
|
||||
'SITE_NAME': settings.SITE_NAME,
|
||||
'SITE_URL': settings.SITE_URL,
|
||||
'NIGHT_MODE': NightModeRedirectView.night_mode_state(request),
|
||||
}
|
||||
|
||||
@@ -8,11 +8,11 @@
|
||||
<table class="table">
|
||||
<tr>
|
||||
<td class="text-center col-lg-6{% if corpstats.corp.alliance %}{% else %}col-lg-offset-3{% endif %}">
|
||||
<img class="ra-avatar" src="{{ corpstats.corp.logo_url_64 }}">
|
||||
<img class="ra-avatar" src="{{ corpstats.corp.logo_url_64 }}" alt="{{ corpstats.corp.corporation_name }}">
|
||||
</td>
|
||||
{% if corpstats.corp.alliance %}
|
||||
<td class="text-center col-lg-6">
|
||||
<img class="ra-avatar" src="{{ corpstats.corp.alliance.logo_url_64 }}">
|
||||
<img class="ra-avatar" src="{{ corpstats.corp.alliance.logo_url_64 }}" alt="{{ corpstats.corp.alliance.alliance_name }}">
|
||||
</td>
|
||||
{% endif %}
|
||||
</tr>
|
||||
@@ -59,7 +59,7 @@
|
||||
<tr>
|
||||
<td class="text-center" style="vertical-align:middle">
|
||||
<div class="thumbnail" style="border: 0 none; box-shadow: none; background: transparent;">
|
||||
<img src="{{ main.main.portrait_url_64 }}" class="img-circle">
|
||||
<img src="{{ main.main.portrait_url_64 }}" class="img-circle" alt="{{ main.main }}">
|
||||
<div class="caption text-center">
|
||||
{{ main.main }}
|
||||
</div>
|
||||
@@ -80,7 +80,7 @@
|
||||
<tr>
|
||||
<td class="text-center" style="width:5%">
|
||||
<div class="thumbnail" style="border: 0 none; box-shadow: none; background: transparent;">
|
||||
<img src="{{ alt.portrait_url_32 }}" class="img-circle">
|
||||
<img src="{{ alt.portrait_url_32 }}" class="img-circle" alt="{{ alt.character_name }}">
|
||||
</div>
|
||||
</td>
|
||||
<td class="text-center" style="width:30%">{{ alt.character_name }}</td>
|
||||
@@ -119,7 +119,7 @@
|
||||
<tbody>
|
||||
{% for member in members %}
|
||||
<tr>
|
||||
<td><img src="{{ member.portrait_url }}" class="img-circle"></td>
|
||||
<td><img src="{{ member.portrait_url }}" class="img-circle" alt="{{ member }}"></td>
|
||||
<td class="text-center">{{ member }}</td>
|
||||
<td class="text-center">
|
||||
<a href="https://zkillboard.com/character/{{ member.character_id }}/" class="label label-danger" target="_blank">{% translate "Killboard" %}</a>
|
||||
@@ -131,7 +131,7 @@
|
||||
{% endfor %}
|
||||
{% for member in unregistered %}
|
||||
<tr class="danger">
|
||||
<td><img src="{{ member.portrait_url }}" class="img-circle"></td>
|
||||
<td><img src="{{ member.portrait_url }}" class="img-circle" alt="{{ member.character_name }}"></td>
|
||||
<td class="text-center">{{ member.character_name }}</td>
|
||||
<td class="text-center">
|
||||
<a href="https://zkillboard.com/character/{{ member.character_id }}/" class="label label-danger" target="_blank">{% translate "Killboard" %}</a>
|
||||
@@ -160,7 +160,7 @@
|
||||
<tbody>
|
||||
{% for member in unregistered %}
|
||||
<tr class="danger">
|
||||
<td><img src="{{ member.portrait_url }}" class="img-circle"></td>
|
||||
<td><img src="{{ member.portrait_url }}" class="img-circle" alt="{{ member.character_name }}"></td>
|
||||
<td class="text-center">{{ member.character_name }}</td>
|
||||
<td class="text-center">
|
||||
<a href="https://zkillboard.com/character/{{ member.character_id }}/" class="label label-danger" target="_blank">
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<tbody>
|
||||
{% for result in results %}
|
||||
<tr {% if not result.1.registered %}class="danger"{% endif %}>
|
||||
<td class="text-center"><img src="{{ result.1.portrait_url }}" class="img-circle"></td>
|
||||
<td class="text-center"><img src="{{ result.1.portrait_url }}" class="img-circle" alt="{{ result.1.character_name }}"></td>
|
||||
<td class="text-center">{{ result.1.character_name }}</td>
|
||||
<td class="text-center">{{ result.0.corp.corporation_name }}</td>
|
||||
<td class="text-center"><a href="https://zkillboard.com/character/{{ result.1.character_id }}/" class="label label-danger" target="_blank">{% translate "Killboard" %}</a></td>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# Generated by Django 4.0.7 on 2022-08-14 16:23
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('eveonline', '0016_character_names_are_not_unique'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='eveallianceinfo',
|
||||
name='alliance_name',
|
||||
field=models.CharField(max_length=254, db_index=True),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='evecorporationinfo',
|
||||
name='corporation_name',
|
||||
field=models.CharField(max_length=254, db_index=True),
|
||||
),
|
||||
]
|
||||
@@ -71,7 +71,7 @@ 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_name = models.CharField(max_length=254, db_index=True)
|
||||
alliance_ticker = models.CharField(max_length=254)
|
||||
executor_corp_id = models.PositiveIntegerField()
|
||||
|
||||
@@ -139,7 +139,7 @@ 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_name = models.CharField(max_length=254, db_index=True)
|
||||
corporation_ticker = models.CharField(max_length=254)
|
||||
member_count = models.IntegerField()
|
||||
ceo_id = models.PositiveIntegerField(blank=True, null=True, default=None)
|
||||
|
||||
@@ -8,6 +8,7 @@ from django.conf import settings
|
||||
from esi.clients import esi_client_factory
|
||||
|
||||
from allianceauth import __version__
|
||||
from allianceauth.utils.django import StartupCommand
|
||||
|
||||
|
||||
SWAGGER_SPEC_PATH = os.path.join(os.path.dirname(
|
||||
@@ -175,15 +176,16 @@ class EveProvider:
|
||||
|
||||
class EveSwaggerProvider(EveProvider):
|
||||
def __init__(self, token=None, adapter=None):
|
||||
if settings.DEBUG:
|
||||
if settings.DEBUG or StartupCommand().is_management_command:
|
||||
self._client = None
|
||||
logger.info(
|
||||
'DEBUG mode detected: ESI client will be loaded on-demand.'
|
||||
)
|
||||
logger.info('ESI client will be loaded on-demand')
|
||||
else:
|
||||
logger.info('Loading ESI client')
|
||||
try:
|
||||
self._client = esi_client_factory(
|
||||
token=token, spec_file=SWAGGER_SPEC_PATH, app_info_text=("allianceauth v" + __version__)
|
||||
token=token,
|
||||
spec_file=SWAGGER_SPEC_PATH,
|
||||
app_info_text=f"allianceauth v{__version__}"
|
||||
)
|
||||
except (HTTPError, RefResolutionError):
|
||||
logger.exception(
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
<div class="panel-heading">{{ character_name }}</div>
|
||||
<div class="panel-body">
|
||||
<div class="col-lg-2 col-sm-2">
|
||||
<img class="ra-avatar img-responsive" src="{{ character_portrait_url }}">
|
||||
<img class="ra-avatar img-responsive" src="{{ character_portrait_url }}" alt="{{ character_name }}">
|
||||
</div>
|
||||
<div class="col-lg-10 col-sm-2">
|
||||
<div class="alert alert-danger" role="alert">{% translate "Character not registered!" %}</div>
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
{% extends "allianceauth/base.html" %}
|
||||
{% load bootstrap %}
|
||||
{% load i18n %}
|
||||
{% block page_title %}{% translate "Fatlink view" %}{% endblock page_title %}
|
||||
|
||||
@@ -31,7 +30,7 @@
|
||||
<td class="text-center">{{ fat.user }}</td>
|
||||
<td class="text-center">{{ fat.character.character_name }}</td>
|
||||
{% if fat.station != "No Station" %}
|
||||
<td class="text-center">{% blocktrans %}Docked in {% endblocktrans %}{{ fat.system }}</td>
|
||||
<td class="text-center">{% blocktranslate %}Docked in {% endblocktranslate %}{{ fat.system }}</td>
|
||||
{% else %}
|
||||
<td class="text-center">{{ fat.system }}</td>
|
||||
{% endif %}
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
{% extends "allianceauth/base.html" %}
|
||||
{% load bootstrap %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block page_title %}{% translate "Personal fatlink statistics" %}{% endblock page_title %}
|
||||
|
||||
{% block content %}
|
||||
<div class="col-lg-12">
|
||||
<h1 class="page-header text-center">{% blocktrans %}Participation data statistics for {{ month }}, {{ year }}{% endblocktrans %}
|
||||
<h1 class="page-header text-center">{% blocktranslate %}Participation data statistics for {{ month }}, {{ year }}{% endblocktranslate %}
|
||||
{% if char_id %}
|
||||
<div class="text-right">
|
||||
<a href="{% url 'fatlink:user_statistics_month' char_id previous_month|date:'Y' previous_month|date:'m' %}" class="btn btn-info">{% translate "Previous month" %}</a>
|
||||
@@ -15,11 +14,11 @@
|
||||
{% endif %}
|
||||
</h1>
|
||||
<h2>
|
||||
{% blocktrans count links=n_fats trimmed %}
|
||||
{% blocktranslate count links=n_fats trimmed %}
|
||||
{{ user }} has collected one link this month.
|
||||
{% plural %}
|
||||
{{ user }} has collected {{ links }} links this month.
|
||||
{% endblocktrans %}
|
||||
{% endblocktranslate %}
|
||||
</h2>
|
||||
<table class="table table-responsive">
|
||||
<tr>
|
||||
@@ -35,11 +34,11 @@
|
||||
</table>
|
||||
{% if created_fats %}
|
||||
<h2>
|
||||
{% blocktrans count links=n_created_fats trimmed %}
|
||||
{% blocktranslate count links=n_created_fats trimmed %}
|
||||
{{ user }} has created one link this month.
|
||||
{% plural %}
|
||||
{{ user }} has created {{ links }} links this month.
|
||||
{% endblocktrans %}
|
||||
{% endblocktranslate %}
|
||||
</h2>
|
||||
{% if created_fats %}
|
||||
<table class="table">
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
{% extends "allianceauth/base.html" %}
|
||||
{% load bootstrap %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block page_title %}{% translate "Personal fatlink statistics" %}{% endblock page_title %}
|
||||
|
||||
{% block content %}
|
||||
<div class="col-lg-12">
|
||||
<h1 class="page-header text-center">{% blocktrans %}Participation data statistics for {{ year }}{% endblocktrans %}
|
||||
<h1 class="page-header text-center">{% blocktranslate %}Participation data statistics for {{ year }}{% endblocktranslate %}
|
||||
<div class="text-right">
|
||||
<a href="{% url 'fatlink:personal_statistics_year' previous_year %}" class="btn btn-info">{% translate "Previous year" %}</a>
|
||||
{% if next_year %}
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
{% extends "allianceauth/base.html" %}
|
||||
{% load bootstrap %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block page_title %}{% translate "Fatlink Corp Statistics" %}{% endblock page_title %}
|
||||
|
||||
{% block content %}
|
||||
<div class="col-lg-12">
|
||||
<h1 class="page-header text-center">{% blocktrans %}Participation data statistics for {{ month }}, {{ year }}{% endblocktrans %}
|
||||
<h1 class="page-header text-center">{% blocktranslate %}Participation data statistics for {{ month }}, {{ year }}{% endblocktranslate %}
|
||||
<div class="text-right">
|
||||
<a href="{% url 'fatlink:statistics_corp_month' corpid previous_month|date:"Y" previous_month|date:"m" %}" class="btn btn-info">{% translate "Previous month" %}</a>
|
||||
{% if next_month %}
|
||||
@@ -28,7 +27,7 @@
|
||||
{% for memberStat in fatStats %}
|
||||
<tr>
|
||||
<td>
|
||||
<img src="{{ memberStat.mainchar.portrait_url_32 }}" class="ra-avatar img-responsive">
|
||||
<img src="{{ memberStat.mainchar.portrait_url_32 }}" class="ra-avatar img-responsive" alt="{{ memberStat.mainchar.character_name }}">
|
||||
</td>
|
||||
<td class="text-center">{{ memberStat.mainchar.character_name }}</td>
|
||||
<td class="text-center">{{ memberStat.n_chars }}</td>
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
{% extends "allianceauth/base.html" %}
|
||||
{% load bootstrap %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block page_title %}{% translate "Fatlink statistics" %}{% endblock page_title %}
|
||||
|
||||
{% block content %}
|
||||
<div class="col-lg-12">
|
||||
<h1 class="page-header text-center">{% blocktrans %}Participation data statistics for {{ month }}, {{ year }}{% endblocktrans %}
|
||||
<h1 class="page-header text-center">{% blocktranslate %}Participation data statistics for {{ month }}, {{ year }}{% endblocktranslate %}
|
||||
<div class="text-right">
|
||||
<a href="{% url 'fatlink:statistics_month' previous_month|date:"Y" previous_month|date:"m" %}" class="btn btn-info">{% translate "Previous month" %}</a>
|
||||
{% if next_month %}
|
||||
@@ -29,9 +28,9 @@
|
||||
{% for corpStat in fatStats %}
|
||||
<tr>
|
||||
<td>
|
||||
<img src="{{ corpStat.corp.logo_url_32 }}" class="ra-avatar img-responsive">
|
||||
<img src="{{ corpStat.corp.logo_url_32 }}" class="ra-avatar img-responsive" alt="{{ corpStat.corp.corporation_name }}">
|
||||
</td>
|
||||
<td class="text-center"><a href="{% url 'fatlink:statistics_corp' corpStat.corp.corporation_id %}">[{{ corpStat.corp.corporation_ticker }}]</td>
|
||||
<td class="text-center"><a href="{% url 'fatlink:statistics_corp' corpStat.corp.corporation_id %}">[{{ corpStat.corp.corporation_ticker }}]</a></td>
|
||||
<td class="text-center">{{ corpStat.corp.corporation_name }}</td>
|
||||
<td class="text-center">{{ corpStat.corp.member_count }}</td>
|
||||
<td class="text-center">{{ corpStat.n_fats }}</td>
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
{% extends "allianceauth/base.html" %}
|
||||
{% load bootstrap %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block page_title %}{% translate "Fatlink view" %}{% endblock page_title %}
|
||||
@@ -34,7 +33,7 @@
|
||||
<td class="text-center">{{ fat.fatlink.fleet }}</td>
|
||||
<td class="text-center">{{ fat.character.character_name }}</td>
|
||||
{% if fat.station != "No Station" %}
|
||||
<td class="text-center">{% blocktrans %}Docked in {% endblocktrans %}{{ fat.system }}</td>
|
||||
<td class="text-center">{% blocktranslate %}Docked in {% endblocktranslate %}{{ fat.system }}</td>
|
||||
{% else %}
|
||||
<td class="text-center">{{ fat.system }}</td>
|
||||
{% endif %}
|
||||
|
||||
@@ -248,59 +248,82 @@ def fatlink_monthly_personal_statistics_view(request, year, month, char_id=None)
|
||||
|
||||
@login_required
|
||||
@token_required(
|
||||
scopes=['esi-location.read_location.v1', 'esi-location.read_ship_type.v1', 'esi-universe.read_structures.v1'])
|
||||
scopes=[
|
||||
'esi-location.read_location.v1',
|
||||
'esi-location.read_ship_type.v1',
|
||||
'esi-universe.read_structures.v1',
|
||||
'esi-location.read_online.v1',
|
||||
]
|
||||
)
|
||||
def click_fatlink_view(request, token, fat_hash=None):
|
||||
fatlink = get_object_or_404(Fatlink, hash=fat_hash)
|
||||
c = token.get_esi_client(spec_file=SWAGGER_SPEC_PATH)
|
||||
character = EveCharacter.objects.get_character_by_id(token.character_id)
|
||||
character_online = c.Location.get_characters_character_id_online(
|
||||
character_id=token.character_id
|
||||
).result()
|
||||
|
||||
if (timezone.now() - fatlink.fatdatetime) < datetime.timedelta(seconds=(fatlink.duration * 60)):
|
||||
if character_online["online"] is True:
|
||||
fatlink = get_object_or_404(Fatlink, hash=fat_hash)
|
||||
|
||||
character = EveCharacter.objects.get_character_by_id(token.character_id)
|
||||
if (timezone.now() - fatlink.fatdatetime) < datetime.timedelta(seconds=(fatlink.duration * 60)):
|
||||
if character:
|
||||
# get data
|
||||
location = c.Location.get_characters_character_id_location(character_id=token.character_id).result()
|
||||
ship = c.Location.get_characters_character_id_ship(character_id=token.character_id).result()
|
||||
location['solar_system_name'] = \
|
||||
c.Universe.get_universe_systems_system_id(system_id=location['solar_system_id']).result()['name']
|
||||
|
||||
if character:
|
||||
# get data
|
||||
c = token.get_esi_client(spec_file=SWAGGER_SPEC_PATH)
|
||||
location = c.Location.get_characters_character_id_location(character_id=token.character_id).result()
|
||||
ship = c.Location.get_characters_character_id_ship(character_id=token.character_id).result()
|
||||
location['solar_system_name'] = \
|
||||
c.Universe.get_universe_systems_system_id(system_id=location['solar_system_id']).result()['name']
|
||||
if location['station_id']:
|
||||
location['station_name'] = \
|
||||
c.Universe.get_universe_stations_station_id(station_id=location['station_id']).result()['name']
|
||||
elif location['structure_id']:
|
||||
location['station_name'] = \
|
||||
c.Universe.get_universe_structures_structure_id(structure_id=location['structure_id']).result()[
|
||||
'name']
|
||||
if location['station_id']:
|
||||
location['station_name'] = \
|
||||
c.Universe.get_universe_stations_station_id(station_id=location['station_id']).result()['name']
|
||||
elif location['structure_id']:
|
||||
location['station_name'] = \
|
||||
c.Universe.get_universe_structures_structure_id(structure_id=location['structure_id']).result()[
|
||||
'name']
|
||||
else:
|
||||
location['station_name'] = "No Station"
|
||||
|
||||
ship['ship_type_name'] = provider.get_itemtype(ship['ship_type_id']).name
|
||||
|
||||
fat = Fat()
|
||||
fat.system = location['solar_system_name']
|
||||
fat.station = location['station_name']
|
||||
fat.shiptype = ship['ship_type_name']
|
||||
fat.fatlink = fatlink
|
||||
fat.character = character
|
||||
fat.user = request.user
|
||||
|
||||
try:
|
||||
fat.full_clean()
|
||||
fat.save()
|
||||
messages.success(request, _('Fleet participation registered.'))
|
||||
except ValidationError as e:
|
||||
err_messages = []
|
||||
|
||||
for errorname, message in e.message_dict.items():
|
||||
err_messages.append(message[0])
|
||||
|
||||
messages.error(request, ' '.join(err_messages))
|
||||
else:
|
||||
location['station_name'] = "No Station"
|
||||
ship['ship_type_name'] = provider.get_itemtype(ship['ship_type_id']).name
|
||||
context = {
|
||||
'character_id': token.character_id,
|
||||
'character_name': token.character_name,
|
||||
'character_portrait_url': EveCharacter.generic_portrait_url(
|
||||
token.character_id, 128
|
||||
),
|
||||
}
|
||||
|
||||
fat = Fat()
|
||||
fat.system = location['solar_system_name']
|
||||
fat.station = location['station_name']
|
||||
fat.shiptype = ship['ship_type_name']
|
||||
fat.fatlink = fatlink
|
||||
fat.character = character
|
||||
fat.user = request.user
|
||||
try:
|
||||
fat.full_clean()
|
||||
fat.save()
|
||||
messages.success(request, _('Fleet participation registered.'))
|
||||
except ValidationError as e:
|
||||
err_messages = []
|
||||
for errorname, message in e.message_dict.items():
|
||||
err_messages.append(message[0])
|
||||
messages.error(request, ' '.join(err_messages))
|
||||
return render(request, 'fleetactivitytracking/characternotexisting.html', context=context)
|
||||
else:
|
||||
context = {
|
||||
'character_id': token.character_id,
|
||||
'character_name': token.character_name,
|
||||
'character_portrait_url': EveCharacter.generic_portrait_url(
|
||||
token.character_id, 128
|
||||
),
|
||||
}
|
||||
return render(request, 'fleetactivitytracking/characternotexisting.html', context=context)
|
||||
messages.error(request, _('FAT link has expired.'))
|
||||
else:
|
||||
messages.error(request, _('FAT link has expired.'))
|
||||
messages.warning(
|
||||
request,
|
||||
_(
|
||||
f"Cannot register the fleet participation for {character.character_name}. The character needs to be online."
|
||||
),
|
||||
)
|
||||
|
||||
return redirect('fatlink:view')
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
{% extends "allianceauth/base.html" %}
|
||||
{% load static %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block page_title %}{{ group }} {% translate "Audit Log" %}{% endblock page_title %}
|
||||
|
||||
@@ -36,7 +36,7 @@
|
||||
{% for member in members %}
|
||||
<tr>
|
||||
<td>
|
||||
<img src="{{ member.main_char|character_portrait_url:32 }}" class="img-circle" style="margin-right: 1rem;">
|
||||
<img src="{{ member.main_char|character_portrait_url:32 }}" class="img-circle" style="margin-right: 1rem;" alt="{{ member.main_char.character_name }}">
|
||||
{% if member.main_char %}
|
||||
<a href="{{ member.main_char|evewho_character_url }}" target="_blank">
|
||||
{{ member.main_char.character_name }}
|
||||
|
||||
@@ -60,7 +60,7 @@
|
||||
<i class="glyphicon glyphicon-list-alt"></i>
|
||||
</a>
|
||||
|
||||
<a id="clipboard-copy" data-clipboard-text="{{ request.scheme }}://{{request.get_host}}{% url 'groupmanagement:request_add' group.id %}" class="btn btn-warning" title="{% translate "Copy Direct Join Link" %}">
|
||||
<a id="clipboard-copy" data-clipboard-text="{{ SITE_URL }}{% url 'groupmanagement:request_add' group.id %}" class="btn btn-warning" title="{% translate "Copy Direct Join Link" %}">
|
||||
<i class="glyphicon glyphicon-copy"></i>
|
||||
</a>
|
||||
</td>
|
||||
|
||||
@@ -63,7 +63,7 @@
|
||||
{% for acceptrequest in acceptrequests %}
|
||||
<tr>
|
||||
<td>
|
||||
<img src="{{ acceptrequest.main_char|character_portrait_url:32 }}" class="img-circle" style="margin-right: 1rem;">
|
||||
<img src="{{ acceptrequest.main_char|character_portrait_url:32 }}" class="img-circle" style="margin-right: 1rem;" alt="{{ acceptrequest.main_char.character_name }}">
|
||||
{% if acceptrequest.main_char %}
|
||||
<a href="{{ acceptrequest.main_char|evewho_character_url }}" target="_blank">
|
||||
{{ acceptrequest.main_char.character_name }}
|
||||
@@ -120,7 +120,7 @@
|
||||
{% for leaverequest in leaverequests %}
|
||||
<tr>
|
||||
<td>
|
||||
<img src="{{ leaverequest.main_char|character_portrait_url:32 }}" class="img-circle" style="margin-right: 1rem;">
|
||||
<img src="{{ leaverequest.main_char|character_portrait_url:32 }}" class="img-circle" style="margin-right: 1rem;" alt="{{ leaverequest.main_char.character_name }}">
|
||||
{% if leaverequest.main_char %}
|
||||
<a href="{{ leaverequest.main_char|evewho_character_url }}" target="_blank">
|
||||
{{ leaverequest.main_char.character_name }}
|
||||
|
||||
@@ -5,7 +5,7 @@ app_name = "groupmanagement"
|
||||
|
||||
urlpatterns = [
|
||||
# groups
|
||||
path("groups", views.groups_view, name="groups"),
|
||||
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"
|
||||
|
||||
@@ -15,11 +15,11 @@
|
||||
<label class="control-label" for="id_{{ question.pk }}">{{ question.title }}</label>
|
||||
<div class=" ">
|
||||
{% if question.help_text %}
|
||||
<div cass="text-center">{{ question.help_text }}</div>
|
||||
<div class="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 }}_choice_{{ forloop.counter }}" value="{{ choice.choice_text }}">
|
||||
<label for="id_{{ question.pk }}_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 %}
|
||||
|
||||
@@ -177,7 +177,7 @@
|
||||
<h4 class="modal-title" id="myModalLabel">{% translate "Application Search" %}</h4>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form class="form-signin" role="form" action={% url 'hrapplications:search' %} method="POST">
|
||||
<form class="form-signin" role="form" action="{% url 'hrapplications:search' %}" method="POST">
|
||||
{% csrf_token %}
|
||||
{{ search_form|bootstrap }}
|
||||
<br>
|
||||
|
||||
@@ -63,7 +63,7 @@
|
||||
<h4 class="modal-title" id="myModalLabel">{% translate "Application Search" %}</h4>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<form class="form-signin" role="form" action={% url 'hrapplications:search' %} method="POST">
|
||||
<form class="form-signin" role="form" action="{% url 'hrapplications:search' %}" method="POST">
|
||||
{% csrf_token %}
|
||||
{{ search_form|bootstrap }}
|
||||
<br>
|
||||
|
||||
@@ -48,7 +48,7 @@
|
||||
{% for char in app.characters %}
|
||||
<tr>
|
||||
<td class="text-center">
|
||||
<img class="ra-avatar img-responsive img-circle" src="{{ char.portrait_url_32 }}">
|
||||
<img class="ra-avatar img-responsive img-circle" src="{{ char.portrait_url_32 }}" alt="{{ char.character_name }}">
|
||||
</td>
|
||||
<td class="text-center">{{ char.character_name }}</td>
|
||||
<td class="text-center">{{ char.corporation_name }}</td>
|
||||
|
||||
@@ -219,7 +219,7 @@ def hr_application_search(request):
|
||||
Q(user__character_ownerships__character__corporation_name__icontains=searchstring) |
|
||||
Q(user__character_ownerships__character__alliance_name__icontains=searchstring) |
|
||||
Q(user__username__icontains=searchstring)
|
||||
)
|
||||
).distinct()
|
||||
|
||||
context = {'applications': applications, 'search_form': HRApplicationSearchForm()}
|
||||
|
||||
|
||||
Binary file not shown.
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Binary file not shown.
File diff suppressed because it is too large
Load Diff
Binary file not shown.
File diff suppressed because it is too large
Load Diff
Binary file not shown.
File diff suppressed because it is too large
Load Diff
Binary file not shown.
File diff suppressed because it is too large
Load Diff
Binary file not shown.
File diff suppressed because it is too large
Load Diff
Binary file not shown.
File diff suppressed because it is too large
Load Diff
BIN
allianceauth/locale/uk/LC_MESSAGES/django.mo
Normal file
BIN
allianceauth/locale/uk/LC_MESSAGES/django.mo
Normal file
Binary file not shown.
2410
allianceauth/locale/uk/LC_MESSAGES/django.po
Normal file
2410
allianceauth/locale/uk/LC_MESSAGES/django.po
Normal file
File diff suppressed because it is too large
Load Diff
Binary file not shown.
File diff suppressed because it is too large
Load Diff
@@ -8,15 +8,15 @@
|
||||
|
||||
<div class="panel panel-default">
|
||||
|
||||
<div class="panel-heading">
|
||||
<ul class="nav nav-pills">
|
||||
<div class="panel-heading clearfix">
|
||||
<ul class="nav nav-pills navbar-left">
|
||||
<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 class="nav navbar-nav navbar-right" style="margin-right: 0;">
|
||||
<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>
|
||||
</div>
|
||||
|
||||
<div class="panel-body">
|
||||
|
||||
@@ -34,7 +34,7 @@ class OpTimer(models.Model):
|
||||
fc = models.CharField(max_length=254, default="")
|
||||
post_time = models.DateTimeField(default=timezone.now)
|
||||
eve_character = models.ForeignKey(EveCharacter, null=True,
|
||||
on_delete=models.SET_NULL)
|
||||
on_delete=models.SET_NULL)
|
||||
description = models.TextField(blank=True, default="")
|
||||
type = models.ForeignKey(OpTimerType, null=True, on_delete=models.SET_NULL)
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
{% extends "allianceauth/base.html" %}
|
||||
{% load static %}
|
||||
{% load i18n %}
|
||||
{% get_current_language as LANGUAGE_CODE %}
|
||||
|
||||
@@ -42,7 +41,7 @@
|
||||
{% include 'bundles/moment-js.html' with locale=True %}
|
||||
{% include 'bundles/timers-js.html' %}
|
||||
|
||||
<script type="application/javascript">
|
||||
<script>
|
||||
// Data
|
||||
let timers = [
|
||||
{% for op in optimer %}
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
{% extends "allianceauth/base.html" %}
|
||||
{% load bootstrap %}
|
||||
{% load static %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block page_title %}{{ permission.permission.codename }} - {% translate "Permissions Audit" %}{% endblock page_title %}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
{{ type }}: {{ name }}
|
||||
</td>
|
||||
<td class="text-right">
|
||||
<img src="{{ user.profile.main_character|character_portrait_url:32 }}" class="img-circle">
|
||||
<img src="{{ user.profile.main_character|character_portrait_url:32 }}" class="img-circle" alt="{{ user.profile.main_character.character_name }}">
|
||||
</td>
|
||||
<td>
|
||||
<strong>{{ user }}<br></strong>
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
{% extends "allianceauth/base.html" %}
|
||||
{% load bootstrap %}
|
||||
{% load static %}
|
||||
{% load i18n %}
|
||||
|
||||
{% block page_title %}{% translate "Permissions Overview" %}{% endblock page_title %}
|
||||
@@ -10,10 +8,10 @@
|
||||
<h1 class="page-header">{% translate "Permissions Overview" %}</h1>
|
||||
<p>
|
||||
{% if request.GET.all != 'yes' %}
|
||||
{% blocktrans %}Showing only applied permissions{% endblocktrans %}
|
||||
{% blocktranslate %}Showing only applied permissions{% endblocktranslate %}
|
||||
<a href="{% url 'permissions_tool:overview' %}?all=yes" class="btn btn-primary">{% translate "Show All" %}</a>
|
||||
{% else %}
|
||||
{% blocktrans %}Showing all permissions{% endblocktrans %}
|
||||
{% blocktranslate %}Showing all permissions{% endblocktranslate %}
|
||||
<a href="{% url 'permissions_tool:overview' %}?all=no" class="btn btn-primary">{% translate "Show Applied" %}</a>
|
||||
{% endif %}
|
||||
</p>
|
||||
|
||||
@@ -84,17 +84,17 @@ LOCALE_PATHS = (
|
||||
os.path.join(BASE_DIR, 'locale/'),
|
||||
)
|
||||
|
||||
ugettext = lambda s: s
|
||||
LANGUAGES = (
|
||||
('en', ugettext('English')),
|
||||
('de', ugettext('German')),
|
||||
('es', ugettext('Spanish')),
|
||||
('zh-hans', ugettext('Chinese Simplified')),
|
||||
('ru', ugettext('Russian')),
|
||||
('ko', ugettext('Korean')),
|
||||
('fr', ugettext('French')),
|
||||
('ja', ugettext('Japanese')),
|
||||
('it', ugettext('Italian')),
|
||||
("en", "English"),
|
||||
("de", "German"),
|
||||
("es", "Spanish"),
|
||||
("zh-hans", "Chinese Simplified"),
|
||||
("ru", "Russian"),
|
||||
("ko", "Korean"),
|
||||
("fr", "French"),
|
||||
("ja", "Japanese"),
|
||||
("it", "Italian"),
|
||||
("uk", "Ukrainian"),
|
||||
)
|
||||
|
||||
TEMPLATES = [
|
||||
|
||||
@@ -13,6 +13,13 @@ STATIC_ROOT = "/var/www/{{ project_name }}/static/"
|
||||
# in page titles and the site header.
|
||||
SITE_NAME = '{{ project_name }}'
|
||||
|
||||
# This is your websites URL, set it accordingly
|
||||
# Make sure this URL is WITHOUT a trailing slash
|
||||
SITE_URL = "https://example.com"
|
||||
|
||||
# Django security
|
||||
CSRF_TRUSTED_ORIGINS = [SITE_URL]
|
||||
|
||||
# Change this to enable/disable debug mode, which displays
|
||||
# useful error messages but can leak sensitive data.
|
||||
DEBUG = False
|
||||
@@ -39,15 +46,16 @@ DATABASES['default'] = {
|
||||
|
||||
# Register an application at https://developers.eveonline.com for Authentication
|
||||
# & API Access and fill out these settings. Be sure to set the callback URL
|
||||
# to https://example.com/sso/callback substituting your domain for example.com
|
||||
# to https://example.com/sso/callback substituting your domain for example.com in
|
||||
# CCP's developer portal
|
||||
# Logging in to auth requires the publicData scope (can be overridden through the
|
||||
# LOGIN_TOKEN_SCOPES setting). Other apps may require more (see their docs).
|
||||
ESI_SSO_CLIENT_ID = ''
|
||||
ESI_SSO_CLIENT_SECRET = ''
|
||||
ESI_SSO_CALLBACK_URL = ''
|
||||
ESI_SSO_CALLBACK_URL = f"{SITE_URL}/sso/callback"
|
||||
ESI_USER_CONTACT_EMAIL = '' # A server maintainer that CCP can contact in case of issues.
|
||||
|
||||
# By default emails are validated before new users can log in.
|
||||
# By default, emails are validated before new users can log in.
|
||||
# It's recommended to use a free service like SparkPost or Elastic Email to send email.
|
||||
# https://www.sparkpost.com/docs/integrations/django/
|
||||
# https://elasticemail.com/resources/settings/smtp-api/
|
||||
|
||||
@@ -3,11 +3,11 @@ from django.contrib import admin
|
||||
|
||||
from allianceauth import hooks
|
||||
from allianceauth.authentication.admin import (
|
||||
MainAllianceFilter,
|
||||
MainCorporationsFilter,
|
||||
user_main_organization,
|
||||
user_profile_pic,
|
||||
user_username,
|
||||
user_main_organization,
|
||||
MainCorporationsFilter,
|
||||
MainAllianceFilter
|
||||
)
|
||||
|
||||
from .models import NameFormatConfig
|
||||
@@ -36,19 +36,18 @@ class ServicesUserAdmin(admin.ModelAdmin):
|
||||
MainAllianceFilter,
|
||||
'user__date_joined',
|
||||
)
|
||||
list_select_related = (
|
||||
'user', 'user__profile__main_character', 'user__profile__state'
|
||||
)
|
||||
|
||||
@admin.display(ordering='user__profile__state__name')
|
||||
def _state(self, obj):
|
||||
return obj.user.profile.state.name
|
||||
|
||||
_state.short_description = 'state'
|
||||
_state.admin_order_field = 'user__profile__state__name'
|
||||
|
||||
@admin.display(ordering='user__date_joined')
|
||||
def _date_joined(self, obj):
|
||||
return obj.user.date_joined
|
||||
|
||||
_date_joined.short_description = 'date joined'
|
||||
_date_joined.admin_order_field = 'user__date_joined'
|
||||
|
||||
|
||||
class NameFormatConfigForm(forms.ModelForm):
|
||||
def __init__(self, *args, **kwargs):
|
||||
@@ -62,6 +61,7 @@ class NameFormatConfigForm(forms.ModelForm):
|
||||
self.fields['service_name'] = forms.ChoiceField(choices=SERVICE_CHOICES)
|
||||
|
||||
|
||||
@admin.register(NameFormatConfig)
|
||||
class NameFormatConfigAdmin(admin.ModelAdmin):
|
||||
form = NameFormatConfigForm
|
||||
list_display = ('service_name', 'get_state_display_string')
|
||||
@@ -69,6 +69,3 @@ class NameFormatConfigAdmin(admin.ModelAdmin):
|
||||
def get_state_display_string(self, obj):
|
||||
return ', '.join([state.name for state in obj.states.all()])
|
||||
get_state_display_string.short_description = 'States'
|
||||
|
||||
|
||||
admin.site.register(NameFormatConfig, NameFormatConfigAdmin)
|
||||
|
||||
@@ -2,12 +2,11 @@ import logging
|
||||
|
||||
from django.contrib import admin
|
||||
|
||||
from . import __title__
|
||||
from ...admin import ServicesUserAdmin
|
||||
from . import __title__
|
||||
from .models import DiscordUser
|
||||
from .utils import LoggerAddTag
|
||||
|
||||
|
||||
logger = LoggerAddTag(logging.getLogger(__name__), __title__)
|
||||
|
||||
|
||||
@@ -18,21 +17,16 @@ class DiscordUserAdmin(ServicesUserAdmin):
|
||||
list_filter = ServicesUserAdmin.list_filter + ('activated',)
|
||||
ordering = ('-activated',)
|
||||
|
||||
def _uid(self, obj):
|
||||
return obj.uid
|
||||
|
||||
_uid.short_description = 'Discord ID (UID)'
|
||||
_uid.admin_order_field = 'uid'
|
||||
|
||||
def _username(self, obj):
|
||||
if obj.username and obj.discriminator:
|
||||
return f'{obj.username}#{obj.discriminator}'
|
||||
else:
|
||||
return ''
|
||||
|
||||
def delete_queryset(self, request, queryset):
|
||||
for user in queryset:
|
||||
user.delete_user()
|
||||
|
||||
_username.short_description = 'Discord Username'
|
||||
_username.admin_order_field = 'username'
|
||||
@admin.display(description='Discord ID (UID)', ordering='uid')
|
||||
def _uid(self, obj):
|
||||
return obj.uid
|
||||
|
||||
@admin.display(description='Discord Username', ordering='username')
|
||||
def _username(self, obj):
|
||||
if obj.username and obj.discriminator:
|
||||
return f'{obj.username}#{obj.discriminator}'
|
||||
return ''
|
||||
|
||||
37
allianceauth/services/modules/discord/api.py
Normal file
37
allianceauth/services/modules/discord/api.py
Normal file
@@ -0,0 +1,37 @@
|
||||
"""Public interface for community apps who want to interact with the Discord server
|
||||
of the current Alliance Auth instance.
|
||||
|
||||
Example
|
||||
=======
|
||||
|
||||
Here is an example for using the api to fetch the current roles from the configured Discord server.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from allianceauth.services.modules.discord.api import create_bot_client, discord_guild_id
|
||||
|
||||
client = create_bot_client() # create a new Discord client
|
||||
guild_id = discord_guild_id() # get the ID of the configured Discord server
|
||||
roles = client.guild_roles(guild_id) # fetch the roles from our Discord server
|
||||
|
||||
.. seealso::
|
||||
The docs for the client class can be found here: :py:class:`~allianceauth.services.modules.discord.discord_client.client.DiscordClient`
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from .app_settings import DISCORD_GUILD_ID
|
||||
from .core import create_bot_client, group_to_role, server_name # noqa
|
||||
from .discord_client.models import Role # noqa
|
||||
from .models import DiscordUser # noqa
|
||||
|
||||
__all__ = ["create_bot_client", "group_to_role", "server_name", "DiscordUser", "Role"]
|
||||
|
||||
|
||||
def discord_guild_id() -> Optional[int]:
|
||||
"""Guild ID of configured Discord server.
|
||||
|
||||
Returns:
|
||||
Guild ID or ``None`` if not configured
|
||||
"""
|
||||
return int(DISCORD_GUILD_ID) if DISCORD_GUILD_ID else None
|
||||
@@ -2,16 +2,25 @@ from .utils import clean_setting
|
||||
|
||||
|
||||
DISCORD_APP_ID = clean_setting('DISCORD_APP_ID', '')
|
||||
"""App ID for the AA bot on Discord. Needs to be set."""
|
||||
|
||||
DISCORD_APP_SECRET = clean_setting('DISCORD_APP_SECRET', '')
|
||||
"""App secret for the AA bot on Discord. Needs to be set."""
|
||||
|
||||
DISCORD_BOT_TOKEN = clean_setting('DISCORD_BOT_TOKEN', '')
|
||||
"""Token used by the AA bot on Discord. Needs to be set."""
|
||||
|
||||
DISCORD_CALLBACK_URL = clean_setting('DISCORD_CALLBACK_URL', '')
|
||||
"""Callback URL for OAuth with Discord. Needs to be set."""
|
||||
|
||||
DISCORD_GUILD_ID = clean_setting('DISCORD_GUILD_ID', '')
|
||||
"""ID of the Discord Server. Needs to be set."""
|
||||
|
||||
# max retries of tasks after an error occurred
|
||||
DISCORD_TASKS_MAX_RETRIES = clean_setting('DISCORD_TASKS_MAX_RETRIES', 3)
|
||||
"""Max retries of tasks after an error occurred."""
|
||||
|
||||
# Pause in seconds until next retry for tasks after the API returned an error
|
||||
DISCORD_TASKS_RETRY_PAUSE = clean_setting('DISCORD_TASKS_RETRY_PAUSE', 60)
|
||||
"""Pause in seconds until next retry for tasks after the API returned an error."""
|
||||
|
||||
# automatically sync Discord users names to user's main character name when created
|
||||
DISCORD_SYNC_NAMES = clean_setting('DISCORD_SYNC_NAMES', False)
|
||||
"""Automatically sync Discord users names to user's main character name when created."""
|
||||
|
||||
@@ -6,6 +6,7 @@ from django.template.loader import render_to_string
|
||||
from allianceauth import hooks
|
||||
from allianceauth.services.hooks import ServicesHook
|
||||
|
||||
from .core import server_name, user_formatted_nick
|
||||
from .models import DiscordUser
|
||||
from .urls import urlpatterns
|
||||
from .utils import LoggerAddTag
|
||||
@@ -53,7 +54,7 @@ class DiscordService(ServicesHook):
|
||||
return render_to_string(
|
||||
self.service_ctrl_template,
|
||||
{
|
||||
'server_name': DiscordUser.objects.server_name(),
|
||||
'server_name': server_name(),
|
||||
'user_has_account': user_has_account,
|
||||
'discord_username': discord_username
|
||||
},
|
||||
@@ -73,7 +74,7 @@ class DiscordService(ServicesHook):
|
||||
'user_pk': user.pk,
|
||||
# since the new nickname is not yet in the DB we need to
|
||||
# provide it manually to the task
|
||||
'nickname': DiscordUser.objects.user_formatted_nick(user)
|
||||
'nickname': user_formatted_nick(user)
|
||||
},
|
||||
priority=SINGLE_TASK_PRIORITY
|
||||
)
|
||||
|
||||
129
allianceauth/services/modules/discord/core.py
Normal file
129
allianceauth/services/modules/discord/core.py
Normal file
@@ -0,0 +1,129 @@
|
||||
"""Core functionality of the Discord service not directly related to models."""
|
||||
|
||||
import logging
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
from requests.exceptions import HTTPError
|
||||
|
||||
from django.contrib.auth.models import Group, User
|
||||
|
||||
from allianceauth.groupmanagement.models import ReservedGroupName
|
||||
from allianceauth.services.hooks import NameFormatter
|
||||
|
||||
from . import __title__
|
||||
from .app_settings import DISCORD_BOT_TOKEN, DISCORD_GUILD_ID
|
||||
from .discord_client import DiscordClient, RolesSet, Role
|
||||
from .discord_client.exceptions import DiscordClientException
|
||||
from .utils import LoggerAddTag
|
||||
|
||||
logger = LoggerAddTag(logging.getLogger(__name__), __title__)
|
||||
|
||||
|
||||
def create_bot_client(is_rate_limited: bool = True) -> DiscordClient:
|
||||
"""Create new bot client for accessing the configured Discord server.
|
||||
|
||||
Args:
|
||||
is_rate_limited: Set to False to turn off rate limiting (use with care).
|
||||
|
||||
Return:
|
||||
Discord client instance
|
||||
"""
|
||||
return DiscordClient(DISCORD_BOT_TOKEN, is_rate_limited=is_rate_limited)
|
||||
|
||||
|
||||
def calculate_roles_for_user(
|
||||
user: User,
|
||||
client: DiscordClient,
|
||||
discord_uid: int,
|
||||
state_name: str = None,
|
||||
) -> Tuple[RolesSet, Optional[bool]]:
|
||||
"""Calculate current Discord roles for an Auth user.
|
||||
|
||||
Takes into account reserved groups and existing managed roles (e.g. nitro).
|
||||
|
||||
Returns:
|
||||
- Discord roles, changed flag:
|
||||
- True when roles have changed,
|
||||
- False when they have not changed,
|
||||
- None if user is not a member of the guild
|
||||
"""
|
||||
roles_calculated = client.match_or_create_roles_from_names_2(
|
||||
guild_id=DISCORD_GUILD_ID,
|
||||
role_names=_user_group_names(user=user, state_name=state_name),
|
||||
)
|
||||
logger.debug("Calculated roles for user %s: %s", user, roles_calculated.ids())
|
||||
roles_current = client.guild_member_roles(
|
||||
guild_id=DISCORD_GUILD_ID, user_id=discord_uid
|
||||
)
|
||||
if roles_current is None:
|
||||
logger.debug("User %s is not a member of the guild.", user)
|
||||
return roles_calculated, None
|
||||
logger.debug("Current roles user %s: %s", user, roles_current.ids())
|
||||
reserved_role_names = ReservedGroupName.objects.values_list("name", flat=True)
|
||||
roles_reserved = roles_current.subset(role_names=reserved_role_names)
|
||||
roles_managed = roles_current.subset(managed_only=True)
|
||||
roles_persistent = roles_managed.union(roles_reserved)
|
||||
if roles_calculated == roles_current.difference(roles_persistent):
|
||||
return roles_calculated, False
|
||||
return roles_calculated.union(roles_persistent), True
|
||||
|
||||
|
||||
def _user_group_names(user: User, state_name: str = None) -> List[str]:
|
||||
"""Names of groups and state the given user is a member of."""
|
||||
if not state_name:
|
||||
state_name = user.profile.state.name
|
||||
group_names = [group.name for group in user.groups.all()] + [state_name]
|
||||
logger.debug("Group names for roles updates of user %s are: %s", user, group_names)
|
||||
return group_names
|
||||
|
||||
|
||||
def user_formatted_nick(user: User) -> Optional[str]:
|
||||
"""Name of the given user's main character with name formatting applied.
|
||||
|
||||
Returns:
|
||||
Name or ``None`` if user has no main.
|
||||
"""
|
||||
from .auth_hooks import DiscordService
|
||||
|
||||
if user.profile.main_character:
|
||||
return NameFormatter(DiscordService(), user).format_name()
|
||||
return None
|
||||
|
||||
|
||||
def group_to_role(group: Group) -> Optional[Role]:
|
||||
"""Fetch the Discord role matching the given Django group by name.
|
||||
|
||||
Returns:
|
||||
Discord role or None if no matching role exist
|
||||
"""
|
||||
return default_bot_client.match_role_from_name(
|
||||
guild_id=DISCORD_GUILD_ID, role_name=group.name
|
||||
)
|
||||
|
||||
|
||||
def server_name(use_cache: bool = True) -> str:
|
||||
"""Fetches the name of the current Discord server.
|
||||
|
||||
Args:
|
||||
use_cache: When set False will force an API call to get the server name
|
||||
|
||||
Returns:
|
||||
Server name or an empty string if the name could not be retrieved
|
||||
"""
|
||||
try:
|
||||
server_name = default_bot_client.guild_name(
|
||||
guild_id=DISCORD_GUILD_ID, use_cache=use_cache
|
||||
)
|
||||
except (HTTPError, DiscordClientException):
|
||||
server_name = ""
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"Unexpected error when trying to retrieve the server name from Discord",
|
||||
exc_info=True,
|
||||
)
|
||||
server_name = ""
|
||||
return server_name
|
||||
|
||||
|
||||
# Default bot client to be used by modules of this package
|
||||
default_bot_client = create_bot_client()
|
||||
@@ -1,3 +1,10 @@
|
||||
from .client import DiscordClient # noqa
|
||||
from .exceptions import DiscordApiBackoff # noqa
|
||||
from .helpers import DiscordRoles # noqa
|
||||
from .app_settings import DISCORD_OAUTH_BASE_URL, DISCORD_OAUTH_TOKEN_URL # noqa
|
||||
from .client import DiscordClient # noqa
|
||||
from .exceptions import ( # noqa
|
||||
DiscordApiBackoff,
|
||||
DiscordClientException,
|
||||
DiscordRateLimitExhausted,
|
||||
DiscordTooManyRequestsError,
|
||||
)
|
||||
from .helpers import RolesSet # noqa
|
||||
from .models import Guild, GuildMember, Role, User # noqa
|
||||
|
||||
@@ -1,45 +1,56 @@
|
||||
"""Settings for the Discord client.
|
||||
|
||||
To overwrite a default set the variable in your local Django settings, e.g:
|
||||
|
||||
.. code:: python
|
||||
|
||||
DISCORD_GUILD_NAME_CACHE_MAX_AGE = 7200
|
||||
"""
|
||||
|
||||
from ..utils import clean_setting
|
||||
|
||||
|
||||
# Base URL for all API calls. Must end with /.
|
||||
DISCORD_API_BASE_URL = clean_setting(
|
||||
'DISCORD_API_BASE_URL', 'https://discord.com/api/'
|
||||
)
|
||||
"""Base URL for all API calls. Must end with /."""
|
||||
|
||||
# Low level connecttimeout for requests to the Discord API in seconds
|
||||
DISCORD_API_TIMEOUT_CONNECT = clean_setting(
|
||||
'DISCORD_API_TIMEOUT', 5
|
||||
)
|
||||
"""Low level connect timeout for requests to the Discord API in seconds."""
|
||||
|
||||
# Low level read timeout for requests to the Discord API in seconds
|
||||
DISCORD_API_TIMEOUT_READ = clean_setting(
|
||||
'DISCORD_API_TIMEOUT', 30
|
||||
)
|
||||
"""Low level read timeout for requests to the Discord API in seconds."""
|
||||
|
||||
# Base authorization URL for Discord Oauth
|
||||
DISCORD_OAUTH_BASE_URL = clean_setting(
|
||||
'DISCORD_OAUTH_BASE_URL', 'https://discord.com/api/oauth2/authorize'
|
||||
)
|
||||
"""Base authorization URL for Discord Oauth."""
|
||||
|
||||
# Base authorization URL for Discord Oauth
|
||||
DISCORD_OAUTH_TOKEN_URL = clean_setting(
|
||||
'DISCORD_OAUTH_TOKEN_URL', 'https://discord.com/api/oauth2/token'
|
||||
)
|
||||
"""Base authorization URL for Discord Oauth."""
|
||||
|
||||
# How long the Discord guild names retrieved from the server are
|
||||
# caches locally in seconds.
|
||||
DISCORD_GUILD_NAME_CACHE_MAX_AGE = clean_setting(
|
||||
'DISCORD_GUILD_NAME_CACHE_MAX_AGE', 3600 * 24
|
||||
)
|
||||
"""How long the Discord guild names retrieved from the server
|
||||
are caches locally in seconds.
|
||||
"""
|
||||
|
||||
# How long Discord roles retrieved from the server are caches locally in seconds.
|
||||
DISCORD_ROLES_CACHE_MAX_AGE = clean_setting(
|
||||
'DISCORD_ROLES_CACHE_MAX_AGE', 3600 * 1
|
||||
)
|
||||
"""How long Discord roles retrieved from the server are caches locally in seconds."""
|
||||
|
||||
# Turns off creation of new roles. In case the rate limit for creating roles is
|
||||
# exhausted, this setting allows the Discord service to continue to function
|
||||
# and wait out the reset. Rate limit is about 250 per 48 hrs.
|
||||
DISCORD_DISABLE_ROLE_CREATION = clean_setting(
|
||||
'DISCORD_DISABLE_ROLE_CREATION', False
|
||||
)
|
||||
"""Turns off creation of new roles. In case the rate limit for creating roles is
|
||||
exhausted, this setting allows the Discord service to continue to function
|
||||
and wait out the reset. Rate limit is about 250 per 48 hrs.
|
||||
"""
|
||||
|
||||
@@ -1,32 +1,37 @@
|
||||
from hashlib import md5
|
||||
"""Client for interacting with the Discord API."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from enum import IntEnum
|
||||
from hashlib import md5
|
||||
from http import HTTPStatus
|
||||
from time import sleep
|
||||
from typing import Iterable, List, Optional, Set, Tuple
|
||||
from urllib.parse import urljoin
|
||||
from uuid import uuid1
|
||||
|
||||
from redis import Redis
|
||||
import requests
|
||||
from requests.exceptions import HTTPError
|
||||
from redis import Redis
|
||||
|
||||
from allianceauth.utils.cache import get_redis_client
|
||||
|
||||
from allianceauth import __title__ as AUTH_TITLE, __url__, __version__
|
||||
from allianceauth import __title__ as AUTH_TITLE
|
||||
from allianceauth import __url__, __version__
|
||||
|
||||
from .. import __title__
|
||||
from ..utils import LoggerAddTag
|
||||
from .app_settings import (
|
||||
DISCORD_API_BASE_URL,
|
||||
DISCORD_API_TIMEOUT_CONNECT,
|
||||
DISCORD_API_TIMEOUT_READ,
|
||||
DISCORD_DISABLE_ROLE_CREATION,
|
||||
DISCORD_GUILD_NAME_CACHE_MAX_AGE,
|
||||
DISCORD_OAUTH_BASE_URL,
|
||||
DISCORD_OAUTH_TOKEN_URL,
|
||||
DISCORD_ROLES_CACHE_MAX_AGE,
|
||||
)
|
||||
from .exceptions import DiscordRateLimitExhausted, DiscordTooManyRequestsError
|
||||
from .helpers import DiscordRoles
|
||||
from ..utils import LoggerAddTag
|
||||
|
||||
from .helpers import RolesSet
|
||||
from .models import Guild, GuildMember, Role, User
|
||||
|
||||
logger = LoggerAddTag(logging.getLogger(__name__), __title__)
|
||||
|
||||
@@ -58,8 +63,13 @@ MINIMUM_BLOCKING_WAIT = 50
|
||||
RATE_LIMIT_RETRIES = 1000
|
||||
|
||||
|
||||
class DiscordApiStatusCode(IntEnum):
|
||||
"""Status code returned from the Discord API."""
|
||||
UNKNOWN_MEMBER = 10007 #:
|
||||
|
||||
|
||||
class DiscordClient:
|
||||
"""This class provides a web client for interacting with the Discord API
|
||||
"""This class provides a web client for interacting with the Discord API.
|
||||
|
||||
The client has rate limiting that supports concurrency.
|
||||
This means it is able to ensure the API rate limit is not violated,
|
||||
@@ -67,24 +77,30 @@ class DiscordClient:
|
||||
|
||||
In addition the client support proper API backoff.
|
||||
|
||||
Synchronization of rate limit infos accross multiple processes
|
||||
Synchronization of rate limit infos across multiple processes
|
||||
is implemented with Redis and thus requires Redis as Django cache backend.
|
||||
|
||||
All durations are in milliseconds.
|
||||
"""
|
||||
OAUTH_BASE_URL = DISCORD_OAUTH_BASE_URL
|
||||
OAUTH_TOKEN_URL = DISCORD_OAUTH_TOKEN_URL
|
||||
The cache is shared across all clients and processes (also using Redis).
|
||||
|
||||
All durations are in milliseconds.
|
||||
|
||||
Most errors from the API will raise a requests.HTTPError.
|
||||
|
||||
Args:
|
||||
access_token: Discord access token used to authenticate all calls to the API
|
||||
redis: Redis instance to be used.
|
||||
is_rate_limited: Set to False to turn off rate limiting (use with care).
|
||||
If not specified will try to use the Redis instance
|
||||
from the default Django cache backend.
|
||||
|
||||
Raises:
|
||||
ValueError: No access token provided
|
||||
"""
|
||||
_KEY_GLOBAL_BACKOFF_UNTIL = 'DISCORD_GLOBAL_BACKOFF_UNTIL'
|
||||
_KEY_GLOBAL_RATE_LIMIT_REMAINING = 'DISCORD_GLOBAL_RATE_LIMIT_REMAINING'
|
||||
_KEYPREFIX_GUILD_NAME = 'DISCORD_GUILD_NAME'
|
||||
_KEYPREFIX_GUILD_ROLES = 'DISCORD_GUILD_ROLES'
|
||||
_KEYPREFIX_ROLE_NAME = 'DISCORD_ROLE_NAME'
|
||||
_NICK_MAX_CHARS = 32
|
||||
|
||||
_HTTP_STATUS_CODE_NOT_FOUND = 404
|
||||
_HTTP_STATUS_CODE_RATE_LIMITED = 429
|
||||
_DISCORD_STATUS_CODE_UNKNOWN_MEMBER = 10007
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -92,14 +108,8 @@ class DiscordClient:
|
||||
redis: Redis = None,
|
||||
is_rate_limited: bool = True
|
||||
) -> None:
|
||||
"""
|
||||
Params:
|
||||
- access_token: Discord access token used to authenticate all calls to the API
|
||||
- redis: Redis instance to be used.
|
||||
- is_rate_limited: Set to False to run of rate limiting (use with care)
|
||||
If not specified will try to use the Redis instance
|
||||
from the default Django cache backend.
|
||||
"""
|
||||
if not access_token:
|
||||
raise ValueError('You must provide an access token.')
|
||||
self._access_token = str(access_token)
|
||||
self._is_rate_limited = bool(is_rate_limited)
|
||||
if not redis:
|
||||
@@ -131,19 +141,20 @@ class DiscordClient:
|
||||
self.__redis_script_set_longer = self._redis.register_script(lua_2)
|
||||
|
||||
@property
|
||||
def access_token(self):
|
||||
def access_token(self) -> str:
|
||||
"""Discord access token."""
|
||||
return self._access_token
|
||||
|
||||
@property
|
||||
def is_rate_limited(self):
|
||||
def is_rate_limited(self) -> bool:
|
||||
"""Wether this instance is rate limited."""
|
||||
return self._is_rate_limited
|
||||
|
||||
def __repr__(self):
|
||||
return f'{type(self).__name__}(access_token=...{self.access_token[-5:]})'
|
||||
|
||||
def _redis_decr_or_set(self, name: str, value: str, px: int) -> bool:
|
||||
"""decreases the key value if it exists and returns the result
|
||||
else sets the key
|
||||
"""Decrease the key value if it exists and returns the result else set the key.
|
||||
|
||||
Implemented as Lua script to ensure atomicity.
|
||||
"""
|
||||
@@ -152,7 +163,7 @@ class DiscordClient:
|
||||
)
|
||||
|
||||
def _redis_set_if_longer(self, name: str, value: str, px: int) -> bool:
|
||||
"""like set, but only goes through if either key doesn't exist
|
||||
"""Like set, but only goes through if either key doesn't exist
|
||||
or px would be extended.
|
||||
|
||||
Implemented as Lua script to ensure atomicity.
|
||||
@@ -163,111 +174,134 @@ class DiscordClient:
|
||||
|
||||
# users
|
||||
|
||||
def current_user(self) -> dict:
|
||||
"""returns the user belonging to the current access_token"""
|
||||
def current_user(self) -> User:
|
||||
"""Fetch user belonging to the current access_token."""
|
||||
authorization = f'Bearer {self.access_token}'
|
||||
r = self._api_request(
|
||||
method='get', route='users/@me', authorization=authorization
|
||||
)
|
||||
return r.json()
|
||||
return User.from_dict(r.json())
|
||||
|
||||
# guild
|
||||
|
||||
def guild_infos(self, guild_id: int) -> dict:
|
||||
"""Returns all basic infos about this guild"""
|
||||
def guild_infos(self, guild_id: int) -> Guild:
|
||||
"""Fetch all basic infos about this guild.
|
||||
|
||||
Args:
|
||||
guild_id: Discord ID of the guild
|
||||
"""
|
||||
route = f"guilds/{guild_id}"
|
||||
r = self._api_request(method='get', route=route)
|
||||
return r.json()
|
||||
return Guild.from_dict(r.json())
|
||||
|
||||
def guild_name(self, guild_id: int, use_cache: bool = True) -> str:
|
||||
"""returns the name of this guild (cached)
|
||||
or an empty string if something went wrong
|
||||
"""Fetch the name of this guild (cached).
|
||||
|
||||
Params:
|
||||
- guild_id: ID of current guild
|
||||
- use_cache: When set to False will force an API call to get the server name
|
||||
Args:
|
||||
guild_id: Discord ID of the guild
|
||||
use_cache: When set to False will force an API call to get the server name
|
||||
|
||||
Returns:
|
||||
Name of the server or an empty string if something went wrong.
|
||||
"""
|
||||
key_name = self._guild_name_cache_key(guild_id)
|
||||
if use_cache:
|
||||
guild_name = self._redis_decode(self._redis.get(key_name))
|
||||
else:
|
||||
guild_name = None
|
||||
guild_name = ""
|
||||
if not guild_name:
|
||||
guild_infos = self.guild_infos(guild_id)
|
||||
if 'name' in guild_infos:
|
||||
guild_name = guild_infos['name']
|
||||
self._redis.set(
|
||||
name=key_name,
|
||||
value=guild_name,
|
||||
ex=DISCORD_GUILD_NAME_CACHE_MAX_AGE
|
||||
)
|
||||
try:
|
||||
guild = self.guild_infos(guild_id)
|
||||
except HTTPError:
|
||||
guild_name = ""
|
||||
else:
|
||||
guild_name = ''
|
||||
|
||||
guild_name = guild.name
|
||||
self._redis.set(
|
||||
name=key_name, value=guild_name, ex=DISCORD_GUILD_NAME_CACHE_MAX_AGE
|
||||
)
|
||||
return guild_name
|
||||
|
||||
@classmethod
|
||||
def _guild_name_cache_key(cls, guild_id: int) -> str:
|
||||
"""Returns key for accessing role given by name in the role cache"""
|
||||
"""Construct key for accessing role given by name in the role cache.
|
||||
|
||||
Args:
|
||||
guild_id: Discord ID of the guild
|
||||
"""
|
||||
gen_key = DiscordClient._generate_hash(f'{guild_id}')
|
||||
return f'{cls._KEYPREFIX_GUILD_NAME}__{gen_key}'
|
||||
|
||||
# guild roles
|
||||
|
||||
def guild_roles(self, guild_id: int, use_cache: bool = True) -> list:
|
||||
"""Returns the list of all roles for this guild
|
||||
def guild_roles(self, guild_id: int, use_cache: bool = True) -> Set[Role]:
|
||||
"""Fetch all roles for this guild.
|
||||
|
||||
If use_cache is set to False it will always hit the API to retrieve
|
||||
fresh data and update the cache
|
||||
Args:
|
||||
guild_id: Discord ID of the guild
|
||||
use_cache: If is set to False it will always hit the API to retrieve
|
||||
fresh data and update the cache.
|
||||
|
||||
Returns:
|
||||
"""
|
||||
cache_key = self._guild_roles_cache_key(guild_id)
|
||||
roles = None
|
||||
if use_cache:
|
||||
roles_raw = self._redis.get(name=cache_key)
|
||||
if roles_raw:
|
||||
logger.debug('Returning roles for guild %s from cache', guild_id)
|
||||
return json.loads(self._redis_decode(roles_raw))
|
||||
else:
|
||||
logger.debug('No roles for guild %s in cache', guild_id)
|
||||
|
||||
route = f"guilds/{guild_id}/roles"
|
||||
r = self._api_request(method='get', route=route)
|
||||
roles = r.json()
|
||||
if roles and isinstance(roles, list):
|
||||
roles = json.loads(self._redis_decode(roles_raw))
|
||||
logger.debug('No roles for guild %s in cache', guild_id)
|
||||
if roles is None:
|
||||
route = f"guilds/{guild_id}/roles"
|
||||
r = self._api_request(method='get', route=route)
|
||||
roles = r.json()
|
||||
if not roles or not isinstance(roles, list):
|
||||
raise RuntimeError(
|
||||
f"Unexpected response when fetching roles from API: {roles}"
|
||||
)
|
||||
self._redis.set(
|
||||
name=cache_key,
|
||||
value=json.dumps(roles),
|
||||
ex=DISCORD_ROLES_CACHE_MAX_AGE
|
||||
)
|
||||
return roles
|
||||
return {Role.from_dict(role) for role in roles}
|
||||
|
||||
def create_guild_role(self, guild_id: int, role_name: str, **kwargs) -> dict:
|
||||
def create_guild_role(
|
||||
self, guild_id: int, role_name: str, **kwargs
|
||||
) -> Optional[Role]:
|
||||
"""Create a new guild role with the given name.
|
||||
|
||||
See official documentation for additional optional parameters.
|
||||
|
||||
Note that Discord allows the creation of multiple roles with the same name,
|
||||
so to avoid duplicates it's important to check existing roles
|
||||
before creating new one
|
||||
|
||||
returns a new role dict on success
|
||||
Args:
|
||||
guild_id: Discord ID of the guild
|
||||
role_name: Name of new role to create
|
||||
|
||||
Returns:
|
||||
new role on success
|
||||
"""
|
||||
route = f"guilds/{guild_id}/roles"
|
||||
data = {'name': DiscordRoles.sanitize_role_name(role_name)}
|
||||
data = {'name': Role.sanitize_name(role_name)}
|
||||
data.update(kwargs)
|
||||
r = self._api_request(method='post', route=route, data=data)
|
||||
role = r.json()
|
||||
if role:
|
||||
self._invalidate_guild_roles_cache(guild_id)
|
||||
return role
|
||||
return Role.from_dict(role)
|
||||
return None
|
||||
|
||||
def delete_guild_role(self, guild_id: int, role_id: int) -> bool:
|
||||
"""Deletes a guild role"""
|
||||
"""Delete a guild role."""
|
||||
route = f"guilds/{guild_id}/roles/{role_id}"
|
||||
r = self._api_request(method='delete', route=route)
|
||||
if r.status_code == 204:
|
||||
self._invalidate_guild_roles_cache(guild_id)
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
return False
|
||||
|
||||
def _invalidate_guild_roles_cache(self, guild_id: int) -> None:
|
||||
cache_key = self._guild_roles_cache_key(guild_id)
|
||||
@@ -276,67 +310,79 @@ class DiscordClient:
|
||||
|
||||
@classmethod
|
||||
def _guild_roles_cache_key(cls, guild_id: int) -> str:
|
||||
"""Returns key for accessing cached roles for a guild"""
|
||||
"""Construct key for accessing cached roles for a guild.
|
||||
|
||||
Args:
|
||||
guild_id: Discord ID of the guild
|
||||
"""
|
||||
gen_key = cls._generate_hash(f'{guild_id}')
|
||||
return f'{cls._KEYPREFIX_GUILD_ROLES}__{gen_key}'
|
||||
|
||||
def match_role_from_name(self, guild_id: int, role_name: str) -> dict:
|
||||
"""returns Discord role matching the given name or an empty dict"""
|
||||
guild_roles = DiscordRoles(self.guild_roles(guild_id))
|
||||
def match_role_from_name(self, guild_id: int, role_name: str) -> Optional[Role]:
|
||||
"""Fetch Discord role matching the given name (cached).
|
||||
|
||||
Args:
|
||||
guild_id: Discord ID of the guild
|
||||
role_name: Name of role
|
||||
|
||||
Returns:
|
||||
Matching role or None if no match is found
|
||||
"""
|
||||
guild_roles = RolesSet(self.guild_roles(guild_id))
|
||||
return guild_roles.role_by_name(role_name)
|
||||
|
||||
def match_or_create_roles_from_names(self, guild_id: int, role_names: list) -> list:
|
||||
"""returns Discord roles matching the given names
|
||||
|
||||
Returns as list of tuple of role and created flag
|
||||
def match_or_create_roles_from_names(
|
||||
self, guild_id: int, role_names: Iterable[str]
|
||||
) -> List[Tuple[Role, bool]]:
|
||||
"""Fetch or create Discord roles matching the given names (cached).
|
||||
|
||||
Will try to match with existing roles names
|
||||
Non-existing roles will be created, then created flag will be True
|
||||
|
||||
Params:
|
||||
- guild_id: ID of guild
|
||||
- role_names: list of name strings each defining a role
|
||||
Args:
|
||||
guild_id: ID of guild
|
||||
role_names: list of name strings each defining a role
|
||||
|
||||
Returns:
|
||||
List of tuple of Role and created flag
|
||||
"""
|
||||
roles = list()
|
||||
guild_roles = DiscordRoles(self.guild_roles(guild_id))
|
||||
role_names_cleaned = {
|
||||
DiscordRoles.sanitize_role_name(name) for name in role_names
|
||||
}
|
||||
guild_roles = RolesSet(self.guild_roles(guild_id))
|
||||
role_names_cleaned = {Role.sanitize_name(name) for name in role_names}
|
||||
for role_name in role_names_cleaned:
|
||||
role, created = self.match_or_create_role_from_name(
|
||||
guild_id=guild_id,
|
||||
role_name=DiscordRoles.sanitize_role_name(role_name),
|
||||
guild_roles=guild_roles
|
||||
guild_id=guild_id, role_name=role_name, guild_roles=guild_roles
|
||||
)
|
||||
if role:
|
||||
roles.append((role, created))
|
||||
if created:
|
||||
guild_roles = guild_roles.union(DiscordRoles([role]))
|
||||
guild_roles = guild_roles.union(RolesSet([role]))
|
||||
return roles
|
||||
|
||||
def match_or_create_role_from_name(
|
||||
self, guild_id: int, role_name: str, guild_roles: DiscordRoles = None
|
||||
) -> tuple:
|
||||
"""returns Discord role matching the given name
|
||||
|
||||
Returns as tuple of role and created flag
|
||||
self, guild_id: int, role_name: str, guild_roles: RolesSet = None
|
||||
) -> Tuple[Role, bool]:
|
||||
"""Fetch or create Discord role matching the given name.
|
||||
|
||||
Will try to match with existing roles names
|
||||
Non-existing roles will be created, then created flag will be True
|
||||
|
||||
Params:
|
||||
- guild_id: ID of guild
|
||||
- role_name: strings defining name of a role
|
||||
- guild_roles: All known guild roles as DiscordRoles object.
|
||||
Helps to void redundant lookups of guild roles
|
||||
when this method is used multiple times.
|
||||
Args:
|
||||
guild_id: ID of guild
|
||||
role_name: strings defining name of a role
|
||||
guild_roles: All known guild roles as RolesSet object.
|
||||
Helps to void redundant lookups of guild roles
|
||||
when this method is used multiple times.
|
||||
|
||||
Returns:
|
||||
Tuple of Role and created flag
|
||||
"""
|
||||
if not isinstance(role_name, str):
|
||||
raise TypeError('role_name must be of type string')
|
||||
|
||||
created = False
|
||||
if guild_roles is None:
|
||||
guild_roles = DiscordRoles(self.guild_roles(guild_id))
|
||||
guild_roles = RolesSet(self.guild_roles(guild_id))
|
||||
role = guild_roles.role_by_name(role_name)
|
||||
if not role:
|
||||
if not DISCORD_DISABLE_ROLE_CREATION:
|
||||
@@ -345,9 +391,24 @@ class DiscordClient:
|
||||
created = True
|
||||
else:
|
||||
role = None
|
||||
|
||||
return role, created
|
||||
|
||||
def match_or_create_roles_from_names_2(
|
||||
self, guild_id: int, role_names: Iterable[str]
|
||||
) -> RolesSet:
|
||||
"""Fetch or create Discord role matching the given name.
|
||||
|
||||
Wrapper for ``match_or_create_role_from_name()``
|
||||
|
||||
Returns:
|
||||
Roles as RolesSet object.
|
||||
"""
|
||||
return RolesSet.create_from_matched_roles(
|
||||
self.match_or_create_roles_from_names(
|
||||
guild_id=guild_id, role_names=role_names
|
||||
)
|
||||
)
|
||||
|
||||
# guild members
|
||||
|
||||
def add_guild_member(
|
||||
@@ -357,13 +418,13 @@ class DiscordClient:
|
||||
access_token: str,
|
||||
role_ids: list = None,
|
||||
nick: str = None
|
||||
) -> bool:
|
||||
"""Adds a user to the guilds.
|
||||
) -> Optional[bool]:
|
||||
"""Adds a user to the guild.
|
||||
|
||||
Returns:
|
||||
- True when a new user was added
|
||||
- None if the user already existed
|
||||
- False when something went wrong or raises exception
|
||||
- True when a new user was added
|
||||
- None if the user already existed
|
||||
- False when something went wrong or raises exception
|
||||
"""
|
||||
route = f"guilds/{guild_id}/members/{user_id}"
|
||||
data = {
|
||||
@@ -371,42 +432,49 @@ class DiscordClient:
|
||||
}
|
||||
if role_ids:
|
||||
data['roles'] = self._sanitize_role_ids(role_ids)
|
||||
|
||||
if nick:
|
||||
data['nick'] = str(nick)[:self._NICK_MAX_CHARS]
|
||||
|
||||
data['nick'] = GuildMember.sanitize_nick(nick)
|
||||
r = self._api_request(method='put', route=route, data=data)
|
||||
r.raise_for_status()
|
||||
if r.status_code == 201:
|
||||
return True
|
||||
elif r.status_code == 204:
|
||||
return None
|
||||
else:
|
||||
return False
|
||||
return False
|
||||
|
||||
def guild_member(self, guild_id: int, user_id: int) -> dict:
|
||||
"""returns the user info for a guild member
|
||||
def guild_member(self, guild_id: int, user_id: int) -> Optional[GuildMember]:
|
||||
"""Fetch info for a guild member.
|
||||
|
||||
or None if the user is not a member of the guild
|
||||
Args:
|
||||
guild_id: Discord ID of the guild
|
||||
user_id: Discord ID of the user
|
||||
|
||||
Returns:
|
||||
guild member or ``None`` if the user is not a member of the guild
|
||||
"""
|
||||
route = f'guilds/{guild_id}/members/{user_id}'
|
||||
r = self._api_request(method='get', route=route, raise_for_status=False)
|
||||
if self._is_member_unknown_error(r):
|
||||
logger.warning("Discord user ID %s could not be found on server.", user_id)
|
||||
return None
|
||||
else:
|
||||
r.raise_for_status()
|
||||
return r.json()
|
||||
r.raise_for_status()
|
||||
return GuildMember.from_dict(r.json())
|
||||
|
||||
def modify_guild_member(
|
||||
self, guild_id: int, user_id: int, role_ids: list = None, nick: str = None
|
||||
) -> bool:
|
||||
"""Modify attributes of a guild member.
|
||||
self, guild_id: int, user_id: int, role_ids: List[int] = None, nick: str = None
|
||||
) -> Optional[bool]:
|
||||
"""Set properties of a guild member.
|
||||
|
||||
Args:
|
||||
guild_id: Discord ID of the guild
|
||||
user_id: Discord ID of the user
|
||||
roles_id: New list of role IDs (if provided)
|
||||
nick: New nickname (if provided)
|
||||
|
||||
Returns
|
||||
- True when successful
|
||||
- None if user is not a member of this guild
|
||||
- False otherwise
|
||||
- True when successful
|
||||
- None if user is not a member of this guild
|
||||
- False otherwise
|
||||
"""
|
||||
if not role_ids and not nick:
|
||||
raise ValueError('Must specify role_ids or nick')
|
||||
@@ -419,7 +487,7 @@ class DiscordClient:
|
||||
data['roles'] = self._sanitize_role_ids(role_ids)
|
||||
|
||||
if nick:
|
||||
data['nick'] = self._sanitize_nick(nick)
|
||||
data['nick'] = GuildMember.sanitize_nick(nick)
|
||||
|
||||
route = f"guilds/{guild_id}/members/{user_id}"
|
||||
r = self._api_request(
|
||||
@@ -428,21 +496,22 @@ class DiscordClient:
|
||||
if self._is_member_unknown_error(r):
|
||||
logger.warning('User ID %s is not a member of this guild', user_id)
|
||||
return None
|
||||
else:
|
||||
r.raise_for_status()
|
||||
|
||||
r.raise_for_status()
|
||||
if r.status_code == 204:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
return False
|
||||
|
||||
def remove_guild_member(self, guild_id: int, user_id: int) -> bool:
|
||||
"""Remove a member from a guild
|
||||
def remove_guild_member(self, guild_id: int, user_id: int) -> Optional[bool]:
|
||||
"""Remove a member from a guild.
|
||||
|
||||
Args:
|
||||
guild_id: Discord ID of the guild
|
||||
user_id: Discord ID of the user
|
||||
|
||||
Returns:
|
||||
- True when successful
|
||||
- None if member does not exist
|
||||
- False otherwise
|
||||
- True when successful
|
||||
- None if member does not exist
|
||||
- False otherwise
|
||||
"""
|
||||
route = f"guilds/{guild_id}/members/{user_id}"
|
||||
r = self._api_request(
|
||||
@@ -451,19 +520,16 @@ class DiscordClient:
|
||||
if self._is_member_unknown_error(r):
|
||||
logger.warning('User ID %s is not a member of this guild', user_id)
|
||||
return None
|
||||
else:
|
||||
r.raise_for_status()
|
||||
|
||||
r.raise_for_status()
|
||||
if r.status_code == 204:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
return False
|
||||
|
||||
# Guild member roles
|
||||
|
||||
def add_guild_member_role(
|
||||
self, guild_id: int, user_id: int, role_id: int
|
||||
) -> bool:
|
||||
) -> Optional[bool]:
|
||||
"""Adds a role to a guild member
|
||||
|
||||
Returns:
|
||||
@@ -476,43 +542,69 @@ class DiscordClient:
|
||||
if self._is_member_unknown_error(r):
|
||||
logger.warning('User ID %s is not a member of this guild', user_id)
|
||||
return None
|
||||
else:
|
||||
r.raise_for_status()
|
||||
|
||||
r.raise_for_status()
|
||||
if r.status_code == 204:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
return False
|
||||
|
||||
def remove_guild_member_role(
|
||||
self, guild_id: int, user_id: int, role_id: int
|
||||
) -> bool:
|
||||
"""Removes a role to a guild member
|
||||
) -> Optional[bool]:
|
||||
"""Remove a role to a guild member
|
||||
|
||||
Args:
|
||||
guild_id: Discord ID of the guild
|
||||
user_id: Discord ID of the user
|
||||
role_id: Discord ID of role to be removed
|
||||
|
||||
Returns:
|
||||
- True when successful
|
||||
- None if member does not exist
|
||||
- False otherwise
|
||||
- True when successful
|
||||
- None if member does not exist
|
||||
- False otherwise
|
||||
"""
|
||||
route = f"guilds/{guild_id}/members/{user_id}/roles/{role_id}"
|
||||
r = self._api_request(method='delete', route=route, raise_for_status=False)
|
||||
if self._is_member_unknown_error(r):
|
||||
logger.warning('User ID %s is not a member of this guild', user_id)
|
||||
return None
|
||||
else:
|
||||
r.raise_for_status()
|
||||
|
||||
r.raise_for_status()
|
||||
if r.status_code == 204:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
return False
|
||||
|
||||
def guild_member_roles(self, guild_id: int, user_id: int) -> Optional[RolesSet]:
|
||||
"""Fetch the current guild roles of a guild member.
|
||||
|
||||
Args:
|
||||
- guild_id: Discord guild ID
|
||||
- user_id: Discord user ID
|
||||
|
||||
Returns:
|
||||
- Member roles
|
||||
- None if user is not a member of the guild
|
||||
"""
|
||||
member_info = self.guild_member(guild_id=guild_id, user_id=user_id)
|
||||
if member_info is None:
|
||||
return None # User is no longer a member
|
||||
guild_roles = RolesSet(self.guild_roles(guild_id=guild_id))
|
||||
logger.debug('Current guild roles: %s', guild_roles.ids())
|
||||
if not guild_roles.has_roles(member_info.roles):
|
||||
guild_roles = RolesSet(
|
||||
self.guild_roles(guild_id=guild_id, use_cache=False)
|
||||
)
|
||||
if not guild_roles.has_roles(member_info.roles):
|
||||
role_ids = set(member_info.roles).difference(guild_roles.ids())
|
||||
raise RuntimeError(
|
||||
f'Discord user {user_id} has unknown roles: {role_ids}'
|
||||
)
|
||||
return guild_roles.subset(member_info.roles)
|
||||
|
||||
@classmethod
|
||||
def _is_member_unknown_error(cls, r: requests.Response) -> bool:
|
||||
try:
|
||||
result = (
|
||||
r.status_code == cls._HTTP_STATUS_CODE_NOT_FOUND
|
||||
and r.json()['code'] == cls._DISCORD_STATUS_CODE_UNKNOWN_MEMBER
|
||||
r.status_code == HTTPStatus.NOT_FOUND
|
||||
and r.json()['code'] == DiscordApiStatusCode.UNKNOWN_MEMBER
|
||||
)
|
||||
except (ValueError, KeyError):
|
||||
result = False
|
||||
@@ -529,7 +621,19 @@ class DiscordClient:
|
||||
authorization: str = None,
|
||||
raise_for_status: bool = True
|
||||
) -> requests.Response:
|
||||
"""Core method for performing all API calls"""
|
||||
"""Core method for performing all API calls.
|
||||
|
||||
Args:
|
||||
method: HTTP method of the request, e.g. "get"
|
||||
route: Route in the Discord API, e.g. "users/@me"
|
||||
data: Data to be send with the request
|
||||
authorization: The authorization string to be used.
|
||||
Will use the default bot token if not set.
|
||||
raise_for_status: Whether a requests exception is to be raised when not ok
|
||||
|
||||
Returns:
|
||||
The raw response from the API
|
||||
"""
|
||||
uid = uuid1().hex
|
||||
|
||||
if not hasattr(requests, method):
|
||||
@@ -577,7 +681,7 @@ class DiscordClient:
|
||||
r.text
|
||||
)
|
||||
|
||||
if r.status_code == self._HTTP_STATUS_CODE_RATE_LIMITED:
|
||||
if r.status_code == HTTPStatus.TOO_MANY_REQUESTS:
|
||||
self._handle_new_api_backoff(r, uid)
|
||||
|
||||
self._report_rate_limit_from_api(r, uid)
|
||||
@@ -588,9 +692,10 @@ class DiscordClient:
|
||||
return r
|
||||
|
||||
def _handle_ongoing_api_backoff(self, uid: str) -> None:
|
||||
"""checks if api is currently on backoff
|
||||
if on backoff: will do a blocking wait if it expires soon,
|
||||
else raises exception
|
||||
"""Check if api is currently on backoff.
|
||||
|
||||
If on backoff: will do a blocking wait if it expires soon,
|
||||
else raises exception.
|
||||
"""
|
||||
global_backoff_duration = self._redis.pttl(self._KEY_GLOBAL_BACKOFF_UNTIL)
|
||||
if global_backoff_duration > 0:
|
||||
@@ -610,8 +715,9 @@ class DiscordClient:
|
||||
raise DiscordTooManyRequestsError(retry_after=global_backoff_duration)
|
||||
|
||||
def _ensure_rate_limed_not_exhausted(self, uid: str) -> int:
|
||||
"""ensures that the rate limit is not exhausted
|
||||
if exhausted: will do a blocking wait if rate limit resets soon,
|
||||
"""Ensures that the rate limit is not exhausted.
|
||||
|
||||
If exhausted: will do a blocking wait if rate limit resets soon,
|
||||
else raises exception
|
||||
|
||||
returns requests remaining on success
|
||||
@@ -654,10 +760,10 @@ class DiscordClient:
|
||||
)
|
||||
raise DiscordRateLimitExhausted(resets_in)
|
||||
|
||||
raise RuntimeError('Failed to handle rate limit after after too tries.')
|
||||
raise RuntimeError('Failed to handle rate limit after after too many tries.')
|
||||
|
||||
def _handle_new_api_backoff(self, r: requests.Response, uid: str) -> None:
|
||||
"""raises exception for new API backoff error"""
|
||||
"""Raise exception for new API backoff error."""
|
||||
response = r.json()
|
||||
if 'retry_after' in response:
|
||||
try:
|
||||
@@ -679,8 +785,8 @@ class DiscordClient:
|
||||
)
|
||||
raise DiscordTooManyRequestsError(retry_after=retry_after)
|
||||
|
||||
def _report_rate_limit_from_api(self, r, uid):
|
||||
"""Tries to log the current rate limit reported from API"""
|
||||
def _report_rate_limit_from_api(self, r, uid) -> None:
|
||||
"""Try to log the current rate limit reported from API."""
|
||||
if (
|
||||
logger.getEffectiveLevel() <= logging.DEBUG
|
||||
and 'x-ratelimit-limit' in r.headers
|
||||
@@ -703,22 +809,17 @@ class DiscordClient:
|
||||
|
||||
@staticmethod
|
||||
def _redis_decode(value: str) -> str:
|
||||
"""Decodes a string from Redis and passes through None and Booleans"""
|
||||
"""Decode a string from Redis and passes through None and Booleans."""
|
||||
if value is not None and not isinstance(value, bool):
|
||||
return value.decode('utf-8')
|
||||
else:
|
||||
return value
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _generate_hash(key: str) -> str:
|
||||
"""Generate hash key for given string."""
|
||||
return md5(key.encode('utf-8')).hexdigest()
|
||||
|
||||
@staticmethod
|
||||
def _sanitize_role_ids(role_ids: list) -> list:
|
||||
"""make sure its a list of integers"""
|
||||
return [int(role_id) for role_id in list(role_ids)]
|
||||
|
||||
@classmethod
|
||||
def _sanitize_nick(cls, nick: str) -> str:
|
||||
"""shortens too long strings if necessary"""
|
||||
return str(nick)[:cls._NICK_MAX_CHARS]
|
||||
def _sanitize_role_ids(role_ids: Iterable[int]) -> List[int]:
|
||||
"""Sanitize a list of role IDs, i.e. make sure its a list of unique integers."""
|
||||
return [int(role_id) for role_id in set(role_ids)]
|
||||
|
||||
@@ -1,23 +1,26 @@
|
||||
"""Custom exceptions for the Discord Client package."""
|
||||
|
||||
import math
|
||||
|
||||
|
||||
class DiscordClientException(Exception):
|
||||
"""Base Exception for the Discord client"""
|
||||
"""Base Exception for the Discord client."""
|
||||
|
||||
|
||||
class DiscordApiBackoff(DiscordClientException):
|
||||
"""Exception signaling we need to backoff from sending requests to the API for now
|
||||
"""Exception signaling we need to backoff from sending requests to the API for now.
|
||||
|
||||
Args:
|
||||
retry_after: time to retry after in milliseconds
|
||||
"""
|
||||
|
||||
def __init__(self, retry_after: int):
|
||||
"""
|
||||
:param retry_after: int time to retry after in milliseconds
|
||||
"""
|
||||
super().__init__()
|
||||
self.retry_after = int(retry_after)
|
||||
|
||||
@property
|
||||
def retry_after_seconds(self):
|
||||
"""Time to retry after in seconds."""
|
||||
return math.ceil(self.retry_after / 1000)
|
||||
|
||||
|
||||
|
||||
@@ -1,27 +1,37 @@
|
||||
from copy import copy
|
||||
from typing import Set, Iterable
|
||||
from typing import Iterable, List, Optional, Set, Tuple
|
||||
|
||||
from .models import Role
|
||||
|
||||
|
||||
class DiscordRoles:
|
||||
"""Container class that helps dealing with Discord roles.
|
||||
class RolesSet:
|
||||
"""Container of Discord roles with added functionality.
|
||||
|
||||
Objects of this class are immutable and work in many ways like sets.
|
||||
|
||||
Ideally objects are initialized from raw API responses,
|
||||
e.g. from DiscordClient.guild.roles()
|
||||
"""
|
||||
_ROLE_NAME_MAX_CHARS = 100
|
||||
e.g. from DiscordClient.guild.roles().
|
||||
|
||||
def __init__(self, roles_lst: list) -> None:
|
||||
"""roles_lst must be a list of dict, each defining a role"""
|
||||
Args:
|
||||
roles_lst: List of dicts, each defining a role
|
||||
"""
|
||||
def __init__(self, roles_lst: Iterable[Role]) -> None:
|
||||
if not isinstance(roles_lst, (list, set, tuple)):
|
||||
raise TypeError('roles_lst must be of type list, set or tuple')
|
||||
self._roles = dict()
|
||||
self._roles_by_name = dict()
|
||||
for role in list(roles_lst):
|
||||
self._assert_valid_role(role)
|
||||
self._roles[int(role['id'])] = role
|
||||
self._roles_by_name[self.sanitize_role_name(role['name'])] = role
|
||||
if not isinstance(role, Role):
|
||||
raise TypeError('Roles must be of type Role: %s' % role)
|
||||
self._roles[role.id] = role
|
||||
self._roles_by_name[role.name] = role
|
||||
|
||||
def __repr__(self) -> str:
|
||||
if self._roles_by_name:
|
||||
roles = '"' + '", "'.join(sorted(list(self._roles_by_name.keys()))) + '"'
|
||||
else:
|
||||
roles = ""
|
||||
return f'{self.__class__.__name__}([{roles}])'
|
||||
|
||||
def __eq__(self, other):
|
||||
if isinstance(other, type(self)):
|
||||
@@ -41,15 +51,15 @@ class DiscordRoles:
|
||||
return len(self._roles.keys())
|
||||
|
||||
def has_roles(self, role_ids: Set[int]) -> bool:
|
||||
"""returns true if this objects contains all roles defined by given role_ids
|
||||
incl. managed roles
|
||||
"""True if this objects contains all roles defined by given role_ids
|
||||
incl. managed roles.
|
||||
"""
|
||||
role_ids = {int(id) for id in role_ids}
|
||||
all_role_ids = self._roles.keys()
|
||||
return role_ids.issubset(all_role_ids)
|
||||
|
||||
def ids(self) -> Set[int]:
|
||||
"""return a set of all role IDs"""
|
||||
"""Set of all role IDs."""
|
||||
return set(self._roles.keys())
|
||||
|
||||
def subset(
|
||||
@@ -57,13 +67,13 @@ class DiscordRoles:
|
||||
role_ids: Iterable[int] = None,
|
||||
managed_only: bool = False,
|
||||
role_names: Iterable[str] = None
|
||||
) -> "DiscordRoles":
|
||||
"""returns a new object containing the subset of roles
|
||||
) -> "RolesSet":
|
||||
"""Create instance containing the subset of roles
|
||||
|
||||
Args:
|
||||
- role_ids: role ids must be in the provided list
|
||||
- managed_only: roles must be managed
|
||||
- role_names: role names must match provided list (not case sensitive)
|
||||
role_ids: role ids must be in the provided list
|
||||
managed_only: roles must be managed
|
||||
role_names: role names must match provided list (not case sensitive)
|
||||
"""
|
||||
if role_ids is not None:
|
||||
role_ids = {int(id) for id in role_ids}
|
||||
@@ -75,72 +85,50 @@ class DiscordRoles:
|
||||
|
||||
elif role_ids is None and managed_only:
|
||||
return type(self)([
|
||||
role for _, role in self._roles.items() if role['managed']
|
||||
role for _, role in self._roles.items() if role.managed
|
||||
])
|
||||
|
||||
elif role_ids is not None and managed_only:
|
||||
return type(self)([
|
||||
role for role_id, role in self._roles.items()
|
||||
if role_id in role_ids and role['managed']
|
||||
if role_id in role_ids and role.managed
|
||||
])
|
||||
|
||||
elif role_ids is None and managed_only is False and role_names is not None:
|
||||
role_names = {self.sanitize_role_name(name).lower() for name in role_names}
|
||||
role_names = {Role.sanitize_name(name).lower() for name in role_names}
|
||||
return type(self)([
|
||||
role for role in self._roles.values()
|
||||
if role["name"].lower() in role_names
|
||||
if role.name.lower() in role_names
|
||||
])
|
||||
|
||||
return copy(self)
|
||||
|
||||
def union(self, other: object) -> "DiscordRoles":
|
||||
"""returns a new roles object that is the union of this roles object
|
||||
with other"""
|
||||
def union(self, other: object) -> "RolesSet":
|
||||
"""Create instance that is the union of this roles object with other."""
|
||||
return type(self)(list(self) + list(other))
|
||||
|
||||
def difference(self, other: object) -> "DiscordRoles":
|
||||
"""returns a new roles object that only contains the roles
|
||||
that exist in the current objects, but not in other
|
||||
def difference(self, other: object) -> "RolesSet":
|
||||
"""Create instance that only contains the roles
|
||||
that exist in the current objects, but not in other.
|
||||
"""
|
||||
new_ids = self.ids().difference(other.ids())
|
||||
return self.subset(role_ids=new_ids)
|
||||
|
||||
def role_by_name(self, role_name: str) -> dict:
|
||||
"""returns role if one with matching name is found else an empty dict"""
|
||||
role_name = self.sanitize_role_name(role_name)
|
||||
def role_by_name(self, role_name: str) -> Optional[Role]:
|
||||
"""Role if one with matching name is found else None."""
|
||||
role_name = Role.sanitize_name(role_name)
|
||||
if role_name in self._roles_by_name:
|
||||
return self._roles_by_name[role_name]
|
||||
return dict()
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def create_from_matched_roles(cls, matched_roles: list) -> "DiscordRoles":
|
||||
"""returns a new object created from the given list of matches roles
|
||||
def create_from_matched_roles(
|
||||
cls, matched_roles: List[Tuple[Role, bool]]
|
||||
) -> "RolesSet":
|
||||
"""Create new instance from the given list of matches roles.
|
||||
|
||||
matches_roles must be a list of tuples in the form: (role, created)
|
||||
Args:
|
||||
matches_roles: list of matches roles
|
||||
"""
|
||||
raw_roles = [x[0] for x in matched_roles]
|
||||
return cls(raw_roles)
|
||||
|
||||
@staticmethod
|
||||
def _assert_valid_role(role: dict) -> None:
|
||||
if not isinstance(role, dict):
|
||||
raise TypeError('Roles must be of type dict: %s' % role)
|
||||
|
||||
if 'id' not in role or 'name' not in role or 'managed' not in role:
|
||||
raise ValueError('This role is not valid: %s' % role)
|
||||
|
||||
@classmethod
|
||||
def sanitize_role_name(cls, role_name: str) -> str:
|
||||
"""shortens too long strings if necessary"""
|
||||
return str(role_name)[:cls._ROLE_NAME_MAX_CHARS]
|
||||
|
||||
|
||||
def match_or_create_roles_from_names(
|
||||
client: object, guild_id: int, role_names: list
|
||||
) -> DiscordRoles:
|
||||
"""Shortcut for getting the result of matching role names as DiscordRoles object"""
|
||||
return DiscordRoles.create_from_matched_roles(
|
||||
client.match_or_create_roles_from_names(
|
||||
guild_id=guild_id, role_names=role_names
|
||||
)
|
||||
)
|
||||
|
||||
125
allianceauth/services/modules/discord/discord_client/models.py
Normal file
125
allianceauth/services/modules/discord/discord_client/models.py
Normal file
@@ -0,0 +1,125 @@
|
||||
"""Implementation of Discord objects used by this client.
|
||||
|
||||
Note that only those objects and properties are implemented, which are needed by AA.
|
||||
|
||||
Names and types are mirrored from the API whenever possible.
|
||||
Discord's snowflake type (used by Discord IDs) is implemented as int.
|
||||
"""
|
||||
|
||||
from dataclasses import asdict, dataclass
|
||||
from typing import FrozenSet
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class User:
|
||||
"""A user on Discord."""
|
||||
|
||||
id: int
|
||||
username: str
|
||||
discriminator: str
|
||||
|
||||
def __post_init__(self):
|
||||
object.__setattr__(self, "id", int(self.id))
|
||||
object.__setattr__(self, "username", str(self.username))
|
||||
object.__setattr__(self, "discriminator", str(self.discriminator))
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict) -> "User":
|
||||
"""Create object from dictionary as received from the API."""
|
||||
return cls(
|
||||
id=int(data["id"]),
|
||||
username=data["username"],
|
||||
discriminator=data["discriminator"],
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Role:
|
||||
"""A role on Discord."""
|
||||
|
||||
_ROLE_NAME_MAX_CHARS = 100
|
||||
|
||||
id: int
|
||||
name: str
|
||||
managed: bool = False
|
||||
|
||||
def __post_init__(self):
|
||||
object.__setattr__(self, "id", int(self.id))
|
||||
object.__setattr__(self, "name", self.sanitize_name(self.name))
|
||||
object.__setattr__(self, "managed", bool(self.managed))
|
||||
|
||||
def asdict(self) -> dict:
|
||||
"""Convert object into a dictionary representation."""
|
||||
return asdict(self)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict) -> "Role":
|
||||
"""Create object from dictionary as received from the API."""
|
||||
return cls(id=int(data["id"]), name=data["name"], managed=data["managed"])
|
||||
|
||||
@classmethod
|
||||
def sanitize_name(cls, role_name: str) -> str:
|
||||
"""Shorten too long names if necessary."""
|
||||
return str(role_name)[: cls._ROLE_NAME_MAX_CHARS]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Guild:
|
||||
"""A guild on Discord."""
|
||||
|
||||
id: int
|
||||
name: str
|
||||
roles: FrozenSet[Role]
|
||||
|
||||
def __post_init__(self):
|
||||
object.__setattr__(self, "id", int(self.id))
|
||||
object.__setattr__(self, "name", str(self.name))
|
||||
for role in self.roles:
|
||||
if not isinstance(role, Role):
|
||||
raise TypeError("roles can only contain Role objects.")
|
||||
object.__setattr__(self, "roles", frozenset(self.roles))
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict) -> "Guild":
|
||||
"""Create object from dictionary as received from the API."""
|
||||
return cls(
|
||||
id=int(data["id"]),
|
||||
name=data["name"],
|
||||
roles=frozenset(Role.from_dict(obj) for obj in data["roles"]),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class GuildMember:
|
||||
"""A member of a guild on Discord."""
|
||||
|
||||
_NICK_MAX_CHARS = 32
|
||||
|
||||
roles: FrozenSet[int]
|
||||
nick: str = None
|
||||
user: User = None
|
||||
|
||||
def __post_init__(self):
|
||||
if self.nick:
|
||||
object.__setattr__(self, "nick", self.sanitize_nick(self.nick))
|
||||
if self.user and not isinstance(self.user, User):
|
||||
raise TypeError("user must be of type User")
|
||||
for role in self.roles:
|
||||
if not isinstance(role, int):
|
||||
raise TypeError("roles can only contain ints")
|
||||
object.__setattr__(self, "roles", frozenset(self.roles))
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict) -> "GuildMember":
|
||||
"""Create object from dictionary as received from the API."""
|
||||
params = {"roles": {int(obj) for obj in data["roles"]}}
|
||||
if data.get("user"):
|
||||
params["user"] = User.from_dict(data["user"])
|
||||
if data.get("nick"):
|
||||
params["nick"] = data["nick"]
|
||||
return cls(**params)
|
||||
|
||||
@classmethod
|
||||
def sanitize_nick(cls, nick: str) -> str:
|
||||
"""Sanitize a nick, i.e. shorten too long strings if necessary."""
|
||||
return str(nick)[: cls._NICK_MAX_CHARS]
|
||||
@@ -1,40 +0,0 @@
|
||||
TEST_GUILD_ID = 123456789012345678
|
||||
TEST_USER_ID = 198765432012345678
|
||||
TEST_USER_NAME = 'Peter Parker'
|
||||
TEST_USER_DISCRIMINATOR = '1234'
|
||||
TEST_BOT_TOKEN = 'abcdefhijlkmnopqastzvwxyz1234567890ABCDEFGHOJKLMNOPQRSTUVWXY'
|
||||
TEST_ROLE_ID = 654321012345678912
|
||||
|
||||
|
||||
def create_role(id: int, name: str, managed=False) -> dict:
|
||||
return {
|
||||
'id': int(id),
|
||||
'name': str(name),
|
||||
'managed': bool(managed)
|
||||
}
|
||||
|
||||
|
||||
def create_matched_role(role, created=False) -> tuple:
|
||||
return role, created
|
||||
|
||||
|
||||
ROLE_ALPHA = create_role(1, 'alpha')
|
||||
ROLE_BRAVO = create_role(2, 'bravo')
|
||||
ROLE_CHARLIE = create_role(3, 'charlie')
|
||||
ROLE_CHARLIE_2 = create_role(4, 'Charlie') # Discord roles are case sensitive
|
||||
ROLE_MIKE = create_role(13, 'mike', True)
|
||||
|
||||
|
||||
ALL_ROLES = [ROLE_ALPHA, ROLE_BRAVO, ROLE_CHARLIE, ROLE_MIKE]
|
||||
|
||||
|
||||
def create_user_info(
|
||||
id: int = TEST_USER_ID,
|
||||
username: str = TEST_USER_NAME,
|
||||
discriminator: str = TEST_USER_DISCRIMINATOR
|
||||
):
|
||||
return {
|
||||
'id': str(id),
|
||||
'username': str(username[:32]),
|
||||
'discriminator': str(discriminator[:4])
|
||||
}
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
{
|
||||
"guilds": {
|
||||
"2909267986263572999": {
|
||||
"id": "2909267986263572999",
|
||||
"name": "Mason's Test Server",
|
||||
"icon": "389030ec9db118cb5b85a732333b7c98",
|
||||
"description": null,
|
||||
"splash": "75610b05a0dd09ec2c3c7df9f6975ea0",
|
||||
"discovery_splash": null,
|
||||
"approximate_member_count": 2,
|
||||
"approximate_presence_count": 2,
|
||||
"features": [
|
||||
"INVITE_SPLASH",
|
||||
"VANITY_URL",
|
||||
"COMMERCE",
|
||||
"BANNER",
|
||||
"NEWS",
|
||||
"VERIFIED",
|
||||
"VIP_REGIONS"
|
||||
],
|
||||
"emojis": [
|
||||
{
|
||||
"name": "ultrafastparrot",
|
||||
"roles": [],
|
||||
"id": "393564762228785161",
|
||||
"require_colons": true,
|
||||
"managed": false,
|
||||
"animated": true,
|
||||
"available": true
|
||||
}
|
||||
],
|
||||
"banner": "5c3cb8d1bc159937fffe7e641ec96ca7",
|
||||
"owner_id": "53908232506183680",
|
||||
"application_id": null,
|
||||
"region": null,
|
||||
"afk_channel_id": null,
|
||||
"afk_timeout": 300,
|
||||
"system_channel_id": null,
|
||||
"widget_enabled": true,
|
||||
"widget_channel_id": "639513352485470208",
|
||||
"verification_level": 0,
|
||||
"roles": [
|
||||
{
|
||||
"id": "2909267986263572999",
|
||||
"name": "@everyone",
|
||||
"permissions": "49794752",
|
||||
"position": 0,
|
||||
"color": 0,
|
||||
"hoist": false,
|
||||
"managed": false,
|
||||
"mentionable": false
|
||||
}
|
||||
],
|
||||
"default_message_notifications": 1,
|
||||
"mfa_level": 0,
|
||||
"explicit_content_filter": 0,
|
||||
"max_presences": null,
|
||||
"max_members": 250000,
|
||||
"max_video_channel_users": 25,
|
||||
"vanity_url_code": "no",
|
||||
"premium_tier": 0,
|
||||
"premium_subscription_count": 0,
|
||||
"system_channel_flags": 0,
|
||||
"preferred_locale": "en-US",
|
||||
"rules_channel_id": null,
|
||||
"public_updates_channel_id": null
|
||||
}
|
||||
},
|
||||
"guildMembers": {
|
||||
"1": {
|
||||
"user": {},
|
||||
"nick": null,
|
||||
"avatar": null,
|
||||
"roles": [],
|
||||
"joined_at": "2015-04-26T06:26:56.936000+00:00",
|
||||
"deaf": false,
|
||||
"mute": false
|
||||
},
|
||||
"2": {
|
||||
"user": {
|
||||
"id": "80351110224678912",
|
||||
"username": "Nelly",
|
||||
"discriminator": "1337",
|
||||
"avatar": "8342729096ea3675442027381ff50dfe",
|
||||
"verified": true,
|
||||
"email": "nelly@discord.com",
|
||||
"flags": 64,
|
||||
"banner": "06c16474723fe537c283b8efa61a30c8",
|
||||
"accent_color": 16711680,
|
||||
"premium_type": 1,
|
||||
"public_flags": 64
|
||||
},
|
||||
"nick": "Nelly the great",
|
||||
"avatar": null,
|
||||
"roles": [
|
||||
"197150972374548480",
|
||||
"41771983423143936"
|
||||
],
|
||||
"joined_at": "2015-04-26T06:26:56.936000+00:00",
|
||||
"deaf": false,
|
||||
"mute": false
|
||||
}
|
||||
},
|
||||
"roles": {
|
||||
"197150972374548480": {
|
||||
"id": "197150972374548480",
|
||||
"name": "My Managed Role",
|
||||
"color": 3447003,
|
||||
"hoist": false,
|
||||
"icon": "cf3ced8600b777c9486c6d8d84fb4327",
|
||||
"unicode_emoji": null,
|
||||
"position": 2,
|
||||
"permissions": "66321471",
|
||||
"managed": true,
|
||||
"mentionable": false
|
||||
},
|
||||
"2909267986263572999": {
|
||||
"id": "2909267986263572999",
|
||||
"name": "@everyone",
|
||||
"permissions": "49794752",
|
||||
"position": 0,
|
||||
"color": 0,
|
||||
"hoist": false,
|
||||
"managed": false,
|
||||
"mentionable": false
|
||||
},
|
||||
"41771983423143936": {
|
||||
"id": "41771983423143936",
|
||||
"name": "WE DEM BOYZZ!!!!!!",
|
||||
"color": 3447003,
|
||||
"hoist": true,
|
||||
"icon": "cf3ced8600b777c9486c6d8d84fb4327",
|
||||
"unicode_emoji": null,
|
||||
"position": 1,
|
||||
"permissions": "66321471",
|
||||
"managed": false,
|
||||
"mentionable": false
|
||||
}
|
||||
},
|
||||
"users": {
|
||||
"80351110224678912": {
|
||||
"id": "80351110224678912",
|
||||
"username": "Nelly",
|
||||
"discriminator": "1337",
|
||||
"avatar": "8342729096ea3675442027381ff50dfe",
|
||||
"verified": true,
|
||||
"email": "nelly@discord.com",
|
||||
"flags": 64,
|
||||
"banner": "06c16474723fe537c283b8efa61a30c8",
|
||||
"accent_color": 16711680,
|
||||
"premium_type": 1,
|
||||
"public_flags": 64
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
from itertools import count
|
||||
|
||||
from django.utils.timezone import now
|
||||
|
||||
from ..client import DiscordApiStatusCode
|
||||
from ..models import Guild, GuildMember, Role, User
|
||||
|
||||
TEST_GUILD_ID = 123456789012345678
|
||||
TEST_GUILD_NAME = "Test Guild"
|
||||
TEST_USER_ID = 198765432012345678
|
||||
TEST_USER_NAME = "Peter Parker"
|
||||
TEST_USER_DISCRIMINATOR = "1234"
|
||||
TEST_BOT_TOKEN = "abcdefhijlkmnopqastzvwxyz1234567890ABCDEFGHOJKLMNOPQRSTUVWXY"
|
||||
TEST_ROLE_ID = 654321012345678912
|
||||
|
||||
|
||||
def create_discord_role_object(id: int, name: str, managed: bool = False) -> dict:
|
||||
return {"id": str(int(id)), "name": str(name), "managed": bool(managed)}
|
||||
|
||||
|
||||
def create_matched_role(role, created=False) -> tuple:
|
||||
return role, created
|
||||
|
||||
|
||||
def create_discord_user_object(**kwargs):
|
||||
params = {
|
||||
"id": TEST_USER_ID,
|
||||
"username": TEST_USER_NAME,
|
||||
"discriminator": TEST_USER_DISCRIMINATOR,
|
||||
}
|
||||
params.update(kwargs)
|
||||
params["id"] = str(int(params["id"]))
|
||||
return params
|
||||
|
||||
|
||||
def create_discord_guild_member_object(user=None, **kwargs):
|
||||
user_params = {}
|
||||
if user:
|
||||
user_params["user"] = user
|
||||
params = {
|
||||
"user": create_discord_user_object(**user_params),
|
||||
"roles": [],
|
||||
"joined_at": now().isoformat(),
|
||||
"deaf": False,
|
||||
"mute": False,
|
||||
}
|
||||
params.update(kwargs)
|
||||
params["roles"] = [str(int(obj)) for obj in params["roles"]]
|
||||
return params
|
||||
|
||||
|
||||
def create_discord_error_response(code: int) -> dict:
|
||||
return {"code": int(code)}
|
||||
|
||||
|
||||
def create_discord_error_response_unknown_member() -> dict:
|
||||
return create_discord_error_response(DiscordApiStatusCode.UNKNOWN_MEMBER.value)
|
||||
|
||||
|
||||
def create_discord_guild_object(**kwargs):
|
||||
params = {"id": TEST_GUILD_ID, "name": TEST_GUILD_NAME, "roles": []}
|
||||
params.update(kwargs)
|
||||
params["id"] = str(int(params["id"]))
|
||||
return params
|
||||
|
||||
|
||||
def create_user(**kwargs):
|
||||
params = {
|
||||
"id": TEST_USER_ID,
|
||||
"username": TEST_USER_NAME,
|
||||
"discriminator": TEST_USER_DISCRIMINATOR,
|
||||
}
|
||||
params.update(kwargs)
|
||||
return User(**params)
|
||||
|
||||
|
||||
def create_guild(**kwargs):
|
||||
params = {"id": TEST_GUILD_ID, "name": TEST_GUILD_NAME, "roles": []}
|
||||
params.update(kwargs)
|
||||
return Guild(**params)
|
||||
|
||||
|
||||
def create_guild_member(**kwargs):
|
||||
params = {"user": create_user(), "roles": []}
|
||||
params.update(kwargs)
|
||||
return GuildMember(**params)
|
||||
|
||||
|
||||
def create_role(**kwargs) -> dict:
|
||||
params = {"managed": False}
|
||||
params.update(kwargs)
|
||||
if "id" not in params:
|
||||
params["id"] = next_number("role")
|
||||
if "name" not in params:
|
||||
params["name"] = f"Test Role #{params['id']}"
|
||||
return Role(**params)
|
||||
|
||||
|
||||
def next_number(key: str = None) -> int:
|
||||
"""Calculate the next number in a persistent sequence."""
|
||||
if key is None:
|
||||
key = "_general"
|
||||
try:
|
||||
return next_number._counter[key].__next__()
|
||||
except AttributeError:
|
||||
next_number._counter = dict()
|
||||
except KeyError:
|
||||
pass
|
||||
next_number._counter[key] = count(start=1)
|
||||
return next_number._counter[key].__next__()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,177 +1,201 @@
|
||||
from unittest import TestCase
|
||||
from allianceauth.utils.testing import NoSocketsTestCase
|
||||
|
||||
from . import (
|
||||
ROLE_ALPHA,
|
||||
ROLE_BRAVO,
|
||||
ROLE_CHARLIE,
|
||||
ROLE_CHARLIE_2,
|
||||
ROLE_MIKE,
|
||||
ALL_ROLES,
|
||||
create_role
|
||||
)
|
||||
from .. import DiscordRoles
|
||||
from ..helpers import RolesSet
|
||||
from .factories import create_matched_role, create_role
|
||||
|
||||
|
||||
MODULE_PATH = 'allianceauth.services.modules.discord.discord_client.client'
|
||||
|
||||
|
||||
class TestDiscordRoles(TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.all_roles = DiscordRoles(ALL_ROLES)
|
||||
|
||||
class TestRolesSet(NoSocketsTestCase):
|
||||
def test_can_create_simple(self):
|
||||
roles_raw = [ROLE_ALPHA]
|
||||
roles = DiscordRoles(roles_raw)
|
||||
# given
|
||||
roles_raw = [create_role()]
|
||||
# when
|
||||
roles = RolesSet(roles_raw)
|
||||
# then
|
||||
self.assertListEqual(list(roles), roles_raw)
|
||||
|
||||
def test_can_create_empty(self):
|
||||
roles_raw = []
|
||||
roles = DiscordRoles(roles_raw)
|
||||
# when
|
||||
roles = RolesSet([])
|
||||
# then
|
||||
self.assertListEqual(list(roles), [])
|
||||
|
||||
def test_raises_exception_if_roles_raw_of_wrong_type(self):
|
||||
with self.assertRaises(TypeError):
|
||||
DiscordRoles({'id': 1})
|
||||
RolesSet({"id": 1})
|
||||
|
||||
def test_raises_exception_if_list_contains_non_dict(self):
|
||||
roles_raw = [ROLE_ALPHA, 'not_valid']
|
||||
# given
|
||||
roles_raw = [create_role(), "not_valid"]
|
||||
# when/then
|
||||
with self.assertRaises(TypeError):
|
||||
DiscordRoles(roles_raw)
|
||||
|
||||
def test_raises_exception_if_invalid_role_1(self):
|
||||
roles_raw = [{'name': 'alpha', 'managed': False}]
|
||||
with self.assertRaises(ValueError):
|
||||
DiscordRoles(roles_raw)
|
||||
|
||||
def test_raises_exception_if_invalid_role_2(self):
|
||||
roles_raw = [{'id': 1, 'managed': False}]
|
||||
with self.assertRaises(ValueError):
|
||||
DiscordRoles(roles_raw)
|
||||
|
||||
def test_raises_exception_if_invalid_role_3(self):
|
||||
roles_raw = [{'id': 1, 'name': 'alpha'}]
|
||||
with self.assertRaises(ValueError):
|
||||
DiscordRoles(roles_raw)
|
||||
RolesSet(roles_raw)
|
||||
|
||||
def test_roles_are_equal(self):
|
||||
roles_a = DiscordRoles([ROLE_ALPHA, ROLE_BRAVO])
|
||||
roles_b = DiscordRoles([ROLE_ALPHA, ROLE_BRAVO])
|
||||
# given
|
||||
role_a = create_role()
|
||||
role_b = create_role()
|
||||
roles_a = RolesSet([role_a, role_b])
|
||||
roles_b = RolesSet([role_a, role_b])
|
||||
# when/then
|
||||
self.assertEqual(roles_a, roles_b)
|
||||
|
||||
def test_roles_are_not_equal(self):
|
||||
roles_a = DiscordRoles([ROLE_ALPHA, ROLE_BRAVO])
|
||||
roles_b = DiscordRoles([ROLE_ALPHA])
|
||||
# given
|
||||
role_a = create_role()
|
||||
role_b = create_role()
|
||||
roles_a = RolesSet([role_a, role_b])
|
||||
roles_b = RolesSet([role_a])
|
||||
# when/then
|
||||
self.assertNotEqual(roles_a, roles_b)
|
||||
|
||||
def test_different_objects_are_not_equal(self):
|
||||
roles_a = DiscordRoles([ROLE_ALPHA, ROLE_BRAVO])
|
||||
roles_a = RolesSet([])
|
||||
self.assertFalse(roles_a == "invalid")
|
||||
|
||||
def test_len(self):
|
||||
self.assertEqual(len(self.all_roles), 4)
|
||||
# given
|
||||
role_a = create_role()
|
||||
role_b = create_role()
|
||||
roles = RolesSet([role_a, role_b])
|
||||
# when/then
|
||||
self.assertEqual(len(roles), 2)
|
||||
|
||||
def test_contains(self):
|
||||
self.assertTrue(1 in self.all_roles)
|
||||
self.assertFalse(99 in self.all_roles)
|
||||
|
||||
def test_sanitize_role_name(self):
|
||||
role_name_input = 'x' * 110
|
||||
role_name_expected = 'x' * 100
|
||||
result = DiscordRoles.sanitize_role_name(role_name_input)
|
||||
self.assertEqual(result, role_name_expected)
|
||||
# given
|
||||
role_a = create_role(id=1)
|
||||
roles = RolesSet([role_a])
|
||||
# when/then
|
||||
self.assertTrue(1 in roles)
|
||||
self.assertFalse(99 in roles)
|
||||
|
||||
def test_objects_are_hashable(self):
|
||||
roles_a = DiscordRoles([ROLE_ALPHA, ROLE_BRAVO])
|
||||
roles_b = DiscordRoles([ROLE_BRAVO, ROLE_ALPHA])
|
||||
roles_c = DiscordRoles([ROLE_ALPHA, ROLE_BRAVO, ROLE_MIKE])
|
||||
# given
|
||||
role_a = create_role()
|
||||
role_b = create_role()
|
||||
role_c = create_role()
|
||||
roles_a = RolesSet([role_a, role_b])
|
||||
roles_b = RolesSet([role_b, role_a])
|
||||
roles_c = RolesSet([role_a, role_b, role_c])
|
||||
# when/then
|
||||
self.assertIsNotNone(hash(roles_a))
|
||||
self.assertEqual(hash(roles_a), hash(roles_b))
|
||||
self.assertNotEqual(hash(roles_a), hash(roles_c))
|
||||
|
||||
def test_create_from_matched_roles(self):
|
||||
role_a = create_role()
|
||||
role_b = create_role()
|
||||
matched_roles = [
|
||||
(ROLE_ALPHA, True),
|
||||
(ROLE_BRAVO, False)
|
||||
create_matched_role(role_a, True),
|
||||
create_matched_role(role_b, False),
|
||||
]
|
||||
roles = DiscordRoles.create_from_matched_roles(matched_roles)
|
||||
self.assertSetEqual(roles.ids(), {1, 2})
|
||||
|
||||
|
||||
class TestIds(TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.all_roles = DiscordRoles(ALL_ROLES)
|
||||
# when
|
||||
roles = RolesSet.create_from_matched_roles(matched_roles)
|
||||
# then
|
||||
self.assertEqual(roles, RolesSet([role_a, role_b]))
|
||||
|
||||
def test_return_role_ids_default(self):
|
||||
result = self.all_roles.ids()
|
||||
expected = {1, 2, 3, 13}
|
||||
self.assertSetEqual(result, expected)
|
||||
role_a = create_role(id=1)
|
||||
role_b = create_role(id=2)
|
||||
roles = RolesSet([role_a, role_b])
|
||||
# when/then
|
||||
self.assertSetEqual(roles.ids(), {1, 2})
|
||||
|
||||
def test_return_role_ids_empty(self):
|
||||
roles = DiscordRoles([])
|
||||
# given
|
||||
roles = RolesSet([])
|
||||
# when/then
|
||||
self.assertSetEqual(roles.ids(), set())
|
||||
|
||||
|
||||
class TestSubset(TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.all_roles = DiscordRoles(ALL_ROLES)
|
||||
|
||||
class TestRolesSetSubset(NoSocketsTestCase):
|
||||
def test_ids_only(self):
|
||||
role_ids = {1, 3}
|
||||
roles_subset = self.all_roles.subset(role_ids)
|
||||
expected = {1, 3}
|
||||
self.assertSetEqual(roles_subset.ids(), expected)
|
||||
# given
|
||||
role_a = create_role(id=1)
|
||||
role_b = create_role(id=2)
|
||||
role_c = create_role(id=3)
|
||||
roles_all = RolesSet([role_a, role_b, role_c])
|
||||
# when
|
||||
roles_subset = roles_all.subset({1, 3})
|
||||
# then
|
||||
self.assertEqual(roles_subset, RolesSet([role_a, role_c]))
|
||||
|
||||
def test_ids_as_string_work_too(self):
|
||||
role_ids = {'1', '3'}
|
||||
roles_subset = self.all_roles.subset(role_ids)
|
||||
expected = {1, 3}
|
||||
self.assertSetEqual(roles_subset.ids(), expected)
|
||||
# given
|
||||
role_a = create_role(id=1)
|
||||
role_b = create_role(id=2)
|
||||
role_c = create_role(id=3)
|
||||
roles_all = RolesSet([role_a, role_b, role_c])
|
||||
# when
|
||||
roles_subset = roles_all.subset({"1", "3"})
|
||||
# then
|
||||
self.assertEqual(roles_subset, RolesSet([role_a, role_c]))
|
||||
|
||||
def test_managed_only(self):
|
||||
roles = self.all_roles.subset(managed_only=True)
|
||||
expected = {13}
|
||||
self.assertSetEqual(roles.ids(), expected)
|
||||
# given
|
||||
role_a = create_role(id=1)
|
||||
role_m = create_role(id=13, managed=True)
|
||||
roles_all = RolesSet([role_a, role_m])
|
||||
# when
|
||||
roles_subset = roles_all.subset(managed_only=True)
|
||||
# then
|
||||
self.assertEqual(roles_subset, RolesSet([role_m]))
|
||||
|
||||
def test_ids_and_managed_only(self):
|
||||
role_ids = {1, 3, 13}
|
||||
roles_subset = self.all_roles.subset(role_ids, managed_only=True)
|
||||
expected = {13}
|
||||
self.assertSetEqual(roles_subset.ids(), expected)
|
||||
# given
|
||||
role_a = create_role(id=1)
|
||||
role_b = create_role(id=2)
|
||||
role_m = create_role(id=13, managed=True)
|
||||
roles_all = RolesSet([role_a, role_b, role_m])
|
||||
# when
|
||||
roles_subset = roles_all.subset({1, 13}, managed_only=True)
|
||||
# then
|
||||
self.assertEqual(roles_subset, RolesSet([role_m]))
|
||||
|
||||
def test_ids_are_empty(self):
|
||||
roles = self.all_roles.subset([])
|
||||
expected = set()
|
||||
self.assertSetEqual(roles.ids(), expected)
|
||||
# given
|
||||
role_a = create_role(id=1)
|
||||
role_b = create_role(id=2)
|
||||
roles_all = RolesSet([role_a, role_b])
|
||||
roles_subset = roles_all.subset([])
|
||||
# then
|
||||
self.assertEqual(roles_subset, RolesSet([]))
|
||||
|
||||
def test_no_parameters(self):
|
||||
roles = self.all_roles.subset()
|
||||
expected = {1, 2, 3, 13}
|
||||
self.assertSetEqual(roles.ids(), expected)
|
||||
# given
|
||||
role_a = create_role(id=1)
|
||||
role_b = create_role(id=2)
|
||||
roles_all = RolesSet([role_a, role_b])
|
||||
roles_subset = roles_all.subset()
|
||||
# then
|
||||
self.assertEqual(roles_subset, roles_all)
|
||||
|
||||
def test_should_return_role_names_only(self):
|
||||
# given
|
||||
all_roles = DiscordRoles([
|
||||
ROLE_ALPHA, ROLE_BRAVO, ROLE_CHARLIE, ROLE_MIKE, ROLE_CHARLIE_2
|
||||
])
|
||||
role_a = create_role(name="alpha")
|
||||
role_b = create_role(name="bravo")
|
||||
role_c1 = create_role(name="charlie")
|
||||
role_c2 = create_role(name="Charlie")
|
||||
roles_all = RolesSet([role_a, role_b, role_c1, role_c2])
|
||||
# when
|
||||
roles = all_roles.subset(role_names={"bravo", "charlie"})
|
||||
roles_subset = roles_all.subset(role_names={"bravo", "charlie"})
|
||||
# then
|
||||
self.assertSetEqual(roles.ids(), {2, 3, 4})
|
||||
self.assertSetEqual(roles_subset, RolesSet([role_b, role_c1, role_c2]))
|
||||
|
||||
|
||||
class TestHasRoles(TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.all_roles = DiscordRoles(ALL_ROLES)
|
||||
class TestRolesSetHasRoles(NoSocketsTestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
role_a = create_role(id=1)
|
||||
role_b = create_role(id=2)
|
||||
role_c = create_role(id=3)
|
||||
cls.all_roles = RolesSet([role_a, role_b, role_c])
|
||||
|
||||
def test_true_if_all_roles_exit(self):
|
||||
self.assertTrue(self.all_roles.has_roles([1, 2]))
|
||||
|
||||
def test_true_if_all_roles_exit_str(self):
|
||||
self.assertTrue(self.all_roles.has_roles(['1', '2']))
|
||||
self.assertTrue(self.all_roles.has_roles(["1", "2"]))
|
||||
|
||||
def test_false_if_role_does_not_exit(self):
|
||||
self.assertFalse(self.all_roles.has_roles([99]))
|
||||
@@ -183,74 +207,104 @@ class TestHasRoles(TestCase):
|
||||
self.assertTrue(self.all_roles.has_roles([]))
|
||||
|
||||
|
||||
class TestGetMatchingRolesByName(TestCase):
|
||||
|
||||
def setUp(self):
|
||||
self.all_roles = DiscordRoles(ALL_ROLES)
|
||||
|
||||
class TestRolesSetGetMatchingRolesByName(NoSocketsTestCase):
|
||||
def test_return_role_if_matches(self):
|
||||
role_name = 'alpha'
|
||||
expected = ROLE_ALPHA
|
||||
result = self.all_roles.role_by_name(role_name)
|
||||
self.assertEqual(result, expected)
|
||||
# given
|
||||
role_a = create_role(name="alpha")
|
||||
role_b = create_role(name="bravo")
|
||||
roles = RolesSet([role_a, role_b])
|
||||
# when
|
||||
result = roles.role_by_name("alpha")
|
||||
# then
|
||||
self.assertEqual(result, role_a)
|
||||
|
||||
def test_return_role_if_matches_and_limit_max_length(self):
|
||||
role_name = 'x' * 120
|
||||
expected = create_role(77, 'x' * 100)
|
||||
roles = DiscordRoles([expected])
|
||||
# given
|
||||
role_name = "x" * 120
|
||||
role = create_role(name="x" * 100)
|
||||
roles = RolesSet([role])
|
||||
# when
|
||||
result = roles.role_by_name(role_name)
|
||||
self.assertEqual(result, expected)
|
||||
# then
|
||||
self.assertEqual(result, role)
|
||||
|
||||
def test_return_empty_if_not_matches(self):
|
||||
role_name = 'lima'
|
||||
expected = {}
|
||||
result = self.all_roles.role_by_name(role_name)
|
||||
self.assertEqual(result, expected)
|
||||
# given
|
||||
role_a = create_role(name="alpha")
|
||||
role_b = create_role(name="bravo")
|
||||
roles = RolesSet([role_a, role_b])
|
||||
# when
|
||||
result = roles.role_by_name("unknown")
|
||||
# then
|
||||
self.assertIsNone(result)
|
||||
|
||||
|
||||
class TestUnion(TestCase):
|
||||
|
||||
class TestRolesSetUnion(NoSocketsTestCase):
|
||||
def test_distinct_sets(self):
|
||||
roles_1 = DiscordRoles([ROLE_ALPHA, ROLE_BRAVO])
|
||||
roles_2 = DiscordRoles([ROLE_CHARLIE, ROLE_MIKE])
|
||||
roles_3 = roles_1.union(roles_2)
|
||||
expected = DiscordRoles([ROLE_ALPHA, ROLE_BRAVO, ROLE_CHARLIE, ROLE_MIKE])
|
||||
self.assertEqual(roles_3, expected)
|
||||
# given
|
||||
role_a = create_role()
|
||||
role_b = create_role()
|
||||
roles_1 = RolesSet([role_a])
|
||||
roles_2 = RolesSet([role_b])
|
||||
# when
|
||||
result = roles_1.union(roles_2)
|
||||
# then
|
||||
self.assertEqual(result, RolesSet([role_a, role_b]))
|
||||
|
||||
def test_overlapping_sets(self):
|
||||
roles_1 = DiscordRoles([ROLE_ALPHA, ROLE_BRAVO])
|
||||
roles_2 = DiscordRoles([ROLE_BRAVO, ROLE_MIKE])
|
||||
roles_3 = roles_1.union(roles_2)
|
||||
expected = DiscordRoles([ROLE_ALPHA, ROLE_BRAVO, ROLE_MIKE])
|
||||
self.assertEqual(roles_3, expected)
|
||||
# given
|
||||
role_a = create_role()
|
||||
role_b = create_role()
|
||||
role_c = create_role()
|
||||
roles_1 = RolesSet([role_a, role_b])
|
||||
roles_2 = RolesSet([role_b, role_c])
|
||||
# when
|
||||
result = roles_1.union(roles_2)
|
||||
self.assertEqual(result, RolesSet([role_a, role_b, role_c]))
|
||||
|
||||
def test_identical_sets(self):
|
||||
roles_1 = DiscordRoles([ROLE_ALPHA, ROLE_BRAVO])
|
||||
roles_2 = DiscordRoles([ROLE_ALPHA, ROLE_BRAVO])
|
||||
roles_3 = roles_1.union(roles_2)
|
||||
expected = DiscordRoles([ROLE_ALPHA, ROLE_BRAVO])
|
||||
self.assertEqual(roles_3, expected)
|
||||
role_a = create_role()
|
||||
role_b = create_role()
|
||||
roles_1 = RolesSet([role_a, role_b])
|
||||
roles_2 = RolesSet([role_a, role_b])
|
||||
# when
|
||||
result = roles_1.union(roles_2)
|
||||
self.assertEqual(result, RolesSet([role_a, role_b]))
|
||||
|
||||
|
||||
class TestDifference(TestCase):
|
||||
|
||||
class TestRolesSetDifference(NoSocketsTestCase):
|
||||
def test_distinct_sets(self):
|
||||
roles_1 = DiscordRoles([ROLE_ALPHA, ROLE_BRAVO])
|
||||
roles_2 = DiscordRoles([ROLE_CHARLIE, ROLE_MIKE])
|
||||
roles_3 = roles_1.difference(roles_2)
|
||||
expected = DiscordRoles([ROLE_ALPHA, ROLE_BRAVO])
|
||||
self.assertEqual(roles_3, expected)
|
||||
# given
|
||||
role_a = create_role()
|
||||
role_b = create_role()
|
||||
role_c = create_role()
|
||||
role_d = create_role()
|
||||
roles_1 = RolesSet([role_a, role_b])
|
||||
roles_2 = RolesSet([role_c, role_d])
|
||||
# when
|
||||
result = roles_1.difference(roles_2)
|
||||
# then
|
||||
self.assertEqual(result, RolesSet([role_a, role_b]))
|
||||
|
||||
def test_overlapping_sets(self):
|
||||
roles_1 = DiscordRoles([ROLE_ALPHA, ROLE_BRAVO])
|
||||
roles_2 = DiscordRoles([ROLE_BRAVO, ROLE_MIKE])
|
||||
roles_3 = roles_1.difference(roles_2)
|
||||
expected = DiscordRoles([ROLE_ALPHA])
|
||||
self.assertEqual(roles_3, expected)
|
||||
# given
|
||||
role_a = create_role()
|
||||
role_b = create_role()
|
||||
role_c = create_role()
|
||||
roles_1 = RolesSet([role_a, role_b])
|
||||
roles_2 = RolesSet([role_b, role_c])
|
||||
# when
|
||||
result = roles_1.difference(roles_2)
|
||||
# then
|
||||
self.assertEqual(result, RolesSet([role_a]))
|
||||
|
||||
def test_identical_sets(self):
|
||||
roles_1 = DiscordRoles([ROLE_ALPHA, ROLE_BRAVO])
|
||||
roles_2 = DiscordRoles([ROLE_ALPHA, ROLE_BRAVO])
|
||||
roles_3 = roles_1.difference(roles_2)
|
||||
expected = DiscordRoles([])
|
||||
self.assertEqual(roles_3, expected)
|
||||
# given
|
||||
role_a = create_role()
|
||||
role_b = create_role()
|
||||
roles_1 = RolesSet([role_a, role_b])
|
||||
roles_2 = RolesSet([role_a, role_b])
|
||||
# when
|
||||
result = roles_1.difference(roles_2)
|
||||
# then
|
||||
self.assertEqual(result, RolesSet([]))
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from unittest import TestCase
|
||||
|
||||
from ..models import Guild, GuildMember, Role, User
|
||||
from .factories import create_guild, create_guild_member, create_role, create_user
|
||||
|
||||
|
||||
def _fetch_example_objects() -> dict:
|
||||
path = Path(__file__).parent / "example_objects.json"
|
||||
with path.open("r", encoding="utf-8") as fp:
|
||||
return json.load(fp)
|
||||
|
||||
|
||||
class TestUser(TestCase):
|
||||
def test_should_create_new_object(self):
|
||||
# when
|
||||
obj = User(id="42", username=123, discriminator=456)
|
||||
# then
|
||||
self.assertEqual(obj.id, 42)
|
||||
self.assertEqual(obj.username, "123")
|
||||
self.assertTrue(obj.discriminator, "456")
|
||||
|
||||
def test_should_create_from_dict(self):
|
||||
# given
|
||||
data = example_objects["users"]["80351110224678912"]
|
||||
# when
|
||||
obj = User.from_dict(data)
|
||||
# then
|
||||
self.assertEqual(obj.id, 80351110224678912)
|
||||
self.assertEqual(obj.username, "Nelly")
|
||||
self.assertEqual(obj.discriminator, "1337")
|
||||
|
||||
|
||||
class TestRole(TestCase):
|
||||
def test_should_create_new_object_with_defaults(self):
|
||||
# when
|
||||
obj = Role(id="42", name="x" * 110)
|
||||
# then
|
||||
self.assertEqual(obj.id, 42)
|
||||
self.assertEqual(obj.name, "x" * 100)
|
||||
self.assertFalse(obj.managed)
|
||||
|
||||
def test_should_create_new_object(self):
|
||||
# when
|
||||
obj = Role(id=42, name="name", managed=1)
|
||||
# then
|
||||
self.assertEqual(obj.id, 42)
|
||||
self.assertEqual(obj.name, "name")
|
||||
self.assertTrue(obj.managed)
|
||||
|
||||
def test_should_create_from_dict(self):
|
||||
# given
|
||||
data = example_objects["roles"]["41771983423143936"]
|
||||
# when
|
||||
obj = Role.from_dict(data)
|
||||
# then
|
||||
self.assertEqual(obj.id, 41771983423143936)
|
||||
self.assertEqual(obj.name, "WE DEM BOYZZ!!!!!!")
|
||||
self.assertFalse(obj.managed)
|
||||
|
||||
def test_should_convert_to_dict(self):
|
||||
# given
|
||||
role = create_role(id=42, name="Special Name", managed=True)
|
||||
# when/then
|
||||
self.assertDictEqual(
|
||||
role.asdict(), {"id": 42, "name": "Special Name", "managed": True}
|
||||
)
|
||||
|
||||
def test_sanitize_role_name(self):
|
||||
# given
|
||||
role_name_input = "x" * 110
|
||||
role_name_expected = "x" * 100
|
||||
# when
|
||||
result = Role.sanitize_name(role_name_input)
|
||||
# then
|
||||
self.assertEqual(result, role_name_expected)
|
||||
|
||||
|
||||
class TestGuild(TestCase):
|
||||
def test_should_create_new_object(self):
|
||||
# given
|
||||
role_a = create_role()
|
||||
# when
|
||||
obj = Guild(id="42", name=123, roles=[role_a])
|
||||
# then
|
||||
self.assertEqual(obj.id, 42)
|
||||
self.assertEqual(obj.name, "123")
|
||||
self.assertEqual(obj.roles, frozenset([role_a]))
|
||||
|
||||
def test_should_create_from_dict(self):
|
||||
# given
|
||||
data = example_objects["guilds"]["2909267986263572999"]
|
||||
# when
|
||||
obj = Guild.from_dict(data)
|
||||
# then
|
||||
self.assertEqual(obj.id, 2909267986263572999)
|
||||
self.assertEqual(obj.name, "Mason's Test Server")
|
||||
(first_role,) = obj.roles
|
||||
self.assertEqual(first_role.id, 2909267986263572999)
|
||||
|
||||
def test_should_raise_error_when_role_type_is_wrong(self):
|
||||
with self.assertRaises(TypeError):
|
||||
create_guild(roles=[create_role(), "invalid"])
|
||||
|
||||
|
||||
class TestGuildMember(TestCase):
|
||||
def test_should_create_new_object(self):
|
||||
# given
|
||||
user = create_user()
|
||||
# when
|
||||
obj = GuildMember(user=user, nick="x" * 40, roles=[1, 2])
|
||||
# then
|
||||
self.assertEqual(obj.user, user)
|
||||
self.assertEqual(obj.nick, "x" * 32)
|
||||
self.assertEqual(obj.roles, frozenset([1, 2]))
|
||||
|
||||
def test_should_create_from_dict_empty(self):
|
||||
# given
|
||||
data = example_objects["guildMembers"]["1"]
|
||||
# when
|
||||
obj = GuildMember.from_dict(data)
|
||||
# then
|
||||
self.assertIsNone(obj.user)
|
||||
self.assertSetEqual(obj.roles, set())
|
||||
self.assertIsNone(obj.nick)
|
||||
|
||||
def test_should_create_from_dict_full(self):
|
||||
# given
|
||||
data = example_objects["guildMembers"]["2"]
|
||||
# when
|
||||
obj = GuildMember.from_dict(data)
|
||||
# then
|
||||
self.assertEqual(obj.user.username, "Nelly")
|
||||
self.assertSetEqual(obj.roles, {197150972374548480, 41771983423143936})
|
||||
self.assertEqual(obj.nick, "Nelly the great")
|
||||
|
||||
def test_should_raise_error_when_user_type_is_wrong(self):
|
||||
with self.assertRaises(TypeError):
|
||||
create_guild_member(user="invalid")
|
||||
|
||||
def test_should_raise_error_when_role_type_is_wrong(self):
|
||||
with self.assertRaises(TypeError):
|
||||
GuildMember(roles=[1, 2, "invalid"])
|
||||
|
||||
def test_sanitize_nick(self):
|
||||
# given
|
||||
nick_input = "x" * 40
|
||||
nick_expected = "x" * 32
|
||||
# when
|
||||
result = GuildMember.sanitize_nick(nick_input)
|
||||
# then
|
||||
self.assertEqual(result, nick_expected)
|
||||
|
||||
|
||||
example_objects = _fetch_example_objects()
|
||||
@@ -1,30 +1,33 @@
|
||||
import logging
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from requests_oauthlib import OAuth2Session
|
||||
from requests.exceptions import HTTPError
|
||||
from requests_oauthlib import OAuth2Session
|
||||
|
||||
from django.contrib.auth.models import User, Group
|
||||
from django.contrib.auth.models import Group, User
|
||||
from django.db import models
|
||||
from django.utils.timezone import now
|
||||
|
||||
from allianceauth.services.hooks import NameFormatter
|
||||
|
||||
from . import __title__
|
||||
from .app_settings import (
|
||||
DISCORD_APP_ID,
|
||||
DISCORD_APP_SECRET,
|
||||
DISCORD_BOT_TOKEN,
|
||||
DISCORD_CALLBACK_URL,
|
||||
DISCORD_GUILD_ID,
|
||||
DISCORD_SYNC_NAMES
|
||||
DISCORD_SYNC_NAMES,
|
||||
)
|
||||
from .core import calculate_roles_for_user, create_bot_client
|
||||
from .core import group_to_role as core_group_to_role
|
||||
from .core import server_name as core_server_name
|
||||
from .core import user_formatted_nick
|
||||
from .discord_client import (
|
||||
DISCORD_OAUTH_BASE_URL,
|
||||
DISCORD_OAUTH_TOKEN_URL,
|
||||
DiscordApiBackoff,
|
||||
DiscordClient,
|
||||
)
|
||||
from .discord_client import DiscordClient
|
||||
from .discord_client.exceptions import DiscordClientException, DiscordApiBackoff
|
||||
from .discord_client.helpers import match_or_create_roles_from_names
|
||||
from .utils import LoggerAddTag
|
||||
|
||||
|
||||
logger = LoggerAddTag(logging.getLogger(__name__), __title__)
|
||||
|
||||
|
||||
@@ -56,79 +59,68 @@ class DiscordUserManager(models.Manager):
|
||||
Returns: True on success, else False or raises exception
|
||||
"""
|
||||
try:
|
||||
nickname = self.user_formatted_nick(user) if DISCORD_SYNC_NAMES else None
|
||||
group_names = self.user_group_names(user)
|
||||
nickname = user_formatted_nick(user) if DISCORD_SYNC_NAMES else None
|
||||
access_token = self._exchange_auth_code_for_token(authorization_code)
|
||||
user_client = DiscordClient(access_token, is_rate_limited=is_rate_limited)
|
||||
discord_user = user_client.current_user()
|
||||
user_id = discord_user['id']
|
||||
bot_client = self._bot_client(is_rate_limited=is_rate_limited)
|
||||
|
||||
if group_names:
|
||||
role_ids = match_or_create_roles_from_names(
|
||||
client=bot_client,
|
||||
guild_id=DISCORD_GUILD_ID,
|
||||
role_names=group_names
|
||||
).ids()
|
||||
else:
|
||||
role_ids = None
|
||||
|
||||
created = bot_client.add_guild_member(
|
||||
guild_id=DISCORD_GUILD_ID,
|
||||
user_id=user_id,
|
||||
access_token=access_token,
|
||||
role_ids=role_ids,
|
||||
nick=nickname
|
||||
bot_client = create_bot_client(is_rate_limited=is_rate_limited)
|
||||
roles, changed = calculate_roles_for_user(
|
||||
user=user, client=bot_client, discord_uid=discord_user.id
|
||||
)
|
||||
if created is not False:
|
||||
if created is None:
|
||||
logger.debug(
|
||||
"User %s with Discord ID %s is already a member. Forcing a Refresh",
|
||||
if changed is None:
|
||||
# Handle new member
|
||||
created = bot_client.add_guild_member(
|
||||
guild_id=DISCORD_GUILD_ID,
|
||||
user_id=discord_user.id,
|
||||
access_token=access_token,
|
||||
role_ids=list(roles.ids()),
|
||||
nick=nickname
|
||||
)
|
||||
if not created:
|
||||
logger.warning(
|
||||
"Failed to add user %s with Discord ID %s to Discord server",
|
||||
user,
|
||||
user_id,
|
||||
discord_user.id,
|
||||
)
|
||||
|
||||
# Force an update cause the discord API won't do it for us.
|
||||
if role_ids:
|
||||
role_ids = list(role_ids)
|
||||
|
||||
updated = bot_client.modify_guild_member(
|
||||
guild_id=DISCORD_GUILD_ID,
|
||||
user_id=user_id,
|
||||
role_ids=role_ids,
|
||||
nick=nickname
|
||||
)
|
||||
|
||||
if not updated:
|
||||
# Could not update the new user so fail.
|
||||
logger.warning(
|
||||
"Failed to add user %s with Discord ID %s to Discord server",
|
||||
user,
|
||||
user_id,
|
||||
)
|
||||
return False
|
||||
|
||||
self.update_or_create(
|
||||
user=user,
|
||||
defaults={
|
||||
'uid': user_id,
|
||||
'username': discord_user['username'][:32],
|
||||
'discriminator': discord_user['discriminator'][:4],
|
||||
'activated': now()
|
||||
}
|
||||
)
|
||||
logger.info(
|
||||
"Added user %s with Discord ID %s to Discord server", user, user_id
|
||||
)
|
||||
return True
|
||||
|
||||
return False
|
||||
else:
|
||||
logger.warning(
|
||||
"Failed to add user %s with Discord ID %s to Discord server",
|
||||
# Handle existing member
|
||||
logger.debug(
|
||||
"User %s with Discord ID %s is already a member. Forcing a Refresh",
|
||||
user,
|
||||
user_id,
|
||||
discord_user.id,
|
||||
)
|
||||
return False
|
||||
# Force an update cause the discord API won't do it for us.
|
||||
updated = bot_client.modify_guild_member(
|
||||
guild_id=DISCORD_GUILD_ID,
|
||||
user_id=discord_user.id,
|
||||
role_ids=list(roles.ids()),
|
||||
nick=nickname
|
||||
)
|
||||
if not updated:
|
||||
# Could not update the new user so fail.
|
||||
logger.warning(
|
||||
"Failed to add user %s with Discord ID %s to Discord server",
|
||||
user,
|
||||
discord_user.id,
|
||||
)
|
||||
return False
|
||||
|
||||
self.update_or_create(
|
||||
user=user,
|
||||
defaults={
|
||||
'uid': discord_user.id,
|
||||
'username': discord_user.username[:32],
|
||||
'discriminator': discord_user.discriminator[:4],
|
||||
'activated': now()
|
||||
}
|
||||
)
|
||||
logger.info(
|
||||
"Added user %s with Discord ID %s to Discord server",
|
||||
user,
|
||||
discord_user.id
|
||||
)
|
||||
return True
|
||||
|
||||
except (HTTPError, ConnectionError, DiscordApiBackoff) as ex:
|
||||
logger.exception(
|
||||
@@ -136,31 +128,6 @@ class DiscordUserManager(models.Manager):
|
||||
)
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def user_formatted_nick(user: User) -> str:
|
||||
"""returns the name of the given users main character with name formatting
|
||||
or None if user has no main
|
||||
"""
|
||||
from .auth_hooks import DiscordService
|
||||
|
||||
if user.profile.main_character:
|
||||
return NameFormatter(DiscordService(), user).format_name()
|
||||
else:
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def user_group_names(user: User, state_name: str = None) -> list:
|
||||
"""returns list of group names plus state the given user is a member of"""
|
||||
if not state_name:
|
||||
state_name = user.profile.state.name
|
||||
group_names = (
|
||||
[group.name for group in user.groups.all()] + [state_name]
|
||||
)
|
||||
logger.debug(
|
||||
"Group names for roles updates of user %s are: %s", user, group_names
|
||||
)
|
||||
return group_names
|
||||
|
||||
def user_has_account(self, user: User) -> bool:
|
||||
"""Returns True if the user has an Discord account, else False
|
||||
|
||||
@@ -178,60 +145,41 @@ class DiscordUserManager(models.Manager):
|
||||
'permissions': str(cls.BOT_PERMISSIONS)
|
||||
|
||||
})
|
||||
return f'{DiscordClient.OAUTH_BASE_URL}?{params}'
|
||||
return f'{DISCORD_OAUTH_BASE_URL}?{params}'
|
||||
|
||||
@classmethod
|
||||
def generate_oauth_redirect_url(cls) -> str:
|
||||
oauth = OAuth2Session(
|
||||
DISCORD_APP_ID, redirect_uri=DISCORD_CALLBACK_URL, scope=cls.SCOPES
|
||||
)
|
||||
url, state = oauth.authorization_url(DiscordClient.OAUTH_BASE_URL)
|
||||
url, _ = oauth.authorization_url(DISCORD_OAUTH_BASE_URL)
|
||||
return url
|
||||
|
||||
@staticmethod
|
||||
def _exchange_auth_code_for_token(authorization_code: str) -> str:
|
||||
oauth = OAuth2Session(DISCORD_APP_ID, redirect_uri=DISCORD_CALLBACK_URL)
|
||||
token = oauth.fetch_token(
|
||||
DiscordClient.OAUTH_TOKEN_URL,
|
||||
DISCORD_OAUTH_TOKEN_URL,
|
||||
client_secret=DISCORD_APP_SECRET,
|
||||
code=authorization_code
|
||||
)
|
||||
logger.debug("Received token from OAuth")
|
||||
return token['access_token']
|
||||
|
||||
@classmethod
|
||||
def server_name(cls, use_cache: bool = True) -> str:
|
||||
"""returns the name of the current Discord server
|
||||
or an empty string if the name could not be retrieved
|
||||
@staticmethod
|
||||
def group_to_role(group: Group) -> dict:
|
||||
"""Fetch the Discord role matching the given Django group by name.
|
||||
|
||||
Params:
|
||||
- use_cache: When set False will force an API call to get the server name
|
||||
Returns:
|
||||
- Discord role as dict
|
||||
- empty dict if no matching role found
|
||||
"""
|
||||
try:
|
||||
server_name = cls._bot_client().guild_name(
|
||||
guild_id=DISCORD_GUILD_ID, use_cache=use_cache
|
||||
)
|
||||
except (HTTPError, DiscordClientException):
|
||||
server_name = ""
|
||||
except Exception:
|
||||
logger.warning(
|
||||
"Unexpected error when trying to retrieve the server name from Discord",
|
||||
exc_info=True
|
||||
)
|
||||
server_name = ""
|
||||
|
||||
return server_name
|
||||
|
||||
@classmethod
|
||||
def group_to_role(cls, group: Group) -> dict:
|
||||
"""returns the Discord role matching the given Django group by name
|
||||
or an empty dict() if no matching role exist
|
||||
"""
|
||||
return cls._bot_client().match_role_from_name(
|
||||
guild_id=DISCORD_GUILD_ID, role_name=group.name
|
||||
)
|
||||
role = core_group_to_role(group)
|
||||
return role.asdict() if role else dict()
|
||||
|
||||
@staticmethod
|
||||
def _bot_client(is_rate_limited: bool = True) -> DiscordClient:
|
||||
"""returns a bot client for access to the Discord API"""
|
||||
return DiscordClient(DISCORD_BOT_TOKEN, is_rate_limited=is_rate_limited)
|
||||
def server_name(use_cache: bool = True) -> str:
|
||||
"""Fetches the name of the current Discord server.
|
||||
This method is kept to ensure backwards compatibility of this API.
|
||||
"""
|
||||
return core_server_name(use_cache)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from requests.exceptions import HTTPError
|
||||
|
||||
@@ -6,13 +7,17 @@ from django.contrib.auth.models import User
|
||||
from django.db import models
|
||||
from django.utils.translation import gettext_lazy
|
||||
|
||||
from allianceauth.groupmanagement.models import ReservedGroupName
|
||||
from allianceauth.notifications import notify
|
||||
|
||||
from . import __title__
|
||||
from .app_settings import DISCORD_GUILD_ID
|
||||
from .discord_client import DiscordApiBackoff, DiscordClient, DiscordRoles
|
||||
from .discord_client.helpers import match_or_create_roles_from_names
|
||||
from .core import (
|
||||
create_bot_client,
|
||||
default_bot_client,
|
||||
calculate_roles_for_user,
|
||||
user_formatted_nick
|
||||
)
|
||||
from .discord_client import DiscordApiBackoff
|
||||
from .managers import DiscordUserManager
|
||||
from .utils import LoggerAddTag
|
||||
|
||||
@@ -21,14 +26,13 @@ logger = LoggerAddTag(logging.getLogger(__name__), __title__)
|
||||
|
||||
|
||||
class DiscordUser(models.Model):
|
||||
|
||||
USER_RELATED_NAME = 'discord'
|
||||
"""The Discord user account of an Auth user."""
|
||||
|
||||
user = models.OneToOneField(
|
||||
User,
|
||||
primary_key=True,
|
||||
on_delete=models.CASCADE,
|
||||
related_name=USER_RELATED_NAME,
|
||||
related_name='discord',
|
||||
help_text='Auth user owning this Discord account'
|
||||
)
|
||||
uid = models.BigIntegerField(
|
||||
@@ -80,24 +84,21 @@ class DiscordUser(models.Model):
|
||||
- False on error or raises exception
|
||||
"""
|
||||
if not nickname:
|
||||
nickname = DiscordUser.objects.user_formatted_nick(self.user)
|
||||
if nickname:
|
||||
client = DiscordUser.objects._bot_client()
|
||||
success = client.modify_guild_member(
|
||||
guild_id=DISCORD_GUILD_ID,
|
||||
user_id=self.uid,
|
||||
nick=nickname
|
||||
)
|
||||
if success:
|
||||
logger.info('Nickname for %s has been updated', self.user)
|
||||
else:
|
||||
logger.warning('Failed to update nickname for %s', self.user)
|
||||
return success
|
||||
|
||||
else:
|
||||
nickname = user_formatted_nick(self.user)
|
||||
if not nickname:
|
||||
return False
|
||||
success = default_bot_client.modify_guild_member(
|
||||
guild_id=DISCORD_GUILD_ID,
|
||||
user_id=self.uid,
|
||||
nick=nickname
|
||||
)
|
||||
if success:
|
||||
logger.info('Nickname for %s has been updated', self.user)
|
||||
else:
|
||||
logger.warning('Failed to update nickname for %s', self.user)
|
||||
return success
|
||||
|
||||
def update_groups(self, state_name: str = None) -> bool:
|
||||
def update_groups(self, state_name: str = None) -> Optional[bool]:
|
||||
"""update groups for a user based on his current group memberships.
|
||||
Will add or remove roles of a user as needed.
|
||||
|
||||
@@ -109,57 +110,18 @@ class DiscordUser(models.Model):
|
||||
- None if user is no longer a member of the Discord server
|
||||
- False on error or raises exception
|
||||
"""
|
||||
client = DiscordUser.objects._bot_client()
|
||||
member_roles = self._determine_member_roles(client)
|
||||
if member_roles is None:
|
||||
new_roles, is_changed = calculate_roles_for_user(
|
||||
user=self.user,
|
||||
client=default_bot_client,
|
||||
discord_uid=self.uid,
|
||||
state_name=state_name
|
||||
)
|
||||
if is_changed is None:
|
||||
logger.debug('User is not a member of this guild %s', self.user)
|
||||
return None
|
||||
return self._update_roles_if_needed(client, state_name, member_roles)
|
||||
|
||||
def _determine_member_roles(self, client: DiscordClient) -> DiscordRoles:
|
||||
"""Determine the roles of the current member / user."""
|
||||
member_info = client.guild_member(guild_id=DISCORD_GUILD_ID, user_id=self.uid)
|
||||
if member_info is None:
|
||||
return None # User is no longer a member
|
||||
guild_roles = DiscordRoles(client.guild_roles(guild_id=DISCORD_GUILD_ID))
|
||||
logger.debug('Current guild roles: %s', guild_roles.ids())
|
||||
if 'roles' in member_info:
|
||||
if not guild_roles.has_roles(member_info['roles']):
|
||||
guild_roles = DiscordRoles(
|
||||
client.guild_roles(guild_id=DISCORD_GUILD_ID, use_cache=False)
|
||||
)
|
||||
if not guild_roles.has_roles(member_info['roles']):
|
||||
raise RuntimeError(
|
||||
'Member {} has unknown roles: {}'.format(
|
||||
self.user,
|
||||
set(member_info['roles']).difference(guild_roles.ids())
|
||||
)
|
||||
)
|
||||
return guild_roles.subset(member_info['roles'])
|
||||
raise RuntimeError('member_info from %s is not valid' % self.user)
|
||||
|
||||
def _update_roles_if_needed(
|
||||
self, client: DiscordClient, state_name: str, member_roles: DiscordRoles
|
||||
) -> bool:
|
||||
"""Update the roles of this member/user if needed."""
|
||||
requested_roles = match_or_create_roles_from_names(
|
||||
client=client,
|
||||
guild_id=DISCORD_GUILD_ID,
|
||||
role_names=DiscordUser.objects.user_group_names(
|
||||
user=self.user, state_name=state_name
|
||||
)
|
||||
)
|
||||
logger.debug(
|
||||
'Requested roles for user %s: %s', self.user, requested_roles.ids()
|
||||
)
|
||||
logger.debug('Current roles user %s: %s', self.user, member_roles.ids())
|
||||
reserved_role_names = ReservedGroupName.objects.values_list("name", flat=True)
|
||||
member_roles_reserved = member_roles.subset(role_names=reserved_role_names)
|
||||
member_roles_managed = member_roles.subset(managed_only=True)
|
||||
member_roles_persistent = member_roles_managed.union(member_roles_reserved)
|
||||
if requested_roles != member_roles.difference(member_roles_persistent):
|
||||
if is_changed:
|
||||
logger.debug('Need to update roles for user %s', self.user)
|
||||
new_roles = requested_roles.union(member_roles_persistent)
|
||||
success = client.modify_guild_member(
|
||||
success = default_bot_client.modify_guild_member(
|
||||
guild_id=DISCORD_GUILD_ID,
|
||||
user_id=self.uid,
|
||||
role_ids=list(new_roles.ids())
|
||||
@@ -172,41 +134,32 @@ class DiscordUser(models.Model):
|
||||
logger.info('No need to update roles for user %s', self.user)
|
||||
return True
|
||||
|
||||
def update_username(self) -> bool:
|
||||
def update_username(self) -> Optional[bool]:
|
||||
"""Updates the username incl. the discriminator
|
||||
from the Discord server and saves it
|
||||
|
||||
Returns:
|
||||
- True on success
|
||||
- None if user is no longer a member of the Discord server
|
||||
- False on error or raises exception
|
||||
"""
|
||||
client = DiscordUser.objects._bot_client()
|
||||
user_info = client.guild_member(guild_id=DISCORD_GUILD_ID, user_id=self.uid)
|
||||
if user_info is None:
|
||||
success = None
|
||||
elif (
|
||||
user_info
|
||||
and 'user' in user_info
|
||||
and 'username' in user_info['user']
|
||||
and 'discriminator' in user_info['user']
|
||||
):
|
||||
self.username = user_info['user']['username']
|
||||
self.discriminator = user_info['user']['discriminator']
|
||||
self.save()
|
||||
logger.info('Username for %s has been updated', self.user)
|
||||
success = True
|
||||
else:
|
||||
logger.warning('Failed to update username for %s', self.user)
|
||||
success = False
|
||||
return success
|
||||
member_info = default_bot_client.guild_member(
|
||||
guild_id=DISCORD_GUILD_ID, user_id=self.uid
|
||||
)
|
||||
if not member_info:
|
||||
logger.warning('%s: User not a guild member', self.user)
|
||||
return None
|
||||
self.username = member_info.user.username
|
||||
self.discriminator = member_info.user.discriminator
|
||||
self.save()
|
||||
logger.info('%s: Username has been updated', self.user)
|
||||
return True
|
||||
|
||||
def delete_user(
|
||||
self,
|
||||
notify_user: bool = False,
|
||||
is_rate_limited: bool = True,
|
||||
handle_api_exceptions: bool = False
|
||||
) -> bool:
|
||||
) -> Optional[bool]:
|
||||
"""Deletes the Discount user both on the server and locally
|
||||
|
||||
Params:
|
||||
@@ -221,7 +174,7 @@ class DiscordUser(models.Model):
|
||||
"""
|
||||
try:
|
||||
_user = self.user
|
||||
client = DiscordUser.objects._bot_client(is_rate_limited=is_rate_limited)
|
||||
client = create_bot_client(is_rate_limited=is_rate_limited)
|
||||
success = client.remove_guild_member(
|
||||
guild_id=DISCORD_GUILD_ID, user_id=self.uid
|
||||
)
|
||||
@@ -241,15 +194,13 @@ class DiscordUser(models.Model):
|
||||
)
|
||||
logger.info('Account for user %s was deleted.', _user)
|
||||
return True
|
||||
else:
|
||||
logger.debug('Account for user %s was already deleted.', _user)
|
||||
return None
|
||||
logger.debug('Account for user %s was already deleted.', _user)
|
||||
return None
|
||||
|
||||
else:
|
||||
logger.warning(
|
||||
'Failed to remove user %s from the Discord server', _user
|
||||
)
|
||||
return False
|
||||
logger.warning(
|
||||
'Failed to remove user %s from the Discord server', _user
|
||||
)
|
||||
return False
|
||||
|
||||
except (HTTPError, ConnectionError, DiscordApiBackoff) as ex:
|
||||
if handle_api_exceptions:
|
||||
@@ -257,5 +208,4 @@ class DiscordUser(models.Model):
|
||||
'Failed to remove user %s from Discord server: %s',self.user, ex
|
||||
)
|
||||
return False
|
||||
else:
|
||||
raise ex
|
||||
raise ex
|
||||
|
||||
@@ -1,19 +1,6 @@
|
||||
from django.contrib.auth.models import Group
|
||||
|
||||
from allianceauth.tests.auth_utils import AuthUtils
|
||||
from ..discord_client.tests import ( # noqa
|
||||
TEST_GUILD_ID,
|
||||
TEST_USER_ID,
|
||||
TEST_USER_NAME,
|
||||
TEST_USER_DISCRIMINATOR,
|
||||
create_role,
|
||||
ROLE_ALPHA,
|
||||
ROLE_BRAVO,
|
||||
ROLE_CHARLIE,
|
||||
ROLE_CHARLIE_2,
|
||||
ROLE_MIKE,
|
||||
ALL_ROLES,
|
||||
create_user_info
|
||||
)
|
||||
|
||||
DEFAULT_AUTH_GROUP = 'Member'
|
||||
MODULE_PATH = 'allianceauth.services.modules.discord'
|
||||
|
||||
31
allianceauth/services/modules/discord/tests/factories.py
Normal file
31
allianceauth/services/modules/discord/tests/factories.py
Normal file
@@ -0,0 +1,31 @@
|
||||
from django.utils.timezone import now
|
||||
|
||||
from allianceauth.authentication.backends import StateBackend
|
||||
from allianceauth.tests.auth_utils import AuthUtils
|
||||
|
||||
from ..discord_client.tests.factories import (
|
||||
TEST_USER_DISCRIMINATOR,
|
||||
TEST_USER_ID,
|
||||
TEST_USER_NAME,
|
||||
)
|
||||
from ..models import DiscordUser
|
||||
|
||||
|
||||
def create_user(**kwargs):
|
||||
params = {"username": TEST_USER_NAME}
|
||||
params.update(kwargs)
|
||||
username = StateBackend.iterate_username(params["username"])
|
||||
user = AuthUtils.create_user(username)
|
||||
return AuthUtils.add_permission_to_user_by_name("discord.access_discord", user)
|
||||
|
||||
|
||||
def create_discord_user(user=None, **kwargs):
|
||||
params = {
|
||||
"user": user or create_user(),
|
||||
"uid": TEST_USER_ID,
|
||||
"username": TEST_USER_NAME,
|
||||
"discriminator": TEST_USER_DISCRIMINATOR,
|
||||
"activated": now(),
|
||||
}
|
||||
params.update(kwargs)
|
||||
return DiscordUser.objects.create(**params)
|
||||
@@ -1,26 +1,32 @@
|
||||
from django.test import TestCase, RequestFactory
|
||||
from unittest.mock import patch
|
||||
|
||||
from django.contrib.admin.sites import AdminSite
|
||||
from django.contrib.auth.models import User
|
||||
from django.test import RequestFactory
|
||||
from django.utils.timezone import now
|
||||
|
||||
from allianceauth.authentication.models import CharacterOwnership
|
||||
from allianceauth.eveonline.models import (
|
||||
EveCharacter, EveCorporationInfo, EveAllianceInfo
|
||||
EveAllianceInfo,
|
||||
EveCharacter,
|
||||
EveCorporationInfo,
|
||||
)
|
||||
from allianceauth.utils.testing import NoSocketsTestCase
|
||||
|
||||
from ....admin import (
|
||||
MainAllianceFilter,
|
||||
MainCorporationsFilter,
|
||||
ServicesUserAdmin,
|
||||
user_main_organization,
|
||||
user_profile_pic,
|
||||
user_username,
|
||||
user_main_organization,
|
||||
ServicesUserAdmin,
|
||||
MainCorporationsFilter,
|
||||
MainAllianceFilter
|
||||
)
|
||||
from ..admin import DiscordUserAdmin
|
||||
from ..models import DiscordUser
|
||||
from . import MODULE_PATH
|
||||
|
||||
|
||||
class TestDataMixin(TestCase):
|
||||
class TestDataMixin(NoSocketsTestCase):
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
@@ -168,7 +174,7 @@ class TestDataMixin(TestCase):
|
||||
)
|
||||
|
||||
|
||||
class TestColumnRendering(TestDataMixin, TestCase):
|
||||
class TestColumnRendering(TestDataMixin, NoSocketsTestCase):
|
||||
|
||||
def test_user_profile_pic_u1(self):
|
||||
expected = (
|
||||
@@ -229,7 +235,7 @@ class TestColumnRendering(TestDataMixin, TestCase):
|
||||
# actions
|
||||
|
||||
|
||||
class TestFilters(TestDataMixin, TestCase):
|
||||
class TestFilters(TestDataMixin, NoSocketsTestCase):
|
||||
|
||||
def test_filter_main_corporations(self):
|
||||
|
||||
@@ -287,3 +293,16 @@ class TestFilters(TestDataMixin, TestCase):
|
||||
queryset = changelist.get_queryset(request)
|
||||
expected = [self.user_1.discord]
|
||||
self.assertSetEqual(set(queryset), set(expected))
|
||||
|
||||
|
||||
@patch(MODULE_PATH + ".admin.DiscordUser.delete_user")
|
||||
class TestDeleteQueryset(TestDataMixin, NoSocketsTestCase):
|
||||
def test_should_delete_all_objects(self, mock_delete_user):
|
||||
# given
|
||||
request = self.factory.get('/')
|
||||
request.user = self.user_1
|
||||
queryset = DiscordUser.objects.filter(user__in=[self.user_2, self.user_3])
|
||||
# when
|
||||
self.modeladmin.delete_queryset(request, queryset)
|
||||
# then
|
||||
self.assertEqual(mock_delete_user.call_count, 2)
|
||||
|
||||
16
allianceauth/services/modules/discord/tests/test_api.py
Normal file
16
allianceauth/services/modules/discord/tests/test_api.py
Normal file
@@ -0,0 +1,16 @@
|
||||
from unittest.mock import patch
|
||||
|
||||
from allianceauth.utils.testing import NoSocketsTestCase
|
||||
|
||||
from ..api import discord_guild_id
|
||||
from . import MODULE_PATH
|
||||
|
||||
|
||||
class TestDiscordGuildId(NoSocketsTestCase):
|
||||
@patch(MODULE_PATH + ".api.DISCORD_GUILD_ID", "123")
|
||||
def test_should_return_guild_id_when_configured(self):
|
||||
self.assertEqual(discord_guild_id(), 123)
|
||||
|
||||
@patch(MODULE_PATH + ".api.DISCORD_GUILD_ID", "")
|
||||
def test_should_return_none_when_not_configured(self):
|
||||
self.assertIsNone(discord_guild_id())
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user