Skip to content

Commit

Permalink
pref(site): 根据讨论,优化favicon.ts
Browse files Browse the repository at this point in the history
refs: #1034
  • Loading branch information
Rhilip committed Apr 3, 2022
1 parent 069661e commit a310efe
Show file tree
Hide file tree
Showing 10 changed files with 257 additions and 186 deletions.
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ module.exports = {

rules: {
semi: ["error", "always"],
quotes: ["error", "double", { avoidEscape: true }],
"max-len": [
"warn",
{
Expand Down
3 changes: 2 additions & 1 deletion packages/site/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"axios": "^0.26.0",
"chrono-node": "^2.2.7",
"dayjs": "^1.11.0",
"localforage": "^1.10.0",
"lodash-es": "^4.17.20",
"sizzle": "^2.3.5",
"url-join": "^5.0.0",
Expand All @@ -19,6 +20,6 @@
"typescript": "^4.6.2"
},
"peerDependencies": {
"webpack":"^5.70.0"
"webpack": "^5.70.0"
}
}
Binary file added packages/site/src/icons/ourbits.ico
Binary file not shown.
45 changes: 24 additions & 21 deletions packages/site/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,28 @@
export * from "./types";
export * from "./utils";
import { ISiteMetadata } from "./types";

import type { ISiteMetadata } from "./types";
import favicon from "./utils/favicon";
import BittorrentSite from "./schema/AbstractBittorrentSite";
import PrivateSite from "./schema/AbstractPrivateSite";
export { BittorrentSite, PrivateSite };

// @ts-ignore
const schemaContent = import.meta.webpackContext('./schema/', {
export { BittorrentSite, PrivateSite, favicon };

// @ts-ignore
const schemaContent = import.meta.webpackContext("./schema/", {
regExp: /\.ts$/,
chunkName: "lib/site/schema/[request]",
mode: 'lazy'
mode: "lazy"
});

// @ts-ignore
const definitionContent = import.meta.webpackContext('./definitions/', {
// @ts-ignore
const definitionContent = import.meta.webpackContext("./definitions/", {
regExp: /\.ts$/,
chunkName: "lib/site/definitions/[request]",
mode: 'lazy'
mode: "lazy"
});

function transContent(value: string) {
function transContent (value: string) {
return value.replace(/^\.\//, "").replace(/\.ts$/, "");
}

Expand All @@ -28,13 +31,13 @@ export const definitionList = definitionContent.keys().map(transContent);

export type TSite = PrivateSite | BittorrentSite;

export async function getSchemaModule(
export async function getSchemaModule (
schema: string
): Promise<{ default: TSite }> {
return await schemaContent(`./${schema}.ts`);
}

export async function getDefinitionModule(definition: string): Promise<{
export async function getDefinitionModule (definition: string): Promise<{
default?: TSite;
siteMetadata: ISiteMetadata;
}> {
Expand All @@ -44,20 +47,20 @@ export async function getDefinitionModule(definition: string): Promise<{
const siteInstanceCache: Record<string, TSite> = {};

// FIXME 部分用户自定义的站点(此时在 js/site 目录中不存在对应模块),不能进行 dynamicImport 的情况,对此应该直接从 schema 中导入
export async function getSite(
export async function getSite (
siteName: string,
userConfig: Partial<ISiteMetadata> = {}
): Promise<TSite> {
if (typeof siteInstanceCache[siteName] === "undefined") {
// eslint-disable-next-line prefer-const
let { siteMetadata: siteMetaData /* use as const */, default: SiteClass } =
await getDefinitionModule(siteName);
if (!siteMetaData.schema) {
siteMetaData.schema =
siteMetaData.type === "private"
? "AbstractPrivateSite"
: "AbstractBittorrentSite";
}
let {
// eslint-disable-next-line prefer-const
siteMetadata: siteMetaData,
default: SiteClass
} = await getDefinitionModule(siteName);

// 补全缺失字段(此处补影响站点mete构造的内容,其余内容在 config 里面构造)
siteMetaData.id ??= siteName;
siteMetaData.schema ??= siteMetaData.type === "private" ? "AbstractPrivateSite" : "AbstractBittorrentSite";

/**
* 如果该模块没有导出 default class,那么我们认为我们需要从基类继承
Expand Down
89 changes: 55 additions & 34 deletions packages/site/src/schema/AbstractBittorrentSite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import {
parseTimeWithZone,
} from "../utils";

function restoreSecureLink(url: string): fullUrl {
function restoreSecureLink (url: string): fullUrl {
return (url.startsWith("aHR0c") ? atob(url) : url) as fullUrl;
}

Expand All @@ -49,15 +49,15 @@ export default class BittorrentSite {
cacheRequest: new Map(),
};

constructor(
constructor (
config: Partial<ISiteMetadata> = {},
siteMetaData: ISiteMetadata
) {
this.userConfig = config;
this.siteMetaData = siteMetaData;
}

get config(): ISiteMetadata {
get config (): ISiteMetadata {
if (!this._config) {
/**
* 使用 lodash 的 mergeWith 来合并站点默认配置和用户配置
Expand Down Expand Up @@ -89,9 +89,7 @@ export default class BittorrentSite {
}

// 防止host信息缺失
if (!this._config.host) {
this._config.host = new URL(this._config.url).host;
}
this._config.host ??= new URL(this._config.url).host;

if (this._config.category && this._config.search) {
this._config.search.categories = ([] as any[]).concat(
Expand All @@ -107,11 +105,11 @@ export default class BittorrentSite {
return this._config;
}

get activateUrl(): string {
get activateUrl (): string {
return this.config.config?.activateUrl || this.config.url;
}

protected transferPostData<T extends Record<string, any>>(
protected transferPostData<T extends Record<string, any>> (
params: T,
transTo: transPostDataTo
) {
Expand All @@ -135,10 +133,13 @@ export default class BittorrentSite {
* 根据搜索筛选条件,生成 AxiosRequestConfig
* @param filter
*/
protected async transformSearchFilter(
protected async transformSearchFilter (
filter: ISearchFilter
): Promise<AxiosRequestConfig> {
const config: AxiosRequestConfig = { params: {}, data: {} };
const config: AxiosRequestConfig = {
params: {},
data: {}
};

const params: any = {};
if (filter.keywords) {
Expand All @@ -148,7 +149,10 @@ export default class BittorrentSite {

if (filter.extraParams) {
for (let i = 0; i < filter.extraParams?.length; i++) {
let { key, value } = filter.extraParams[i];
let {
key,
value
} = filter.extraParams[i];

if (key === "#changeDomain") {
// 更换 baseURL
Expand Down Expand Up @@ -207,7 +211,7 @@ export default class BittorrentSite {
* 种子搜索方法
* @param filter
*/
public async searchTorrents(
public async searchTorrents (
filter: ISearchFilter = {}
): Promise<ISearchResult> {
const result: ISearchResult = {
Expand Down Expand Up @@ -235,7 +239,10 @@ export default class BittorrentSite {

// 根据配置和搜索关键词生成 AxiosRequestConfig
let axiosConfig: AxiosRequestConfig = merge(
{ url: "/", responseType: "document" },
{
url: "/",
responseType: "document"
},
this.config.search?.requestConfig, // 使用默认配置覆盖垫片配置
await this.transformSearchFilter(filter) // 根据搜索信息生成配置
);
Expand All @@ -247,10 +254,16 @@ export default class BittorrentSite {

// 请求页面并转化为document
try {
const req = await this.request({ ...axiosConfig, checkLogin: true });
const req = await this.request({
...axiosConfig,
checkLogin: true
});
const rawTorrent = await this.transformSearchPage(req.data);
result.data = rawTorrent.map((t) =>
this.fixParsedTorrent(t, { filter, axiosConfig })
this.fixParsedTorrent(t, {
filter,
axiosConfig
})
);
} catch (e) {
if (e instanceof NeedLoginError) {
Expand All @@ -264,7 +277,7 @@ export default class BittorrentSite {
return result;
}

async request<T>(
async request<T> (
axiosConfig: AxiosRequestConfig & {
requestName?: string;
checkLogin?: boolean;
Expand Down Expand Up @@ -324,7 +337,7 @@ export default class BittorrentSite {
* @param uri
* @param requestConfig
*/
protected fixLink(uri: string, requestConfig: AxiosRequestConfig): string {
protected fixLink (uri: string, requestConfig: AxiosRequestConfig): string {
let url = uri;

if (uri.length > 0 && !uri.startsWith("magnet:")) {
Expand All @@ -349,11 +362,9 @@ export default class BittorrentSite {
* @param fields
* @protected
*/
protected getFieldsData<
G extends "search" | "detail" | "userInfo",
protected getFieldsData<G extends "search" | "detail" | "userInfo",
// @ts-ignore
F extends keyof Required<Required<ISiteMetadata>[G]>["selectors"]
>(
F extends keyof Required<Required<ISiteMetadata>[G]>["selectors"]> (
element: Element | object,
selectorGroup: G,
fields: F[]
Expand All @@ -370,7 +381,7 @@ export default class BittorrentSite {
return ret;
}

protected getFieldData(
protected getFieldData (
element: Element | object,
elementQuery: IElementQuery
): any {
Expand Down Expand Up @@ -448,7 +459,7 @@ export default class BittorrentSite {
return query;
}

protected runQueryFilters<T>(
protected runQueryFilters<T> (
query: any,
filters: TQueryFilter[] | TQueryFilter
): T {
Expand All @@ -469,15 +480,15 @@ export default class BittorrentSite {
* 登录检查方法,对于公开站点,该方法一定直接返回 True
* @param raw
*/
protected loggedCheck(raw: AxiosResponse): boolean {
protected loggedCheck (raw: AxiosResponse): boolean {
return true;
}

/**
* 如何解析 JSON 或者 Document,获得种子详情列表
* @param doc
*/
protected async transformSearchPage(
protected async transformSearchPage (
doc: Document | object | any
): Promise<ITorrent[]> {
if (!this.config.search?.selectors?.rows) {
Expand Down Expand Up @@ -537,7 +548,7 @@ export default class BittorrentSite {
return torrents;
}

protected fixParsedTorrent(
protected fixParsedTorrent (
torrent: ITorrent,
requestConfig: ISearchRequestConfig
): ITorrent {
Expand Down Expand Up @@ -605,7 +616,7 @@ export default class BittorrentSite {
return torrent;
}

protected parseRowToTorrent(
protected parseRowToTorrent (
row: Element | Document | object,
torrent: Partial<ITorrent> = {}
): Partial<ITorrent> {
Expand Down Expand Up @@ -638,7 +649,7 @@ export default class BittorrentSite {
return torrent;
}

protected parseTagsFromRow(row: Element | Document | object): ITorrentTag[] {
protected parseTagsFromRow (row: Element | Document | object): ITorrentTag[] {
const tags: ITorrentTag[] = [];
const tagsQuerys = this.config.search!.selectors!.tags!;
for (let i = 0; i < tagsQuerys.length; i++) {
Expand All @@ -654,32 +665,42 @@ export default class BittorrentSite {
}
}

const { selector, name, color } = tagsQuerys[i];
const {
selector,
name,
color
} = tagsQuerys[i];
if (row instanceof Element) {
if (Sizzle(selector, row).length > 0) {
tags.push({ name, color });
tags.push({
name,
color
});
}
} else {
if (get(row, selector)) {
tags.push({ name, color });
tags.push({
name,
color
});
}
}
}

return tags;
}

protected parseDownloadProcessFromRow(
protected parseDownloadProcessFromRow (
row: Element | Document | object
): Pick<ITorrent, "progress" | "status"> {
return {};
}

async getTorrentPageLink(torrent: ITorrent): Promise<string> {
async getTorrentPageLink (torrent: ITorrent): Promise<string> {
return torrent.url;
}

async getTorrentDownloadLink(torrent: ITorrent): Promise<string> {
async getTorrentDownloadLink (torrent: ITorrent): Promise<string> {
if (!torrent.link && this.config?.detail?.selectors?.link) {
const { data } = await this.request<any>(
merge(
Expand Down
Loading

0 comments on commit a310efe

Please sign in to comment.