SentenceService.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Sentence;
  4. use App\Models\SentHistory;
  5. use App\Models\Channel;
  6. use Illuminate\Support\Facades\Log;
  7. use Illuminate\Support\Facades\Http;
  8. use Illuminate\Http\Client\RequestException;
  9. use Illuminate\Support\Str;
  10. class SentenceService
  11. {
  12. protected $timeOut = 30;
  13. public function save(array $data)
  14. {
  15. $row = Sentence::firstOrNew([
  16. "book_id" => $data['book_id'],
  17. "paragraph" => $data['paragraph'],
  18. "word_start" => $data['word_start'],
  19. "word_end" => $data['word_end'],
  20. "channel_uid" => $data['channel_uid'],
  21. ], [
  22. "id" => app('snowflake')->id(),
  23. "uid" => Str::uuid(),
  24. ]);
  25. $row->content = $data['content'];
  26. if (isset($data['content_type']) && !empty($data['content_type'])) {
  27. $row->content_type = $data['content_type'];
  28. }
  29. $row->strlen = mb_strlen($data['content'], "UTF-8");
  30. $lang = Channel::where('uid', $data['channel_uid'])->value('lang');
  31. $row->language = $lang;
  32. $row->status = $data['status'] ?? 10;
  33. if (isset($data['copy'])) {
  34. //复制句子,保留原作者信息
  35. $row->editor_uid = $data["editor_uid"];
  36. $row->acceptor_uid = $data["acceptor_uid"];
  37. $row->pr_edit_at = $data["updated_at"];
  38. if (isset($data['fork_from'])) {
  39. $row->fork_at = now();
  40. }
  41. } else {
  42. $row->editor_uid = $data["editor_uid"];
  43. $row->acceptor_uid = null;
  44. $row->pr_edit_at = null;
  45. }
  46. $row->create_time = time() * 1000;
  47. $row->modify_time = time() * 1000;
  48. $row->save();
  49. }
  50. /**
  51. * 'sentence' => [
  52. 'book_id' => $sentence['id'][0],
  53. 'paragraph' => $sentence['id'][1],
  54. 'word_start' => $sentence['id'][2],
  55. 'word_end' => $sentence['id'][3],
  56. 'channel_uid' => $channelId,
  57. 'content' => $prompt,
  58. 'content_type' => 'markdown',
  59. 'access_token' => $sentChannelInfo[1] ?? $params['token'],
  60. ],
  61. */
  62. public function saveRpc(array $sentence, string $editorToken)
  63. {
  64. $url = config('app.url') . '/api/v2/sentence';
  65. Log::info(" sentence update {$url}");
  66. $response = Http::timeout($this->timeOut)
  67. ->withToken($editorToken)
  68. ->post($url, [
  69. 'sentences' => [$sentence],
  70. ]);
  71. if ($response->failed()) {
  72. Log::error(' sentence update failed', [
  73. 'url' => $url,
  74. 'data' => $response->json(),
  75. ]);
  76. throw new DatabaseException("sentence 数据库写入错误");
  77. }
  78. $count = $response->json()['data']['count'];
  79. return $count;
  80. }
  81. }