FreeNom.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. <?php
  2. /**
  3. * FreeNom域名自动续期
  4. *
  5. * @author mybsdc <[email protected]>
  6. * @date 2020/1/19
  7. * @time 17:29
  8. * @link https://github.com/luolongfei/freenom
  9. */
  10. namespace Luolongfei\App\Console;
  11. use Luolongfei\App\Exceptions\LlfException;
  12. use Luolongfei\App\Exceptions\WarningException;
  13. use GuzzleHttp\Client;
  14. use GuzzleHttp\Cookie\CookieJar;
  15. use Luolongfei\Libs\Log;
  16. use Luolongfei\Libs\Message;
  17. use GuzzleHttp\Cookie\SetCookie;
  18. class FreeNom extends Base
  19. {
  20. const VERSION = 'v0.6.1';
  21. const TIMEOUT = 33;
  22. // FreeNom登录地址
  23. const LOGIN_URL = 'https://my.freenom.com/dologin.php';
  24. // 域名状态地址
  25. const DOMAIN_STATUS_URL = 'https://my.freenom.com/domains.php?a=renewals';
  26. // 域名续期地址
  27. const RENEW_DOMAIN_URL = 'https://my.freenom.com/domains.php?submitrenewals=true';
  28. // 匹配token的正则
  29. const TOKEN_REGEX = '/name="token"\svalue="(?P<token>[^"]+)"/i';
  30. // 匹配域名信息的正则
  31. const DOMAIN_INFO_REGEX = '/<tr><td>(?P<domain>[^<]+)<\/td><td>[^<]+<\/td><td>[^<]+<span class="[^"]+">(?P<days>\d+)[^&]+&domain=(?P<id>\d+)"/i';
  32. // 匹配登录状态的正则
  33. const LOGIN_STATUS_REGEX = '/<li.*?Logout.*?<\/li>/i';
  34. // 匹配无域名的正则
  35. const NO_DOMAIN_REGEX = '/<tr\sclass="carttablerow"><td\scolspan="5">(?P<msg>[^<]+)<\/td><\/tr>/i';
  36. /**
  37. * @var Client
  38. */
  39. protected $client;
  40. /**
  41. * @var CookieJar | bool
  42. */
  43. protected $jar = true;
  44. /**
  45. * @var string FreeNom 账户
  46. */
  47. protected $username;
  48. /**
  49. * @var string FreeNom 密码
  50. */
  51. protected $password;
  52. /**
  53. * @var FreeNom
  54. */
  55. private static $instance;
  56. /**
  57. * @var int 最大请求重试次数
  58. */
  59. public $maxRequestRetryCount;
  60. /**
  61. * @return FreeNom
  62. */
  63. public static function getInstance()
  64. {
  65. if (!self::$instance instanceof self) {
  66. self::$instance = new self();
  67. }
  68. return self::$instance;
  69. }
  70. private function __construct()
  71. {
  72. $this->client = new Client([
  73. 'headers' => [
  74. 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
  75. 'Accept-Encoding' => 'gzip, deflate, br',
  76. 'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
  77. ],
  78. 'timeout' => self::TIMEOUT,
  79. CURLOPT_FOLLOWLOCATION => true,
  80. CURLOPT_AUTOREFERER => true,
  81. 'verify' => config('verify_ssl'),
  82. 'debug' => config('debug'),
  83. 'proxy' => config('freenom_proxy'),
  84. ]);
  85. $this->maxRequestRetryCount = config('max_request_retry_count');
  86. system_log(sprintf(lang('100038'), self::VERSION));
  87. }
  88. private function __clone()
  89. {
  90. }
  91. /**
  92. * 登录
  93. *
  94. * @param string $username
  95. * @param string $password
  96. *
  97. * @return bool
  98. * @throws LlfException
  99. */
  100. protected function login(string $username, string $password)
  101. {
  102. try {
  103. autoRetry(function ($username, $password, &$jar) {
  104. return $this->client->post(self::LOGIN_URL, [
  105. 'headers' => [
  106. 'Content-Type' => 'application/x-www-form-urlencoded',
  107. 'Referer' => 'https://my.freenom.com/clientarea.php'
  108. ],
  109. 'form_params' => [
  110. 'username' => $username,
  111. 'password' => $password
  112. ],
  113. 'cookies' => $jar
  114. ]);
  115. }, $this->maxRequestRetryCount, [$username, $password, &$this->jar]);
  116. } catch (\Exception $e) {
  117. throw new LlfException(34520002, $e->getMessage());
  118. }
  119. if (empty($this->jar->getCookieByName('WHMCSZH5eHTGhfvzP')->getValue())) {
  120. throw new LlfException(34520002, lang('100001'));
  121. }
  122. system_log(sprintf(lang('100138'), $username));
  123. return true;
  124. }
  125. /**
  126. * 匹配获取所有域名
  127. *
  128. * @param string $domainStatusPage
  129. *
  130. * @return array
  131. * @throws LlfException
  132. * @throws WarningException
  133. */
  134. protected function getAllDomains(string $domainStatusPage)
  135. {
  136. if (preg_match(self::NO_DOMAIN_REGEX, $domainStatusPage, $m)) {
  137. throw new WarningException(34520014, [$this->username, $m['msg']]);
  138. }
  139. if (!preg_match_all(self::DOMAIN_INFO_REGEX, $domainStatusPage, $allDomains, PREG_SET_ORDER)) {
  140. throw new LlfException(34520003);
  141. }
  142. return $allDomains;
  143. }
  144. /**
  145. * 获取匹配 token
  146. *
  147. * 据观察,每次登录后此 token 不会改变,故可以只获取一次,多次使用
  148. *
  149. * @param string $domainStatusPage
  150. *
  151. * @return string
  152. * @throws LlfException
  153. */
  154. protected function getToken(string $domainStatusPage)
  155. {
  156. if (!preg_match(self::TOKEN_REGEX, $domainStatusPage, $matches)) {
  157. throw new LlfException(34520004);
  158. }
  159. return $matches['token'];
  160. }
  161. /**
  162. * 获取域名状态页面
  163. *
  164. * @return string
  165. * @throws LlfException
  166. */
  167. protected function getDomainStatusPage()
  168. {
  169. try {
  170. $resp = autoRetry(function (&$jar) {
  171. return $this->client->get(self::DOMAIN_STATUS_URL, [
  172. 'headers' => [
  173. 'Referer' => 'https://my.freenom.com/clientarea.php'
  174. ],
  175. 'cookies' => $jar
  176. ]);
  177. }, $this->maxRequestRetryCount, [&$this->jar]);
  178. $page = (string)$resp->getBody();
  179. } catch (\Exception $e) {
  180. throw new LlfException(34520013, $e->getMessage());
  181. }
  182. if (!preg_match(self::LOGIN_STATUS_REGEX, $page)) {
  183. throw new LlfException(34520009);
  184. }
  185. return $page;
  186. }
  187. /**
  188. * 续期所有域名
  189. *
  190. * @param array $allDomains
  191. * @param string $token
  192. *
  193. * @return bool
  194. */
  195. public function renewAllDomains(array $allDomains, string $token)
  196. {
  197. $renewalSuccessArr = [];
  198. $renewalFailuresArr = [];
  199. $domainStatusArr = [];
  200. foreach ($allDomains as $d) {
  201. $domain = $d['domain'];
  202. $days = (int)$d['days'];
  203. $id = $d['id'];
  204. // 免费域名只允许在到期前 14 天内续期
  205. if ($days <= 14) {
  206. $renewalResult = $this->renew($id, $token);
  207. sleep(1);
  208. if ($renewalResult) {
  209. $renewalSuccessArr[] = $domain;
  210. continue; // 续期成功的域名无需记录过期天数
  211. } else {
  212. $renewalFailuresArr[] = $domain;
  213. }
  214. }
  215. // 记录域名过期天数
  216. $domainStatusArr[$domain] = $days;
  217. }
  218. // 存在续期操作
  219. if ($renewalSuccessArr || $renewalFailuresArr) {
  220. $data = [
  221. 'username' => $this->username,
  222. 'renewalSuccessArr' => $renewalSuccessArr,
  223. 'renewalFailuresArr' => $renewalFailuresArr,
  224. 'domainStatusArr' => $domainStatusArr,
  225. ];
  226. $result = Message::send('', lang('100039'), 2, $data);
  227. system_log(sprintf(
  228. lang('100040'),
  229. count($renewalSuccessArr),
  230. count($renewalFailuresArr),
  231. $result ? lang('100041') : ''
  232. ));
  233. Log::info(sprintf(lang('100042'), $this->username), $data);
  234. return true;
  235. }
  236. // 不存在续期操作
  237. if (config('notice_freq') === 1) {
  238. $data = [
  239. 'username' => $this->username,
  240. 'domainStatusArr' => $domainStatusArr,
  241. ];
  242. Message::send('', lang('100043'), 3, $data);
  243. } else {
  244. system_log(lang('100044'));
  245. }
  246. system_log(sprintf(lang('100045'), $this->username));
  247. return true;
  248. }
  249. /**
  250. * 续期单个域名
  251. *
  252. * @param int $id
  253. * @param string $token
  254. *
  255. * @return bool
  256. */
  257. protected function renew(int $id, string $token)
  258. {
  259. try {
  260. $resp = autoRetry(function ($token, $id, &$jar) {
  261. return $this->client->post(self::RENEW_DOMAIN_URL, [
  262. 'headers' => [
  263. 'Referer' => sprintf('https://my.freenom.com/domains.php?a=renewdomain&domain=%s', $id),
  264. 'Content-Type' => 'application/x-www-form-urlencoded'
  265. ],
  266. 'form_params' => [
  267. 'token' => $token,
  268. 'renewalid' => $id,
  269. sprintf('renewalperiod[%s]', $id) => '12M', // 续期一年
  270. 'paymentmethod' => 'credit', // 支付方式:信用卡
  271. ],
  272. 'cookies' => $jar
  273. ]);
  274. }, $this->maxRequestRetryCount, [$token, $id, &$this->jar]);
  275. $resp = (string)$resp->getBody();
  276. return stripos($resp, 'Order Confirmation') !== false;
  277. } catch (\Exception $e) {
  278. $errorMsg = sprintf(lang('100046'), $e->getMessage(), $id, $this->username);
  279. system_log($errorMsg);
  280. Message::send($errorMsg);
  281. return false;
  282. }
  283. }
  284. /**
  285. * 二维数组去重
  286. *
  287. * @param array $array 原始数组
  288. * @param array $keys 可指定对应的键联合
  289. *
  290. * @return bool
  291. */
  292. public function arrayUnique(array &$array, array $keys = [])
  293. {
  294. if (!isset($array[0]) || !is_array($array[0])) {
  295. return false;
  296. }
  297. if (empty($keys)) {
  298. $keys = array_keys($array[0]);
  299. }
  300. $tmp = [];
  301. foreach ($array as $k => $items) {
  302. $combinedKey = '';
  303. foreach ($keys as $key) {
  304. $combinedKey .= $items[$key];
  305. }
  306. if (isset($tmp[$combinedKey])) {
  307. unset($array[$k]);
  308. } else {
  309. $tmp[$combinedKey] = $k;
  310. }
  311. }
  312. unset($tmp);
  313. return true;
  314. }
  315. /**
  316. * 获取 FreeNom 账户信息
  317. *
  318. * @return array
  319. * @throws LlfException
  320. */
  321. protected function getAccounts()
  322. {
  323. $accounts = [];
  324. $multipleAccounts = preg_replace('/\s/', '', env('MULTIPLE_ACCOUNTS'));
  325. if (preg_match_all('/<(?P<u>.*?)>@<(?P<p>.*?)>/i', $multipleAccounts, $matches, PREG_SET_ORDER)) {
  326. foreach ($matches as $m) {
  327. $accounts[] = [
  328. 'username' => $m['u'],
  329. 'password' => $m['p']
  330. ];
  331. }
  332. }
  333. $username = env('FREENOM_USERNAME');
  334. $password = env('FREENOM_PASSWORD');
  335. if ($username && $password) {
  336. $accounts[] = [
  337. 'username' => $username,
  338. 'password' => $password
  339. ];
  340. }
  341. if (empty($accounts)) {
  342. throw new LlfException(34520001);
  343. }
  344. // 去重
  345. $this->arrayUnique($accounts);
  346. return $accounts;
  347. }
  348. /**
  349. * 发送异常报告
  350. *
  351. * @param $e \Exception|LlfException
  352. */
  353. private function sendExceptionReport($e)
  354. {
  355. Message::send(sprintf(
  356. lang('100047'),
  357. $e->getFile(),
  358. $e->getLine(),
  359. $e->getMessage(),
  360. $this->username
  361. ), lang('100048') . $e->getMessage());
  362. }
  363. /**
  364. * @throws LlfException
  365. * @throws \Exception
  366. */
  367. public function handle()
  368. {
  369. $accounts = $this->getAccounts();
  370. $totalAccounts = count($accounts);
  371. system_log(sprintf(lang('100049'), $totalAccounts));
  372. foreach ($accounts as $index => $account) {
  373. try {
  374. $this->username = $account['username'];
  375. $this->password = $account['password'];
  376. $num = $index + 1;
  377. system_log(sprintf(lang('100050'), get_local_num($num), $this->username, $num, $totalAccounts));
  378. $this->jar = new CookieJar(); // 所有请求共用一个 CookieJar 实例
  379. if (needAwsWafToken()) {
  380. $awsWafToken = getAwsWafToken();
  381. $this->jar->setCookie(buildAwsWafCookie($awsWafToken));
  382. } else {
  383. system_log(lang('100140'));
  384. }
  385. $this->login($this->username, $this->password);
  386. $domainStatusPage = $this->getDomainStatusPage();
  387. $allDomains = $this->getAllDomains($domainStatusPage);
  388. $token = $this->getToken($domainStatusPage);
  389. $this->renewAllDomains($allDomains, $token);
  390. } catch (WarningException $e) {
  391. system_log(sprintf(lang('100129'), $e->getMessage()));
  392. } catch (LlfException $e) {
  393. system_log(sprintf(lang('100051'), $e->getMessage()));
  394. $this->sendExceptionReport($e);
  395. } catch (\Exception $e) {
  396. system_log(sprintf(lang('100052'), $e->getMessage()), $e->getTrace());
  397. $this->sendExceptionReport($e);
  398. }
  399. }
  400. }
  401. }