| 1 | class ApiKeySwitcher { |
| 2 | constructor(keys) { |
| 3 | this.keys = keys || []; |
| 4 | this.currentIndex = 0; |
| 5 | this.userToken = localStorage.getItem('userOmdbToken'); // توکن کاربر |
| 6 | } |
| 7 | |
| 8 | getCurrentKey() { |
| 9 | if (this.userToken) { |
| 10 | console.log('استفاده از توکن کاربر:', this.userToken); |
| 11 | return this.userToken; // اولویت با توکن کاربر |
| 12 | } |
| 13 | if (this.keys.length === 0) { |
| 14 | throw new Error('هیچ کلید API در دسترس نیست.'); |
| 15 | } |
| 16 | return this.keys[this.currentIndex]; |
| 17 | } |
| 18 | |
| 19 | switchToNextKey() { |
| 20 | if (this.userToken) { |
| 21 | console.log('توکن کاربر استفاده میشود، تعویض کلید غیرفعال است.'); |
| 22 | return; // اگر توکن کاربر باشد، تعویض کلید غیرفعال است |
| 23 | } |
| 24 | this.currentIndex = (this.currentIndex + 1) % this.keys.length; |
| 25 | console.log(`تعویض به کلید API جدید: ${this.getCurrentKey()}`); |
| 26 | } |
| 27 | |
| 28 | async fetchWithKeySwitch(urlTemplate, maxRetriesPerKey = 3) { |
| 29 | let attempts = 0; |
| 30 | const totalAttemptsLimit = this.userToken ? maxRetriesPerKey : this.keys.length * maxRetriesPerKey; |
| 31 | |
| 32 | while (attempts < totalAttemptsLimit) { |
| 33 | const url = urlTemplate(this.getCurrentKey()); |
| 34 | try { |
| 35 | const response = window.FreeMovieApi |
| 36 | ? await window.FreeMovieApi.request(url) |
| 37 | : await fetch(url); |
| 38 | if (!response.ok) { |
| 39 | if (response.status === 429) { |
| 40 | console.warn('محدودیت نرخ OMDB API - تلاش مجدد...'); |
| 41 | await new Promise(resolve => setTimeout(resolve, 1000)); |
| 42 | attempts++; |
| 43 | continue; |
| 44 | } |
| 45 | throw new Error(`خطای سرور (OMDB): ${response.status}`); |
| 46 | } |
| 47 | return await response.json(); |
| 48 | } catch (error) { |
| 49 | console.warn(`خطا در درخواست با کلید ${this.getCurrentKey()}: ${error.message}`); |
| 50 | attempts++; |
| 51 | if (!this.userToken && attempts % maxRetriesPerKey === 0) { |
| 52 | this.switchToNextKey(); |
| 53 | } |
| 54 | await new Promise(resolve => setTimeout(resolve, 1000)); |
| 55 | if (attempts >= totalAttemptsLimit) { |
| 56 | throw new Error('تمام تلاشها ناموفق بود.'); |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | } |
nothing calls this directly
no outgoing calls
no test coverage detected