Skip to content
Projects
Groups
Snippets
Help
Loading...
Sign in
Toggle navigation
B
browser-backend
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Administrator
browser-backend
Commits
37fb2889
Commit
37fb2889
authored
Aug 22, 2024
by
chenchao.deng
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
发送验证码 +注册流程优化
parent
248b4d9d
Hide whitespace changes
Inline
Side-by-side
Showing
16 changed files
with
457 additions
and
29 deletions
+457
-29
AccountController.java
.../browserbackend/account/controller/AccountController.java
+13
-0
Otp.java
...ain/java/com/edgec/browserbackend/account/domain/Otp.java
+2
-0
AccountService.java
.../edgec/browserbackend/account/service/AccountService.java
+2
-0
AccountServiceImpl.java
...owserbackend/account/service/impl/AccountServiceImpl.java
+15
-0
OAuth2AuthorizationConfig.java
...browserbackend/auth/config/OAuth2AuthorizationConfig.java
+2
-2
OAuth2AuthorizationNewConfig.java
...wserbackend/auth/config/OAuth2AuthorizationNewConfig.java
+142
-0
SMSCodeTokenGranter.java
...edgec/browserbackend/auth/config/SMSCodeTokenGranter.java
+52
-0
ConfigController.java
...c/browserbackend/browser/controller/ConfigController.java
+19
-0
IpResource.java
...a/com/edgec/browserbackend/browser/domain/IpResource.java
+1
-1
ReceptionPlatformOptions.java
...owserbackend/browser/domain/ReceptionPlatformOptions.java
+30
-0
ReceptionPlatformOptionsRepository.java
...rowser/repository/ReceptionPlatformOptionsRepository.java
+17
-0
IpResourceServiceImpl.java
...erbackend/browser/service/Impl/IpResourceServiceImpl.java
+61
-12
IpResourceService.java
...gec/browserbackend/browser/service/IpResourceService.java
+4
-0
BrowserTask.java
...va/com/edgec/browserbackend/browser/task/BrowserTask.java
+65
-0
AliEcsClient.java
.../com/edgec/browserbackend/common/client/AliEcsClient.java
+21
-8
BrowserBackendApplicationTests.java
.../edgec/browserbackend/BrowserBackendApplicationTests.java
+11
-6
No files found.
src/main/java/com/edgec/browserbackend/account/controller/AccountController.java
View file @
37fb2889
...
...
@@ -129,6 +129,19 @@ public class AccountController {
return
resultDto
;
}
@RequestMapping
(
path
=
"/loginAuthCode"
,
method
=
RequestMethod
.
POST
)
public
ResultDto
loginAuthCode
(
@RequestBody
MobileDto
mobile
)
{
ResultDto
resultDto
=
new
ResultDto
();
try
{
accountService
.
loginAuthCode
(
mobile
.
getMobile
());
resultDto
.
setStatus
(
0
);
}
catch
(
ClientRequestException
e
)
{
logger
.
error
(
"fail to send sms"
,
e
);
dealClientRequestException
(
resultDto
,
e
);
}
return
resultDto
;
}
/**
* 用户注册
*/
...
...
src/main/java/com/edgec/browserbackend/account/domain/Otp.java
View file @
37fb2889
...
...
@@ -14,6 +14,8 @@ public class Otp {
@Id
private
String
phone
;
private
String
type
;
//0.登陆 1、
/**
* 发送给用户的短信验证码
*/
...
...
src/main/java/com/edgec/browserbackend/account/service/AccountService.java
View file @
37fb2889
...
...
@@ -113,4 +113,6 @@ public interface AccountService {
boolean
setAuthorize
(
String
username
,
boolean
isAgree
);
void
sendSmsOtpReset
(
String
mobile
);
void
loginAuthCode
(
String
mobile
);
}
src/main/java/com/edgec/browserbackend/account/service/impl/AccountServiceImpl.java
View file @
37fb2889
...
...
@@ -912,6 +912,12 @@ public class AccountServiceImpl implements AccountService {
@Override
public
void
sendSmsOtp
(
String
phone
)
{
// 1. 校验注册用户是否已存在
Account
existing1
=
accountRepository
.
findByName
(
phone
).
orElse
(
null
);
Account
existing2
=
accountRepository
.
findOneByPhoneNumber
(
phone
);
if
(
existing1
!=
null
||
existing2
!=
null
)
{
throw
new
ClientRequestException
(
AccountErrorCode
.
NAMEEXIST
,
"account already exists: "
+
phone
);
}
String
code
=
SmsUtils
.
sendSmsOTP
(
phone
,
SmsTemplateCode
.
NEWACCOUNT
);
Otp
otp
=
new
Otp
();
otp
.
setPhone
(
phone
);
...
...
@@ -1174,6 +1180,15 @@ public class AccountServiceImpl implements AccountService {
otpRepository
.
save
(
otp
);
}
@Override
public
void
loginAuthCode
(
String
mobile
)
{
// Otp otp = new Otp();
// otp.setPhone(phone);
// otp.setOtp(code);
// otp.setCreatedAt(Instant.now().toEpochMilli());
//otpRepository.save(otp);
}
private
void
notifyCustomerRegister
(
Account
contactUs
)
{
StringBuilder
sb
=
new
StringBuilder
();
sb
.
append
(
"Name: "
+
contactUs
.
getName
()
+
"<br/>"
);
...
...
src/main/java/com/edgec/browserbackend/auth/config/OAuth2AuthorizationConfig.java
View file @
37fb2889
...
...
@@ -18,8 +18,8 @@ import org.springframework.security.oauth2.config.annotation.web.configurers.Aut
/**
* @author cdov
*/
@Configuration
@EnableAuthorizationServer
//
@Configuration
//
@EnableAuthorizationServer
public
class
OAuth2AuthorizationConfig
extends
AuthorizationServerConfigurerAdapter
{
private
final
String
NOOP_PASSWORD_ENCODE
=
"{noop}"
;
...
...
src/main/java/com/edgec/browserbackend/auth/config/OAuth2AuthorizationNewConfig.java
0 → 100644
View file @
37fb2889
package
com
.
edgec
.
browserbackend
.
auth
.
config
;
import
com.edgec.browserbackend.auth.service.MongoTokenStore
;
import
com.edgec.browserbackend.auth.service.security.MongoUserDetailsService
;
import
java.util.ArrayList
;
import
java.util.List
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.beans.factory.annotation.Qualifier
;
import
org.springframework.context.annotation.Configuration
;
import
org.springframework.core.env.Environment
;
import
org.springframework.security.authentication.AuthenticationManager
;
import
org.springframework.security.crypto.password.NoOpPasswordEncoder
;
import
org.springframework.security.oauth2.common.OAuth2AccessToken
;
import
org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer
;
import
org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter
;
import
org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer
;
import
org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer
;
import
org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer
;
import
org.springframework.security.oauth2.provider.CompositeTokenGranter
;
import
org.springframework.security.oauth2.provider.OAuth2RequestFactory
;
import
org.springframework.security.oauth2.provider.TokenGranter
;
import
org.springframework.security.oauth2.provider.TokenRequest
;
import
org.springframework.security.oauth2.provider.client.ClientCredentialsTokenGranter
;
import
org.springframework.security.oauth2.provider.code.AuthorizationCodeServices
;
import
org.springframework.security.oauth2.provider.code.AuthorizationCodeTokenGranter
;
import
org.springframework.security.oauth2.provider.implicit.ImplicitTokenGranter
;
import
org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter
;
import
org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter
;
import
org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices
;
/**
* @author cdov
*/
@Configuration
@EnableAuthorizationServer
public
class
OAuth2AuthorizationNewConfig
extends
AuthorizationServerConfigurerAdapter
{
private
final
String
NOOP_PASSWORD_ENCODE
=
"{noop}"
;
@Autowired
private
MongoTokenStore
mongoTokenStore
;
@Autowired
@Qualifier
(
"authenticationManagerBean"
)
private
AuthenticationManager
authenticationManager
;
@Autowired
private
MongoUserDetailsService
userDetailsService
;
@Autowired
private
Environment
env
;
@Autowired
private
OAuthResponseExceptionTranslator
oAuthResponseExceptionTranslator
;
@Override
public
void
configure
(
ClientDetailsServiceConfigurer
clients
)
throws
Exception
{
// TODO persist clients details
// @formatter:off
clients
.
inMemory
()
.
withClient
(
"browser"
)
.
authorizedGrantTypes
(
"refresh_token"
,
"password"
,
"sms"
)
.
scopes
(
"browser"
)
.
accessTokenValiditySeconds
(
7
*
24
*
60
*
60
)
.
refreshTokenValiditySeconds
(
30
*
24
*
60
*
60
)
.
and
()
.
withClient
(
"cloudam-browser"
)
.
secret
(
env
.
getProperty
(
"ACCOUNT_SERVICE_PASSWORD"
))
.
authorizedGrantTypes
(
"client_credentials"
,
"refresh_token"
)
.
scopes
(
"server"
);
// @formatter:on
}
@Override
public
void
configure
(
AuthorizationServerEndpointsConfigurer
endpoints
)
throws
Exception
{
endpoints
.
tokenStore
(
mongoTokenStore
)
.
tokenGranter
(
tokenGranter
(
endpoints
))
.
authenticationManager
(
authenticationManager
)
.
userDetailsService
(
userDetailsService
).
exceptionTranslator
(
oAuthResponseExceptionTranslator
);
}
@Override
public
void
configure
(
AuthorizationServerSecurityConfigurer
oauthServer
)
throws
Exception
{
oauthServer
.
tokenKeyAccess
(
"permitAll()"
)
.
checkTokenAccess
(
"isAuthenticated()"
)
.
passwordEncoder
(
NoOpPasswordEncoder
.
getInstance
())
.
allowFormAuthenticationForClients
();
}
/**
* 自定义TokenGranter
*/
private
TokenGranter
tokenGranter
(
AuthorizationServerEndpointsConfigurer
endpoints
)
{
TokenGranter
tokenGranter
=
new
TokenGranter
()
{
private
CompositeTokenGranter
delegate
;
@Override
public
OAuth2AccessToken
grant
(
String
grantType
,
TokenRequest
tokenRequest
)
{
if
(
delegate
==
null
)
{
delegate
=
new
CompositeTokenGranter
(
getDefaultTokenGranters
(
endpoints
));
}
return
delegate
.
grant
(
grantType
,
tokenRequest
);
}
};
return
tokenGranter
;
}
/**
* 这是从spring 的代码中 copy出来的, 默认的几个TokenGranter, 还原封不动加进去.
* 主要目的是覆盖原来的List<TokenGranter>,方便我们添加自定义的授权方式,比如SMSCodeTokenGranter短信验证码授权
*/
private
List
<
TokenGranter
>
getDefaultTokenGranters
(
AuthorizationServerEndpointsConfigurer
endpoints
)
{
AuthorizationServerTokenServices
tokenServices
=
endpoints
.
getDefaultAuthorizationServerTokenServices
();
AuthorizationCodeServices
authorizationCodeServices
=
endpoints
.
getAuthorizationCodeServices
();
OAuth2RequestFactory
requestFactory
=
endpoints
.
getOAuth2RequestFactory
();
List
<
TokenGranter
>
tokenGranters
=
new
ArrayList
<
TokenGranter
>();
tokenGranters
.
add
(
new
AuthorizationCodeTokenGranter
(
tokenServices
,
authorizationCodeServices
,
endpoints
.
getClientDetailsService
(),
requestFactory
));
tokenGranters
.
add
(
new
RefreshTokenGranter
(
tokenServices
,
endpoints
.
getClientDetailsService
(),
requestFactory
));
ImplicitTokenGranter
implicit
=
new
ImplicitTokenGranter
(
tokenServices
,
endpoints
.
getClientDetailsService
(),
requestFactory
);
tokenGranters
.
add
(
implicit
);
tokenGranters
.
add
(
new
ClientCredentialsTokenGranter
(
tokenServices
,
endpoints
.
getClientDetailsService
(),
requestFactory
));
if
(
authenticationManager
!=
null
)
{
tokenGranters
.
add
(
new
ResourceOwnerPasswordTokenGranter
(
authenticationManager
,
tokenServices
,
endpoints
.
getClientDetailsService
(),
requestFactory
));
}
// 这里就是我们自己的授权验证
tokenGranters
.
add
(
new
SMSCodeTokenGranter
(
tokenServices
,
endpoints
.
getClientDetailsService
(),
requestFactory
,
"sms"
));
// 再有其他的验证, 就往下面添加....
return
tokenGranters
;
}
}
src/main/java/com/edgec/browserbackend/auth/config/SMSCodeTokenGranter.java
0 → 100644
View file @
37fb2889
package
com
.
edgec
.
browserbackend
.
auth
.
config
;
import
com.edgec.browserbackend.auth.domain.User
;
import
com.edgec.browserbackend.auth.domain.mongo.MongoOAuth2AccessToken
;
import
com.edgec.browserbackend.auth.repository.mongo.MongoOAuth2AccessTokenRepository
;
import
java.util.LinkedHashMap
;
import
java.util.Map
;
import
org.apache.tomcat.util.net.openssl.ciphers.Authentication
;
import
org.springframework.security.authentication.AbstractAuthenticationToken
;
import
org.springframework.security.authentication.UsernamePasswordAuthenticationToken
;
import
org.springframework.security.oauth2.provider.ClientDetails
;
import
org.springframework.security.oauth2.provider.ClientDetailsService
;
import
org.springframework.security.oauth2.provider.OAuth2Authentication
;
import
org.springframework.security.oauth2.provider.OAuth2Request
;
import
org.springframework.security.oauth2.provider.OAuth2RequestFactory
;
import
org.springframework.security.oauth2.provider.TokenGranter
;
import
org.springframework.security.oauth2.provider.TokenRequest
;
import
org.springframework.security.oauth2.provider.token.AbstractTokenGranter
;
import
org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices
;
/**
* XXXX
*
* @Author: Chen
* @Date: 2024/08/22
*/
public
class
SMSCodeTokenGranter
extends
AbstractTokenGranter
{
public
SMSCodeTokenGranter
(
AuthorizationServerTokenServices
tokenServices
,
ClientDetailsService
clientDetailsService
,
OAuth2RequestFactory
requestFactory
,
String
grantType
)
{
super
(
tokenServices
,
clientDetailsService
,
requestFactory
,
grantType
);
}
@Override
protected
OAuth2Authentication
getOAuth2Authentication
(
ClientDetails
client
,
TokenRequest
tokenRequest
)
{
Map
<
String
,
String
>
parameters
=
new
LinkedHashMap
<
String
,
String
>(
tokenRequest
.
getRequestParameters
());
String
userMobileNo
=
parameters
.
get
(
"mobile"
);
//客户端提交的用户名
String
smsCode
=
parameters
.
get
(
"smscode"
);
//客户端提交的验证码
/** 下面写自己的验证逻辑 */
User
user
=
new
User
();
user
.
setPhone
(
"11111111"
);
UsernamePasswordAuthenticationToken
userAuth
=
new
UsernamePasswordAuthenticationToken
(
user
,
null
,
user
.
getAuthorities
());
((
AbstractAuthenticationToken
)
userAuth
).
setDetails
(
parameters
);
OAuth2Request
storedOAuth2Request
=
getRequestFactory
().
createOAuth2Request
(
client
,
tokenRequest
);
return
new
OAuth2Authentication
(
storedOAuth2Request
,
userAuth
);
}
}
src/main/java/com/edgec/browserbackend/browser/controller/ConfigController.java
View file @
37fb2889
...
...
@@ -81,4 +81,23 @@ public class ConfigController {
return
ResponseUtil
.
error
(
e
.
getMessage
());
}
}
/**
* 获取所属平台配置选项(电商前台
*
* @return ResultDto
*/
@RequestMapping
(
value
=
"/receptionPlatformOptions"
,
method
=
RequestMethod
.
POST
)
public
ResultDto
receptionPlatformOptions
()
{
String
logs
=
"【receptionPlatformOptions】 "
;
try
{
return
ResponseUtil
.
success
(
ipResourceService
.
getReceptionPlatformOptions
());
}
catch
(
ClientRequestException
e
)
{
log
.
warn
(
"{}, ClientRequestException : {}"
,
logs
,
e
.
getErrorCode
().
getReason
());
return
ResponseUtil
.
error
(
e
.
getErrorCode
());
}
catch
(
Exception
e
)
{
log
.
error
(
"{}, Exception : {}"
,
logs
,
e
.
getMessage
(),
e
);
return
ResponseUtil
.
error
(
e
.
getMessage
());
}
}
}
src/main/java/com/edgec/browserbackend/browser/domain/IpResource.java
View file @
37fb2889
...
...
@@ -46,7 +46,7 @@ public class IpResource implements Serializable {
/**
* ip 的状态
* 0:正常, 1:已过期, 2:即将过期, 3:正在分配, 4:未使用, 5:已失效, 6:未分配, 7:未缴费, 8:分配成功
* 0:正常, 1:已过期, 2:即将过期, 3:正在分配, 4:未使用, 5:已失效, 6:未分配, 7:未缴费, 8:分配成功
9:续费中
*/
private
int
status
;
...
...
src/main/java/com/edgec/browserbackend/browser/domain/ReceptionPlatformOptions.java
0 → 100644
View file @
37fb2889
package
com
.
edgec
.
browserbackend
.
browser
.
domain
;
import
java.util.Map
;
import
lombok.Getter
;
import
lombok.Setter
;
import
org.springframework.data.mongodb.core.mapping.Document
;
/**
* @author Chen
* @description 电商前台网站记录
* @date 2024/8/21 19:23
*/
@Getter
@Setter
@Document
(
"receptionPlatformOptions"
)
public
class
ReceptionPlatformOptions
{
private
String
platform
;
//平台
private
String
url
;
//网址
private
int
platformType
;
//平台类型: 1:全球开店 2:亚马逊站点
private
int
childType
;
//子类型
private
String
pictureUrl
;
//图片地址
private
int
weight
;
//权重
}
src/main/java/com/edgec/browserbackend/browser/repository/ReceptionPlatformOptionsRepository.java
0 → 100644
View file @
37fb2889
package
com
.
edgec
.
browserbackend
.
browser
.
repository
;
import
com.edgec.browserbackend.browser.domain.PlatformOptions
;
import
com.edgec.browserbackend.browser.domain.ReceptionPlatformOptions
;
import
java.util.List
;
import
org.springframework.data.mongodb.repository.MongoRepository
;
/**
* @author Chen
* @description 电商前台网站记录
* @date 2024/8/21 22:51
*/
public
interface
ReceptionPlatformOptionsRepository
extends
MongoRepository
<
ReceptionPlatformOptions
,
String
>
{
List
<
ReceptionPlatformOptions
>
findAllByOrderByPlatformTypeAscChildTypeAscWeightDesc
();
}
\ No newline at end of file
src/main/java/com/edgec/browserbackend/browser/service/Impl/IpResourceServiceImpl.java
View file @
37fb2889
...
...
@@ -2,6 +2,9 @@ package com.edgec.browserbackend.browser.service.Impl;
import
com.alibaba.fastjson.JSON
;
import
com.alibaba.fastjson.JSONObject
;
import
com.aliyun.sdk.service.ecs20140526.models.DescribeInstancesResponse
;
import
com.aliyun.sdk.service.ecs20140526.models.DescribeInstancesResponseBody.Instance
;
import
com.aliyun.sdk.service.ecs20140526.models.RenewInstanceResponse
;
import
com.edgec.browserbackend.account.controller.LimitedUsers
;
import
com.edgec.browserbackend.account.domain.Account
;
import
com.edgec.browserbackend.account.domain.IpChargeRequestDto
;
...
...
@@ -12,12 +15,16 @@ import com.edgec.browserbackend.account.service.AccountService;
import
com.edgec.browserbackend.browser.ErrorCode.BrowserErrorCode
;
import
com.edgec.browserbackend.browser.domain.*
;
import
com.edgec.browserbackend.browser.dto.*
;
import
com.edgec.browserbackend.browser.dto.IpBuyResultDto.IPData
;
import
com.edgec.browserbackend.browser.repository.*
;
import
com.edgec.browserbackend.browser.service.IpAndShopService
;
import
com.edgec.browserbackend.browser.service.IpResourceService
;
import
com.edgec.browserbackend.common.client.AliEcsClient
;
import
com.edgec.browserbackend.common.commons.error.ClientRequestException
;
import
com.edgec.browserbackend.common.commons.utils.NotifyUtils
;
import
com.edgec.browserbackend.common.utils.FileUtil
;
import
java.time.format.DateTimeFormatter
;
import
javax.annotation.Resource
;
import
org.apache.commons.collections4.CollectionUtils
;
import
org.apache.commons.lang3.StringUtils
;
import
org.jetbrains.annotations.NotNull
;
...
...
@@ -140,6 +147,12 @@ public class IpResourceServiceImpl implements IpResourceService {
@Autowired
private
SpecialLineRepository
specialLineRepository
;
@Resource
private
ReceptionPlatformOptionsRepository
receptionPlatformOptionsRepository
;
@Resource
private
CloudPlatformOrderRepository
cloudPlatformOrderRepository
;
public
HttpHeaders
buildPostHeader
()
{
HttpHeaders
header
=
new
HttpHeaders
();
header
.
setContentType
(
MediaType
.
APPLICATION_JSON
);
...
...
@@ -346,7 +359,7 @@ public class IpResourceServiceImpl implements IpResourceService {
IpOperationResultDto
ipOperationResultDto
=
new
IpOperationResultDto
();
List
<
String
>
failedList
=
ipResourceRequestDto
.
getAddr
();
if
(
ipResourceRequestDto
.
getAddr
()
!=
null
&&
ipResourceRequestDto
.
getAddr
().
size
()
>
0
)
{
// 6.1
远程调用 云E
续费 传入的所有的 ip,校验是否续费成功
// 6.1 续费 传入的所有的 ip,校验是否续费成功
RenewIpResultDto
renewIpResultDto
=
getRenewIpResultDto
(
ipResourceRequestDto
,
period
);
if
(
StringUtils
.
isNotBlank
(
renewIpResultDto
.
getErrorCode
()))
{
logger
.
error
(
renewIpResultDto
.
getErrorCode
());
...
...
@@ -373,7 +386,7 @@ public class IpResourceServiceImpl implements IpResourceService {
accountService
.
chargeByMoney
(
username
,
newprice1
*
ipResourceRequestDto
.
getPeriod
()
*
ipResourceRequestDto
.
getAmount
(),
ipChargeRequestDto
);
// 更新ip资源的到期时间
ipResource
.
set
ValidTime
(
Instant
.
parse
(
x
.
getValidTill
()).
toEpochMilli
()
);
ipResource
.
set
Status
(
9
);
ipResourceRepository
.
save
(
ipResource
);
// 封装 ipOperationResultDto
...
...
@@ -913,6 +926,18 @@ public class IpResourceServiceImpl implements IpResourceService {
return
platformOptionsRepository
.
updatePlatformOptions
(
platform
,
subPlatform
,
url
);
}
@Override
public
List
<
ReceptionPlatformOptions
>
getReceptionPlatformOptions
()
{
try
{
List
<
ReceptionPlatformOptions
>
platformOptions
=
receptionPlatformOptionsRepository
.
findAllByOrderByPlatformTypeAscChildTypeAscWeightDesc
();
return
platformOptions
;
}
catch
(
Exception
e
)
{
logger
.
error
(
e
.
getMessage
());
throw
new
ClientRequestException
(
BrowserErrorCode
.
UNKNOWN
);
}
}
private
IpChargeRequestDto
buildIpChargeRequestDto
(
IpResourceRequestDto
request
,
int
chargeType
,
int
payMethod
)
{
IpChargeRequestDto
ipChargeRequestDto
=
new
IpChargeRequestDto
();
...
...
@@ -1085,16 +1110,40 @@ public class IpResourceServiceImpl implements IpResourceService {
@Nullable
private
RenewIpResultDto
getRenewIpResultDto
(
IpResourceRequestDto
ipResourceRequestDto
,
int
period
)
{
RestTemplate
restTemplate
=
new
RestTemplate
();
RenewIpResultDto
renewIpResultDto
=
new
RenewIpResultDto
();
List
<
IPData
>
ipDataList
=
new
ArrayList
<>();
for
(
String
s
:
ipResourceRequestDto
.
getAddr
())
{
IpResource
ipResource
=
ipResourceRepository
.
findByAddrAndIsDeleted
(
s
,
false
);
List
<
CloudPlatformOrder
>
cloudPlatformOrders
=
cloudPlatformOrderRepository
.
findByOwnerAndIpResourceId
(
ipResource
.
getOwner
(),
ipResource
.
getId
());
if
(
CollectionUtils
.
isEmpty
(
cloudPlatformOrders
))
{
logger
.
error
(
"queryIpTask- 查询云平台订单失败:入参:{}"
,
JSON
.
toJSON
(
ipResource
));
continue
;
}
CloudPlatformOrder
cloudPlatformOrder
=
cloudPlatformOrders
.
get
(
0
);
if
(
"aliyun"
.
equals
(
cloudPlatformOrder
.
getPlatformType
())){
String
periodUnit
=
ipResourceRequestDto
.
getUnit
().
equals
(
"week"
)
?
"Week"
:
"Month"
;
RenewInstanceResponse
response
=
AliEcsClient
.
renewInstance
(
ipResource
.
getOwner
(),
cloudPlatformOrder
.
getRegionId
(),
cloudPlatformOrder
.
getPlatformOrderId
(),
period
,
periodUnit
);
if
(
null
==
response
||
!
response
.
getStatusCode
().
equals
(
200
))
{
logger
.
error
(
"fail to renew ip : {}"
,
JSON
.
toJSON
(
response
));
}
else
if
(
Objects
.
nonNull
(
response
.
getBody
())){
IPData
ipData
=
new
IPData
();
ipData
.
setIp
(
ipResource
.
getAddr
());
ipDataList
.
add
(
ipData
);
HashMap
<
String
,
Object
>
map
=
new
HashMap
<>();
map
.
put
(
"iplist"
,
ipResourceRequestDto
.
getAddr
());
map
.
put
(
"period"
,
period
);
map
.
put
(
"unit"
,
ipResourceRequestDto
.
getUnit
());
HttpHeaders
headers
=
buildPostHeader
();
HttpEntity
<
Map
<
String
,
Object
>>
entity
=
new
HttpEntity
<>(
map
,
headers
);
String
URL
=
(
profiles
.
equals
(
"dev"
)
||
profiles
.
equals
(
"staging"
))
?
TESTURL
:
CLOUDAMURL
;
ResponseEntity
<
String
>
result
=
restTemplate
.
exchange
(
URL
+
"/intelligroup/renewip?accountId=browser"
,
HttpMethod
.
PUT
,
entity
,
String
.
class
);
return
JSON
.
parseObject
(
result
.
getBody
(),
RenewIpResultDto
.
class
);
}
}
}
if
(
CollectionUtils
.
isNotEmpty
(
ipDataList
))
{
renewIpResultDto
.
setIplist
(
ipDataList
);
}
else
{
renewIpResultDto
.
setErrorCode
(
"续费ip失败,请联系客服"
);
}
return
renewIpResultDto
;
}
}
src/main/java/com/edgec/browserbackend/browser/service/IpResourceService.java
View file @
37fb2889
...
...
@@ -3,6 +3,7 @@ package com.edgec.browserbackend.browser.service;
import
com.edgec.browserbackend.browser.domain.IpOptions
;
import
com.edgec.browserbackend.browser.domain.IpSummary
;
import
com.edgec.browserbackend.browser.domain.PlatformOptions
;
import
com.edgec.browserbackend.browser.domain.ReceptionPlatformOptions
;
import
com.edgec.browserbackend.browser.dto.*
;
import
java.security.Principal
;
...
...
@@ -50,4 +51,7 @@ public interface IpResourceService {
* @return boolean
*/
boolean
updatePlatformOptions
(
Principal
principal
,
String
platform
,
String
subPlatform
,
String
url
);
List
<
ReceptionPlatformOptions
>
getReceptionPlatformOptions
();
}
src/main/java/com/edgec/browserbackend/browser/task/BrowserTask.java
View file @
37fb2889
...
...
@@ -374,6 +374,71 @@ public class BrowserTask {
}
}
@Scheduled
(
cron
=
"0 0/1 * * * ?"
)
public
void
queryIpRenewTasks
()
{
long
time
=
Instant
.
now
().
minusSeconds
(
300
).
toEpochMilli
();
List
<
IpResource
>
ipResources
=
ipResourceRepository
.
sampleTasks
(
9
,
time
);
for
(
IpResource
ipResource
:
ipResources
)
{
long
start
=
System
.
currentTimeMillis
();
CompletableFuture
.
runAsync
(
()
->
{
if
(
ipResourceRepository
.
lockTask
(
ipResource
))
{
try
{
//查询cloudPlatform
List
<
CloudPlatformOrder
>
cloudPlatformOrders
=
cloudPlatformOrderRepository
.
findByOwnerAndIpResourceId
(
ipResource
.
getOwner
(),
ipResource
.
getId
());
if
(
CollectionUtils
.
isEmpty
(
cloudPlatformOrders
))
{
log
.
error
(
"queryIpRenewTasks- 查询云平台订单失败:入参:{}"
,
JSON
.
toJSON
(
ipResource
));
return
;
}
CloudPlatformOrder
cloudPlatformOrder
=
cloudPlatformOrders
.
get
(
0
);
if
(
"aliyun"
.
equals
(
cloudPlatformOrder
.
getPlatformType
()))
{
DescribeInstancesResponse
response
=
AliEcsClient
.
getDescribeInstances
(
ipResource
.
getOwner
(),
cloudPlatformOrder
.
getPlatformOrderId
(),
cloudPlatformOrder
.
getRegionId
());
if
(!
response
.
getStatusCode
().
equals
(
200
))
{
log
.
error
(
", fail to query ip : {}"
,
JSON
.
toJSON
(
response
.
getBody
()));
}
if
(
Objects
.
nonNull
(
response
.
getBody
()))
{
//判断是否重复购买
Instance
instance
=
response
.
getBody
().
getInstances
()
.
getInstance
().
get
(
0
);
if
(
instance
.
getInstanceChargeType
().
equals
(
"PrePaid"
))
{
//包年包夜 更新ip状态
ipResource
.
setStatus
(
0
);
DateTimeFormatter
formatter
=
DateTimeFormatter
.
ofPattern
(
"yyyy-MM-dd'T'HH:mmX"
);
Instant
instant
=
Instant
.
from
(
formatter
.
parse
(
instance
.
getExpiredTime
()));
ipResource
.
setValidTime
(
instant
.
toEpochMilli
());
ipResourceRepository
.
save
(
ipResource
);
}
}
}
}
catch
(
Exception
e
)
{
log
.
error
(
e
.
getMessage
(),
e
);
NotifyUtils
.
sendMessage
(
"浏览器后端 queryIpTasks() 又炸了,赶紧看啊"
,
e
,
NotifyUtils
.
MsgType
.
WEBHOOK
);
}
finally
{
long
end
=
System
.
currentTimeMillis
();
log
.
debug
(
"queryIpTask {} execution time is: "
+
(
end
-
start
)
/
1000
+
"s"
,
ipResource
.
getId
());
try
{
ipResourceRepository
.
unLockTask
(
ipResource
.
getId
());
}
catch
(
Throwable
th
)
{
log
.
error
(
"unlock failed"
,
th
);
//try again
ipResourceRepository
.
unLockTask
(
ipResource
.
getId
());
}
}
}
},
ThreadPoolUtils
.
queryIpTasksPool
);
}
}
/**
* 购买ip的定时任务,每分钟一次
*/
...
...
src/main/java/com/edgec/browserbackend/common/client/AliEcsClient.java
View file @
37fb2889
...
...
@@ -115,15 +115,28 @@ public class AliEcsClient {
/**
* 续费实例
*/
public
static
RenewInstanceResponse
renewInstance
(
String
regionId
)
throws
Exception
{
RenewInstanceRequest
renewInstanceRequest
=
RenewInstanceRequest
.
builder
()
//TODO待确定传参
.
build
();
public
static
RenewInstanceResponse
renewInstance
(
String
owner
,
String
regionId
,
String
instanceId
,
Integer
period
,
String
periodUnit
){
AsyncClient
client
=
createClient
(
regionId
);
CompletableFuture
<
RenewInstanceResponse
>
response
=
client
.
renewInstance
(
renewInstanceRequest
);
client
.
close
();
return
response
.
get
();
RenewInstanceResponse
renewInstanceResponse
=
null
;
try
{
RenewInstanceRequest
renewInstanceRequest
=
RenewInstanceRequest
.
builder
()
.
instanceId
(
instanceId
)
.
period
(
period
)
.
periodUnit
(
periodUnit
)
.
build
();
log
.
info
(
"调用aliEcs续费实例,入参:owner:{},regionId:{},instanceId:{},period:{},periodUnit:{}"
,
owner
,
regionId
,
instanceId
,
period
,
periodUnit
);
CompletableFuture
<
RenewInstanceResponse
>
response
=
client
.
renewInstance
(
renewInstanceRequest
);
renewInstanceResponse
=
response
.
get
();
log
.
info
(
"调用aliEcs续费实例,响应参数:owner:{},response:{}"
,
owner
,
JSON
.
toJSON
(
renewInstanceResponse
));
}
catch
(
Exception
e
)
{
log
.
error
(
"fail to aliEcs runInstances {}"
,
e
.
getMessage
());
}
finally
{
client
.
close
();
}
return
renewInstanceResponse
;
}
/**
...
...
src/test/java/com/edgec/browserbackend/BrowserBackendApplicationTests.java
View file @
37fb2889
...
...
@@ -6,8 +6,10 @@ import com.edgec.browserbackend.account.domain.UserBalance;
import
com.edgec.browserbackend.account.repository.UserBalanceRepository
;
import
com.edgec.browserbackend.browser.domain.CloudPlatformConfig
;
import
com.edgec.browserbackend.browser.domain.IpHistory
;
import
com.edgec.browserbackend.browser.domain.ReceptionPlatformOptions
;
import
com.edgec.browserbackend.browser.repository.CloudPlatformConfigRepository
;
import
com.edgec.browserbackend.browser.repository.IpHistoryRepository
;
import
com.edgec.browserbackend.browser.repository.ReceptionPlatformOptionsRepository
;
import
com.edgec.browserbackend.browser.task.BrowserTask
;
import
com.edgec.browserbackend.common.client.AliEcsClient
;
import
com.edgec.browserbackend.common.commons.utils.SmsUtils
;
...
...
@@ -21,7 +23,7 @@ import org.springframework.boot.test.context.SpringBootTest;
class
BrowserBackendApplicationTests
{
@Resource
private
UserBalanceRepository
userBalanceR
epository
;
private
ReceptionPlatformOptionsRepository
r
epository
;
@Resource
private
BrowserTask
browserTask
;
...
...
@@ -30,11 +32,14 @@ class BrowserBackendApplicationTests {
private
CloudPlatformConfigRepository
cloudPlatformConfigRepository
;
@Test
void
contextLoads
()
{
UserBalance
userBalance
=
new
UserBalance
();
userBalance
.
setUsername
(
"13323269174"
);
userBalance
.
setBalanced
(
100
l
);
userBalance
.
setUsed
(
0
l
);
userBalanceRepository
.
save
(
userBalance
);
ReceptionPlatformOptions
receptionPlatformOptions
=
new
ReceptionPlatformOptions
();
receptionPlatformOptions
.
setPlatformType
(
1
);
receptionPlatformOptions
.
setChildType
(
1
);
receptionPlatformOptions
.
setPlatform
(
"敦煌网"
);
receptionPlatformOptions
.
setUrl
(
"https:www.dhgate.com"
);
receptionPlatformOptions
.
setPictureUrl
(
"https://ip-image.oss-rg-china-mainland.aliyuncs.com/app_image/app_image/dhgate.png"
);
receptionPlatformOptions
.
setWeight
(
100
);
repository
.
save
(
receptionPlatformOptions
);
}
@Test
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment