commit
2c10ec4831
16
HELP.md
16
HELP.md
@ -97,3 +97,19 @@ enter/回车: 未选中书签情况下,用于发起网页搜索。选中书签
|
||||
### 个人中心
|
||||
|
||||
通过右上角悬浮菜单进入个人中心页面,可进行头像更换,密码修改等操作
|
||||
|
||||
### 浏览器插件
|
||||
|
||||
浏览器插件功能终于有 0.1 版本,支持鼠标右键菜单添加书签。
|
||||
|
||||
#### 安装插件
|
||||
|
||||
1. 首先下载插件压缩包,下载地址:[点击下载](https://fleyx.com/static/bookmarkBrowserPlugin.7z)
|
||||
|
||||
2. 安装插件(以 chrome 浏览器为例,其他支持插件的浏览器差不多)进入插件管理页面->开启开发者模式->加载已解压的拓展程序
|
||||
|
||||
![](https://qiniupic.fleyx.com/blog/202204151605709.png)
|
||||
|
||||
3. 之后页面点击右键->添加到书签,即可
|
||||
|
||||
![](https://qiniupic.fleyx.com/blog/202204151607593.png)
|
||||
|
@ -0,0 +1,16 @@
|
||||
package com.fanxb.bookmark.business.bookmark.constant;
|
||||
|
||||
import java.nio.file.Paths;
|
||||
|
||||
/**
|
||||
* TODO
|
||||
*
|
||||
* @author fanxb
|
||||
*/
|
||||
public class FileConstant {
|
||||
|
||||
/**
|
||||
* 网站icon存储路径
|
||||
*/
|
||||
public static final String FAVICON_PATH = Paths.get("files", "public", "favicon").toString();
|
||||
}
|
@ -0,0 +1,33 @@
|
||||
package com.fanxb.bookmark.business.bookmark.dao;
|
||||
|
||||
import org.apache.ibatis.annotations.Insert;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
/**
|
||||
* @author fanxb
|
||||
*/
|
||||
@Mapper
|
||||
public interface HostIconDao {
|
||||
|
||||
/**
|
||||
* 插入一条数据
|
||||
*
|
||||
* @param host host
|
||||
* @param iconPath path
|
||||
* @author fanxb
|
||||
*/
|
||||
@Insert("insert into host_icon(host,iconPath) value(#{host},#{iconPath})")
|
||||
void insert(@Param("host") String host, @Param("iconPath") String iconPath);
|
||||
|
||||
/**
|
||||
* 根据host获取iconPath
|
||||
*
|
||||
* @param host host
|
||||
* @return {@link String}
|
||||
* @author fanxb
|
||||
*/
|
||||
@Select("select iconPath from host_icon where host=#{host}")
|
||||
String selectByHost(String host);
|
||||
}
|
@ -1,21 +1,29 @@
|
||||
package com.fanxb.bookmark.business.bookmark.service.impl;
|
||||
|
||||
import cn.hutool.core.io.FileUtil;
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import cn.hutool.core.util.CharsetUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.fanxb.bookmark.business.api.UserApi;
|
||||
import com.fanxb.bookmark.business.bookmark.constant.FileConstant;
|
||||
import com.fanxb.bookmark.business.bookmark.dao.BookmarkDao;
|
||||
import com.fanxb.bookmark.business.bookmark.dao.HostIconDao;
|
||||
import com.fanxb.bookmark.business.bookmark.entity.BookmarkEs;
|
||||
import com.fanxb.bookmark.business.bookmark.entity.MoveNodeBody;
|
||||
import com.fanxb.bookmark.business.bookmark.entity.redis.BookmarkDeleteMessage;
|
||||
import com.fanxb.bookmark.business.bookmark.entity.redis.VisitNumPlus;
|
||||
import com.fanxb.bookmark.business.bookmark.service.BookmarkService;
|
||||
import com.fanxb.bookmark.business.bookmark.service.PinYinService;
|
||||
import com.fanxb.bookmark.common.constant.CommonConstant;
|
||||
import com.fanxb.bookmark.common.constant.EsConstant;
|
||||
import com.fanxb.bookmark.common.constant.RedisConstant;
|
||||
import com.fanxb.bookmark.common.entity.po.Bookmark;
|
||||
import com.fanxb.bookmark.common.exception.CustomException;
|
||||
import com.fanxb.bookmark.common.util.*;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
import org.elasticsearch.index.query.BoolQueryBuilder;
|
||||
import org.elasticsearch.index.query.QueryBuilders;
|
||||
import org.elasticsearch.search.builder.SearchSourceBuilder;
|
||||
@ -28,9 +36,15 @@ import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.InputStream;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@ -51,13 +65,15 @@ public class BookmarkServiceImpl implements BookmarkService {
|
||||
private final PinYinService pinYinService;
|
||||
private final UserApi userApi;
|
||||
private final EsUtil esUtil;
|
||||
private final HostIconDao hostIconDao;
|
||||
|
||||
@Autowired
|
||||
public BookmarkServiceImpl(BookmarkDao bookmarkDao, PinYinService pinYinService, UserApi userApi, EsUtil esUtil) {
|
||||
public BookmarkServiceImpl(BookmarkDao bookmarkDao, PinYinService pinYinService, UserApi userApi, EsUtil esUtil, HostIconDao hostIconDao) {
|
||||
this.bookmarkDao = bookmarkDao;
|
||||
this.pinYinService = pinYinService;
|
||||
this.userApi = userApi;
|
||||
this.esUtil = esUtil;
|
||||
this.hostIconDao = hostIconDao;
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -201,7 +217,7 @@ public class BookmarkServiceImpl implements BookmarkService {
|
||||
bookmark.setUserId(userId);
|
||||
bookmark.setCreateTime(System.currentTimeMillis());
|
||||
bookmark.setAddTime(bookmark.getCreateTime());
|
||||
bookmark.setIcon(getIconBase64(bookmark.getUrl()));
|
||||
bookmark.setIcon(getIconPath(bookmark.getUrl()));
|
||||
//文件夹和书签都建立搜索key
|
||||
pinYinService.changeBookmark(bookmark);
|
||||
bookmarkDao.insertOne(bookmark);
|
||||
@ -215,7 +231,7 @@ public class BookmarkServiceImpl implements BookmarkService {
|
||||
bookmark.setUserId(userId);
|
||||
if (bookmark.getType() == 0) {
|
||||
pinYinService.changeBookmark(bookmark);
|
||||
bookmark.setIcon(getIconBase64(bookmark.getUrl()));
|
||||
bookmark.setIcon(getIconPath(bookmark.getUrl()));
|
||||
}
|
||||
bookmarkDao.editBookmark(bookmark);
|
||||
userApi.versionPlus(userId);
|
||||
@ -274,7 +290,7 @@ public class BookmarkServiceImpl implements BookmarkService {
|
||||
while ((deal = bookmarkDao.selectUserNoIcon(userId, start, size)).size() > 0) {
|
||||
start += size;
|
||||
deal.forEach(item -> {
|
||||
String icon = getIconBase64(item.getUrl());
|
||||
String icon = getIconPath(item.getUrl());
|
||||
if (StrUtil.isNotEmpty(icon)) {
|
||||
bookmarkDao.updateIcon(item.getBookmarkId(), icon);
|
||||
}
|
||||
@ -305,21 +321,56 @@ public class BookmarkServiceImpl implements BookmarkService {
|
||||
return resPath;
|
||||
}
|
||||
|
||||
private String getIconBase64(String url) {
|
||||
/**
|
||||
* 获取icon
|
||||
*
|
||||
* @param url url
|
||||
* @return {@link String}
|
||||
* @author fanxb
|
||||
*/
|
||||
private String getIconPath(String url) {
|
||||
if (StrUtil.isEmpty(url)) {
|
||||
return "";
|
||||
}
|
||||
String host;
|
||||
try {
|
||||
URL urlObj = new URL(url);
|
||||
byte[] data = HttpUtil.download(urlIconAddress + "/icon?url=" + urlObj.getHost() + "&size=8..16..64", false);
|
||||
String base64 = new String(Base64.getEncoder().encode(data));
|
||||
if (StrUtil.isNotEmpty(base64)) {
|
||||
return "data:image/png;base64," + base64;
|
||||
} else {
|
||||
log.warn("url无法获取icon:{}", url);
|
||||
}
|
||||
} catch (MalformedURLException e) {
|
||||
host = urlObj.getHost();
|
||||
} catch (Exception e) {
|
||||
log.warn("url无法解析出domain:{}", url);
|
||||
return "";
|
||||
}
|
||||
String iconPath = hostIconDao.selectByHost(host);
|
||||
if (iconPath != null) {
|
||||
return iconPath;
|
||||
}
|
||||
iconPath = saveFile(host, urlIconAddress + "/icon?url=" + host + "&size=16..64..256");
|
||||
if (StrUtil.isNotEmpty(iconPath)) {
|
||||
hostIconDao.insert(host, iconPath);
|
||||
}
|
||||
return iconPath;
|
||||
}
|
||||
|
||||
private String saveFile(String host, String url) {
|
||||
try {
|
||||
try (Response res = HttpUtil.getClient(false).newCall(new Request.Builder().url(url)
|
||||
.header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36 Edg/100.0.1185.36")
|
||||
.get().build()).execute()) {
|
||||
assert res.body() != null;
|
||||
if (!HttpUtil.checkIsOk(res.code())) {
|
||||
throw new CustomException("请求错误:" + res.code());
|
||||
}
|
||||
byte[] data = res.body().byteStream().readAllBytes();
|
||||
if (data.length > 0) {
|
||||
String iconUrl = res.request().url().toString();
|
||||
String fileName = URLEncoder.encode(host, StandardCharsets.UTF_8) + iconUrl.substring(iconUrl.lastIndexOf("."));
|
||||
String filePath = Paths.get(FileConstant.FAVICON_PATH, host.substring(0, 2), fileName).toString();
|
||||
FileUtil.writeBytes(data, Paths.get(CommonConstant.fileSavePath, filePath).toString());
|
||||
return File.separator + filePath;
|
||||
} else {
|
||||
log.info("未获取到icon:{}", url);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("url获取icon故障:{}", url, e);
|
||||
}
|
||||
|
@ -1,5 +1,6 @@
|
||||
package com.fanxb.bookmark.business.user.constant;
|
||||
|
||||
import com.fanxb.bookmark.common.constant.CommonConstant;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.nio.file.Paths;
|
||||
@ -17,6 +18,6 @@ public class FileConstant {
|
||||
/**
|
||||
* 用户头像目录
|
||||
*/
|
||||
public static String iconPath = Paths.get("files", "public", "icon").toString();
|
||||
public static String iconPath = Paths.get(CommonConstant.fileSavePath, "files", "public", "icon").toString();
|
||||
|
||||
}
|
||||
|
@ -12,8 +12,6 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Proxy;
|
||||
import java.util.Map;
|
||||
@ -51,42 +49,33 @@ public class HttpUtil {
|
||||
/**
|
||||
* 无代理环境
|
||||
*/
|
||||
private static final OkHttpClient CLIENT = new OkHttpClient.Builder().connectTimeout(2, TimeUnit.SECONDS)
|
||||
private static final OkHttpClient CLIENT = new OkHttpClient.Builder().connectTimeout(1, TimeUnit.SECONDS)
|
||||
.readTimeout(60, TimeUnit.SECONDS)
|
||||
.build();
|
||||
|
||||
/**
|
||||
* 获取客户端
|
||||
*
|
||||
* @param proxy 是否代理
|
||||
* @return {@link OkHttpClient}
|
||||
* @author fanxb
|
||||
*/
|
||||
public static OkHttpClient getClient(boolean proxy) {
|
||||
return proxy ? PROXY_CLIENT : CLIENT;
|
||||
}
|
||||
|
||||
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
OkHttpClient.Builder builder = new OkHttpClient.Builder();
|
||||
OkHttpClient.Builder builder = new OkHttpClient.Builder().connectTimeout(1, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS);
|
||||
log.info("代理配置,ip:{},port:{}", proxyIp, proxyPort);
|
||||
if (StrUtil.isNotBlank(proxyIp) && StrUtil.isNotBlank(proxyPort)) {
|
||||
builder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, Integer.parseInt(proxyPort))));
|
||||
proxyExist = true;
|
||||
}
|
||||
PROXY_CLIENT = builder.connectTimeout(10, TimeUnit.SECONDS)
|
||||
.readTimeout(60, TimeUnit.SECONDS)
|
||||
.build();
|
||||
}
|
||||
|
||||
/***
|
||||
* 下载文件
|
||||
* @author fanxb
|
||||
* @param url 下载链接
|
||||
* @param proxy 是否使用代理
|
||||
* @return java.io.InputStream
|
||||
* @date 2021/3/12
|
||||
**/
|
||||
public static byte[] download(String url, boolean proxy) {
|
||||
try (Response res = (proxy ? PROXY_CLIENT : CLIENT).newCall(new Request.Builder().url(url).build()).execute()) {
|
||||
assert res.body() != null;
|
||||
if (checkIsOk(res.code())) {
|
||||
return res.body().byteStream().readAllBytes();
|
||||
} else {
|
||||
throw new CustomException("下载出现问题:" + res.body().string());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new CustomException(e);
|
||||
PROXY_CLIENT = builder.build();
|
||||
} else {
|
||||
PROXY_CLIENT = CLIENT;
|
||||
}
|
||||
}
|
||||
|
||||
@ -270,6 +259,8 @@ public class HttpUtil {
|
||||
}
|
||||
return ipAddress;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
@ -1,17 +0,0 @@
|
||||
<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<!-- This is an automatically generated file.
|
||||
It will be read and overwritten.
|
||||
DO NOT EDIT! -->
|
||||
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
|
||||
<TITLE>Bookmarks</TITLE>
|
||||
<H1>Bookmarks Menu</H1>
|
||||
|
||||
<DL><p>
|
||||
<DT><A HREF="http://0.0.0.1/" ADD_DATE="1614837460" LAST_MODIFIED="1614837465">1</A>
|
||||
<DT><A HREF="http://0.0.0.2/" ADD_DATE="1614837471" LAST_MODIFIED="1614837474">2</A>
|
||||
<DT><H3 ADD_DATE="1614837478" LAST_MODIFIED="1614837497">f1</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="http://asdf/" ADD_DATE="1614837485" LAST_MODIFIED="1614837493" TAGS="ww">f11</A>
|
||||
<DT><A HREF="http://f12/" ADD_DATE="1614837497" LAST_MODIFIED="1614837502">f12</A>
|
||||
</DL><p>
|
||||
</DL>
|
@ -1,17 +0,0 @@
|
||||
<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<!-- This is an automatically generated file.
|
||||
It will be read and overwritten.
|
||||
DO NOT EDIT! -->
|
||||
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
|
||||
<TITLE>Bookmarks</TITLE>
|
||||
<H1>Bookmarks Menu</H1>
|
||||
|
||||
<DL><p>
|
||||
<DT><A HREF="http://0.0.0.1/" ADD_DATE="1614837460" LAST_MODIFIED="1614837465">1</A>
|
||||
<DT><A HREF="http://0.0.0.2/" ADD_DATE="1614837471" LAST_MODIFIED="1614837474">2</A>
|
||||
<DT><H3 ADD_DATE="1614837478" LAST_MODIFIED="1614837497">f1</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="http://asdf/" ADD_DATE="1614837485" LAST_MODIFIED="1614837493" TAGS="ww">f11</A>
|
||||
<DT><A HREF="http://f12/" ADD_DATE="1614837497" LAST_MODIFIED="1614837502">f12</A>
|
||||
</DL><p>
|
||||
</DL>
|
@ -0,0 +1,10 @@
|
||||
CREATE TABLE bookmark.host_icon (
|
||||
id INT UNSIGNED auto_increment NOT NULL,
|
||||
host varchar(300) NOT NULL COMMENT 'host',
|
||||
iconPath varchar(330) NOT NULL,
|
||||
CONSTRAINT host_icon_pk PRIMARY KEY (id)
|
||||
)
|
||||
ENGINE=InnoDB
|
||||
DEFAULT CHARSET=utf8mb4
|
||||
COLLATE=utf8mb4_0900_ai_ci;
|
||||
CREATE INDEX host_icon_host_IDX USING BTREE ON bookmark.host_icon (host(20));
|
1
bookmark_front/.gitignore
vendored
1
bookmark_front/.gitignore
vendored
@ -3,6 +3,7 @@ node_modules
|
||||
/dist
|
||||
package-lock.json
|
||||
yarn.lock
|
||||
public/files
|
||||
|
||||
# local env files
|
||||
.env.local
|
||||
|
BIN
bookmark_front/public/static/bookmarkBrowserPlugin.7z
Normal file
BIN
bookmark_front/public/static/bookmarkBrowserPlugin.7z
Normal file
Binary file not shown.
@ -6,7 +6,7 @@
|
||||
|
||||
<script>
|
||||
export default {
|
||||
name: "App",
|
||||
name: "App"
|
||||
};
|
||||
</script>
|
||||
|
||||
|
@ -1,65 +1,69 @@
|
||||
import Vue from "vue";
|
||||
import VueRouter from "vue-router";
|
||||
import * as vuex from "../store/index.js";
|
||||
import { GLOBAL_CONFIG, SUPPORT_NO_LOGIN, TOKEN } from "@/store/modules/globalConfig";
|
||||
import { GLOBAL_CONFIG, SUPPORT_NO_LOGIN, TOKEN, setToken } from "@/store/modules/globalConfig";
|
||||
import { checkJwtValid } from "@/util/UserUtil";
|
||||
|
||||
Vue.use(VueRouter);
|
||||
|
||||
const routes = [
|
||||
{ path: "/", component: () => import("@/views/home/index") },
|
||||
{
|
||||
path: "/manage",
|
||||
component: () => import("@/views/manage/index"),
|
||||
children: [
|
||||
{ path: "", redirect: "/manage/bookmarkTree" },
|
||||
{ path: "bookmarkTree", component: () => import("@/views/manage/bookmarkTree/index") },
|
||||
{ path: "personSpace/userInfo", component: () => import("@/views/manage/personSpace/index") },
|
||||
]
|
||||
},
|
||||
{
|
||||
path: "/public",
|
||||
component: () => import("@/views/public/index"),
|
||||
children: [
|
||||
{ path: "login", component: () => import("@/views/public/login/index") },
|
||||
{ path: "register", component: () => import("@/views/public/register/index") },
|
||||
{ path: "resetPassword", component: () => import("@/views/public/passwordReset/index") },
|
||||
{ path: "oauth/github", component: () => import("@/views/public/oauth/github/index") },
|
||||
{ path: "about", component: () => import("@/views/public/about/index") },
|
||||
{ path: "404", component: () => import("@/views/public/notFound/index") },
|
||||
]
|
||||
},
|
||||
{ path: "*", redirect: "/public/404" }
|
||||
{ path: "/", component: () => import("@/views/home/index") },
|
||||
{ path: "/noHead/addBookmark", component: () => import("@/views/noHead/addBookmark/index") },
|
||||
{
|
||||
path: "/manage",
|
||||
component: () => import("@/views/manage/index"),
|
||||
children: [
|
||||
{ path: "", redirect: "/manage/bookmarkTree" },
|
||||
{ path: "bookmarkTree", component: () => import("@/views/manage/bookmarkTree/index") },
|
||||
{ path: "personSpace/userInfo", component: () => import("@/views/manage/personSpace/index") },
|
||||
{ path: "sso/auth", component: () => import("@/views/manage/sso/auth/index") }
|
||||
]
|
||||
},
|
||||
{
|
||||
path: "/public",
|
||||
component: () => import("@/views/public/index"),
|
||||
children: [
|
||||
{ path: "login", component: () => import("@/views/public/login/index") },
|
||||
{ path: "register", component: () => import("@/views/public/register/index") },
|
||||
{ path: "resetPassword", component: () => import("@/views/public/passwordReset/index") },
|
||||
{ path: "oauth/github", component: () => import("@/views/public/oauth/github/index") },
|
||||
{ path: "about", component: () => import("@/views/public/about/index") },
|
||||
{ path: "404", component: () => import("@/views/public/notFound/index") }
|
||||
]
|
||||
},
|
||||
{ path: "*", redirect: "/public/404" }
|
||||
];
|
||||
|
||||
const router = new VueRouter({
|
||||
mode: "history",
|
||||
routes
|
||||
mode: "history",
|
||||
routes
|
||||
});
|
||||
|
||||
/**
|
||||
* 在此进行登录信息判断,以及重定向到登录页面
|
||||
*/
|
||||
router.beforeEach(async (to, from, next) => {
|
||||
//进入主页面/管理页面时,确认已经进行初始化操作
|
||||
if (to.path === '/' || to.path.startsWith("/manage")) {
|
||||
await vuex.loginInit();
|
||||
}
|
||||
let supportNoLogin = to.path === '/' || to.path.startsWith("/public");
|
||||
vuex.default.commit(GLOBAL_CONFIG + "/" + SUPPORT_NO_LOGIN, supportNoLogin);
|
||||
if (!supportNoLogin && !checkJwtValid(vuex.default.state[GLOBAL_CONFIG][TOKEN])) {
|
||||
//如不支持未登录进入,切jwt已过期,直接跳转到登录页面,并清理缓存
|
||||
await vuex.default.dispatch("treeData/clear");
|
||||
await vuex.default.dispatch("globalConfig/clear");
|
||||
next({
|
||||
path: "/public/login?to=" + btoa(location.href),
|
||||
replace: true
|
||||
});
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
if (to.query.token && checkJwtValid(to.query.token)) {
|
||||
console.log("获取到页面token", to.query.token);
|
||||
await vuex.default.dispatch(GLOBAL_CONFIG + "/" + setToken, to.query.token);
|
||||
}
|
||||
//进入除/public以外的路由,确认已经进行初始化操作
|
||||
if (!to.path.startsWith("/public")) {
|
||||
await vuex.loginInit();
|
||||
}
|
||||
let supportNoLogin = to.path === "/" || to.path.startsWith("/public");
|
||||
vuex.default.commit(GLOBAL_CONFIG + "/" + SUPPORT_NO_LOGIN, supportNoLogin);
|
||||
if (!supportNoLogin && !checkJwtValid(vuex.default.state[GLOBAL_CONFIG][TOKEN])) {
|
||||
//如不支持未登录进入,切jwt已过期,直接跳转到登录页面,并清理缓存
|
||||
await vuex.default.dispatch("treeData/clear");
|
||||
await vuex.default.dispatch("globalConfig/clear");
|
||||
next({
|
||||
path: "/public/login?to=" + btoa(location.href),
|
||||
replace: true
|
||||
});
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
@ -11,95 +11,100 @@ export const IS_PHONE = "isPhone";
|
||||
|
||||
export const noLoginInit = "noLoginInit";
|
||||
export const loginInit = "loginInit";
|
||||
/**
|
||||
* 登出清除数据
|
||||
*/
|
||||
export const clear = "clear";
|
||||
/**
|
||||
* 设置token
|
||||
*/
|
||||
export const setToken = "setToken";
|
||||
/**
|
||||
* 存储全局配置
|
||||
*/
|
||||
const state = {
|
||||
/**
|
||||
* 用户信息
|
||||
*/
|
||||
[USER_INFO]: null,
|
||||
/**
|
||||
* token,null说明未获取登录凭证
|
||||
*/
|
||||
[TOKEN]: null,
|
||||
/**
|
||||
* 是否已经初始化完成,避免多次重复初始化
|
||||
*/
|
||||
[IS_INIT]: false,
|
||||
/**
|
||||
* 是否移动端
|
||||
*/
|
||||
[IS_PHONE]: /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent),
|
||||
/**
|
||||
* 是否支持未登录进入页面
|
||||
*/
|
||||
[SUPPORT_NO_LOGIN]: false,
|
||||
/**
|
||||
* 服务端全局配置
|
||||
*/
|
||||
[SERVER_CONFIG]: {}
|
||||
/**
|
||||
* 用户信息
|
||||
*/
|
||||
[USER_INFO]: null,
|
||||
/**
|
||||
* token,null说明未获取登录凭证
|
||||
*/
|
||||
[TOKEN]: null,
|
||||
/**
|
||||
* 是否已经初始化完成,避免多次重复初始化
|
||||
*/
|
||||
[IS_INIT]: false,
|
||||
/**
|
||||
* 是否移动端
|
||||
*/
|
||||
[IS_PHONE]: /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent),
|
||||
/**
|
||||
* 是否支持未登录进入页面
|
||||
*/
|
||||
[SUPPORT_NO_LOGIN]: false,
|
||||
/**
|
||||
* 服务端全局配置
|
||||
*/
|
||||
[SERVER_CONFIG]: {}
|
||||
};
|
||||
|
||||
const getters = {};
|
||||
|
||||
const actions = {
|
||||
//未登录需要进行的初始化
|
||||
async [noLoginInit] ({ commit }) {
|
||||
commit(SERVER_CONFIG, await HttpUtil.get("/common/config/global"));
|
||||
let token = await localforage.getItem(TOKEN);
|
||||
if (token) {
|
||||
commit(TOKEN, token);
|
||||
window.jwtToken = token;
|
||||
}
|
||||
},
|
||||
//登陆后的,初始化数据
|
||||
async [loginInit] (context) {
|
||||
if (context.state.isInit) {
|
||||
return;
|
||||
}
|
||||
let userInfo = await HttpUtil.get("/user/currentUserInfo");
|
||||
context.commit(USER_INFO, userInfo);
|
||||
context.commit(IS_INIT, true);
|
||||
},
|
||||
async setToken ({ commit }, token) {
|
||||
await localforage.setItem(TOKEN, token);
|
||||
window.jwtToken = token;
|
||||
commit(TOKEN, token);
|
||||
},
|
||||
//登出清除数据
|
||||
async [clear] (context) {
|
||||
await localforage.removeItem(TOKEN);
|
||||
context.commit(USER_INFO, null);
|
||||
context.commit(TOKEN, null);
|
||||
context.commit(IS_INIT, false);
|
||||
},
|
||||
//未登录需要进行的初始化
|
||||
async [noLoginInit]({ commit }) {
|
||||
commit(SERVER_CONFIG, await HttpUtil.get("/common/config/global"));
|
||||
let token = await localforage.getItem(TOKEN);
|
||||
if (token) {
|
||||
commit(TOKEN, token);
|
||||
window.jwtToken = token;
|
||||
}
|
||||
},
|
||||
//登陆后的,初始化数据
|
||||
async [loginInit](context) {
|
||||
if (context.state.isInit) {
|
||||
return;
|
||||
}
|
||||
let userInfo = await HttpUtil.get("/user/currentUserInfo");
|
||||
context.commit(USER_INFO, userInfo);
|
||||
context.commit(IS_INIT, true);
|
||||
},
|
||||
async [setToken]({ commit }, token) {
|
||||
await localforage.setItem(TOKEN, token);
|
||||
window.jwtToken = token;
|
||||
commit(TOKEN, token);
|
||||
},
|
||||
async [clear](context) {
|
||||
await localforage.removeItem(TOKEN);
|
||||
context.commit(USER_INFO, null);
|
||||
context.commit(TOKEN, null);
|
||||
context.commit(IS_INIT, false);
|
||||
}
|
||||
};
|
||||
|
||||
const mutations = {
|
||||
[USER_INFO] (state, userInfo) {
|
||||
state[USER_INFO] = userInfo;
|
||||
},
|
||||
[TOKEN] (state, token) {
|
||||
state[TOKEN] = token;
|
||||
},
|
||||
[IS_INIT] (state, isInit) {
|
||||
state[IS_INIT] = isInit;
|
||||
},
|
||||
[SERVER_CONFIG] (state, serverConfig) {
|
||||
state[SERVER_CONFIG] = serverConfig;
|
||||
},
|
||||
[SUPPORT_NO_LOGIN] (state, val) {
|
||||
state[SUPPORT_NO_LOGIN] = val;
|
||||
}
|
||||
[USER_INFO](state, userInfo) {
|
||||
state[USER_INFO] = userInfo;
|
||||
},
|
||||
[TOKEN](state, token) {
|
||||
state[TOKEN] = token;
|
||||
},
|
||||
[IS_INIT](state, isInit) {
|
||||
state[IS_INIT] = isInit;
|
||||
},
|
||||
[SERVER_CONFIG](state, serverConfig) {
|
||||
state[SERVER_CONFIG] = serverConfig;
|
||||
},
|
||||
[SUPPORT_NO_LOGIN](state, val) {
|
||||
state[SUPPORT_NO_LOGIN] = val;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
export const store = {
|
||||
namespaced: true,
|
||||
state,
|
||||
getters,
|
||||
actions,
|
||||
mutations
|
||||
namespaced: true,
|
||||
state,
|
||||
getters,
|
||||
actions,
|
||||
mutations
|
||||
};
|
||||
|
@ -30,6 +30,10 @@ export const clear = "clear";
|
||||
* 删除书签数据
|
||||
*/
|
||||
export const deleteData = "deleteData";
|
||||
/**
|
||||
* 新增节点
|
||||
*/
|
||||
export const addNode = "addNode";
|
||||
|
||||
/**
|
||||
* 版本检查定时调度
|
||||
@ -44,277 +48,273 @@ let toastShow = false;
|
||||
* 书签树相关配置
|
||||
*/
|
||||
const state = {
|
||||
//全部书签数据
|
||||
[TOTAL_TREE_DATA]: {},
|
||||
//版本
|
||||
[VERSION]: null,
|
||||
//是否已经初始化书签数据
|
||||
[IS_INIT]: false,
|
||||
// 是否正在加载数据
|
||||
[IS_INITING]: false,
|
||||
[SHOW_REFRESH_TOAST]: false,
|
||||
[HOME_PIN_LIST]: [],
|
||||
[HOME_PIN_BOOKMARK_ID_MAP]: {}
|
||||
//全部书签数据
|
||||
[TOTAL_TREE_DATA]: {},
|
||||
//版本
|
||||
[VERSION]: null,
|
||||
//是否已经初始化书签数据
|
||||
[IS_INIT]: false,
|
||||
// 是否正在加载数据
|
||||
[IS_INITING]: false,
|
||||
[SHOW_REFRESH_TOAST]: false,
|
||||
[HOME_PIN_LIST]: [],
|
||||
[HOME_PIN_BOOKMARK_ID_MAP]: {}
|
||||
};
|
||||
|
||||
const getters = {
|
||||
[getById]: state => id => {
|
||||
let arr = Object.values(state[TOTAL_TREE_DATA]);
|
||||
for (let i in arr) {
|
||||
for (let j in arr[i]) {
|
||||
if (arr[i][j].bookmarkId === id) {
|
||||
return arr[i][j];
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
[getById]: state => id => {
|
||||
let arr = Object.values(state[TOTAL_TREE_DATA]);
|
||||
for (let i in arr) {
|
||||
for (let j in arr[i]) {
|
||||
if (arr[i][j].bookmarkId === id) {
|
||||
return arr[i][j];
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const actions = {
|
||||
async [noLoginInit] () {
|
||||
|
||||
},
|
||||
async [loginInit] (context) {
|
||||
if (context.state.isInit || context.state.isIniting) {
|
||||
return;
|
||||
}
|
||||
await context.dispatch(refreshHomePinList);
|
||||
context.commit(IS_INITING, true);
|
||||
context.commit(TOTAL_TREE_DATA, await localforage.getItem(TOTAL_TREE_DATA));
|
||||
context.commit(VERSION, await localforage.getItem(VERSION));
|
||||
await treeDataCheck(context, true);
|
||||
context.commit(IS_INIT, true);
|
||||
context.commit(IS_INITING, false);
|
||||
timer = setInterval(() => treeDataCheck(context, false), CHECK_INTERVAL);
|
||||
},
|
||||
/**
|
||||
* 确保数据加载完毕
|
||||
*/
|
||||
ensureDataOk (context) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let timer = setInterval(() => {
|
||||
try {
|
||||
if (context.state[IS_INIT] && context.state[IS_INITING] == false) {
|
||||
clearInterval(timer);
|
||||
resolve();
|
||||
}
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
}, 50);
|
||||
});
|
||||
},
|
||||
//刷新缓存数据
|
||||
async [refresh] (context) {
|
||||
let treeData = await HttpUtil.get("/bookmark/currentUser");
|
||||
if (!treeData[""]) {
|
||||
treeData[""] = [];
|
||||
}
|
||||
Object.values(treeData).forEach(item =>
|
||||
item.forEach(item1 => {
|
||||
item1.isLeaf = item1.type === 0;
|
||||
item1.class = "treeNodeItem";
|
||||
item1.scopedSlots = { title: "nodeTitle" };
|
||||
})
|
||||
);
|
||||
let version = await HttpUtil.get("/user/version");
|
||||
await context.dispatch("updateVersion", version);
|
||||
await context.dispatch(refreshHomePinList);
|
||||
context.commit(TOTAL_TREE_DATA, treeData);
|
||||
await localforage.setItem(TOTAL_TREE_DATA, treeData);
|
||||
},
|
||||
//清除缓存数据
|
||||
async [clear] (context) {
|
||||
context.commit(TOTAL_TREE_DATA, null);
|
||||
context.commit(VERSION, null);
|
||||
context.commit(SHOW_REFRESH_TOAST, false);
|
||||
context.commit(IS_INIT, false);
|
||||
context.commit(IS_INITING, false);
|
||||
context.commit(HOME_PIN_LIST, []);
|
||||
if (timer != null) {
|
||||
clearInterval(timer);
|
||||
}
|
||||
await localforage.removeItem(TOTAL_TREE_DATA);
|
||||
await localforage.removeItem(VERSION);
|
||||
},
|
||||
/**
|
||||
* 移动节点
|
||||
*/
|
||||
async moveNode (context, info) {
|
||||
let data = context.state[TOTAL_TREE_DATA];
|
||||
const target = info.node.dataRef;
|
||||
const current = info.dragNode.dataRef;
|
||||
//从原来位置中删除当前节点
|
||||
let currentList = data[current.path];
|
||||
currentList.splice(
|
||||
currentList.findIndex(item => item.bookmarkId === current.bookmarkId),
|
||||
1
|
||||
);
|
||||
//请求体
|
||||
const body = {
|
||||
bookmarkId: current.bookmarkId,
|
||||
sourcePath: current.path,
|
||||
targetPath: "",
|
||||
//-1 表示排在最后
|
||||
sort: -1
|
||||
};
|
||||
if (info.dropToGap) {
|
||||
body.targetPath = target.path;
|
||||
//移动到目标节点的上面或者下面
|
||||
let targetList = data[target.path];
|
||||
//目标节点index
|
||||
let index = targetList.indexOf(target);
|
||||
//移动节点相对于目标节点位置的增量
|
||||
let addIndex = info.dropPosition > index ? 1 : 0;
|
||||
body.sort = target.sort + addIndex;
|
||||
targetList.splice(index + addIndex, 0, current);
|
||||
for (let i = index + 1; i < targetList.length; i++) {
|
||||
targetList[i].sort += 1;
|
||||
}
|
||||
} else {
|
||||
//移动到一个文件夹下面
|
||||
body.targetPath = target.path + "." + target.bookmarkId;
|
||||
let targetList = data[body.targetPath];
|
||||
if (!targetList) {
|
||||
targetList = [];
|
||||
data[body.targetPath] = targetList;
|
||||
}
|
||||
body.sort = targetList.length > 0 ? targetList[targetList.length - 1].sort + 1 : 1;
|
||||
targetList.push(current);
|
||||
}
|
||||
//更新节点的path和对应子节点path
|
||||
current.path = body.targetPath;
|
||||
current.sort = body.sort;
|
||||
//如果为文件夹还要更新所有子书签的path
|
||||
if (body.sourcePath !== body.targetPath) {
|
||||
let keys = Object.keys(data);
|
||||
//旧路径
|
||||
let oldPath = body.sourcePath + "." + current.bookmarkId;
|
||||
//新路径
|
||||
let newPath = body.targetPath + "." + current.bookmarkId;
|
||||
keys.forEach(item => {
|
||||
if (!item.startsWith(oldPath)) {
|
||||
return;
|
||||
}
|
||||
let newPathStr = item.replace(oldPath, newPath);
|
||||
let list = data[item];
|
||||
delete data[item];
|
||||
data[newPathStr] = list;
|
||||
list.forEach(item1 => (item1.path = newPathStr));
|
||||
});
|
||||
}
|
||||
context.commit(TOTAL_TREE_DATA, context.state[TOTAL_TREE_DATA]);
|
||||
await context.dispatch("updateVersion", null);
|
||||
await localforage.setItem(TOTAL_TREE_DATA, state[TOTAL_TREE_DATA]);
|
||||
return body;
|
||||
},
|
||||
async [refreshHomePinList] ({ commit }) {
|
||||
let list = await HttpUtil.get("/home/pin");
|
||||
commit(HOME_PIN_LIST, list);
|
||||
let map = {};
|
||||
list.filter(item => item.id).forEach(item => map[item.bookmarkId] = true);
|
||||
commit(HOME_PIN_BOOKMARK_ID_MAP, map);
|
||||
|
||||
},
|
||||
/**
|
||||
* 更新版本数据
|
||||
*/
|
||||
async updateVersion ({ commit, state }, version) {
|
||||
commit(VERSION, version == null ? state[VERSION] + 1 : version);
|
||||
await localforage.setItem(VERSION, state[VERSION]);
|
||||
},
|
||||
/**
|
||||
* 新增书签、文件夹
|
||||
*/
|
||||
async addNode (context, { sourceNode, targetNode }) {
|
||||
if (sourceNode === null) {
|
||||
if (context.state[TOTAL_TREE_DATA][""] === undefined) {
|
||||
context.state[TOTAL_TREE_DATA][""] = [];
|
||||
}
|
||||
context.state[TOTAL_TREE_DATA][""].push(targetNode);
|
||||
} else {
|
||||
if (sourceNode.children === undefined) {
|
||||
sourceNode.children = [];
|
||||
}
|
||||
sourceNode.children.push(targetNode);
|
||||
}
|
||||
if (targetNode.type === 0) {
|
||||
context.state[TOTAL_TREE_DATA][targetNode.path + "." + targetNode.bookmarkId] = [];
|
||||
}
|
||||
targetNode.isLeaf = targetNode.type === 0;
|
||||
targetNode.class = "treeNodeItem";
|
||||
targetNode.scopedSlots = { title: "nodeTitle" };
|
||||
context.commit(TOTAL_TREE_DATA, context.state[TOTAL_TREE_DATA]);
|
||||
await context.dispatch("updateVersion", null);
|
||||
await localforage.setItem(TOTAL_TREE_DATA, state[TOTAL_TREE_DATA]);
|
||||
},
|
||||
/**
|
||||
* 删除节点数据
|
||||
*/
|
||||
async [deleteData] (context, { pathList, bookmarkIdList }) {
|
||||
//待删除的书签
|
||||
let bookmarkIdSet = new Set();
|
||||
bookmarkIdList.forEach(item => bookmarkIdSet.add(item));
|
||||
//删除子节点
|
||||
pathList.forEach(item => {
|
||||
delete state[TOTAL_TREE_DATA][item];
|
||||
Object.keys(context.state[TOTAL_TREE_DATA])
|
||||
.filter(key => key.startsWith(item + "."))
|
||||
.forEach(key => delete state[TOTAL_TREE_DATA][key]);
|
||||
bookmarkIdSet.add(parseInt(item.split(".").reverse()));
|
||||
});
|
||||
//删除直接选中的节点
|
||||
Object.keys(context.state[TOTAL_TREE_DATA]).forEach(item => {
|
||||
let list = context.state[TOTAL_TREE_DATA][item];
|
||||
for (let i = list.length - 1; i >= 0; i--) {
|
||||
if (bookmarkIdSet.has(list[i].bookmarkId)) {
|
||||
list.splice(i, 1);
|
||||
}
|
||||
}
|
||||
});
|
||||
context.commit(TOTAL_TREE_DATA, context.state[TOTAL_TREE_DATA]);
|
||||
await context.dispatch("updateVersion", null);
|
||||
await localforage.setItem(TOTAL_TREE_DATA, state[TOTAL_TREE_DATA]);
|
||||
},
|
||||
/**
|
||||
* 编辑书签节点
|
||||
*/
|
||||
async editNode ({ dispatch, state, commit }, { node, newName, newUrl, newIcon }) {
|
||||
node.name = newName;
|
||||
node.url = newUrl;
|
||||
node.icon = newIcon;
|
||||
commit(TOTAL_TREE_DATA, state[TOTAL_TREE_DATA]);
|
||||
await dispatch("updateVersion", null);
|
||||
await localforage.setItem(TOTAL_TREE_DATA, state[TOTAL_TREE_DATA]);
|
||||
}
|
||||
async [noLoginInit]() {},
|
||||
async [loginInit](context) {
|
||||
if (context.state.isInit || context.state.isIniting) {
|
||||
return;
|
||||
}
|
||||
await context.dispatch(refreshHomePinList);
|
||||
context.commit(IS_INITING, true);
|
||||
context.commit(TOTAL_TREE_DATA, await localforage.getItem(TOTAL_TREE_DATA));
|
||||
context.commit(VERSION, await localforage.getItem(VERSION));
|
||||
await treeDataCheck(context, true);
|
||||
context.commit(IS_INIT, true);
|
||||
context.commit(IS_INITING, false);
|
||||
timer = setInterval(() => treeDataCheck(context, false), CHECK_INTERVAL);
|
||||
},
|
||||
/**
|
||||
* 确保数据加载完毕
|
||||
*/
|
||||
ensureDataOk(context) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let timer = setInterval(() => {
|
||||
try {
|
||||
if (context.state[IS_INIT] && context.state[IS_INITING] == false) {
|
||||
clearInterval(timer);
|
||||
resolve();
|
||||
}
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
}, 50);
|
||||
});
|
||||
},
|
||||
//刷新缓存数据
|
||||
async [refresh](context) {
|
||||
let treeData = await HttpUtil.get("/bookmark/currentUser");
|
||||
if (!treeData[""]) {
|
||||
treeData[""] = [];
|
||||
}
|
||||
Object.values(treeData).forEach(item =>
|
||||
item.forEach(item1 => {
|
||||
item1.isLeaf = item1.type === 0;
|
||||
item1.class = "treeNodeItem";
|
||||
item1.scopedSlots = { title: "nodeTitle" };
|
||||
})
|
||||
);
|
||||
let version = await HttpUtil.get("/user/version");
|
||||
await context.dispatch("updateVersion", version);
|
||||
await context.dispatch(refreshHomePinList);
|
||||
context.commit(TOTAL_TREE_DATA, treeData);
|
||||
await localforage.setItem(TOTAL_TREE_DATA, treeData);
|
||||
},
|
||||
//清除缓存数据
|
||||
async [clear](context) {
|
||||
context.commit(TOTAL_TREE_DATA, null);
|
||||
context.commit(VERSION, null);
|
||||
context.commit(SHOW_REFRESH_TOAST, false);
|
||||
context.commit(IS_INIT, false);
|
||||
context.commit(IS_INITING, false);
|
||||
context.commit(HOME_PIN_LIST, []);
|
||||
if (timer != null) {
|
||||
clearInterval(timer);
|
||||
}
|
||||
await localforage.removeItem(TOTAL_TREE_DATA);
|
||||
await localforage.removeItem(VERSION);
|
||||
},
|
||||
/**
|
||||
* 移动节点
|
||||
*/
|
||||
async moveNode(context, info) {
|
||||
let data = context.state[TOTAL_TREE_DATA];
|
||||
const target = info.node.dataRef;
|
||||
const current = info.dragNode.dataRef;
|
||||
//从原来位置中删除当前节点
|
||||
let currentList = data[current.path];
|
||||
currentList.splice(
|
||||
currentList.findIndex(item => item.bookmarkId === current.bookmarkId),
|
||||
1
|
||||
);
|
||||
//请求体
|
||||
const body = {
|
||||
bookmarkId: current.bookmarkId,
|
||||
sourcePath: current.path,
|
||||
targetPath: "",
|
||||
//-1 表示排在最后
|
||||
sort: -1
|
||||
};
|
||||
if (info.dropToGap) {
|
||||
body.targetPath = target.path;
|
||||
//移动到目标节点的上面或者下面
|
||||
let targetList = data[target.path];
|
||||
//目标节点index
|
||||
let index = targetList.indexOf(target);
|
||||
//移动节点相对于目标节点位置的增量
|
||||
let addIndex = info.dropPosition > index ? 1 : 0;
|
||||
body.sort = target.sort + addIndex;
|
||||
targetList.splice(index + addIndex, 0, current);
|
||||
for (let i = index + 1; i < targetList.length; i++) {
|
||||
targetList[i].sort += 1;
|
||||
}
|
||||
} else {
|
||||
//移动到一个文件夹下面
|
||||
body.targetPath = target.path + "." + target.bookmarkId;
|
||||
let targetList = data[body.targetPath];
|
||||
if (!targetList) {
|
||||
targetList = [];
|
||||
data[body.targetPath] = targetList;
|
||||
}
|
||||
body.sort = targetList.length > 0 ? targetList[targetList.length - 1].sort + 1 : 1;
|
||||
targetList.push(current);
|
||||
}
|
||||
//更新节点的path和对应子节点path
|
||||
current.path = body.targetPath;
|
||||
current.sort = body.sort;
|
||||
//如果为文件夹还要更新所有子书签的path
|
||||
if (body.sourcePath !== body.targetPath) {
|
||||
let keys = Object.keys(data);
|
||||
//旧路径
|
||||
let oldPath = body.sourcePath + "." + current.bookmarkId;
|
||||
//新路径
|
||||
let newPath = body.targetPath + "." + current.bookmarkId;
|
||||
keys.forEach(item => {
|
||||
if (!item.startsWith(oldPath)) {
|
||||
return;
|
||||
}
|
||||
let newPathStr = item.replace(oldPath, newPath);
|
||||
let list = data[item];
|
||||
delete data[item];
|
||||
data[newPathStr] = list;
|
||||
list.forEach(item1 => (item1.path = newPathStr));
|
||||
});
|
||||
}
|
||||
context.commit(TOTAL_TREE_DATA, context.state[TOTAL_TREE_DATA]);
|
||||
await context.dispatch("updateVersion", null);
|
||||
await localforage.setItem(TOTAL_TREE_DATA, state[TOTAL_TREE_DATA]);
|
||||
return body;
|
||||
},
|
||||
async [refreshHomePinList]({ commit }) {
|
||||
let list = await HttpUtil.get("/home/pin");
|
||||
commit(HOME_PIN_LIST, list);
|
||||
let map = {};
|
||||
list.filter(item => item.id).forEach(item => (map[item.bookmarkId] = true));
|
||||
commit(HOME_PIN_BOOKMARK_ID_MAP, map);
|
||||
},
|
||||
/**
|
||||
* 更新版本数据
|
||||
*/
|
||||
async updateVersion({ commit, state }, version) {
|
||||
commit(VERSION, version == null ? state[VERSION] + 1 : version);
|
||||
await localforage.setItem(VERSION, state[VERSION]);
|
||||
},
|
||||
/**
|
||||
* 新增书签、文件夹
|
||||
*/
|
||||
async [addNode](context, { sourceNode, targetNode }) {
|
||||
if (sourceNode === null) {
|
||||
if (context.state[TOTAL_TREE_DATA][""] === undefined) {
|
||||
context.state[TOTAL_TREE_DATA][""] = [];
|
||||
}
|
||||
context.state[TOTAL_TREE_DATA][""].push(targetNode);
|
||||
} else {
|
||||
if (sourceNode.children === undefined) {
|
||||
sourceNode.children = [];
|
||||
}
|
||||
sourceNode.children.push(targetNode);
|
||||
}
|
||||
if (targetNode.type === 0) {
|
||||
context.state[TOTAL_TREE_DATA][targetNode.path + "." + targetNode.bookmarkId] = [];
|
||||
}
|
||||
targetNode.isLeaf = targetNode.type === 0;
|
||||
targetNode.class = "treeNodeItem";
|
||||
targetNode.scopedSlots = { title: "nodeTitle" };
|
||||
context.commit(TOTAL_TREE_DATA, context.state[TOTAL_TREE_DATA]);
|
||||
await context.dispatch("updateVersion", null);
|
||||
await localforage.setItem(TOTAL_TREE_DATA, state[TOTAL_TREE_DATA]);
|
||||
},
|
||||
/**
|
||||
* 删除节点数据
|
||||
*/
|
||||
async [deleteData](context, { pathList, bookmarkIdList }) {
|
||||
//待删除的书签
|
||||
let bookmarkIdSet = new Set();
|
||||
bookmarkIdList.forEach(item => bookmarkIdSet.add(item));
|
||||
//删除子节点
|
||||
pathList.forEach(item => {
|
||||
delete state[TOTAL_TREE_DATA][item];
|
||||
Object.keys(context.state[TOTAL_TREE_DATA])
|
||||
.filter(key => key.startsWith(item + "."))
|
||||
.forEach(key => delete state[TOTAL_TREE_DATA][key]);
|
||||
bookmarkIdSet.add(parseInt(item.split(".").reverse()));
|
||||
});
|
||||
//删除直接选中的节点
|
||||
Object.keys(context.state[TOTAL_TREE_DATA]).forEach(item => {
|
||||
let list = context.state[TOTAL_TREE_DATA][item];
|
||||
for (let i = list.length - 1; i >= 0; i--) {
|
||||
if (bookmarkIdSet.has(list[i].bookmarkId)) {
|
||||
list.splice(i, 1);
|
||||
}
|
||||
}
|
||||
});
|
||||
context.commit(TOTAL_TREE_DATA, context.state[TOTAL_TREE_DATA]);
|
||||
await context.dispatch("updateVersion", null);
|
||||
await localforage.setItem(TOTAL_TREE_DATA, state[TOTAL_TREE_DATA]);
|
||||
},
|
||||
/**
|
||||
* 编辑书签节点
|
||||
*/
|
||||
async editNode({ dispatch, state, commit }, { node, newName, newUrl, newIcon }) {
|
||||
node.name = newName;
|
||||
node.url = newUrl;
|
||||
node.icon = newIcon;
|
||||
commit(TOTAL_TREE_DATA, state[TOTAL_TREE_DATA]);
|
||||
await dispatch("updateVersion", null);
|
||||
await localforage.setItem(TOTAL_TREE_DATA, state[TOTAL_TREE_DATA]);
|
||||
}
|
||||
};
|
||||
|
||||
const mutations = {
|
||||
[TOTAL_TREE_DATA]: (state, totalTreeData) => {
|
||||
state.totalTreeData = totalTreeData;
|
||||
},
|
||||
[IS_INIT] (state, isInit) {
|
||||
state.isInit = isInit;
|
||||
},
|
||||
[IS_INITING] (state, isIniting) {
|
||||
state.isIniting = isIniting;
|
||||
},
|
||||
[VERSION]: (state, version) => {
|
||||
state[VERSION] = version;
|
||||
},
|
||||
[SHOW_REFRESH_TOAST]: (state, val) => {
|
||||
state[SHOW_REFRESH_TOAST] = val;
|
||||
},
|
||||
[HOME_PIN_LIST]: (state, val) => {
|
||||
state[HOME_PIN_LIST] = val;
|
||||
},
|
||||
[HOME_PIN_BOOKMARK_ID_MAP]: (state, val) => {
|
||||
state[HOME_PIN_BOOKMARK_ID_MAP] = val;
|
||||
}
|
||||
[TOTAL_TREE_DATA]: (state, totalTreeData) => {
|
||||
state.totalTreeData = totalTreeData;
|
||||
},
|
||||
[IS_INIT](state, isInit) {
|
||||
state.isInit = isInit;
|
||||
},
|
||||
[IS_INITING](state, isIniting) {
|
||||
state.isIniting = isIniting;
|
||||
},
|
||||
[VERSION]: (state, version) => {
|
||||
state[VERSION] = version;
|
||||
},
|
||||
[SHOW_REFRESH_TOAST]: (state, val) => {
|
||||
state[SHOW_REFRESH_TOAST] = val;
|
||||
},
|
||||
[HOME_PIN_LIST]: (state, val) => {
|
||||
state[HOME_PIN_LIST] = val;
|
||||
},
|
||||
[HOME_PIN_BOOKMARK_ID_MAP]: (state, val) => {
|
||||
state[HOME_PIN_BOOKMARK_ID_MAP] = val;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* 检查书签缓存是否最新
|
||||
*
|
||||
@ -322,43 +322,42 @@ const mutations = {
|
||||
* @param {*} isFirst
|
||||
* @returns
|
||||
*/
|
||||
async function treeDataCheck (context, isFirst) {
|
||||
if (toastShow || !checkJwtValid(context.rootState.globalConfig.token)) {
|
||||
return;
|
||||
}
|
||||
let realVersion = await HttpUtil.get("/user/version");
|
||||
if (realVersion !== context.state[VERSION]) {
|
||||
if (context.state[SHOW_REFRESH_TOAST] && !isFirst) {
|
||||
//如果在书签管理页面需要弹窗提示
|
||||
window.vueInstance.$confirm({
|
||||
title: "书签数据有更新,是否立即刷新?",
|
||||
cancelText: "稍后提醒",
|
||||
closable: false,
|
||||
keyboard: false,
|
||||
maskClosable: false,
|
||||
onOk () {
|
||||
toastShow = false;
|
||||
return new Promise(async (resolve) => {
|
||||
await context.dispatch(refresh);
|
||||
resolve();
|
||||
});
|
||||
},
|
||||
onCancel () {
|
||||
toastShow = false;
|
||||
}
|
||||
});
|
||||
toastShow = true;
|
||||
} else {
|
||||
await context.dispatch(refresh);
|
||||
}
|
||||
}
|
||||
async function treeDataCheck(context, isFirst) {
|
||||
if (toastShow || !checkJwtValid(context.rootState.globalConfig.token)) {
|
||||
return;
|
||||
}
|
||||
let realVersion = await HttpUtil.get("/user/version");
|
||||
if (realVersion !== context.state[VERSION]) {
|
||||
if (context.state[SHOW_REFRESH_TOAST] && !isFirst) {
|
||||
//如果在书签管理页面需要弹窗提示
|
||||
window.vueInstance.$confirm({
|
||||
title: "书签数据有更新,是否立即刷新?",
|
||||
cancelText: "稍后提醒",
|
||||
closable: false,
|
||||
keyboard: false,
|
||||
maskClosable: false,
|
||||
onOk() {
|
||||
toastShow = false;
|
||||
return new Promise(async resolve => {
|
||||
await context.dispatch(refresh);
|
||||
resolve();
|
||||
});
|
||||
},
|
||||
onCancel() {
|
||||
toastShow = false;
|
||||
}
|
||||
});
|
||||
toastShow = true;
|
||||
} else {
|
||||
await context.dispatch(refresh);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const store = {
|
||||
namespaced: true,
|
||||
state,
|
||||
getters,
|
||||
actions,
|
||||
mutations
|
||||
namespaced: true,
|
||||
state,
|
||||
getters,
|
||||
actions,
|
||||
mutations
|
||||
};
|
||||
|
||||
|
@ -15,7 +15,7 @@
|
||||
<a-tooltip
|
||||
v-if="
|
||||
(checkedKeys.length === 0 && (currentSelect == null || currentSelect.type === 1)) ||
|
||||
(checkedKeys.length === 1 && checkedNodes[0].type === 1)
|
||||
(checkedKeys.length === 1 && checkedNodes[0].type === 1)
|
||||
"
|
||||
title="添加书签"
|
||||
>
|
||||
@ -77,7 +77,7 @@
|
||||
<a-menu-item v-if="!rec.dataRef.isLeaf" key="add">新增</a-menu-item>
|
||||
<a-menu-item v-else key="copy" class="copy-to-board" :data="rec.dataRef.url">复制URL</a-menu-item>
|
||||
<a-menu-item v-if="rec.dataRef.isLeaf" key="pin">
|
||||
{{ homePinList.filter((item) => item.id && item.bookmarkId == rec.dataRef.bookmarkId).length > 0 ? "从首页移除" : "固定到首页" }}
|
||||
{{ homePinList.filter(item => item.id && item.bookmarkId == rec.dataRef.bookmarkId).length > 0 ? "从首页移除" : "固定到首页" }}
|
||||
</a-menu-item>
|
||||
<a-menu-item key="edit">编辑</a-menu-item>
|
||||
<a-menu-item key="delete">删除</a-menu-item>
|
||||
@ -114,7 +114,7 @@ export default {
|
||||
loadedKeys: [], // 已加载数据
|
||||
replaceFields: {
|
||||
title: "name",
|
||||
key: "bookmarkId",
|
||||
key: "bookmarkId"
|
||||
},
|
||||
mulSelect: false, // 多选框是否显示
|
||||
currentSelect: null, // 当前树的选择项
|
||||
@ -126,19 +126,19 @@ export default {
|
||||
// 新增、修改目标数据,null说明向根节点增加数据
|
||||
targetNode: null,
|
||||
// 是否为新增动作
|
||||
isAdd: false,
|
||||
isAdd: false
|
||||
},
|
||||
copyBoard: null, //剪贴板对象
|
||||
copyBoard: null //剪贴板对象
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
...mapState("treeData", ["totalTreeData", HOME_PIN_LIST]),
|
||||
...mapState("globalConfig", ["isPhone"]),
|
||||
...mapState("globalConfig", ["isPhone"])
|
||||
},
|
||||
watch: {
|
||||
totalTreeData(newVal, oldVal) {
|
||||
this.resetData();
|
||||
},
|
||||
}
|
||||
},
|
||||
async mounted() {
|
||||
this.$store.commit(TREE_DATA + "/" + SHOW_REFRESH_TOAST, true);
|
||||
@ -147,14 +147,21 @@ export default {
|
||||
this.loading = false;
|
||||
//初始化clipboard
|
||||
this.copyBoard = new ClipboardJS(".copy-to-board", {
|
||||
text: function (trigger) {
|
||||
text: function(trigger) {
|
||||
return trigger.attributes.data.nodeValue;
|
||||
},
|
||||
}
|
||||
});
|
||||
this.copyBoard.on("success", (e) => {
|
||||
this.copyBoard.on("success", e => {
|
||||
this.$message.success("复制成功");
|
||||
e.clearSelection();
|
||||
});
|
||||
|
||||
window.onblur = e => {
|
||||
console.log("窗口非激活");
|
||||
};
|
||||
window.onfocus = e => {
|
||||
console.log("窗口激活");
|
||||
};
|
||||
},
|
||||
beforeDestroy() {
|
||||
this.$store.commit(TREE_DATA + "/" + SHOW_REFRESH_TOAST, false);
|
||||
@ -168,7 +175,7 @@ export default {
|
||||
*/
|
||||
loadData(treeNode) {
|
||||
console.log("加载数据", treeNode);
|
||||
return new Promise((resolve) => {
|
||||
return new Promise(resolve => {
|
||||
const data = typeof treeNode === "number" ? this.$store.getters["treeData/getById"](treeNode) : treeNode.dataRef;
|
||||
let newPath = data.path + "." + data.bookmarkId;
|
||||
if (!this.totalTreeData[newPath]) {
|
||||
@ -212,9 +219,9 @@ export default {
|
||||
this.expandedKeys = [
|
||||
...item.path
|
||||
.split(".")
|
||||
.filter((item) => item.length > 0)
|
||||
.map((item) => parseInt(item)),
|
||||
item.bookmarkId,
|
||||
.filter(item => item.length > 0)
|
||||
.map(item => parseInt(item)),
|
||||
item.bookmarkId
|
||||
];
|
||||
} else {
|
||||
this.expandedKeys.pop();
|
||||
@ -228,7 +235,7 @@ export default {
|
||||
} else {
|
||||
this.checkedKeys.splice(this.checkedKeys.indexOf(item.bookmarkId), 1);
|
||||
this.checkedNodes.splice(
|
||||
this.checkedNodes.findIndex((item1) => item1.bookmarkId === item.bookmarkId),
|
||||
this.checkedNodes.findIndex(item1 => item1.bookmarkId === item.bookmarkId),
|
||||
1
|
||||
);
|
||||
}
|
||||
@ -248,9 +255,9 @@ export default {
|
||||
this.expandedKeys = [
|
||||
...item.path
|
||||
.split(".")
|
||||
.filter((item) => item.length > 0)
|
||||
.map((item) => parseInt(item)),
|
||||
item.bookmarkId,
|
||||
.filter(item => item.length > 0)
|
||||
.map(item => parseInt(item)),
|
||||
item.bookmarkId
|
||||
];
|
||||
}
|
||||
} else {
|
||||
@ -273,7 +280,7 @@ export default {
|
||||
const bookmarkIdList = [];
|
||||
const pathList = [];
|
||||
if (this.checkedNodes) {
|
||||
this.checkedNodes.forEach((item) =>
|
||||
this.checkedNodes.forEach(item =>
|
||||
item.type === 1 ? pathList.push(item.path + "." + item.bookmarkId) : bookmarkIdList.push(item.bookmarkId)
|
||||
);
|
||||
}
|
||||
@ -290,7 +297,7 @@ export default {
|
||||
await HttpUtil.post("/bookmark/batchDelete", null, { pathList, bookmarkIdList });
|
||||
await this.$store.dispatch(TREE_DATA + "/" + deleteData, { pathList, bookmarkIdList });
|
||||
//删除已经被删除的数据
|
||||
pathList.forEach((item) => {
|
||||
pathList.forEach(item => {
|
||||
const id = parseInt(item.split(".").reverse()[0]);
|
||||
let index = this.loadedKeys.indexOf(id);
|
||||
if (index > -1) {
|
||||
@ -322,13 +329,13 @@ export default {
|
||||
this.refresh(false);
|
||||
this.expandedKeys = item.path
|
||||
.split(".")
|
||||
.filter((one) => one.length > 0)
|
||||
.map((one) => parseInt(one));
|
||||
.filter(one => one.length > 0)
|
||||
.map(one => parseInt(one));
|
||||
this.loadedKeys = item.path
|
||||
.split(".")
|
||||
.filter((one) => one.length > 0)
|
||||
.map((one) => parseInt(one));
|
||||
this.expandedKeys.forEach(async (one) => await this.loadData(one));
|
||||
.filter(one => one.length > 0)
|
||||
.map(one => parseInt(one));
|
||||
this.expandedKeys.forEach(async one => await this.loadData(one));
|
||||
this.currentSelect = item;
|
||||
},
|
||||
/**
|
||||
@ -344,7 +351,7 @@ export default {
|
||||
this.addModal = {
|
||||
show: false,
|
||||
targetNode: null,
|
||||
isAdd: false,
|
||||
isAdd: false
|
||||
};
|
||||
},
|
||||
async onDrop(info) {
|
||||
@ -388,12 +395,12 @@ export default {
|
||||
await this.deleteBookmarks();
|
||||
resolve();
|
||||
});
|
||||
},
|
||||
}
|
||||
});
|
||||
} else if (key === "edit") {
|
||||
this.editData();
|
||||
} else if (key === "pin") {
|
||||
let pin = this.homePinList.filter((one) => one.id && one.bookmarkId == item.bookmarkId);
|
||||
let pin = this.homePinList.filter(one => one.id && one.bookmarkId == item.bookmarkId);
|
||||
if (pin.length > 0) {
|
||||
await HttpUtil.delete("/home/pin", { id: pin[0].id });
|
||||
} else {
|
||||
@ -411,8 +418,8 @@ export default {
|
||||
dealList(root, map[""], map);
|
||||
let content = exportFileHead + root.outerHTML;
|
||||
downloadFile(moment().format("YYYY-MM-DD") + "导出书签.html", content);
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
|
39
bookmark_front/src/views/manage/sso/auth/index.vue
Normal file
39
bookmark_front/src/views/manage/sso/auth/index.vue
Normal file
@ -0,0 +1,39 @@
|
||||
<template>
|
||||
<div class="ssoMain">{{ message }}</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import { GLOBAL_CONFIG, TOKEN } from "@/store/modules/globalConfig";
|
||||
export default {
|
||||
name: "ssoPage",
|
||||
data() {
|
||||
return {
|
||||
message: "loading"
|
||||
};
|
||||
},
|
||||
mounted() {
|
||||
window.addEventListener("message", event => {
|
||||
if (!event.data.code) {
|
||||
return;
|
||||
}
|
||||
console.log("收到content消息", event);
|
||||
if (event.data.code == "setTokenOk") {
|
||||
this.message = "登陆成功,3s后关闭本页面";
|
||||
setTimeout(() => window.close(), 3000);
|
||||
}
|
||||
});
|
||||
|
||||
let token = this.$store.state[GLOBAL_CONFIG][TOKEN];
|
||||
window.postMessage({ code: "setToken", data: token }, "*");
|
||||
},
|
||||
beforeDestroy() {
|
||||
window.removeEventListener("message");
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.ssoMain {
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
63
bookmark_front/src/views/noHead/addBookmark/index.vue
Normal file
63
bookmark_front/src/views/noHead/addBookmark/index.vue
Normal file
@ -0,0 +1,63 @@
|
||||
<template>
|
||||
<div class="ssoAddBookmark">
|
||||
正在添加,请稍后!!!
|
||||
<!-- <button @click="closeIframe">关闭</button> -->
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import HttpUtil from "@/util/HttpUtil";
|
||||
import { TREE_DATA, addNode } from "@/store/modules/treeData";
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
form: {
|
||||
name: null,
|
||||
url: null,
|
||||
type: 0,
|
||||
path: ""
|
||||
}
|
||||
};
|
||||
},
|
||||
mounted() {
|
||||
//接受父节点传递的书签信息
|
||||
window.addEventListener("message", event => {
|
||||
if (!event.data.code) {
|
||||
return;
|
||||
}
|
||||
console.log("收到content消息", event);
|
||||
if (event.data.code == "addBookmarkAction") {
|
||||
console.log("新增书签");
|
||||
this.form.name = event.data.data.name;
|
||||
this.form.url = event.data.data.url;
|
||||
this.addBookmark();
|
||||
}
|
||||
});
|
||||
console.log("向父节点获取数据");
|
||||
window.parent.postMessage({ code: "getBookmarkData", receiver: "content" }, "*");
|
||||
},
|
||||
methods: {
|
||||
closeIframe() {
|
||||
window.parent.postMessage({ code: "closeIframe", receiver: "content" }, "*");
|
||||
},
|
||||
//新增书签
|
||||
async addBookmark() {
|
||||
let res = await HttpUtil.put("/bookmark", null, this.form);
|
||||
this.$message.success("添加成功");
|
||||
await this.$store.dispatch(TREE_DATA + "/" + addNode, { sourceNode: null, targetNode: res });
|
||||
setTimeout(this.closeIframe, 500);
|
||||
}
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.ssoAddBookmark {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
background: white;
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
}
|
||||
</style>
|
@ -9,6 +9,11 @@
|
||||
使用教程:
|
||||
<a href="https://blog.fleyx.com/blog/detail/20220329" target="_blank">点击跳转</a>
|
||||
</div>
|
||||
<div>
|
||||
浏览器插件:
|
||||
<a href="/static/bookmarkBrowserPlugin.7z" download="浏览器插件.7z" target="_blank">点击下载</a>
|
||||
,使用详情请参考使用教程
|
||||
</div>
|
||||
<div>交流反馈qq群:150056494,邮箱:fleyx20@outlook.com</div>
|
||||
<div>
|
||||
统计:
|
||||
@ -38,7 +43,7 @@ export default {
|
||||
script.defer = true;
|
||||
script.src = "https://qiezi.fleyx.com/qiezijs/1.0/qiezi_statistic.min.js";
|
||||
document.getElementsByTagName("head")[0].appendChild(script);
|
||||
},
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
|
100
浏览器插件/bookmarkBrowserPlugin/background.js
Normal file
100
浏览器插件/bookmarkBrowserPlugin/background.js
Normal file
@ -0,0 +1,100 @@
|
||||
chrome.runtime.onInstalled.addListener(() => {
|
||||
chrome.contextMenus.create(
|
||||
{
|
||||
title: '添加到书签',
|
||||
id: "addBookmark",
|
||||
},
|
||||
() => console.log("创建右键菜单成功")
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
|
||||
chrome.contextMenus.onClicked.addListener(async function (info, tab) {
|
||||
console.log(info, tab);
|
||||
let body = {
|
||||
name: tab.title,
|
||||
url: tab.url,
|
||||
};
|
||||
sendToContent(tab.id, { code: "addBookmark", data: body, token: await getVal("token") });
|
||||
});
|
||||
|
||||
|
||||
// 接收content/popup发送的消息
|
||||
chrome.runtime.onMessage.addListener(async (data, sender, sendResponse) => {
|
||||
if (!data.code || !data.receiver == 'background') {
|
||||
return;
|
||||
}
|
||||
sendResponse("ok");
|
||||
console.log("收到消息:", data, sender);
|
||||
if (data.code == 'setToken') {
|
||||
await setVal("token", data.data);
|
||||
// sendToContent
|
||||
await sendToContent(sender.tab.id, { code: "setTokenOk" });
|
||||
} else if (data.code == 'getToken') {
|
||||
let token = await getVal("token");
|
||||
sendToPopup({ code: "setToken", data: await getVal("token") });
|
||||
} else if (data.code == "clearToken") {
|
||||
await clearVal("token");
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* 向content发送消息
|
||||
* @param {*} tabId
|
||||
* @param {*} data
|
||||
*/
|
||||
function sendToContent (tabId, data) {
|
||||
console.log(tabId, data);
|
||||
data.receiver = "content";
|
||||
chrome.tabs.sendMessage(tabId, data, res => {
|
||||
console.log("接受响应", res);
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 向popup发送消息
|
||||
* @param {*} data
|
||||
*/
|
||||
function sendToPopup (data) {
|
||||
data.receiver = "popup";
|
||||
chrome.runtime.sendMessage(data, res => console.log(res));
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置值
|
||||
* @param {*} key
|
||||
* @param {*} val
|
||||
* @returns
|
||||
*/
|
||||
function setVal (key, val) {
|
||||
return new Promise((resolve, reject) => {
|
||||
chrome.storage.local.set({ [key]: val }, function () {
|
||||
console.log("设置值成功:", key, val)
|
||||
resolve();
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取值
|
||||
* @param {*} key
|
||||
* @returns
|
||||
*/
|
||||
function getVal (key) {
|
||||
return new Promise((resolve, reject) => {
|
||||
chrome.storage.local.get([key], function (res) {
|
||||
console.log("取值成功", res);
|
||||
resolve(res[key]);
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function clearVal (key) {
|
||||
return new Promise((resolve, reject) => {
|
||||
chrome.storage.local.remove(key, function () {
|
||||
console.log("remove成功", key);
|
||||
resolve();
|
||||
})
|
||||
})
|
||||
}
|
26
浏览器插件/bookmarkBrowserPlugin/manifest.json
Normal file
26
浏览器插件/bookmarkBrowserPlugin/manifest.json
Normal file
@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "签签世界",
|
||||
"description": "云书签管理平台",
|
||||
"version": "1.0",
|
||||
"manifest_version": 3,
|
||||
"permissions": ["contextMenus", "storage"],
|
||||
"action": {
|
||||
"default_popup": "popup/index.html"
|
||||
},
|
||||
"icons": {
|
||||
"48": "static/icons/favicon.png",
|
||||
"128": "static/icons/favicon.png"
|
||||
},
|
||||
"background": {
|
||||
"service_worker": "background.js"
|
||||
},
|
||||
"options_ui": {
|
||||
"page": "options/index.html"
|
||||
},
|
||||
"content_scripts": [
|
||||
{
|
||||
"matches": ["*://*/*"],
|
||||
"js": ["static/js/axios.min.js", "static/js/config.js", "static/js/content.js"]
|
||||
}
|
||||
]
|
||||
}
|
16
浏览器插件/bookmarkBrowserPlugin/options/index.html
Normal file
16
浏览器插件/bookmarkBrowserPlugin/options/index.html
Normal file
@ -0,0 +1,16 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Document</title>
|
||||
<style>
|
||||
#content {
|
||||
color: red;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>option.html</h1>
|
||||
</body>
|
||||
</html>
|
31
浏览器插件/bookmarkBrowserPlugin/popup/index.html
Normal file
31
浏览器插件/bookmarkBrowserPlugin/popup/index.html
Normal file
@ -0,0 +1,31 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Document</title>
|
||||
<style>
|
||||
html,
|
||||
body {
|
||||
padding: 0.2em;
|
||||
width: 8em;
|
||||
}
|
||||
#content {
|
||||
color: red;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<a id="login" href="https://fleyx.com/userSpace/ssoAuth" target="_blank">点击登录</a>
|
||||
<div id="action" style="display: none">
|
||||
<button id="logout">退出登陆</button>
|
||||
<!-- <button title="同步云端书签到浏览器(覆盖本地)">同步云端书签</button> -->
|
||||
<!-- <button title="同步浏览器书签到云端(覆盖云端)">同步浏览器</button> -->
|
||||
</div>
|
||||
<p id="content"></p>
|
||||
<div class="bottom">插件版本:<span id="version"></span></div>
|
||||
<script type="text/javascript" src="/static/js/axios.min.js"></script>
|
||||
<script type="text/javascript" src="/static/js/config.js"></script>
|
||||
<script type="text/javascript" src="/popup/index.js"></script>
|
||||
</body>
|
||||
</html>
|
50
浏览器插件/bookmarkBrowserPlugin/popup/index.js
Normal file
50
浏览器插件/bookmarkBrowserPlugin/popup/index.js
Normal file
@ -0,0 +1,50 @@
|
||||
console.log("asdf");
|
||||
console.log(bookmarkHost);
|
||||
|
||||
var token;
|
||||
var login = document.getElementById("login");
|
||||
var action = document.getElementById("action");
|
||||
|
||||
(async () => {
|
||||
//初始化
|
||||
login.href = bookmarkHost + "/manage/sso/auth";
|
||||
document.getElementById("version").innerText = version;
|
||||
sendToBg("getToken", null);
|
||||
})();
|
||||
|
||||
/**
|
||||
* 退出登陆
|
||||
*/
|
||||
document.getElementById("logout").addEventListener("click", () => {
|
||||
console.log("click");
|
||||
sendToBg("clearToken", null);
|
||||
action.style.display = "none";
|
||||
login.style.display = "block";
|
||||
});
|
||||
|
||||
/**
|
||||
* 发送消息到后台
|
||||
* @param {*} data
|
||||
*/
|
||||
function sendToBg (code, data) {
|
||||
chrome.runtime.sendMessage({ code, data, receiver: "background" }, res => console.log(res));
|
||||
}
|
||||
|
||||
|
||||
// 接收content/background发送的消息
|
||||
chrome.runtime.onMessage.addListener(async (data, sender, sendResponse) => {
|
||||
if (!data.code || !data.receiver == 'popup') {
|
||||
return;
|
||||
}
|
||||
sendResponse("ok");
|
||||
console.log("popup收到消息:", data);
|
||||
if (data.code == 'setToken') {
|
||||
token = data.data;
|
||||
if (token) {
|
||||
action.style.display = "block";
|
||||
login.style.display = "none";
|
||||
} else {
|
||||
login.style.display = "block";
|
||||
}
|
||||
}
|
||||
})
|
BIN
浏览器插件/bookmarkBrowserPlugin/static/icons/favicon.ico
Normal file
BIN
浏览器插件/bookmarkBrowserPlugin/static/icons/favicon.ico
Normal file
Binary file not shown.
After Width: | Height: | Size: 4.2 KiB |
BIN
浏览器插件/bookmarkBrowserPlugin/static/icons/favicon.png
Normal file
BIN
浏览器插件/bookmarkBrowserPlugin/static/icons/favicon.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 62 KiB |
2
浏览器插件/bookmarkBrowserPlugin/static/js/axios.min.js
vendored
Normal file
2
浏览器插件/bookmarkBrowserPlugin/static/js/axios.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
10
浏览器插件/bookmarkBrowserPlugin/static/js/config.js
Normal file
10
浏览器插件/bookmarkBrowserPlugin/static/js/config.js
Normal file
@ -0,0 +1,10 @@
|
||||
var bookmarkHost = "https://fleyx.com";
|
||||
// var bookmarkHost = "http://localhost:8080";
|
||||
|
||||
var version = "0.1";
|
||||
|
||||
window.token = localStorage.getItem('token');
|
||||
axios.defaults.baseURL = bookmarkHost + '/bookmark/api';
|
||||
axios.defaults.headers.common['jwt-token'] = window.token;
|
||||
axios.defaults.headers.post['Content-Type'] = 'application/json';
|
||||
axios.defaults.headers.put['Content-Type'] = 'application/json';
|
98
浏览器插件/bookmarkBrowserPlugin/static/js/content.js
Normal file
98
浏览器插件/bookmarkBrowserPlugin/static/js/content.js
Normal file
@ -0,0 +1,98 @@
|
||||
console.log('注入了页面');
|
||||
|
||||
var bookmarkInfo = null;
|
||||
var addBlockDiv = null;
|
||||
var iframe = null;
|
||||
|
||||
/**
|
||||
* 接收当前注入页面传来的消息
|
||||
*/
|
||||
window.addEventListener('message', function (event) {
|
||||
console.log(event);
|
||||
if (event.data.code === undefined) {
|
||||
return;
|
||||
}
|
||||
console.log('接受到网页消息:', event.data);
|
||||
if (event.data.code === 'getBookmarkData') {
|
||||
iframe.contentWindow.postMessage({ code: "addBookmarkAction", data: bookmarkInfo }, "*");
|
||||
} else if (event.data.code === 'setToken') {
|
||||
sendToBg(event.data);
|
||||
} else if (event.data.code == 'closeIframe') {
|
||||
addBlockDiv.remove();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* 接收content/background发送的消息
|
||||
*/
|
||||
chrome.runtime.onMessage.addListener(async (data, sender, sendResponse) => {
|
||||
if (!data || !data.code || data.receiver != "content") {
|
||||
return;
|
||||
}
|
||||
sendResponse("ok");
|
||||
console.log('收到消息:', data);
|
||||
if (data.code == 'setTokenOk') {
|
||||
sendToPage(data);
|
||||
} else if (data.code == 'addBookmark') {
|
||||
await addBookmark(data);
|
||||
}
|
||||
});
|
||||
|
||||
async function addBookmark (data) {
|
||||
if (!checkTokenValid(data.token)) {
|
||||
alert("登陆失效,请登陆后,重试");
|
||||
window.open(bookmarkHost + "/manage/sso/auth");
|
||||
return;
|
||||
}
|
||||
//新增书签
|
||||
console.log("新增书签", data.data);
|
||||
bookmarkInfo = data.data;
|
||||
addBlockDiv = document.createElement("div");
|
||||
addBlockDiv.setAttribute("style", "position:fixed;width:100%;height:100vh;z-index:100000;left:0;top:0;background:rgba(211, 211, 205, 0.8)");
|
||||
document.getElementsByTagName("body")[0].appendChild(addBlockDiv);
|
||||
iframe = document.createElement("iframe");
|
||||
iframe.src = bookmarkHost + "/noHead/addBookmark?token=" + data.token;
|
||||
iframe.setAttribute("style", "width:70%;min-height:60vh;margin-left:15%;margin-top:10vh;padding:0;border:0;border-radius:10px");
|
||||
addBlockDiv.appendChild(iframe);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送消息给bg
|
||||
* @param {*} data
|
||||
*/
|
||||
function sendToBg (data) {
|
||||
data.receiver = "background";
|
||||
chrome.runtime.sendMessage(data, response => {
|
||||
console.log(response);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 发消息到页面
|
||||
* @param {*} data
|
||||
*/
|
||||
function sendToPage (data) {
|
||||
data.receiver = "page";
|
||||
window.postMessage(data, "*");
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查token是否有效
|
||||
* @param {*} token
|
||||
* @returns
|
||||
*/
|
||||
function checkTokenValid (token) {
|
||||
try {
|
||||
if (token && token.trim().length > 0) {
|
||||
//检查token是否还有效
|
||||
let content = JSON.parse(window.atob(token.split(".")[1]));
|
||||
if (content.exp > Date.now() / 1000) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
return false;
|
||||
}
|
2
浏览器插件/bookmarkBrowserPlugin/static/js/jquery.js
vendored
Normal file
2
浏览器插件/bookmarkBrowserPlugin/static/js/jquery.js
vendored
Normal file
File diff suppressed because one or more lines are too long
Loading…
x
Reference in New Issue
Block a user