release: 0.1.0

This commit is contained in:
Starcea 2024-06-27 23:57:01 +09:00
commit a2c51585b4
No known key found for this signature in database
GPG key ID: B7A77E32374911E1
18 changed files with 2276 additions and 0 deletions

19
.eslintrc.json Normal file
View file

@ -0,0 +1,19 @@
{
"env": {
"es2021": true
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"prettier"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": ["@typescript-eslint", "prettier"],
"rules": {
"prettier/prettier": "warn"
}
}

21
.github/workflows/ci.yml vendored Normal file
View file

@ -0,0 +1,21 @@
name: CI
on: [push, pull_request]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- name: Checkout branch
uses: actions/checkout@v4
- name: Setup pnpm
uses: pnpm/action-setup@v4
- name: Setup node.js 20
uses: actions/setup-node@v4
with:
node-version: 20
cache: 'pnpm'
- name: Install Dependencies
run: pnpm i --frozen-lockfile
- name: Run lint
run: pnpm run lint

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
node_modules
dist

10
.prettierrc.json Normal file
View file

@ -0,0 +1,10 @@
{
"semi": false,
"singleQuote": true,
"importOrderSeparation": true,
"importOrderSortSpecifiers": true,
"importOrderParserPlugins": ["typescript", "decorators-legacy"],
"plugins": ["@trivago/prettier-plugin-sort-imports"]
}

28
README.md Normal file
View file

@ -0,0 +1,28 @@
# comcigan.ts
[컴시간알리미](http://컴시간학생.kr)를 파싱하는 TypeScript 라이브러리입니다.
## 설치
```bash
npm install comcigan.ts # npm
yarn add comcigan.ts # yarn
pnpm add comcigan.ts # pnpm
```
## 사용법
```typescript
import Comcigan, { Weekday } from 'comcigan.ts'
const comcigan = new Comcigan()
const main = async () => {
const schools = await comcigan.searchSchool('학교 이름')
const timetable = await comcigan.getTimetable(schools[0].code)
console.log(timetable.getByDay(1, 2, Weekday.Monday)) // 1학년 2반 월요일 시간표
}
main()
```

38
package.json Normal file
View file

@ -0,0 +1,38 @@
{
"name": "comcigan.ts",
"version": "0.1.0",
"description": "A Comcigan parser written in TypeScript",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "rimraf dist && tsc",
"lint": "eslint src --ignore-path .gitignore"
},
"keywords": [
"comcigan",
"parser",
"typescript",
"school",
"korean"
],
"author": "Starcea <stardev.uwu@gmail.com>",
"license": "MIT",
"packageManager": "pnpm@9.4.0+sha512.f549b8a52c9d2b8536762f99c0722205efc5af913e77835dbccc3b0b0b2ca9e7dc8022b78062c17291c48e88749c70ce88eb5a74f1fa8c4bf5e18bb46c8bd83a",
"devDependencies": {
"@trivago/prettier-plugin-sort-imports": "^4.3.0",
"@types/node": "^20.14.9",
"@typescript-eslint/eslint-plugin": "^7.14.1",
"@typescript-eslint/parser": "^7.14.1",
"eslint": "^8.57.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-prettier": "^5.1.3",
"prettier": "^3.3.2",
"rimraf": "^5.0.7",
"ts-node": "^10.9.2",
"typescript": "^5.5.2"
},
"dependencies": {
"axios": "^1.7.2",
"iconv-lite": "^0.6.3"
}
}

1839
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load diff

68
src/client.ts Normal file
View file

@ -0,0 +1,68 @@
import { BASE_URL, USER_AGENT } from './constants'
import DataManager from './data'
import type { School } from './models/School'
import type { Timetable } from './models/Timetable'
import { TimetableManager } from './models/Timetable'
import { encodeBase64, encodeEUCKR } from './utils/encode'
import { log10int } from './utils/math'
import { parseResponse } from './utils/parse'
import axios from 'axios'
export default class Comcigan {
private readonly rest = axios.create({
baseURL: BASE_URL,
headers: {
'User-Agent': USER_AGENT,
},
})
private readonly dataManager = new DataManager(this.rest)
async searchSchools(schoolName: string): Promise<School[]> {
const { mainRoute, searchRoute } = await this.dataManager.getData()
const res = await this.rest.get(
`${mainRoute}?${searchRoute}l${encodeEUCKR(schoolName)}`,
)
const { 학교검색: data } = parseResponse<{
: [number, string, string, number][]
}>(res.data)
return data.map(([regionCode, regionName, schoolName, schoolCode]) => ({
code: schoolCode,
name: schoolName,
region: { code: regionCode, name: regionName },
}))
}
async getRawTimetable(schoolCode: number): Promise<Timetable[][][][]> {
const { mainRoute, timetableRoute, teacherCode, dayCode, subjectCode } =
await this.dataManager.getData()
const res = await this.rest.get(
`${mainRoute}_T?${encodeBase64(`${timetableRoute}_${schoolCode}_0_1`)}`,
)
const data = parseResponse(res.data)
const teachers = data[`자료${teacherCode}`] as string[]
const teachersLen = log10int(teachers.length - 1) + 1
const subjects = data[`자료${subjectCode}`] as string[]
return (data[`자료${dayCode}`] as number[][][][]).slice(1).map((grade) =>
grade.slice(1).map((cls) =>
cls.slice(1).map((day) =>
day.slice(1).map((period) => {
const p = period.toString()
return {
subject: subjects[Number(p.slice(0, p.length - teachersLen - 1))],
teacher: teachers[Number(p.slice(-teachersLen))],
}
}),
),
),
)
}
async getTimetable(schoolCode: number) {
return new TimetableManager(await this.getRawTimetable(schoolCode))
}
}

22
src/constants.ts Normal file
View file

@ -0,0 +1,22 @@
export const BASE_URL = 'http://comci.net:4082'
export const USER_AGENT =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36'
export const RegExes = {
MainRoute: /(?<=\.\/)\d+(?=\?\d+l)/,
SearchRoute: /(?<=\?)\d+(?=l)/,
TimetableRoute: /(?<=')\d+(?=_')/,
TeacherCode: /(?<=성명=자료\.자료)\d+/,
DayCode: /(?<=일일자료=Q자료\(자료.자료)\d+/,
SubjectCode: /(?<=자료.자료)\d+(?=\[sb\])/,
WhiteSpace: /\0+$/,
}
export enum Weekday {
Monday = 1,
Tuesday,
Wednesday,
Thursday,
Friday,
}

64
src/data.ts Normal file
View file

@ -0,0 +1,64 @@
import { RegExes } from './constants'
import type { AxiosInstance } from 'axios'
import { decode } from 'iconv-lite'
interface Data {
mainRoute: string
searchRoute: string
timetableRoute: string
teacherCode: string
dayCode: string
subjectCode: string
}
export default class DataManager {
private _data: Data | null = null
private _lastFetch = 0
constructor(private readonly rest: AxiosInstance) {}
private async fetchData(): Promise<Data> {
const res = await this.rest.get('/st', {
responseType: 'arraybuffer',
})
const data = decode(Buffer.from(res.data), 'euc-kr')
const main = RegExes.MainRoute.exec(data)
if (!main) throw new Error('Failed to fetch main route')
const search = RegExes.SearchRoute.exec(data)
if (!search) throw new Error('Failed to fetch search route')
const timetable = RegExes.TimetableRoute.exec(data)
if (!timetable) throw new Error('Failed to fetch timetable route')
const teacher = RegExes.TeacherCode.exec(data)
if (!teacher) throw new Error('Failed to fetch teacher code')
const day = RegExes.DayCode.exec(data)
if (!day) throw new Error('Failed to fetch day code')
const subject = RegExes.SubjectCode.exec(data)
if (!subject) throw new Error('Failed to fetch subject code')
this._lastFetch = Date.now()
this._data = {
mainRoute: main[0],
searchRoute: search[0],
timetableRoute: timetable[0],
teacherCode: teacher[0],
dayCode: day[0],
subjectCode: subject[0],
}
return this._data
}
async getData() {
if (this._data && Date.now() - this._lastFetch < 1000 * 60 * 60)
return this._data
return this.fetchData()
}
}

8
src/index.ts Normal file
View file

@ -0,0 +1,8 @@
import Comcigan from './client'
export default Comcigan
export * from './models/Region'
export * from './models/School'
export * from './models/Timetable'
export { Weekday } from './constants'

6
src/models/Region.ts Normal file
View file

@ -0,0 +1,6 @@
export interface Region {
/** 지역 코드 // TODO: 지역 코드가 아닌 것으로 보임 */
code: number
/** 지역 이름 */
name: string
}

10
src/models/School.ts Normal file
View file

@ -0,0 +1,10 @@
import type { Region } from './Region'
export interface School {
/** 학교 코드 */
code: number
/** 학교 이름 */
name: string
/** 학교 지역 */
region: Region
}

24
src/models/Timetable.ts Normal file
View file

@ -0,0 +1,24 @@
export interface Timetable {
subject: string
teacher: string
}
export class TimetableManager {
constructor(private readonly timetables: Timetable[][][][]) {}
getByGrade(grade: number) {
return this.timetables[grade - 1]
}
getByClass(grade: number, cls: number) {
return this.timetables[grade - 1][cls - 1]
}
getByDay(grade: number, cls: number, day: number) {
return this.timetables[grade - 1][cls - 1][day - 1]
}
getByPeriod(grade: number, cls: number, day: number, period: number) {
return this.timetables[grade - 1][cls - 1][day - 1][period - 1]
}
}

6
src/utils/encode.ts Normal file
View file

@ -0,0 +1,6 @@
import { encode } from 'iconv-lite'
export const encodeEUCKR = (str: string) =>
[...encode(str, 'euc-kr')].map((v) => '%' + v.toString(16)).join('')
export const encodeBase64 = (str: string) => Buffer.from(str).toString('base64')

1
src/utils/math.ts Normal file
View file

@ -0,0 +1 @@
export const log10int = (n: number) => Math.floor(Math.log10(n))

5
src/utils/parse.ts Normal file
View file

@ -0,0 +1,5 @@
import { RegExes } from '../constants'
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const parseResponse = <T = any>(str: string): T =>
JSON.parse(str.replace(RegExes.WhiteSpace, ''))

105
tsconfig.json Normal file
View file

@ -0,0 +1,105 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "ES2021" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
"experimentalDecorators": true /* Enable experimental support for TC39 stage 2 draft decorators. */,
"emitDecoratorMetadata": true /* Emit design-type metadata for decorated declarations in source files. */,
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs" /* Specify what module code is generated. */,
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
"declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
"outDir": "./dist" /* Specify an output folder for all emitted files. */,
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
/* Type Checking */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}