Repository navigation
Expand file tree
/
Copy pathUser.php
More file actions
735 lines (660 loc) · 22.6 KB
/
Copy pathUser.php
File metadata and controls
735 lines (660 loc) · 22.6 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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
<?php
declare(strict_types=1);
namespace App\Models;
use App\Actions\CreateTomFriendship;
use App\Actions\CreateWorldReply;
use App\Dto\LiveStream;
use App\Enums\LivePlatform;
use App\Enums\Log;
use App\Enums\RemotesFrom;
use Carbon\CarbonInterface;
use Database\Factories\UserFactory;
use Illuminate\Contracts\Database\Eloquent\Builder as BuilderContract;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\DB;
use LogicException;
/**
* @property-read string $id
* @property-read string $github_id
* @property-read string $handle
* @property-read string $name
* @property-read string|null $email
* @property-read string|null $avatar_url
* @property-read string|null $bio
* @property-read string|null $location
* @property-read string|null $website
* @property-read string|null $company
* @property-read bool $has_sponsors_listing
* @property-read int|null $preferred_lane
* @property-read string|null $lane_color
* @property-read bool $pasteis_mode
* @property-read bool $remotes_enabled
* @property-read RemotesFrom $remotes_from
* @property-read bool $pull_receipts
* @property-read bool $push_follows
* @property-read bool $push_replies
* @property-read bool $push_mentions
* @property-read bool $push_direct_remotes
* @property-read bool $push_org_remotes
* @property-read int $pasteis_received
* @property-read int $pasteis_given_today
* @property-read CarbonInterface|null $pasteis_given_on
* @property-read string|null $pinned_commit_id
* @property-read bool|null $automatic_translation
* @property-read string|null $translation_language
* @property-read string|null $timezone
* @property-read bool $show_local_time
* @property-read LivePlatform|null $live_platform
* @property-read string|null $live_url
* @property-read CarbonInterface|null $live_ends_at
* @property-read Log $log
* @property-read CarbonInterface|null $onboarded_at
* @property-read CarbonInterface|null $github_follows_imported_at
* @property-read CarbonInterface|null $github_organization_follows_imported_at
* @property-read string|null $remember_token
* @property-read CarbonInterface|null $github_synced_at
* @property-read CarbonInterface|null $last_seen_at
* @property-read CarbonInterface|null $banned_at
* @property-read CarbonInterface|null $terms_accepted_at
* @property-read CarbonInterface|null $commit_rules_accepted_at
* @property-read CarbonInterface|null $emails_unsubscribed_at
* @property-read CarbonInterface $created_at
* @property-read CarbonInterface $updated_at
* @property-read Collection<int, Commit> $commits
* @property-read Collection<int, Commit> $starredCommits
* @property-read Collection<int, User> $following
* @property-read Collection<int, User> $followers
* @property-read Collection<int, User> $muting
* @property-read Collection<int, User> $mutedBy
* @property-read Collection<int, User> $blocking
* @property-read Collection<int, User> $blockers
* @property-read Collection<int, Notification> $notifications
* @property-read Collection<int, SshKey> $sshKeys
* @property-read Collection<int, PollVote> $pollVotes
* @property-read Collection<int, Device> $devices
* @property-read Collection<int, UserTimeout> $timeouts
* @property-read Ban|null $ban
* @property-read Profile $profile
* @property-read int $commits_count
* @property-read int $timeouts_count
* @property-read int $following_count
* @property-read int $followers_count
*/
#[Hidden([
'profile',
'github_id',
'email',
'remember_token',
'translation_language',
'automatic_translation',
'preferred_lane',
'lane_color',
'pasteis_mode',
'remotes_enabled',
'pushSubscriptions',
'remotes_from',
'pull_receipts',
'push_follows',
'push_replies',
'push_mentions',
'push_direct_remotes',
'push_org_remotes',
'pasteis_received',
'pasteis_given_today',
'pasteis_given_on',
'pinned_commit_id',
'log',
'onboarded_at',
'github_follows_imported_at',
'github_organization_follows_imported_at',
'live_platform',
'live_url',
'live_ends_at',
'last_seen_at',
'banned_at',
'commit_rules_accepted_at',
'terms_accepted_at',
'emails_unsubscribed_at',
])]
final class User extends Authenticatable
{
/** @use HasFactory<UserFactory> */
use HasFactory;
use HasUuids;
public const int DAILY_PASTEIS = 10;
/**
* The longest a stream can be shown as live, in hours.
*/
public const int MAX_LIVE_HOURS = 12;
/**
* The accounts that never sign in, which product metrics leave out: Tom and @world.
*/
public const array BOT_GITHUB_IDS = [CreateTomFriendship::GITHUB_ID, CreateWorldReply::GITHUB_ID];
/**
* Every user shows their GitHub identity, so their profile comes with them.
*
* @var list<string>
*/
protected $with = ['profile'];
/**
* @var array<string, mixed>
*/
protected $attributes = [
'log' => Log::Following->value,
'translation_language' => null,
'show_local_time' => false,
'pasteis_mode' => false,
'remotes_enabled' => true,
'remotes_from' => RemotesFrom::Following->value,
'pull_receipts' => true,
'push_follows' => true,
'push_replies' => true,
'push_mentions' => true,
'push_direct_remotes' => true,
'push_org_remotes' => true,
'pasteis_received' => 0,
'pasteis_given_today' => 0,
'pasteis_given_on' => null,
'live_platform' => null,
'live_url' => null,
'live_ends_at' => null,
'last_seen_at' => null,
'banned_at' => null,
'commit_rules_accepted_at' => null,
'terms_accepted_at' => null,
'emails_unsubscribed_at' => null,
];
/**
* The bots as a Postgres array, for raw queries that leave them out with `github_id <> all(?::text[])`.
*/
public static function botGitHubIdsArray(): string
{
return '{'.implode(',', self::BOT_GITHUB_IDS).'}';
}
/**
* @return array<string, string>
*/
public function casts(): array
{
return [
'id' => 'string',
'github_id' => 'string',
'email' => 'string',
'company' => 'string',
'has_sponsors_listing' => 'boolean',
'preferred_lane' => 'integer',
'lane_color' => 'string',
'pasteis_mode' => 'boolean',
'remotes_enabled' => 'boolean',
'remotes_from' => RemotesFrom::class,
'pull_receipts' => 'boolean',
'push_follows' => 'boolean',
'push_replies' => 'boolean',
'push_mentions' => 'boolean',
'push_direct_remotes' => 'boolean',
'push_org_remotes' => 'boolean',
'pasteis_received' => 'integer',
'pasteis_given_today' => 'integer',
'pasteis_given_on' => 'date',
'pinned_commit_id' => 'string',
'timezone' => 'string',
'show_local_time' => 'boolean',
'translation_language' => 'encrypted',
'automatic_translation' => 'boolean',
'log' => Log::class,
'onboarded_at' => 'datetime',
'github_follows_imported_at' => 'datetime',
'github_organization_follows_imported_at' => 'datetime',
'remember_token' => 'string',
'live_platform' => LivePlatform::class,
'live_url' => 'string',
'live_ends_at' => 'datetime',
'last_seen_at' => 'date',
'banned_at' => 'datetime',
'commit_rules_accepted_at' => 'datetime',
'terms_accepted_at' => 'datetime',
'emails_unsubscribed_at' => 'datetime',
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
}
/**
* A user shares their profile's ID, as an organization does.
*
* @return BelongsTo<Profile, $this>
*/
public function profile(): BelongsTo
{
return $this->belongsTo(Profile::class, 'id');
}
/**
* Resolves "@handle" URLs through the profile, which holds the handle, whatever its case, like GitHub.
*
* @param Model|BuilderContract|Relation<Model, Model, mixed> $query
* @param mixed $value
* @param string|null $field
*/
public function resolveRouteBindingQuery($query, $value, $field = null): BuilderContract
{
return $field === 'handle'
? parent::resolveRouteBindingQuery($query, Profile::query()->select('id')->where('handle', $value), 'id')
: parent::resolveRouteBindingQuery($query, $value, $field);
}
/**
* The commits from the user's own profile.
*
* @return HasMany<Commit, $this>
*/
public function commits(): HasMany
{
return $this->hasMany(Commit::class, 'author_id');
}
/**
* Ten followers are enough, so the check stops at the tenth instead of counting every follower.
*/
public function hasGoodReputation(): bool
{
return $this->created_at->lt(now()->subHour())
&& $this->commits()->approved()->exists()
&& $this->followers()->skip(9)->exists();
}
/**
* @return HasMany<PollVote, $this>
*/
public function pollVotes(): HasMany
{
return $this->hasMany(PollVote::class);
}
/**
* @return HasMany<SshKey, $this>
*/
public function sshKeys(): HasMany
{
return $this->hasMany(SshKey::class);
}
/**
* @return HasMany<PushSubscription, $this>
*/
public function pushSubscriptions(): HasMany
{
return $this->hasMany(PushSubscription::class);
}
/**
* @return HasMany<Device, $this>
*/
public function devices(): HasMany
{
return $this->hasMany(Device::class);
}
/**
* The org messages that mentioned the user, until they open or clear them.
*
* @return BelongsToMany<Message, $this>
*/
public function mentions(): BelongsToMany
{
return $this->belongsToMany(Message::class, 'message_mentions');
}
/**
* Timeouts go by GitHub account, like bans, so they outlive the user and still apply if the same account signs up
* again.
*
* @return HasMany<UserTimeout, $this>
*/
public function timeouts(): HasMany
{
return $this->hasMany(UserTimeout::class, 'github_id', 'github_id');
}
/**
* Ban decisions go by GitHub account, so they outlive the user and apply again after a new signup.
*
* @return HasMany<BanEvent, $this>
*/
public function banEvents(): HasMany
{
return $this->hasMany(BanEvent::class, 'github_id', 'github_id');
}
/**
* The timeout the user is in right now, the one that ends last if moderators gave more than one.
*/
public function activeTimeout(): ?UserTimeout
{
return $this->timeouts()->where('ends_at', '>', now())->latest('ends_at')->first();
}
/**
* Bans go by GitHub account, so they outlive the user and still apply if the same account signs up again.
*
* @return HasOne<Ban, $this>
*/
public function ban(): HasOne
{
return $this->hasOne(Ban::class, 'github_id', 'github_id');
}
/**
* Read from the user rather than the ban, since it's checked on every request.
*/
public function isBanned(): bool
{
return $this->banned_at !== null;
}
/**
* The organizations the user is a member of, see `Organization::members()`.
*
* @return BelongsToMany<Organization, $this>
*/
public function organizations(): BelongsToMany
{
return $this->belongsToMany(Organization::class, 'organization_members', 'user_id', 'organization_id')->withPivot('role')->withTimestamps(updatedAt: false);
}
/**
* The organizations the user follows, see `Organization::followers()`.
*
* @return BelongsToMany<Organization, $this>
*/
public function followedOrganizations(): BelongsToMany
{
return $this->belongsToMany(Organization::class, 'organization_follows', 'user_id', 'organization_id')->withTimestamps(updatedAt: false);
}
/**
* @return BelongsToMany<Commit, $this>
*/
public function starredCommits(): BelongsToMany
{
return $this->belongsToMany(Commit::class, 'stars')->withTimestamps();
}
public function hasStarred(Commit $commit): bool
{
return $this->starredCommits()->whereKey($commit->id)->exists();
}
/**
* @return BelongsToMany<User, $this>
*/
public function following(): BelongsToMany
{
return $this->belongsToMany(self::class, 'follows', 'follower_id', 'followed_id')->withTimestamps();
}
/**
* @return BelongsToMany<User, $this>
*/
public function followers(): BelongsToMany
{
return $this->belongsToMany(self::class, 'follows', 'followed_id', 'follower_id')->withTimestamps();
}
/**
* @return BelongsToMany<User, $this>
*/
public function muting(): BelongsToMany
{
return $this->belongsToMany(self::class, 'mutes', 'muter_id', 'muted_id')->withTimestamps();
}
/**
* @return BelongsToMany<User, $this>
*/
public function dismissedSuggestions(): BelongsToMany
{
return $this->belongsToMany(self::class, 'suggestion_dismissals', 'user_id', 'dismissed_id')->withTimestamps();
}
/**
* @return BelongsToMany<User, $this>
*/
public function mutedBy(): BelongsToMany
{
return $this->belongsToMany(self::class, 'mutes', 'muted_id', 'muter_id')->withTimestamps();
}
/**
* @return BelongsToMany<User, $this>
*/
public function blocking(): BelongsToMany
{
return $this->belongsToMany(self::class, 'blocks', 'blocker_id', 'blocked_id')->withTimestamps();
}
/**
* @return BelongsToMany<User, $this>
*/
public function blockers(): BelongsToMany
{
return $this->belongsToMany(self::class, 'blocks', 'blocked_id', 'blocker_id')->withTimestamps();
}
/**
* @return HasMany<Notification, $this>
*/
public function notifications(): HasMany
{
return $this->hasMany(Notification::class, 'recipient_id');
}
/**
* Users sign in with GitHub, so they have no password.
*/
public function getAuthPassword(): string
{
return '';
}
/**
* Whether they have accepted the terms and privacy policy as they stand now.
*/
public function hasAcceptedCurrentTerms(): bool
{
return $this->terms_accepted_at?->gte(config()->string('legal.terms_version')) ?? false;
}
public function isOnboarded(): bool
{
return $this->onboarded_at !== null;
}
/**
* The user's private channel, where only they hear what changed for them.
*/
public function broadcastChannel(): string
{
return 'users.'.$this->id;
}
public function isAdmin(): bool
{
/** @var list<string> $admins */
$admins = config('app.admins');
return in_array(mb_strtolower($this->handle), array_map(mb_strtolower(...), $admins), true);
}
/**
* Unlike loadCount(), counts follows on the pivot tables alone: the self-referencing
* relations would otherwise join the users table for every follow. Commits are
* counted as the viewer sees them, which is all of them for the user themselves.
*/
public function loadCounts(?self $viewer = null): self
{
return $this->fillCounts($this->commits()->visibleTo($viewer ?? $this)->count());
}
/**
* Counts what anyone may see about the user, so only approved commits.
*/
public function loadPublicCounts(): self
{
return $this->fillCounts($this->commits()->approved()->count());
}
/**
* Changes whenever anything drawn on the profile's link preview image may have changed.
*/
public function openGraphImageVersion(): string
{
return hash('xxh3', (string) json_encode([
...$this->openGraphIdentity(),
$this->bio,
$this->commits_count,
$this->following_count,
$this->followers_count,
]));
}
/**
* What every link preview image draws of the user, so saving anything else leaves them cached.
*
* @return list<int|string|null>
*/
public function openGraphIdentity(): array
{
return [$this->name, $this->handle, $this->avatar_url, $this->lane()];
}
public function mention(): string
{
return $this->profile->mention();
}
public function nameWithHandle(): string
{
return $this->profile->nameWithHandle();
}
public function isFollowing(self $user): bool
{
return $this->following()->newPivotQuery()->where('followed_id', $user->id)->exists();
}
public function isMuting(self $user): bool
{
return $this->muting()->newPivotQuery()->where('muted_id', $user->id)->exists();
}
public function isBlocking(self $user): bool
{
return $this->blocking()->newPivotQuery()->where('blocked_id', $user->id)->exists();
}
/**
* A block works both ways, so either one blocking the other keeps them apart.
*/
public function hasBlockWith(self $user): bool
{
return $this->blockerIdWith($user) !== null;
}
/**
* Whether the user can have a conversation with someone at all: remotes on, someone else, and no block between
* them. Whether they may push to it right now is the conversation's own business.
*/
public function canMessage(self $user): bool
{
return $this->remotes_enabled && ! $this->is($user) && ! $this->hasBlockWith($user);
}
/**
* Whether a first message from the sender opens the conversation straight away. When it doesn't, it waits
* fetched for a merge, or can't be sent at all while requests are off. Site admins can always reach anyone with
* remotes on.
*/
public function acceptsRemotesFrom(self $sender): bool
{
return $sender->isAdmin() || ($this->remotes_from === RemotesFrom::Everyone && config('remotes.everyone')) || $this->isFollowing($sender);
}
/**
* Which of the two blocked the other, if either did.
*/
public function blockerIdWith(self $user): ?string
{
$blockerId = DB::table('blocks')
->where(fn (QueryBuilder $query): QueryBuilder => $query->where('blocker_id', $this->id)->where('blocked_id', $user->id))
->orWhere(fn (QueryBuilder $query): QueryBuilder => $query->where('blocker_id', $user->id)->where('blocked_id', $this->id))
->value('blocker_id');
return is_string($blockerId) ? $blockerId : null;
}
/**
* The ids of everyone the user blocks or is blocked by, as a subquery.
*/
public function idsAcrossBlocks(): QueryBuilder
{
return $this->blocking()->newPivotQuery()->select('blocked_id')
->union($this->blockers()->newPivotQuery()->select('blocker_id'));
}
/**
* The ids of everyone the user mutes, as a subquery.
*/
public function mutedIds(): QueryBuilder
{
return $this->muting()->newPivotQuery()->select('muted_id');
}
public function pasteisRemaining(): int
{
return self::DAILY_PASTEIS - ($this->pasteis_given_on?->isToday() ? $this->pasteis_given_today : 0);
}
public function lane(): int|string
{
return $this->preferredLane() ?? $this->automaticLane();
}
public function preferredLane(): int|string|null
{
return $this->lane_color ?? $this->preferred_lane;
}
/**
* The same hash of the id the frontend used before lanes could be chosen, so nobody's color changes on its own.
*/
public function automaticLane(): int
{
$hash = 0;
foreach (mb_str_split($this->id) as $character) {
$hash = ($hash * 31 + mb_ord($character)) & 0xFFFFFFFF;
}
return $hash % 6;
}
/**
* @return array<mixed>
*/
public function toArray(): array
{
return [
'id' => $this->id,
'handle' => $this->handle,
'name' => $this->name,
'avatar_url' => $this->avatar_url,
'bio' => $this->bio,
'location' => $this->location,
'website' => $this->website,
...parent::toArray(),
'lane' => $this->lane(),
'has_github_account' => $this->hasGitHubAccount(),
'live' => $this->liveStream()?->toArray(),
];
}
/**
* The stream the user is on until it runs out, which also hides a stream the scheduler has not cleared yet.
*/
public function liveStream(): ?LiveStream
{
return $this->live_ends_at?->isFuture() === true
? $this->live_platform?->driver()->stream((string) $this->live_url)
: null;
}
/**
* Everyone signs in with GitHub except Tom, who was made up and has no GitHub profile to link to.
*/
public function hasGitHubAccount(): bool
{
return $this->github_id !== CreateTomFriendship::GITHUB_ID;
}
/**
* The GitHub identity lives on the profile: it reads through, and only the profile changes it.
*
* @param string $key
*/
public function getAttribute($key): mixed
{
return in_array($key, Profile::USER_ATTRIBUTES, true) ? $this->profile->getAttribute($key) : parent::getAttribute($key);
}
/**
* @param string $key
*/
public function setAttribute($key, $value): mixed
{
throw_if(in_array($key, Profile::USER_ATTRIBUTES, true), LogicException::class, "Update the {$key} of a user on their profile.");
return parent::setAttribute($key, $value);
}
private function fillCounts(int $commits): self
{
$counts = [
'commits_count' => $commits,
'followers_count' => $this->followers()->newPivotQuery()->count(),
'following_count' => $this->following()->newPivotQuery()->count() + $this->followedOrganizations()->newPivotQuery()->count(),
];
$this->forceFill($counts)->syncOriginalAttributes(array_keys($counts));
return $this;
}
}