nsarchive 3.0.0a8__py3-none-any.whl → 3.0.0b2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,11 @@
1
+ import json
1
2
  import requests
2
3
  import time
3
4
 
4
5
  from .base import NSID
5
6
 
7
+ from .. import errors
8
+
6
9
  # Votes
7
10
 
8
11
  class VoteOption:
@@ -18,10 +21,19 @@ class VoteOption:
18
21
  Nombre de sympathisants pour cette option
19
22
  """
20
23
 
21
- def __init__(self, id: str, title: str = None, count: int = 0):
22
- self.id = id
23
- self.title = title if title else id
24
- self.count = count
24
+ def __init__(self, title: str, count: int = 0):
25
+ self.title: str = title
26
+ self.count: int = count
27
+
28
+ def __repr__(self) -> dict:
29
+ return json.dumps({
30
+ 'title': self.title,
31
+ 'count': self.count
32
+ })
33
+
34
+ def _load(self, _data: dict):
35
+ self.title = str(_data['title'])
36
+ self.count = int(_data['count'])
25
37
 
26
38
  class Vote:
27
39
  """
@@ -32,7 +44,7 @@ class Vote:
32
44
  Identifiant du vote
33
45
  - title: `str`\n
34
46
  Titre du vote
35
- - options: list[.VoteOption]\n
47
+ - options: dict[str, .VoteOption]\n
36
48
  Liste des choix disponibles
37
49
  - author: `NSID`\n
38
50
  Identifiant de l'auteur du vote
@@ -53,31 +65,29 @@ class Vote:
53
65
  self.startDate: int = round(time.time())
54
66
  self.endDate: int = 0
55
67
 
56
- self.options: list[VoteOption] = []
68
+ self.options: dict[str, VoteOption] = {}
57
69
 
58
70
  def _load(self, _data: dict, url: str, headers: dict) -> None:
59
- self._url = url + '/votes/' + _data['id']
71
+ self._url = url
60
72
  self._headers = headers
61
73
 
62
74
  self.id = NSID(_data['id'])
63
75
  self.title = _data['title']
64
- self.author = _data['author_id']
76
+ self.author = _data['author']
65
77
 
66
- self.startDate = _data['start_date']
67
- self.endDate = _data['end_date']
78
+ self.startDate = _data['start']
79
+ self.endDate = _data['end']
68
80
 
69
- self.options = []
81
+ self.options = {}
70
82
 
71
- for opt in _data['options']:
72
- option = VoteOption(opt["id"], opt["title"])
73
- option.count = opt["count"]
83
+ for _opt_id, opt in _data['options'].items():
84
+ option = VoteOption(*tuple(opt.values()))
74
85
 
75
- self.options.append(option)
86
+ self.options[_opt_id] = option
76
87
 
77
88
  def get(self, id: str) -> VoteOption:
78
- for opt in self.options:
79
- if opt.id == id:
80
- return opt
89
+ if id in self.options.keys():
90
+ return self.options[id]
81
91
  else:
82
92
  raise ValueError(f"Option {id} not found in vote {self.id}")
83
93
 
@@ -86,17 +96,31 @@ class Vote:
86
96
  Ajoute un vote à l'option spécifiée
87
97
  """
88
98
 
89
- res = requests.post(f"{self._url}/vote?choice={id}", headers = self._headers)
99
+ res = requests.post(f"{self._url}/vote?option={id}", headers = self._headers)
90
100
 
91
101
  if res.status_code == 200:
92
- for opt in self.options:
93
- if opt.id == id:
94
- opt.count += 1
95
- break
96
- else:
97
- raise ValueError(f"Option {id} not found in vote {self.id}")
98
- else:
99
- res.raise_for_status()
102
+ self.get(id).count += 1
103
+ elif 500 <= res.status_code < 600:
104
+ raise errors.globals.ServerDownError()
105
+
106
+ _data = res.json()
107
+
108
+ if res.status_code == 400:
109
+ if _data['message'] == "MissingParam":
110
+ raise errors.globals.MissingParamError(f"Missing parameter '{_data['param']}'.")
111
+ elif _data['message'] == "InvalidParam":
112
+ raise errors.globals.InvalidParamError(f"Invalid parameter '{_data['param']}'.")
113
+ elif _data['message'] == "InvalidToken":
114
+ raise errors.globals.AuthError("Token is not valid.")
115
+
116
+ elif res.status_code == 401:
117
+ raise errors.globals.AuthError(_data['message'])
118
+
119
+ elif res.status_code == 403:
120
+ raise errors.globals.PermissionError(_data['message'])
121
+
122
+ elif res.status_code == 404:
123
+ raise errors.globals.NotFoundError(_data['message'])
100
124
 
101
125
  def close(self):
102
126
  """
@@ -107,8 +131,27 @@ class Vote:
107
131
 
108
132
  if res.status_code == 200:
109
133
  self.endDate = round(time.time())
110
- else:
111
- res.raise_for_status()
134
+ elif 500 <= res.status_code < 600:
135
+ raise errors.globals.ServerDownError()
136
+
137
+ _data = res.json()
138
+
139
+ if res.status_code == 400:
140
+ if _data['message'] == "MissingParam":
141
+ raise errors.globals.MissingParamError(f"Missing parameter '{_data['param']}'.")
142
+ elif _data['message'] == "InvalidParam":
143
+ raise errors.globals.InvalidParamError(f"Invalid parameter '{_data['param']}'.")
144
+ elif _data['message'] == "InvalidToken":
145
+ raise errors.globals.AuthError("Token is not valid.")
146
+
147
+ elif res.status_code == 401:
148
+ raise errors.globals.AuthError(_data['message'])
149
+
150
+ elif res.status_code == 403:
151
+ raise errors.globals.PermissionError(_data['message'])
152
+
153
+ elif res.status_code == 404:
154
+ raise errors.globals.NotFoundError(_data['message'])
112
155
 
113
156
  class LawsuitVote(Vote):
114
157
  """
nsarchive/models/state.py CHANGED
@@ -1,7 +1,10 @@
1
+ from __future__ import annotations
2
+
1
3
  import requests
2
4
 
3
5
  from .base import NSID
4
6
  from .republic import Vote
7
+ from .. import errors
5
8
 
6
9
  class Party:
7
10
  def __init__(self, org_id: NSID):
@@ -13,7 +16,7 @@ class Party:
13
16
  self.color: int = 0x000000
14
17
  self.motto: str = None
15
18
  self.scale: dict = {}
16
- self.last_elected: int = None
19
+ self.last_election: int = None
17
20
 
18
21
  def _load(self, _data: dict, url: str = None, headers: dict = None):
19
22
  self._url = url
@@ -24,7 +27,10 @@ class Party:
24
27
  self.color = _data['color']
25
28
  self.motto = _data['motto']
26
29
  self.scale = _data['politiscales']
27
- self.last_elected = _data['last_elected']
30
+ self.last_election = _data['last_election']
31
+
32
+ def cancel_candidacy(self, election: Election):
33
+ election.cancel_candidacy()
28
34
 
29
35
  class Election:
30
36
  def __init__(self, id: NSID):
@@ -35,25 +41,74 @@ class Election:
35
41
  self.type: str = 'full' # Partial = législatives, full = totales
36
42
  self.vote: Vote = None
37
43
 
38
- self.add_vote = self.vote.add_vote
39
- self.close = self.vote.close
40
-
41
44
  def _load(self, _data: dict, url: str = None, headers: str = None):
42
45
  self._url = url
43
46
  self._headers = headers
44
47
 
45
48
  self.id = _data['id']
46
49
  self.type = _data['type']
50
+
51
+ self.vote = Vote(_data['vote']['id'])
47
52
  self.vote._load(_data['vote'], url, headers)
48
53
 
54
+ def close(self):
55
+ if self.vote:
56
+ self.vote.close()
57
+ else:
58
+ return
59
+
60
+ def add_vote(self, id: str):
61
+ if self.vote:
62
+ self.vote.add_vote(id)
63
+ else:
64
+ return
65
+
49
66
  def submit_candidacy(self):
50
67
  res = requests.put(f"{self._url}/submit")
51
68
 
52
- if res.status_code != 200:
53
- res.raise_for_status()
69
+ if 500 <= res.status_code < 600:
70
+ raise errors.globals.ServerDownError()
71
+
72
+ _data = res.json()
73
+
74
+ if res.status_code == 400:
75
+ if _data['message'] == "MissingParam":
76
+ raise errors.globals.MissingParamError(f"Missing parameter '{_data['param']}'.")
77
+ elif _data['message'] == "InvalidParam":
78
+ raise errors.globals.InvalidParamError(f"Invalid parameter '{_data['param']}'.")
79
+ elif _data['message'] == "InvalidToken":
80
+ raise errors.globals.AuthError("Token is not valid.")
81
+
82
+ elif res.status_code == 401:
83
+ raise errors.globals.AuthError(_data['message'])
84
+
85
+ elif res.status_code == 403:
86
+ raise errors.globals.PermissionError(_data['message'])
87
+
88
+ elif res.status_code == 404:
89
+ raise errors.globals.NotFoundError(_data['message'])
54
90
 
55
91
  def cancel_candidacy(self):
56
92
  res = requests.put(f"{self._url}/cancel_candidacy")
57
93
 
58
- if res.status_code != 200:
59
- res.raise_for_status()
94
+ if 500 <= res.status_code < 600:
95
+ raise errors.globals.ServerDownError()
96
+
97
+ _data = res.json()
98
+
99
+ if res.status_code == 400:
100
+ if _data['message'] == "MissingParam":
101
+ raise errors.globals.MissingParamError(f"Missing parameter '{_data['param']}'.")
102
+ elif _data['message'] == "InvalidParam":
103
+ raise errors.globals.InvalidParamError(f"Invalid parameter '{_data['param']}'.")
104
+ elif _data['message'] == "InvalidToken":
105
+ raise errors.globals.AuthError("Token is not valid.")
106
+
107
+ elif res.status_code == 401:
108
+ raise errors.globals.AuthError(_data['message'])
109
+
110
+ elif res.status_code == 403:
111
+ raise errors.globals.PermissionError(_data['message'])
112
+
113
+ elif res.status_code == 404:
114
+ raise errors.globals.NotFoundError(_data['message'])
@@ -0,0 +1,90 @@
1
+ Metadata-Version: 2.3
2
+ Name: nsarchive
3
+ Version: 3.0.0b2
4
+ Summary: API-wrapper pour récupérer des données liées à Nation
5
+ License: GPL-3.0
6
+ Author: happex
7
+ Author-email: 110610727+okayhappex@users.noreply.github.com
8
+ Requires-Python: >=3.10,<4.0
9
+ Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Requires-Dist: pillow (>=10.4,<11.0)
16
+ Requires-Dist: requests (>=2.31,<3.0)
17
+ Description-Content-Type: text/markdown
18
+
19
+ # NSArchive v3
20
+
21
+ ## Pré-requis
22
+
23
+ - Python 3.10 ou + (Python 3.13 si possible)
24
+ - Un serveur avec [nation.db](https://github.com/1nserv/nation-db)
25
+ - Deux barres de Twix ou une tasse de thé
26
+
27
+
28
+ ## Avant de démarrer
29
+
30
+ Dans la documentation, vous croiserez souvent des noms de classes comme `.User` ou autres similaires. Le «.» devant le nom de la classe signfie qu'elle appartient au module NSAv3, et qu'il faut donc les interprêter comme `nsarchive.User`. La seule exception est `NSID` qui ne sera pas précédé d'un point mais devra être interprêté de la même manière.
31
+
32
+
33
+ ## Installation
34
+
35
+ L'installation de NSAv3 se fait via pip:
36
+
37
+ ```sh
38
+ pip install nsarchive
39
+ ```
40
+
41
+ La dernière version de nsarchive devrait s'installer. Les dépendances requises pour nsarchive sont `pillow` et `requests` mais celles-ci devraient s'installer en même temps que le module. Vous pourriez également avoir besoin des modules `bcrypt` et `python-dotenv`, ceux-ci devront être installés manuellement.
42
+
43
+
44
+ ### Bonus: Environnement virtuel
45
+
46
+ Il est recommandé mais non obligatoire d'avoir un environnement virtuel (venv) pour votre projet. Sa création se fait comme ceci:
47
+
48
+ ```sh
49
+ python -m venv .venv
50
+ ```
51
+
52
+ N'oubliez pas de l'activer via cette commande pour powershell...
53
+
54
+ ```ps1
55
+ .venv\Scripts\Activate
56
+ ```
57
+
58
+ ...ou cette commande pour les terminaux type UNIX (Bash par exemple)
59
+
60
+ ```sh
61
+ source .venv/Scripts/Activate
62
+ ```
63
+
64
+ ## Prise en main
65
+
66
+ ### Identifier les objets
67
+
68
+ Les objets sont tous identifiables sur NSAv3. Ils ont un identifiant commun appelé NSID (`from nsarchive import NSID`). Cet identifiant n'est rien de plus qu'un nombre hexadécimal. Il peut être utilisé comme un string, dans un print ou un f-string par exemple. Cet identifiant est communément basé sur plusieurs valeurs fixes ou universelles, dont les deux plus fréquentes sont:
69
+ - L'ID Discord de l'objet concerné, dans le cas d'un utilisateur par exemple
70
+ - Le timestamp (secondes depuis 1970) du moment où il a été créé, dans le cas de la plupart des autres objets
71
+
72
+
73
+ ### Interfaces
74
+
75
+ Le module nsarchive est divisé en **4 interfaces**:
76
+ - [Entités](/docs/interfaces/entities.md) (membres, groupes, positions)
77
+ - [Économie](/docs/interfaces/economy.md) (comptes en banque, dettes)
78
+ - [Justice](/docs/interfaces/justice.md) (signalements, procès, sanctions)
79
+ - [État](/docs/interfaces/state.md) (votes, élections)
80
+
81
+ > Les interfaces État et Justice peuvent être confondues et désignées comme République, comme c'était le cas dans les versions précédentes.
82
+
83
+
84
+ Les interfaces ont toutes quatre rôles en commun:
85
+ - Vous authentifier
86
+ - Récupérer des objets
87
+ - Créer des objets
88
+ - Supprimer des objets (Entités uniquement)
89
+
90
+ Une documentation plus détaillée est disponible [ici](/docs/interfaces/README.md).
@@ -0,0 +1,21 @@
1
+ nsarchive/__init__.py,sha256=8Cssxv2lkW3eJStVoTg0y84_E7mPm0y4-oLe_nA42A0,877
2
+ nsarchive/assets/default_avatar.png,sha256=n-4vG_WPke8LvbY3ZU6oA-H-OtRoIu7woKnRq9DCIlI,51764
3
+ nsarchive/errors/__init__.py,sha256=rjyE5B4WmJI-_ILUtCP6wk4HhpmvLahkFTFyWwTlulw,33
4
+ nsarchive/errors/_globals.py,sha256=e3EvZ2HoCwfKbRkn7uYmqFkyE3013b4jkaZCvoAErkU,749
5
+ nsarchive/interfaces/_economy.py,sha256=wkmPvj3GVy7Et2Z-cJMQ9BBem1tKcIfeJmNaB03xspc,3072
6
+ nsarchive/interfaces/_entities.py,sha256=oPGkcnpXLOQfQpoqrvhjXhQq6nDCQ-nKwYSwnb1lze8,9384
7
+ nsarchive/interfaces/_justice.py,sha256=J8rLJ9STAax7uvnuMqwO0RdbzrsQcFzjUwkQaEEA1kU,8683
8
+ nsarchive/interfaces/_state.py,sha256=CYnwLO5Ihv27tc5-bn_w6y7SjMZG3kQsv3AfozP4nfw,10462
9
+ nsarchive/mandate.py,sha256=-CF6HMbDge2JYZIHT4WtAkUo6Cvc5WrsYhbrdKrriyA,2117
10
+ nsarchive/models/base.py,sha256=Hl19C00pXD76KwcUsbfqZDxMfGghLxEAYTBSLUG_l34,10464
11
+ nsarchive/models/economy.py,sha256=EkGfwWlvNlF8Ho9oOYS-eXybiHjsmqBoJxNObeOMRPE,6715
12
+ nsarchive/models/entities.py,sha256=OQPgaqybw7dr1lbNplV-EsWqZH4MwBfYTWtI_Yt8ulo,27412
13
+ nsarchive/models/justice.py,sha256=aHlDQ04agLJDSr13NXq-0RUaICM3_ZUok3mtEGPXbPY,4301
14
+ nsarchive/models/republic.py,sha256=CRpZQEKM-nx_DFy1r0QPK3u9xTNQ7sdOsKw2zb75J4o,4997
15
+ nsarchive/models/scale.py,sha256=ukh6wiE4mBcqbqtAC9GvCyTVUnwYUp3jla03Nohnsck,751
16
+ nsarchive/models/state.py,sha256=KhEv1F9g6RBvdfuw-uO3ruyuTfn9PGdeA1nMMABN2qU,3652
17
+ nsarchive/utils.py,sha256=L37Dm8aO0Sm3FDLPf2tP6fo-1lodDq7JIz-WXttNuJg,684
18
+ nsarchive-3.0.0b2.dist-info/LICENSE,sha256=aFLFZg6LEJFpTlNQ8su3__jw4GfV-xWBmC1cePkKZVw,35802
19
+ nsarchive-3.0.0b2.dist-info/METADATA,sha256=f3WgdYrnXXYpuk7Df-8MaeM2UffweQgo0rIfQrmsMsg,3457
20
+ nsarchive-3.0.0b2.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
21
+ nsarchive-3.0.0b2.dist-info/RECORD,,
@@ -1,21 +0,0 @@
1
- Metadata-Version: 2.3
2
- Name: nsarchive
3
- Version: 3.0.0a8
4
- Summary: API-wrapper pour récupérer des données liées à Nation
5
- License: GPL-3.0
6
- Author: happex
7
- Author-email: 110610727+okayhappex@users.noreply.github.com
8
- Requires-Python: >=3.10,<4.0
9
- Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
10
- Classifier: Programming Language :: Python :: 3
11
- Classifier: Programming Language :: Python :: 3.10
12
- Classifier: Programming Language :: Python :: 3.11
13
- Classifier: Programming Language :: Python :: 3.12
14
- Classifier: Programming Language :: Python :: 3.13
15
- Requires-Dist: pillow (>=10.4,<11.0)
16
- Requires-Dist: requests (>=2.31,<3.0)
17
- Description-Content-Type: text/markdown
18
-
19
- # NSArchive
20
-
21
- Documentation pas disponible pour l'instant
@@ -1,19 +0,0 @@
1
- nsarchive/__init__.py,sha256=QyFBy5jIe_cJBpTdNj-q_0nLqLfKoGC7m4D8LjCOpQo,823
2
- nsarchive/assets/default_avatar.png,sha256=n-4vG_WPke8LvbY3ZU6oA-H-OtRoIu7woKnRq9DCIlI,51764
3
- nsarchive/interfaces/_economy.py,sha256=54TpYKRw07HIryd3EDifA9Hs3s6O7aHcrtV4P8qY0QY,9348
4
- nsarchive/interfaces/_entities.py,sha256=FSFHtM2ygDGLWMU32zJej-BO2rVbrMYhxaJoXymdHMA,6480
5
- nsarchive/interfaces/_justice.py,sha256=perTRdhI7g7he2hcJ0kW9g8plt_BSHD8rMcR6FzBqG0,1382
6
- nsarchive/interfaces/_state.py,sha256=OCpSx4i_lqkJQ2FWZpFBKp2HIlwVCqsQOG42d8yCmO0,3747
7
- nsarchive/mandate.py,sha256=U0RE9Gpr3XawSWyr99X__GUoiwJAwKbOP4v_I2Z97Oc,1609
8
- nsarchive/models/base.py,sha256=yu04x3-vwPeda5R1DviHsDjP-44vIGZIpriX_c6czIY,8698
9
- nsarchive/models/economy.py,sha256=TA6QewVdhNYn4VuhsGaCkjSlJojDO59sgfLtCE5mgPE,7710
10
- nsarchive/models/entities.py,sha256=W6kXMsBlrIAfSOerRJEzVNtufHdNjXv2QNvXDwnVfTM,17426
11
- nsarchive/models/justice.py,sha256=kr3g3UqA7eexVqjiWSaT_O49NIJ84g_7z8vCXjTrLhA,3411
12
- nsarchive/models/republic.py,sha256=7KfNCzj6mNe389csKhHuTFqlAT60HeikhQbMWwPwnBk,3292
13
- nsarchive/models/scale.py,sha256=ukh6wiE4mBcqbqtAC9GvCyTVUnwYUp3jla03Nohnsck,751
14
- nsarchive/models/state.py,sha256=iP13C4IP0e0P-f1rkPwzTVe6j_QVM-ZRMDILlVVEUU8,1622
15
- nsarchive/utils.py,sha256=L37Dm8aO0Sm3FDLPf2tP6fo-1lodDq7JIz-WXttNuJg,684
16
- nsarchive-3.0.0a8.dist-info/LICENSE,sha256=aFLFZg6LEJFpTlNQ8su3__jw4GfV-xWBmC1cePkKZVw,35802
17
- nsarchive-3.0.0a8.dist-info/METADATA,sha256=A9g3R24rXcBYUFS2xVqptNBY9DwdyxOagaL7NyGyvG0,746
18
- nsarchive-3.0.0a8.dist-info/WHEEL,sha256=b4K_helf-jlQoXBBETfwnf4B04YC67LOev0jo4fX5m8,88
19
- nsarchive-3.0.0a8.dist-info/RECORD,,