FreeNom.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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 GuzzleHttp\Client;
  13. use GuzzleHttp\Cookie\CookieJar;
  14. use Luolongfei\Libs\Log;
  15. use Luolongfei\Libs\Message;
  16. use Luolongfei\Libs\MessageServices\Mail;
  17. use Luolongfei\Libs\MessageServices\TelegramBot;
  18. class FreeNom
  19. {
  20. const VERSION = 'v0.4';
  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. * @var FreeNom
  36. */
  37. protected static $instance;
  38. /**
  39. * @var Client
  40. */
  41. protected $client;
  42. /**
  43. * @var CookieJar | bool
  44. */
  45. protected $jar = true;
  46. /**
  47. * @var string FreeNom 账户
  48. */
  49. protected $username;
  50. /**
  51. * @var string FreeNom 密码
  52. */
  53. protected $password;
  54. public function __construct()
  55. {
  56. $this->client = new Client([
  57. 'headers' => [
  58. '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',
  59. 'Accept-Encoding' => 'gzip, deflate, br',
  60. 'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
  61. ],
  62. 'timeout' => self::TIMEOUT,
  63. CURLOPT_FOLLOWLOCATION => true,
  64. CURLOPT_AUTOREFERER => true,
  65. 'verify' => config('verify_ssl'),
  66. 'debug' => config('debug')
  67. ]);
  68. system_log(sprintf('当前程序版本 %s', self::VERSION));
  69. }
  70. /**
  71. * @return FreeNom
  72. */
  73. public static function getInstance()
  74. {
  75. if (!self::$instance instanceof self) {
  76. self::$instance = new self();
  77. }
  78. return self::$instance;
  79. }
  80. /**
  81. * 登录
  82. *
  83. * @param string $username
  84. * @param string $password
  85. *
  86. * @return bool
  87. * @throws LlfException
  88. */
  89. protected function login(string $username, string $password)
  90. {
  91. try {
  92. $this->client->post(self::LOGIN_URL, [
  93. 'headers' => [
  94. 'Content-Type' => 'application/x-www-form-urlencoded',
  95. 'Referer' => 'https://my.freenom.com/clientarea.php'
  96. ],
  97. 'form_params' => [
  98. 'username' => $username,
  99. 'password' => $password
  100. ],
  101. 'cookies' => $this->jar
  102. ]);
  103. } catch (\Exception $e) {
  104. throw new LlfException(34520002, $e->getMessage());
  105. }
  106. if (empty($this->jar->getCookieByName('WHMCSZH5eHTGhfvzP')->getValue())) {
  107. throw new LlfException(34520002, lang('error_msg.100001'));
  108. }
  109. return true;
  110. }
  111. /**
  112. * 匹配获取所有域名
  113. *
  114. * @param string $domainStatusPage
  115. *
  116. * @return array
  117. * @throws LlfException
  118. */
  119. protected function getAllDomains(string $domainStatusPage)
  120. {
  121. if (!preg_match_all(self::DOMAIN_INFO_REGEX, $domainStatusPage, $allDomains, PREG_SET_ORDER)) {
  122. throw new LlfException(34520003);
  123. }
  124. return $allDomains;
  125. }
  126. /**
  127. * 获取匹配 token
  128. *
  129. * 据观察,每次登录后此 token 不会改变,故可以只获取一次,多次使用
  130. *
  131. * @param string $domainStatusPage
  132. *
  133. * @return string
  134. * @throws LlfException
  135. */
  136. protected function getToken(string $domainStatusPage)
  137. {
  138. if (!preg_match(self::TOKEN_REGEX, $domainStatusPage, $matches)) {
  139. throw new LlfException(34520004);
  140. }
  141. return $matches['token'];
  142. }
  143. /**
  144. * 获取域名状态页面
  145. *
  146. * @return string
  147. * @throws LlfException
  148. */
  149. protected function getDomainStatusPage()
  150. {
  151. try {
  152. $resp = $this->client->get(self::DOMAIN_STATUS_URL, [
  153. 'headers' => [
  154. 'Referer' => 'https://my.freenom.com/clientarea.php'
  155. ],
  156. 'cookies' => $this->jar
  157. ]);
  158. $page = (string)$resp->getBody();
  159. } catch (\Exception $e) {
  160. throw new LlfException(34520013, $e->getMessage());
  161. }
  162. if (!preg_match(self::LOGIN_STATUS_REGEX, $page)) {
  163. throw new LlfException(34520009);
  164. }
  165. return $page;
  166. }
  167. /**
  168. * 续期所有域名
  169. *
  170. * @param array $allDomains
  171. * @param string $token
  172. *
  173. * @return bool
  174. */
  175. public function renewAllDomains(array $allDomains, string $token)
  176. {
  177. $renewalSuccessArr = [];
  178. $renewalFailuresArr = [];
  179. $domainStatusArr = [];
  180. foreach ($allDomains as $d) {
  181. $domain = $d['domain'];
  182. $days = (int)$d['days'];
  183. $id = $d['id'];
  184. // 免费域名只允许在到期前 14 天内续期
  185. if ($days <= 14) {
  186. $renewalResult = $this->renew($id, $token);
  187. sleep(1);
  188. if ($renewalResult) {
  189. $renewalSuccessArr[] = $domain;
  190. continue; // 续期成功的域名无需记录过期天数
  191. } else {
  192. $renewalFailuresArr[] = $domain;
  193. }
  194. }
  195. // 记录域名过期天数
  196. $domainStatusArr[$domain] = $days;
  197. }
  198. // 存在续期操作
  199. if ($renewalSuccessArr || $renewalFailuresArr) {
  200. $data = [
  201. 'username' => $this->username,
  202. 'renewalSuccessArr' => $renewalSuccessArr,
  203. 'renewalFailuresArr' => $renewalFailuresArr,
  204. 'domainStatusArr' => $domainStatusArr,
  205. ];
  206. Message::send('', '主人,我刚刚帮你续期域名啦~', 2, $data);
  207. system_log(sprintf(
  208. '恭喜,成功续期 <green>%d</green> 个域名,失败 <green>%d</green> 个域名,详细的续期结果已送信成功,请注意查收',
  209. count($renewalSuccessArr),
  210. count($renewalFailuresArr)
  211. ));
  212. Log::info(sprintf("账户:%s\n续期结果如下:\n", $this->username), $data);
  213. return true;
  214. }
  215. // 不存在续期操作
  216. if (config('notice_freq') === 1) {
  217. $data = [
  218. 'username' => $this->username,
  219. 'domainStatusArr' => $domainStatusArr,
  220. ];
  221. Message::send('', '报告,今天没有域名需要续期', 3, $data);
  222. system_log('域名状态信息已送信成功,请注意查收');
  223. } else {
  224. system_log('当前通知频率为「仅当有续期操作时」,故本次不会推送通知');
  225. }
  226. system_log(sprintf('%s:<green>执行成功,今次没有需要续期的域名</green>', $this->username));
  227. return true;
  228. }
  229. /**
  230. * 续期单个域名
  231. *
  232. * @param int $id
  233. * @param string $token
  234. *
  235. * @return bool
  236. */
  237. protected function renew(int $id, string $token)
  238. {
  239. try {
  240. $resp = $this->client->post(self::RENEW_DOMAIN_URL, [
  241. 'headers' => [
  242. 'Referer' => sprintf('https://my.freenom.com/domains.php?a=renewdomain&domain=%s', $id),
  243. 'Content-Type' => 'application/x-www-form-urlencoded'
  244. ],
  245. 'form_params' => [
  246. 'token' => $token,
  247. 'renewalid' => $id,
  248. sprintf('renewalperiod[%s]', $id) => '12M', // 续期一年
  249. 'paymentmethod' => 'credit', // 支付方式:信用卡
  250. ],
  251. 'cookies' => $this->jar
  252. ]);
  253. $resp = (string)$resp->getBody();
  254. return stripos($resp, 'Order Confirmation') !== false;
  255. } catch (\Exception $e) {
  256. $errorMsg = sprintf('续期请求出错:%s,域名 ID:%s(账户:%s)', $e->getMessage(), $id, $this->username);
  257. system_log($errorMsg);
  258. Message::send($errorMsg);
  259. return false;
  260. }
  261. }
  262. /**
  263. * 二维数组去重
  264. *
  265. * @param array $array 原始数组
  266. * @param array $keys 可指定对应的键联合
  267. *
  268. * @return bool
  269. */
  270. public function arrayUnique(array &$array, array $keys = [])
  271. {
  272. if (!isset($array[0]) || !is_array($array[0])) {
  273. return false;
  274. }
  275. if (empty($keys)) {
  276. $keys = array_keys($array[0]);
  277. }
  278. $tmp = [];
  279. foreach ($array as $k => $items) {
  280. $combinedKey = '';
  281. foreach ($keys as $key) {
  282. $combinedKey .= $items[$key];
  283. }
  284. if (isset($tmp[$combinedKey])) {
  285. unset($array[$k]);
  286. } else {
  287. $tmp[$combinedKey] = $k;
  288. }
  289. }
  290. unset($tmp);
  291. return true;
  292. }
  293. /**
  294. * 获取 FreeNom 账户信息
  295. *
  296. * @return array
  297. * @throws LlfException
  298. */
  299. protected function getAccounts()
  300. {
  301. $accounts = [];
  302. $multipleAccounts = preg_replace('/\s/', '', env('MULTIPLE_ACCOUNTS'));
  303. if (preg_match_all('/<(?P<u>.*?)>@<(?P<p>.*?)>/i', $multipleAccounts, $matches, PREG_SET_ORDER)) {
  304. foreach ($matches as $m) {
  305. $accounts[] = [
  306. 'username' => $m['u'],
  307. 'password' => $m['p']
  308. ];
  309. }
  310. }
  311. $username = env('FREENOM_USERNAME');
  312. $password = env('FREENOM_PASSWORD');
  313. if ($username && $password) {
  314. $accounts[] = [
  315. 'username' => $username,
  316. 'password' => $password
  317. ];
  318. }
  319. if (empty($accounts)) {
  320. throw new LlfException(34520001);
  321. }
  322. // 去重
  323. $this->arrayUnique($accounts);
  324. return $accounts;
  325. }
  326. /**
  327. * 发送异常报告
  328. *
  329. * @param $e \Exception|LlfException
  330. */
  331. private function sendExceptionReport($e)
  332. {
  333. Message::send(sprintf(
  334. '具体是在%s文件的第%d行,抛出了一个异常。异常的内容是%s,快去看看吧。(账户:%s)',
  335. $e->getFile(),
  336. $e->getLine(),
  337. $e->getMessage(),
  338. $this->username
  339. ), '主人,出错了,' . $e->getMessage());
  340. }
  341. /**
  342. * @throws LlfException
  343. * @throws \Exception
  344. */
  345. public function handle()
  346. {
  347. $accounts = $this->getAccounts();
  348. foreach ($accounts as $account) {
  349. try {
  350. $this->username = $account['username'];
  351. $this->password = $account['password'];
  352. $this->jar = new CookieJar(); // 所有请求共用一个 CookieJar 实例
  353. $this->login($this->username, $this->password);
  354. $domainStatusPage = $this->getDomainStatusPage();
  355. $allDomains = $this->getAllDomains($domainStatusPage);
  356. $token = $this->getToken($domainStatusPage);
  357. $this->renewAllDomains($allDomains, $token);
  358. } catch (LlfException $e) {
  359. system_log(sprintf('出错:<red>%s</red>', $e->getMessage()));
  360. $this->sendExceptionReport($e);
  361. } catch (\Exception $e) {
  362. system_log(sprintf('出错:<red>%s</red>', $e->getMessage()), $e->getTrace());
  363. $this->sendExceptionReport($e);
  364. }
  365. }
  366. }
  367. }