[~] Refactor

This commit is contained in:
Siarhei Siniak 2024-08-17 00:37:29 +03:00
parent a67d765569
commit 2b3305ab56
5 changed files with 517 additions and 1 deletions

@ -1,4 +1,7 @@
{ {
"name": "greasyfork", "name": "greasyfork",
"packageManager": "yarn@4.4.0" "packageManager": "yarn@4.4.0",
"dependencies": {
"typescript": "^5.5.4"
}
} }

382
deps/greasyfork/src/linkedin.user.js vendored Normal file

@ -0,0 +1,382 @@
"use strict";
// ==UserScript==
// @name data extraction linkedin
// @namespace Violentmonkey Scripts
// @match https://www.linkedin.com/*
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_getValues
// @grant GM_setValues
// @grant GM_listValues
// @grant GM_deleteValue
// @grant GM_deleteValues
// @grant GM_addStyle
// @grant GM_addElement
// @version 0.1
// @author Siarhei Siniak
// @license Unlicense
// @description 10/08/2024, 8:44:59 PM
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
// @run-at document-body
// @inject-into content
// @require https://cdn.jsdelivr.net/npm/@violentmonkey/dom@1
// @require https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js
// @noframes
// ==/UserScript==
/*
Use this extension to disalbe CSP for linkedin
https://addons.mozilla.org/en-US/firefox/addon/header-editor/
https://github.com/FirefoxBar/HeaderEditor
https://github.com/violentmonkey/violentmonkey/issues/1335
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src
{
"request": [],
"sendHeader": [],
"receiveHeader": [
{
"enable": true,
"name": "disable CSP for linkedin",
"ruleType": "modifyReceiveHeader",
"matchType": "domain",
"pattern": "www.linkedin.com",
"exclude": "",
"group": "Ungrouped",
"isFunction": false,
"action": {
"name": "content-security-policy",
"value": ""
}
}
],
"receiveBody": []
}
*/
class Linkedin {
constructor() {
this.data = new Map();
this.ui = {
root: null,
entries: null,
search: null,
state: null,
};
this.state = {
search: '',
};
}
clean_page() {
if (location.href.search('empty_body=true') != -1) {
$('head').empty();
$('body').empty();
$('body').addClass('no-border');
}
}
data_load() {
return __awaiter(this, void 0, void 0, function* () {
let self = this;
const keys = yield GM_listValues();
let loaded = 0;
for (let o of keys) {
if (!o.startsWith('data-')) {
return;
}
self.data.set(o.slice(5), yield GM_getValue(o));
loaded += 1;
}
console.log({ action: 'loaded', total: loaded });
});
}
string_reduce(text) {
return text.replaceAll(/\s+/gi, ' ').trim();
}
parse_header() {
let self = this;
return [
$('.scaffold-finite-scroll__content > div > .relative .update-components-header').map((i, o) => ({
header: o.innerText
})),
$('.scaffold-finite-scroll__content > div > .relative .update-components-actor').map((i, o) => {
let header = $(o);
let teaser = $(o).parents('.relative')
.parent().find('.feed-shared-update-v2__description-wrapper');
return {
header: self.string_reduce(header.text()),
teaser: self.string_reduce(teaser.text()),
};
})
];
}
data_add(entry) {
return __awaiter(this, void 0, void 0, function* () {
let self = this;
if (self.data.has(entry.header)) {
return false;
}
self.data.set(entry.header, {
entry: entry,
ts: (new Date()).valueOf(),
});
yield GM_setValue('data-' + entry.header, self.data.get(entry.header));
console.log('saved ' + entry.header);
console.log(self.data.get(entry.header));
return true;
});
}
document_on_changed() {
return __awaiter(this, void 0, void 0, function* () {
let self = this;
let state_changed = false;
if (JSON.stringify(self.state_get()) != JSON.stringify(self.state)) {
state_changed = true;
self.old_state = self.state;
self.state = self.state_get();
}
let current_data = self.parse_header();
let changed = false;
for (let o of current_data[0]) {
let current_changed = yield self.data_add(o);
if (current_changed) {
changed = current_changed;
}
}
for (let o of current_data[1]) {
let current_changed = yield self.data_add(o);
if (current_changed) {
changed = current_changed;
}
}
if (changed || (state_changed ||
self.ui.entries === null && self.data.size > 0)) {
self.display();
}
});
}
listener_add() {
let self = this;
return VM.observe(document.body, () => {
self.document_on_changed();
});
}
display_init() {
let self = this;
self.ui.root = $(`<div class=online-fxreader-linkedin>`);
$('head').append($('<style>').html(`
div.online-fxreader-linkedin {
height: 3em;
overflow: scroll;
z-index: 9999;
position: fixed;
top: 5em;
background: yellow;
margin-left: 1em;
word-wrap: anywhere;
white-space: break-spaces;
margin-right: 1em;
width: calc(100% - 2em);
}
.d-none {
display: none !important;
}
.online-fxreader-linkedin .search,
.online-fxreader-linkedin .search input
{
height: 2em;
line-height: 2em;
box-sizing: border-box;
}
.no-border {
padding: unset;
margin: unset;
}
.online-fxreader-linkedin:hover {
height: 10em;
}
`));
GM_addElement('script', {
"textContent": `
class Linkedin {
constructor() {
let self = this;
this.ui = {
root: () => {
return document.getElementsByClassName('online-fxreader-linkedin')[0];
},
};
self.ui.search = () => {
let search = self.ui.root().getElementsByClassName('search')[0];
let search_input = search.getElementsByTagName('input')[0];
return search_input;
};
self.ui.state = () => {
let state = self.ui.root().getElementsByClassName('state')[0];
return state;
};
}
blah(class_name) {
console.log('blah');
Array.from(
document.getElementsByClassName(class_name)
).forEach((o) => o.remove());
}
state_update(partial) {
let self = this;
let ui_state = self.ui.state();
let old_state = JSON.parse(ui_state.innerText);
ui_state.innerText = JSON.stringify(
{
...old_state,
...partial
}
);
}
search_on_change() {
let self = this;
let search = self.ui.search();
self.state_update(
{
search: search.value
}
);
}
};
const online_fxreader_linkedin = new Linkedin();
console.log('started');
`
});
$(document.body).append(self.ui.root);
}
state_get() {
let self = this;
if (self.ui.state && self.ui.state.text() !== '') {
return JSON.parse(self.ui.state.text());
}
else {
return {};
}
}
state_set(partial) {
let self = this;
self.ui.state.text(Object.assign(Object.assign({}, state_get()), partial));
}
display() {
var _a;
let self = this;
let sorted_entries = Array.from(self.data.entries()).sort((a, b) => a[1].ts - b[1].ts);
// self.ui.root.empty();
if (self.ui.search === null) {
let search = $('<div>').addClass('search').append($('<input>').val(self.state.search)).attr('onkeyup', `online_fxreader_linkedin.search_on_change()`);
search.append($('<div>').addClass('total'));
;
self.ui.root.append(search);
self.ui.search = search;
}
if (self.ui.state === null) {
self.ui.state = $('<div>').addClass('state d-none').text(JSON.stringify(self.state));
self.ui.root.append(self.ui.state);
}
else {
}
//state_set(old_state);
let entries = null;
if (self.ui.entries === null) {
entries = $('<div>').addClass('entries');
self.ui.root.append(entries);
self.ui.entries = entries;
}
else {
entries = self.ui.entries;
entries.empty();
}
let keywords = (((_a = self.state) === null || _a === void 0 ? void 0 : _a.search) || '').split(/\s+/).map((o) => {
let action = null;
let word = null;
if (o.length > 0) {
if (o[0] == '+') {
action = 'include';
word = o.slice(1);
}
else if (o[0] == '-') {
action = 'exclude';
word = o.slice(1);
}
else {
action = 'include';
word = o;
}
}
return {
action,
word,
};
}).filter((o) => o.action !== null);
let filtered_entries = sorted_entries.filter((o) => {
let match = true;
let text = JSON.stringify(o);
for (let k of keywords) {
if (k.action == 'include') {
if (text.search(k.word) == -1) {
match = false;
}
}
else if (k.action == 'exclude') {
if (text.search(k.word) != -1) {
match = false;
}
}
if (!match) {
break;
}
}
return match;
});
self.ui.search.find('.total').text(filtered_entries.length);
for (let o of filtered_entries.reverse()) {
let raw = JSON.stringify(o[1]);
let ts = (new Date(o[1].ts));
let entry = $('<div>').addClass('entry');
entry.append($('<div>').addClass('ts').text(ts.toISOString()));
entry.append($('<div>').addClass('header').text(o[1].entry.header));
entry.append($('<div>').addClass('teaser').text(o[1].entry.teaser));
// entry.append($('<pre>').text(raw));
entries.append(entry);
}
GM_addElement('script', {
"class": 'bridge',
"textContent": `
online_fxreader_linkedin.blah('bridge');
`
});
}
}
const l = new Linkedin();
(() => __awaiter(void 0, void 0, void 0, function* () {
l.clean_page();
yield l.data_load();
const disconnect = l.listener_add();
l.display_init();
}))();

109
deps/greasyfork/tsconfig.json vendored Normal file

@ -0,0 +1,109 @@
{
"include": ["src"],
"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": "./", /* 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. */
// "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. */
// "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. */
// "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": "./", /* 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. */
// "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. */
// "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. */
}
}

@ -8,5 +8,27 @@ __metadata:
"greasyfork@workspace:.": "greasyfork@workspace:.":
version: 0.0.0-use.local version: 0.0.0-use.local
resolution: "greasyfork@workspace:." resolution: "greasyfork@workspace:."
dependencies:
typescript: "npm:^5.5.4"
languageName: unknown languageName: unknown
linkType: soft linkType: soft
"typescript@npm:^5.5.4":
version: 5.5.4
resolution: "typescript@npm:5.5.4"
bin:
tsc: bin/tsc
tsserver: bin/tsserver
checksum: 10c0/422be60f89e661eab29ac488c974b6cc0a660fb2228003b297c3d10c32c90f3bcffc1009b43876a082515a3c376b1eefcce823d6e78982e6878408b9a923199c
languageName: node
linkType: hard
"typescript@patch:typescript@npm%3A^5.5.4#optional!builtin<compat/typescript>":
version: 5.5.4
resolution: "typescript@patch:typescript@npm%3A5.5.4#optional!builtin<compat/typescript>::version=5.5.4&hash=379a07"
bin:
tsc: bin/tsc
tsserver: bin/tsserver
checksum: 10c0/73409d7b9196a5a1217b3aaad929bf76294d3ce7d6e9766dd880ece296ee91cf7d7db6b16c6c6c630ee5096eccde726c0ef17c7dfa52b01a243e57ae1f09ef07
languageName: node
linkType: hard