SentenceApi.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace App\Http\Api;
  3. use App\Models\Channel;
  4. use App\Models\Sentence;
  5. use App\Models\SentHistory;
  6. use Illuminate\Support\Facades\Redis;
  7. use Illuminate\Support\Str;
  8. class SentenceApi
  9. {
  10. protected $auth = false;
  11. protected $channel = null;
  12. public function auth($channelId, $userId)
  13. {
  14. $channel = Channel::where('uid', $channelId)->first();
  15. if (! $channel) {
  16. return false;
  17. }
  18. if ($channel->owner_uid !== $userId) {
  19. // 判断是否为协作
  20. $power = ShareApi::getResPower($userId, $channel->uid, 2);
  21. if ($power < 20) {
  22. return false;
  23. }
  24. }
  25. $this->channel = $channel;
  26. $this->auth = true;
  27. return true;
  28. }
  29. public function store($sent, $user, $copy = false)
  30. {
  31. $row = Sentence::firstOrNew([
  32. 'book_id' => $sent['book_id'],
  33. 'paragraph' => $sent['paragraph'],
  34. 'word_start' => $sent['word_start'],
  35. 'word_end' => $sent['word_end'],
  36. 'channel_uid' => $this->channel->uid,
  37. ], [
  38. 'id' => app('snowflake')->id(),
  39. 'uid' => Str::uuid(),
  40. ]);
  41. $row->content = $sent['content'];
  42. $row->strlen = mb_strlen($sent['content'], 'UTF-8');
  43. $row->language = $this->channel->lang;
  44. $row->status = $this->channel->status;
  45. if ($copy) {
  46. // 复制句子,保留原作者信息
  47. $row->editor_uid = $sent['editor_uid'];
  48. $row->acceptor_uid = $user['user_uid'];
  49. $row->pr_edit_at = $sent['updated_at'];
  50. } else {
  51. $row->editor_uid = $user['user_uid'];
  52. $row->acceptor_uid = null;
  53. $row->pr_edit_at = null;
  54. }
  55. $row->create_time = time() * 1000;
  56. $row->modify_time = time() * 1000;
  57. $row->save();
  58. // 保存历史记录
  59. if ($copy) {
  60. $this->saveHistory($row->uid, $sent['editor_uid'], $sent['content']);
  61. } else {
  62. $this->saveHistory($row->uid, $user['user_uid'], $sent['content']);
  63. }
  64. // 清除缓存
  65. $sentId = "{$sent['book_id']}-{$sent['paragraph']}-{$sent['word_start']}-{$sent['word_end']}";
  66. $hKey = "/sentence/res-count/{$sentId}/";
  67. Redis::del($hKey);
  68. }
  69. private function saveHistory($uid, $editor, $content)
  70. {
  71. $newHis = new SentHistory;
  72. $newHis->id = app('snowflake')->id();
  73. $newHis->sent_uid = $uid;
  74. $newHis->user_uid = $editor;
  75. if (empty($content)) {
  76. $newHis->content = '';
  77. } else {
  78. $newHis->content = $content;
  79. }
  80. $newHis->create_time = time() * 1000;
  81. $newHis->save();
  82. }
  83. }