Skip to content

Commit

Permalink
estandarizando estilo del código + docs
Browse files Browse the repository at this point in the history
  • Loading branch information
pablouser1 committed May 9, 2024
1 parent 1fd76e5 commit f12c3f0
Show file tree
Hide file tree
Showing 18 changed files with 391 additions and 298 deletions.
4 changes: 1 addition & 3 deletions meta.json
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
{
"namespace": "Violentmonkey Scripts",
"match": [
"https://wuolah.com/*"
],
"match": ["https://wuolah.com/*"],
"grant": [
"GM_getValue",
"GM_setValue",
Expand Down
28 changes: 13 additions & 15 deletions meta.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,29 @@
import metablock from 'rollup-plugin-userscript-metablock';
import metablock from "rollup-plugin-userscript-metablock";
import type { Plugin } from "rollup";
import pkg from "./package.json" assert { type: "json" };
import { readFileSync } from 'fs';
import { join } from 'path';
import { readFileSync } from "fs";
import { join } from "path";

// Required external resources from npm
const PKG_RESOURCES = {
"gulagcleaner_wasm": "gulagcleaner_wasm_bg.wasm"
gulagcleaner_wasm: "gulagcleaner_wasm_bg.wasm",
};

// Requiered js files from npm
const PKG_REQS = {
"pdf-lib": "dist/pdf-lib.min.js"
"pdf-lib": "dist/pdf-lib.min.js",
};

// Static required js files
const EXTERNAL_REQS = [
"https://openuserjs.org/src/libs/sizzle/GM_config.js"
]
const EXTERNAL_REQS = ["https://openuserjs.org/src/libs/sizzle/GM_config.js"];

// Get dependency version
const getPkgVer = (pkg: string): string => {
const jsonStr = readFileSync(join("node_modules", pkg, "package.json"));

const json = JSON.parse(jsonStr.toString("utf-8"));
return json.version;
}
};

// Build map from PKG_RESOURCES
const getResources = (): Record<string, string> => {
Expand All @@ -38,7 +36,7 @@ const getResources = (): Record<string, string> => {
}

return entries;
}
};

// Build array from PKG_RQS and EXTERNAL_REQS
const getRequires = (): string[] => {
Expand All @@ -52,11 +50,11 @@ const getRequires = (): string[] => {
}

return els;
}
};

const getMetablock = (): Plugin => {
return metablock({
file: './meta.json',
file: "./meta.json",
override: {
name: pkg.displayName,
version: pkg.version,
Expand All @@ -66,9 +64,9 @@ const getMetablock = (): Plugin => {
license: pkg.license,
// @ts-expect-error dependency typing not configed properly
require: getRequires(),
resource: getResources()
}
resource: getResources(),
},
});
}
};

export default getMetablock;
42 changes: 22 additions & 20 deletions rollup.config.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import externalGlobals from "rollup-plugin-external-globals";
import { nodeResolve } from '@rollup/plugin-node-resolve';
import typescript from '@rollup/plugin-typescript';
import { nodeResolve } from "@rollup/plugin-node-resolve";
import typescript from "@rollup/plugin-typescript";
// @ts-expect-error dependency typing not configed properly
import serve from 'rollup-plugin-serve';
import sass from 'rollup-plugin-sass';
import serve from "rollup-plugin-serve";
import sass from "rollup-plugin-sass";
import type { Plugin, RollupOptions } from "rollup";
import getMetablock from './meta';
import getMetablock from "./meta";

// Map package name -> Global window name
export const EXTERNAL_GLOBALS = {
"pdf-lib": "PDFLib"
}
"pdf-lib": "PDFLib",
};

const isProduction = !process.env.ROLLUP_WATCH;

Expand All @@ -19,27 +19,29 @@ const plugins: Plugin[] = [
externalGlobals(EXTERNAL_GLOBALS),
nodeResolve(),
sass(),
typescript()
]
typescript(),
];

if (!isProduction) {
plugins.push(serve({
contentBase: ['dist'],
headers: {
'Cache-Control': 'public, max-age=5'
}
}))
plugins.push(
serve({
contentBase: ["dist"],
headers: {
"Cache-Control": "public, max-age=5",
},
})
);
}

const config: RollupOptions = {
input: 'src/main.ts',
input: "src/main.ts",
output: {
file: "dist/WuolahExtra.user.js",
format: "esm",
// Sourcemaps only for development
sourcemap: isProduction ? false : 'inline'
sourcemap: isProduction ? false : "inline",
},
plugins
}
plugins,
};

export default config
export default config;
7 changes: 5 additions & 2 deletions src/constants/ClearMethods.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
/**
* Listado de métodos de limpieza de PDF
*/
enum ClearMethods {
NONE = "none",
GULAG = "gulag",
PDFLIB = "pdflib"
PDFLIB = "pdflib",
}

export default ClearMethods
export default ClearMethods;
80 changes: 53 additions & 27 deletions src/constants/Hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,77 +4,103 @@ import { HookAfter, HookBefore } from "../types/Hooks";
import Log from "./Log";
import handlePDF, { openBlob } from "../helpers/Cleaner";

/**
* Hooks de Fetch
*/
export default class Hooks {
/**
* Hooks que se ejecutan antes de enviar una solicitud
*/
static BEFORE: HookBefore[] = [
{
id: 'no-analytics',
id: "no-analytics",
endpoint: /^\/v2\/events$/,
func: Hooks.noAnalytics,
cond: () => GM_config.get("no_analytics")
}
]
cond: () => GM_config.get("no_analytics"),
},
];

/**
* Hooks que se ejecutan después de enviar una solicitud
*/
static AFTER: HookAfter[] = [
{
id: 'make-pro',
id: "make-pro",
endpoint: /^\/v2\/me$/,
func: Hooks.makePro
func: Hooks.makePro,
},
{
id: 'no-ui-ads',
id: "no-ui-ads",
endpoint: /^\/v2\/a-d-s$/,
func: Hooks.noUiAds,
cond: () => GM_config.get("clean_ui")
cond: () => GM_config.get("clean_ui"),
},
{
id: 'folder-download',
id: "folder-download",
endpoint: /^\/v2\/group-downloads\/uploads/,
func: Hooks.folderDownload,
cond: () => GM_config.get("folder_download")
}
]
cond: () => GM_config.get("folder_download"),
},
];

// -- Before -- //
/**
* Eliminar analíticas de Wuolah
*/
static noAnalytics(_input: RequestInfo | URL, init?: RequestInit) {
if (init) {
Misc.log('Removing events', Log.INFO)
Misc.log("Eliminando eventos", Log.INFO);
init.body = JSON.stringify({
events: []
})
events: [],
});
}
}

// -- After -- //
/**
* Reemplaza solicitud de /me y hacer al usuario pro
*/
static makePro(res: Response) {
if (res.ok) {
Misc.log('Making user client-side pro V2', Log.INFO)
const json = () => res.clone().json().then(d => ({ ...d, isPro: true }));
Misc.log("Haciendo usuario pro client-side", Log.INFO);
const json = () =>
res
.clone()
.json()
.then((d) => ({ ...d, isPro: true }));
res.json = json;
}
}

/**
* Elimina anuncios de la UI
*/
static noUiAds(res: Response) {
if (res.ok) {
Misc.log('Wiping ui ads array', Log.INFO)
Misc.log("Eliminando ui ads", Log.INFO);

const json = async () => {
return { items: [] }
}
return { items: [] };
};

res.json = json
res.json = json;
}
}

/**
* Descarga carpetas
* @todo Gestionar captchas
*/
static folderDownload(res: Response) {
const url = res.url
const id = parseInt(url.substring(url.lastIndexOf('/') + 1));
const url = res.url;
const id = parseInt(url.substring(url.lastIndexOf("/") + 1));

if (isNaN(id)) {
Misc.log("Couldn't get folder ID!", Log.INFO);
Misc.log("¡Error al obtener id de la carpeta!", Log.INFO);
return;
}

Misc.log(`Starting folder download of ${id}`, Log.INFO);
Misc.log(`Descargando carpeta ${id}`, Log.INFO);

Api.folder(id).then(async (docs) => {
let failed = false;
Expand All @@ -87,10 +113,10 @@ export default class Hooks {
let buf = await Api.docData(url);
let options: BlobPropertyBag | undefined = undefined;

if (doc.fileType === 'application/pdf') {
if (doc.fileType === "application/pdf") {
buf = await handlePDF(buf);
options = {
type: "application/pdf"
type: "application/pdf",
};
}

Expand Down
9 changes: 7 additions & 2 deletions src/constants/Log.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
/**
* Modos de Logging
*/
enum Log {
DEBUG, INFO
DEBUG,
INFO,
ERROR,
}

export default Log
export default Log;
29 changes: 21 additions & 8 deletions src/helpers/Api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ export default class Api {
static TOKEN_KEY = "token";

/**
* Get all documents from a folder
* @param id Folder id
* @returns All documents linked to the folder
* Lista todos los documentos de una carpeta
* @param id Id carpeta
* @returns Todos los documentos pertenecientes a la carpeta
*/
static async folder(id: number): Promise<Doc[]> {
const params = new URLSearchParams();
Expand All @@ -24,11 +24,19 @@ export default class Api {
params.append("pagination[pageSize]", "9999");
params.append("pagination[withCount]", "false");

const res = await origFetch(`${Api.BASE_URL}/documents?${params.toString()}`, Api._buildInit());
const res = await origFetch(
`${Api.BASE_URL}/documents?${params.toString()}`,
Api._buildInit()
);
const json: ApiRes<Doc[]> = await res.json();
return json.data;
}

/**
* Consigue URL del documento a partir de su ID
* @param id Id documento
* @returns Url para descargar documento
*/
static async docUrl(id: number): Promise<string | null> {
const body: DownloadBody = {
adblockDetected: false,
Expand All @@ -45,14 +53,14 @@ export default class Api {
ubication2ExpectedPubs: 0,
ubication2RequestedPubs: 0,
ubication3ExpectedPubs: 0,
ubication3RequestedPubs: 0
ubication3RequestedPubs: 0,
};

const bodyStr = JSON.stringify(body);
const res = await origFetch(`${Api.BASE_URL}/download`, {
method: "POST",
body: bodyStr,
...Api._buildInit()
...Api._buildInit(),
});

if (!res.ok) {
Expand All @@ -63,6 +71,11 @@ export default class Api {
return data.url;
}

/**
* Descarga un documento
* @param url Url del documento
* @returns Documento ya descargado como `ArrayBuffer`
*/
static async docData(url: string): Promise<ArrayBuffer> {
const res = await origFetch(url);
const buf = await res.arrayBuffer();
Expand All @@ -76,8 +89,8 @@ export default class Api {
private static _buildInit(): RequestInit {
return {
headers: {
Authorization: `Bearer ${Api._getToken()}`
}
Authorization: `Bearer ${Api._getToken()}`,
},
};
}
}
Loading

0 comments on commit f12c3f0

Please sign in to comment.