UserHourlyDataFlow.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Builder;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  6. /**
  7. * 用户流量每小时统计
  8. */
  9. class UserHourlyDataFlow extends Model
  10. {
  11. public const UPDATED_AT = null;
  12. protected $table = 'user_hourly_data_flow';
  13. protected $guarded = [];
  14. public function user(): BelongsTo
  15. {
  16. return $this->belongsTo(User::class);
  17. }
  18. public function node(): BelongsTo
  19. {
  20. return $this->belongsTo(Node::class);
  21. }
  22. // 用户每时使用总流量
  23. public function scopeUserHourly(Builder $query, ?int $uid): Builder
  24. {
  25. if (! $uid) {
  26. $uid = auth()->id();
  27. }
  28. return $query->whereUserId($uid)->whereNodeId(null);
  29. }
  30. public function scopeUserRecentUsed(Builder $query, ?int $uid = null): Builder
  31. {
  32. return $query->userHourly($uid)->where('created_at', '>=', date('Y-m-d H:i:s', time() - 3900));
  33. }
  34. // 1小时内流量异常用户
  35. public function trafficAbnormal(): array
  36. {
  37. $userTotalTrafficList = self::whereNodeId(null)
  38. ->where('d', '>', MiB * 10)
  39. ->where('created_at', '>=', date('Y-m-d H:i:s', time() - 3900))
  40. ->groupBy('user_id')
  41. ->selectRaw('user_id, sum(u + d) as total')->pluck('total', 'user_id')
  42. ->toArray(); // 只统计10M以上的记录,加快速度
  43. foreach ($userTotalTrafficList as $user => $traffic) {
  44. if ($traffic > (int) sysConfig('traffic_abuse_limit') * GiB) {
  45. $result[] = $user;
  46. }
  47. }
  48. return $result ?? [];
  49. }
  50. }