Easy Pages

这个提交包含在:
2025-03-18 22:14:01 +08:00
当前提交 3b7103fb34
共有 12 个文件被更改,包括 2260 次插入 和 0 次删除

5
.gitignore vendored 普通文件
查看文件

@ -0,0 +1,5 @@
dist
node_modules
tsconfig.tsbuildinfo
config.json

26
package.json 普通文件
查看文件

@ -0,0 +1,26 @@
{
"name": "jamadeamon",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"@types/express": "^5.0.0",
"@types/jsonwebtoken": "^9.0.9",
"@types/vhost": "^3.0.9",
"axios": "^1.8.3",
"body-parser": "^1.20.3",
"bull": "^4.16.5",
"cookie-session": "^2.1.0",
"dotenv": "^16.4.7",
"express": "^4.21.2",
"jsonwebtoken": "^9.0.2",
"passport": "^0.7.0",
"simple-git": "^3.27.0",
"sqlite": "^5.1.1",
"sqlite3": "^5.1.7",
"vhost": "^3.0.2"
},
"scripts": {
"build":"tsc --build"
}
}

13
src/config.ts 普通文件
查看文件

@ -0,0 +1,13 @@
export var Config = {
listen:{
host:"",
port:9898,
rooturl:"http://10.70.105.196:9898",
serverurl:"*.jamaccao.cn"
},
GiteaURL:"http://www.jamaccao.cn:3000",
OAuth:{
CLIENT_ID:"",
CLIENT_SERECT:""
}
}

18
src/index.ts 普通文件
查看文件

@ -0,0 +1,18 @@
import { json } from 'body-parser';
import express from 'express';
import Webhook from './routes/webhook';
import Auth, { au } from './routes/auth';
import { Config } from './config';
import Pages from './routes/pages';
import {InittDB } from './services/database';
const GiteaDeamon = express();
InittDB()
GiteaDeamon.use(json());
GiteaDeamon.use(Webhook)
GiteaDeamon.use(Auth)
GiteaDeamon.use(Pages)
GiteaDeamon.listen(Config.listen.port)
console.log(au)

102
src/interfaces/gitea.d.ts vendored 普通文件
查看文件

@ -0,0 +1,102 @@
declare interface GiteaUser{
"id": number,
"login": string,
"login_name": "",
"source_id": number,
"full_name": string,
"email": string,
"avatar_url": string,
"html_url": string,
"language": string,
"is_admin": boolean,
"last_login": string,
"created": string,
"restricted": boolean,
"active": boolean,
"prohibit_login": boolean,
"location": string,
"website": string,
"description": string,
"visibility": "public"|"private",
"followers_count": number,
"following_count": number,
"starred_repos_count": number,
"username": string
}
declare interface GitUser{
name:string,
email:string,
username:string
}
declare type timestamp = string
declare interface Repository {
"id": number,
"owner": GiteaUser,
"name": string,
"full_name": string,
"description": string,
"empty": boolean,
"private": boolean,
"fork": boolean,
"template": boolean,
"parent": Repository | null,
"mirror": boolean,
"size": number,
"language": "",
"languages_url": string,
"html_url": string,
"url": string,
"link": "",
"ssh_url": string,
"clone_url": string,
"original_url": "",
"website": "",
"stars_count": number,
"forks_count": number,
"watchers_count": number,
"open_issues_count": number,
"open_pr_counter": number,
"release_counter": number,
"default_branch": string,
"archived": boolean,
"created_at": timestamp,
"updated_at": timestamp,
"archived_at": timestamp,
"permissions": {
"admin": boolean,
"push": boolean,
"pull": boolean
},
"has_issues": boolean,
"internal_tracker": {
"enable_time_tracker": boolean,
"allow_only_contributors_to_track_time": boolean,
"enable_issue_dependencies": boolean
},
"has_wiki": boolean,
"has_pull_requests": boolean,
"has_projects": boolean,
"projects_mode": "all",
"has_releases": boolean,
"has_packages": boolean,
"has_actions": boolean,
"ignore_whitespace_conflicts": boolean,
"allow_merge_commits": boolean,
"allow_rebase": boolean,
"allow_rebase_explicit": boolean,
"allow_squash_merge": boolean,
"allow_fast_forward_only_merge": boolean,
"allow_rebase_update": boolean,
"default_delete_branch_after_merge": boolean,
"default_merge_style": "merge"|"rebase",
"default_allow_maintainer_edit": boolean,
"avatar_url": string,
"internal": boolean,
"mirror_interval": "",
"object_format_name": "sha1",
"mirror_updated": timestamp,
"repo_transfer": null
}

56
src/routes/auth.ts 普通文件
查看文件

@ -0,0 +1,56 @@
import { Router } from "express";
import { Config } from "../config";
const Auth = Router();
export default Auth;
// https://[YOUR-GITEA-URL]/login/oauth/authorize?client_id=CLIENT_ID&redirect_uri=REDIRECT_URI& response_type=code&state=STATE
// https://[REDIRECT_URI]?code=RETURNED_CODE&state=STATE
// POST https://[YOUR-GITEA-URL]/login/oauth/access_token
export var au = `${Config.GiteaURL}/login/oauth/authorize?client_id=${Config.OAuth.CLIENT_ID}&redirect_uri=${Config.listen.rooturl}/auth&response_type=code&state=1`
export var access_token = ""
interface OAuth{
code:string,
state:number
}
interface OAuthResponse{
access_token:string,
refresh_token:string,
token_type:string,
expires_in:number
}
Auth.get('/auth',(req,res)=>{
const query = req.query as any as OAuth;
fetch(`${Config.GiteaURL}/login/oauth/access_token`,{
headers:{
"Content-Type":"application/json",
},
body:JSON.stringify({
"client_id": Config.OAuth.CLIENT_ID,
"client_secret": Config.OAuth.CLIENT_SERECT,
"code": query.code,
"grant_type": "authorization_code",
"redirect_uri": `${Config.listen.rooturl}/auth`
}),
method:"post"
}).then((AccessTokenResult)=>{
AccessTokenResult.json().then((OAuthResult:OAuthResponse)=>{
access_token = OAuthResult.access_token;
fetch(`${Config.GiteaURL}/api/v1/user/repos?token=${OAuthResult.access_token}`,{
method:"get"
}).then((RepoGetHandle)=>{
RepoGetHandle.json().then((RepoGetResponse:Repository[])=>{
console.log(RepoGetResponse)
res.status(200).send(JSON.stringify(RepoGetResponse)).end();
})
})
console.log(OAuthResult);
})
})
})

15
src/routes/pages.ts 普通文件
查看文件

@ -0,0 +1,15 @@
import express, { Router } from "express";
import vhost from "vhost";
import { Config } from "../config";
import { DataBase } from "../services/database";
import path from 'path'
const Pages = Router();
// Pages.use(vhost(Config.listen.serverurl,(req,res,next)=>{
// var s = DataBase.get(req.vhost[0]);
// (express.static(s?s:"404"))(req,res as any,next)
// }))
Pages.use(express.static(path.join("git","test")));
export default Pages;

30
src/routes/webhook.ts 普通文件
查看文件

@ -0,0 +1,30 @@
interface GiteaWebhook{
ref:string,
before:string,
after:string,
compare_url:string,
commits:{
id:string,
message:string,
url:string,
author:GitUser,
committer:GitUser,
timestamp:string
}[],
repository:Repository,
pusher:GiteaUser,
sender:GiteaUser
}
import { Router } from "express";
import { pull } from "../services/git";
import { access_token } from "./auth";
const Webhook = Router();
Webhook.post('/webhook',(req,res)=>{
var data = req.body as GiteaWebhook;
console.log(data)
res.status(200).json({errcode:0,errmsg:'ok'}).end()
pull("test",data.repository.clone_url,access_token)
})
export default Webhook;

19
src/services/database.ts 普通文件
查看文件

@ -0,0 +1,19 @@
import { existsSync,readFileSync,writeFileSync } from "fs";
import path from "path";
interface KV{
[K:string]:string|undefined
}
var file = path.join("database.json")
export var DataBase:KV;
export var InittDB = (()=>{
if(!existsSync(file)){
writeFileSync(file,JSON.stringify({}))
}
DataBase = JSON.parse(readFileSync(file).toString())
});
export var ExportDB = (()=>{
writeFileSync(file,JSON.stringify(DataBase))
})

31
src/services/git.ts 普通文件
查看文件

@ -0,0 +1,31 @@
import simpleGit from "simple-git";
import * as fs from 'fs'
import path from "path";
export var pull = ((name:string,url:string,token:string)=>{
console.log(`开始pull repo ${name} in ${url}`)
if(!fs.existsSync(path.join("git"))){
fs.mkdirSync(path.join("git"))
}
var p = path.join("git",name);
var exist = fs.existsSync(p);
if(!exist){
fs.mkdirSync(p)
}
var git = simpleGit(p)
console.log(`git载入完毕`)
if(!exist){
git.clone(url.replace("://",`://oauth2:${token}@`)).then((v)=>{
console.log("clone successfully")
}).catch((err)=>{
console.log(err)
})
}else{
git.pull(url.replace("://",`://oauth2:${token}@`)).then((v)=>{
console.log("pull successfully")
}).catch((err)=>{
console.log(err)
})
}
})

111
tsconfig.json 普通文件
查看文件

@ -0,0 +1,111 @@
{
"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": "es2016", /* 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 legacy experimental 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": "./src", /* Specify the root folder within your source files. */
// "moduleResolution": "node10", /* 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. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "noUncheckedSideEffectImports": true, /* Check side effect imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "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. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "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. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "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. */
// "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. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
// "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. */
// "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
// "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. */
}
}

1834
yarn.lock 普通文件

文件差异内容过多而无法显示 加载差异