|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Services; |
| 4 | + |
| 5 | +use App\Models\Plugin; |
| 6 | +use App\Support\CommonMark\CommonMark; |
| 7 | +use Illuminate\Support\Facades\Http; |
| 8 | +use Illuminate\Support\Facades\Log; |
| 9 | + |
| 10 | +class PluginSyncService |
| 11 | +{ |
| 12 | + public function sync(Plugin $plugin): bool |
| 13 | + { |
| 14 | + $repo = $plugin->getRepositoryOwnerAndName(); |
| 15 | + |
| 16 | + if (! $repo) { |
| 17 | + Log::warning("Plugin {$plugin->id} has no valid repository URL"); |
| 18 | + |
| 19 | + return false; |
| 20 | + } |
| 21 | + |
| 22 | + $baseUrl = "https://raw.githubusercontent.com/{$repo['owner']}/{$repo['repo']}/main"; |
| 23 | + |
| 24 | + $readme = $this->fetchFile("{$baseUrl}/README.md"); |
| 25 | + $composerJson = $this->fetchFile("{$baseUrl}/composer.json"); |
| 26 | + $nativephpJson = $this->fetchFile("{$baseUrl}/nativephp.json"); |
| 27 | + |
| 28 | + if (! $composerJson) { |
| 29 | + Log::warning("Plugin {$plugin->id}: Could not fetch composer.json"); |
| 30 | + |
| 31 | + return false; |
| 32 | + } |
| 33 | + |
| 34 | + $composerData = json_decode($composerJson, true); |
| 35 | + $nativephpData = $nativephpJson ? json_decode($nativephpJson, true) : null; |
| 36 | + |
| 37 | + $updateData = [ |
| 38 | + 'composer_data' => $composerData, |
| 39 | + 'nativephp_data' => $nativephpData, |
| 40 | + 'last_synced_at' => now(), |
| 41 | + ]; |
| 42 | + |
| 43 | + if ($composerData) { |
| 44 | + if (isset($composerData['description'])) { |
| 45 | + $updateData['description'] = $composerData['description']; |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + if ($nativephpData) { |
| 50 | + $updateData['ios_version'] = $this->extractIosVersion($nativephpData); |
| 51 | + $updateData['android_version'] = $this->extractAndroidVersion($nativephpData); |
| 52 | + } |
| 53 | + |
| 54 | + if ($readme) { |
| 55 | + $updateData['readme_html'] = CommonMark::convertToHtml($readme); |
| 56 | + } |
| 57 | + |
| 58 | + $plugin->update($updateData); |
| 59 | + |
| 60 | + Log::info("Plugin {$plugin->id} synced successfully"); |
| 61 | + |
| 62 | + return true; |
| 63 | + } |
| 64 | + |
| 65 | + protected function fetchFile(string $url): ?string |
| 66 | + { |
| 67 | + try { |
| 68 | + $response = Http::timeout(10)->get($url); |
| 69 | + |
| 70 | + if ($response->successful()) { |
| 71 | + return $response->body(); |
| 72 | + } |
| 73 | + } catch (\Exception $e) { |
| 74 | + Log::warning("Failed to fetch {$url}: {$e->getMessage()}"); |
| 75 | + } |
| 76 | + |
| 77 | + return null; |
| 78 | + } |
| 79 | + |
| 80 | + protected function extractIosVersion(array $nativephpData): ?string |
| 81 | + { |
| 82 | + return $nativephpData['ios']['min_version'] ?? null; |
| 83 | + } |
| 84 | + |
| 85 | + protected function extractAndroidVersion(array $nativephpData): ?string |
| 86 | + { |
| 87 | + return $nativephpData['android']['min_version'] ?? null; |
| 88 | + } |
| 89 | +} |
0 commit comments