Browse Source

支持AliYunDriver

main
zhouxin 4 years ago
parent
commit
f6630111de
  1. 5
      src/main/java/com/github/zxbu/webdavteambition/WebdavTeambitionApplication.java
  2. 77
      src/main/java/com/github/zxbu/webdavteambition/client/AliYunDriverClient.java
  3. 43
      src/main/java/com/github/zxbu/webdavteambition/config/AliYunDriveProperties.java
  4. 41
      src/main/java/com/github/zxbu/webdavteambition/config/TeambitionAutoConfig.java
  5. 88
      src/main/java/com/github/zxbu/webdavteambition/config/TeambitionProperties.java
  6. 40
      src/main/java/com/github/zxbu/webdavteambition/model/BaseQuery.java
  7. 22
      src/main/java/com/github/zxbu/webdavteambition/model/FileGetRequest.java
  8. 67
      src/main/java/com/github/zxbu/webdavteambition/model/FileListRequest.java
  9. 4
      src/main/java/com/github/zxbu/webdavteambition/model/NodeQuery.java
  10. 20
      src/main/java/com/github/zxbu/webdavteambition/model/Page.java
  11. 15
      src/main/java/com/github/zxbu/webdavteambition/model/result/ListResult.java
  12. 139
      src/main/java/com/github/zxbu/webdavteambition/model/result/TFile.java
  13. 15
      src/main/java/com/github/zxbu/webdavteambition/model/result/TFileListResult.java
  14. 101
      src/main/java/com/github/zxbu/webdavteambition/store/AliYunDriverClientService.java
  15. 46
      src/main/java/com/github/zxbu/webdavteambition/store/AliYunDriverFileSystemStore.java

5
src/main/java/com/github/zxbu/webdavteambition/WebdavTeambitionApplication.java

@ -1,7 +1,6 @@
package com.github.zxbu.webdavteambition; package com.github.zxbu.webdavteambition;
import com.github.zxbu.webdavteambition.store.TeambitionFileSystemStore; import com.github.zxbu.webdavteambition.store.AliYunDriverFileSystemStore;
import net.sf.webdav.LocalFileSystemStore;
import net.sf.webdav.WebdavServlet; import net.sf.webdav.WebdavServlet;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
@ -24,7 +23,7 @@ public class WebdavTeambitionApplication {
public ServletRegistrationBean<WebdavServlet> myServlet(){ public ServletRegistrationBean<WebdavServlet> myServlet(){
ServletRegistrationBean<WebdavServlet> servletRegistrationBean = new ServletRegistrationBean<>(new WebdavServlet(), "/*"); ServletRegistrationBean<WebdavServlet> servletRegistrationBean = new ServletRegistrationBean<>(new WebdavServlet(), "/*");
Map<String, String> inits = new LinkedHashMap<>(); Map<String, String> inits = new LinkedHashMap<>();
inits.put("ResourceHandlerImplementation", TeambitionFileSystemStore.class.getName()); inits.put("ResourceHandlerImplementation", AliYunDriverFileSystemStore.class.getName());
// inits.put("ResourceHandlerImplementation", LocalFileSystemStore.class.getName()); // inits.put("ResourceHandlerImplementation", LocalFileSystemStore.class.getName());
inits.put("rootpath", "./"); inits.put("rootpath", "./");
inits.put("storeDebug", "1"); inits.put("storeDebug", "1");

77
src/main/java/com/github/zxbu/webdavteambition/client/TeambitionClient.java → src/main/java/com/github/zxbu/webdavteambition/client/AliYunDriverClient.java

@ -1,12 +1,11 @@
package com.github.zxbu.webdavteambition.client; package com.github.zxbu.webdavteambition.client;
import com.github.zxbu.webdavteambition.config.TeambitionProperties; import com.github.zxbu.webdavteambition.config.AliYunDriveProperties;
import com.github.zxbu.webdavteambition.util.JsonUtil; import com.github.zxbu.webdavteambition.util.JsonUtil;
import net.sf.webdav.exceptions.WebdavException; import net.sf.webdav.exceptions.WebdavException;
import okhttp3.*; import okhttp3.*;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import java.io.IOException; import java.io.IOException;
@ -14,80 +13,39 @@ import java.io.InputStream;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TeambitionClient { public class AliYunDriverClient {
private static final Logger LOGGER = LoggerFactory.getLogger(TeambitionClient.class); private static final Logger LOGGER = LoggerFactory.getLogger(AliYunDriverClient.class);
private OkHttpClient okHttpClient; private OkHttpClient okHttpClient;
private TeambitionProperties teambitionProperties; private AliYunDriveProperties aliYunDriveProperties;
public TeambitionClient(OkHttpClient okHttpClient, TeambitionProperties teambitionProperties) { public AliYunDriverClient(OkHttpClient okHttpClient, AliYunDriveProperties aliYunDriveProperties) {
this.okHttpClient = okHttpClient; this.okHttpClient = okHttpClient;
this.teambitionProperties = teambitionProperties; this.aliYunDriveProperties = aliYunDriveProperties;
} }
private void login() { private void login() {
if (StringUtils.hasLength(teambitionProperties.getCookies())) { if (StringUtils.hasLength(aliYunDriveProperties.getAuthorization())) {
return; return;
} }
Assert.hasLength(teambitionProperties.getUserName(), "没有输入用户名");
Assert.hasLength(teambitionProperties.getPassword(), "没有输入密码"); // todo 暂不支持登录功能
String loginHtml = get("https://account.teambition.com/login/password", Collections.emptyMap());
Pattern pattern = Pattern.compile("\"TOKEN\":\"(\\S+?)\"");
Matcher matcher = pattern.matcher(loginHtml);
Assert.isTrue(matcher.find(), "未找到Token");
String token = matcher.group(1);
Map<String, Object> login = new LinkedHashMap<>();
login.put("client_id", "90727510-5e9f-11e6-bf41-15ed35b6cc41");
login.put("password", teambitionProperties.getPassword());
login.put("phone", teambitionProperties.getUserName());
login.put("token", token);
login.put("response_type", "session");
String loginResult = post("https://account.teambition.com/api/login/phone", login);
String name = (String) JsonUtil.getJsonNodeValue(loginResult, "user.name");
LOGGER.info("{} 登录成功", name);
} }
public void init() { public void init() {
login(); login();
if (getOrgId() == null || getRootId() == null || getDriveId() == null || getSpaceId() == null) { if (getDriveId() == null) {
String personalJson = get("https://www.teambition.com/api/organizations/personal", Collections.emptyMap()); String personalJson = post("/user/get", Collections.emptyMap());
String orgId = (String) JsonUtil.getJsonNodeValue(personalJson, "_id"); String driveId = (String) JsonUtil.getJsonNodeValue(personalJson, "default_drive_id");
teambitionProperties.setOrgId(orgId); aliYunDriveProperties.setDriveId(driveId);
String memberId = (String) JsonUtil.getJsonNodeValue(personalJson, "_creatorId");
String orgJson = get("/pan/api/orgs/" + orgId, Collections.singletonMap("orgId", orgId));
String driveId = (String) JsonUtil.getJsonNodeValue(orgJson, "data.driveId");
teambitionProperties.setDriveId(driveId);
Map<String, String> params = new LinkedHashMap<>();
params.put("orgId", orgId);
params.put("memberId", memberId);
String spacesJson = get("/pan/api/spaces", params);
String rootId = (String) JsonUtil.getJsonNodeValue(spacesJson, "[0].rootId");
String spaceId = (String) JsonUtil.getJsonNodeValue(spacesJson, "[0].spaceId");
teambitionProperties.setRootId(rootId);
teambitionProperties.setSpaceId(spaceId);
} }
} }
public String getOrgId() {
return teambitionProperties.getOrgId();
}
public String getDriveId() { public String getDriveId() {
return teambitionProperties.getDriveId(); return aliYunDriveProperties.getDriveId();
} }
public String getSpaceId() {
return teambitionProperties.getSpaceId();
}
public String getRootId() {
return teambitionProperties.getRootId();
}
public InputStream download(String url) { public InputStream download(String url) {
Request request = new Request.Builder().url(url).build(); Request request = new Request.Builder().url(url).build();
@ -116,11 +74,12 @@ public class TeambitionClient {
} }
public String post(String url, Object body) { public String post(String url, Object body) {
String bodyAsJson = JsonUtil.toJson(body);
Request request = new Request.Builder() Request request = new Request.Builder()
.post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JsonUtil.toJson(body))) .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyAsJson))
.url(getTotalUrl(url)).build(); .url(getTotalUrl(url)).build();
try (Response response = okHttpClient.newCall(request).execute()){ try (Response response = okHttpClient.newCall(request).execute()){
LOGGER.info("post {}, code {}", url, response.code()); LOGGER.info("post {}, body {}, code {}", url, bodyAsJson, response.code());
if (!response.isSuccessful()) { if (!response.isSuccessful()) {
LOGGER.error("请求失败,url={}, code={}, body={}", url, response.code(), response.body().string()); LOGGER.error("请求失败,url={}, code={}, body={}", url, response.code(), response.body().string());
throw new WebdavException("请求失败:" + url); throw new WebdavException("请求失败:" + url);
@ -178,6 +137,6 @@ public class TeambitionClient {
if (url.startsWith("http")) { if (url.startsWith("http")) {
return url; return url;
} }
return teambitionProperties.getUrl() + url; return aliYunDriveProperties.getUrl() + url;
} }
} }

43
src/main/java/com/github/zxbu/webdavteambition/config/AliYunDriveProperties.java

@ -0,0 +1,43 @@
package com.github.zxbu.webdavteambition.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "aliyundrive", ignoreUnknownFields = true)
public class AliYunDriveProperties {
private String url = "https://api.aliyundrive.com/v2";
private String authorization;
private String agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_0_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36";
private String driveId;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getAuthorization() {
return authorization;
}
public void setAuthorization(String authorization) {
this.authorization = authorization;
}
public String getAgent() {
return agent;
}
public void setAgent(String agent) {
this.agent = agent;
}
public String getDriveId() {
return driveId;
}
public void setDriveId(String driveId) {
this.driveId = driveId;
}
}

41
src/main/java/com/github/zxbu/webdavteambition/config/TeambitionAutoConfig.java

@ -1,6 +1,6 @@
package com.github.zxbu.webdavteambition.config; package com.github.zxbu.webdavteambition.config;
import com.github.zxbu.webdavteambition.client.TeambitionClient; import com.github.zxbu.webdavteambition.client.AliYunDriverClient;
import okhttp3.*; import okhttp3.*;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -18,15 +18,15 @@ import java.util.Collections;
import java.util.List; import java.util.List;
@Configuration @Configuration
@EnableConfigurationProperties(TeambitionProperties.class) @EnableConfigurationProperties(AliYunDriveProperties.class)
public class TeambitionAutoConfig { public class TeambitionAutoConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(TeambitionAutoConfig.class); private static final Logger LOGGER = LoggerFactory.getLogger(TeambitionAutoConfig.class);
@Autowired @Autowired
private TeambitionProperties teambitionProperties; private AliYunDriveProperties aliYunDriveProperties;
@Bean @Bean
public TeambitionClient teambitionClient(ApplicationContext applicationContext) throws Exception { public AliYunDriverClient teambitionClient(ApplicationContext applicationContext) throws Exception {
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() { OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
@Override @Override
@ -34,38 +34,15 @@ public class TeambitionAutoConfig {
Request request = chain.request(); Request request = chain.request();
request = request.newBuilder() request = request.newBuilder()
.removeHeader("User-Agent") .removeHeader("User-Agent")
.addHeader("User-Agent", teambitionProperties.getAgent()) .addHeader("User-Agent", aliYunDriveProperties.getAgent())
.addHeader("authorization", aliYunDriveProperties.getAuthorization())
.build(); .build();
return chain.proceed(request); return chain.proceed(request);
} }
}).cookieJar(new CookieJar() {
private List<Cookie> cookies = Collections.emptyList();
@Override
public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
if (!StringUtils.hasLength(teambitionProperties.getCookies())) {
this.cookies = cookies;
}
}
@Override
public List<Cookie> loadForRequest(HttpUrl url) {
String cookiesStr = teambitionProperties.getCookies();
if (CollectionUtils.isEmpty(this.cookies) && StringUtils.hasLength(cookiesStr)) {
String[] cookieSplit = cookiesStr.split("; ");
List<Cookie> cookieList = new ArrayList<>(cookieSplit.length);
for (String cookie : cookieSplit) {
Cookie parse = Cookie.parse(url, cookie);
cookieList.add(parse);
}
this.cookies = cookieList;
}
return this.cookies;
}
}).build(); }).build();
TeambitionClient teambitionClient = new TeambitionClient(okHttpClient, teambitionProperties); AliYunDriverClient aliYunDriverClient = new AliYunDriverClient(okHttpClient, aliYunDriveProperties);
teambitionClient.init(); aliYunDriverClient.init();
return teambitionClient; return aliYunDriverClient;
} }

88
src/main/java/com/github/zxbu/webdavteambition/config/TeambitionProperties.java

@ -1,88 +0,0 @@
package com.github.zxbu.webdavteambition.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "teambition", ignoreUnknownFields = true)
public class TeambitionProperties {
private String url = "https://pan.teambition.com";
private String cookies;
private String agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_0_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36";
private String orgId;
private String driveId;
private String spaceId;
private String rootId;
private String userName;
private String password;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCookies() {
return cookies;
}
public void setCookies(String cookies) {
this.cookies = cookies;
}
public String getOrgId() {
return orgId;
}
public void setOrgId(String orgId) {
this.orgId = orgId;
}
public String getDriveId() {
return driveId;
}
public void setDriveId(String driveId) {
this.driveId = driveId;
}
public String getSpaceId() {
return spaceId;
}
public String getAgent() {
return agent;
}
public void setAgent(String agent) {
this.agent = agent;
}
public void setSpaceId(String spaceId) {
this.spaceId = spaceId;
}
public String getRootId() {
return rootId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setRootId(String rootId) {
this.rootId = rootId;
}
}

40
src/main/java/com/github/zxbu/webdavteambition/model/BaseQuery.java

@ -1,40 +0,0 @@
package com.github.zxbu.webdavteambition.model;
public class BaseQuery extends Page{
private String orgId;
private String driveId;
private String spaceId;
private String parentId;
public String getOrgId() {
return orgId;
}
public void setOrgId(String orgId) {
this.orgId = orgId;
}
public String getDriveId() {
return driveId;
}
public void setDriveId(String driveId) {
this.driveId = driveId;
}
public String getSpaceId() {
return spaceId;
}
public void setSpaceId(String spaceId) {
this.spaceId = spaceId;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
}

22
src/main/java/com/github/zxbu/webdavteambition/model/FileGetRequest.java

@ -0,0 +1,22 @@
package com.github.zxbu.webdavteambition.model;
public class FileGetRequest {
private String drive_id;
private String file_id;
public String getDrive_id() {
return drive_id;
}
public void setDrive_id(String drive_id) {
this.drive_id = drive_id;
}
public String getFile_id() {
return file_id;
}
public void setFile_id(String file_id) {
this.file_id = file_id;
}
}

67
src/main/java/com/github/zxbu/webdavteambition/model/FileListRequest.java

@ -0,0 +1,67 @@
package com.github.zxbu.webdavteambition.model;
public class FileListRequest extends Page{
private String drive_id;
private Boolean all = false;
private String fields = "*";
private String image_thumbnail_process = "image/resize,w_400/format,jpeg";
private String image_url_process = "image/resize,w_1920/format,jpeg";
private String parent_file_id;
private String video_thumbnail_process = "video/snapshot,t_0,f_jpg,ar_auto,w_300";
public String getDrive_id() {
return drive_id;
}
public void setDrive_id(String drive_id) {
this.drive_id = drive_id;
}
public Boolean getAll() {
return all;
}
public void setAll(Boolean all) {
this.all = all;
}
public String getFields() {
return fields;
}
public void setFields(String fields) {
this.fields = fields;
}
public String getImage_thumbnail_process() {
return image_thumbnail_process;
}
public void setImage_thumbnail_process(String image_thumbnail_process) {
this.image_thumbnail_process = image_thumbnail_process;
}
public String getImage_url_process() {
return image_url_process;
}
public void setImage_url_process(String image_url_process) {
this.image_url_process = image_url_process;
}
public String getParent_file_id() {
return parent_file_id;
}
public void setParent_file_id(String parent_file_id) {
this.parent_file_id = parent_file_id;
}
public String getVideo_thumbnail_process() {
return video_thumbnail_process;
}
public void setVideo_thumbnail_process(String video_thumbnail_process) {
this.video_thumbnail_process = video_thumbnail_process;
}
}

4
src/main/java/com/github/zxbu/webdavteambition/model/NodeQuery.java

@ -1,4 +0,0 @@
package com.github.zxbu.webdavteambition.model;
public class NodeQuery extends BaseQuery {
}

20
src/main/java/com/github/zxbu/webdavteambition/model/Page.java

@ -3,8 +3,8 @@ package com.github.zxbu.webdavteambition.model;
public class Page { public class Page {
private int offset; private int offset;
private int limit; private int limit;
private String orderBy; private String order_by;
private String orderDirection; private String order_direction;
public int getOffset() { public int getOffset() {
return offset; return offset;
@ -22,19 +22,19 @@ public class Page {
this.limit = limit; this.limit = limit;
} }
public String getOrderBy() { public String getOrder_by() {
return orderBy; return order_by;
} }
public void setOrderBy(String orderBy) { public void setOrder_by(String order_by) {
this.orderBy = orderBy; this.order_by = order_by;
} }
public String getOrderDirection() { public String getOrder_direction() {
return orderDirection; return order_direction;
} }
public void setOrderDirection(String orderDirection) { public void setOrder_direction(String order_direction) {
this.orderDirection = orderDirection; this.order_direction = order_direction;
} }
} }

15
src/main/java/com/github/zxbu/webdavteambition/model/result/ListResult.java

@ -1,15 +0,0 @@
package com.github.zxbu.webdavteambition.model.result;
import java.util.List;
public class ListResult<T> {
private List<T> data;
public List<T> getData() {
return data;
}
public void setData(List<T> data) {
this.data = data;
}
}

139
src/main/java/com/github/zxbu/webdavteambition/model/result/TFile.java

@ -4,64 +4,92 @@ import java.util.Date;
import java.util.Objects; import java.util.Objects;
public class TFile { public class TFile {
private String kind; private Date created_at;
private String nodeId; private String domain_id;
private String drive_id;
private String encrypt_mode;
private String file_id;
private Boolean hidden;
private String name; private String name;
private Date created; private String parent_file_id;
private Date updated; private String starred;
private String parentId;
private String status; private String status;
private String downloadUrl; private String type;
private Date updated_at;
private String url;
private Long size; private Long size;
private String ccpFileId; private String download_url;
private String ccpParentFileId;
public String getKind() { public Date getCreated_at() {
return kind; return created_at;
} }
public void setKind(String kind) { public void setCreated_at(Date created_at) {
this.kind = kind; this.created_at = created_at;
} }
public String getNodeId() { public String getDomain_id() {
return nodeId; return domain_id;
} }
public void setNodeId(String nodeId) { public void setDomain_id(String domain_id) {
this.nodeId = nodeId; this.domain_id = domain_id;
} }
public String getName() { public String getDrive_id() {
return name; return drive_id;
} }
public void setName(String name) { public void setDrive_id(String drive_id) {
this.name = name; this.drive_id = drive_id;
}
public String getEncrypt_mode() {
return encrypt_mode;
}
public void setEncrypt_mode(String encrypt_mode) {
this.encrypt_mode = encrypt_mode;
}
public String getFile_id() {
return file_id;
}
public void setFile_id(String file_id) {
this.file_id = file_id;
}
public Boolean getHidden() {
return hidden;
} }
public Date getCreated() { public void setHidden(Boolean hidden) {
return created; this.hidden = hidden;
} }
public void setCreated(Date created) { public String getName() {
this.created = created; return name;
} }
public Date getUpdated() { public void setName(String name) {
return updated; this.name = name;
} }
public void setUpdated(Date updated) { public String getParent_file_id() {
this.updated = updated; return parent_file_id;
} }
public String getParentId() { public void setParent_file_id(String parent_file_id) {
return parentId; this.parent_file_id = parent_file_id;
} }
public void setParentId(String parentId) { public String getStarred() {
this.parentId = parentId; return starred;
}
public void setStarred(String starred) {
this.starred = starred;
} }
public String getStatus() { public String getStatus() {
@ -72,50 +100,43 @@ public class TFile {
this.status = status; this.status = status;
} }
public Long getSize() { public String getType() {
return size; return type;
}
public String getDownloadUrl() {
return downloadUrl;
} }
public void setDownloadUrl(String downloadUrl) { public void setType(String type) {
this.downloadUrl = downloadUrl; this.type = type;
} }
public String getCcpFileId() { public Date getUpdated_at() {
return ccpFileId; return updated_at;
} }
public void setCcpFileId(String ccpFileId) { public String getUrl() {
this.ccpFileId = ccpFileId; return url;
} }
public String getCcpParentFileId() { public void setUrl(String url) {
return ccpParentFileId; this.url = url;
} }
public void setCcpParentFileId(String ccpParentFileId) { public Long getSize() {
this.ccpParentFileId = ccpParentFileId; return size;
} }
public void setSize(Long size) { public void setSize(Long size) {
this.size = size; this.size = size;
} }
@Override public String getDownload_url() {
public boolean equals(Object o) { return download_url;
if (this == o) return true; }
if (o == null || getClass() != o.getClass()) return false;
TFile tFile = (TFile) o; public void setDownload_url(String download_url) {
return Objects.equals(kind, tFile.kind) && this.download_url = download_url;
Objects.equals(name, tFile.name) &&
Objects.equals(parentId, tFile.parentId);
} }
@Override public void setUpdated_at(Date updated_at) {
public int hashCode() { this.updated_at = updated_at;
return Objects.hash(kind, name, parentId);
} }
} }

15
src/main/java/com/github/zxbu/webdavteambition/model/result/TFileListResult.java

@ -0,0 +1,15 @@
package com.github.zxbu.webdavteambition.model.result;
import java.util.List;
public class TFileListResult<T> {
private List<T> items;
public List<T> getItems() {
return items;
}
public void setItems(List<T> items) {
this.items = items;
}
}

101
src/main/java/com/github/zxbu/webdavteambition/store/TeambitionClientService.java → src/main/java/com/github/zxbu/webdavteambition/store/AliYunDriverClientService.java

@ -2,10 +2,10 @@ package com.github.zxbu.webdavteambition.store;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.zxbu.webdavteambition.client.TeambitionClient; import com.github.zxbu.webdavteambition.client.AliYunDriverClient;
import com.github.zxbu.webdavteambition.model.*; import com.github.zxbu.webdavteambition.model.*;
import com.github.zxbu.webdavteambition.model.result.CreateFileResult; import com.github.zxbu.webdavteambition.model.result.CreateFileResult;
import com.github.zxbu.webdavteambition.model.result.ListResult; import com.github.zxbu.webdavteambition.model.result.TFileListResult;
import com.github.zxbu.webdavteambition.model.result.TFile; import com.github.zxbu.webdavteambition.model.result.TFile;
import com.github.zxbu.webdavteambition.model.result.UploadPreResult; import com.github.zxbu.webdavteambition.model.result.UploadPreResult;
import com.github.zxbu.webdavteambition.util.JsonUtil; import com.github.zxbu.webdavteambition.util.JsonUtil;
@ -22,19 +22,19 @@ import java.util.*;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@Service @Service
public class TeambitionClientService { public class AliYunDriverClientService {
private static final Logger LOGGER = LoggerFactory.getLogger(TeambitionClientService.class); private static final Logger LOGGER = LoggerFactory.getLogger(AliYunDriverClientService.class);
private static ObjectMapper objectMapper = new ObjectMapper(); private static ObjectMapper objectMapper = new ObjectMapper();
private static String rootPath = "/"; private static String rootPath = "/";
private static int chunkSize = 10485760; // 10MB private static int chunkSize = 10485760; // 10MB
private TFile rootTFile = null; private TFile rootTFile = null;
private ThreadLocal<Map<String, Set<TFile>>> tFilesCache = new ThreadLocal<>(); private ThreadLocal<Map<String, Set<TFile>>> tFilesCache = new ThreadLocal<>();
private final TeambitionClient client; private final AliYunDriverClient client;
public TeambitionClientService(TeambitionClient teambitionClient) { public AliYunDriverClientService(AliYunDriverClient aliYunDriverClient) {
this.client = teambitionClient; this.client = aliYunDriverClient;
TeambitionFileSystemStore.setBean(this); AliYunDriverFileSystemStore.setBean(this);
} }
public Set<TFile> getTFiles(String nodeId) { public Set<TFile> getTFiles(String nodeId) {
@ -44,20 +44,18 @@ public class TeambitionClientService {
tFilesCache.set(map); tFilesCache.set(map);
} }
return map.computeIfAbsent(nodeId, key -> { return map.computeIfAbsent(nodeId, key -> {
NodeQuery nodeQuery = new NodeQuery(); FileListRequest listQuery = new FileListRequest();
nodeQuery.setOrgId(client.getOrgId()); listQuery.setOffset(0);
nodeQuery.setOffset(0); listQuery.setLimit(10000);
nodeQuery.setLimit(10000); listQuery.setOrder_by("updated_at");
nodeQuery.setOrderBy("updateTime"); listQuery.setOrder_direction("DESC");
nodeQuery.setOrderDirection("desc"); listQuery.setDrive_id(client.getDriveId());
nodeQuery.setDriveId(client.getDriveId()); listQuery.setParent_file_id(nodeId);
nodeQuery.setSpaceId(client.getSpaceId()); String json = client.post("/file/list", listQuery);
nodeQuery.setParentId(nodeId); TFileListResult<TFile> tFileListResult = JsonUtil.readValue(json, new TypeReference<TFileListResult<TFile>>() {
String json = client.get("/pan/api/nodes", toMap(nodeQuery));
ListResult<TFile> tFileListResult = JsonUtil.readValue(json, new TypeReference<ListResult<TFile>>() {
}); });
List<TFile> tFileList = tFileListResult.getData(); List<TFile> tFileList = tFileListResult.getItems();
tFileList.sort(Comparator.comparing(TFile::getUpdated).reversed()); tFileList.sort(Comparator.comparing(TFile::getUpdated_at).reversed());
Set<TFile> tFileSets = new LinkedHashSet<>(); Set<TFile> tFileSets = new LinkedHashSet<>();
for (TFile tFile : tFileList) { for (TFile tFile : tFileList) {
if (!tFileSets.add(tFile)) { if (!tFileSets.add(tFile)) {
@ -98,11 +96,11 @@ public class TeambitionClientService {
int chunkCount = (int) Math.ceil(((double) size) / chunkSize); // 进1法 int chunkCount = (int) Math.ceil(((double) size) / chunkSize); // 进1法
UploadPreRequest uploadPreRequest = new UploadPreRequest(); UploadPreRequest uploadPreRequest = new UploadPreRequest();
uploadPreRequest.setOrgId(client.getOrgId()); // uploadPreRequest.setOrgId(client.getOrgId());
uploadPreRequest.setParentId(parent.getNodeId()); // uploadPreRequest.setParentId(parent.getNodeId());
uploadPreRequest.setSpaceId(client.getSpaceId()); // uploadPreRequest.setSpaceId(client.getSpaceId());
UploadPreInfo uploadPreInfo = new UploadPreInfo(); UploadPreInfo uploadPreInfo = new UploadPreInfo();
uploadPreInfo.setCcpParentId(parent.getCcpFileId()); // uploadPreInfo.setCcpParentId(parent.getCcpFileId());
uploadPreInfo.setDriveId(client.getDriveId()); uploadPreInfo.setDriveId(client.getDriveId());
uploadPreInfo.setName(pathInfo.getName()); uploadPreInfo.setName(pathInfo.getName());
uploadPreInfo.setSize(size); uploadPreInfo.setSize(size);
@ -139,7 +137,7 @@ public class TeambitionClientService {
uploadFinalRequest.setCcpFileId(uploadPreResult.getCcpFileId()); uploadFinalRequest.setCcpFileId(uploadPreResult.getCcpFileId());
uploadFinalRequest.setDriveId(client.getDriveId()); uploadFinalRequest.setDriveId(client.getDriveId());
uploadFinalRequest.setNodeId(uploadPreResult.getNodeId()); uploadFinalRequest.setNodeId(uploadPreResult.getNodeId());
uploadFinalRequest.setOrgId(client.getOrgId()); // uploadFinalRequest.setOrgId(client.getOrgId());
uploadFinalRequest.setUploadId(uploadPreResult.getUploadId()); uploadFinalRequest.setUploadId(uploadPreResult.getUploadId());
client.post("/pan/api/nodes/complete", uploadFinalRequest); client.post("/pan/api/nodes/complete", uploadFinalRequest);
LOGGER.info("文件上传成功。文件名:{}", path); LOGGER.info("文件上传成功。文件名:{}", path);
@ -159,7 +157,7 @@ public class TeambitionClientService {
RenameRequest renameRequest = new RenameRequest(); RenameRequest renameRequest = new RenameRequest();
renameRequest.setCcpFileId(uploadPreResult.getCcpFileId()); renameRequest.setCcpFileId(uploadPreResult.getCcpFileId());
renameRequest.setDriveId(client.getDriveId()); renameRequest.setDriveId(client.getDriveId());
renameRequest.setOrgId(client.getOrgId()); // renameRequest.setOrgId(client.getOrgId());
renameRequest.setName(pathInfo.getName()); renameRequest.setName(pathInfo.getName());
client.put("/pan/api/nodes/" + uploadPreResult.getNodeId(), renameRequest); client.put("/pan/api/nodes/" + uploadPreResult.getNodeId(), renameRequest);
} }
@ -170,11 +168,11 @@ public class TeambitionClientService {
sourcePath = normalizingPath(sourcePath); sourcePath = normalizingPath(sourcePath);
TFile tFile = getTFileByPath(sourcePath); TFile tFile = getTFileByPath(sourcePath);
RenameRequest renameRequest = new RenameRequest(); RenameRequest renameRequest = new RenameRequest();
renameRequest.setCcpFileId(tFile.getCcpFileId()); // renameRequest.setCcpFileId(tFile.getCcpFileId());
renameRequest.setDriveId(client.getDriveId()); renameRequest.setDriveId(client.getDriveId());
renameRequest.setOrgId(client.getOrgId()); // renameRequest.setOrgId(client.getOrgId());
renameRequest.setName(newName); renameRequest.setName(newName);
client.put("/pan/api/nodes/" + tFile.getNodeId(), renameRequest); // client.put("/pan/api/nodes/" + tFile.getNodeId(), renameRequest);
clearCache(); clearCache();
} }
@ -185,12 +183,12 @@ public class TeambitionClientService {
TFile sourceTFile = getTFileByPath(sourcePath); TFile sourceTFile = getTFileByPath(sourcePath);
TFile targetTFile = getTFileByPath(targetPath); TFile targetTFile = getTFileByPath(targetPath);
MoveRequest moveRequest = new MoveRequest(); MoveRequest moveRequest = new MoveRequest();
moveRequest.setOrgId(client.getOrgId()); // moveRequest.setOrgId(client.getOrgId());
moveRequest.setDriveId(client.getDriveId()); moveRequest.setDriveId(client.getDriveId());
moveRequest.setParentId(targetTFile.getNodeId()); // moveRequest.setParentId(targetTFile.getNodeId());
MoveRequestId moveRequestId = new MoveRequestId(); MoveRequestId moveRequestId = new MoveRequestId();
moveRequestId.setCcpFileId(sourceTFile.getCcpFileId()); // moveRequestId.setCcpFileId(sourceTFile.getCcpFileId());
moveRequestId.setId(sourceTFile.getNodeId()); // moveRequestId.setId(sourceTFile.getNodeId());
moveRequest.setIds(Collections.singletonList(moveRequestId)); moveRequest.setIds(Collections.singletonList(moveRequestId));
client.post("/pan/api/nodes/move", moveRequest); client.post("/pan/api/nodes/move", moveRequest);
clearCache(); clearCache();
@ -204,8 +202,8 @@ public class TeambitionClientService {
return; return;
} }
RemoveRequest removeRequest = new RemoveRequest(); RemoveRequest removeRequest = new RemoveRequest();
removeRequest.setOrgId(client.getOrgId()); // removeRequest.setOrgId(client.getOrgId());
removeRequest.setNodeIds(Collections.singletonList(tFile.getNodeId())); // removeRequest.setNodeIds(Collections.singletonList(tFile.getNodeId()));
client.post("/pan/api/nodes/archive", removeRequest); client.post("/pan/api/nodes/archive", removeRequest);
clearCache(); clearCache();
} }
@ -221,12 +219,12 @@ public class TeambitionClientService {
} }
CreateFileRequest createFileRequest = new CreateFileRequest(); CreateFileRequest createFileRequest = new CreateFileRequest();
createFileRequest.setCcpParentId(parent.getCcpFileId()); // createFileRequest.setCcpParentId(parent.getCcpFileId());
createFileRequest.setDriveId(client.getDriveId()); createFileRequest.setDriveId(client.getDriveId());
createFileRequest.setName(pathInfo.getName()); createFileRequest.setName(pathInfo.getName());
createFileRequest.setOrgId(client.getOrgId()); // createFileRequest.setOrgId(client.getOrgId());
createFileRequest.setParentId(parent.getNodeId()); // createFileRequest.setParentId(parent.getNodeId());
createFileRequest.setSpaceId(client.getSpaceId()); // createFileRequest.setSpaceId(client.getSpaceId());
createFileRequest.setType(FileType.folder.name()); createFileRequest.setType(FileType.folder.name());
String json = client.post("/pan/api/nodes/folder", createFileRequest); String json = client.post("/pan/api/nodes/folder", createFileRequest);
List<CreateFileResult> createFileResults = JsonUtil.readValue(json, new TypeReference<List<CreateFileResult>>() { List<CreateFileResult> createFileResults = JsonUtil.readValue(json, new TypeReference<List<CreateFileResult>>() {
@ -251,8 +249,8 @@ public class TeambitionClientService {
} }
public InputStream download(String path) { public InputStream download(String path) {
String downloadUrl = getTFileByPath(path).getDownloadUrl(); // String downloadUrl = getTFileByPath(path).getDownloadUrl();
return client.download(downloadUrl); return client.download("downloadUrl");
} }
private TFile getNodeIdByPath2(String path) { private TFile getNodeIdByPath2(String path) {
@ -267,7 +265,7 @@ public class TeambitionClientService {
if (tFile == null ) { if (tFile == null ) {
return null; return null;
} }
return getNodeIdByParentId(tFile.getNodeId(), pathInfo.getName()); return getNodeIdByParentId(tFile.getFile_id(), pathInfo.getName());
} }
@ -291,12 +289,17 @@ public class TeambitionClientService {
private TFile getRootTFile() { private TFile getRootTFile() {
if (rootTFile == null) { if (rootTFile == null) {
NodeQuery nodeQuery = new NodeQuery(); // FileGetRequest fileGetRequest = new FileGetRequest();
nodeQuery.setOrgId(client.getOrgId()); // fileGetRequest.setFile_id("root");
nodeQuery.setDriveId(client.getDriveId()); // fileGetRequest.setDrive_id(client.getDriveId());
nodeQuery.setSpaceId(client.getSpaceId()); // String json = client.post("/file/get", fileGetRequest);
String json = client.get("/pan/api/nodes/" + client.getRootId(), toMap(nodeQuery)); // rootTFile = JsonUtil.readValue(json, TFile.class);
rootTFile = JsonUtil.readValue(json, TFile.class); rootTFile = new TFile();
rootTFile.setName("/");
rootTFile.setFile_id("root");
rootTFile.setCreated_at(new Date());
rootTFile.setUpdated_at(new Date());
rootTFile.setType("folder");
} }
return rootTFile; return rootTFile;
} }

46
src/main/java/com/github/zxbu/webdavteambition/store/TeambitionFileSystemStore.java → src/main/java/com/github/zxbu/webdavteambition/store/AliYunDriverFileSystemStore.java

@ -17,16 +17,16 @@ import java.io.InputStream;
import java.security.Principal; import java.security.Principal;
import java.util.Set; import java.util.Set;
public class TeambitionFileSystemStore implements IWebdavStore { public class AliYunDriverFileSystemStore implements IWebdavStore {
private static final Logger LOGGER = LoggerFactory.getLogger(TeambitionFileSystemStore.class); private static final Logger LOGGER = LoggerFactory.getLogger(AliYunDriverFileSystemStore.class);
private static TeambitionClientService teambitionClientService; private static AliYunDriverClientService aliYunDriverClientService;
public TeambitionFileSystemStore(File file) { public AliYunDriverFileSystemStore(File file) {
} }
public static void setBean(TeambitionClientService teambitionClientService) { public static void setBean(AliYunDriverClientService aliYunDriverClientService) {
TeambitionFileSystemStore.teambitionClientService = teambitionClientService; AliYunDriverFileSystemStore.aliYunDriverClientService = aliYunDriverClientService;
} }
@ -41,7 +41,7 @@ public class TeambitionFileSystemStore implements IWebdavStore {
@Override @Override
public ITransaction begin(Principal principal) { public ITransaction begin(Principal principal) {
LOGGER.debug("begin"); LOGGER.debug("begin");
teambitionClientService.clearCache(); aliYunDriverClientService.clearCache();
return null; return null;
} }
@ -53,7 +53,7 @@ public class TeambitionFileSystemStore implements IWebdavStore {
@Override @Override
public void commit(ITransaction transaction) { public void commit(ITransaction transaction) {
teambitionClientService.clearCache(); aliYunDriverClientService.clearCache();
LOGGER.debug("commit"); LOGGER.debug("commit");
} }
@ -67,7 +67,7 @@ public class TeambitionFileSystemStore implements IWebdavStore {
public void createFolder(ITransaction transaction, String folderUri) { public void createFolder(ITransaction transaction, String folderUri) {
LOGGER.info("createFolder {}", folderUri); LOGGER.info("createFolder {}", folderUri);
teambitionClientService.createFolder(folderUri); aliYunDriverClientService.createFolder(folderUri);
} }
@Override @Override
@ -79,7 +79,7 @@ public class TeambitionFileSystemStore implements IWebdavStore {
@Override @Override
public InputStream getResourceContent(ITransaction transaction, String resourceUri) { public InputStream getResourceContent(ITransaction transaction, String resourceUri) {
LOGGER.debug("getResourceContent: {}", resourceUri); LOGGER.debug("getResourceContent: {}", resourceUri);
return teambitionClientService.download(resourceUri); return aliYunDriverClientService.download(resourceUri);
} }
@Override @Override
@ -99,15 +99,15 @@ public class TeambitionFileSystemStore implements IWebdavStore {
return 0; return 0;
} }
} }
teambitionClientService.uploadPre(resourceUri, contentLength, content); aliYunDriverClientService.uploadPre(resourceUri, contentLength, content);
return contentLength; return contentLength;
} }
@Override @Override
public String[] getChildrenNames(ITransaction transaction, String folderUri) { public String[] getChildrenNames(ITransaction transaction, String folderUri) {
LOGGER.debug("getChildrenNames: {}", folderUri); LOGGER.debug("getChildrenNames: {}", folderUri);
TFile tFile = teambitionClientService.getTFileByPath(folderUri); TFile tFile = aliYunDriverClientService.getTFileByPath(folderUri);
Set<TFile> tFileList = teambitionClientService.getTFiles(tFile.getNodeId()); Set<TFile> tFileList = aliYunDriverClientService.getTFiles(tFile.getFile_id());
return tFileList.stream().map(TFile::getName).toArray(String[]::new); return tFileList.stream().map(TFile::getName).toArray(String[]::new);
} }
@ -116,7 +116,7 @@ public class TeambitionFileSystemStore implements IWebdavStore {
@Override @Override
public long getResourceLength(ITransaction transaction, String path) { public long getResourceLength(ITransaction transaction, String path) {
LOGGER.debug("getResourceLength: {}", path); LOGGER.debug("getResourceLength: {}", path);
TFile tFile = teambitionClientService.getTFileByPath(path); TFile tFile = aliYunDriverClientService.getTFileByPath(path);
if (tFile == null || tFile.getSize() == null) { if (tFile == null || tFile.getSize() == null) {
return 384; return 384;
} }
@ -127,24 +127,24 @@ public class TeambitionFileSystemStore implements IWebdavStore {
@Override @Override
public void removeObject(ITransaction transaction, String uri) { public void removeObject(ITransaction transaction, String uri) {
LOGGER.info("removeObject: {}", uri); LOGGER.info("removeObject: {}", uri);
teambitionClientService.remove(uri); aliYunDriverClientService.remove(uri);
} }
@Override @Override
public boolean moveObject(ITransaction transaction, String destinationPath, String sourcePath) { public boolean moveObject(ITransaction transaction, String destinationPath, String sourcePath) {
LOGGER.info("moveObject, destinationPath={}, sourcePath={}", destinationPath, sourcePath); LOGGER.info("moveObject, destinationPath={}, sourcePath={}", destinationPath, sourcePath);
PathInfo destinationPathInfo = teambitionClientService.getPathInfo(destinationPath); PathInfo destinationPathInfo = aliYunDriverClientService.getPathInfo(destinationPath);
PathInfo sourcePathInfo = teambitionClientService.getPathInfo(sourcePath); PathInfo sourcePathInfo = aliYunDriverClientService.getPathInfo(sourcePath);
// 名字相同,说明是移动目录 // 名字相同,说明是移动目录
if (sourcePathInfo.getName().equals(destinationPathInfo.getName())) { if (sourcePathInfo.getName().equals(destinationPathInfo.getName())) {
teambitionClientService.move(sourcePath, destinationPathInfo.getParentPath()); aliYunDriverClientService.move(sourcePath, destinationPathInfo.getParentPath());
} else { } else {
if (!destinationPathInfo.getParentPath().equals(sourcePathInfo.getParentPath())) { if (!destinationPathInfo.getParentPath().equals(sourcePathInfo.getParentPath())) {
throw new WebdavException("不支持目录和名字同时修改"); throw new WebdavException("不支持目录和名字同时修改");
} }
// 名字不同,说明是修改名字。不考虑目录和名字同时修改的情况 // 名字不同,说明是修改名字。不考虑目录和名字同时修改的情况
teambitionClientService.rename(sourcePath, destinationPathInfo.getName()); aliYunDriverClientService.rename(sourcePath, destinationPathInfo.getName());
} }
return true; return true;
} }
@ -152,13 +152,13 @@ public class TeambitionFileSystemStore implements IWebdavStore {
@Override @Override
public StoredObject getStoredObject(ITransaction transaction, String uri) { public StoredObject getStoredObject(ITransaction transaction, String uri) {
LOGGER.debug("getStoredObject: {}", uri); LOGGER.debug("getStoredObject: {}", uri);
TFile tFile = teambitionClientService.getTFileByPath(uri); TFile tFile = aliYunDriverClientService.getTFileByPath(uri);
if (tFile != null) { if (tFile != null) {
StoredObject so = new StoredObject(); StoredObject so = new StoredObject();
so.setFolder(tFile.getKind().equalsIgnoreCase("folder")); so.setFolder(tFile.getType().equalsIgnoreCase("folder"));
so.setResourceLength(getResourceLength(transaction, uri)); so.setResourceLength(getResourceLength(transaction, uri));
so.setCreationDate(tFile.getCreated()); so.setCreationDate(tFile.getCreated_at());
so.setLastModified(tFile.getUpdated()); so.setLastModified(tFile.getUpdated_at());
return so; return so;
} }
Loading…
Cancel
Save