Commit 5afbc854 authored by nanahira's avatar nanahira

first

parent b9a60ea4
webpack.config.js
dist/*
build/*
\ No newline at end of file
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
/build
/output
/dest
/config.yaml
.idea
stages:
- build
- deploy
variables:
GIT_DEPTH: "1"
build:
stage: build
tags:
- linux
script:
- npm ci
- npm run build
artifacts:
paths:
- dist/
upload_to_minio:
stage: deploy
dependencies:
- build
tags:
- linux
script:
- aws s3 --endpoint=https://minio.mycard.moe:9000 sync --delete dist/ s3://nanahira/koishi-plugin/hisoutensoku-jammer
only:
- master
deploy_npm:
stage: deploy
dependencies:
- build
tags:
- linux
script:
- apt update;apt -y install coreutils
- echo $NPMRC | base64 --decode > ~/.npmrc
- npm publish . || true
only:
- master
/install-npm.sh
.git*
/output
/dest
/config.yaml
.idea
.dockerignore
Dockerfile
/src
.eslintrc.js
.prettierrc
webpack.config.js
tsconfig.json
\ No newline at end of file
{
"singleQuote": true,
"trailingComma": "all"
}
\ No newline at end of file
The MIT License (MIT)
Copyright (c) 2021 Nanahira
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
#!/bin/bash
npm install --save \
source-map-support
npm install --save-dev \
@types/node \
typescript \
'@typescript-eslint/eslint-plugin@^4.28.2' \
'@typescript-eslint/parser@^4.28.2 '\
'eslint@^7.30.0' \
'eslint-config-prettier@^8.3.0' \
'eslint-plugin-prettier@^3.4.0' \
prettier \
raw-loader \
ts-loader \
webpack \
webpack-cli \
koishi@^4.0.0-alpha.9
This diff is collapsed.
{
"name": "koishi-plugin-ygocard",
"version": "1.0.0",
"description": "Koishi Plugin for YGOPro card query",
"main": "dist/index.js",
"scripts": {
"lint": "eslint --fix .",
"build": "webpack"
},
"repository": {
"type": "git",
"url": "https://code.mycard.moe/3rdeye/koishi-plugin-ygocard.git"
},
"author": "Nanahira <nanahira@momobako.com>",
"license": "MIT",
"keywords": [
"Koishi.js",
"qqbot",
"cqhttp",
"onebot"
],
"bugs": {
"url": "https://code.mycard.moe/3rdeye/koishi-plugin-ygocard/issues"
},
"homepage": "https://code.mycard.moe/3rdeye/koishi-plugin-ygocard",
"dependencies": {
"source-map-support": "^0.5.20"
},
"devDependencies": {
"@types/better-sqlite3": "^7.4.0",
"@types/lodash": "^4.14.175",
"@types/mustache": "^4.1.2",
"@types/node": "^16.11.1",
"@typescript-eslint/eslint-plugin": "^4.33.0",
"@typescript-eslint/parser": "^4.33.0",
"better-sqlite3": "^7.4.3",
"class-transformer": "^0.4.0",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^3.4.1",
"koishi": "^4.0.0-alpha.9",
"koishi-utils-schemagen": "^1.0.7",
"leven": "3.1",
"lodash": "^4.17.21",
"mustache": "^4.2.0",
"prettier": "^2.4.1",
"raw-loader": "^4.0.2",
"ts-loader": "^9.2.6",
"typescript": "^4.4.4",
"webpack": "^5.58.2",
"webpack-cli": "^4.9.0"
}
}
import { segment } from 'koishi';
import { CardInfoService } from './card-info.service';
import { YGOCardConfig } from './config';
import leven from 'leven';
const cardInfoService = new CardInfoService();
const attrOffset = 1010;
const raceOffset = 1020;
const typeOffset = 1050;
const ygoproConstants = {
TYPES: {
TYPE_MONSTER: 1,
TYPE_SPELL: 2,
TYPE_TRAP: 4,
TYPE_NORMAL: 16,
TYPE_EFFECT: 32,
TYPE_FUSION: 64,
TYPE_RITUAL: 128,
TYPE_TRAPMONSTER: 256,
TYPE_SPIRIT: 512,
TYPE_UNION: 1024,
TYPE_DUAL: 2048,
TYPE_TUNER: 4096,
TYPE_SYNCHRO: 8192,
TYPE_TOKEN: 16384,
TYPE_QUICKPLAY: 65536,
TYPE_CONTINUOUS: 131072,
TYPE_EQUIP: 262144,
TYPE_FIELD: 524288,
TYPE_COUNTER: 1048576,
TYPE_FLIP: 2097152,
TYPE_TOON: 4194304,
TYPE_XYZ: 8388608,
TYPE_PENDULUM: 16777216,
TYPE_SPSUMMON: 33554432,
TYPE_LINK: 67108864,
},
LINK_MARKERS: {
LINK_MARKER_BOTTOM_LEFT: 1,
LINK_MARKER_BOTTOM: 2,
LINK_MARKER_BOTTOM_RIGHT: 4,
LINK_MARKER_LEFT: 8,
LINK_MARKER_RIGHT: 32,
LINK_MARKER_TOP_LEFT: 64,
LINK_MARKER_TOP: 128,
LINK_MARKER_TOP_RIGHT: 256,
},
};
export interface YGOProCardLike {
id: number;
name: string;
desc: string;
ot: number;
alias: number;
setcode: number;
type: number;
atk: number;
def: number;
level: number;
race: number;
attribute: number;
category: number;
}
export interface YGOProCardView extends YGOProCardLike {
cardLScale: number;
cardRScale: number;
displayAtk: string;
displayDef: string;
displayRace: string;
displayAttribute: string;
displayType: string;
linkMarkers: string;
}
function getStatusValue(s: number) {
if (s >= 0) {
return s.toString();
} else {
return '?';
}
}
export class YGOProCard implements YGOProCardLike {
id: number;
name: string;
desc: string;
ot: number;
alias: number;
setcode: number;
type: number;
atk: number;
def: number;
level: number;
race: number;
attribute: number;
category: number;
getIdAndName() {
return `${this.name}[${this.id}]`;
}
isType(type: keyof typeof ygoproConstants.TYPES) {
return !!(this.type & ygoproConstants.TYPES[type]);
}
getView(lang: 'cn' | 'en'): Partial<YGOProCardView> {
const result: Partial<YGOProCardView> = {};
result.id = this.id;
result.name = this.name;
result.desc = this.desc;
result.ot = this.ot;
result.alias = this.alias;
result.setcode = this.setcode;
result.atk = this.atk;
result.def = this.def;
result.type = this.type;
result.race = this.race;
result.attribute = this.attribute;
result.category = this.category;
if (this.level <= 12) {
result.level = this.level;
} else {
//转化为16位,0x01010004,前2位是左刻度,2-4是右刻度,末2位是等级
const levelHex = this.level;
const cardLevel = levelHex & 0xff;
const cardLScale = (levelHex >> 6) & 0xff;
const cardRScale = (levelHex >> 4) & 0xff;
result.level = cardLevel;
result.cardLScale = cardLScale;
result.cardRScale = cardRScale;
}
result.displayAtk = getStatusValue(this.atk);
if (!(this.type & ygoproConstants.TYPES.TYPE_LINK)) {
result.displayDef = getStatusValue(this.def);
} else {
// result.name+="[LINK-" + cardLevel + "]";
// result.name += " " + (result.atk < 0 ? "?" : result.atk) + "/- ";
result.linkMarkers = '';
if (result.def & ygoproConstants.LINK_MARKERS.LINK_MARKER_TOP_LEFT)
result.linkMarkers += '[↖]';
if (result.def & ygoproConstants.LINK_MARKERS.LINK_MARKER_TOP)
result.linkMarkers += '[↑]';
if (result.def & ygoproConstants.LINK_MARKERS.LINK_MARKER_TOP_RIGHT)
result.linkMarkers += '[↗]';
if (result.def & ygoproConstants.LINK_MARKERS.LINK_MARKER_LEFT)
result.linkMarkers += '[←]';
if (result.def & ygoproConstants.LINK_MARKERS.LINK_MARKER_RIGHT)
result.linkMarkers += '[→]';
if (result.def & ygoproConstants.LINK_MARKERS.LINK_MARKER_BOTTOM_LEFT)
result.linkMarkers += '[↙]';
if (result.def & ygoproConstants.LINK_MARKERS.LINK_MARKER_BOTTOM)
result.linkMarkers += '[↓]';
if (result.def & ygoproConstants.LINK_MARKERS.LINK_MARKER_BOTTOM_RIGHT)
result.linkMarkers += '[↘]';
result.displayDef = '-';
}
result.displayType = cardInfoService.getStringValueByMysticalNumber(
lang,
typeOffset,
this.type,
);
result.displayRace = cardInfoService.getStringValueByMysticalNumber(
lang,
raceOffset,
this.race,
);
result.displayAttribute = cardInfoService.getStringValueByMysticalNumber(
lang,
attrOffset,
this.attribute,
);
return result;
}
getDisplayString(config: YGOCardConfig) {
const view = this.getView(config.lang);
const lines = [
segment('image', { url: config.renderUrl(view), cache: true }),
`${view.name}[${view.id}]`,
];
const isMonster = this.isType('TYPE_MONSTER');
let typeString = `[${view.displayType}]`;
if (isMonster) {
typeString += ` ${view.displayRace}/${view.displayAttribute}`;
}
lines.push(typeString);
if (isMonster) {
const starString = this.isType('TYPE_XYZ')
? '\u2606'
: this.isType('TYPE_LINK')
? 'LINK-'
: '\u2605';
let monsterStatus = `[${starString}${view.level}] ${view.displayAtk}/${view.displayDef}`;
if (this.isType('TYPE_PENDULUM')) {
monsterStatus += ` ${view.cardLScale}/${view.cardRScale}`;
}
if (this.isType('TYPE_LINK')) {
monsterStatus += ` ${view.linkMarkers}`;
}
lines.push(monsterStatus);
}
lines.push('');
lines.push(view.desc);
return lines.join('\n');
}
getDistanceFrom(value: string) {
if (parseInt(value) === this.id) {
return 1;
} else if (this.name.includes(value)) {
return leven(value, this.name) + 2;
} else {
return (leven(value, this.desc) + 2) << 16;
}
}
}
export class CardInfoService {
private cardInfo = {
cn: {
'1010': '',
'1011': '',
'1012': '',
'1013': '',
'1014': '',
'1015': '',
'1016': '',
'1020': '战士',
'1021': '魔法师',
'1022': '天使',
'1023': '恶魔',
'1024': '不死',
'1025': '机械',
'1026': '',
'1027': '',
'1028': '岩石',
'1029': '鸟兽',
'1030': '植物',
'1031': '昆虫',
'1032': '',
'1033': '',
'1034': '',
'1035': '兽战士',
'1036': '恐龙',
'1037': '',
'1038': '海龙',
'1039': '爬虫',
'1040': '念动力',
'1041': '幻神兽',
'1042': '创造神',
'1043': '幻龙',
'1044': '电子界',
'1050': '怪兽',
'1051': '魔法',
'1052': '陷阱',
'1053': '???',
'1054': '通常',
'1055': '效果',
'1056': '融合',
'1057': '仪式',
'1058': '陷阱怪兽',
'1059': '灵魂',
'1060': '同盟',
'1061': '二重',
'1062': '调整',
'1063': '同调',
'1064': '衍生物',
'1065': '???',
'1066': '速攻',
'1067': '永续',
'1068': '装备',
'1069': '场地',
'1070': '反击',
'1071': '反转',
'1072': '卡通',
'1073': '超量',
'1074': '灵摆',
'1075': '特殊召唤',
'1076': '连接',
},
en: {
'1010': 'EARTH',
'1011': 'WATER',
'1012': 'FIRE',
'1013': 'WIND',
'1014': 'LIGHT',
'1015': 'DARK',
'1016': 'DIVINE',
'1020': 'Warrior',
'1021': 'Spellcaster',
'1022': 'Fairy',
'1023': 'Fiend',
'1024': 'Zombie',
'1025': 'Machine',
'1026': 'Aqua',
'1027': 'Pyro',
'1028': 'Rock',
'1029': 'Winged Beast',
'1030': 'Plant',
'1031': 'Insect',
'1032': 'Thunder',
'1033': 'Dragon',
'1034': 'Beast',
'1035': 'Beast-Warrior',
'1036': 'Dinosaur',
'1037': 'Fish',
'1038': 'Sea Serpent',
'1039': 'Reptile',
'1040': 'Psychic',
'1041': 'Divine-Beast',
'1042': 'Creator God',
'1043': 'Wyrm',
'1044': 'Cyberse',
'1050': 'Monster',
'1051': 'Spell',
'1052': 'Trap',
'1053': '???',
'1054': 'Normal',
'1055': 'Effect',
'1056': 'Fusion',
'1057': 'Ritual',
'1058': 'Trap Monster',
'1059': 'Spirit',
'1060': 'Union',
'1061': 'Gemini',
'1062': 'Tuner',
'1063': 'Synchro',
'1064': 'Token',
'1065': '???',
'1066': 'Quick-Play',
'1067': 'Continuous',
'1068': 'Equip',
'1069': 'Field',
'1070': 'Counter',
'1071': 'Flip',
'1072': 'Toon',
'1073': 'Xyz',
'1074': 'Pendulum',
'1075': 'Special Summon',
'1076': 'Link',
},
};
getStringValueByMysticalNumber(
lang: 'cn' | 'en',
offset: number,
num: number,
): string {
const results: string[] = [];
for (let i = 0; i < 32; i++) {
if (num & (1 << i)) {
const index = offset + i;
const key = index.toString();
results.push(this.cardInfo[lang][key] || index);
}
}
return results.join('|');
}
}
import { DefineSchema, UseSchema } from 'koishi-utils-schemagen';
import { Schema } from 'koishi';
import { YGOProCardLike } from './YGOProCard';
import _ from 'lodash';
import { renderTemplate } from './utility';
export class YGOCardConfig {
@DefineSchema({ type: 'string', desc: '命令名', default: 'card' })
commandName: string;
@DefineSchema({
type: 'string',
array: true,
default: ['./cdb'],
desc: '数据库文件的路径',
})
databasePaths: string[];
@DefineSchema({ type: 'number', default: 100, desc: '查询最多显示的数量' })
matchCount: number;
@UseSchema(Schema.select(['cn', 'en'], '显示语言').default('cn'))
lang: 'cn' | 'en';
@DefineSchema({
type: 'string',
desc: '卡图源,将 {{id}} 替换为卡号',
default:
'https://cdn02.moecube.com:444/images/ygopro-images-zh-CN/{{id}}.jpg',
})
picUrl: string;
renderUrl(obj: Partial<YGOProCardLike>) {
return renderTemplate(
this.picUrl,
_.mapValues(obj, (s) => encodeURIComponent(s)),
);
}
}
import 'source-map-support/register';
import { Context } from 'koishi';
import { Config, MyPlugin } from './plugin';
export { Config } from './plugin';
export const name = 'ygocard';
const plugin = new MyPlugin();
export const schema = plugin.schema;
export function apply(ctx: Context, config: Config) {
ctx.plugin(plugin, config);
}
import 'source-map-support/register';
import { Context, Schema } from 'koishi';
import { YGOCardConfig } from './config';
import { schemaFromClass, schemaTransform } from 'koishi-utils-schemagen';
import sqlite, { Database } from 'better-sqlite3';
import { promises as fs } from 'fs';
import _ from 'lodash';
import { YGOProCard } from './YGOProCard';
import { plainToClass } from 'class-transformer';
import path from 'path';
export type Config = Partial<YGOCardConfig>;
export class MyPlugin {
private config: YGOCardConfig;
private ctx: Context;
private dbs: Database[] = [];
name = 'ygocard-main';
schema: Schema<Config> = schemaFromClass(YGOCardConfig);
private queryInDB(value: string, db: Database) {
const possibleValueNumber = parseInt(value) || 0;
const statement = db.prepare<[number, string, string]>(
"select datas.*,texts.name,texts.desc from datas,texts where datas.id = texts.id and datas.type & 0x4000 = 0 and (datas.alias = 0 or datas.id - datas.alias > 10) and (datas.id = ? or texts.name like ('%' || ? || '%') or texts.desc like ('%' || ? || '%'))",
);
return statement
.all(possibleValueNumber, value, value)
.map((obj) => plainToClass(YGOProCard, obj));
}
private queryInAllDBs(value: string, matchCount?: number) {
return _.sortBy(
_.uniqBy(
_.flatten(this.dbs.map((db) => this.queryInDB(value, db))),
(c) => c.id,
),
(c) => c.getDistanceFrom(value),
).slice(0, matchCount || this.config.matchCount);
}
private async loadDBs() {
const allDatabaseFiles = _.flatten(
await Promise.all(
this.config.databasePaths.map(async (p) =>
(await fs.readdir(p))
.filter((f) => f.endsWith('.cdb'))
.map((f) => path.join(p, f)),
),
),
);
this.ctx
.logger('ygocard')
.info(`Will load cards from ${allDatabaseFiles.length} databases.`);
this.dbs = allDatabaseFiles.map((dbFile) =>
sqlite(dbFile, {
readonly: true,
fileMustExist: true,
}),
);
}
async apply(ctx: Context, config: Config) {
this.ctx = ctx;
this.config = schemaTransform(YGOCardConfig, config);
await this.loadDBs();
ctx
.command(
`${this.config.commandName} <cardQuery:string>`,
'查询 YGOPro 卡片',
)
.option('count', '-c <count:posint>', {
fallback: this.config.matchCount,
})
.usage(`使用 ${this.config.commandName} 卡号或关键词 搜索卡片。`)
.example(
`${this.config.commandName} 10000 搜索卡号为 10000 的卡片。 ${this.config.commandName} 青眼白龙 搜索卡名或描述中包含『青眼白龙』的卡片。`,
)
.action(async ({ session, options }, value) => {
const cards = this.queryInAllDBs(value, options.count);
if (!cards.length) {
return `没有找到卡片 ${value} 。`;
}
if (cards.length === 1) {
return cards[0].getDisplayString(this.config);
}
await session.send(
`卡片 ${value} 匹配下列结果:\n--------------------\n${cards
.map((c, i) => `${i + 1}\t${c.getIdAndName()}`)
.join(
'\n',
)}\n--------------------\n输入编号或卡片密码查询对应的卡片。`,
);
const reply = await session.prompt();
if (!reply) {
return;
}
const replyNumber = parseInt(reply);
const card =
cards[replyNumber - 1] ||
cards.find((c) => c.id === replyNumber) ||
cards.find((c) => c.name === value) ||
cards.find((c) => c.name.includes(value)) ||
cards.find((c) => c.desc.includes(value));
if (!card) {
return '没有找到卡片。';
}
return card.getDisplayString(this.config);
});
}
}
import Mustache from 'mustache';
export function renderTemplate(template: string, view: any) {
return Mustache.render(template, view, null, { escape: (v) => v });
}
{
"compilerOptions": {
"outDir": "dist",
"module": "commonjs",
"target": "es2021",
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"declaration": true,
"sourceMap": true
},
"compileOnSave": true,
"allowJs": true,
"include": [
"*.ts",
"src/**/*.ts"
]
}
const path = require('path');
module.exports = {
entry: './src/index.ts',
mode: 'production',
target: 'node',
devtool: 'source-map',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
{ test: /\.mustache$/, use: 'raw-loader' },
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
output: {
filename: 'index.js',
library: {
type: 'commonjs',
},
path: path.resolve(__dirname, 'dist'),
},
externals: {
koishi: 'koishi',
'better-sqlite3': 'better-sqlite3',
},
};
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment