1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Created for IG Monitoring. |
4
|
|
|
* User: jakim <[email protected]> |
5
|
|
|
* Date: 09.05.2018 |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace app\components\http; |
9
|
|
|
|
10
|
|
|
|
11
|
|
|
use app\models\Account; |
12
|
|
|
use app\models\Proxy; |
13
|
|
|
use app\models\ProxyTag; |
14
|
|
|
use app\models\Tag; |
15
|
|
|
use yii\base\Component; |
16
|
|
|
use yii\base\Exception; |
17
|
|
|
use yii\base\InvalidConfigException; |
18
|
|
|
|
19
|
|
|
class ProxyManager extends Component |
20
|
|
|
{ |
21
|
|
|
public $restTime = 1; |
22
|
|
|
|
23
|
|
|
public function reserve($model): Proxy |
24
|
|
|
{ |
25
|
|
|
$uid = $this->generateUid(); |
26
|
|
|
|
27
|
|
|
$condition = $this->prepareCondition($model); |
28
|
|
|
|
29
|
|
|
$sql = \Yii::$app->db->createCommand() |
30
|
|
|
->update('proxy', [ |
31
|
|
|
'reservation_uid' => $uid, |
32
|
|
|
'updated_at' => (new \DateTime())->format('Y-m-d H:i:s'), |
33
|
|
|
], $condition)->rawSql; |
34
|
|
|
|
35
|
|
|
$n = \Yii::$app->db->createCommand("{$sql} ORDER BY [[updated_at]] ASC LIMIT 1") |
36
|
|
|
->execute(); |
37
|
|
|
|
38
|
|
|
if (empty($n)) { |
39
|
|
|
throw new Exception('No proxy available.'); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
$proxy = Proxy::findOne(['reservation_uid' => $uid]); |
43
|
|
|
|
44
|
|
|
if (empty($proxy)) { |
45
|
|
|
throw new InvalidConfigException('Something is wrong with \'ProxyManager\'.'); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
return $proxy; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function release(Proxy $proxy) |
52
|
|
|
{ |
53
|
|
|
Proxy::updateAll(['reservation_uid' => null], 'reservation_uid=:reservation_uid', [':reservation_uid' => $proxy->reservation_uid]); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
protected function generateUid() |
57
|
|
|
{ |
58
|
|
|
return sprintf("%s_%s", \Yii::$app->security->generateRandomString(64), time()); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
private function prepareCondition($model) |
62
|
|
|
{ |
63
|
|
|
$andWhere = [ |
64
|
|
|
'and', |
65
|
|
|
['active' => 1], |
66
|
|
|
['reservation_uid' => null], |
67
|
|
|
['<=', 'updated_at', (new \DateTime(sprintf('-%d seconds', (int)$this->restTime)))->format('Y-m-d H:i:s')], |
68
|
|
|
]; |
69
|
|
|
|
70
|
|
|
if ($model->proxy_id) { |
71
|
|
|
$andWhere[] = ['id' => $model->proxy_id]; |
72
|
|
|
} elseif ($model->proxy_tag_id) { |
73
|
|
|
$proxyIds = ProxyTag::find() |
74
|
|
|
->select('proxy_id') |
75
|
|
|
->andWhere(['tag_id' => $model->proxy_tag_id]) |
76
|
|
|
->column(); |
77
|
|
|
$andWhere[] = ['id' => $proxyIds]; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
return $andWhere; |
81
|
|
|
} |
82
|
|
|
} |