-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathservices.py
More file actions
414 lines (356 loc) · 14.2 KB
/
services.py
File metadata and controls
414 lines (356 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
"""
Service layer for cppa_user_tracker.
All creates/updates/deletes for this app's models must go through functions in this
module. Do not call Model.objects.create(), model.save(), or model.delete() from
outside this module (e.g. from management commands, views, or other apps).
See CONTRIBUTING.md for the project-wide rule.
"""
from __future__ import annotations
from typing import Any, Optional, Protocol
from django.db import transaction
from django.db.models import Min
from .models import (
BaseProfile,
Email,
Identity,
TempProfileIdentityRelation,
TmpIdentity,
GitHubAccount,
GitHubAccountType,
MailingListProfile,
SlackUser,
DiscordProfile,
WG21PaperAuthorProfile,
YoutubeSpeaker,
)
# --- Identity ---
def create_identity(
display_name: str = "",
description: str = "",
) -> Identity:
"""Create an Identity. Returns the new Identity."""
return Identity.objects.create(
display_name=display_name,
description=description,
)
def get_or_create_identity(
display_name: str = "",
description: str = "",
defaults: Optional[dict[str, Any]] = None,
) -> tuple[Identity, bool]:
"""Get or create an Identity by display_name. If exists, updates description from defaults."""
lookup = {"display_name": display_name}
defaults = defaults or {"description": description}
identity, created = Identity.objects.get_or_create(defaults=defaults, **lookup)
if (
not created
and "description" in defaults
and identity.description != defaults["description"]
):
identity.description = defaults["description"]
identity.save(update_fields=["description"])
return identity, created
# --- TmpIdentity ---
def create_tmp_identity(
display_name: str = "",
description: str = "",
) -> TmpIdentity:
"""Create a TmpIdentity (staging). Returns the new TmpIdentity."""
return TmpIdentity.objects.create(
display_name=display_name,
description=description,
)
# --- TempProfileIdentityRelation (staging) ---
def add_temp_profile_identity_relation(
base_profile: BaseProfile,
target_identity: TmpIdentity,
) -> tuple[TempProfileIdentityRelation, bool]:
"""Link a BaseProfile to a TmpIdentity (staging). Returns (relation, created)."""
return TempProfileIdentityRelation.objects.get_or_create(
base_profile=base_profile,
target_identity=target_identity,
)
def remove_temp_profile_identity_relation(
base_profile: BaseProfile,
target_identity: TmpIdentity,
) -> None:
"""Remove the staging relation between base_profile and target_identity."""
TempProfileIdentityRelation.objects.filter(
base_profile=base_profile,
target_identity=target_identity,
).delete()
# --- Email ---
def add_email(
base_profile: BaseProfile,
email: str,
is_primary: bool = False,
is_active: bool = True,
) -> Email:
"""Add an email to a BaseProfile. Returns the new Email."""
return Email.objects.create(
base_profile=base_profile,
email=email,
is_primary=is_primary,
is_active=is_active,
)
def update_email(email_obj: Email, **kwargs: Any) -> Email:
"""Update an Email instance. Allowed keys: email, is_primary, is_active."""
for key in ("email", "is_primary", "is_active"):
if key in kwargs:
setattr(email_obj, key, kwargs[key])
email_obj.save()
return email_obj
def remove_email(email_obj: Email) -> None:
"""Remove an email from a profile."""
email_obj.delete()
def get_or_create_mailing_list_profile(
display_name: str = "",
email: str = "",
) -> tuple[MailingListProfile, bool]:
"""Get or create a MailingListProfile by display_name and email. Returns (profile, created).
Mailing list has no external id; we identify by display_name + email. Looks up a profile
that has this display_name and an Email with this address. If found, returns that profile.
Otherwise creates a new MailingListProfile, adds the email, and returns the new profile.
Raises ValueError if display_name or email is missing or empty after stripping.
"""
display_name_val = (display_name or "").strip()
email_val = (email or "").strip()
if not display_name_val:
raise ValueError("display_name must not be empty.")
profile = (
MailingListProfile.objects.filter(
display_name=display_name_val,
emails__email=email_val,
)
.distinct()
.first()
)
if profile is not None:
return profile, False
profile = MailingListProfile.objects.create(
display_name=display_name_val,
)
if email_val:
add_email(profile, email_val, is_primary=True)
return profile, True
def get_or_create_github_account(
github_account_id: int,
username: str = "",
display_name: str = "",
avatar_url: str = "",
account_type: str = GitHubAccountType.USER,
identity: Optional[Identity] = None,
) -> tuple[GitHubAccount, bool]:
"""Get or create a GitHubAccount by github_account_id. Returns (account, created).
If account exists, updates username, display_name, avatar_url, account_type if provided.
identity is only set on creation; to update identity use a separate service function.
"""
# API/user data can be None; store as empty string for NOT NULL columns.
username_val = username or ""
display_name_val = display_name or ""
avatar_url_val = avatar_url or ""
account, created = GitHubAccount.objects.get_or_create(
github_account_id=github_account_id,
defaults={
"username": username_val,
"display_name": display_name_val,
"avatar_url": avatar_url_val,
"account_type": account_type,
"identity": identity,
},
)
if not created:
# Update fields if not newly created
account.username = username_val or account.username
account.display_name = display_name_val or account.display_name
account.avatar_url = avatar_url_val or account.avatar_url
account.account_type = account_type
account.save()
return account, created
class GitHubClientProtocol(Protocol):
"""Protocol for a GitHub API client used by get_or_create_owner_account."""
def rest_request(self, path: str) -> dict[str, Any]: ...
def get_or_create_owner_account(
client: GitHubClientProtocol, owner: str
) -> GitHubAccount:
"""Get or create a GitHubAccount for an owner (org or user). For use by any app.
Checks DB first by username to avoid unnecessary API calls. Uses GET /users/{owner}
(GitHub returns both users and orgs with a \"type\" field). Returns the GitHubAccount.
"""
existing = GitHubAccount.objects.filter(username=owner).first()
if existing is not None:
return existing
data = client.rest_request(f"/users/{owner}")
api_type = (data.get("type") or "User").strip().lower()
account_type_map = {
"organization": GitHubAccountType.ORGANIZATION,
"user": GitHubAccountType.USER,
"enterprise": GitHubAccountType.ENTERPRISE,
}
account_type = account_type_map.get(api_type, GitHubAccountType.USER)
account = get_or_create_github_account(
github_account_id=data["id"],
username=data.get("login") or owner,
display_name=data.get("name") or "",
avatar_url=data.get("avatar_url") or "",
account_type=account_type,
)[0]
email_str = (data.get("email") or "").strip()
if email_str and not account.emails.filter(email=email_str).exists():
add_email(account, email_str, is_primary=not account.emails.exists())
return account
def _get_next_negative_github_account_id() -> int:
"""Return the next negative id for synthetic/unknown accounts (-1, -2, ...)."""
r = GitHubAccount.objects.filter(github_account_id__lt=0).aggregate(
Min("github_account_id")
)
min_id = r.get("github_account_id__min")
return (min_id - 1) if min_id is not None else -1
@transaction.atomic
def get_or_create_slack_user(
user_data: dict[str, Any],
) -> tuple[SlackUser, bool]:
"""Get or create a SlackUser from Slack API user data. Returns (SlackUser, created).
If the user exists, updates username, display_name, and avatar_url from user_data.
Creates an Email linked to the user if profile.email is provided and not already
present. Does not create or link an Identity (that is handled separately).
Raises ValueError if user_data has no 'id'.
"""
user_id = (user_data.get("id") or "").strip()
if not user_id:
raise ValueError("Slack user ID ('id') is required")
profile = user_data.get("profile") or {}
username = (user_data.get("name") or "").strip()
display_name = (user_data.get("real_name") or user_data.get("name") or "").strip()
avatar_url = (profile.get("image_72") or "").strip()
user, created = SlackUser.objects.get_or_create(
slack_user_id=user_id,
defaults={
"username": username,
"display_name": display_name,
"avatar_url": avatar_url,
},
)
if not created:
user.username = username or user.username
user.display_name = display_name or user.display_name
user.avatar_url = avatar_url or user.avatar_url
user.save()
email_str = (profile.get("email") or "").strip()
if email_str and not user.emails.filter(email=email_str).exists():
add_email(
user,
email_str,
is_primary=not user.emails.filter(is_active=True).exists(),
)
return user, created
def get_or_create_unknown_github_account(
name: Optional[str] = None,
email: str = "",
) -> tuple[GitHubAccount, bool]:
"""Get or create a GitHubAccount for commits with no API author/committer.
Uses display_name for lookup; if None/empty, uses \"unknown\". Checks DB for an
existing account with that display_name and negative github_account_id first; if
found, returns it (and adds email if provided and not already present). Otherwise
creates a new account with id -1, -2, etc. Returns (account, created).
"""
display_name = (name or "").strip() or "unknown"
email_str = (email or "").strip()
existing = GitHubAccount.objects.filter(
display_name=display_name, github_account_id__lt=0
).first()
if existing is not None:
if email_str and not existing.emails.filter(email=email_str).exists():
add_email(existing, email_str, is_primary=not existing.emails.exists())
return existing, False
next_id = _get_next_negative_github_account_id()
account = get_or_create_github_account(
github_account_id=next_id,
username=display_name,
display_name=display_name,
avatar_url="",
)[0]
if email_str:
add_email(account, email_str, is_primary=True)
return account, True
def get_or_create_discord_profile(
discord_user_id: int,
username: str = "",
display_name: str = "",
avatar_url: str = "",
is_bot: bool = False,
identity: Optional[Identity] = None,
) -> tuple[DiscordProfile, bool]:
"""Get or create a DiscordProfile by discord_user_id. Returns (profile, created).
If profile exists, updates username, display_name, avatar_url, is_bot if provided.
identity is only set on creation; to update identity use a separate service function.
"""
username_val = username or ""
display_name_val = display_name or ""
avatar_url_val = avatar_url or ""
profile, created = DiscordProfile.objects.get_or_create(
discord_user_id=discord_user_id,
defaults={
"username": username_val,
"display_name": display_name_val,
"avatar_url": avatar_url_val,
"is_bot": is_bot,
"identity": identity,
},
)
if not created:
profile.username = username_val or profile.username
profile.display_name = display_name_val or profile.display_name
profile.avatar_url = avatar_url_val or profile.avatar_url
profile.is_bot = is_bot
profile.save()
return profile, created
def get_or_create_wg21_paper_author_profile(
display_name: str,
email: Optional[str] = None,
) -> tuple[WG21PaperAuthorProfile, bool]:
"""Get or create a WG21PaperAuthorProfile by display_name, with optional email disambiguation.
Finds all profiles with the given display_name. If none exist, creates one and adds
email if provided. If one exists, returns it. If multiple exist, and email is
provided, returns the one with that email if any; otherwise returns the first.
"""
display_name_val = (display_name or "").strip()
email_val = (email or "").strip() or None
candidates = list(
WG21PaperAuthorProfile.objects.filter(display_name=display_name_val).order_by(
"id"
)
)
# Disambiguate by email if provided.
for p in candidates:
if email_val and p.emails.filter(email=email_val).exists():
return p, False
elif not email_val and not p.emails.exists():
return p, False
profile = WG21PaperAuthorProfile.objects.create(display_name=display_name_val)
if email_val:
add_email(profile, email_val, is_primary=True)
return profile, True
def get_or_create_youtube_speaker(
external_id: str,
display_name: str = "",
identity: Optional[Identity] = None,
) -> tuple[YoutubeSpeaker, bool]:
"""Get or create a YoutubeSpeaker by external_id. Returns (speaker, created).
Looks up by external_id. On creation, sets identity/display_name if provided.
If the record already exists and a non-empty display_name is provided, updates
display_name when changed.
Raises ValueError if external_id is empty.
"""
external_id_val = (external_id or "").strip()
display_name_val = (display_name or "").strip()
if not external_id_val:
raise ValueError("external_id must not be empty.")
speaker, created = YoutubeSpeaker.objects.get_or_create(
external_id=external_id_val,
defaults={"display_name": display_name_val, "identity": identity},
)
if not created and display_name_val and speaker.display_name != display_name_val:
speaker.display_name = display_name_val
speaker.save(update_fields=["display_name", "updated_at"])
return speaker, created