Skip to content

Commit

Permalink
Merge pull request #642 from 2anki/refactor/code-smells
Browse files Browse the repository at this point in the history
enable: eslint action
  • Loading branch information
aalemayhu authored May 22, 2022
2 parents b1ffc62 + 89b576a commit 96bc7e4
Show file tree
Hide file tree
Showing 243 changed files with 11,762 additions and 8,217 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ jobs:
- name: npm run lint
run: |
npm --prefix server install
echo npm --prefix server run lint
npm --prefix server run lint
env:
CI: true
18 changes: 18 additions & 0 deletions server/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: ['airbnb-typescript', 'prettier'],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
project: './tsconfig.json',
},
plugins: ['import', '@typescript-eslint', 'prettier'],
rules: {
'react/jsx-filename-extension': 'off',
'prettier/prettier': ['error'],
},
};
4 changes: 4 additions & 0 deletions server/.husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx pretty-quick --staged
4 changes: 4 additions & 0 deletions server/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"singleQuote": true,
"printWidth": 80
}
10 changes: 5 additions & 5 deletions server/KnexConfig.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { Knex } from "knex";
import { Knex } from 'knex';

const KnexConfig: Knex.Config = {
client: "pg",
client: 'pg',
connection:
process.env.DATABASE_URL || "postgresql://aa:focaccia@localhost:5432/n",
process.env.DATABASE_URL || 'postgresql://aa:focaccia@localhost:5432/n',
pool: {
min: 2,
max: 10,
},
migrations: {
tableName: "knex_migrations",
directory: process.env.MIGRATIONS_DIR || "migrations",
tableName: 'knex_migrations',
directory: process.env.MIGRATIONS_DIR || 'migrations',
},
};

Expand Down
4 changes: 2 additions & 2 deletions server/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
modulePathIgnorePatterns: ["<rootDir>/test/"]
};
modulePathIgnorePatterns: ['<rootDir>/test/'],
};
11 changes: 6 additions & 5 deletions server/lib/CrashReporter.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import * as Sentry from "@sentry/node";
import * as Tracing from "@sentry/tracing";
import express from "express";
import { Express } from "express-serve-static-core";
import * as Sentry from '@sentry/node';
import * as Tracing from '@sentry/tracing';
import express from 'express';
import { Express } from 'express-serve-static-core';

export default class CrashReporter {
static AddErrorHandler(app: Express) {
app.use(Sentry.Handlers.errorHandler());
}

static Configure(app: express.Application) {
Sentry.init({
dsn: "https://067ae1c6d7c847278d84a7bbd12515ec@o404766.ingest.sentry.io/5965064",
dsn: 'https://067ae1c6d7c847278d84a7bbd12515ec@o404766.ingest.sentry.io/5965064',
integrations: [
// enable HTTP calls tracing
new Sentry.Integrations.Http({ tracing: true }),
Expand Down
2 changes: 1 addition & 1 deletion server/lib/User/comparePassword.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import bcrypt from "bcryptjs";
import bcrypt from 'bcryptjs';

export default function comparePassword(
password: string,
Expand Down
4 changes: 2 additions & 2 deletions server/lib/User/getEmailFromOwner.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Knex } from "knex";
import { Knex } from 'knex';

export default function getEmailFromOwner(DB: Knex, id: string) {
return DB("users").where({ id }).returning(["email"]).first();
return DB('users').where({ id }).returning(['email']).first();
}
8 changes: 4 additions & 4 deletions server/lib/User/getOwnerFromAccessToken.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Knex } from "knex";
import { Knex } from 'knex';

export default function getOwnerFromAccessToken(DB: Knex, token: string) {
return DB("access_tokens")
.where({ token, host: "2anki.net" })
.returning(["owner"])
return DB('access_tokens')
.where({ token, host: '2anki.net' })
.returning(['owner'])
.first();
}
6 changes: 3 additions & 3 deletions server/lib/User/getQuota.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Knex } from "knex";
import { Knex } from 'knex';

export default async function getQuota(DB: Knex, owner: string) {
const allUserUploads = await DB("uploads")
const allUserUploads = await DB('uploads')
.where({ owner })
.returning(["object_id", "status", "size_mb"]);
.returning(['object_id', 'status', 'size_mb']);
let size = 0;
for (const u of allUserUploads) {
size += u.size_mb;
Expand Down
2 changes: 1 addition & 1 deletion server/lib/User/hashPassword.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import bcrypt from "bcryptjs";
import bcrypt from 'bcryptjs';

export default function hashPassword(password: string): string {
return bcrypt.hashSync(password, 12);
Expand Down
4 changes: 2 additions & 2 deletions server/lib/User/isPatron.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Knex } from "knex";
import { Knex } from 'knex';

export default function isPatron(DB: Knex, id: string) {
return DB("users").where({ id }).returning(["patreon"]).first();
return DB('users').where({ id }).returning(['patreon']).first();
}
6 changes: 3 additions & 3 deletions server/lib/User/updatePassword.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { Knex } from "knex";
import { Knex } from 'knex';

import hashPassword from "./hashPassword";
import hashPassword from './hashPassword';

export default async function updatePassword(
DB: Knex,
password: any,
reset_token: any
) {
return DB("users")
return DB('users')
.where({ reset_token })
.update({ password: hashPassword(password), reset_token: null });
}
19 changes: 10 additions & 9 deletions server/lib/anki/CardGenerator.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,33 @@
import { execFile } from "child_process";
import { homedir } from "os";
import path from "path";
import { execFile } from 'child_process';
import { homedir } from 'os';
import path from 'path';

import { resolvePath } from "../constants";
import { resolvePath } from '../constants';

function PYTHON() {
const os = process.platform;
if (os === "win32") {
if (os === 'win32') {
return `${homedir}\\AppData\\Local\\Programs\\Python\\Python38\\python.exe`;
}
return "/usr/bin/python3";
return '/usr/bin/python3';
}

class CardGenerator {
createDeckScriptPath: string;

currentDirectory: string;

constructor(workspace: string) {
this.createDeckScriptPath = resolvePath(
__dirname,
"../../genanki/create_deck.py"
'../../genanki/create_deck.py'
);
this.currentDirectory = workspace;
}

async run() {
const dpayload = path.join(this.currentDirectory, "deck_info.json");
const tdir = resolvePath(__dirname, "../../templates/");
const dpayload = path.join(this.currentDirectory, 'deck_info.json');
const tdir = resolvePath(__dirname, '../../templates/');

const createDeckScriptPathARGS = [
this.createDeckScriptPath,
Expand Down
6 changes: 3 additions & 3 deletions server/lib/anki/getDeckname.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ describe('getDeckname', () => {
});
it('has parent', () => {
expect(getDeckName('parent', 'test')).toBe('parent::test');
})
it("ignores parent is same as child", () => {
});
it('ignores parent is same as child', () => {
expect(getDeckName('test', 'test')).toBe('test');
})
});
});
12 changes: 6 additions & 6 deletions server/lib/anki/getDeckname.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
/**
* This will collapse children with exact same title to the parent.
* This is safe to do because the parent will be the one that is used to create the deck.
* This is safe to do because the parent will be the one that is used to create the deck.
* The user is potentially losing the ability to create a deck with the same name as a parent.
* In the real world this does not really matter but adding this note in case that assumption
* In the real world this does not really matter but adding this note in case that assumption
* changes.
*/
export default function getDeckName(
parent: string | undefined,
name: string
): string {
if (parent && parent !== name) {
return `${parent}::${name}`;
}
return name;
if (parent && parent !== name) {
return `${parent}::${name}`;
}
return name;
}
22 changes: 11 additions & 11 deletions server/lib/anki/sanitizeTags.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import sanitizeTags from "./sanitizeTags"
import sanitizeTags from './sanitizeTags';

describe("sanitizeTags", () => {
it.each([
["spaces are handled", ["this tag"], ["this-tag"]],
["tabs are handled", ["\tthis tag"], ["this-tag"]],
["newlines are handled", ["\nthis tag"], ["this-tag"]],
["double spaces are handled", ["\nthis tag"], ["this-tag"]],
])("%s", (_, input, expected) => {
expect(sanitizeTags(input)).toEqual(expected)
})
})
describe('sanitizeTags', () => {
it.each([
['spaces are handled', ['this tag'], ['this-tag']],
['tabs are handled', ['\tthis tag'], ['this-tag']],
['newlines are handled', ['\nthis tag'], ['this-tag']],
['double spaces are handled', ['\nthis tag'], ['this-tag']],
])('%s', (_, input, expected) => {
expect(sanitizeTags(input)).toEqual(expected);
});
});
7 changes: 3 additions & 4 deletions server/lib/anki/sanitizeTags.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
const sanitizeTags = (
tags: string[]
): string[] => tags.map(($1) => $1.trim().replace(/\s+/g, "-"))
const sanitizeTags = (tags: string[]): string[] =>
tags.map(($1) => $1.trim().replace(/\s+/g, '-'));

export default sanitizeTags
export default sanitizeTags;
23 changes: 16 additions & 7 deletions server/lib/anki/zip.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import JSZip from "jszip";
import Package from "../parser/Package";
import JSZip from 'jszip';
import { MAX_UPLOAD_SIZE } from '../misc/file';
import Package from '../parser/Package';

interface File {
name: string;
Expand All @@ -8,6 +9,7 @@ interface File {

class ZipHandler {
fileNames: string[];

files: File[];

constructor() {
Expand All @@ -16,17 +18,24 @@ class ZipHandler {
}

async build(zipData: Buffer) {
const size = Buffer.byteLength(zipData);
if (size > MAX_UPLOAD_SIZE) {
throw new Error(
`Zip data is too big max is ${MAX_UPLOAD_SIZE} but got ${size}`
);
}

const loadedZip = await JSZip.loadAsync(zipData);
this.fileNames = Object.keys(loadedZip.files);
this.fileNames = this.fileNames.filter((f) => !f.endsWith("/"));
this.fileNames = this.fileNames.filter((f) => !f.endsWith('/'));
this.files = [];

for (const name of this.fileNames) {
let contents;
if (name.match(/.(md|html)$/)) {
contents = await loadedZip.files[name].async("text");
contents = await loadedZip.files[name].async('text');
} else {
contents = await loadedZip.files[name].async("uint8array");
contents = await loadedZip.files[name].async('uint8array');
}
if (contents) {
this.files.push({ name, contents });
Expand All @@ -44,9 +53,9 @@ class ZipHandler {
zip.file(`${d.name}.apkg`, d.apkg);
}
if (advertisment) {
zip.file("README.html", advertisment);
zip.file('README.html', advertisment);
}
return zip.generateAsync({ type: "nodebuffer" });
return zip.generateAsync({ type: 'nodebuffer' });
}
}

Expand Down
37 changes: 19 additions & 18 deletions server/lib/constants.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,33 @@
import path from "path";
import path from 'path';

export const TEMPLATE_DIR = path.join(__dirname, "../templates");
export const TEMPLATE_DIR = path.join(__dirname, '../templates');

export const ALLOWED_ORIGINS = [
"http://localhost:8080",
"http://localhost:2020",
"https://dev.notion2anki.alemayhu.com",
"https://dev.2anki.net",
"https://notion.2anki.com",
"https://2anki.net",
"https://2anki.com",
"https://notion.2anki.net",
"https://dev.notion.2anki.net",
"https://notion.2anki.net/",
"https://staging.2anki.net",
"https://templates.2anki.net/",
'http://localhost:8080',
'http://localhost:2020',
'https://dev.notion2anki.alemayhu.com',
'https://dev.2anki.net',
'https://notion.2anki.com',
'https://2anki.net',
'https://2anki.com',
'https://notion.2anki.net',
'https://dev.notion.2anki.net',
'https://notion.2anki.net/',
'https://staging.2anki.net',
'https://templates.2anki.net/',
];

export function resolvePath(dir: string, x: string) {
const p = path
.resolve(path.join(dir, x))
.replace(/app.asar/g, "app.asar.unpacked");
return x.endsWith("/") ? p + "/" : p;
.replace(/app.asar/g, 'app.asar.unpacked');
return x.endsWith('/') ? `${p}/` : p;
}

export const TIME_21_MINUTES_AS_SECONDS = 1260;

export const ONE_HOUR = 60 * 60 * 1000;

export const BUILD_DIR = process.env.WEB_BUILD_DIR || path.join(__dirname, "../../web/build")
export const INDEX_FILE = path.join(BUILD_DIR, "index.html");
export const BUILD_DIR =
process.env.WEB_BUILD_DIR || path.join(__dirname, '../../web/build');
export const INDEX_FILE = path.join(BUILD_DIR, 'index.html');
5 changes: 2 additions & 3 deletions server/lib/debug/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
export const IsDebug = () => {
return process.env.SPACES_DEFAULT_BUCKET_NAME == "dev.2anki.net";
};
export const IsDebug = () =>
process.env.SPACES_DEFAULT_BUCKET_NAME == 'dev.2anki.net';
Loading

0 comments on commit 96bc7e4

Please sign in to comment.