Repository: ajayyy/SponsorBlock Branch: master Commit: 7f881e808c76 Files: 141 Total size: 883.0 KB Directory structure: gitextract_jhhxv7ay/ ├── .editorconfig ├── .eslintrc.json ├── .github/ │ ├── FUNDING.yml │ ├── pull_request_template.md │ └── workflows/ │ ├── ci.yml │ ├── release.yml │ ├── take-action.yml │ ├── tests.yml │ ├── update-oss-attribution.yml │ └── updateInvidous.yml ├── .gitignore ├── .gitmodules ├── CONTRIBUTING.md ├── LICENSE ├── LICENSE-APPSTORE.txt ├── LICENSE-HISTORY.txt ├── README.md ├── ci/ │ ├── generateList.ts │ ├── invidiousCI.ts │ ├── invidiousType.ts │ ├── invidiouslist.json │ ├── pipedCI.ts │ └── prettify.ts ├── config.json.example ├── crowdin.yml ├── jest.config.js ├── manifest/ │ ├── beta-manifest-extra.json │ ├── chrome-manifest-extra.json │ ├── firefox-beta-manifest-extra.json │ ├── firefox-manifest-extra.json │ ├── manifest-v2-extra.json │ ├── manifest.json │ └── safari-manifest-extra.json ├── oss-attribution/ │ └── licenseInfos.json ├── package.json ├── public/ │ ├── content.css │ ├── help/ │ │ ├── index.html │ │ └── styles.css │ ├── icons/ │ │ └── beep.oga │ ├── libs/ │ │ └── Source+Sans+Pro.css │ ├── options/ │ │ ├── options.css │ │ └── options.html │ ├── oss-attribution/ │ │ └── attribution.txt │ ├── permissions/ │ │ ├── index.html │ │ └── styles.css │ ├── popup.css │ ├── popup.html │ ├── res/ │ │ └── countries.json │ └── shared.css ├── src/ │ ├── background.ts │ ├── components/ │ │ ├── CategoryPillComponent.tsx │ │ ├── ChapterVoteComponent.tsx │ │ ├── NoticeComponent.tsx │ │ ├── NoticeTextSectionComponent.tsx │ │ ├── SelectorComponent.tsx │ │ ├── SkipNoticeComponent.tsx │ │ ├── SponsorTimeEditComponent.tsx │ │ ├── SubmissionNoticeComponent.tsx │ │ └── options/ │ │ ├── AdvancedSkipOptionsComponent.tsx │ │ ├── CategoryChooserComponent.tsx │ │ ├── CategorySkipOptionsComponent.tsx │ │ ├── KeybindComponent.tsx │ │ ├── KeybindDialogComponent.tsx │ │ ├── NumberInputOptionComponent.tsx │ │ ├── SelectOptionComponent.tsx │ │ ├── ToggleOptionComponent.tsx │ │ ├── UnsubmittedVideoListComponent.tsx │ │ ├── UnsubmittedVideoListItem.tsx │ │ └── UnsubmittedVideosComponent.tsx │ ├── config.ts │ ├── content.ts │ ├── dearrowPromotion.ts │ ├── document.ts │ ├── globals.d.ts │ ├── help.ts │ ├── js-components/ │ │ ├── previewBar.ts │ │ └── skipButtonControlBar.ts │ ├── messageTypes.ts │ ├── options.ts │ ├── permissions.ts │ ├── popup/ │ │ ├── PopupComponent.tsx │ │ ├── SegmentListComponent.tsx │ │ ├── SegmentSubmissionComponent.tsx │ │ ├── YourWorkComponent.tsx │ │ ├── popup.tsx │ │ └── popupUtils.ts │ ├── render/ │ │ ├── AdvancedSkipOptions.tsx │ │ ├── CategoryChooser.tsx │ │ ├── CategoryPill.tsx │ │ ├── ChapterVote.tsx │ │ ├── GenericNotice.tsx │ │ ├── RectangleTooltip.tsx │ │ ├── SkipNotice.tsx │ │ ├── SubmissionNotice.tsx │ │ ├── Tooltip.tsx │ │ ├── UnsubmittedVideos.tsx │ │ └── UpcomingNotice.tsx │ ├── svg-icons/ │ │ ├── checkIcon.tsx │ │ ├── clipboardIcon.tsx │ │ ├── lock_svg.tsx │ │ ├── pencilIcon.tsx │ │ ├── pencil_svg.tsx │ │ ├── resetIcon.tsx │ │ ├── sb_svg.tsx │ │ ├── thumbs_down_svg.tsx │ │ └── thumbs_up_svg.tsx │ ├── types.ts │ ├── utils/ │ │ ├── arrayUtils.ts │ │ ├── categoryUtils.ts │ │ ├── compatibility.ts │ │ ├── configUtils.ts │ │ ├── constants.ts │ │ ├── crossExtension.ts │ │ ├── exporter.ts │ │ ├── genericUtils.ts │ │ ├── logger.ts │ │ ├── mobileUtils.ts │ │ ├── noticeUtils.ts │ │ ├── pageCleaner.ts │ │ ├── pageUtils.ts │ │ ├── requests.ts │ │ ├── segmentData.ts │ │ ├── skipProfiles.ts │ │ ├── skipRule.ts │ │ ├── skipRule.type.ts │ │ ├── thumbnails.ts │ │ ├── urlParser.ts │ │ ├── videoLabels.ts │ │ └── warnings.ts │ └── utils.ts ├── test/ │ ├── exporter.test.ts │ ├── previewBar.test.ts │ ├── selenium.test.ts │ └── urlParser.test.ts ├── tsconfig-production.json ├── tsconfig.json └── webpack/ ├── configDiffPlugin.js ├── webpack.common.js ├── webpack.dev.js ├── webpack.manifest.js └── webpack.prod.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ # EditorConfig is awesome: https://EditorConfig.org # top-most EditorConfig file root = true # Unix-style newlines with a newline ending every file [*] end_of_line = lf insert_final_newline = true [*.{js,json,ts,tsx}] charset = utf-8 indent_style = space indent_size = 4 [package.json] indent_style = space indent_size = 2 ================================================ FILE: .eslintrc.json ================================================ { "env": { "browser": true, "es2021": true, "node": true, "jest": true }, "extends": [ "eslint:recommended", "plugin:react/recommended", "plugin:@typescript-eslint/recommended" ], "parser": "@typescript-eslint/parser", "parserOptions": { "ecmaFeatures": { "jsx": true }, "ecmaVersion": 12, "sourceType": "module" }, "plugins": ["react", "@typescript-eslint"], "rules": { "@typescript-eslint/no-unused-vars": "error", "no-self-assign": "off", "@typescript-eslint/no-empty-interface": "off", "react/prop-types": [2, { "ignore": ["children"] }], "@typescript-eslint/member-delimiter-style": "warn", "@typescript-eslint/no-non-null-assertion": "off", "@typescript-eslint/ban-ts-comment": "off", "@typescript-eslint/no-this-alias": "off" }, "settings": { "react": { "version": "detect" } } } ================================================ FILE: .github/FUNDING.yml ================================================ github: ajayyy-org patreon: ajayyy custom: [sponsor.ajay.app/donate] ================================================ FILE: .github/pull_request_template.md ================================================ - [ ] I agree to license my contribution under GPL-3.0 and agree to allow distribution on app stores as outlined in [LICENSE-APPSTORE](https://github.com/ajayyy/SponsorBlock/blob/master/LICENSE-APPSTORE.txt) To test this pull request, follow the [instructions in the wiki](https://github.com/ajayyy/SponsorBlock/wiki/Testing-a-Pull-Request). *** ================================================ FILE: .github/workflows/ci.yml ================================================ name: CI on: [push, pull_request] jobs: build: name: Create artifacts runs-on: ubuntu-latest steps: # Initialization - uses: actions/checkout@v4 with: submodules: recursive - uses: actions/setup-node@v4 with: node-version: '18' - run: npm ci - name: Copy configuration run: cp config.json.example config.json # Run linter - name: Lint run: npm run lint # Create Chrome artifacts - name: Create Chrome artifacts run: npm run build:chrome - uses: actions/upload-artifact@v4 with: name: ChromeExtension path: dist - run: mkdir ./builds - uses: montudor/action-zip@0852c26906e00f8a315c704958823928d8018b28 with: args: zip -qq -r ./builds/ChromeExtension.zip ./dist # Create Firefox artifacts - name: Create Firefox artifacts run: npm run build:firefox - uses: actions/upload-artifact@v4 with: name: FirefoxExtension path: dist - uses: montudor/action-zip@0852c26906e00f8a315c704958823928d8018b28 with: args: zip -qq -r ./builds/FirefoxExtension.zip ./dist # Create Beta artifacts (Builds with the name changed to beta) - name: Create Chrome Beta artifacts run: npm run build:chrome -- --env stream=beta - uses: actions/upload-artifact@v4 with: name: ChromeExtensionBeta path: dist - uses: montudor/action-zip@0852c26906e00f8a315c704958823928d8018b28 with: args: zip -qq -r ./builds/ChromeExtensionBeta.zip ./dist - name: Create Firefox Beta artifacts run: npm run build:firefox -- --env stream=beta - uses: actions/upload-artifact@v4 with: name: FirefoxExtensionBeta path: dist - uses: montudor/action-zip@0852c26906e00f8a315c704958823928d8018b28 with: args: zip -qq -r ./builds/FirefoxExtensionBeta.zip ./dist ================================================ FILE: .github/workflows/release.yml ================================================ name: Upload Release Build on: release: types: [published] jobs: build: name: Upload Release runs-on: ubuntu-latest steps: # Initialization - name: Checkout release branch w/submodules uses: actions/checkout@v5 with: submodules: recursive - uses: actions/setup-node@v4 with: node-version: '18' - name: Copy configuration run: cp config.json.example config.json # Create source artifact with submodule - name: Create directory run: cd ..; mkdir ./builds - name: Zip Source code run: zip -r ../builds/SourceCodeUseThisOne.zip * - name: Upload Source to release uses: Shopify/upload-to-release@07611424e04f1475ddf550e1c0dd650b867d5467 with: args: ../builds/SourceCodeUseThisOne.zip name: SourceCodeUseThisOne.zip path: ../builds/SourceCodeUseThisOne.zip repo-token: ${{ secrets.GITHUB_TOKEN }} - name: Checkout source maps branch uses: actions/checkout@v5 with: path: source-maps ref: source-maps - name: Set up committer info run: | git config --global user.name "github-actions[bot]" git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com" - run: npm ci # Create Firefox artifacts - name: Create Firefox artifacts run: npm run build:firefox -- --env ghpSourceMaps - run: mkdir ./builds - name: Move Firefox source maps to source map repo run: | VERSION=`jq -r '.version' ./dist/manifest.json` mkdir -p "./source-maps/firefox/$VERSION/" mv -v ./dist/**/*.js.map "./source-maps/firefox/$VERSION/" cp -v ./dist/**/*.js.LICENSE.txt "./source-maps/firefox/$VERSION/" - name: Zip Artifacts run: cd ./dist ; zip -r ../builds/FirefoxExtension.zip * - name: Upload FirefoxExtension to release uses: Shopify/upload-to-release@07611424e04f1475ddf550e1c0dd650b867d5467 with: args: builds/FirefoxExtension.zip name: FirefoxExtension.zip path: ./builds/FirefoxExtension.zip repo-token: ${{ secrets.GITHUB_TOKEN }} # Create Chrome artifacts - name: Create Chrome artifacts run: npm run build:chrome -- --env ghpSourceMaps - name: Move Chrome source maps to source map repo run: | VERSION=`jq -r '.version' ./dist/manifest.json` mkdir -p "./source-maps/chrome/$VERSION/" mv -v ./dist/**/*.js.map "./source-maps/chrome/$VERSION/" cp -v ./dist/**/*.js.LICENSE.txt "./source-maps/chrome/$VERSION/" - name: Zip Artifacts run: cd ./dist ; zip -r ../builds/ChromeExtension.zip * - name: Upload ChromeExtension to release uses: Shopify/upload-to-release@07611424e04f1475ddf550e1c0dd650b867d5467 with: args: builds/ChromeExtension.zip name: ChromeExtension.zip path: ./builds/ChromeExtension.zip repo-token: ${{ secrets.GITHUB_TOKEN }} # Create Edge artifacts - name: Clear dist for Edge run: rm -rf ./dist - name: Create Edge artifacts run: npm run build:edge -- --env ghpSourceMaps - name: Move Edge source maps to source map repo run: | VERSION=`jq -r '.version' ./dist/manifest.json` mkdir -p "./source-maps/edge/$VERSION/" mv -v ./dist/**/*.js.map "./source-maps/edge/$VERSION/" cp -v ./dist/**/*.js.LICENSE.txt "./source-maps/edge/$VERSION/" - name: Zip Artifacts run: cd ./dist ; zip -r ../builds/EdgeExtension.zip * - name: Upload EdgeExtension to release uses: Shopify/upload-to-release@07611424e04f1475ddf550e1c0dd650b867d5467 with: args: builds/EdgeExtension.zip name: EdgeExtension.zip path: ./builds/EdgeExtension.zip repo-token: ${{ secrets.GITHUB_TOKEN }} # Create Safari artifacts - name: Create Safari artifacts run: npm run build:safari -- --env ghpSourceMaps - name: Move Safari source maps to source map repo run: | VERSION=`jq -r '.version' ./dist/manifest.json` mkdir -p "./source-maps/safari/$VERSION/" mv -v ./dist/**/*.js.map "./source-maps/safari/$VERSION/" cp -v ./dist/**/*.js.LICENSE.txt "./source-maps/safari/$VERSION/" - name: Zip Artifacts run: cd ./dist ; zip -r ../builds/SafariExtension.zip * - name: Upload SafariExtension to release uses: Shopify/upload-to-release@07611424e04f1475ddf550e1c0dd650b867d5467 with: args: builds/SafariExtension.zip name: SafariExtension.zip path: ./builds/SafariExtension.zip repo-token: ${{ secrets.GITHUB_TOKEN }} # Create Beta artifacts (Builds with the name changed to beta) - name: Create Chrome Beta artifacts run: npm run build:chrome -- --env stream=beta --env ghpSourceMaps - name: Move Chrome Beta source maps to source map repo run: | VERSION=`jq -r '.version' ./dist/manifest.json` mkdir -p "./source-maps/chrome-beta/$VERSION/" mv -v ./dist/**/*.js.map "./source-maps/chrome-beta/$VERSION/" cp -v ./dist/**/*.js.LICENSE.txt "./source-maps/chrome-beta/$VERSION/" - name: Zip Artifacts run: cd ./dist ; zip -r ../builds/ChromeExtensionBeta.zip * - name: Upload ChromeExtensionBeta to release uses: Shopify/upload-to-release@07611424e04f1475ddf550e1c0dd650b867d5467 with: args: builds/ChromeExtensionBeta.zip name: ChromeExtensionBeta.zip path: ./builds/ChromeExtensionBeta.zip repo-token: ${{ secrets.GITHUB_TOKEN }} # Firefox Beta - name: Create Firefox Beta artifacts run: npm run build:firefox -- --env stream=beta --env autoupdate --env ghpSourceMaps - uses: actions/upload-artifact@v4 with: name: FirefoxExtensionBeta path: dist - name: Move Firefox Beta source maps to source map repo run: | VERSION=`jq -r '.version' ./dist/manifest.json` mkdir -p "./source-maps/firefox-beta/$VERSION/" mv -v ./dist/**/*.js.map "./source-maps/firefox-beta/$VERSION/" cp -v ./dist/**/*.js.LICENSE.txt "./source-maps/firefox-beta/$VERSION/" - name: Zip Artifacts run: cd ./dist ; zip -r ../builds/FirefoxExtensionBeta.zip * # Create Firefox Signed Beta version - name: Create Firefox Signed Beta artifacts run: npm run web-sign env: WEB_EXT_API_KEY: ${{ secrets.WEB_EXT_API_KEY }} WEB_EXT_API_SECRET: ${{ secrets.WEB_EXT_API_SECRET }} - name: Rename signed file run: mv ./web-ext-artifacts/* ./web-ext-artifacts/FirefoxSignedInstaller.xpi - uses: actions/upload-artifact@v4 with: name: FirefoxExtensionSigned.xpi path: ./web-ext-artifacts/FirefoxSignedInstaller.xpi - name: Upload FirefoxSignedInstaller.xpi to release uses: Shopify/upload-to-release@07611424e04f1475ddf550e1c0dd650b867d5467 with: args: web-ext-artifacts/FirefoxSignedInstaller.xpi name: FirefoxSignedInstaller.xpi path: ./web-ext-artifacts/FirefoxSignedInstaller.xpi repo-token: ${{ secrets.GITHUB_TOKEN }} - name: Commit & push new source maps if: always() run: | VERSION=`jq -r '.version' ./dist/manifest.json` cd ./source-maps git add . git commit -m "Publish source maps for version $VERSION" git push - name: Prepare new github pages deployment shell: python run: | from pathlib import Path import json import shutil import os # config stuff installer_name = "FirefoxSignedInstaller.xpi" owner, repo_name = os.environ["GITHUB_REPOSITORY"].split("/") owner = owner.lower() # create the github paged dir ghp_dir = Path("./github-pages") ghp_dir.mkdir(parents=True, exist_ok=True) # move in the installer Path("./web-ext-artifacts", installer_name).rename(ghp_dir / installer_name) # read manifest.json and extract parameters with open("./dist/manifest.json") as f: manifest = json.load(f) current_version = manifest["version"] ext_id = manifest["browser_specific_settings"]["gecko"]["id"] # generate updates file updates = { "addons": { ext_id: { "updates": [ { "version": current_version, # param doesn't actually matter, it's just a cachebuster "update_link": f"https://{owner}.github.io/{repo_name}/{installer_name}?v={current_version}", }, ], }, }, } (ghp_dir / "updates.json").write_text(json.dumps(updates)) # copy in source maps def only_sourcemaps(cur, ls): if '/' in cur: return [] return set(ls) - {"chrome", "chrome-beta", "edge", "firefox", "firefox-beta", "safari"} shutil.copytree("source-maps", ghp_dir, ignore=only_sourcemaps, dirs_exist_ok=True) - name: Upload new github pages deployment uses: actions/upload-pages-artifact@v3 with: path: ./github-pages deploy-ghp: name: Deploy to github pages needs: build permissions: id-token: write pages: write environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} runs-on: ubuntu-latest steps: - name: Deploy id: deployment uses: actions/deploy-pages@v4 ================================================ FILE: .github/workflows/take-action.yml ================================================ # .github/workflows/take.yml name: Assign issue to contributor on: issue_comment: jobs: assign: name: Take an issue runs-on: ubuntu-latest steps: - name: take the issue uses: bdougie/take-action@28b86cd8d25593f037406ecbf96082db2836e928 env: GITHUB_TOKEN: ${{ github.token }} ================================================ FILE: .github/workflows/tests.yml ================================================ name: Tests on: [push, pull_request] jobs: test: name: Run tests runs-on: ubuntu-latest steps: # Initialization - uses: actions/checkout@v4 with: submodules: recursive - uses: actions/setup-node@v4 with: node-version: '18' - run: npm ci - name: Copy configuration run: cp config.json.example config.json - name: Set up WireGuard Connection uses: niklaskeerl/easy-wireguard-action@50341d5f4b8245ff3a90e278aca67b2d283c78d0 with: WG_CONFIG_FILE: ${{ secrets.WG_CONFIG_FILE }} - name: Run tests run: npm run test - name: Upload results on fail if: ${{ failure() }} uses: actions/upload-artifact@v4 with: name: Test Results path: ./test-results ================================================ FILE: .github/workflows/update-oss-attribution.yml ================================================ name: update oss attributions on: push: branches: - master paths: - 'package.json' - 'package-lock.json' workflow_dispatch: jobs: update-oss: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: submodules: recursive - uses: actions/setup-node@v4 with: node-version: '18' - name: Install and generate attribution run: | npm ci npm i -g oss-attribution-generator generate-attribution mv ./oss-attribution/attribution.txt ./public/oss-attribution/attribution.txt - name: Prettify attributions run: | cd ci && npx ts-node prettify.ts - name: Create pull request to update list uses: peter-evans/create-pull-request@v7 # v4.2.3 with: commit-message: Update OSS Attribution author: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> branch: ci/oss_attribution title: Update OSS Attribution body: Automated OSS Attribution update ================================================ FILE: .github/workflows/updateInvidous.yml ================================================ name: update invidious on: workflow_dispatch: schedule: - cron: '0 0 1 * *' # check every month jobs: check-list: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: submodules: recursive - name: Download instance lists run: | wget https://api.invidious.io/instances.json -O ci/invidious_instances.json wget https://github.com/TeamPiped/piped-uptime/raw/master/history/summary.json -O ci/piped_instances.json - name: Install dependencies run: npm ci - name: "Run CI" run: npm run ci:invidious - name: Create pull request to update list uses: peter-evans/create-pull-request@v7 # v4.2.3 with: commit-message: Update Invidious List author: github-actions[bot] branch: ci/update_invidious_list title: Update Invidious List body: Automated Invidious list update ================================================ FILE: .gitignore ================================================ config.json ignored .idea/ node_modules web-ext-artifacts .vscode/ dist/ tmp/ .DS_Store ci/invidious_instances.json ci/piped_instances.json test-results ================================================ FILE: .gitmodules ================================================ [submodule "public/_locales"] path = public/_locales url = https://github.com/ajayyy/ExtensionTranslations [submodule "maze-utils"] path = maze-utils url = https://github.com/ajayyy/maze-utils ================================================ FILE: CONTRIBUTING.md ================================================ If you make any contributions to SponsorBlock after this file was created, you are agreeing that any code you have contributed will be licensed under GPL-3.0 and agree to allow distribution on app stores as outlined in LICENSE-APPSTORE. # Translations https://crowdin.com/project/sponsorblock # Building ## Building locally 0. You must have [Node.js 22 or later](https://nodejs.org/) and npm installed. Works best on Linux 1. Clone with submodules ```bash git clone --recursive https://github.com/ajayyy/SponsorBlock ``` Or if you already cloned it, pull submodules with ```bash git submodule update --init --recursive ``` 2. Copy the file `config.json.example` to `config.json` and adjust configuration as desired. - Comments are invalid in JSON, make sure they are all removed. - You will need to repeat this step in the future if you get build errors related to `CompileConfig` or `property does not exist on type ConfigClass`. This can happen for example when a new category is added. 3. Run `npm ci` in the repository to install dependencies. 4. Run `npm run build:dev` (for Chrome) or `npm run build:dev:firefox` (for Firefox) to generate a development version of the extension with source maps. - You can also run `npm run build` (for Chrome) or `npm run build:firefox` (for Firefox) to generate a production build. 5. The built extension is now in `dist/`. You can load this folder directly in Chrome as an [unpacked extension](https://developer.chrome.com/docs/extensions/mv3/getstarted/#manifest), or convert it to a zip file to load it as a [temporary extension](https://developer.mozilla.org/docs/Tools/about:debugging#loading_a_temporary_extension) in Firefox. ## Developing with a clean profile and hot reloading Run `npm run dev` (for Chrome) or `npm run dev:firefox` (for Firefox) to run the extension using a clean browser profile with hot reloading. This uses [`web-ext run`](https://extensionworkshop.com/documentation/develop/web-ext-command-reference/#commands). Known chromium bug: Extension is not loaded properly on first start. Visit `chrome://extensions/` and reload the extension. For Firefox for Android, use `npm run dev:firefox-android -- --adb-device `. See the [Firefox documentation](https://extensionworkshop.com/documentation/develop/developing-extensions-for-firefox-for-android/#debug-your-extension) for more information. You may need to edit package.json and add the parameters directly there. ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: LICENSE-APPSTORE.txt ================================================ The developers are aware that the terms of service that apply to apps distributed via Apple's App Store services and similar app stores may conflict with rights granted under the SponsorBlock license, the GNU General Public License, version 3. The copyright holders of the SponsorBlock project do not wish this conflict to prevent the otherwise-compliant distribution of derived apps via the App Store and similar app stores. Therefore, we have committed not to pursue any license violation that results solely from the conflict between the GNU GPLv3 and the Apple App Store terms of service or similar app stores. In other words, as long as you comply with the GPL in all other respects, including its requirements to provide users with source code and the text of the license, we will not object to your distribution of the SponsorBlock project through the App Store. ================================================ FILE: LICENSE-HISTORY.txt ================================================ Prior to commit 7338af3b384e2297eaf710443121ac840099a9f1, this project was licensed under LGPL 3.0. You must follow LICENSE instead if you want to use any newer version. ---- GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. ================================================ FILE: README.md ================================================

Logo
Logo by @munadikieh

SponsorBlock

Download: Chrome/Chromium | Firefox | Android | Edge | Safari for MacOS and iOS | Website | Stats

3rd-Party Ports: MPV | Kodi | Chromecast | iOS

Badge Badge Badge Badge Badge

SponsorBlock is an open-source crowdsourced browser extension to skip sponsor segments in YouTube videos. Users submit when a sponsor happens from the extension, and the extension automatically skips sponsors it knows about. It also supports skipping other categories, such as intros, outros and reminders to subscribe. It also supports Invidious. **Translate:** [![Crowdin](https://badges.crowdin.net/sponsorblock/localized.svg)](https://crowdin.com/project/sponsorblock) # Important Links See the [Wiki](https://github.com/ajayyy/SponsorBlock/wiki) for important links. # Server The backend server code is available here: https://github.com/ajayyy/SponsorBlockServer To make sure that this project doesn't die, I have made the database publicly downloadable at https://sponsor.ajay.app/database ([License](https://github.com/ajayyy/SponsorBlock/wiki/Database-and-API-License)). If you are planning on using the database in another project, please read the [API Docs](https://wiki.sponsor.ajay.app/index.php/API_Docs) page for more information. The dataset and API are now being used in some [ports](https://github.com/ajayyy/SponsorBlock/wiki/3rd-Party-Ports) as well as a [neural network](https://github.com/andrewzlee/NeuralBlock). # API You can read the API docs [here](https://wiki.sponsor.ajay.app/w/API_Docs). # Building See [CONTRIBUTING.md](CONTRIBUTING.md) # Credit The awesome [Invidious API](https://docs.invidious.io/) was previously used, and the server is now using [NewLeaf](https://git.sr.ht/~cadence/NewLeaf) to get video info from YouTube. Originally forked from [YTSponsorSkip](https://github.com/NDevTK/YTSponsorSkip), but very little code remains. Icons made by: * Gregor Cresnar from www.flaticon.com and are licensed by CC 3.0 BY * Freepik from www.flaticon.com and are licensed by CC 3.0 BY * Alexander Kahlkopf from iconmonstr.com and are licensed by iconmonstr License ### License This project is licensed under GNU GPL v3 or any later version ================================================ FILE: ci/generateList.ts ================================================ /* This file is only ran by GitHub Actions in order to populate the Invidious instances list This file should not be shipped with the extension */ /* Criteria for inclusion: Invidious - uptime >= 80% - must have been up for at least 90 days - HTTPS only - url includes name (this is to avoid redirects) Piped - 30d uptime >= 90% - available for at least 80/90 days - must have been up for at least 90 days - must not be a wildcard redirect to piped.video - must be currently up - must have a functioning frontend - must have a functioning API */ import { writeFile, existsSync } from "fs" import { join } from "path" import { getInvidiousList } from "./invidiousCI"; // import { getPipedList } from "./pipedCI"; const checkPath = (path: string) => existsSync(path); const fixArray = (arr: string[]) => [...new Set(arr)].sort() async function generateList() { // import file from https://api.invidious.io/instances.json const invidiousPath = join(__dirname, "invidious_instances.json"); // import file from https://github.com/TeamPiped/piped-uptime/raw/master/history/summary.json const pipedPath = join(__dirname, "piped_instances.json"); // check if files exist if (!checkPath(invidiousPath) || !checkPath(pipedPath)) { console.log("Missing files") process.exit(1); } // static non-invidious instances const staticInstances = ["www.youtubekids.com"]; // invidious instances const invidiousList = fixArray(getInvidiousList()) // piped instnaces // const pipedList = fixArray(await getPipedList()) console.log([...staticInstances, ...invidiousList]) writeFile( join(__dirname, "./invidiouslist.json"), JSON.stringify([...staticInstances, ...invidiousList]), (err) => { if (err) return console.log(err); } ); } generateList() ================================================ FILE: ci/invidiousCI.ts ================================================ import { InvidiousInstance, monitor } from "./invidiousType" import * as data from "../ci/invidious_instances.json"; // only https servers const mapped = (data as InvidiousInstance[]) .filter((i) => i[1]?.type === "https" && i[1]?.monitor?.enabled ) .map((instance) => { const monitor = instance[1].monitor as monitor; return { name: instance[0], url: instance[1].uri, uptime: monitor.uptime || 0, down: monitor.down ?? false, created_at: monitor.created_at, } }); // reliability and sanity checks const reliableCheck = mapped .filter(instance => { const uptime = instance.uptime > 80 && !instance.down; const nameIncluded = instance.url.includes(instance.name); const ninetyDays = 90 * 24 * 60 * 60 * 1000; const ninetyDaysAgo = new Date(Date.now() - ninetyDays); const createdAt = new Date(instance.created_at).getTime() < ninetyDaysAgo.getTime(); return uptime && nameIncluded && createdAt; }) export const getInvidiousList = (): string[] => reliableCheck.map(instance => instance.name).sort() ================================================ FILE: ci/invidiousType.ts ================================================ export type InvidiousInstance = [ string, { flag: string; region: string; stats: null | ivStats; cors: null | boolean; api: null | boolean; type: "https" | "http" | "onion" | "i2p"; uri: string; monitor: null | monitor; } ] export type monitor = { token: string; url: string; alias: string; last_status: number; uptime: number; down: boolean; down_since: null | string; up_since: null | string; error: null | string; period: number; apdex_t: number; string_match: string; enabled: boolean; published: boolean; disabled_locations: string[]; recipients: string[]; last_check_at: string; next_check_at: string; created_at: string; mute_until: null | string; favicon_url: string; custom_headers: Record; http_verb: string; http_body: string; ssl: { tested_at: string; expires_at: string; valid: boolean; error: null | string; }; } export type ivStats = { version: string; software: { name: "invidious" | string; version: string; branch: "master" | string; }; openRegistrations: boolean; usage: { users: { total: number; activeHalfyear: number; activeMonth: number; }; }; metadata: { updatedAt: number; lastChannelRefreshedAt: number; }; playback: { totalRequests: number; successfulRequests: number; ratio: number; }; } ================================================ FILE: ci/invidiouslist.json ================================================ ["www.youtubekids.com","inv.nadeko.net","inv.tux.pizza","invidious.adminforge.de","invidious.jing.rocks","invidious.nerdvpn.de","invidious.perennialte.ch","invidious.privacyredirect.com","invidious.reallyaweso.me","invidious.yourdevice.ch","iv.ggtyler.dev","iv.nboeck.de","yewtu.be"] ================================================ FILE: ci/pipedCI.ts ================================================ import * as data from "../ci/piped_instances.json"; type percent = string type dailyMinutesDown = Record type PipedInstance = { name: string; url: string; icon: string; slug: string; status: string; uptime: percent; uptimeDay: percent; uptimeWeek: percent; uptimeMonth: percent; uptimeYear: percent; time: number; timeDay: number; timeWeek: number; timeMonth: number; timeYear: number; dailyMinutesDown: dailyMinutesDown } const percentNumber = (percent: percent) => Number(percent.replace("%", "")) const ninetyDaysAgo = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000) function dailyMinuteFilter (dailyMinutesDown: dailyMinutesDown) { let daysDown = 0 for (const [date, minsDown] of Object.entries(dailyMinutesDown)) { if (new Date(date) >= ninetyDaysAgo && minsDown > 1000) { // if within 90 days and down for more than 1000 minutes daysDown++ } } // return true f less than 10 days down return daysDown < 10 } const getHost = (url: string) => new URL(url).host const getWatchPage = async (instance: PipedInstance) => fetch(`https://${getHost(instance.url)}`, { redirect: "manual" }) .then(res => res.headers.get("Location")) .catch(e => { console.log (e); return null }) const siteOK = async (instance) => { // check if entire site is redirect const notRedirect = await fetch(instance.url, { redirect: "manual" }) .then(res => res.status == 200) // only allow kavin to return piped.video // if (instance.url.startsWith("https://piped.video") && instance.slug !== "kavin-rocks-official") return false // check if frontend is OK const watchPageStatus = await fetch(instance.frontendUrl) .then(res => res.ok) // test API - stream returns ok result const streamStatus = await fetch(`${instance.apiUrl}/streams/BaW_jenozKc`) .then(res => res.ok) // get startTime of monitor const age = await fetch(instance.historyUrl) .then(res => res.text()) .then(text => { // startTime greater than 90 days ago const date = text.match(/startTime: (.+)/)[1] return Date.parse(date) < ninetyDaysAgo.valueOf() }) // console.log(notRedirect, watchPageStatus, streamStatus, age, instance.frontendUrl, instance.apiUrl) return notRedirect && watchPageStatus && streamStatus && age } const staticFilters = (data as PipedInstance[]) .filter(instance => { const isup = instance.status === "up" const monthCheck = percentNumber(instance.uptimeMonth) >= 90 const dailyMinuteCheck = dailyMinuteFilter(instance.dailyMinutesDown) return isup && monthCheck && dailyMinuteCheck }) .map(async instance => { // get frontend url const frontendUrl = await getWatchPage(instance) if (!frontendUrl) return null // return false if frontend doesn't resolve // get api base const apiUrl = instance.url.replace("/healthcheck", "") const historyUrl = `https://raw.githubusercontent.com/TeamPiped/piped-uptime/master/history/${instance.slug}.yml` const pass = await siteOK({ apiUrl, historyUrl, frontendUrl, url: instance.url }) const frontendHost = getHost(frontendUrl) return pass ? frontendHost : null }) export async function getPipedList(): Promise { const instances = await Promise.all(staticFilters) .then(arr => arr.filter(i => i !== null)) return instances } ================================================ FILE: ci/prettify.ts ================================================ import { writeFile } from 'fs'; import * as license from "../oss-attribution/licenseInfos.json"; const result = JSON.stringify(license, null, 2); writeFile("../oss-attribution/licenseInfos.json", result, err => { if (err) return console.log(err) } ); ================================================ FILE: config.json.example ================================================ { "serverAddress": "https://sponsor.ajay.app", "testingServerAddress": "https://sponsor.ajay.app/test", "serverAddressComment": "This specifies the default SponsorBlock server to connect to", "categoryList": ["sponsor", "selfpromo", "exclusive_access", "interaction", "poi_highlight", "intro", "outro", "preview", "hook", "filler", "chapter", "music_offtopic"], "categorySupport": { "sponsor": ["skip", "mute", "full"], "selfpromo": ["skip", "mute", "full"], "exclusive_access": ["full"], "interaction": ["skip", "mute"], "intro": ["skip", "mute"], "outro": ["skip", "mute"], "preview": ["skip", "mute"], "hook": ["skip", "mute"], "filler": ["skip", "mute"], "music_offtopic": ["skip"], "poi_highlight": ["poi"], "chapter": ["chapter"] }, "wikiLinks": { "sponsor": "https://wiki.sponsor.ajay.app/w/Sponsor", "selfpromo": "https://wiki.sponsor.ajay.app/w/Unpaid/Self_Promotion", "exclusive_access": "https://wiki.sponsor.ajay.app/w/Exclusive_Access", "interaction": "https://wiki.sponsor.ajay.app/w/Interaction_Reminder_(Subscribe)", "intro": "https://wiki.sponsor.ajay.app/w/Intermission/Intro_Animation", "outro": "https://wiki.sponsor.ajay.app/w/Endcards/Credits", "preview": "https://wiki.sponsor.ajay.app/w/Preview/Recap", "hook": "https://wiki.sponsor.ajay.app/w/Hook/Greetings", "filler": "https://wiki.sponsor.ajay.app/w/Tangents/Jokes", "music_offtopic": "https://wiki.sponsor.ajay.app/w/Music:_Non-Music_Section", "poi_highlight": "https://wiki.sponsor.ajay.app/w/Highlight", "guidelines": "https://wiki.sponsor.ajay.app/w/Guidelines", "mute": "https://wiki.sponsor.ajay.app/w/Mute_Segment", "chapter": "https://wiki.sponsor.ajay.app/w/Chapter" }, "extensionImportList": { "chromium": [ "enamippconapkdmgfgjchkhakpfinmaj" ], "firefox": [ "deArrow@ajay.app", "deArrowBETA@ajay.app" ], "safari": [ "app.ajay.dearrow.extension" ] } } ================================================ FILE: crowdin.yml ================================================ files: - source: /public/_locales/en/* translation: /public/_locales/%two_letters_code%/%original_file_name% ================================================ FILE: jest.config.js ================================================ module.exports = { "roots": [ "test" ], "transform": { "^.+\\.ts$": "ts-jest" }, "reporters": ["default", "github-actions"] }; ================================================ FILE: manifest/beta-manifest-extra.json ================================================ { "name": "BETA - SponsorBlock" } ================================================ FILE: manifest/chrome-manifest-extra.json ================================================ { "host_permissions": [ "https://*.youtube.com/*", "https://sponsor.ajay.app/*" ], "optional_host_permissions": [ "*://*/*" ], "web_accessible_resources": [{ "resources": [ "icons/LogoSponsorBlocker256px.png", "icons/IconSponsorBlocker256px.png", "icons/PlayerStartIconSponsorBlocker.svg", "icons/PlayerStopIconSponsorBlocker.svg", "icons/PlayerUploadIconSponsorBlocker.svg", "icons/PlayerUploadFailedIconSponsorBlocker.svg", "icons/PlayerCancelSegmentIconSponsorBlocker.svg", "icons/clipboard.svg", "icons/settings.svg", "icons/pencil.svg", "icons/check.svg", "icons/check-smaller.svg", "icons/upvote.png", "icons/downvote.png", "icons/thumbs_down.svg", "icons/thumbs_down_locked.svg", "icons/thumbs_up.svg", "icons/help.svg", "icons/report.png", "icons/close.png", "icons/skipIcon.svg", "icons/refresh.svg", "icons/beep.oga", "icons/pause.svg", "icons/stop.svg", "icons/skip.svg", "icons/heart.svg", "icons/visible.svg", "icons/not_visible.svg", "icons/sort.svg", "icons/money.svg", "icons/segway.png", "icons/close-smaller.svg", "icons/right-arrow.svg", "icons/campaign.svg", "icons/star.svg", "icons/lightbulb.svg", "icons/bolt.svg", "icons/stopwatch.svg", "icons/music-note.svg", "icons/import.svg", "icons/export.svg", "icons/PlayerInfoIconSponsorBlocker.svg", "icons/PlayerDeleteIconSponsorBlocker.svg", "icons/dearrow.svg", "icons/sb-pride.png", "icons/pride.svg", "popup.html", "popup.css", "content.css", "shared.css", "js/document.js", "libs/Source+Sans+Pro.css", "libs/6xKydSBYKcSV-LCoeQqfX1RYOo3ig4vwlxdu.woff2", "libs/6xKydSBYKcSV-LCoeQqfX1RYOo3ig4vwmRduz8A.woff2", "libs/6xKydSBYKcSV-LCoeQqfX1RYOo3ig4vwmBduz8A.woff2", "libs/6xKydSBYKcSV-LCoeQqfX1RYOo3ig4vwlBduz8A.woff2" ], "matches": [""] }], "content_scripts": [ { "world": "MAIN", "js": [ "./js/document.js" ], "matches": [ "https://*.youtube.com/*", "https://www.youtube-nocookie.com/embed/*" ], "exclude_matches": [ "https://accounts.youtube.com/RotateCookiesPage*" ], "all_frames": true, "run_at": "document_start" }, { "world": "ISOLATED", "js": [ "./js/content.js" ], "css": [ "content.css", "shared.css" ], "matches": [ "https://*.youtube.com/*", "https://www.youtube-nocookie.com/embed/*" ], "exclude_matches": [ "https://accounts.youtube.com/RotateCookiesPage*" ], "all_frames": true, "run_at": "document_start" } ], "action": { "default_title": "SponsorBlock", "default_popup": "popup.html", "default_icon": { "16": "icons/IconSponsorBlocker16px.png", "32": "icons/IconSponsorBlocker32px.png", "64": "icons/IconSponsorBlocker64px.png", "128": "icons/IconSponsorBlocker128px.png" }, "theme_icons": [ { "light": "icons/IconSponsorBlocker16px.png", "dark": "icons/IconSponsorBlocker16px.png", "size": 16 }, { "light": "icons/IconSponsorBlocker32px.png", "dark": "icons/IconSponsorBlocker32px.png", "size": 32 }, { "light": "icons/IconSponsorBlocker64px.png", "dark": "icons/IconSponsorBlocker64px.png", "size": 64 }, { "light": "icons/IconSponsorBlocker128px.png", "dark": "icons/IconSponsorBlocker128px.png", "size": 128 }, { "light": "icons/IconSponsorBlocker256px.png", "dark": "icons/IconSponsorBlocker256px.png", "size": 256 }, { "light": "icons/IconSponsorBlocker512px.png", "dark": "icons/IconSponsorBlocker512px.png", "size": 512 }, { "light": "icons/IconSponsorBlocker1024px.png", "dark": "icons/IconSponsorBlocker1024px.png", "size": 1024 } ] }, "background": { "service_worker": "./js/background.js" }, "manifest_version": 3 } ================================================ FILE: manifest/firefox-beta-manifest-extra.json ================================================ { "browser_specific_settings": { "gecko": { "id": "sponsorBlockerBETA@ajay.app" } } } ================================================ FILE: manifest/firefox-manifest-extra.json ================================================ { "browser_specific_settings": { "gecko": { "id": "sponsorBlocker@ajay.app", "strict_min_version": "102.0" }, "gecko_android": { "strict_min_version": "113.0" } }, "background": { "persistent": false }, "browser_action": { "default_area": "navbar" } } ================================================ FILE: manifest/manifest-v2-extra.json ================================================ { "web_accessible_resources": [ "icons/LogoSponsorBlocker256px.png", "icons/IconSponsorBlocker256px.png", "icons/PlayerStartIconSponsorBlocker.svg", "icons/PlayerStopIconSponsorBlocker.svg", "icons/PlayerUploadIconSponsorBlocker.svg", "icons/PlayerUploadFailedIconSponsorBlocker.svg", "icons/PlayerCancelSegmentIconSponsorBlocker.svg", "icons/clipboard.svg", "icons/settings.svg", "icons/pencil.svg", "icons/check.svg", "icons/check-smaller.svg", "icons/upvote.png", "icons/downvote.png", "icons/thumbs_down.svg", "icons/thumbs_down_locked.svg", "icons/thumbs_up.svg", "icons/help.svg", "icons/report.png", "icons/close.png", "icons/skipIcon.svg", "icons/refresh.svg", "icons/beep.oga", "icons/pause.svg", "icons/stop.svg", "icons/skip.svg", "icons/heart.svg", "icons/visible.svg", "icons/not_visible.svg", "icons/sort.svg", "icons/money.svg", "icons/segway.png", "icons/close-smaller.svg", "icons/right-arrow.svg", "icons/campaign.svg", "icons/star.svg", "icons/lightbulb.svg", "icons/bolt.svg", "icons/stopwatch.svg", "icons/music-note.svg", "icons/import.svg", "icons/export.svg", "icons/PlayerInfoIconSponsorBlocker.svg", "icons/PlayerDeleteIconSponsorBlocker.svg", "icons/dearrow.svg", "icons/sb-pride.png", "icons/pride.svg", "popup.html", "popup.css", "content.css", "shared.css", "js/document.js", "libs/Source+Sans+Pro.css", "libs/6xKydSBYKcSV-LCoeQqfX1RYOo3ig4vwlxdu.woff2", "libs/6xKydSBYKcSV-LCoeQqfX1RYOo3ig4vwmRduz8A.woff2", "libs/6xKydSBYKcSV-LCoeQqfX1RYOo3ig4vwmBduz8A.woff2", "libs/6xKydSBYKcSV-LCoeQqfX1RYOo3ig4vwlBduz8A.woff2" ], "permissions": [ "https://sponsor.ajay.app/*" ], "optional_permissions": [ "*://*/*" ], "browser_action": { "default_title": "SponsorBlock", "default_popup": "popup.html", "default_icon": { "16": "icons/IconSponsorBlocker16px.png", "32": "icons/IconSponsorBlocker32px.png", "64": "icons/IconSponsorBlocker64px.png", "128": "icons/IconSponsorBlocker128px.png" }, "theme_icons": [ { "light": "icons/IconSponsorBlocker16px.png", "dark": "icons/IconSponsorBlocker16px.png", "size": 16 }, { "light": "icons/IconSponsorBlocker32px.png", "dark": "icons/IconSponsorBlocker32px.png", "size": 32 }, { "light": "icons/IconSponsorBlocker64px.png", "dark": "icons/IconSponsorBlocker64px.png", "size": 64 }, { "light": "icons/IconSponsorBlocker128px.png", "dark": "icons/IconSponsorBlocker128px.png", "size": 128 }, { "light": "icons/IconSponsorBlocker256px.png", "dark": "icons/IconSponsorBlocker256px.png", "size": 256 }, { "light": "icons/IconSponsorBlocker512px.png", "dark": "icons/IconSponsorBlocker512px.png", "size": 512 }, { "light": "icons/IconSponsorBlocker1024px.png", "dark": "icons/IconSponsorBlocker1024px.png", "size": 1024 } ] }, "background": { "scripts":[ "./js/background.js" ] }, "content_scripts": [{ "run_at": "document_start", "matches": [ "https://*.youtube.com/*", "https://www.youtube-nocookie.com/embed/*" ], "exclude_matches": [ "https://accounts.youtube.com/RotateCookiesPage*" ], "all_frames": true, "js": [ "./js/content.js" ], "css": [ "content.css", "shared.css" ] }], "manifest_version": 2 } ================================================ FILE: manifest/manifest.json ================================================ { "name": "__MSG_fullName__", "short_name": "SponsorBlock", "version": "6.1.2", "default_locale": "en", "description": "__MSG_Description__", "homepage_url": "https://sponsor.ajay.app", "icons": { "16": "icons/IconSponsorBlocker16px.png", "32": "icons/IconSponsorBlocker32px.png", "64": "icons/IconSponsorBlocker64px.png", "128": "icons/IconSponsorBlocker128px.png", "256": "icons/IconSponsorBlocker256px.png", "512": "icons/IconSponsorBlocker512px.png", "1024": "icons/IconSponsorBlocker1024px.png" }, "permissions": [ "storage", "scripting", "unlimitedStorage" ], "options_ui": { "page": "options/options.html", "open_in_tab": true } } ================================================ FILE: manifest/safari-manifest-extra.json ================================================ { "background": { "persistent": false }, "optional_permissions": [ "webNavigation" ], "browser_action": { "default_icon": { "16": "icons/SafariIconSponsorBlocker16px.png", "32": "icons/SafariIconSponsorBlocker32px.png", "64": "icons/SafariIconSponsorBlocker64px.png", "128": "icons/SafariIconSponsorBlocker128px.png" } }, "browser_specific_settings": { "safari": { "strict_min_version": "14.0" } } } ================================================ FILE: oss-attribution/licenseInfos.json ================================================ { "content-scripts-register-polyfill": { "ignore": false, "name": "content-scripts-register-polyfill", "version": "4.0.2", "authors": "Federico Brigante (https://fregante.com)", "url": "https://github.com/fregante/content-scripts-register-polyfill", "license": "MIT", "licenseText": "MIT License\n\nCopyright (c) Federico Brigante (https://fregante.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n" }, "escape-string-regexp": { "ignore": false, "name": "escape-string-regexp", "version": "5.0.0", "authors": "Sindre Sorhus ", "url": "https://github.com/sindresorhus/escape-string-regexp", "license": "MIT", "licenseText": "MIT License\n\nCopyright (c) Sindre Sorhus (https://sindresorhus.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n" }, "js-tokens": { "ignore": false, "name": "js-tokens", "version": "4.0.0", "authors": "Simon Lydell", "url": "https://github.com/lydell/js-tokens", "license": "MIT", "licenseText": "The MIT License (MIT)\n\nCopyright (c) 2014, 2015, 2016, 2017, 2018 Simon Lydell\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n" }, "loose-envify": { "ignore": false, "name": "loose-envify", "version": "1.4.0", "authors": "Andres Suarez ", "url": "https://github.com/zertosh/loose-envify", "license": "MIT", "licenseText": "The MIT License (MIT)\n\nCopyright (c) 2015 Andres Suarez \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n" }, "react-dom": { "ignore": false, "name": "react-dom", "version": "18.2.0", "url": "https://github.com/facebook/react", "license": "MIT", "licenseText": "MIT License\n\nCopyright (c) Facebook, Inc. and its affiliates.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n" }, "react": { "ignore": false, "name": "react", "version": "18.2.0", "url": "https://github.com/facebook/react", "license": "MIT", "licenseText": "MIT License\n\nCopyright (c) Facebook, Inc. and its affiliates.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n" }, "scheduler": { "ignore": false, "name": "scheduler", "version": "0.23.0", "url": "https://github.com/facebook/react", "license": "MIT", "licenseText": "MIT License\n\nCopyright (c) Facebook, Inc. and its affiliates.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n" }, "webext-content-scripts": { "ignore": false, "name": "webext-content-scripts", "version": "2.5.5", "authors": "Federico Brigante (https://fregante.com)", "url": "https://github.com/fregante/webext-content-scripts", "license": "MIT", "licenseText": "MIT License\n\nCopyright (c) Federico Brigante (https://fregante.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n" }, "webext-patterns": { "ignore": false, "name": "webext-patterns", "version": "1.3.0", "authors": "Federico Brigante (https://fregante.com)", "url": "https://github.com/fregante/webext-patterns", "license": "MIT", "licenseText": "MIT License\n\nCopyright (c) Federico Brigante (https://fregante.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n" }, "webext-polyfill-kinda": { "ignore": false, "name": "webext-polyfill-kinda", "version": "1.0.2", "authors": "Federico Brigante (https://fregante.com)", "url": "https://github.com/fregante/webext-polyfill-kinda", "license": "MIT", "licenseText": "MIT License\n\nCopyright (c) Federico Brigante (https://fregante.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n" } } ================================================ FILE: package.json ================================================ { "name": "sponsorblock", "version": "1.0.0", "description": "", "main": "background.js", "dependencies": { "content-scripts-register-polyfill": "^4.0.2", "react": "^18.2.0", "react-dom": "^18.2.0" }, "overrides": { "content-scripts-register-polyfill": { "webext-content-scripts": "v2.5.5" } }, "devDependencies": { "@types/chrome": "^0.0.220", "@types/firefox-webext-browser": "^111.0.0", "@types/jest": "^29.4.0", "@types/react": "^18.0.28", "@types/react-dom": "^18.0.11", "@types/selenium-webdriver": "^4.1.13", "@types/wicg-mediasession": "^1.1.4", "@typescript-eslint/eslint-plugin": "^5.54.1", "@typescript-eslint/parser": "^5.54.1", "chromedriver": "^140.0.0", "concurrently": "^7.6.0", "copy-webpack-plugin": "^11.0.0", "eslint": "^8.35.0", "eslint-plugin-react": "^7.32.2", "fork-ts-checker-webpack-plugin": "^7.3.0", "jest": "^29.5.0", "jest-environment-jsdom": "^30.2.0", "rimraf": "^4.3.1", "schema-utils": "^4.0.0", "selenium-webdriver": "^4.8.1", "ts-jest": "^29.0.5", "ts-loader": "^9.4.2", "ts-node": "^10.9.1", "typescript": "4.9", "web-ext": "^8.10.0", "webpack": "^5.105.0", "webpack-cli": "^4.10.0", "webpack-merge": "^5.8.0" }, "scripts": { "web-run": "npm run web-run:chrome", "web-sign": "web-ext sign --channel unlisted -s dist", "web-run:firefox": "cd dist && web-ext run --start-url https://addons.mozilla.org/firefox/addon/ublock-origin/", "web-run:firefox-android": "cd dist && web-ext run -t firefox-android --firefox-apk org.mozilla.fenix", "web-run:chrome": "cd dist && web-ext run --start-url https://chrome.google.com/webstore/detail/ublock-origin/cjpalhdlnbpafiamejdnhcphjbkeiagm -t chromium", "build": "npm run build:chrome", "build:chrome": "webpack --env browser=chrome --config webpack/webpack.prod.js", "build:firefox": "webpack --env browser=firefox --config webpack/webpack.prod.js", "build:safari": "webpack --env browser=safari --config webpack/webpack.prod.js", "build:edge": "webpack --env browser=edge --config webpack/webpack.prod.js", "build:dev": "npm run build:dev:chrome", "build:dev:chrome": "webpack --env browser=chrome --config webpack/webpack.dev.js", "build:dev:firefox": "webpack --env browser=firefox --config webpack/webpack.dev.js", "build:watch": "npm run build:watch:chrome", "build:watch:chrome": "webpack --env browser=chrome --config webpack/webpack.dev.js --watch", "build:watch:firefox": "webpack --env browser=firefox --config webpack/webpack.dev.js --watch", "ci:invidious": "ts-node ci/generateList.ts", "dev": "npm run build:dev && concurrently \"npm run web-run\" \"npm run build:watch\"", "dev:firefox": "npm run build:dev:firefox && concurrently \"npm run web-run:firefox\" \"npm run build:watch:firefox\"", "dev:firefox-android": "npm run build:dev:firefox && concurrently \"npm run web-run:firefox-android\" \"npm run build:watch:firefox\"", "clean": "rimraf dist", "test": "npm run build:chrome && npx jest", "test-without-building": "npx jest", "lint": "eslint src", "lint:fix": "eslint src --fix" }, "engines": { "node": ">=16" }, "funding": [ { "type": "individual", "url": "https://sponsor.ajay.app/donate" }, { "type": "github", "url": "https://github.com/sponsors/ajayyy-org" }, { "type": "patreon", "url": "https://www.patreon.com/ajayyy" }, { "type": "individual", "url": "https://paypal.me/ajayyy" } ], "repository": { "type": "git", "url": "git+https://github.com/ajayyy/SponsorBlock.git" }, "author": "Ajay Ramachandran", "license": "GPL-3.0", "private": true } ================================================ FILE: public/content.css ================================================ :root { --skip-notice-right: 10px; --skip-notice-padding: 5px; --skip-notice-margin: 5px; --skip-notice-border-horizontal: 5px; --skip-notice-border-vertical: 10px; --sb-dark-red-outline: rgb(130,0,0,0.9); } .sbhidden { display: none; } /* Vorapi compatibility */ #player-api_VORAPI_ELEMENT_ID #previewbar { z-index: 999; } #previewbar { overflow: visible; padding: 0; margin: 0; position: absolute; width: 100%; pointer-events: none; height: 100%; transform: scaleY(0.667) translateY(-30%) translateY(1.5px); z-index: 42; transition: transform .1s cubic-bezier(0,0,0.2,1); } /* Prevent bar from covering highlights on YTTV */ #previewbar.sponsorblock-yttv-container { z-index: unset; } ytu-time-bar.ytu-storyboard { text-align: center; } /* May 2024 hover preview */ .YtPlayerProgressBarProgressBar #previewbar { transform: none; } .ytp-big-mode #previewbar { transform: scaleY(0.625) translateY(-30%) translateY(1.5px); } .ytp-big-mode .sponsorTwoTooltips .sponsorCategoryTooltip { top: 75px !important; } .progress-bar-line > #previewbar { height: 3px; } div:hover > #previewbar.sbNotInvidious { transform: scaleY(1); } /* Vorapis */ .v3 #previewbar.sbNotInvidious { transform: scaleY(1); } .sponsorCategoryTooltipVisible.ytp-progress-tooltip { width: 216px !important; /* left: 264.308px !important; */ } .previewbar { display: inline-block; height: 100%; min-width: 1px; } .previewbar-yttv { height: 10px; top: 14px; } .previewbar.requiredSegment { transform: scaleY(3); } .previewbar.selectedSegment { opacity: 1 !important; z-index: 100; transform: scaleY(1.5); } /* Make sure settings are upfront */ .ytp-settings-menu { z-index: 6000 !important; } /* Preview Bar page hacks */ .ytp-tooltip:not(.sponsorCategoryTooltipVisible) .sponsorCategoryTooltip { display: none !important; } /* Pull up for precise seeking */ .ytp-tooltip.sponsorCategoryTooltipVisible .ytp-tooltip-edu { transform: translateY(-1em) !important; } .ytp-tooltip.sponsorCategoryTooltipVisible { transform: translateY(-1em) !important; } .ytp-tooltip.sponsorCategoryTooltipVisible.sponsorTwoTooltips { transform: translateY(-2em) !important; } .ytp-tooltip.sponsorCategoryTooltipVisible.sponsorHasOriginalTooltip { transform: translateY(-2em) !important; } .ytp-tooltip.sponsorCategoryTooltipVisible.sponsorTwoTooltips.sponsorHasOriginalTooltip { transform: translateY(-3em) !important; } .ytp-big-mode .ytp-tooltip.sponsorCategoryTooltipVisible { transform: translateY(-2em) !important; } .ytp-big-mode .ytp-tooltip.sponsorCategoryTooltipVisible.sponsorTwoTooltips { transform: translateY(-4em) !important; } #movie_player:not(.ytp-big-mode) .ytp-tooltip.sponsorCategoryTooltipVisible > .ytp-tooltip-text-wrapper { transform: translateY(1em) !important; } #movie_player:not(.ytp-big-mode) .ytp-tooltip.sponsorCategoryTooltipVisible.sponsorTwoTooltips > .ytp-tooltip-text-wrapper { transform: translateY(2em) !important; } /* Pull up for precise seeking */ .ytp-tooltip.sponsorCategoryTooltipVisible.sponsorTwoTooltips .ytp-tooltip-edu { transform: translateY(-2em) !important; } .ytp-big-mode .ytp-tooltip.sponsorCategoryTooltipVisible > .ytp-tooltip-text-wrapper { transform: translateY(0.5em) !important; } .ytp-big-mode .ytp-tooltip.sponsorCategoryTooltipVisible.sponsorTwoTooltips > .ytp-tooltip-text-wrapper { transform: translateY(1.75em) !important; } .ytp-big-mode .ytp-tooltip.sponsorCategoryTooltipVisible > .ytp-tooltip-text-wrapper .ytp-tooltip-text { display: inline-block !important; transform: translateY(0.75em) !important; } .ytp-big-mode .ytp-tooltip.sponsorCategoryTooltipVisible.sponsorTwoTooltips > .ytp-tooltip-text-wrapper .ytp-tooltip-text { display: inline-block !important; transform: translateY(0.75em) !important; } div:hover > .sponsorBlockChapterBar { z-index: 41 !important; } /* */ .popup { z-index: 10; width: 100%; height: 500px; } .smallLink { font-size: 10px; text-decoration: underline; cursor: pointer; } .playerButtonImage { height: 60%; top: 0; bottom: 0; display: block; margin: auto; } .sbChapterVoteButton { padding: 0 !important; } .playerButton { vertical-align: top; } .playerButton.sbhidden:not(.autoHiding) { display: none !important; } /* Removes auto width from being a ytp-player-button */ .sbPlayerDownvote { width: auto !important; } /* Adds back the padding */ .sbPlayerDownvote svg { padding-right: 3.6px; } .sbButtonYTTV { padding-left: 5px !important; } /* YTTV only */ .ytu-player-controls > .skipButtonControlBarContainer > div { padding-left: 5px; align-content: center; } .autoHiding { overflow: visible !important; } .autoHiding:not(.sbhidden) { transform: translateX(0%) scale(1); /* opacity is from YouTube page */ transition: transform 0.2s, width 0.2s, opacity .1s cubic-bezier(0.4,0.0,1,1) !important; } .autoHiding.sbhidden { transform: translateX(100%) scale(0); /* opacity is from YouTube page */ transition: transform 0.2s, width 0.2s, opacity .1s cubic-bezier(0.4,0.0,1,1) !important; width: 0px !important; } .autoHiding.sbhidden.autoHideLeft { transform: translateX(-100%) scale(0); } .sponsorSkipObject { font-family: Roboto, Arial, Helvetica, sans-serif; margin-left: var(--skip-notice-margin); margin-right: var(--skip-notice-margin); } .sponsorSkipObjectFirst { margin-left: 0; } .sponsorSkipLogo { height: 18px; float: left; } #categoryPill .sbPillNoText .sponsorSkipLogo { margin-top: calc(2.6rem - 18px); margin-bottom: calc(2.6rem - 18px); } @keyframes fadeIn { from { opacity: 0; } } @keyframes fadeInToFaded { from { opacity: 0; } to { opacity: 0.5; } } @keyframes fadeOut { to { opacity: 0; } } .sponsorBlockSpacer { background-color: rgb(100, 100, 100); border-color: rgb(100, 100, 100); margin-left: 5px; } .sbChatNotice { min-width: 350px; height: 70%; position: absolute; right: 5px; bottom: 100px; right: var(--skip-notice-right); } .sponsorSkipNoticeParent { position: absolute; bottom: 100px; right: 10px; } .sponsorSkipNoticeParent, .sponsorSkipNotice { border-spacing: 5px 10px; padding-left: 5px; padding-right: 5px; border-collapse: unset; } .sponsorSkipNotice { width: 100%; } .sponsorSkipNoticeTableContainer { color: white; background-color: rgba(28, 28, 28, 0.9); border-radius: 5px; min-width: 100%; } .exportCopiedNotice .sponsorSkipNoticeTableContainer { background-color: transparent; } .sponsorSkipNotice { transition: all 0.1s ease-out; } .sponsorSkipNoticeLimitWidth { max-width: calc(100% - 50px); } .sponsorSkipNotice .sbhidden { display: none; } /* For Cloudtube */ .sponsorSkipNotice td, .sponsorSkipNotice table, .sponsorSkipNotice th { border: none; } .sponsorSkipNoticeFadeIn { animation: fadeIn 0.5s ease-out; } .sponsorSkipNoticeFadeIn.sponsorSkipNoticeFaded { animation: fadeInToFaded 0.5s ease-out; } .exportCopiedNotice .sponsorSkipNoticeFadeIn { animation: none; } .sponsorSkipNoticeFaded { opacity: 0.5; } .sponsorSkipNoticeFadeOut { transition: opacity 3s cubic-bezier(0.55, 0.055, 0.675, 0.19); opacity: 0 !important; animation: none !important; } .sponsorSkipNotice .sponsorSkipNoticeTimeLeft { color: #eeeeee; border-radius: 4px; padding: 2px 5px; font-size: 12px; display: flex; align-items: center; border: 1px solid #eeeeee; } .sponsorSkipNoticeTimeLeft img { vertical-align: middle; height: 13px; padding-top: 7.8%; padding-bottom: 7.8%; } .noticeLeftIcon { display: flex; align-items: center; } .sponsorSkipNotice .sponsorSkipNoticeUnskipSection { float: left; border-left: 1px solid rgb(150, 150, 150); } .sponsorSkipNoticeButton { background: none; color: rgb(235, 235, 235); border: none; display: inline-block; font-size: 13.3333px !important; cursor: pointer; margin-right: 10px; padding: 2px 5px; } .sponsorSkipNoticeButton:hover { background-color: rgba(235, 235, 235,0.2); border-radius: 4px; transition: background-color 0.4s; } .sponsorTimesVoteButtonsContainer { float: left; vertical-align:middle; padding: 2px 5px; margin-right: 4px; } .sponsorTimesVoteButtonsContainer div{ display: inline-block; } .sponsorSkipNoticeRightSection { right: 0; position: absolute; float: right; margin-right: 10px; display: flex; align-items: center; } .sponsorSkipNoticeRightButton { margin-right: 0; } .sponsorSkipNoticeCloseButton { height: 10px; width: 10px; box-sizing: unset; padding: 2px 5px; margin-left: 2px; float: right; } .sponsorSkipNoticeCloseButton.biggerCloseButton { padding: 20px; } .sponsorSkipMessage { font-size: 14px; font-weight: bold; color: rgb(235, 235, 235); margin-top: auto; display: inline-block; margin-right: 10px; margin-bottom: auto; } .sponsorSkipInfo { font-size: 10px; color: #000000; text-align: center; margin-top: 0px; } #sponsorTimesThanksForVotingText { font-size: 20px; font-weight: bold; color: #000000; text-align: center; margin-top: 0px; margin-bottom: 0px; } #sponsorTimesThanksForVotingInfoText { font-size: 12px; font-weight: bold; color: #000000; text-align: center; margin-top: 0px; } .sponsorTimesVoteButtonMessage { float: left; } .sponsorTimesInfoMessage { font-size: 13.3333px; color: rgb(235, 235, 235); overflow-wrap: anywhere; } .sb-guidelines-notice .sponsorTimesInfoMessage td { padding-left: 5px; padding-top: 2px; padding-bottom: 2px; font-size: 15px; display: flex; align-items: center; } .sponsorTimesInfoIcon { width: 30px; padding-right: 10px; padding-left: 10px; } .segmentSummary { outline: none !important; } .submitButton { background-color:#ec1c1c; -moz-border-radius:28px; -webkit-border-radius:28px; border-radius:28px; border:1px solid #d31919; display:inline-block; cursor:pointer; color:#ffffff; font-size:14px; padding:4px 15px; text-decoration:none; text-shadow:0px 0px 0px #662727; margin-top: 5px; margin-right: 15px; } .submitButton:hover { background-color:#bf2a2a; } .submitButton:focus { outline: none; background-color:#bf2a2a; } .submitButton:active { position:relative; top:1px; } @keyframes rotate { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } .sponsorSkipButton { background-color:#ec1c1c; -moz-border-radius:28px; -webkit-border-radius:28px; border-radius:28px; border:1px solid #d31919; display:inline-block; cursor:pointer; color:#ffffff; font-size:14px; padding:4px 15px; text-decoration:none; text-shadow:0px 0px 0px #662727; margin-top: 5px; margin-right: 15px; } .sponsorSkipButton:hover { background-color:#bf2a2a; } .sponsorSkipButton:focus { outline: none; background-color:#bf2a2a; } .sponsorSkipButton:active { position:relative; top:1px; } .sponsorSkipDontShowButton { -moz-box-shadow:inset 0px 1px 0px 0px #cf866c; -webkit-box-shadow:inset 0px 1px 0px 0px #cf866c; box-shadow:inset 0px 1px 0px 0px #cf866c; background-color:#d0451b; -moz-border-radius:3px; -webkit-border-radius:3px; border-radius:3px; border:1px solid #942911; display:inline-block; cursor:pointer; color:#ffffff; font-size:13px; padding:6px 24px; text-decoration:none; text-shadow:0px 1px 0px #854629; } .sponsorSkipDontShowButton:hover { background-color:#bc3315; } .sponsorSkipDontShowButton:focus { outline: none; background-color:#bc3315; } .sponsorSkipDontShowButton:active { position:relative; top:1px; } /* Submission Notice */ .sponsorTimeDisplay { font-size: 15px; } .sponsorTimeEditButton { text-decoration: underline; margin-left: 13px; margin-right: 13px; font-size: 13px; cursor: pointer; } .sponsorTimeEdit > input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; } .sponsorTimeMessagesRow { max-height: 300px; display: flex; overflow: auto; } .sponsorTimeEdit { font-size: 14px; -moz-appearance: textfield; appearance: textfield; } .sponsorTimeEditInput { width: 90px; border: 3px solid var(--sb-dark-red-outline); } .sponsorTimeEditInput.sponsorChapterNameInput { width: auto; padding: 3px; } .sponsorNowButton { font-size: 11px; cursor: pointer; text-decoration: underline; } .sponsorTimeEditSelector { margin-top: 5px; margin-bottom: 5px; background-color: rgba(28, 28, 28, 0.9); border-color: var(--sb-dark-red-outline); color: white; border-width: 3px; padding: 3px; } .sponsorTimeEditSelector > option { background-color: rgba(28, 28, 28, 0.9); color: white; } .hideSegmentSubmitButton { cursor: pointer; margin: auto; top: 0; bottom: 0; position: absolute; } /* Start SelectorComponent */ .sbSelector { position: absolute; text-align: center; width: calc(100% - var(--skip-notice-right) - var(--skip-notice-padding) * 2 - var(--skip-notice-margin) * 2 - var(--skip-notice-border-horizontal) * 2); z-index: 1000; } .sbSelectorBackground { text-align: center; background-color: rgba(28, 28, 28, 0.9); border-radius: 6px; padding: 3px; margin: auto; width: 170px; } .sbSelectorOption { cursor: pointer; background-color: rgb(43, 43, 43); padding: 5px; margin: 5px; color: white; border-radius: 5px; font-size: 14px; margin-left: auto; margin-right: auto; } .sbSelectorOption:hover { background-color: #3a0000; } /* End SelectorComponent */ .helpButton { height: 25px; cursor: pointer; padding: 5px; margin: auto; top: 0; bottom: 0; position: absolute; } .helpButton:hover { opacity: 0.8; } .skipButtonControlBarContainer { cursor: pointer; display: flex; color: white; align-items: center; } /* July 2025 test UI */ .ytp-delhi-modern .skipButtonControlBarContainer { height: 48px; margin: auto 0; } .skipButtonControlBarContainer.sbhidden { display: none !important; } .skipButtonControlBarContainer.mobile { bottom: 30%; margin-left: 5px; position: absolute; height: 20px; background-color: #00000030; opacity: 0.5; border-radius: 10px; padding: 4px; } .skipButtonControlBarContainer.mobile.textDisabled { padding: 0; background-color: transparent; } .skipButtonControlBarContainer.mobile > div { margin: auto; margin-left: 5px; } #sbSkipIconControlBarImage { height: 60%; top: 0px; bottom: 0px; display: block; margin: auto; } .mobile #sbSkipIconControlBarImage { height: 100%; width: 20px; } .sponsorBlockTooltip { position: absolute; background-color: rgba(28, 28, 28, 0.7); border-radius: 5px; padding: 10px; max-width: 300px; width: max-content; white-space: normal; line-height: 1.5em; color: white; font-size: 12px; z-index: 10000; font-weight: normal; } .sponsorBlockTooltip a { color: white; } .sponsorBlockTooltip.sbTriangle::after { content: " "; position: absolute; top: 100%; left: 15%; margin-left: -15px; border-width: 15px; border-style: solid; border-color: rgba(28, 28, 28, 0.7) transparent transparent transparent; } .sponsorBlockTooltip.sbTriangle.centeredSBTriangle::after { left: 50%; right: 50%; } .sponsorBlockTooltip.sbTriangle.sbTopTriangle::after { bottom: 100%; top: unset; border-color: transparent transparent rgba(28, 28, 28, 0.7) transparent; } .sponsorBlockLockedColor { color: #ffc83d !important; } .sponsorBlockRectangleTooltip { position: absolute; border-radius: 5px; padding: 10px; min-width: 250px; min-height: 75px; white-space: normal; line-height: 1.5em; } /* Description on right layout */ #title > #categoryPillParent { font-size: 2rem; font-weight: bold; display: flex; justify-content: center; line-height: 2.8rem; } #title > #categoryPillParent > #categoryPill.cbPillOpen { margin-bottom: 5px; } #categoryPillParent { height: fit-content; margin-top: auto; margin-bottom: auto; position: relative; } .sponsorBlockCategoryPill { border-radius: 25px; padding-left: 8px; padding-right: 8px; margin-right: 3px; cursor: pointer; font-size: 75%; height: 100%; align-items: center; inline-size: max-content; } .sponsorBlockCategoryPillTitleSection { display: flex; align-items: center; } .sponsorBlockCategoryPillTitle { white-space: nowrap; } /* Vorapis V3 support */ #watch7-content .sponsorBlockCategoryPill { padding-top: 5px; padding-bottom: 5px; } #watch7-content .sponsorBlockCategoryPillTitle { font-size: 15px; } .categoryPillClose { display: none; height: 10px; width: 10px; box-sizing: unset; margin: 0px 0px 0px 5px; } .sponsorBlockCategoryPill:hover .categoryPillClose { display: inherit; } /* tweak for mobile duration */ #sponsorBlockDurationAfterSkips.ytm-time-display { padding-left: 4px; margin: 0px; color: #fff; opacity: .7; } /* full video labels on thumbnails */ .sponsorThumbnailLabel { display: none; position: absolute; top: 0; left: 0; padding: 0.5em; margin: 0.5em; border-radius: 2em; z-index: 1000; background-color: var(--category-color, #000); opacity: 0.7; box-shadow: 0 0 8px 2px #333; font-size: 10px; } .sponsorThumbnailLabel.sponsorThumbnailLabelVisible { display: flex; } .sponsorThumbnailLabel svg { height: 2em; fill: var(--category-text-color, #fff); } .sponsorThumbnailLabel span { display: none; padding-left: 0.25em; font-size: 1.5em; color: var(--category-text-color, #fff); } .sponsorThumbnailLabel:hover { border-radius: 0.25em; opacity: 1; } .sponsorThumbnailLabel:hover span { display: inline; } .sponsorblock-chapter-visible { display: block !important; } /* Pride theme */ .playerButton.prideTheme:nth-of-type(1) { filter: brightness(50%) sepia(100) saturate(100); } .playerButton.prideTheme:nth-of-type(2) { filter: sepia(100) saturate(100) hue-rotate(0deg); } .playerButton.prideTheme:nth-of-type(3) { filter: sepia(100) saturate(100) hue-rotate(45deg); } .playerButton.prideTheme:nth-of-type(4) { filter: sepia(100) saturate(100) invert() hue-rotate(5deg); } .playerButton.prideTheme:nth-of-type(5) { filter: sepia(100) saturate(100) invert() hue-rotate(35deg); } ================================================ FILE: public/help/index.html ================================================ SponsorBlock
SponsorBlock

Created By Ajay Ramachandran

__MSG_helpPageReviewOptions__

__MSG_helpPageFeatureDisclaimer__

================================================ FILE: public/help/styles.css ================================================ :root { --color-scheme: dark; --background: #333333; --header-color: #212121; --dialog-background: #181818; --dialog-border: white; --text: #c4c4c4; --title: #dad8d8; --disabled: #520000; --black: black; --white: white; } [data-theme="light"] { --color-scheme: light; --background: #f9f9f9; --header-color: white; --dialog-background: #f9f9f9; --dialog-border: #282828; --text: #262626; --title: #707070; --disabled: #ffcaca; --black: white; --white: black; } html { color-scheme: var(--color-scheme); } .bigText { font-size: 30px; } .smallText { font-size: 14px; } body { background-color: var(--background); font-family: sans-serif; } .center { text-align: center; } .inline { display: inline-block; } .container { margin: auto; } .projectPreview { position: relative; } .projectPreviewImage { position: absolute; left: -90px; width: 80px; top: 50%; transform: translateY(-50%); } .projectPreviewImageLarge { position: absolute; left: -210px; width: 200px; top: 50%; transform: translateY(-20%); } .createdBy { font-size: 14px; text-align: center; padding-top: 0px; padding-bottom: 0px; } #title { background-color: #636363; text-align: center; vertical-align: middle; font-size: 50px; color: var(--header-color); padding: 20px; text-decoration: none; border-radius: 15px; transition: font-size 1s; } .subtitle { font-size: 40px; color: #dad8d8; padding-top: 10px; transition: font-size 0.4s; } .subtitle:hover { font-size: 45px; transition: font-size 0.4s; } .profilepic { background-color: #636363 !important; vertical-align: middle; } .profilepiccircle { vertical-align: middle; overflow: hidden; border-radius: 50%; } a { text-decoration: underline; color: inherit; } .link { padding: 20px; height: 80px; transition: height 0.2s; } .link:hover { height: 95px; transition: height 0.2s; } #contact,.smalllink { font-size: 25px; color: #e8e8e8; text-align: center; padding: 10px; } #contact { text-decoration: none; } p,li { font-size: 16px; } p,li,a,span,div { color: var(--text); } p,li,code,a { text-align: left; overflow-wrap: break-word; } .optionsFrame { width: 100%; height: 100%; } .previewImage { max-height: 200px; } img { max-width: 100%; text-align: center; } #recentPostTitle { font-size: 30px; color: #dad8d8; } #recentPostDate { font-size: 15px; color: #dad8d8; } h1,h2,h3,h4,h5,h6 { color: var(--title); text-align: center; font-size: 25px; margin: 5px 0px; } svg { text-decoration: none; } .donate-ask { background-color: rgb(26, 26, 26, 0.95); border-radius: 15px; text-align: center; padding: 10px; margin: 0.7em 0px; } .donate-ask .donate-text { margin-top: 10px; margin-bottom: 10px; display: flex; align-items: center; justify-content: center; } .donate-ask .donate-text img { height: 2rem; border-radius: 100%; margin-right: 15px; } .donate-ask a { text-decoration: none; color: #eee; border-radius: 15px; background-color: rgb(58, 58, 58, 0.9); padding: 10px; transition: background-color 0.3s ease; display: block; width: fit-content; margin: auto; margin-top: 10px; margin-bottom: 10px; } .donate-ask a:hover { background-color: rgba(70, 70, 70, 0.9); } @media screen and (orientation:portrait) { .projectPreviewImage { position: unset; width: 50%; display: block; margin: auto; transform: none; } .projectPreviewImageLarge { position: unset; left: 0; width: 50%; display: block; margin: auto; transform: unset; } .container { max-width: 100%; margin: 5px; text-align: center; } p,li,code,a { text-align: center; } } /* keybind dialog */ .key { border-width: 1px; border-style: solid; border-radius: 5px; display: inline-block; min-width: 33px; text-align: center; font-weight: bold; border-color: var(--white); box-sizing: border-box; } .unbound, .key { padding: 8px; } #keybind-dialog .dialog { position: fixed; border-width: 3px; border-style: solid; border-radius: 15px; max-height: 100vh; width: 400px; overflow-x: auto; z-index: 100; padding: 15px; left: 50%; top: 50%; transform: translate(-50%, -50%); font-size: 14px; background-color: var(--dialog-background); border-color: var(--dialog-border); } #change-keybind-buttons { float: right; } #change-keybind-buttons > .option-button { margin: 0 2px; } #change-keybind-settings { margin: 15px 15px 30px; } #change-keybind-settings .key { vertical-align: top; margin: 15px 0 0 40px; height: 34px; } #change-keybind-error { margin-bottom: 15px; color: red; font-weight: bold; } .blocker { position: fixed; left: 0; right: 0; top: 0; bottom: 0; z-index: 90; background-color: #00000080; } .option-button { cursor: pointer; background-color: #c00000; padding: 10px; color: white; border-radius: 5px; font-size: 14px; width: max-content; } .option-button:hover:not(.disabled) { background-color: #fc0303; } .option-button.disabled { cursor: default; background-color: var(--disabled); color: grey; } .dearrow-link { display: flex; align-items: center; justify-content: center; text-decoration: none; font-size: 16px; } .dearrow-link img { width: 35px; padding: 10px } .dearrow-link .close-button { opacity: 0; width: 15px; filter: invert(0.3); transition: opacity 0.2s; } .dearrow-link:hover .close-button { opacity: 1; } .hidden { display: none; } .help-page-flex-container { display: flex; flex-direction: row; gap: 20px; margin-left: 20px; margin-right: 20px; } .left-sidebar { display: flex; flex-direction: column; flex: 1 1 50%; } .box2 { flex: 1 1 50%; } /* Mobile */ @media only screen and (max-width: 600px) { .box1 { order: 1; } .box2 { order: 2; } .box3 { order: 3; } .left-sidebar { display: contents; } .help-page-flex-container { flex-direction: column; } .optionsFrame { height: 500px; } } ================================================ FILE: public/libs/Source+Sans+Pro.css ================================================ /* cyrillic-ext */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 400; src: local('Source Sans Pro Regular'), local('SourceSansPro-Regular'), url(6xK3dSBYKcSV-LCoeQqfX1RYOo3qNa7lqDY.woff2) format('woff2'); unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; } /* cyrillic */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 400; src: local('Source Sans Pro Regular'), local('SourceSansPro-Regular'), url(6xK3dSBYKcSV-LCoeQqfX1RYOo3qPK7lqDY.woff2) format('woff2'); unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; } /* greek-ext */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 400; src: local('Source Sans Pro Regular'), local('SourceSansPro-Regular'), url(6xK3dSBYKcSV-LCoeQqfX1RYOo3qNK7lqDY.woff2) format('woff2'); unicode-range: U+1F00-1FFF; } /* greek */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 400; src: local('Source Sans Pro Regular'), local('SourceSansPro-Regular'), url(6xK3dSBYKcSV-LCoeQqfX1RYOo3qO67lqDY.woff2) format('woff2'); unicode-range: U+0370-03FF; } /* vietnamese */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 400; src: local('Source Sans Pro Regular'), local('SourceSansPro-Regular'), url(6xK3dSBYKcSV-LCoeQqfX1RYOo3qN67lqDY.woff2) format('woff2'); unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; } /* latin-ext */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 400; src: local('Source Sans Pro Regular'), local('SourceSansPro-Regular'), url(6xK3dSBYKcSV-LCoeQqfX1RYOo3qNq7lqDY.woff2) format('woff2'); unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; } /* latin */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 400; src: local('Source Sans Pro Regular'), local('SourceSansPro-Regular'), url(6xK3dSBYKcSV-LCoeQqfX1RYOo3qOK7l.woff2) format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; } /* cyrillic-ext */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 700; src: local('Source Sans Pro Bold'), local('SourceSansPro-Bold'), url(6xKydSBYKcSV-LCoeQqfX1RYOo3ig4vwmhduz8A.woff2) format('woff2'); unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F; } /* cyrillic */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 700; src: local('Source Sans Pro Bold'), local('SourceSansPro-Bold'), url(6xKydSBYKcSV-LCoeQqfX1RYOo3ig4vwkxduz8A.woff2) format('woff2'); unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116; } /* greek-ext */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 700; src: local('Source Sans Pro Bold'), local('SourceSansPro-Bold'), url(6xKydSBYKcSV-LCoeQqfX1RYOo3ig4vwmxduz8A.woff2) format('woff2'); unicode-range: U+1F00-1FFF; } /* greek */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 700; src: local('Source Sans Pro Bold'), local('SourceSansPro-Bold'), url(6xKydSBYKcSV-LCoeQqfX1RYOo3ig4vwlBduz8A.woff2) format('woff2'); unicode-range: U+0370-03FF; } /* vietnamese */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 700; src: local('Source Sans Pro Bold'), local('SourceSansPro-Bold'), url(6xKydSBYKcSV-LCoeQqfX1RYOo3ig4vwmBduz8A.woff2) format('woff2'); unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+1EA0-1EF9, U+20AB; } /* latin-ext */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 700; src: local('Source Sans Pro Bold'), local('SourceSansPro-Bold'), url(6xKydSBYKcSV-LCoeQqfX1RYOo3ig4vwmRduz8A.woff2) format('woff2'); unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF; } /* latin */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 700; src: local('Source Sans Pro Bold'), local('SourceSansPro-Bold'), url(6xKydSBYKcSV-LCoeQqfX1RYOo3ig4vwlxdu.woff2) format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; } ================================================ FILE: public/options/options.css ================================================ /* Options page CSS */ :root { --color-scheme: dark; --background: #333333; --menu-background: #181818; --menu-foreground: white; --dialog-background: #181818; --dialog-border: white; --tab-color: #242424; --tab-button-hover: #4d0000; --tab-hover: white; --description: #dfdfdf; --disabled: #520000; --slider: #707070; --title: #dad8d8; --border-color: #484848; --black: black; --white: white; --selector-red: #c00000; --selector-red-hover: #fc0303; --tab-selected: #950000; } [data-theme="light"] { --color-scheme: light; --background: #f9f9f9; --menu-background: #dbdbdb; --menu-foreground: #212121; --dialog-background: #f9f9f9; --dialog-border: #282828; --tab-color: #ababab; --tab-button-hover: #750000; --tab-hover: #2e2e2e; --description: #262626; --disabled: #ffcaca; --slider: #bfbebe; --title: #707070; --border-color: #d9d9d9; --black: white; --white: black; } [data-theme="pride"] { --menu-background: #181818d0; } .medium-description, .switch-container, .optionLabel, .categoryTableElement, .promotion-description { color: var(--white); } .small-description, p, li, span, div { color: var(--description); } h1,h2,h3,h4,h5,h6 { color: var(--title); } html, body { color-scheme: var(--color-scheme); font-family: sans-serif; margin: 0; font-size: 14px; background-color: var(--background); } [data-theme="pride"] body { background: url("../icons/pride.svg"); background-size: contain; } * { box-sizing: border-box; } #options-container { display: flex; } #menubar { display: flex; flex-direction: column; gap: 20px; flex-basis: 20%; min-width: 300px; max-width: 600px; border-radius: 15px; margin: 15px; z-index: 10; background-color: var(--menu-background); color: var(--menu-foreground); } #navigation { display: flex; flex-direction: column; gap: 30px; } .tab-heading { font-size: 18px; height: 55px; line-height: 55px; width: 80%; margin: 0 auto; border-radius: 15px; cursor: pointer; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; background-color: var(--tab-color); color: var(--white); } .tab-heading:hover { background-color: var(--tab-button-hover); color: white; } .tab-heading.selected { background-color: var(--selector-red); color: white; } .tab-heading:active { background-color: var(--tab-selected); color: white; } [data-theme="pride"] .tab-heading:nth-of-type(1) { background-color: #2f0000; } [data-theme="pride"] .tab-heading:nth-of-type(2) { background-color: #3a2000; } [data-theme="pride"] .tab-heading:nth-of-type(3) { background-color: #3e3a00; } [data-theme="pride"] .tab-heading:nth-of-type(4) { background-color: #003e13; } [data-theme="pride"] .tab-heading:nth-of-type(5) { background-color: #00164a; } [data-theme="pride"] .tab-heading:hover:nth-of-type(1) { background-color: #550000; } [data-theme="pride"] .tab-heading:hover:nth-of-type(2), [data-theme="pride"] #category-type tr:nth-of-type(5n) .slider, [data-theme="pride"] [data-type="toggle"]:nth-of-type(5n) .slider { background-color: #824700; } [data-theme="pride"] .tab-heading:hover:nth-of-type(3), [data-theme="pride"] #category-type tr:nth-of-type(5n + 1) .slider, [data-theme="pride"] [data-type="toggle"]:nth-of-type(5n + 1) .slider { background-color: #867d00; } [data-theme="pride"] .tab-heading:hover:nth-of-type(4), [data-theme="pride"] #category-type tr:nth-of-type(5n + 2) .slider, [data-theme="pride"] [data-type="toggle"]:nth-of-type(5n + 2) .slider { background-color: #00691f; } [data-theme="pride"] .tab-heading:hover:nth-of-type(5), [data-theme="pride"] #category-type tr:nth-of-type(5n + 3) .slider, [data-theme="pride"] [data-type="toggle"]:nth-of-type(5n + 3) .slider { background-color: #002374; } [data-theme="pride"] #category-type tr:nth-of-type(5n + 4) .slider, [data-theme="pride"] [data-type="toggle"]:nth-of-type(5n + 4) .slider { background-color: #400449; } [data-theme="pride"] #category-type tr .optionsSelector { color: var(--white); } [data-theme="pride"] .tab-heading:nth-of-type(1).selected { background-color: #E40303; } [data-theme="pride"] .tab-heading:nth-of-type(2).selected, [data-theme="pride"] #category-type tr:nth-of-type(10n + 2) .optionsSelector, [data-theme="pride"] #category-type tr:nth-of-type(5n) input:checked + .slider, [data-theme="pride"] [data-type]:nth-of-type(5n) :is(input:checked + .slider, .option-button, .optionsSelector) { background-color: #dd7a00; } [data-theme="pride"] .tab-heading:nth-of-type(3).selected, [data-theme="pride"] #category-type tr:nth-of-type(10n + 4) .optionsSelector, [data-theme="pride"] #category-type tr:nth-of-type(2n + 1) .optionsSelector, [data-theme="pride"] #category-type tr:nth-of-type(5n + 1) input:checked + .slider, [data-theme="pride"] [data-type]:nth-of-type(5n + 1) :is(input:checked + .slider, .option-button, .optionsSelector) { background-color: #FFED00; color: rgb(23, 23, 23); } [data-theme="pride"] .tab-heading:nth-of-type(4).selected, [data-theme="pride"] #category-type tr:nth-of-type(10n + 6) .optionsSelector, [data-theme="pride"] #category-type tr:nth-of-type(5n + 2) input:checked + .slider, [data-theme="pride"] [data-type]:nth-of-type(5n + 2) :is(input:checked + .slider, .option-button, .optionsSelector) { background-color: #008026; } [data-theme="pride"] .tab-heading:nth-of-type(5).selected, [data-theme="pride"] #category-type tr:nth-of-type(10n + 8) .optionsSelector, [data-theme="pride"] #category-type tr:nth-of-type(5n + 3) input:checked + .slider, [data-theme="pride"] [data-type]:nth-of-type(5n + 3) :is(input:checked + .slider, .option-button, .optionsSelector) { background-color: #004DFF; } [data-theme="pride"] .tab-heading:nth-of-type(5).selected, [data-theme="pride"] #category-type tr:nth-of-type(10n + 10) .optionsSelector, [data-theme="pride"] #category-type tr:nth-of-type(5n + 4) input:checked + .slider, [data-theme="pride"] [data-type]:nth-of-type(5n + 4) :is(input:checked + .slider, .option-button, .optionsSelector) { background-color: #750787; } .option-group > div, .extraOptionGroup { min-height: 50px; padding: 15px 0; border-image: linear-gradient(to right, var(--border-color), #00000000 80%) 1; } .option-group > div { border-bottom: 1px solid var(--border-color); } .extraOptionGroup { border-top: 1px solid var(--border-color); } .extraOptionGroup tr:not(:last-child) { padding-bottom: 15px; display: block; } #category-type { padding: 0; } #category-type .categoryExtraOptions { padding-bottom: 15px; } #music_offtopic_autoSkipOnMusicVideos { padding-bottom: 0; } .option-group > div:last-child, .option-group > #keybind-dialog { border-bottom: inherit; } .optionLabel, #version { font-size: 14px; height: 15px; } div[data-type="keybind-change"] .optionLabel { display: inline-block; min-width: 150px; margin-right: 20px; } input[type='number'] { width: 50px; } .key { border-width: 1px; border-style: solid; border-radius: 5px; display: inline-block; min-width: 33px; text-align: center; font-weight: bold; border-color: var(--white); } .unbound, .key { padding: 8px; } .keybind-buttons { border-radius: 5px; padding: 5px 3px; cursor: pointer; margin-right: 10px; } .keybind-buttons:hover { background-color: #00000030; } .keybind-buttons > div, .keybind-buttons > span { margin: 0 2px; } #keybind-dialog .dialog { position: fixed; border-width: 3px; border-style: solid; border-radius: 15px; max-height: 100vh; width: 400px; overflow-x: auto; z-index: 100; padding: 15px; left: 50%; top: 50%; transform: translate(-50%, -50%); background-color: var(--dialog-background); border-color: var(--dialog-border); } #change-keybind-buttons { float: right; } #change-keybind-buttons > .option-button { margin: 0 2px; } #change-keybind-settings { margin: 15px 15px 30px; } #change-keybind-settings .key { vertical-align: top; margin: 15px 0 0 40px; height: 34px; } #change-keybind-error { margin-bottom: 15px; color: red; font-weight: bold; } .blocker { position: fixed; left: 0; right: 0; top: 0; bottom: 0; z-index: 90; background-color: #00000080; } .low-profile { height: 23px; line-height: 5px; vertical-align: middle; } .center { text-align: center; } .inline { display: inline-block; } .next-line { padding: 15px 0 0 0; } .bold { font-weight: bold; } .hiding { opacity: 0; } .hidden, .sbhidden { display: none !important; } .spacing { margin-top: 15px; } .keybind-status { display: inline; } .small-description { font-size: 13px; padding: 5px 0 0 20px; } .small-description td { padding: 2.5px 0 10px 20px; } .indent { padding-left: 20px; } .categoryTableElement td { padding-top: 5px; border-top: 1px solid var(--border-color); } .medium-description { font-size: 15px; } .option-text-box { width: 300px; } .option-button { cursor: pointer; background-color: var(--selector-red); padding: 10px; color: white; border-radius: 5px; font-size: 14px; width: max-content; } .option-button:hover:not(.disabled) { background-color: var(--selector-red-hover); } .option-button.disabled { cursor: default; background-color: var(--disabled); color: grey; } .sb-toggle-option.disabled .slider { cursor: default; } /* To hide everything except upsell button */ .disabled td:not(.skipOption, .categoryExtraOptions), .disabled td.skipOption > :not(.upsellButton) { opacity: 0.3; } #options { height: 100vh; flex-basis: 80%; overflow: auto; text-align: left; padding: 80px 15% 0 3%; box-sizing: border-box; display: flex; justify-content: center; transition: padding 0.3s; } #options.embed > div { max-width: 100%; } #title .profilepic { height: 60px; } .switch-container { content: attr(label-name); width: max-content; font-size: 14px; display: flex; align-items: center; } .switch-container .switch-label { display: table-cell; vertical-align: middle; padding: 4px; } .sb-number-input { margin-left: 4px; margin-right: 4px; } .switch-label { width: inherit; } .switch { position: relative; display: inline-block; width: 40px; height: 24px; min-width: 40px; } .switch input { opacity: 0; width: 0; height: 0; } .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: var(--slider); } .animated * { -webkit-transition: .4s; transition: .4s; } .slider:before { position: absolute; content: ""; height: 16px; width: 16px; left: 4px; bottom: 4px; background-color: white; } .animated .slider:before { -webkit-transition: .4s; transition: .4s; } input:checked + .slider { background-color: var(--selector-red-hover); } input:checked + .slider:before { -webkit-transform: translateX(16px); -ms-transform: translateX(16px); transform: translateX(16px); } /* Rounded sliders */ .slider.round { border-radius: 34px; } .slider.round:before { border-radius: 50%; } /* Boilerplate CSS from https://ajay.app (edited) */ .projectPreview { position: relative; } .projectPreviewImage { position: absolute; left: -90px; width: 80px; top: 50%; transform: translateY(-50%); } .projectPreviewImageLarge { position: absolute; left: -210px; width: 200px; top: 50%; transform: translateY(-20%); } .projectPreviewImageLargeRight { position: absolute; right: -210px; width: 200px; top: 50%; transform: translateY(-50%); } #createdBy { text-align: center; margin: auto 0 10px 0; height: 50px; } #createdBy > * { font-size: 14px; } #title { text-align: center; vertical-align: middle; font-size: 40px; padding: 40px 20px; text-decoration: none; } .subtitle { font-size: 40px; color: #dad8d8; padding-top: 10px; transition: font-size 0.4s; } .subtitle:hover { font-size: 45px; transition: font-size 0.4s; } .profilepic { vertical-align: middle; } .profilepiccircle { vertical-align: middle; overflow: hidden; border-radius: 50%; } a { text-decoration: underline; color: inherit; } .link { padding: 20px; height: 80px; transition: height 0.2s; } .link:hover { height: 95px; transition: height 0.2s; } #contact,.smalllink { font-size: 25px; color: #e8e8e8; text-align: center; padding: 10px; } #contact { text-decoration: none; } p,li { font-size: 20px; padding: 10px; } .previewImage { max-height: 200px; } img { max-width: 100%; text-align: center; } #recentPostTitle { font-size: 30px; color: #dad8d8; } #recentPostDate { font-size: 15px; color: #dad8d8; } svg { text-decoration: none; } .number-container:before { content: attr(label-name); padding-right: 4px; width: max-content; font-size: 14px; color: white; } /* React styles */ .categoryTableElement { font-size: 16px; } .categoryTableElement > * { padding-right: 15px; } .categoryTableDescription > * { padding-bottom: 15px; } .optionsSelector { background-color: var(--selector-red); color: white; border: none; font-size: 14px; padding: 5px; border-radius: 5px; } .categoryColorTextBox { width: 60px; background: none; border: none; } #sbDonate { font-size: 10px; } /* Top bar navigation for smaller screens */ @media only screen and (max-height: 725px), only screen and (max-width: 1200px) { #options-container { flex-direction: column; } #menubar { gap: 8px; min-width: unset; max-width: unset; padding: 8px; } #navigation { gap: 8px; flex-direction: row; flex-wrap: wrap; justify-content: center; } #options { padding: 0 50px; } #options > div { max-width: 70%; } .tab-heading { width: unset; min-width: unset; height: 35px; line-height: 35px; font-size: 16px; padding: 0 10px; margin: 0; } #title { width: 100%; font-size: 30px; padding: 10px; } #title .profilepic { height: 40px; } #createdBy { margin: 10px 0 0 0; height: unset; width: 100%; } #createdBy > div { display: inline-block; } #sbDonate { position: absolute; right: 30px; margin-top: 10px; } #version { font-size: 10px; height: 10px; transform: translate(-50px, -5px); } .sticky #menubar { position: fixed; left: 0; right: 0; margin: 0 15px; } .sticky #title, .sticky #createdBy { display: none; } } @media only screen and (max-width: 800px) { #options { padding: 0 15px; } #options > div { max-width: 100%; } } .upsellButton { cursor: pointer; vertical-align: middle; } .no-bottom-border { border: none !important; padding: 20px 0px 0px 0px !important; } .promotion-container { width: fit-content; } .dearrow-link { display: flex; align-items: center; justify-content: center; text-decoration: none; } .dearrow-link > img { width: 40px; margin-right: 4px; } .dearrow-link .close-button { opacity: 0; width: 15px; filter: invert(0.3); transition: opacity 0.2s; margin-left: 10px; } .dearrow-link:hover .close-button { opacity: 1; } .invalid-advanced-config { color: red; } .advanced-skip-options-menu { margin-top: 10px; } .advanced-config-help-message { margin-bottom: 10px; transition: none; } .categoryChooserTopRow { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; } .partiallyHidden { opacity: 0.5; } .partiallyHidden:hover { opacity: 1; } .reset-button svg { margin-left: 5px; width: 10px; fill: var(--white); cursor: pointer; } .skipProfileMenu { position: absolute; } .configurationInfo > *:not(:last-child) { margin-bottom: 10px; } .configurationInfo .option-text-box { width: 100%; } ================================================ FILE: public/options/options.html ================================================ __MSG_Options__ - SponsorBlock
================================================ FILE: public/oss-attribution/attribution.txt ================================================ content-scripts-register-polyfill 4.0.2 MIT License Copyright (c) Federico Brigante (https://fregante.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************** escape-string-regexp 5.0.0 MIT License Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************** js-tokens 4.0.0 The MIT License (MIT) Copyright (c) 2014, 2015, 2016, 2017, 2018 Simon Lydell Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************** loose-envify 1.4.0 The MIT License (MIT) Copyright (c) 2015 Andres Suarez Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************** react 18.2.0 MIT License Copyright (c) Facebook, Inc. and its affiliates. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************** react-dom 18.2.0 MIT License Copyright (c) Facebook, Inc. and its affiliates. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************** scheduler 0.23.0 MIT License Copyright (c) Facebook, Inc. and its affiliates. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************** webext-content-scripts 2.5.5 MIT License Copyright (c) Federico Brigante (https://fregante.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************** webext-patterns 1.3.0 MIT License Copyright (c) Federico Brigante (https://fregante.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************** webext-polyfill-kinda 1.0.2 MIT License Copyright (c) Federico Brigante (https://fregante.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: public/permissions/index.html ================================================ Permissions - SponsorBlock
SponsorBlock

__MSG_invidiousPermissionRefresh__

__MSG_acceptPermission__
================================================ FILE: public/permissions/styles.css ================================================ /* Options page CSS */ html { color-scheme: dark; } body { font-family: sans-serif; } .center { text-align: center; } .inline { display: inline-block; } .bold { font-weight: bold; } .hidden, .sbhidden { display: none !important; } .keybind-status { display: inline; } .small-description { color: white; font-size: 13px; } .medium-description { color: white; font-size: 15px; } .option-text-box { width: 300px; } .option-button { cursor: pointer; background-color: #c00000; padding: 10px; color: white; border-radius: 5px; font-size: 14px; width: max-content; } .option-button:hover { background-color: #fc0303; } .option-button.disabled { cursor: default; background-color: #520000; color: grey; } #options { max-width: 60%; text-align: left; display: inline-block; } .switch-container:after { content: attr(label-name); position: absolute; padding: 4px; width: max-content; font-size: 14px; color: white; } .text-label-container { font-size: 14px; color: white; } .switch { position: relative; display: inline-block; width: 40px; height: 24px; } .switch input { opacity: 0; width: 0; height: 0; } .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #707070; } .animated * { -webkit-transition: .4s; transition: .4s; } .slider:before { position: absolute; content: ""; height: 16px; width: 16px; left: 4px; bottom: 4px; background-color: white; } .animated .slider:before { -webkit-transition: .4s; transition: .4s; } input:checked + .slider { background-color: #fc0303; } input:checked + .slider:before { -webkit-transform: translateX(16px); -ms-transform: translateX(16px); transform: translateX(16px); } /* Rounded sliders */ .slider.round { border-radius: 34px; } .slider.round:before { border-radius: 50%; } /* Boilerplate CSS from https://ajay.app */ body { background-color: #333333; } .projectPreview { position: relative; } .projectPreviewImage { position: absolute; left: -90px; width: 80px; top: 50%; transform: translateY(-50%); } .projectPreviewImageLarge { position: absolute; left: -210px; width: 200px; top: 50%; transform: translateY(-20%); } .projectPreviewImageLargeRight { position: absolute; right: -210px; width: 200px; top: 50%; transform: translateY(-50%); } .createdBy { font-size: 14px; text-align: center; padding-top: 0px; padding-bottom: 0px; display: inline-block; } #title { background-color: #636363; text-align: center; vertical-align: middle; font-size: 50px; color: #212121; padding: 20px; text-decoration: none; transition: font-size 1s; } .subtitle { font-size: 40px; color: #dad8d8; padding-top: 10px; transition: font-size 0.4s; } .subtitle:hover { font-size: 45px; transition: font-size 0.4s; } .profilepic { background-color: #636363 !important; vertical-align: middle; } .profilepiccircle { vertical-align: middle; overflow: hidden; border-radius: 50%; } a { text-decoration: underline; color: inherit; } .link { padding: 20px; height: 80px; transition: height 0.2s; } .link:hover { height: 95px; transition: height 0.2s; } #contact,.smalllink { font-size: 25px; color: #e8e8e8; text-align: center; padding: 10px; } #contact { text-decoration: none; } p,li { font-size: 20px; color: #c4c4c4; padding: 10px; } p,li,code,a { max-width: 60%; text-align: left; overflow-wrap: break-word; } @media screen and (orientation:portrait) { p,li,code,a { max-width: 100%; } .projectPreviewImage { position: unset; width: 130px; display: block; margin: auto; transform: none; } } .previewImage { max-height: 200px; } img { max-width: 100%; text-align: center; } #recentPostTitle { font-size: 30px; color: #dad8d8; } #recentPostDate { font-size: 15px; color: #dad8d8; } h1,h2,h3,h4,h5,h6 { color: #dad8d8; } svg { text-decoration: none; } .number-container:before { content: attr(label-name); padding-right: 4px; width: max-content; font-size: 14px; color: white; } /* React styles */ .categoryTableElement { font-size: 16px; color: white; } .categoryTableElement > * { padding-right: 15px; padding-bottom: 15px; } .categoryOptionsSelector { background-color: #c00000; color: white; border: none; font-size: 14px; padding: 5px; border-radius: 5px; } .categoryColorTextBox { width: 60px; background: none; border: none; } ================================================ FILE: public/popup.css ================================================ :root { --sb-main-font-family: "Source Sans Pro", sans-serif; --sb-main-bg-color: #222; --sb-main-fg-color: #fff; --sb-grey-bg-color: #333; --sb-grey-bg-active-color: #444; --sb-grey-fg-color: #999; --sb-red-bg-color: #cc1717; --sb-red-bg-active-color: #ec1c1c; --sb-skip-profile-bg: #292828; --sb-skip-profile-disabled: #808080; --sb-skip-profile-option-bg: #222; --sb-skip-profile-highlighted: rgb(127, 0, 0); } .prideTheme { --sb-main-fg-color: #fff; --sb-grey-bg-color: #008026; --sb-grey-bg-active-color: #FF8C00; --sb-grey-fg-color: #FFED00; --sb-red-bg-color: #732982; --sb-red-bg-active-color: #004CFF; --sb-skip-profile-bg: #FFAFC8; --sb-skip-profile-disabled: #74D7EE; --sb-skip-profile-option-bg: #f687aa; --sb-skip-profile-highlighted: #38153f; background: url("icons/pride.svg"); } /* * Generic utilities */ .grey-text { color: var(--sb-grey-fg-color); } .white-text { color: var(--sb-main-fg-color); } .sbHeader { font-size: 20px; font-weight: bold; text-align: left; margin: 0; } #sponsorBlockPopupBody .u-mZ { margin: 0 !important; position: relative; } #sponsorBlockPopupBody .hidden, #sponsorBlockPopupBody .sbhidden { display: none !important; } /* * {/* Downvote Button */} ); } private async vote(event: React.MouseEvent, type: number, element?: HTMLElement): Promise { event.stopPropagation(); if (this.state.segment) { const stopAnimation = AnimationUtils.applyLoadingAnimation(element ?? event.currentTarget as HTMLElement, 0.3); const response = await this.props.vote(type, this.state.segment.UUID); await stopAnimation(); if ("error" in response){ console.error("[SB] Caught error while attempting to vote on a chapter", response.error); alert(formatJSErrorMessage(response.error)); } else if (response.ok || response.status == 429) { this.setState({ show: type === 1 }); } else if (response.status !== 403) { logRequest({headers: null, ...response}, "SB", "vote on chapter"); alert(getLongErrorMessage(response.status, response.responseText)); } } } } export default ChapterVoteComponent; ================================================ FILE: src/components/NoticeComponent.tsx ================================================ import * as React from "react"; import Config from "../config"; import SbSvg from "../svg-icons/sb_svg"; enum CountdownMode { Timer, Paused, Stopped } export interface NoticeProps { noticeTitle: string; maxCountdownTime?: () => number; dontPauseCountdown?: boolean; amountOfPreviousNotices?: number; showInSecondSlot?: boolean; timed?: boolean; idSuffix?: string; fadeIn?: boolean; fadeOut?: boolean; startFaded?: boolean; firstColumn?: React.ReactElement[] | React.ReactElement; firstRow?: React.ReactElement; bottomRow?: React.ReactElement[]; smaller?: boolean; limitWidth?: boolean; extraClass?: string; hideLogo?: boolean; hideRightInfo?: boolean; logoFill?: string; // Callback for when this is closed closeListener: () => void; onMouseEnter?: (e: React.MouseEvent) => void; zIndex?: number; style?: React.CSSProperties; biggerCloseButton?: boolean; children?: React.ReactNode; } interface MouseDownInfo { x: number; y: number; right: number; bottom: number; } export interface NoticeState { maxCountdownTime: () => number; countdownTime: number; countdownMode: CountdownMode; mouseHovering: boolean; startFaded: boolean; mouseDownInfo: MouseDownInfo | null; mouseMoved: boolean; right: number; bottom: number; } // Limits for dragging notice around const bounds = [10, 100, 10, 10]; class NoticeComponent extends React.Component { countdownInterval: NodeJS.Timeout; idSuffix: string; amountOfPreviousNotices: number; parentRef: React.RefObject; handleMouseMoveBinded: (e: MouseEvent) => void = this.handleMouseMove.bind(this); constructor(props: NoticeProps) { super(props); this.parentRef = React.createRef(); const maxCountdownTime = () => { if (this.props.maxCountdownTime) return this.props.maxCountdownTime(); else return Config.config.skipNoticeDuration; }; //the id for the setInterval running the countdown this.countdownInterval = null; this.amountOfPreviousNotices = props.amountOfPreviousNotices || 0; this.idSuffix = props.idSuffix || ""; // Setup state this.state = { maxCountdownTime, //the countdown until this notice closes countdownTime: maxCountdownTime(), countdownMode: CountdownMode.Timer, mouseHovering: false, startFaded: this.props.startFaded ?? false, mouseDownInfo: null, mouseMoved: false, right: bounds[0], bottom: props.showInSecondSlot ? 290 : bounds[1] } } componentDidMount(): void { this.startCountdown(); } render(): React.ReactElement { const noticeStyle: React.CSSProperties = { zIndex: this.props.zIndex || (1000 + this.amountOfPreviousNotices), right: this.state.right, bottom: this.state.bottom, userSelect: this.state.mouseDownInfo && this.state.mouseMoved ? "none" : "auto", ...(this.props.style ?? {}) } return (
this.onMouseEnter(e) } onMouseLeave={() => { this.timerMouseLeave(); }} onMouseDown={(e) => { document.addEventListener("mousemove", this.handleMouseMoveBinded); this.setState({ mouseDownInfo: { x: e.clientX, y: e.clientY, right: this.state.right, bottom: this.state.bottom }, mouseMoved: false }); }} onMouseUp={() => { document.removeEventListener("mousemove", this.handleMouseMoveBinded); this.setState({ mouseDownInfo: null }); }} ref={this.parentRef} style={noticeStyle} >
{/* First row */} {/* Left column */} {this.props.firstRow} {/* Right column */} {!this.props.hideRightInfo && } {this.props.children} {!this.props.smaller && this.props.bottomRow ? this.props.bottomRow : null}
{/* Logo */} {!this.props.hideLogo && ( !Config.config.prideTheme ? : ) } {this.props.noticeTitle} {this.props.firstColumn} {/* Time left */} {this.props.timed ? ( this.toggleManualPause()} className="sponsorSkipObject sponsorSkipNoticeTimeLeft"> {this.getCountdownElements()} ) : ""} {/* Close button */} this.close()}>
{/* Add as a hidden table to keep the height constant */} {this.props.smaller && this.props.bottomRow ? {this.props.bottomRow}
: null}
); } getCountdownElements(): React.ReactElement[] { return [( {chrome.i18n.getMessage("NoticeTimeAfterSkip").replace("{seconds}", Math.ceil(this.state.countdownTime).toString())} ),( {chrome.i18n.getMessage("paused")} ),( {chrome.i18n.getMessage("manualPaused")} )]; } onMouseEnter(event: React.MouseEvent): void { if (this.props.onMouseEnter) this.props.onMouseEnter(event); this.fadedMouseEnter(); this.timerMouseEnter(); } fadedMouseEnter(): void { if (this.state.startFaded) { this.setState({ startFaded: false }); } } timerMouseEnter(): void { if (this.state.countdownMode === CountdownMode.Stopped) return; this.pauseCountdown(); this.setState({ mouseHovering: true }); } timerMouseLeave(): void { if (this.state.countdownMode === CountdownMode.Stopped) return; this.startCountdown(); this.setState({ mouseHovering: false }); } toggleManualPause(): void { this.setState({ countdownMode: this.state.countdownMode === CountdownMode.Stopped ? CountdownMode.Timer : CountdownMode.Stopped }, () => { if (this.state.countdownMode === CountdownMode.Stopped || this.state.mouseHovering) { this.pauseCountdown(); } else { this.startCountdown(); } }); } //called every second to lower the countdown before hiding the notice countdown(): void { if (!this.props.timed) return; const countdownTime = Math.min(this.state.countdownTime - 1, this.state.maxCountdownTime()); if (countdownTime <= 0) { //remove this from setInterval clearInterval(this.countdownInterval); //time to close this notice this.close(); return; } if (countdownTime == 3 && this.props.fadeOut) { //start fade out animation const notice = document.getElementById("sponsorSkipNotice" + this.idSuffix); notice?.style.removeProperty("animation"); notice?.classList.add("sponsorSkipNoticeFadeOut"); } this.setState({ countdownTime }) } removeFadeAnimation(): void { //remove the fade out class if it exists const notice = document.getElementById("sponsorSkipNotice" + this.idSuffix); notice.classList.remove("sponsorSkipNoticeFadeOut"); notice.style.animation = "none"; } pauseCountdown(): void { if (!this.props.timed || this.props.dontPauseCountdown) return; //remove setInterval if (this.countdownInterval) clearInterval(this.countdownInterval); this.countdownInterval = null; //reset countdown and inform the user this.setState({ countdownTime: this.state.maxCountdownTime(), countdownMode: this.state.countdownMode === CountdownMode.Timer ? CountdownMode.Paused : this.state.countdownMode }); this.removeFadeAnimation(); } startCountdown(): void { if (!this.props.timed) return; //if it has already started, don't start it again if (this.countdownInterval !== null) return; this.setState({ countdownTime: this.state.maxCountdownTime(), countdownMode: CountdownMode.Timer }); this.setupInterval(); } setupInterval(): void { if (this.countdownInterval) clearInterval(this.countdownInterval); this.countdownInterval = setInterval(this.countdown.bind(this), 1000); } resetCountdown(): void { if (!this.props.timed) return; this.setupInterval(); this.setState({ countdownTime: this.state.maxCountdownTime(), countdownMode: CountdownMode.Timer }); this.removeFadeAnimation(); } /** * @param silent If true, the close listener will not be called */ close(silent?: boolean): void { //remove setInterval if (this.countdownInterval !== null) clearInterval(this.countdownInterval); if (!silent) this.props.closeListener(); } addNoticeInfoMessage(message: string, message2 = ""): void { //TODO: Replace const previousInfoMessage = document.getElementById("sponsorTimesInfoMessage" + this.idSuffix); if (previousInfoMessage != null) { //remove it document.getElementById("sponsorSkipNotice" + this.idSuffix).removeChild(previousInfoMessage); } const previousInfoMessage2 = document.getElementById("sponsorTimesInfoMessage" + this.idSuffix + "2"); if (previousInfoMessage2 != null) { //remove it document.getElementById("sponsorSkipNotice" + this.idSuffix).removeChild(previousInfoMessage2); } //add info const thanksForVotingText = document.createElement("p"); thanksForVotingText.id = "sponsorTimesInfoMessage" + this.idSuffix; thanksForVotingText.className = "sponsorTimesInfoMessage"; thanksForVotingText.innerText = message; //add element to div document.querySelector("#sponsorSkipNotice" + this.idSuffix + " > tbody").insertBefore(thanksForVotingText, document.getElementById("sponsorSkipNoticeSpacer" + this.idSuffix)); if (message2 !== undefined) { const thanksForVotingText2 = document.createElement("p"); thanksForVotingText2.id = "sponsorTimesInfoMessage" + this.idSuffix + "2"; thanksForVotingText2.className = "sponsorTimesInfoMessage"; thanksForVotingText2.innerText = message2; //add element to div document.querySelector("#sponsorSkipNotice" + this.idSuffix + " > tbody").insertBefore(thanksForVotingText2, document.getElementById("sponsorSkipNoticeSpacer" + this.idSuffix)); } } getElement(): React.RefObject { return this.parentRef; } componentWillUnmount(): void { document.removeEventListener("mousemove", this.handleMouseMoveBinded); } // For dragging around notice handleMouseMove(e: MouseEvent): void { if (this.state.mouseDownInfo && e.buttons === 1) { const [mouseX, mouseY] = [e.clientX, e.clientY]; const deltaX = mouseX - this.state.mouseDownInfo.x; const deltaY = mouseY - this.state.mouseDownInfo.y; if (deltaX > 0 || deltaY > 0) this.setState({ mouseMoved: true }); const element = this.parentRef.current; const parent = element.parentElement.parentElement; this.setState({ right: Math.min(parent.clientWidth - element.clientWidth - bounds[2], Math.max(bounds[0], this.state.mouseDownInfo.right - deltaX)), bottom: Math.min(parent.clientHeight - element.clientHeight - bounds[3], Math.max(bounds[1], this.state.mouseDownInfo.bottom - deltaY)) }); } else { document.removeEventListener("mousemove", this.handleMouseMoveBinded); } } } export default NoticeComponent; ================================================ FILE: src/components/NoticeTextSectionComponent.tsx ================================================ import * as React from "react"; export interface NoticeTextSelectionProps { icon?: string; text: string; idSuffix: string; onClick?: (event: React.MouseEvent) => unknown; children?: React.ReactNode; } export interface NoticeTextSelectionState { } class NoticeTextSelectionComponent extends React.Component { constructor(props: NoticeTextSelectionProps) { super(props); } render(): React.ReactElement { const style: React.CSSProperties = {}; if (this.props.onClick) { style.cursor = "pointer"; style.textDecoration = "underline" } return ( {this.props.icon ? : null} {this.getTextElements(this.props.text)} ); } private getTextElements(text: string): Array { const elements: Array = []; const textParts = text.split(/(?=\s+)/); for (const textPart of textParts) { if (textPart.match(/^\s*http/)) { elements.push( {textPart} ); } else { elements.push(textPart); } } return elements; } } export default NoticeTextSelectionComponent; ================================================ FILE: src/components/SelectorComponent.tsx ================================================ import * as React from "react"; export interface SelectorOption { label: string; } export interface SelectorProps { id: string; options: SelectorOption[]; onChange: (value: string) => void; onMouseEnter?: () => void; onMouseLeave?: () => void; } export interface SelectorState { } class SelectorComponent extends React.Component { constructor(props: SelectorProps) { super(props); // Setup state this.state = { } } render(): React.ReactElement { return (
0 ? "inherit" : "none"}} className="sbSelector">
{this.getOptions()}
); } getOptions(): React.ReactElement[] { const result: React.ReactElement[] = []; for (const option of this.props.options) { result.push(
{ e.stopPropagation(); this.props.onChange(option.label); }} key={option.label}> {option.label}
); } return result; } } export default SelectorComponent; ================================================ FILE: src/components/SkipNoticeComponent.tsx ================================================ import * as React from "react"; import * as CompileConfig from "../../config.json"; import Config from "../config" import { Category, ContentContainer, SponsorTime, NoticeVisibilityMode, ActionType, SponsorSourceType, SegmentUUID } from "../types"; import NoticeComponent from "./NoticeComponent"; import NoticeTextSelectionComponent from "./NoticeTextSectionComponent"; import Utils from "../utils"; const utils = new Utils(); import { getSkippingText, getUpcomingText, getVoteText } from "../utils/categoryUtils"; import ThumbsUpSvg from "../svg-icons/thumbs_up_svg"; import ThumbsDownSvg from "../svg-icons/thumbs_down_svg"; import PencilSvg from "../svg-icons/pencil_svg"; import { downvoteButtonColor, SkipNoticeAction } from "../utils/noticeUtils"; import { generateUserID } from "../../maze-utils/src/setup"; import { keybindToString } from "../../maze-utils/src/config"; import { getFormattedTime } from "../../maze-utils/src/formating"; import { getCurrentTime, getVideo } from "../../maze-utils/src/video"; enum SkipButtonState { Undo, // Unskip Redo, // Reskip Start // Skip } export interface SkipNoticeProps { segments: SponsorTime[]; autoSkip: boolean; startReskip?: boolean; upcomingNotice?: boolean; voteNotice?: boolean; // Contains functions and variables from the content script needed by the skip notice contentContainer: ContentContainer; closeListener: () => void; showKeybindHint?: boolean; smaller: boolean; fadeIn: boolean; maxCountdownTime?: number; componentDidMount?: () => void; unskipTime?: number; } export interface SkipNoticeState { noticeTitle?: string; messages?: string[]; messageOnClick?: (event: React.MouseEvent) => unknown; countdownTime?: number; maxCountdownTime?: () => number; countdownText?: string; skipButtonStates?: SkipButtonState[]; skipButtonCallbacks?: Array<(buttonIndex: number, index: number, forceSeek: boolean) => void>; showSkipButton?: boolean[]; editing?: boolean; choosingCategory?: boolean; thanksForVotingText?: string; //null until the voting buttons should be hidden actionState?: SkipNoticeAction; showKeybindHint?: boolean; smaller?: boolean; voted?: SkipNoticeAction[]; copied?: SkipNoticeAction[]; } class SkipNoticeComponent extends React.Component { segments: SponsorTime[]; autoSkip: boolean; // Contains functions and variables from the content script needed by the skip notice contentContainer: ContentContainer; amountOfPreviousNotices: number; showInSecondSlot: boolean; idSuffix: string; noticeRef: React.MutableRefObject; categoryOptionRef: React.RefObject; selectedColor: string; unselectedColor: string; lockedColor: string; // Used to update on config change configListener: () => void; constructor(props: SkipNoticeProps) { super(props); this.noticeRef = React.createRef(); this.categoryOptionRef = React.createRef(); this.segments = props.segments; this.autoSkip = props.autoSkip; this.contentContainer = props.contentContainer; const noticeTitle = this.props.voteNotice ? getVoteText(this.segments) : !this.props.upcomingNotice ? getSkippingText(this.segments, this.props.autoSkip) : getUpcomingText(this.segments); const previousSkipNotices = document.querySelectorAll(".sponsorSkipNoticeParent:not(.sponsorSkipUpcomingNotice)"); this.amountOfPreviousNotices = previousSkipNotices.length; // If there is at least one already in the first slot this.showInSecondSlot = previousSkipNotices.length > 0 && [...previousSkipNotices].some(notice => !notice.classList.contains("secondSkipNotice")); // Sort segments if (this.segments.length > 1) { this.segments.sort((a, b) => a.segment[0] - b.segment[0]); } // This is the suffix added at the end of every id for (const segment of this.segments) { this.idSuffix += segment.UUID; } this.idSuffix += this.amountOfPreviousNotices; this.selectedColor = Config.config.colorPalette.red; this.unselectedColor = Config.config.colorPalette.white; this.lockedColor = Config.config.colorPalette.locked; const isMuteSegment = this.segments[0].actionType === ActionType.Mute; const maxCountdownTime = props.maxCountdownTime ? () => props.maxCountdownTime : (isMuteSegment ? this.getFullDurationCountdown(0) : () => Config.config.skipNoticeDuration); const defaultSkipButtonState = this.props.startReskip ? SkipButtonState.Redo : SkipButtonState.Undo; const skipButtonStates = [defaultSkipButtonState, isMuteSegment ? SkipButtonState.Start : defaultSkipButtonState]; const defaultSkipButtonCallback = this.props.startReskip ? this.reskip.bind(this) : this.unskip.bind(this); const skipButtonCallbacks = [defaultSkipButtonCallback, isMuteSegment ? this.reskip.bind(this) : defaultSkipButtonCallback]; // Setup state this.state = { noticeTitle, messages: [], messageOnClick: null, //the countdown until this notice closes maxCountdownTime, countdownTime: maxCountdownTime(), countdownText: null, skipButtonStates, skipButtonCallbacks, showSkipButton: [true, true], editing: false, choosingCategory: false, thanksForVotingText: null, actionState: SkipNoticeAction.None, showKeybindHint: this.props.showKeybindHint ?? true, smaller: this.props.smaller ?? false, // Keep track of what segment the user interacted with. voted: new Array(this.props.segments.length).fill(SkipNoticeAction.None), copied: new Array(this.props.segments.length).fill(SkipNoticeAction.None), } if (!this.autoSkip) { // Assume manual skip is only skipping 1 submission Object.assign(this.state, this.getUnskippedModeInfo(null, 0, SkipButtonState.Start)); } } render(): React.ReactElement { const noticeStyle: React.CSSProperties = { } if (this.contentContainer().onMobileYouTube) { noticeStyle.bottom = "4em"; noticeStyle.transform = "scale(0.8) translate(10%, 10%)"; } const firstColumn = this.getSkipButton(0); return ( = NoticeVisibilityMode.FadedForAll || (Config.config.noticeVisibilityMode >= NoticeVisibilityMode.FadedForAutoSkip && this.autoSkip)} timed={true} maxCountdownTime={this.state.maxCountdownTime} style={noticeStyle} biggerCloseButton={this.contentContainer().onMobileYouTube} ref={this.noticeRef} closeListener={() => this.closeListener()} smaller={this.state.smaller} logoFill={Config.config.barTypes[this.segments[0].category].color} limitWidth={true} firstColumn={firstColumn} dontPauseCountdown={!!this.props.upcomingNotice} bottomRow={[...this.getMessageBoxes(), ...this.getBottomRow() ]} extraClass={this.props.upcomingNotice ? "sponsorSkipUpcomingNotice" : ""} onMouseEnter={() => this.onMouseEnter() } > ); } componentDidMount(): void { if (this.props.componentDidMount) { this.props.componentDidMount(); } } getBottomRow(): JSX.Element[] { return [ /* Bottom Row */ ( {/* Vote Button Container */} {!this.state.thanksForVotingText ? {/* Upvote Button */}
this.prepAction(SkipNoticeAction.Upvote)}>
{/* Report Button */}
this.prepAction(SkipNoticeAction.Downvote)}>
{/* Copy and Downvote Button */} { !this.props.voteNotice &&
this.openEditingOptions()}>
} : {/* Submitted string */} {this.state.thanksForVotingText} {/* Continue Voting Button */} } {/* Unskip/Skip Button */} {!this.props.voteNotice && (!this.props.smaller || this.segments[0].actionType === ActionType.Mute) ? this.getSkipButton(1) : null} {/* Never show button */} {!this.autoSkip || this.props.startReskip || this.props.voteNotice ? "" : } ), /* Edit Segments Row */ (this.state.editing && !this.state.thanksForVotingText && !(this.state.choosingCategory || this.state.actionState === SkipNoticeAction.CopyDownvote) && {/* Copy Segment */} {/* Category vote */} ), /* Category Chooser Row */ (this.state.choosingCategory && !this.state.thanksForVotingText && {/* Category Selector */} {/* Submit Button */} {this.segments.length === 1 && } ), /* Segment Chooser Row */ (this.state.actionState !== SkipNoticeAction.None && this.segments.length > 1 && !this.state.thanksForVotingText && {this.getSubmissionChooser()} ) ]; } getSkipButton(buttonIndex: number): JSX.Element { if (this.state.showSkipButton[buttonIndex] && (this.segments.length > 1 || this.segments[0].actionType !== ActionType.Poi || this.props.unskipTime)) { const forceSeek = buttonIndex === 1 && this.segments[0].actionType === ActionType.Mute; const style: React.CSSProperties = { marginLeft: "4px", color: ([SkipNoticeAction.Unskip0, SkipNoticeAction.Unskip1].includes(this.state.actionState)) ? this.selectedColor : this.unselectedColor }; if (this.contentContainer().onMobileYouTube) { style.padding = "20px"; style.minWidth = "100px"; } const showSkipButton = (buttonIndex !== 0 || this.props.smaller || !this.props.voteNotice || this.segments[0].actionType === ActionType.Mute) && !this.props.upcomingNotice; return ( ); } return null; } getSubmissionChooser(): JSX.Element[] { const elements: JSX.Element[] = []; for (let i = 0; i < this.segments.length; i++) { elements.push( ); } return elements; } getSubmissionChooserOpacity(index: number): number { const isUpvote = this.state.actionState === SkipNoticeAction.Upvote; const isDownvote = this.state.actionState == SkipNoticeAction.Downvote; const isCopyDownvote = this.state.actionState == SkipNoticeAction.CopyDownvote; const shouldBeGray: boolean = (isUpvote && this.state.voted[index] == SkipNoticeAction.Upvote) || (isDownvote && this.state.voted[index] == SkipNoticeAction.Downvote) || (isCopyDownvote && this.state.copied[index] == SkipNoticeAction.CopyDownvote); return shouldBeGray ? 0.35 : 1; } getSubmissionChooserColor(index: number): string { const isDownvote = this.state.actionState == SkipNoticeAction.Downvote; const isCopyDownvote = this.state.actionState == SkipNoticeAction.CopyDownvote; const shouldWarnUser = Config.config.isVip && (isDownvote || isCopyDownvote) && this.segments[index].locked === 1; return shouldWarnUser ? this.lockedColor : this.unselectedColor; } onMouseEnter(): void { if (this.state.smaller && !this.props.upcomingNotice) { this.setState({ smaller: false }); } } getMessageBoxes(): JSX.Element[] { if (this.state.messages.length === 0) { // Add a spacer if there is no text return [ ]; } const elements: JSX.Element[] = []; for (let i = 0; i < this.state.messages.length; i++) { elements.push( ) } return elements; } prepAction(action: SkipNoticeAction): void { if (this.segments.length === 1) { this.performAction(0, action); } else { if (this.state.smaller) { this.setState({ smaller: false }); this.noticeRef.current.fadedMouseEnter(); this.noticeRef.current.resetCountdown(); } switch (action ?? this.state.actionState) { case SkipNoticeAction.None: this.resetStateToStart(); break; case SkipNoticeAction.Upvote: this.resetStateToStart(SkipNoticeAction.Upvote); break; case SkipNoticeAction.Downvote: this.resetStateToStart(SkipNoticeAction.Downvote); break; case SkipNoticeAction.CategoryVote: this.resetStateToStart(SkipNoticeAction.CategoryVote, true, true); break; case SkipNoticeAction.CopyDownvote: this.resetStateToStart(SkipNoticeAction.CopyDownvote, true); break; case SkipNoticeAction.Unskip0: this.resetStateToStart(SkipNoticeAction.Unskip0); break; case SkipNoticeAction.Unskip1: this.resetStateToStart(SkipNoticeAction.Unskip1); break; } } } /** * Performs the action from the current state * * @param index */ performAction(index: number, action?: SkipNoticeAction): void { switch (action ?? this.state.actionState) { case SkipNoticeAction.None: this.noAction(index); break; case SkipNoticeAction.Upvote: this.upvote(index); break; case SkipNoticeAction.Downvote: this.downvote(index); break; case SkipNoticeAction.CategoryVote: this.categoryVote(index); break; case SkipNoticeAction.CopyDownvote: this.copyDownvote(index); break; case SkipNoticeAction.Unskip0: this.unskipAction(0, index, false); break; case SkipNoticeAction.Unskip1: this.unskipAction(1, index, true); break; default: this.resetStateToStart(); break; } } noAction(index: number): void { const voted = this.state.voted; voted[index] = SkipNoticeAction.None; this.setState({ voted }); } upvote(index: number): void { if (this.segments.length === 1) this.resetStateToStart(); this.contentContainer().vote(1, this.segments[index].UUID, undefined, this); } downvote(index: number): void { if (this.segments.length === 1) this.resetStateToStart(); this.contentContainer().vote(0, this.segments[index].UUID, undefined, this); } categoryVote(index: number): void { this.contentContainer().vote(undefined, this.segments[index].UUID, this.categoryOptionRef.current.value as Category, this) } copyDownvote(index: number): void { const sponsorVideoID = this.props.contentContainer().sponsorVideoID; const sponsorTimesSubmitting : SponsorTime = { segment: this.segments[index].segment, UUID: generateUserID() as SegmentUUID, category: this.segments[index].category, actionType: this.segments[index].actionType, source: SponsorSourceType.Local }; const segmentTimes = Config.local.unsubmittedSegments[sponsorVideoID] || []; segmentTimes.push(sponsorTimesSubmitting); Config.local.unsubmittedSegments[sponsorVideoID] = segmentTimes; Config.forceLocalUpdate("unsubmittedSegments"); this.props.contentContainer().sponsorTimesSubmitting.push(sponsorTimesSubmitting); this.props.contentContainer().updatePreviewBar(); this.props.contentContainer().resetSponsorSubmissionNotice(); this.props.contentContainer().updateEditButtonsOnPlayer(); this.contentContainer().vote(0, this.segments[index].UUID, undefined, this); const copied = this.state.copied; copied[index] = SkipNoticeAction.CopyDownvote; this.setState({ copied }); } unskipAction(buttonIndex: number, index: number, forceSeek: boolean): void { this.state.skipButtonCallbacks[buttonIndex](buttonIndex, index, forceSeek); } openEditingOptions(): void { this.resetStateToStart(undefined, true); } getCategoryOptions(): React.ReactElement[] { const elements = []; const categories = (CompileConfig.categoryList.filter((cat => CompileConfig.categorySupport[cat].includes(ActionType.Skip)))) as Category[]; for (const category of categories) { elements.push( ); } return elements; } getCategoryNameClass(category: string): string { return this.props.contentContainer().lockedCategories.includes(category) ? "sponsorBlockLockedColor" : "" } unskip(buttonIndex: number, index: number, forceSeek: boolean): void { this.contentContainer().unskipSponsorTime(this.segments[index], this.props.unskipTime, forceSeek, this.props.voteNotice); this.unskippedMode(buttonIndex, index, this.segments[0].actionType === ActionType.Poi ? SkipButtonState.Undo : SkipButtonState.Redo); } reskip(buttonIndex: number, index: number, forceSeek: boolean): void { this.contentContainer().reskipSponsorTime(this.segments[index], forceSeek); this.reskippedMode(buttonIndex); } reskippedMode(buttonIndex: number): void { const skipButtonStates = this.state.skipButtonStates; skipButtonStates[buttonIndex] = SkipButtonState.Undo; const skipButtonCallbacks = this.state.skipButtonCallbacks; skipButtonCallbacks[buttonIndex] = this.unskip.bind(this); const newState: SkipNoticeState = { skipButtonStates, skipButtonCallbacks, maxCountdownTime: () => Config.config.skipNoticeDuration, countdownTime: Config.config.skipNoticeDuration }; //reset countdown this.setState(newState, () => { this.noticeRef.current.resetCountdown(); }); } /** Sets up notice to be not skipped yet */ unskippedMode(buttonIndex: number, index: number, skipButtonState: SkipButtonState): void { //setup new callback and reset countdown this.setState(this.getUnskippedModeInfo(buttonIndex, index, skipButtonState), () => { this.noticeRef.current.resetCountdown(); }); } getUnskippedModeInfo(buttonIndex: number, index: number, skipButtonState: SkipButtonState): SkipNoticeState { const changeCountdown = !this.props.voteNotice && this.segments[index].actionType !== ActionType.Poi; const maxCountdownTime = changeCountdown ? this.getFullDurationCountdown(index) : this.state.maxCountdownTime; const skipButtonStates = this.state.skipButtonStates; const skipButtonCallbacks = this.state.skipButtonCallbacks; if (buttonIndex === null) { for (let i = 0; i < skipButtonStates.length; i++) { skipButtonStates[i] = skipButtonState; skipButtonCallbacks[i] = this.reskip.bind(this); } } else { skipButtonStates[buttonIndex] = skipButtonState; skipButtonCallbacks[buttonIndex] = this.reskip.bind(this); if (buttonIndex === 1) { // Trigger both to move at once skipButtonStates[0] = SkipButtonState.Redo; skipButtonCallbacks[0] = this.reskip.bind(this); } } return { skipButtonStates, skipButtonCallbacks, // change max duration to however much of the sponsor is left maxCountdownTime, countdownTime: maxCountdownTime(), showSkipButton: buttonIndex === 1 ? [true, true] : this.state.showSkipButton } as SkipNoticeState; } getFullDurationCountdown(index: number): () => number { return () => { const sponsorTime = this.segments[index]; const duration = Math.round((sponsorTime.segment[1] - (getCurrentTime() ?? 0)) * (1 / (getVideo()?.playbackRate ?? 1))); return Math.max(duration, Config.config.skipNoticeDuration); }; } afterVote(segment: SponsorTime, type: number, category: Category): void { const index = utils.getSponsorIndexFromUUID(this.segments, segment.UUID); const wikiLinkText = CompileConfig.wikiLinks[segment.category]; const voted = this.state.voted; switch (type) { case 0: this.clearConfigListener(); this.setNoticeInfoMessageWithOnClick(() => window.open(wikiLinkText), chrome.i18n.getMessage("OpenCategoryWikiPage")); voted[index] = SkipNoticeAction.Downvote; break; case 1: voted[index] = SkipNoticeAction.Upvote; break; case 20: voted[index] = SkipNoticeAction.None; break; } this.setState({ voted }); this.addVoteButtonInfo(chrome.i18n.getMessage("voted")); if (segment && category) { // This is the segment inside the skip notice this.segments[index].category = category; } } setNoticeInfoMessageWithOnClick(onClick: (event: React.MouseEvent) => unknown, ...messages: string[]): void { this.setState({ messages, messageOnClick: (event) => onClick(event) }); } setNoticeInfoMessage(...messages: string[]): void { this.setState({ messages }); } addVoteButtonInfo(message: string): void { this.setState({ thanksForVotingText: message }); } resetVoteButtonInfo(): void { this.setState({ thanksForVotingText: null }); } closeListener(): void { this.clearConfigListener(); this.props.closeListener(); } clearConfigListener(): void { if (this.configListener) { Config.configSyncListeners.splice(Config.configSyncListeners.indexOf(this.configListener), 1); this.configListener = null; } } unmutedListener(time: number): void { if (this.props.segments.length === 1 && this.props.segments[0].actionType === ActionType.Mute && time >= this.props.segments[0].segment[1]) { this.setState({ showSkipButton: [false, true] }); } } resetStateToStart(actionState: SkipNoticeAction = SkipNoticeAction.None, editing = false, choosingCategory = false): void { this.setState({ actionState: actionState, editing: editing, choosingCategory: choosingCategory, thanksForVotingText: null, messages: [] }); } private getSkipButtonText(buttonIndex: number, forceType?: ActionType): string { switch (this.state.skipButtonStates[buttonIndex]) { case SkipButtonState.Undo: return this.getUndoText(forceType); case SkipButtonState.Redo: return this.getRedoText(forceType); case SkipButtonState.Start: return this.getStartText(forceType); } } private getUndoText(forceType?: ActionType): string { const actionType = forceType || this.segments[0].actionType; switch (actionType) { case ActionType.Mute: { return chrome.i18n.getMessage("unmute"); } case ActionType.Skip: default: { return chrome.i18n.getMessage("unskip"); } } } private getRedoText(forceType?: ActionType): string { const actionType = forceType || this.segments[0].actionType; switch (actionType) { case ActionType.Mute: { return chrome.i18n.getMessage("mute"); } case ActionType.Skip: default: { return chrome.i18n.getMessage("reskip"); } } } private getStartText(forceType?: ActionType): string { const actionType = forceType || this.segments[0].actionType; switch (actionType) { case ActionType.Mute: { return chrome.i18n.getMessage("mute"); } case ActionType.Skip: default: { return chrome.i18n.getMessage("skip"); } } } } export default SkipNoticeComponent; ================================================ FILE: src/components/SponsorTimeEditComponent.tsx ================================================ import * as React from "react"; import * as CompileConfig from "../../config.json"; import Config from "../config"; import { ActionType, Category, ChannelIDStatus, ContentContainer, SponsorHideType, SponsorTime } from "../types"; import SubmissionNoticeComponent from "./SubmissionNoticeComponent"; import { RectangleTooltip } from "../render/RectangleTooltip"; import SelectorComponent, { SelectorOption } from "./SelectorComponent"; import { DEFAULT_CATEGORY } from "../utils/categoryUtils"; import { getFormattedTime, getFormattedTimeToSeconds } from "../../maze-utils/src/formating"; import { asyncRequestToServer } from "../utils/requests"; import { defaultPreviewTime } from "../utils/constants"; import { getVideo, getVideoDuration } from "../../maze-utils/src/video"; import { AnimationUtils } from "../../maze-utils/src/animationUtils"; import { Tooltip } from "../render/Tooltip"; import { logRequest } from "../../maze-utils/src/background-request-proxy"; export interface SponsorTimeEditProps { index: number; idSuffix: string; // Contains functions and variables from the content script needed by the skip notice contentContainer: ContentContainer; submissionNotice: SubmissionNoticeComponent; categoryList?: Category[]; categoryChangeListener?: (index: number, category: Category) => void; children?: React.ReactNode; } export interface SponsorTimeEditState { editing: boolean; sponsorTimeEdits: [string, string]; selectedCategory: Category; selectedActionType: ActionType; description: string; suggestedNames: SelectorOption[]; chapterNameSelectorOpen: boolean; chapterNameSelectorHovering: boolean; } const categoryNamesGrams: string[] = [].concat(...CompileConfig.categoryList.filter((name) => !["chapter", "intro"].includes(name)) .map((name) => chrome.i18n.getMessage("category_" + name).split(/\/|\s|-/))); class SponsorTimeEditComponent extends React.Component { idSuffix: string; categoryOptionRef: React.RefObject; actionTypeOptionRef: React.RefObject; descriptionOptionRef: React.RefObject; configUpdateListener: () => void; previousSkipType: ActionType; // Used when selecting POI or Full timesBeforeChanging: number[] = []; fullVideoWarningShown = false; categoryNameWarningShown = false; // For description auto-complete fetchingSuggestions: boolean; constructor(props: SponsorTimeEditProps) { super(props); this.categoryOptionRef = React.createRef(); this.actionTypeOptionRef = React.createRef(); this.descriptionOptionRef = React.createRef(); this.idSuffix = this.props.idSuffix; this.previousSkipType = ActionType.Skip; const sponsorTime = this.props.contentContainer().sponsorTimesSubmitting[this.props.index]; this.state = { editing: false, sponsorTimeEdits: [null, null], selectedCategory: sponsorTime.category ?? DEFAULT_CATEGORY as Category, selectedActionType: sponsorTime.actionType, description: sponsorTime.description || "", suggestedNames: [], chapterNameSelectorOpen: false, chapterNameSelectorHovering: false }; } componentDidMount(): void { // Prevent inputs from triggering key events document.getElementById("sponsorTimeEditContainer" + this.idSuffix).addEventListener('keydown', (e) => { e.stopPropagation(); }); // Prevent scrolling while changing times document.getElementById("sponsorTimesContainer" + this.idSuffix).addEventListener('wheel', (e) => { if (this.state.editing) { e.preventDefault(); } }, {passive: false}); // Add as a config listener if (!this.configUpdateListener) { this.configUpdateListener = () => this.configUpdate(); Config.configSyncListeners.push(this.configUpdate.bind(this)); } this.checkToShowFullVideoWarning(); } componentWillUnmount(): void { if (this.configUpdateListener) { Config.configSyncListeners.splice(Config.configSyncListeners.indexOf(this.configUpdate.bind(this)), 1); } } render(): React.ReactElement { this.checkToShowFullVideoWarning(); this.checkToShowChapterWarning(); const style: React.CSSProperties = { textAlign: "center" }; if (this.props.index != 0) { style.marginTop = "15px"; } const borderColor = this.state.selectedCategory ? Config.config.barTypes[this.state.selectedCategory]?.color : null; // Create time display let timeDisplay: JSX.Element; const timeDisplayStyle: React.CSSProperties = {}; const sponsorTime = this.props.contentContainer().sponsorTimesSubmitting[this.props.index]; const segment = sponsorTime.segment; if (this.state.selectedActionType === ActionType.Full) timeDisplayStyle.display = "none"; if (this.state.editing) { timeDisplay = (
{this.state.selectedActionType !== ActionType.Poi ? ( this.setTimeTo(0, 0)}> {chrome.i18n.getMessage("bracketStart")} ): ""} this.setTimeToNow(0)}> {chrome.i18n.getMessage("bracketNow")} e.stopPropagation()} onKeyUp={(e) => e.stopPropagation()} onChange={(e) => this.handleOnChange(0, e, sponsorTime, e.target.value)} onWheel={(e) => this.changeTimesWhenScrolling(0, e, sponsorTime)}> {this.state.selectedActionType !== ActionType.Poi ? ( {" " + chrome.i18n.getMessage("to") + " "} e.stopPropagation()} onKeyUp={(e) => e.stopPropagation()} onChange={(e) => this.handleOnChange(1, e, sponsorTime, e.target.value)} onWheel={(e) => this.changeTimesWhenScrolling(1, e, sponsorTime)}> this.setTimeToNow(1)}> {chrome.i18n.getMessage("bracketNow")} this.setTimeToEnd()}> {chrome.i18n.getMessage("bracketEnd")} ): ""}
); } else { timeDisplay = (
{getFormattedTime(segment[0], true) + ((!isNaN(segment[1]) && this.state.selectedActionType !== ActionType.Poi) ? " " + chrome.i18n.getMessage("to") + " " + getFormattedTime(segment[1], true) : "")}
); } return (
{timeDisplay} {/* Category */}
{/* open in new tab */}
{/* Action Type */} {CompileConfig.categorySupport[sponsorTime.category] && (CompileConfig.categorySupport[sponsorTime.category]?.length > 1 || CompileConfig.categorySupport[sponsorTime.category]?.[0] === ActionType.Full) ? (
{ const stopAnimation = AnimationUtils.applyLoadingAnimation(e.currentTarget, 0.4); stopAnimation(); if (sponsorTime.hidden === SponsorHideType.Hidden) { sponsorTime.hidden = SponsorHideType.Visible; } else { sponsorTime.hidden = SponsorHideType.Hidden; } this.saveEditTimes(); }}/>
): ""} {/* Chapter Name */} {this.state.selectedActionType=== ActionType.Chapter ? (
this.setState({chapterNameSelectorOpen: false})}> e.stopPropagation()} onKeyUp={(e) => e.stopPropagation()} onContextMenu={(e) => e.stopPropagation()} onChange={(e) => this.descriptionUpdate(e.target.value)} onFocus={() => this.setState({chapterNameSelectorOpen: true})}> {this.state.description && (this.state.chapterNameSelectorOpen || this.state.chapterNameSelectorHovering) && this.setState({chapterNameSelectorHovering: true})} onMouseLeave={() => this.setState({chapterNameSelectorHovering: false})} onChange={(v) => this.descriptionUpdate(v)} /> }
): ""} {/* Editing Tools */}
{chrome.i18n.getMessage("delete")} {(!isNaN(segment[1]) && ![ActionType.Poi, ActionType.Full].includes(this.state.selectedActionType)) && this.state.selectedActionType !== ActionType.Chapter ? ( this.previewTime(e.ctrlKey, e.shiftKey)}> {chrome.i18n.getMessage("preview")} ): ""} {(!isNaN(segment[0]) && this.state.selectedActionType != ActionType.Full) ? ( {chrome.i18n.getMessage("inspect")} ): ""} {(!isNaN(segment[1]) && ![ActionType.Poi, ActionType.Full].includes(this.state.selectedActionType)) ? ( this.previewTime(e.ctrlKey, e.shiftKey, true)}> {chrome.i18n.getMessage("End")} ): ""} {(!isNaN(segment[1]) && this.state.selectedActionType != ActionType.Full) ? ( {this.state.editing ? chrome.i18n.getMessage("save") : chrome.i18n.getMessage("edit")} ): ""}
); } handleOnChange(index: number, e: React.ChangeEvent, sponsorTime: SponsorTime, targetValue: string): void { const sponsorTimeEdits = this.state.sponsorTimeEdits; // check if change is small engough to show tooltip const before = getFormattedTimeToSeconds(sponsorTimeEdits[index]); const after = getFormattedTimeToSeconds(targetValue); const difference = Math.abs(before - after); if (0 < difference && difference < 0.5) this.showScrollToEditToolTip(); sponsorTimeEdits[index] = targetValue; if (index === 0 && sponsorTime.actionType === ActionType.Poi) sponsorTimeEdits[1] = targetValue; this.setState({sponsorTimeEdits}, () => this.saveEditTimes()); } changeTimesWhenScrolling(index: number, e: React.WheelEvent, sponsorTime: SponsorTime): void { if (!Config.config.allowScrollingToEdit) return; let step = 0; // shift + ctrl = 1 // ctrl = 0.1 // default = 0.01 // shift = 0.001 if (e.shiftKey) { step = (e.ctrlKey) ? 1 : 0.001; } else { step = (e.ctrlKey) ? 0.1 : 0.01; } const sponsorTimeEdits = this.state.sponsorTimeEdits; let timeAsNumber = getFormattedTimeToSeconds(this.state.sponsorTimeEdits[index]); if (timeAsNumber !== null && e.deltaY != 0) { if (e.deltaY < 0) { timeAsNumber += step; } else if (timeAsNumber >= step) { timeAsNumber -= step; } else { timeAsNumber = 0; } sponsorTimeEdits[index] = getFormattedTime(timeAsNumber, true); if (sponsorTime.actionType === ActionType.Poi) sponsorTimeEdits[1] = sponsorTimeEdits[0]; this.setState({sponsorTimeEdits}); this.saveEditTimes(); } } showScrollToEditToolTip(): void { if (!Config.config.scrollToEditTimeUpdate && document.getElementById("sponsorRectangleTooltip" + "sponsorTimesContainer" + this.idSuffix) === null) { this.showToolTip(chrome.i18n.getMessage("SponsorTimeEditScrollNewFeature"), "scrollToEdit", () => { Config.config.scrollToEditTimeUpdate = true }); } } showToolTip(text: string, id: string, buttonFunction?: () => void): boolean { const element = document.getElementById("sponsorTimesContainer" + this.idSuffix); if (element) { const htmlId = `sponsorRectangleTooltip${id + this.idSuffix}`; if (!document.getElementById(htmlId)) { new RectangleTooltip({ text, referenceNode: element.parentElement, prependElement: element, timeout: 15, bottomOffset: 0 + "px", leftOffset: -318 + "px", backgroundColor: "rgba(28, 28, 28, 1.0)", htmlId, buttonFunction, fontSize: "14px", maxHeight: "200px" }); } return true; } else { return false; } } checkToShowFullVideoWarning(): void { const sponsorTime = this.props.contentContainer().sponsorTimesSubmitting[this.props.index]; const segmentDuration = sponsorTime.segment[1] - sponsorTime.segment[0]; const videoPercentage = segmentDuration / getVideoDuration(); if (videoPercentage > 0.6 && !this.fullVideoWarningShown && (sponsorTime.category === "sponsor" || sponsorTime.category === "selfpromo" || sponsorTime.category === "chooseACategory")) { if (this.showToolTip(chrome.i18n.getMessage("fullVideoTooltipWarning"), "fullVideoWarning")) { this.fullVideoWarningShown = true; } } } checkToShowChapterWarning(): void { const sponsorTime = this.props.contentContainer().sponsorTimesSubmitting[this.props.index]; if (sponsorTime.actionType === ActionType.Chapter && sponsorTime.description && !this.categoryNameWarningShown && categoryNamesGrams.some( (category) => sponsorTime.description.toLowerCase().includes(category.toLowerCase()))) { if (this.showToolTip(chrome.i18n.getMessage("chapterNameTooltipWarning"), "chapterWarning")) { this.categoryNameWarningShown = true; } } } getCategoryOptions(): React.ReactElement[] { const elements = [( )]; for (const category of (this.props.categoryList ?? CompileConfig.categoryList)) { // If permission not loaded, treat it like we have permission except chapter const defaultBlockCategories = ["chapter"]; const permission = (Config.config.showCategoryWithoutPermission || Config.config.permissions[category as Category]); if ((defaultBlockCategories.includes(category) || (permission !== undefined && !Config.config.showCategoryWithoutPermission)) && !permission) continue; elements.push( ); } return elements; } getCategoryLockedClass(category: string): string { return this.props.contentContainer().lockedCategories.includes(category) ? "sponsorBlockLockedColor" : ""; } categorySelectionChange(event: React.ChangeEvent): void { const chosenCategory = event.target.value as Category; this.setState({ selectedCategory: chosenCategory }); // See if show more categories was pressed if (chosenCategory !== DEFAULT_CATEGORY && !Config.config.categorySelections.some((category) => category.name === chosenCategory)) { event.target.value = DEFAULT_CATEGORY; // Alert that they have to enable this category first if (confirm(chrome.i18n.getMessage("enableThisCategoryFirst") .replace("{0}", chrome.i18n.getMessage("category_" + chosenCategory)))) { // Open options page chrome.runtime.sendMessage({message: "openConfig", hash: "behavior"}); } return; } // Hook update if (!Config.config.hookUpdate && chosenCategory === "preview") { Config.config.hookUpdate = true; const target = event.target.closest(".sponsorSkipNotice tbody"); if (target) { new Tooltip({ text: chrome.i18n.getMessage("hookNewFeature"), referenceNode: target.parentElement, prependElement: target as HTMLElement, bottomOffset: "30px", opacity: 0.9, timeout: 100 }); } } const sponsorTime = this.props.contentContainer().sponsorTimesSubmitting[this.props.index]; this.handleReplacingLostTimes(chosenCategory, sponsorTime.actionType, sponsorTime); this.saveEditTimes(); if (this.props.categoryChangeListener) { this.props.categoryChangeListener(this.props.index, chosenCategory); } } actionTypeSelectionChange(event: React.ChangeEvent): void { const sponsorTime = this.props.contentContainer().sponsorTimesSubmitting[this.props.index]; this.setState({ selectedActionType: event.target.value as ActionType }); this.handleReplacingLostTimes(sponsorTime.category, event.target.value as ActionType, sponsorTime); this.saveEditTimes(); } private handleReplacingLostTimes(category: Category, actionType: ActionType, segment: SponsorTime): void { if (CompileConfig.categorySupport[category]?.includes(ActionType.Poi)) { if (this.previousSkipType !== ActionType.Poi) { this.timesBeforeChanging = [null, segment.segment[1]]; } this.setTimeTo(1, null); this.props.contentContainer().updateEditButtonsOnPlayer(); if (this.props.contentContainer().sponsorTimesSubmitting .some((segment, i) => segment.category === category && i !== this.props.index)) { alert(chrome.i18n.getMessage("poiOnlyOneSegment")); } this.previousSkipType = ActionType.Poi; } else if (CompileConfig.categorySupport[category]?.length === 1 && CompileConfig.categorySupport[category]?.[0] === ActionType.Full) { if (this.previousSkipType !== ActionType.Full) { this.timesBeforeChanging = [...segment.segment]; } this.previousSkipType = ActionType.Full; } else if ((category === "chooseACategory" || ((CompileConfig.categorySupport[category]?.includes(ActionType.Skip) || CompileConfig.categorySupport[category]?.includes(ActionType.Chapter)) && ![ActionType.Poi, ActionType.Full].includes(this.getNextActionType(category, actionType)))) && this.previousSkipType !== ActionType.Skip) { if (this.timesBeforeChanging[0]) { this.setTimeTo(0, this.timesBeforeChanging[0]); } if (this.timesBeforeChanging[1]) { this.setTimeTo(1, this.timesBeforeChanging[1]); } this.previousSkipType = ActionType.Skip; } } getActionTypeOptions(sponsorTime: SponsorTime): React.ReactElement[] { const elements = []; for (const actionType of CompileConfig.categorySupport[sponsorTime.category]) { elements.push( ); } return elements; } setTimeToNow(index: number): void { this.setTimeTo(index, this.props.contentContainer().getRealCurrentTime()); } setTimeToEnd(): void { this.setTimeTo(1, getVideoDuration()); } /** * @param index * @param time If null, will set time to the first index's time */ setTimeTo(index: number, time: number): void { const sponsorTime = this.props.contentContainer().sponsorTimesSubmitting[this.props.index]; if (time === null) time = sponsorTime.segment[0]; const addedTime = sponsorTime.segment.length === 1; sponsorTime.segment[index] = time; if (sponsorTime.actionType === ActionType.Poi) sponsorTime.segment[1] = time; if (addedTime) { this.props.contentContainer().updateEditButtonsOnPlayer(); } this.setState({ sponsorTimeEdits: this.getFormattedSponsorTimesEdits(sponsorTime) }, () => this.saveEditTimes()); } toggleEditTime(): void { if (this.state.editing) { this.setState({ editing: false }); this.saveEditTimes(); } else { const sponsorTime = this.props.contentContainer().sponsorTimesSubmitting[this.props.index]; this.setState({ editing: true, sponsorTimeEdits: this.getFormattedSponsorTimesEdits(sponsorTime) }); } } /** Returns an array in the sponsorTimeEdits form (formatted time string) from a normal seconds sponsor time */ getFormattedSponsorTimesEdits(sponsorTime: SponsorTime): [string, string] { return [getFormattedTime(sponsorTime.segment[0], true), getFormattedTime(sponsorTime.segment[1], true)]; } lastEditTime = 0; editTimeTimeout: NodeJS.Timeout | null = null; saveEditTimes(): void { // Rate limit edits const timeSinceLastEdit = Date.now() - this.lastEditTime; const rateLimitTime = 200; if (timeSinceLastEdit < rateLimitTime) { if (!this.editTimeTimeout) { this.editTimeTimeout = setTimeout(() => { this.saveEditTimes(); }, rateLimitTime - timeSinceLastEdit) } return; } this.lastEditTime = Date.now(); this.editTimeTimeout = null; const sponsorTimesSubmitting = this.props.contentContainer().sponsorTimesSubmitting; const category = this.categoryOptionRef.current.value as Category if (this.state.editing) { const startTime = getFormattedTimeToSeconds(this.state.sponsorTimeEdits[0]); const endTime = getFormattedTimeToSeconds(this.state.sponsorTimeEdits[1]); // Change segment time only if the format was correct if (startTime !== null && endTime !== null) { const addingTime = sponsorTimesSubmitting[this.props.index].segment.length === 1; sponsorTimesSubmitting[this.props.index].segment = [startTime, endTime]; if (addingTime) { this.props.contentContainer().updateEditButtonsOnPlayer(); } } else if (startTime !== null) { // Only start time is valid, still an incomplete segment sponsorTimesSubmitting[this.props.index].segment[0] = startTime; } } else if (this.state.sponsorTimeEdits[1] === null && category === "outro" && !sponsorTimesSubmitting[this.props.index].segment[1]) { sponsorTimesSubmitting[this.props.index].segment[1] = getVideoDuration(); this.props.contentContainer().updateEditButtonsOnPlayer(); } sponsorTimesSubmitting[this.props.index].category = category; const actionType = this.getNextActionType(category, this.actionTypeOptionRef?.current?.value as ActionType); sponsorTimesSubmitting[this.props.index].actionType = actionType; this.setState({ selectedActionType: actionType }); const description = actionType === ActionType.Chapter ? this.descriptionOptionRef?.current?.value : ""; sponsorTimesSubmitting[this.props.index].description = description; Config.local.unsubmittedSegments[this.props.contentContainer().sponsorVideoID] = sponsorTimesSubmitting; Config.forceLocalUpdate("unsubmittedSegments"); this.props.contentContainer().updatePreviewBar(); if (sponsorTimesSubmitting[this.props.index].actionType === ActionType.Full && (sponsorTimesSubmitting[this.props.index].segment[0] !== 0 || sponsorTimesSubmitting[this.props.index].segment[1] !== 0)) { this.setTimeTo(0, 0); this.setTimeTo(1, 0); } } private getNextActionType(category: Category, actionType: ActionType): ActionType { return actionType && CompileConfig.categorySupport[category]?.includes(actionType) ? actionType : CompileConfig.categorySupport[category]?.[0] ?? ActionType.Skip } previewTime(ctrlPressed = false, shiftPressed = false, skipToEndTime = false): void { const sponsorTimes = this.props.contentContainer().sponsorTimesSubmitting; const index = this.props.index; let seekTime = defaultPreviewTime; if (ctrlPressed) seekTime = 0.5; if (shiftPressed) seekTime = 0.25; const startTime = sponsorTimes[index].segment[0]; const endTime = sponsorTimes[index].segment[1]; // If segment starts at 0:00, start playback at the end of the segment const skipTime = (startTime === 0 || skipToEndTime) ? endTime : (startTime - (seekTime * getVideo().playbackRate)); this.props.contentContainer().previewTime(skipTime, !skipToEndTime); } inspectTime(): void { const sponsorTimes = this.props.contentContainer().sponsorTimesSubmitting; const index = this.props.index; const skipTime = sponsorTimes[index].segment[0]; this.props.contentContainer().previewTime(skipTime + 0.0001, false); } deleteTime(): void { const sponsorTimes = this.props.contentContainer().sponsorTimesSubmitting; const index = this.props.index; const removingIncomplete = sponsorTimes[index].segment.length < 2; sponsorTimes.splice(index, 1); //save this if (sponsorTimes.length > 0) { Config.local.unsubmittedSegments[this.props.contentContainer().sponsorVideoID] = sponsorTimes; } else { delete Config.local.unsubmittedSegments[this.props.contentContainer().sponsorVideoID]; } Config.forceLocalUpdate("unsubmittedSegments"); this.props.contentContainer().updatePreviewBar(); //if they are all removed if (sponsorTimes.length == 0) { this.props.submissionNotice.cancel(); } else { //update display this.props.submissionNotice.forceUpdate(); } //if it is not a complete segment, or all are removed if (sponsorTimes.length === 0 || removingIncomplete) { //update video player this.props.contentContainer().updateEditButtonsOnPlayer(); } } descriptionUpdate(description: string): void { this.setState({ description }, () => { this.saveEditTimes(); }); if (!this.fetchingSuggestions) { this.fetchSuggestions(description); } } async fetchSuggestions(description: string): Promise { if (this.props.contentContainer().channelIDInfo.status !== ChannelIDStatus.Found) return; this.fetchingSuggestions = true; try { const result = await asyncRequestToServer("GET", "/api/chapterNames", { description, channelID: this.props.contentContainer().channelIDInfo.id }); if (result.ok) { const names = JSON.parse(result.responseText) as {description: string}[]; this.setState({ suggestedNames: names.map(n => ({ label: n.description })) }); } else if (result.status !== 404) { logRequest(result, "SB", "chapter suggestion") } } catch (e) { console.warn("[SB] Caught error while fetching chapter suggestions", e); } finally { this.fetchingSuggestions = false; } } configUpdate(): void { this.forceUpdate(); } } export default SponsorTimeEditComponent; ================================================ FILE: src/components/SubmissionNoticeComponent.tsx ================================================ import * as React from "react"; import Config from "../config" import GenericNotice from "../render/GenericNotice"; import { Category, ContentContainer } from "../types"; import * as CompileConfig from "../../config.json"; import NoticeComponent from "./NoticeComponent"; import NoticeTextSelectionComponent from "./NoticeTextSectionComponent"; import SponsorTimeEditComponent from "./SponsorTimeEditComponent"; import { getGuidelineInfo } from "../utils/constants"; import { exportTimes } from "../utils/exporter"; import { getVideo, isCurrentTimeWrong } from "../../maze-utils/src/video"; export interface SubmissionNoticeProps { // Contains functions and variables from the content script needed by the skip notice contentContainer: ContentContainer; callback: () => Promise; closeListener: () => void; } export interface SubmissionNoticeState { noticeTitle: string; messages: string[]; idSuffix: string; } class SubmissionNoticeComponent extends React.Component { // Contains functions and variables from the content script needed by the skip notice contentContainer: ContentContainer; callback: () => unknown; noticeRef: React.MutableRefObject; timeEditRefs: React.RefObject[]; videoObserver: MutationObserver; guidelinesReminder: GenericNotice; lastSegmentCount: number; constructor(props: SubmissionNoticeProps) { super(props); this.noticeRef = React.createRef(); this.contentContainer = props.contentContainer; this.callback = props.callback; const noticeTitle = chrome.i18n.getMessage("confirmNoticeTitle"); this.lastSegmentCount = this.props.contentContainer().sponsorTimesSubmitting.length; // Setup state this.state = { noticeTitle, messages: [], idSuffix: "SubmissionNotice" }; } componentDidMount(): void { // Catch and rerender when the video size changes //TODO: Use ResizeObserver when it is supported in TypeScript this.videoObserver = new MutationObserver(() => { this.forceUpdate(); }); this.videoObserver.observe(getVideo(), { attributes: true }); // Prevent zooming while changing times document.getElementById("sponsorSkipNoticeMiddleRow" + this.state.idSuffix).addEventListener('wheel', function (event) { if (event.ctrlKey) { event.preventDefault(); } }, {passive: false}); } componentWillUnmount(): void { if (this.videoObserver) { this.videoObserver.disconnect(); } } componentDidUpdate() { const currentSegmentCount = this.props.contentContainer().sponsorTimesSubmitting.length; if (currentSegmentCount > this.lastSegmentCount) { this.lastSegmentCount = currentSegmentCount; this.scrollToBottom(); } } scrollToBottom() { const scrollElement = this.noticeRef.current.getElement().current.querySelector("#sponsorSkipNoticeMiddleRowSubmissionNotice"); scrollElement.scrollTo({ top: scrollElement.scrollHeight + 1000 }); } render(): React.ReactElement { const sortButton = this.sortSegments()} title={chrome.i18n.getMessage("sortSegments")} key="sortButton" src={chrome.runtime.getURL("icons/sort.svg")}> ; const exportButton = this.exportSegments()} title={chrome.i18n.getMessage("exportSegments")} key="exportButton" src={chrome.runtime.getURL("icons/export.svg")}> ; return ( {/* Text Boxes */} {this.getMessageBoxes()} {/* Sponsor Time List */} e.stopPropagation()}> {this.getSponsorTimeMessages()} {/* Last Row */} {/* Guidelines button */} {/* Submit Button */} ); } getSponsorTimeMessages(): JSX.Element[] | JSX.Element { const elements: JSX.Element[] = []; this.timeEditRefs = []; const sponsorTimes = this.props.contentContainer().sponsorTimesSubmitting; for (let i = 0; i < sponsorTimes.length; i++) { const timeRef = React.createRef(); elements.push( ); this.timeEditRefs.push(timeRef); } return elements; } getMessageBoxes(): JSX.Element[] | JSX.Element { const elements: JSX.Element[] = []; for (let i = 0; i < this.state.messages.length; i++) { elements.push( ); } return elements; } cancel(): void { this.guidelinesReminder?.close(); this.noticeRef.current.close(true); this.contentContainer().resetSponsorSubmissionNotice(false); this.props.closeListener(); } submit(): void { if (isCurrentTimeWrong()) { alert(chrome.i18n.getMessage("submissionFailedServerSideAds")); return; } // save all items for (const ref of this.timeEditRefs) { ref.current.saveEditTimes(); } const sponsorTimesSubmitting = this.props.contentContainer().sponsorTimesSubmitting; for (const sponsorTime of sponsorTimesSubmitting) { if (sponsorTime.category === "chooseACategory") { alert(chrome.i18n.getMessage("youMustSelectACategory")); return; } } // Check if any non music categories are being used on a music video if (this.contentContainer().videoInfo?.microformat?.playerMicroformatRenderer?.category === "Music") { for (const sponsorTime of sponsorTimesSubmitting) { if (sponsorTime.category === "sponsor") { if (!confirm(chrome.i18n.getMessage("nonMusicCategoryOnMusic"))) return; break; } } } this.props.callback().then((success) => { if (success) { this.cancel(); } }); } sortSegments(): void { let sponsorTimesSubmitting = this.props.contentContainer().sponsorTimesSubmitting; sponsorTimesSubmitting = sponsorTimesSubmitting.sort((a, b) => a.segment[0] - b.segment[0]); Config.local.unsubmittedSegments[this.props.contentContainer().sponsorVideoID] = sponsorTimesSubmitting; Config.forceLocalUpdate("unsubmittedSegments"); this.forceUpdate(); } exportSegments() { const sponsorTimesSubmitting = this.props.contentContainer() .sponsorTimesSubmitting.sort((a, b) => a.segment[0] - b.segment[0]); window.navigator.clipboard.writeText(exportTimes(sponsorTimesSubmitting)); new GenericNotice(null, "exportCopied", { title: chrome.i18n.getMessage(`CopiedExclamation`), timed: true, maxCountdownTime: () => 0.6, referenceNode: document.querySelector(".noticeLeftIcon"), dontPauseCountdown: true, style: { top: 0, bottom: 0, minWidth: 0, right: "30px", margin: "auto" }, hideLogo: true, hideRightInfo: true, extraClass: "exportCopiedNotice" }); } categoryChangeListener(index: number, category: Category): void { const dialogWidth = this.noticeRef?.current?.getElement()?.current?.offsetWidth; if (category !== "chooseACategory" && Config.config.showCategoryGuidelines && getVideo().offsetWidth > dialogWidth * 2) { const options = { title: chrome.i18n.getMessage(`category_${category}`), textBoxes: getGuidelineInfo(category), buttons: [{ name: chrome.i18n.getMessage("FullDetails"), listener: () => window.open(CompileConfig.wikiLinks[category]) }, { name: chrome.i18n.getMessage("Hide"), listener: () => { Config.config.showCategoryGuidelines = false; this.guidelinesReminder?.close(); this.guidelinesReminder = null; } }], timed: false, style: { right: `${dialogWidth + 10}px`, }, extraClass: "sb-guidelines-notice" }; if (options.textBoxes) { if (this.guidelinesReminder) { this.guidelinesReminder.update(options); } else { this.guidelinesReminder = new GenericNotice(null, "GuidelinesReminder", options); } } else { this.guidelinesReminder?.close(); this.guidelinesReminder = null; } } } } export default SubmissionNoticeComponent; ================================================ FILE: src/components/options/AdvancedSkipOptionsComponent.tsx ================================================ import * as React from "react"; import Config from "../../config"; import { configToText, parseConfig, } from "../../utils/skipRule"; import { AdvancedSkipRule } from "../../utils/skipRule.type"; let configSaveTimeout: NodeJS.Timeout | null = null; export function AdvancedSkipOptionsComponent() { const [optionsOpen, setOptionsOpen] = React.useState(false); const [config, setConfig] = React.useState(configToText(Config.local.skipRules)); const [configValid, setConfigValid] = React.useState(true); return (
{ setOptionsOpen(!optionsOpen); }}> {chrome.i18n.getMessage("openAdvancedSkipOptions")}
{ optionsOpen &&
{chrome.i18n.getMessage("advancedSkipSettingsHelp")} {" - "} {chrome.i18n.getMessage("advancedSkipNotSaved")}
) } ================================================ FILE: src/popup/SegmentSubmissionComponent.tsx ================================================ import * as React from "react"; import { VideoID } from "../types"; import Config from "../config"; import { Message, MessageResponse } from "../messageTypes"; import { LoadingStatus } from "./PopupComponent"; interface SegmentSubmissionComponentProps { videoID: VideoID; status: LoadingStatus; sendMessage: (request: Message) => Promise; } export const SegmentSubmissionComponent = (props: SegmentSubmissionComponentProps) => { const segments = Config.local.unsubmittedSegments[props.videoID]; const [showSubmitButton, setShowSubmitButton] = React.useState(segments && segments.length > 0); const [showStartSegment, setShowStartSegment] = React.useState(!segments || segments[segments.length - 1].segment.length === 2); return (

{chrome.i18n.getMessage("recordTimesDescription")}

{chrome.i18n.getMessage("popupHint")}
{chrome.i18n.getMessage("submissionEditHint")}
); }; ================================================ FILE: src/popup/YourWorkComponent.tsx ================================================ import * as React from "react"; import { getHash } from "../../maze-utils/src/hash"; import { formatJSErrorMessage, getShortErrorMessage } from "../../maze-utils/src/formating"; import Config from "../config"; import { asyncRequestToServer } from "../utils/requests"; import PencilIcon from "../svg-icons/pencilIcon"; import ClipboardIcon from "../svg-icons/clipboardIcon"; import CheckIcon from "../svg-icons/checkIcon"; import { showDonationLink } from "../utils/configUtils"; import { FetchResponse, logRequest } from "../../maze-utils/src/background-request-proxy"; export const YourWorkComponent = () => { const [isSettingUsername, setIsSettingUsername] = React.useState(false); const [username, setUsername] = React.useState(""); const [newUsername, setNewUsername] = React.useState(""); const [usernameSubmissionStatus, setUsernameSubmissionStatus] = React.useState(""); const [submissionCount, setSubmissionCount] = React.useState(""); const [viewCount, setViewCount] = React.useState(0); const [minutesSaved, setMinutesSaved] = React.useState(0); const [showDonateMessage, setShowDonateMessage] = React.useState(false); React.useEffect(() => { (async () => { const values = ["userName", "viewCount", "minutesSaved", "vip", "permissions", "segmentCount"]; let result: FetchResponse; try { result = await asyncRequestToServer("GET", "/api/userInfo", { publicUserID: await getHash(Config.config!.userID!), values }); } catch (e) { console.error("[SB] Caught error while fetching user info", e); return } if (result.ok) { const userInfo = JSON.parse(result.responseText); setUsername(userInfo.userName); setSubmissionCount(Math.max(Config.config.sponsorTimesContributed ?? 0, userInfo.segmentCount).toLocaleString()); setViewCount(userInfo.viewCount); setMinutesSaved(userInfo.minutesSaved); if (username === "sponege") { Config.config.prideTheme = true; } Config.config!.isVip = userInfo.vip; Config.config!.permissions = userInfo.permissions; setShowDonateMessage(Config.config.showDonationLink && Config.config.donateClicked <= 0 && Config.config.showPopupDonationCount < 5 && viewCount < 50000 && !Config.config.isVip && Config.config.skipCount > 10 && showDonationLink()); } else { logRequest(result, "SB", "user info"); } })(); }, []); return (

{chrome.i18n.getMessage("yourWork")}

{/* Username */}

{chrome.i18n.getMessage("Username")}: {/* loading/errors */} {usernameSubmissionStatus}

{username}

{ setNewUsername(e.target.value); }}/>
{showDonateMessage && { setShowDonateMessage(false); Config.config.showPopupDonationCount = 100; }} />}
); }; function SubmissionCounts(props: { isSettingUsername: boolean; submissionCount: string }): JSX.Element { return <>

{chrome.i18n.getMessage("Submissions")}:

{props.submissionCount}

} function TimeSavedMessage({ viewCount, minutesSaved }: { viewCount: number; minutesSaved: number }): JSX.Element { return ( <> { viewCount > 0 &&

{chrome.i18n.getMessage("savedPeopleFrom")} {viewCount.toLocaleString()}{" "} {viewCount !== 1 ? chrome.i18n.getMessage("Segments") : chrome.i18n.getMessage("Segment")}
{"("}{" "} {getFormattedHours(minutesSaved)}{" "} {minutesSaved !== 1 ? chrome.i18n.getMessage("minsLower") : chrome.i18n.getMessage("minLower")}{" "} {chrome.i18n.getMessage("youHaveSavedTimeEnd")}{" "} {" )"}

}

{chrome.i18n.getMessage("youHaveSkipped")} {Config.config.skipCount}{" "} {Config.config.skipCount > 1 ? chrome.i18n.getMessage("Segments") : chrome.i18n.getMessage("Segment")}{" "} {"("}{" "} {getFormattedHours(Config.config.minutesSaved)}{" "} {Config.config.minutesSaved !== 1 ? chrome.i18n.getMessage("minsLower") : chrome.i18n.getMessage("minLower")}{" "} {")"}

); } function DonateMessage(props: { onClose: () => void }): JSX.Element { return ( ); } /** * Converts time in minutes to 2d 5h 25.1 * If less than 1 hour, just returns minutes * * @param {float} minutes * @returns {string} */ function getFormattedHours(minutes) { minutes = Math.round(minutes * 10) / 10; const years = Math.floor(minutes / 525600); // Assumes 365.0 days in a year const days = Math.floor(minutes / 1440) % 365; const hours = Math.floor(minutes / 60) % 24; return (years > 0 ? years + chrome.i18n.getMessage("yearAbbreviation") + " " : "") + (days > 0 ? days + chrome.i18n.getMessage("dayAbbreviation") + " " : "") + (hours > 0 ? hours + chrome.i18n.getMessage("hourAbbreviation") + " " : "") + (minutes % 60).toFixed(1); } ================================================ FILE: src/popup/popup.tsx ================================================ import * as React from "react"; import { createRoot } from "react-dom/client"; import { PopupComponent } from "./PopupComponent"; import { waitFor } from "../../maze-utils/src"; import Config from "../config"; document.addEventListener("DOMContentLoaded", async () => { await waitFor(() => Config.isReady()); const root = createRoot(document.body); root.render(); }) ================================================ FILE: src/popup/popupUtils.ts ================================================ import { Message, MessageResponse } from "../messageTypes"; export function copyToClipboardPopup(text: string, sendMessage: (request: Message) => Promise): void { if (window === window.top) { window.navigator.clipboard.writeText(text); } else { sendMessage({ message: "copyToClipboard", text }); } } ================================================ FILE: src/render/AdvancedSkipOptions.tsx ================================================ import * as React from "react"; import { createRoot } from 'react-dom/client'; import { AdvancedSkipOptionsComponent } from "../components/options/AdvancedSkipOptionsComponent"; class AdvancedSkipOptions { constructor(element: Element) { const root = createRoot(element); root.render( ); } } export default AdvancedSkipOptions; ================================================ FILE: src/render/CategoryChooser.tsx ================================================ import * as React from "react"; import { createRoot } from 'react-dom/client'; import { CategoryChooserComponent } from "../components/options/CategoryChooserComponent"; class CategoryChooser { constructor(element: Element) { const root = createRoot(element); root.render( ); } } export default CategoryChooser; ================================================ FILE: src/render/CategoryPill.tsx ================================================ import * as React from "react"; import { createRoot, Root } from "react-dom/client"; import CategoryPillComponent, { CategoryPillState } from "../components/CategoryPillComponent"; import Config from "../config"; import { VoteResponse } from "../messageTypes"; import { Category, SegmentUUID, SponsorTime } from "../types"; import { Tooltip } from "./Tooltip"; import { waitFor } from "../../maze-utils/src"; import { getYouTubeTitleNode } from "../../maze-utils/src/elements"; import { addCleanupListener } from "../../maze-utils/src/cleanup"; const id = "categoryPill"; export class CategoryPill { container: HTMLElement; ref: React.RefObject; root: Root; lastState: CategoryPillState; mutationObserver?: MutationObserver; onMobileYouTube: boolean; onInvidious: boolean; vote: (type: number, UUID: SegmentUUID, category?: Category) => Promise; constructor() { this.ref = React.createRef(); addCleanupListener(() => { if (this.mutationObserver) { this.mutationObserver.disconnect(); } }); } async attachToPage(onMobileYouTube: boolean, onInvidious: boolean, vote: (type: number, UUID: SegmentUUID, category?: Category) => Promise): Promise { this.onMobileYouTube = onMobileYouTube; this.onInvidious = onInvidious; this.vote = vote; this.attachToPageInternal(); } private async attachToPageInternal(): Promise { let referenceNode = await waitFor(() => getYouTubeTitleNode()); // Experimental YouTube layout with description on right const isOnDescriptionOnRightLayout = document.querySelector("#title #description"); if (isOnDescriptionOnRightLayout) { referenceNode = referenceNode.parentElement; } if (referenceNode && !referenceNode.contains(this.container)) { if (!this.container) { this.container = document.createElement('span'); this.container.id = id; this.container.style.display = "relative"; this.root = createRoot(this.container); this.ref = React.createRef(); this.root.render(); if (this.onMobileYouTube) { if (this.mutationObserver) { this.mutationObserver.disconnect(); } this.mutationObserver = new MutationObserver((changes) => { if (changes.some((change) => change.removedNodes.length > 0)) { this.attachToPageInternal(); } }); this.mutationObserver.observe(referenceNode, { childList: true, subtree: true }); } } if (this.lastState) { waitFor(() => this.ref.current).then(() => { this.ref.current?.setState(this.lastState); }); } // Use a parent because YouTube does weird things to the top level object // react would have to rerender if container was the top level const parent = document.createElement("span"); parent.id = "categoryPillParent"; parent.appendChild(this.container); referenceNode.prepend(parent); if (!isOnDescriptionOnRightLayout) { referenceNode.style.display = "flex"; } } } close(): void { this.root.unmount(); this.container.remove(); } setVisibility(show: boolean): void { const newState = { show, open: show ? this.ref.current?.state.open : false }; this.ref.current?.setState(newState); this.lastState = newState; } async setSegment(segment: SponsorTime): Promise { await waitFor(() => this.ref.current); if (this.ref.current?.state?.segment !== segment || !this.ref.current?.state?.show) { const newState = { segment, show: true, open: false }; this.ref.current?.setState(newState); this.lastState = newState; if (!Config.config.categoryPillUpdate) { Config.config.categoryPillUpdate = true; const watchDiv = await waitFor(() => document.querySelector("#info.ytd-watch-flexy") as HTMLElement); if (watchDiv) { new Tooltip({ text: chrome.i18n.getMessage("categoryPillNewFeature"), link: "https://blog.ajay.app/full-video-sponsorblock", referenceNode: watchDiv, prependElement: watchDiv.firstChild as HTMLElement, bottomOffset: "-10px", opacity: 0.95, timeout: 50000 }); } } } if (this.onMobileYouTube && !document.contains(this.container)) { this.attachToPageInternal(); } } } ================================================ FILE: src/render/ChapterVote.tsx ================================================ import * as React from "react"; import { createRoot, Root } from 'react-dom/client'; import ChapterVoteComponent, { ChapterVoteState } from "../components/ChapterVoteComponent"; import { VoteResponse } from "../messageTypes"; import { Category, SegmentUUID, SponsorTime } from "../types"; export class ChapterVote { container: HTMLElement; ref: React.RefObject; root: Root; unsavedState: ChapterVoteState; mutationObserver?: MutationObserver; constructor(vote: (type: number, UUID: SegmentUUID, category?: Category) => Promise) { this.ref = React.createRef(); this.container = document.createElement('span'); this.container.id = "chapterVote"; this.container.style.height = "100%"; if (document.location.host === "tv.youtube.com") { this.container.style.lineHeight = "initial"; } this.root = createRoot(this.container); this.root.render(); } getContainer(): HTMLElement { return this.container; } close(): void { this.root.unmount(); this.container.remove(); } setVisibility(show: boolean): void { const newState = { show, ...(!show ? { segment: null } : {}) }; if (this.ref.current) { this.ref.current?.setState(newState); } else { this.unsavedState = newState; } } async setSegment(segment: SponsorTime): Promise { if (this.ref.current?.state?.segment !== segment) { const newState = { segment, show: true }; if (this.ref.current) { this.ref.current?.setState(newState); } else { this.unsavedState = newState; } } } } ================================================ FILE: src/render/GenericNotice.tsx ================================================ import * as React from "react"; import { createRoot, Root } from 'react-dom/client'; import NoticeComponent from "../components/NoticeComponent"; import Utils from "../utils"; const utils = new Utils(); import { ContentContainer } from "../types"; import NoticeTextSelectionComponent from "../components/NoticeTextSectionComponent"; import { ButtonListener } from "../../maze-utils/src/components/component-types"; import { getVideo } from "../../maze-utils/src/video"; export interface TextBox { icon: string; text: string; } export interface NoticeOptions { title: string; referenceNode?: HTMLElement; textBoxes?: TextBox[]; buttons?: ButtonListener[]; fadeIn?: boolean; timed?: boolean; style?: React.CSSProperties; extraClass?: string; maxCountdownTime?: () => number; dontPauseCountdown?: boolean; hideLogo?: boolean; hideRightInfo?: boolean; } export default class GenericNotice { // Contains functions and variables from the content script needed by the skip notice contentContainer: ContentContainer; noticeElement: HTMLDivElement; noticeRef: React.MutableRefObject; idSuffix: string; root: Root; constructor(contentContainer: ContentContainer, idSuffix: string, options: NoticeOptions) { this.noticeRef = React.createRef(); this.idSuffix = idSuffix; this.contentContainer = contentContainer; const referenceNode = options.referenceNode ?? utils.findReferenceNode(); this.noticeElement = document.createElement("div"); this.noticeElement.className = "sponsorSkipNoticeContainer"; this.noticeElement.id = "sponsorSkipNoticeContainer" + idSuffix; referenceNode.prepend(this.noticeElement); this.root = createRoot(this.noticeElement); this.update(options); } update(options: NoticeOptions): void { this.root.render( this.close()} > {options.textBoxes?.length > 0 ? {this.getMessageBoxes(this.idSuffix, options.textBoxes)} : null} {!options.hideLogo ? <> {this.getButtons(options.buttons)} : null} ); } getMessageBoxes(idSuffix: string, textBoxes: TextBox[]): JSX.Element[] { if (textBoxes) { const result = []; for (let i = 0; i < textBoxes.length; i++) { result.push( ) } return result; } else { return null; } } getButtons(buttons?: ButtonListener[]): JSX.Element[] { if (buttons) { const result: JSX.Element[] = []; for (const button of buttons) { result.push( ) } return result; } else { return null; } } close(): void { this.root.unmount(); this.noticeElement.remove(); } } ================================================ FILE: src/render/RectangleTooltip.tsx ================================================ import * as React from "react"; import { createRoot, Root } from 'react-dom/client'; export interface RectangleTooltipProps { text: string; link?: string; referenceNode: HTMLElement; prependElement?: HTMLElement; // Element to append before bottomOffset?: string; leftOffset?: string; timeout?: number; htmlId?: string; maxHeight?: string; maxWidth?: string; backgroundColor?: string; fontSize?: string; buttonFunction?: () => void; } export class RectangleTooltip { text: string; container: HTMLDivElement; root: Root; timer: NodeJS.Timeout; constructor(props: RectangleTooltipProps) { props.bottomOffset ??= "0px"; props.leftOffset ??= "0px"; props.maxHeight ??= "100px"; props.maxWidth ??= "300px"; props.backgroundColor ??= "rgba(28, 28, 28, 0.7)"; this.text = props.text; props.fontSize ??= "10px"; this.container = document.createElement('div'); props.htmlId ??= "sponsorRectangleTooltip" + props.text; this.container.id = props.htmlId; this.container.style.display = "relative"; if (props.prependElement) { props.referenceNode.insertBefore(this.container, props.prependElement); } else { props.referenceNode.appendChild(this.container); } if (props.timeout) { this.timer = setTimeout(() => this.close(), props.timeout * 1000); } this.root = createRoot(this.container); this.root.render(
{this.text + (props.link ? ". " : "")} {props.link ? {chrome.i18n.getMessage("LearnMore")} : null}
) } close(): void { this.root.unmount(); this.container.remove(); if (this.timer) clearTimeout(this.timer); } } ================================================ FILE: src/render/SkipNotice.tsx ================================================ import * as React from "react"; import { createRoot, Root } from 'react-dom/client'; import Utils from "../utils"; const utils = new Utils(); import SkipNoticeComponent from "../components/SkipNoticeComponent"; import { SponsorTime, ContentContainer, NoticeVisibilityMode } from "../types"; import Config from "../config"; import { SkipNoticeAction } from "../utils/noticeUtils"; class SkipNotice { segments: SponsorTime[]; autoSkip: boolean; // Contains functions and variables from the content script needed by the skip notice contentContainer: ContentContainer; noticeElement: HTMLDivElement; skipNoticeRef: React.MutableRefObject; root: Root; constructor(segments: SponsorTime[], autoSkip = false, contentContainer: ContentContainer, componentDidMount: () => void, unskipTime: number = null, startReskip = false, upcomingNoticeShown: boolean, voteNotice = false) { this.skipNoticeRef = React.createRef(); this.segments = segments; this.autoSkip = autoSkip; this.contentContainer = contentContainer; const referenceNode = utils.findReferenceNode(); const amountOfPreviousNotices = document.getElementsByClassName("sponsorSkipNotice").length; //this is the suffix added at the end of every id let idSuffix = ""; for (const segment of this.segments) { idSuffix += segment.UUID; } idSuffix += amountOfPreviousNotices; this.noticeElement = document.createElement("div"); this.noticeElement.className = "sponsorSkipNoticeContainer"; this.noticeElement.id = "sponsorSkipNoticeContainer" + idSuffix; referenceNode.prepend(this.noticeElement); this.root = createRoot(this.noticeElement); this.root.render( this.close()} smaller={!voteNotice && (Config.config.noticeVisibilityMode >= NoticeVisibilityMode.MiniForAll || (Config.config.noticeVisibilityMode >= NoticeVisibilityMode.MiniForAutoSkip && autoSkip))} fadeIn={!upcomingNoticeShown && !voteNotice} unskipTime={unskipTime} componentDidMount={componentDidMount} /> ); } setShowKeybindHint(value: boolean): void { this.skipNoticeRef?.current?.setState({ showKeybindHint: value }); } close(): void { this.root.unmount(); this.noticeElement.remove(); const skipNotices = this.contentContainer().skipNotices; skipNotices.splice(skipNotices.indexOf(this), 1); } toggleSkip(): void { this.skipNoticeRef?.current?.prepAction(SkipNoticeAction.Unskip0); } unmutedListener(time: number): void { this.skipNoticeRef?.current?.unmutedListener(time); } async waitForSkipNoticeRef(): Promise { const waitForRef = () => new Promise((resolve) => { const observer = new MutationObserver(() => { if (this.skipNoticeRef.current) { observer.disconnect(); resolve(this.skipNoticeRef.current); } }); observer.observe(document.getElementsByClassName("sponsorSkipNoticeContainer")[0], { childList: true, subtree: true}); if (this.skipNoticeRef.current) { observer.disconnect(); resolve(this.skipNoticeRef.current); } }); return this.skipNoticeRef?.current || await waitForRef(); } } export default SkipNotice; ================================================ FILE: src/render/SubmissionNotice.tsx ================================================ import * as React from "react"; import { createRoot, Root } from 'react-dom/client'; import Utils from "../utils"; const utils = new Utils(); import SubmissionNoticeComponent from "../components/SubmissionNoticeComponent"; import { ContentContainer } from "../types"; class SubmissionNotice { // Contains functions and variables from the content script needed by the skip notice contentContainer: () => unknown; callback: () => Promise; noticeRef: React.MutableRefObject; noticeElement: HTMLDivElement; root: Root; constructor(contentContainer: ContentContainer, callback: () => Promise) { this.noticeRef = React.createRef(); this.contentContainer = contentContainer; this.callback = callback; const referenceNode = utils.findReferenceNode(); this.noticeElement = document.createElement("div"); this.noticeElement.id = "submissionNoticeContainer"; referenceNode.prepend(this.noticeElement); this.root = createRoot(this.noticeElement); this.root.render( this.close(false)} /> ); } update(): void { this.noticeRef.current.forceUpdate(); } close(callRef = true): void { if (callRef) this.noticeRef.current.cancel(); this.root.unmount(); this.noticeElement.remove(); } submit(): void { this.noticeRef.current?.submit?.(); } scrollToBottom(): void { this.noticeRef.current?.scrollToBottom?.(); } } export default SubmissionNotice; ================================================ FILE: src/render/Tooltip.tsx ================================================ import { GenericTooltip, TooltipProps } from "../../maze-utils/src/components/Tooltip"; export class Tooltip extends GenericTooltip { constructor(props: TooltipProps) { super(props, "icons/IconSponsorBlocker256px.png") } } ================================================ FILE: src/render/UnsubmittedVideos.tsx ================================================ import * as React from "react"; import { createRoot } from 'react-dom/client'; import UnsubmittedVideosComponent from "../components/options/UnsubmittedVideosComponent"; class UnsubmittedVideos { ref: React.RefObject; constructor(element: Element) { this.ref = React.createRef(); const root = createRoot(element); root.render( ); } update(): void { this.ref.current?.forceUpdate(); } } export default UnsubmittedVideos; ================================================ FILE: src/render/UpcomingNotice.tsx ================================================ import * as React from "react"; import { createRoot, Root } from "react-dom/client"; import { ContentContainer, SponsorTime } from "../types"; import Utils from "../utils"; import SkipNoticeComponent from "../components/SkipNoticeComponent"; const utils = new Utils(); class UpcomingNotice { segments: SponsorTime[]; // Contains functions and variables from the content script needed by the skip notice contentContainer: ContentContainer; noticeElement: HTMLDivElement; upcomingNoticeRef: React.MutableRefObject; root: Root; closed = false; constructor(segments: SponsorTime[], contentContainer: ContentContainer, timeLeft: number, autoSkip: boolean) { this.upcomingNoticeRef = React.createRef(); this.segments = segments; this.contentContainer = contentContainer; const referenceNode = utils.findReferenceNode(); this.noticeElement = document.createElement("div"); this.noticeElement.className = "sponsorSkipNoticeContainer"; referenceNode.prepend(this.noticeElement); this.root = createRoot(this.noticeElement); this.root.render( this.close()} smaller={true} fadeIn={true} maxCountdownTime={timeLeft} /> ); } close(): void { this.root.unmount(); this.noticeElement.remove(); this.closed = true; } sameNotice(segments: SponsorTime[]): boolean { if (segments.length !== this.segments.length) return false; for (let i = 0; i < segments.length; i++) { if (segments[i].UUID !== this.segments[i].UUID) return false; } return true; } } export default UpcomingNotice; ================================================ FILE: src/svg-icons/checkIcon.tsx ================================================ import * as React from "react"; export interface CheckIconProps { id?: string; style?: React.CSSProperties; className?: string; onClick?: () => void; } const CheckIcon = ({ id = "", className = "", style = {}, onClick }: CheckIconProps): JSX.Element => ( ); export default CheckIcon; ================================================ FILE: src/svg-icons/clipboardIcon.tsx ================================================ import * as React from "react"; export interface ClipboardIconProps { id?: string; style?: React.CSSProperties; className?: string; onClick?: () => void; } const ClipboardIcon = ({ id = "", className = "", style = {}, onClick }: ClipboardIconProps): JSX.Element => ( ); export default ClipboardIcon; ================================================ FILE: src/svg-icons/lock_svg.tsx ================================================ import * as React from "react"; const lockSvg = ({ fill = "#fcba03", className = "", width = "20", height = "20", onClick }): JSX.Element => ( ); export default lockSvg; ================================================ FILE: src/svg-icons/pencilIcon.tsx ================================================ import * as React from "react"; export interface PencilIconProps { id?: string; style?: React.CSSProperties; className?: string; onClick?: () => void; } const PencilIcon = ({ id = "", className = "", style = {}, onClick }: PencilIconProps): JSX.Element => ( ); export default PencilIcon; ================================================ FILE: src/svg-icons/pencil_svg.tsx ================================================ import * as React from "react"; const pencilSvg = ({ fill = "#ffffff" }): JSX.Element => ( ); export default pencilSvg; ================================================ FILE: src/svg-icons/resetIcon.tsx ================================================ import * as React from "react"; export interface AddIconProps { style?: React.CSSProperties; className?: string; onClick?: () => void; } const ResetIcon = ({ className = "", style = {}, onClick }: AddIconProps): JSX.Element => ( ); export default ResetIcon; ================================================ FILE: src/svg-icons/sb_svg.tsx ================================================ import * as React from "react"; export interface SbIconProps { id?: string; fill?: string; className?: string; width?: string; height?: string; onClick?: () => void; } export default function SbSvg({ id = "", fill = "#ff0000", className = "", onClick }: SbIconProps): JSX.Element { return ( onClick?.() } > ); } ================================================ FILE: src/svg-icons/thumbs_down_svg.tsx ================================================ import * as React from "react"; const thumbsDownSvg = ({ fill = "#ffffff", className = "", width = "18", height = "18" }): JSX.Element => ( ); export default thumbsDownSvg; ================================================ FILE: src/svg-icons/thumbs_up_svg.tsx ================================================ import * as React from "react"; const thumbsUpSvg = ({ fill = "#ffffff", className = "", width = "18", height = "18" }): JSX.Element => ( ); export default thumbsUpSvg; ================================================ FILE: src/types.ts ================================================ import SubmissionNotice from "./render/SubmissionNotice"; import SkipNoticeComponent from "./components/SkipNoticeComponent"; import SkipNotice from "./render/SkipNotice"; export interface ContentContainer { (): { vote: (type: number, UUID: SegmentUUID, category?: Category, skipNotice?: SkipNoticeComponent) => void; dontShowNoticeAgain: () => void; unskipSponsorTime: (segment: SponsorTime, unskipTime: number, forceSeek?: boolean, voteNotice?: boolean) => void; sponsorTimes: SponsorTime[]; sponsorTimesSubmitting: SponsorTime[]; skipNotices: SkipNotice[]; sponsorVideoID; reskipSponsorTime: (segment: SponsorTime, forceSeek?: boolean) => void; updatePreviewBar: () => void; onMobileYouTube: boolean; sponsorSubmissionNotice: SubmissionNotice; resetSponsorSubmissionNotice: (callRef?: boolean) => void; updateEditButtonsOnPlayer: () => void; previewTime: (time: number, unpause?: boolean) => void; videoInfo: VideoInfo; getRealCurrentTime: () => number; lockedCategories: string[]; channelIDInfo: ChannelIDInfo; }; } export interface VideoDurationResponse { duration: number; } export enum CategorySkipOption { FallbackToDefault = -2, Disabled = -1, ShowOverlay, ManualSkip, AutoSkip } export interface CategorySelection { name: Category; option: CategorySkipOption; } export enum SponsorHideType { Visible = undefined, Downvoted = 1, MinimumDuration, Hidden, } export enum ActionType { Skip = "skip", Mute = "mute", Chapter = "chapter", Full = "full", Poi = "poi" } export const ActionTypes = [ ActionType.Skip, ActionType.Mute, ActionType.Chapter, ActionType.Full, ActionType.Poi ]; export type SegmentUUID = string & { __segmentUUIDBrand: unknown }; export type Category = string & { __categoryBrand: unknown }; export enum SponsorSourceType { Server = undefined, Local = 1, YouTube = 2, Autogenerated = 3 } export interface SegmentContainer { segment: [number] | [number, number]; } export interface SponsorTime extends SegmentContainer { UUID: SegmentUUID; locked?: number; category: Category; actionType: ActionType; description?: string; hidden?: SponsorHideType; source: SponsorSourceType; videoDuration?: number; } export interface ScheduledTime extends SponsorTime { scheduledTime: number; } export interface PreviewBarOption { color: string; opacity: string; } export interface Registration { message: string; id: string; allFrames: boolean; js: string[]; css: string[]; matches: string[]; } export interface BackgroundScriptContainer { registerFirefoxContentScript: (opts: Registration) => void; unregisterFirefoxContentScript: (id: string) => void; } export interface VideoInfo { responseContext: { serviceTrackingParams: Array<{service: string; params: Array<{key: string; value: string}>}>; webResponseContextExtensionData: { hasDecorated: boolean; }; }; playabilityStatus: { status: string; playableInEmbed: boolean; miniplayer: { miniplayerRenderer: { playbackMode: string; }; }; }; streamingData: unknown; playbackTracking: unknown; videoDetails: { videoId: string; title: string; lengthSeconds: string; keywords: string[]; channelId: string; isOwnerViewing: boolean; shortDescription: string; isCrawlable: boolean; thumbnail: { thumbnails: Array<{url: string; width: number; height: number}>; }; averageRating: number; allowRatings: boolean; viewCount: string; author: string; isPrivate: boolean; isUnpluggedCorpus: boolean; isLiveContent: boolean; }; playerConfig: unknown; storyboards: unknown; microformat: { playerMicroformatRenderer: { thumbnail: { thumbnails: Array<{url: string; width: number; height: number}>; }; embed: { iframeUrl: string; flashUrl: string; width: number; height: number; flashSecureUrl: string; }; title: { simpleText: string; }; description: { simpleText: string; }; lengthSeconds: string; ownerProfileUrl: string; externalChannelId: string; availableCountries: string[]; isUnlisted: boolean; hasYpcMetadata: boolean; viewCount: string; category: Category; publishDate: string; ownerChannelName: string; uploadDate: string; }; }; trackingParams: string; attestation: unknown; messages: unknown; } export type VideoID = string; export type UnEncodedSegmentTimes = [string, SponsorTime[]][]; export enum ChannelIDStatus { Fetching, Found, Failed } export interface ChannelIDInfo { id: string; status: ChannelIDStatus; } export interface SkipToTimeParams { v: HTMLVideoElement; skipTime: number[]; skippingSegments: SponsorTime[]; openNotice: boolean; forceAutoSkip?: boolean; unskipTime?: number; } export interface ToggleSkippable { toggleSkip: () => void; setShowKeybindHint: (show: boolean) => void; } export enum NoticeVisibilityMode { FullSize = 0, MiniForAutoSkip = 1, MiniForAll = 2, FadedForAutoSkip = 3, FadedForAll = 4 } export enum SegmentListDefaultTab { Segments, Chapters, } ================================================ FILE: src/utils/arrayUtils.ts ================================================ export function partition(array: T[], filter: (element: T) => boolean): [T[], T[]] { const pass = [], fail = []; array.forEach((element) => (filter(element) ? pass : fail).push(element)); return [pass, fail]; } ================================================ FILE: src/utils/categoryUtils.ts ================================================ import { ActionType, Category, SponsorTime } from "../types"; export function getSkippingText(segments: SponsorTime[], autoSkip: boolean): string { const categoryName = chrome.i18n.getMessage(segments.length > 1 ? "multipleSegments" : "category_" + segments[0].category + "_short") || chrome.i18n.getMessage("category_" + segments[0].category); if (autoSkip) { let messageId = ""; switch (segments[0].actionType) { case ActionType.Chapter: case ActionType.Skip: messageId = "skipped"; break; case ActionType.Mute: messageId = "muted"; break; case ActionType.Poi: messageId = "skipped_to_category"; break; } return chrome.i18n.getMessage(messageId).replace("{0}", categoryName); } else { let messageId = ""; switch (segments[0].actionType) { case ActionType.Chapter: case ActionType.Skip: messageId = "skip_category"; break; case ActionType.Mute: messageId = "mute_category"; break; case ActionType.Poi: messageId = "skip_to_category"; break; } return chrome.i18n.getMessage(messageId).replace("{0}", categoryName); } } export function getUpcomingText(segments: SponsorTime[]): string { const categoryName = chrome.i18n.getMessage(segments.length > 1 ? "multipleSegments" : "category_" + segments[0].category + "_short") || chrome.i18n.getMessage("category_" + segments[0].category); const messageId = "upcoming"; return chrome.i18n.getMessage(messageId).replace("{0}", categoryName); } export function getVoteText(segments: SponsorTime[]): string { const categoryName = chrome.i18n.getMessage(segments.length > 1 ? "multipleSegments" : "category_" + segments[0].category + "_short") || chrome.i18n.getMessage("category_" + segments[0].category); const messageId = "voted_on"; return chrome.i18n.getMessage(messageId).replace("{0}", categoryName); } export function getCategorySuffix(category: Category): string { if (category.startsWith("poi_")) { return "_POI"; } else if (category === "exclusive_access") { return "_full"; } else if (category === "chapter") { return "_chapter"; } else { return ""; } } export function shortCategoryName(categoryName: string): string { return chrome.i18n.getMessage("category_" + categoryName + "_short") || chrome.i18n.getMessage("category_" + categoryName); } export const DEFAULT_CATEGORY = "chooseACategory"; ================================================ FILE: src/utils/compatibility.ts ================================================ import Config from "../config"; export function runCompatibilityChecks() { if (Config.config.showZoomToFillError2 && document.URL.includes("watch?v=")) { setTimeout(() => { const zoomToFill = document.querySelector(".zoomtofillBtn"); if (zoomToFill) { alert(chrome.i18n.getMessage("zoomToFillUnsupported")); } Config.config.showZoomToFillError2 = false; }, 10000); } } export function isVorapisInstalled() { return document.querySelector(`.v3`); } ================================================ FILE: src/utils/configUtils.ts ================================================ import Config from "../config"; export function showDonationLink(): boolean { return navigator.vendor !== "Apple Computer, Inc." && Config.config.showDonationLink; } ================================================ FILE: src/utils/constants.ts ================================================ import { TextBox } from "../render/GenericNotice"; import { Category } from "../types"; export function getGuidelineInfo(category: Category): TextBox[] { switch (category) { case "sponsor": return [{ icon: "icons/money.svg", text: chrome.i18n.getMessage(`category_${category}_guideline1`) }, { icon: "icons/close-smaller.svg", text: chrome.i18n.getMessage(`category_${category}_guideline2`) }, { icon: "icons/segway.png", text: chrome.i18n.getMessage(`generic_guideline1`) }, { icon: "icons/right-arrow.svg", text: chrome.i18n.getMessage(`generic_guideline2`) }]; case "selfpromo": return [{ icon: "icons/money.svg", text: chrome.i18n.getMessage(`category_${category}_guideline1`) }, { icon: "icons/campaign.svg", text: chrome.i18n.getMessage(`category_${category}_guideline2`) }, { icon: "icons/close-smaller.svg", text: chrome.i18n.getMessage(`category_${category}_guideline3`) }, { icon: "icons/segway.png", text: chrome.i18n.getMessage(`generic_guideline1`) }, { icon: "icons/right-arrow.svg", text: chrome.i18n.getMessage(`generic_guideline2`) }]; case "exclusive_access": return [{ icon: "icons/money.svg", text: chrome.i18n.getMessage(`category_${category}_guideline1`) }]; case "interaction": return [{ icon: "icons/lightbulb.svg", text: chrome.i18n.getMessage(`category_${category}_guideline1`) }, { icon: "icons/lightbulb.svg", text: chrome.i18n.getMessage(`category_${category}_guideline2`) }, { icon: "icons/close-smaller.svg", text: chrome.i18n.getMessage(`category_${category}_guideline3`) }, { icon: "icons/segway.png", text: chrome.i18n.getMessage(`generic_guideline1`) }, { icon: "icons/right-arrow.svg", text: chrome.i18n.getMessage(`generic_guideline2`) }]; case "intro": return [{ icon: "icons/check-smaller.svg", text: chrome.i18n.getMessage(`category_${category}_guideline1`) }, { icon: "icons/close-smaller.svg", text: chrome.i18n.getMessage(`category_${category}_guideline2`) }, { icon: "icons/segway.png", text: chrome.i18n.getMessage(`generic_guideline1`) }, { icon: "icons/right-arrow.svg", text: chrome.i18n.getMessage(`generic_guideline2`) }]; case "outro": return [{ icon: "icons/close-smaller.svg", text: chrome.i18n.getMessage(`category_${category}_guideline1`) }, { icon: "icons/segway.png", text: chrome.i18n.getMessage(`generic_guideline1`) }, { icon: "icons/right-arrow.svg", text: chrome.i18n.getMessage(`generic_guideline2`) }]; case "preview": return [{ icon: "icons/check-smaller.svg", text: chrome.i18n.getMessage(`category_${category}_guideline1`) }, { icon: "icons/check-smaller.svg", text: chrome.i18n.getMessage(`category_${category}_guideline2`) }, { icon: "icons/close-smaller.svg", text: chrome.i18n.getMessage(`category_${category}_guideline3`) }, { icon: "icons/segway.png", text: chrome.i18n.getMessage(`generic_guideline1`) }, { icon: "icons/right-arrow.svg", text: chrome.i18n.getMessage(`generic_guideline2`) }]; case "hook": return [{ icon: "icons/campaign.svg", text: chrome.i18n.getMessage(`category_${category}_guideline1`) }, { icon: "icons/check-smaller.svg", text: chrome.i18n.getMessage(`category_${category}_guideline2`) }, { icon: "icons/close-smaller.svg", text: chrome.i18n.getMessage(`category_${category}_guideline3`) }, { icon: "icons/segway.png", text: chrome.i18n.getMessage(`generic_guideline1`) }, { icon: "icons/right-arrow.svg", text: chrome.i18n.getMessage(`generic_guideline2`) }]; case "filler": return [{ icon: "icons/stopwatch.svg", text: chrome.i18n.getMessage(`category_${category}_guideline1`) }, { icon: "icons/stopwatch.svg", text: chrome.i18n.getMessage(`category_${category}_guideline2`) }, { icon: "icons/close-smaller.svg", text: chrome.i18n.getMessage(`category_${category}_guideline3`) }, { icon: "icons/segway.png", text: chrome.i18n.getMessage(`generic_guideline1`) }, { icon: "icons/right-arrow.svg", text: chrome.i18n.getMessage(`generic_guideline2`) }]; case "music_offtopic": return [{ icon: "icons/music-note.svg", text: chrome.i18n.getMessage(`category_${category}_guideline1`) }, { icon: "icons/music-note.svg", text: chrome.i18n.getMessage(`category_${category}_guideline2`) }, { icon: "icons/right-arrow.svg", text: chrome.i18n.getMessage(`generic_guideline2`) }]; case "poi_highlight": return [{ icon: "icons/star.svg", text: chrome.i18n.getMessage(`category_${category}_guideline1`) }, { icon: "icons/bolt.svg", text: chrome.i18n.getMessage(`category_${category}_guideline2`) }, { icon: "icons/bolt.svg", text: chrome.i18n.getMessage(`category_${category}_guideline3`) }]; case "chapter": return [{ icon: "icons/close-smaller.svg", text: chrome.i18n.getMessage(`category_${category}_guideline1`) }, { icon: "icons/check-smaller.svg", text: chrome.i18n.getMessage(`category_${category}_guideline2`) }, { icon: "icons/check-smaller.svg", text: chrome.i18n.getMessage(`category_${category}_guideline3`) }]; default: return [{ icon: "icons/segway.png", text: chrome.i18n.getMessage(`generic_guideline1`) }, { icon: "icons/right-arrow.svg", text: chrome.i18n.getMessage(`generic_guideline2`) }]; } } export const defaultPreviewTime = 2; ================================================ FILE: src/utils/crossExtension.ts ================================================ import * as CompileConfig from "../../config.json"; import Config from "../config"; import { isSafari } from "../../maze-utils/src/config"; import { isFirefoxOrSafari } from "../../maze-utils/src"; export function isDeArrowInstalled(): Promise { if (Config.config.deArrowInstalled) { return Promise.resolve(true); } else { return new Promise((resolve) => { const extensionIds = getExtensionIdsToImportFrom(); let count = 0; for (const id of extensionIds) { chrome.runtime.sendMessage(id, { message: "isInstalled" }, (response) => { if (chrome.runtime.lastError) { count++; if (count === extensionIds.length) { resolve(false); } return; } resolve(response); if (response) { Config.config.deArrowInstalled = true; } }); } }); } } export function getExtensionIdsToImportFrom(): string[] { if (isSafari()) { return CompileConfig.extensionImportList.safari; } else if (isFirefoxOrSafari()) { return CompileConfig.extensionImportList.firefox; } else { return CompileConfig.extensionImportList.chromium; } } ================================================ FILE: src/utils/exporter.ts ================================================ import { ActionType, Category, SegmentUUID, SponsorSourceType, SponsorTime } from "../types"; import { shortCategoryName } from "./categoryUtils"; import * as CompileConfig from "../../config.json"; import { getFormattedTime, getFormattedTimeToSeconds } from "../../maze-utils/src/formating"; import { generateUserID } from "../../maze-utils/src/setup"; const inTest = typeof chrome === "undefined"; const chapterNames = CompileConfig.categoryList.filter((code) => code !== "chapter") .map((code) => ({ code, names: !inTest ? [chrome.i18n.getMessage("category_" + code), shortCategoryName(code)] : [code] })); export function exportTimes(segments: SponsorTime[]): string { let result = ""; for (const segment of segments) { if (![ActionType.Full, ActionType.Mute].includes(segment.actionType) && ![SponsorSourceType.YouTube, SponsorSourceType.Autogenerated].includes(segment.source)) { result += exportTime(segment) + "\n"; } } return result.replace(/\n$/, ""); } function exportTime(segment: SponsorTime): string { const name = segment.description || shortCategoryName(segment.category); return `${getFormattedTime(segment.segment[0], true)}${ segment.segment[1] && segment.segment[0] !== segment.segment[1] ? ` - ${getFormattedTime(segment.segment[1], true)}` : ""} ${name}`; } export function importTimes(data: string, videoDuration: number): SponsorTime[] { const lines = data.split("\n"); const timeRegex = /(?:((?:\d+:)?\d+:\d+)+(?:\.\d+)?)|(?:\d+(?=s| second))/g; const anyLineHasTime = lines.some((line) => timeRegex.test(line)); const result: SponsorTime[] = []; for (const line of lines) { const match = line.match(timeRegex); if (match) { const startTime = getFormattedTimeToSeconds(match[0]); if (startTime !== null) { // Remove "seconds", "at", special characters, and ")" if there was a "(" const specialCharMatchers = [{ matcher: /^(?:\s+seconds?)?[-:()\s]*|(?:\s+at)?[-:(\s]+$/g }, { matcher: /[-:()\s]*$/g, condition: (value) => !!value.match(/^\s*\(/) }]; const titleLeft = removeIf(line.split(match[0])[0], specialCharMatchers); let titleRight = null; const split2 = line.split(match[1] || match[0]); titleRight = removeIf(split2[split2.length - 1], specialCharMatchers) const title = titleLeft?.length > titleRight?.length ? titleLeft : titleRight; const determinedCategory = chapterNames.find(c => c.names.includes(title))?.code as Category; const category = title ? (determinedCategory ?? ("chapter" as Category)) : "chooseACategory" as Category; const segment: SponsorTime = { segment: [startTime, getFormattedTimeToSeconds(match[1])], category, actionType: category === "chapter" ? ActionType.Chapter : ActionType.Skip, description: category === "chapter" ? title : null, source: SponsorSourceType.Local, UUID: generateUserID() as SegmentUUID }; if (result.length > 0 && result[result.length - 1].segment[1] === null) { result[result.length - 1].segment[1] = segment.segment[0]; } result.push(segment); } } else if (!anyLineHasTime) { // Adding chapters with placeholder times const segment: SponsorTime = { segment: [0, 0], category: "chapter" as Category, actionType: ActionType.Chapter, description: line, source: SponsorSourceType.Local, UUID: generateUserID() as SegmentUUID }; result.push(segment); } } if (result.length > 0 && result[result.length - 1].segment[1] === null) { result[result.length - 1].segment[1] = videoDuration; } return result; } function removeIf(value: string, matchers: Array<{ matcher: RegExp; condition?: (value: string) => boolean }>): string { let result = value; for (const matcher of matchers) { if (!matcher.condition || matcher.condition(value)) { result = result.replace(matcher.matcher, ""); } } return result; } export function exportTimesAsHashParam(segments: SponsorTime[]): string { const hashparamSegments = segments.map(segment => ({ actionType: segment.actionType, category: segment.category, segment: segment.segment, ...(segment.description ? {description: segment.description} : {}) // don't include the description param if empty })); return `#segments=${JSON.stringify(hashparamSegments)}`; } export function normalizeChapterName(description: string): string { return description.toLowerCase().replace(/[.:'’`‛‘"‟”-]/ug, "").replace(/\s+/g, " "); } ================================================ FILE: src/utils/genericUtils.ts ================================================ /* Gets percieved luminance of a color */ function getLuminance(color: string): number { const {r, g, b} = hexToRgb(color); return Math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b)); } /* Converts hex color to rgb color */ const hexChars = "0123456789abcdef"; function hexToRgb(hex: string): { r: number; g: number; b: number } | null { if (hex.length == 4) hex = "#" + hex[1] + hex[1] + hex[2] + hex[2] + hex[3] + hex[3]; return /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex) ? { r: hexChars.indexOf(hex[1]) * 16 + hexChars.indexOf(hex[2]), g: hexChars.indexOf(hex[3]) * 16 + hexChars.indexOf(hex[4]), b: hexChars.indexOf(hex[5]) * 16 + hexChars.indexOf(hex[6]), }: null; } /** * List of all indexes that have the specified value * https://stackoverflow.com/a/54954694/1985387 */ function indexesOf(array: T[], value: T): number[] { return array.map((v, i) => v === value ? i : -1).filter(i => i !== -1); } export const GenericUtils = { getLuminance, indexesOf } ================================================ FILE: src/utils/logger.ts ================================================ if (typeof (window) !== "undefined") { window["SBLogs"] = { debug: [], warn: [] }; } export function logDebug(message: string) { if (typeof (window) !== "undefined") { window["SBLogs"].debug.push(`[${new Date().toISOString()}] ${message}`); } else { console.log(`[${new Date().toISOString()}] ${message}`) } } export function logWarn(message: string) { if (typeof (window) !== "undefined") { window["SBLogs"].warn.push(`[${new Date().toISOString()}] ${message}`); } else { console.warn(`[${new Date().toISOString()}] ${message}`) } } ================================================ FILE: src/utils/mobileUtils.ts ================================================ export function isMobileControlsOpen(): boolean { const overlay = document.getElementById("player-control-overlay"); if (overlay) { return !!overlay?.classList?.contains("fadein"); } return false; } ================================================ FILE: src/utils/noticeUtils.ts ================================================ import Config from "../config"; import { SponsorTime } from "../types"; export enum SkipNoticeAction { None, Upvote, Downvote, CategoryVote, CopyDownvote, Unskip0, Unskip1 } export function downvoteButtonColor(segments: SponsorTime[], actionState: SkipNoticeAction, downvoteType: SkipNoticeAction): string { // Also used for "Copy and Downvote" if (segments?.length > 1) { return (actionState === downvoteType) ? Config.config.colorPalette.red : Config.config.colorPalette.white; } else { // You dont have segment selectors so the lockbutton needs to be colored and cannot be selected. return Config.config.isVip && segments?.[0].locked === 1 ? Config.config.colorPalette.locked : Config.config.colorPalette.white; } } ================================================ FILE: src/utils/pageCleaner.ts ================================================ export function cleanPage() { // For live-updates if (document.readyState === "complete") { for (const element of document.querySelectorAll("#categoryPillParent, .playerButton, .sponsorThumbnailLabel, #submissionNoticeContainer, .sponsorSkipNoticeContainer, #sponsorBlockPopupContainer, .skipButtonControlBarContainer, #previewbar, .sponsorBlockChapterBar")) { element.remove(); } } } ================================================ FILE: src/utils/pageUtils.ts ================================================ import { ActionType, Category, SponsorSourceType, SponsorTime, VideoID } from "../types"; import { getFormattedTimeToSeconds } from "../../maze-utils/src/formating"; import { getSkipProfileBool } from "./skipProfiles"; export function getControls(): HTMLElement { const controlsSelectors = [ // YouTube ".ytp-right-controls", // Mobile YouTube ".player-controls-top", // Invidious/videojs video element's controls element ".vjs-control-bar", // Piped shaka player ".shaka-bottom-controls", // Vorapis v3 ".html5-player-chrome", // tv.youtube.com ".ypcs-control-buttons-right" ]; for (const controlsSelector of controlsSelectors) { const controls = Array.from(document.querySelectorAll(controlsSelector)).filter(el => !isInPreviewPlayer(el)); if (controls.length > 0) { return controls[controls.length - 1]; } } return null; } export function isInPreviewPlayer(element: Element): boolean { return !!element.closest("#inline-preview-player"); } export function isVisible(element: HTMLElement): boolean { return element && element.offsetWidth > 0 && element.offsetHeight > 0; } export function getHashParams(): Record { const windowHash = window.location.hash.slice(1); if (windowHash) { const params: Record = windowHash.split('&').reduce((acc, param) => { const [key, value] = param.split('='); const decoded = decodeURIComponent(value); try { acc[key] = decoded?.match(/{|\[/) ? JSON.parse(decoded) : value; } catch (e) { console.error(`Failed to parse hash parameter ${key}: ${value}`); } return acc; }, {}); return params; } return {}; } export function hasAutogeneratedChapters(): boolean { return !!document.querySelector("ytd-engagement-panel-section-list-renderer ytd-macro-markers-list-renderer #menu"); } export function getExistingChapters(currentVideoID: VideoID, duration: number): SponsorTime[] { const chaptersBox = document.querySelector("ytd-macro-markers-list-renderer"); const title = chaptersBox?.closest("ytd-engagement-panel-section-list-renderer")?.querySelector("#title-text.ytd-engagement-panel-title-header-renderer"); if (title?.textContent?.includes("Key moment")) return []; const autogenerated = hasAutogeneratedChapters(); if (!getSkipProfileBool("showAutogeneratedChapters") && autogenerated) return []; const chapters: SponsorTime[] = []; // .ytp-timed-markers-container indicates that key-moments are present, which should not be divided if (chaptersBox) { let lastSegment: SponsorTime = null; const links = chaptersBox.querySelectorAll("ytd-macro-markers-list-item-renderer > a"); for (const link of links) { const timeElement = link.querySelector("#time") as HTMLElement; const description = link.querySelector("#details h4") as HTMLElement; if (timeElement && description?.innerText?.length > 0 && link.getAttribute("href")?.includes(currentVideoID)) { const time = getFormattedTimeToSeconds(timeElement.innerText.replace(/\./g, ":")); if (time === null) return []; if (lastSegment) { lastSegment.segment[1] = time; chapters.push(lastSegment); } lastSegment = { segment: [time, null], category: "chapter" as Category, actionType: ActionType.Chapter, description: description.innerText, source: autogenerated ? SponsorSourceType.Autogenerated : SponsorSourceType.YouTube, UUID: null }; } } if (lastSegment) { lastSegment.segment[1] = duration; chapters.push(lastSegment); } } return chapters; } export function isPlayingPlaylist() { return !!document.URL.includes("&list="); } ================================================ FILE: src/utils/requests.ts ================================================ import Config from "../config"; import * as CompileConfig from "../../config.json"; import { FetchResponse, sendRequestToCustomServer } from "../../maze-utils/src/background-request-proxy"; /** * Sends a request to the SponsorBlock server with address added as a query * * @param type The request type. "GET", "POST", etc. * @param address The address to add to the SponsorBlock server address * @param callback */ export async function asyncRequestToServer(type: string, address: string, data = {}, headers = {}): Promise { const serverAddress = Config.config.testingServer ? CompileConfig.testingServerAddress : Config.config.serverAddress; return await (sendRequestToCustomServer(type, serverAddress + address, data, headers)); } ================================================ FILE: src/utils/segmentData.ts ================================================ import { DataCache } from "../../maze-utils/src/cache"; import { getHash, HashedValue } from "../../maze-utils/src/hash"; import Config, { } from "../config"; import * as CompileConfig from "../../config.json"; import { ActionTypes, SponsorSourceType, SponsorTime, VideoID } from "../types"; import { getHashParams } from "./pageUtils"; import { asyncRequestToServer } from "./requests"; import { extensionUserAgent } from "../../maze-utils/src"; import { logRequest, serializeOrStringify } from "../../maze-utils/src/background-request-proxy"; const segmentDataCache = new DataCache(() => { return { segments: null, status: 200 }; }, null, 5); const pendingList: Record> = {}; export interface SegmentResponse { segments: SponsorTime[] | null; status: number | Error | string; } export async function getSegmentsForVideo(videoID: VideoID, ignoreCache: boolean): Promise { if (!ignoreCache) { const cachedData = segmentDataCache.getFromCache(videoID); if (cachedData) { segmentDataCache.cacheUsed(videoID); return cachedData; } } if (pendingList[videoID]) { return await pendingList[videoID]; } const pendingData = fetchSegmentsForVideo(videoID); pendingList[videoID] = pendingData; let result: Awaited; try { result = await pendingData; } catch (e) { console.error("[SB] Caught error while fetching segments", e); return { segments: null, status: serializeOrStringify(e), } } finally { delete pendingList[videoID]; } return result; } async function fetchSegmentsForVideo(videoID: VideoID): Promise { const extraRequestData: Record = {}; const hashParams = getHashParams(); if (hashParams.requiredSegment) extraRequestData.requiredSegment = hashParams.requiredSegment; const hashPrefix = (await getHash(videoID, 1)).slice(0, 5) as VideoID & HashedValue; const hasDownvotedSegments = !!Config.local.downvotedSegments[hashPrefix.slice(0, 4)]; const response = await asyncRequestToServer('GET', "/api/skipSegments/" + hashPrefix, { categories: CompileConfig.categoryList, actionTypes: ActionTypes, trimUUIDs: hasDownvotedSegments ? null : 5, ...extraRequestData }, { "X-CLIENT-NAME": extensionUserAgent(), }); if (response.ok) { const receivedSegments: SponsorTime[] = JSON.parse(response.responseText) ?.filter((video) => video.videoID === videoID) ?.map((video) => video.segments)?.[0] ?.map((segment) => ({ ...segment, source: SponsorSourceType.Server })) ?.sort((a, b) => a.segment[0] - b.segment[0]); if (receivedSegments && receivedSegments.length) { const result = { segments: receivedSegments, status: response.status }; segmentDataCache.setupCache(videoID).segments = result.segments; return result; } else { // Setup with null data segmentDataCache.setupCache(videoID); } } else if (response.status !== 404) { logRequest(response, "SB", "skip segments"); } return { segments: null, status: response.status }; } ================================================ FILE: src/utils/skipProfiles.ts ================================================ import { getChannelIDInfo, getVideoID } from "../../maze-utils/src/video"; import Config, { ConfigurationID, CustomConfiguration } from "../config"; import { SponsorHideType, SponsorTime } from "../types"; let currentTabSkipProfile: ConfigurationID = null; export function getSkipProfileIDForTime(): ConfigurationID | null { if (Config.local.skipProfileTemp !== null && Config.local.skipProfileTemp.time > Date.now() - 60 * 60 * 1000) { return Config.local.skipProfileTemp.configID; } else { return null; } } export function getSkipProfileIDForTab(): ConfigurationID | null { return currentTabSkipProfile; } export function setCurrentTabSkipProfile(configID: ConfigurationID | null) { currentTabSkipProfile = configID ?? null; } export function getSkipProfileIDForVideo(): ConfigurationID | null { return Config.local.channelSkipProfileIDs[getVideoID()] ?? null; } export function getSkipProfileIDForChannel(): ConfigurationID | null { const channelInfo = getChannelIDInfo(); if (!channelInfo) { return null; } return Config.local.channelSkipProfileIDs[channelInfo.id] ?? Config.local.channelSkipProfileIDs[channelInfo.author] ?? null; } export function getSkipProfileID(): ConfigurationID | null { const configID = getSkipProfileIDForTime() ?? getSkipProfileIDForTab() ?? getSkipProfileIDForVideo() ?? getSkipProfileIDForChannel(); return configID ?? null; } export function getSkipProfile(): CustomConfiguration | null { const configID = getSkipProfileID(); if (configID) { return Config.local.skipProfiles[configID]; } return null; } type SkipProfileBoolKey = "showAutogeneratedChapters" | "autoSkipOnMusicVideos" | "skipNonMusicOnlyOnYoutubeMusic" | "muteSegments" | "fullVideoSegments" | "manualSkipOnFullVideo"; export function getSkipProfileBool(key: SkipProfileBoolKey): boolean { return getSkipProfileValue(key); } export function getSkipProfileNum(key: "minDuration"): number { return getSkipProfileValue(key); } function getSkipProfileValue(key: keyof CustomConfiguration): T { const profile = getSkipProfile(); if (profile && profile[key] !== null) { return profile[key] as T; } return Config.config[key]; } export function hideTooShortSegments(sponsorTimes: SponsorTime[]) { const minDuration = getSkipProfileNum("minDuration"); if (minDuration !== 0) { for (const segment of sponsorTimes) { const duration = segment.segment[1] - segment.segment[0]; if (duration > 0 && duration < minDuration && (segment.hidden === SponsorHideType.Visible || SponsorHideType.MinimumDuration)) { segment.hidden = SponsorHideType.MinimumDuration; } else if (segment.hidden === SponsorHideType.MinimumDuration) { segment.hidden = SponsorHideType.Visible; } } } } ================================================ FILE: src/utils/skipRule.ts ================================================ import { getCurrentPageTitle } from "../../maze-utils/src/elements"; import { getChannelIDInfo, getVideoDuration } from "../../maze-utils/src/video"; import Config from "../config"; import {ActionType, ActionTypes, CategorySelection, CategorySkipOption, SponsorSourceType, SponsorTime} from "../types"; import { getSkipProfile, getSkipProfileBool } from "./skipProfiles"; import { VideoLabelsCacheData } from "./videoLabels"; import * as CompileConfig from "../../config.json"; import { AdvancedSkipCheck, AdvancedSkipPredicate, AdvancedSkipRule, PredicateOperator, SkipRuleAttribute, SkipRuleOperator } from "./skipRule.type"; const SKIP_RULE_ATTRIBUTES = Object.values(SkipRuleAttribute); const SKIP_RULE_OPERATORS = Object.values(SkipRuleOperator); const INVERTED_SKIP_RULE_OPERATORS = { "<=": SkipRuleOperator.Greater, "<": SkipRuleOperator.GreaterOrEqual, ">=": SkipRuleOperator.Less, ">": SkipRuleOperator.LessOrEqual, "!=": SkipRuleOperator.Equal, "==": SkipRuleOperator.NotEqual, "!*=": SkipRuleOperator.Contains, "*=": SkipRuleOperator.NotContains, "!~=": SkipRuleOperator.Regex, "~=": SkipRuleOperator.NotRegex, "!~i=": SkipRuleOperator.RegexIgnoreCase, "~i=": SkipRuleOperator.NotRegexIgnoreCase, }; const WORD_EXTRA_CHARACTER = /[a-zA-Z0-9.]/; const OPERATOR_EXTRA_CHARACTER = /[<>=!~*&|-]/; const ANY_EXTRA_CHARACTER = /[a-zA-Z0-9<>=!~*&|.-]/; export function getCategorySelection(segment: SponsorTime | VideoLabelsCacheData): CategorySelection { // First check skip rules for (const rule of Config.local.skipRules) { if (isSkipPredicatePassing(segment, rule.predicate)) { return { name: segment.category, option: rule.skipOption } as CategorySelection; } } // Action type filters if ("actionType" in segment && (segment as SponsorTime).actionType === "mute" && !getSkipProfileBool("muteSegments")) { return { name: segment.category, option: CategorySkipOption.Disabled } as CategorySelection; } // Then check skip profile const profile = getSkipProfile(); if (profile) { const profileSelection = profile.categorySelections.find(selection => selection.name === segment.category); if (profileSelection) { return profileSelection; } } // Then fallback to default for (const selection of Config.config.categorySelections) { if (selection.name === segment.category) { return selection; } } return { name: segment.category, option: CategorySkipOption.Disabled} as CategorySelection; } function getSkipCheckValue(segment: SponsorTime | VideoLabelsCacheData, rule: AdvancedSkipCheck): string | number | undefined { switch (rule.attribute) { case SkipRuleAttribute.StartTime: return (segment as SponsorTime).segment?.[0]; case SkipRuleAttribute.EndTime: return (segment as SponsorTime).segment?.[1]; case SkipRuleAttribute.Duration: return (segment as SponsorTime).segment?.[1] - (segment as SponsorTime).segment?.[0]; case SkipRuleAttribute.StartTimePercent: { const startTime = (segment as SponsorTime).segment?.[0]; if (startTime === undefined) return undefined; return startTime / getVideoDuration() * 100; } case SkipRuleAttribute.EndTimePercent: { const endTime = (segment as SponsorTime).segment?.[1]; if (endTime === undefined) return undefined; return endTime / getVideoDuration() * 100; } case SkipRuleAttribute.DurationPercent: { const startTime = (segment as SponsorTime).segment?.[0]; const endTime = (segment as SponsorTime).segment?.[1]; if (startTime === undefined || endTime === undefined) return undefined; return (endTime - startTime) / getVideoDuration() * 100; } case SkipRuleAttribute.Category: return segment.category; case SkipRuleAttribute.ActionType: return (segment as SponsorTime).actionType; case SkipRuleAttribute.Description: return (segment as SponsorTime).description || ""; case SkipRuleAttribute.Source: switch ((segment as SponsorTime).source) { case SponsorSourceType.Local: return "local"; case SponsorSourceType.YouTube: return "youtube"; case SponsorSourceType.Autogenerated: return "autogenerated"; case SponsorSourceType.Server: return "server"; default: return undefined; } case SkipRuleAttribute.ChannelID: return getChannelIDInfo().id; case SkipRuleAttribute.ChannelName: return getChannelIDInfo().author; case SkipRuleAttribute.VideoDuration: return getVideoDuration(); case SkipRuleAttribute.Title: return getCurrentPageTitle() || ""; default: return undefined; } } function isSkipCheckPassing(segment: SponsorTime | VideoLabelsCacheData, rule: AdvancedSkipCheck): boolean { const value = getSkipCheckValue(segment, rule); switch (rule.operator) { case SkipRuleOperator.Less: return typeof value === "number" && value < (rule.value as number); case SkipRuleOperator.LessOrEqual: return typeof value === "number" && value <= (rule.value as number); case SkipRuleOperator.Greater: return typeof value === "number" && value > (rule.value as number); case SkipRuleOperator.GreaterOrEqual: return typeof value === "number" && value >= (rule.value as number); case SkipRuleOperator.Equal: return value === rule.value; case SkipRuleOperator.NotEqual: return value !== rule.value; case SkipRuleOperator.Contains: return String(value).toLocaleLowerCase().includes(String(rule.value).toLocaleLowerCase()); case SkipRuleOperator.NotContains: return !String(value).toLocaleLowerCase().includes(String(rule.value).toLocaleLowerCase()); case SkipRuleOperator.Regex: return new RegExp(rule.value as string).test(String(value)); case SkipRuleOperator.RegexIgnoreCase: return new RegExp(rule.value as string, "i").test(String(value)); case SkipRuleOperator.NotRegex: return !new RegExp(rule.value as string).test(String(value)); case SkipRuleOperator.NotRegexIgnoreCase: return !new RegExp(rule.value as string, "i").test(String(value)); default: return false; } } function isSkipPredicatePassing(segment: SponsorTime | VideoLabelsCacheData, predicate: AdvancedSkipPredicate): boolean { if (predicate.kind === "check") { return isSkipCheckPassing(segment, predicate as AdvancedSkipCheck); } else { // predicate.kind === "operator" // TODO Is recursion fine to use here? if (predicate.operator == PredicateOperator.And) { return isSkipPredicatePassing(segment, predicate.left) && isSkipPredicatePassing(segment, predicate.right); } else { // predicate.operator === PredicateOperator.Or return isSkipPredicatePassing(segment, predicate.left) || isSkipPredicatePassing(segment, predicate.right); } } } export function getCategoryDefaultSelection(category: string): CategorySelection { for (const selection of Config.config.categorySelections) { if (selection.name === category) { return selection; } } return { name: category, option: CategorySkipOption.Disabled} as CategorySelection; } type TokenType = | "if" // Keywords | "disabled" | "show overlay" | "manual skip" | "auto skip" // Skip option | `${SkipRuleAttribute}` // Segment attributes | `${SkipRuleOperator}` // Segment attribute operators | "and" | "or" | "not" // Expression operators | "(" | ")" | "comment" // Syntax | "string" | "number" // Literal values | "eof" | "error"; // Sentinel and special tokens export interface SourcePos { line: number; } export interface Span { start: SourcePos; end: SourcePos; } interface Token { type: TokenType; span: Span; value: string; } class Lexer { private readonly source: string; private start: number; private current: number; private start_pos: SourcePos; private current_pos: SourcePos; public constructor(source: string) { this.source = source; this.start = 0; this.current = 0; this.start_pos = { line: 1 }; this.current_pos = { line: 1 }; } private makeToken(type: TokenType): Token { return { type, span: { start: this.start_pos, end: this.current_pos, }, value: this.source.slice(this.start, this.current), }; } /** * Returns the UTF-16 value at the current position and advances it forward. * If the end of the source string has been reached, returns null. * * @return current UTF-16 value, or null on EOF */ private consume(): string | null { if (this.source.length > this.current) { // The UTF-16 value at the current position, which could be either a Unicode code point or a lone surrogate. // The check above this is also based on the UTF-16 value count, so this should not be able to fail on “weird” inputs. const c = this.source[this.current]; this.current++; if (c === "\n") { // Cannot use this.current_pos.line++, because SourcePos is mutable and used in tokens without copying this.current_pos = { line: this.current_pos.line + 1, }; } return c; } else { return null; } } /** * Returns the UTF-16 value at the current position without advancing it. * If the end of the source string has been reached, returns null. * * @return current UTF-16 value, or null on EOF */ private peek(): string | null { if (this.source.length > this.current) { // See comment in consume() for Unicode expectations here return this.source[this.current]; } else { return null; } } /** * Checks the word at the current position against a list of * expected keywords. The keyword can consist of multiple characters. * If a match is found, the current position is advanced by the length * of the keyword found. * * @param keywords the expected set of keywords at the current position * @param caseSensitive whether to do a case-sensitive comparison * @return the matching keyword, or null */ private expectKeyword(keywords: readonly string[], caseSensitive: boolean): string | null { for (const keyword of keywords) { // slice() clamps to string length, so cannot cause out of bounds errors const actual = this.source.slice(this.current, this.current + keyword.length); if (caseSensitive && keyword === actual || !caseSensitive && keyword.toLowerCase() === actual.toLowerCase()) { // Does not handle keywords containing line feeds, which shouldn't happen anyway this.current += keyword.length; return keyword; } } return null; } /** * Skips a series of whitespace characters starting at the current * position. May advance the current position multiple times, once, * or not at all. */ private skipWhitespace() { let c = this.peek(); const whitespace = /\s+/; while (c != null) { if (!whitespace.test(c)) { return; } this.consume(); c = this.peek(); } } /** * Skips all characters until the next "\n" (line feed) * character occurs (inclusive). Will always advance the current position * at least once. */ private skipLine() { let c = this.consume(); while (c != null) { if (c == '\n') { return; } c = this.consume(); } } /** * @return whether the lexer has reached the end of input */ private isEof(): boolean { return this.current >= this.source.length; } /** * Sets the start position of the next token that will be emitted * to the current position. * * More characters need to be consumed after calling this, as * an empty token would be emitted otherwise. */ private resetToCurrent() { this.start = this.current; this.start_pos = this.current_pos; } public nextToken(): Token { this.skipWhitespace(); this.resetToCurrent(); if (this.isEof()) { return this.makeToken("eof"); } const keyword = this.expectKeyword([ "if", "and", "or", "not", "(", ")", "//", ].concat(SKIP_RULE_ATTRIBUTES) .concat(SKIP_RULE_OPERATORS), true); let type: TokenType | null = null; let kind: "word" | "operator" | null = null; if (keyword !== null) { if ((SKIP_RULE_ATTRIBUTES as string[]).includes(keyword)) { kind = "word"; type = keyword as TokenType; } else if ((SKIP_RULE_OPERATORS as string[]).includes(keyword)) { kind = "operator"; type = keyword as TokenType; } else { switch (keyword) { case "if": // Fallthrough case "and": // Fallthrough case "or": // Fallthrough case "not": kind = "word"; type = keyword as TokenType; break; case "(": return this.makeToken("("); case ")": return this.makeToken(")"); case "//": this.resetToCurrent(); this.skipLine(); return this.makeToken("comment"); default: } } } else { const keyword2 = this.expectKeyword( [ "disabled", "show overlay", "manual skip", "auto skip" ], false); if (keyword2 !== null) { kind = "word"; type = keyword2 as TokenType; } } if (type !== null) { const more = kind == "operator" ? OPERATOR_EXTRA_CHARACTER : kind == "word" ? WORD_EXTRA_CHARACTER : ANY_EXTRA_CHARACTER; let c = this.peek(); let error = false; while (c !== null && more.test(c)) { error = true; this.consume(); c = this.peek(); } return this.makeToken(error ? "error" : type); } let c = this.consume(); if (c === '"') { // Parses string according to ECMA-404 2nd edition (JSON), section 9 “String” let output = ""; let c = this.consume(); let error = false; while (c !== null && c !== '"') { if (c == '\\') { c = this.consume(); switch (c) { case '"': output = output.concat('"'); break; case '\\': output = output.concat('\\'); break; case '/': output = output.concat('/'); break; case 'b': output = output.concat('\b'); break; case 'f': output = output.concat('\f'); break; case 'n': output = output.concat('\n'); break; case 'r': output = output.concat('\r'); break; case 't': output = output.concat('\t'); break; case 'u': { // UTF-16 value sequence const digits = this.source.slice(this.current, this.current + 4); if (digits.length < 4 || !/[0-9a-zA-Z]{4}/.test(digits)) { error = true; output = output.concat(`\\u`); c = this.consume(); continue; } const value = parseInt(digits, 16); // fromCharCode() takes a UTF-16 value without performing validity checks, // which is exactly what is needed here – in JSON, code units outside the // BMP are represented by two Unicode escape sequences. output = output.concat(String.fromCharCode(value)); break; } default: error = true; output = output.concat(`\\${c}`); break; } } else if (c === '\n') { // Unterminated / multi-line string, unsupported error = true; // Prevent unterminated strings from consuming the entire rest of the input break; } else { output = output.concat(c); } c = this.consume(); } return { type: error || c !== '"' ? "error" : "string", span: { start: this.start_pos, end: this.current_pos, }, value: output, }; } else if (/[0-9-]/.test(c)) { // Parses number according to ECMA-404 2nd edition (JSON), section 8 “Numbers” if (c === '-') { c = this.consume(); if (!/[0-9]/.test(c)) { return this.makeToken("error"); } } const leadingZero = c === '0'; let next = this.peek(); let error = false; while (next !== null && /[0-9]/.test(next)) { this.consume(); next = this.peek(); if (leadingZero) { error = true; } } if (next !== null && next === '.') { this.consume(); next = this.peek(); if (next === null || !/[0-9]/.test(next)) { return this.makeToken("error"); } do { this.consume(); next = this.peek(); } while (next !== null && /[0-9]/.test(next)); } next = this.peek(); if (next != null && (next === 'e' || next === 'E')) { this.consume(); next = this.peek(); if (next === null) { return this.makeToken("error"); } if (next === '+' || next === '-') { this.consume(); next = this.peek(); } while (next !== null && /[0-9]/.test(next)) { this.consume(); next = this.peek(); } } return this.makeToken(error ? "error" : "number"); } // Consume common characters up to a space for a more useful value in the error token const common = ANY_EXTRA_CHARACTER; c = this.peek(); while (c !== null && common.test(c)) { this.consume(); c = this.peek(); } return this.makeToken("error"); } } export interface ParseError { span: Span; message: string; } class Parser { private lexer: Lexer; private previous: Token; private current: Token; private readonly rules: AdvancedSkipRule[]; private readonly errors: ParseError[]; private erroring: boolean; private panicMode: boolean; public constructor(lexer: Lexer) { this.lexer = lexer; this.previous = null; this.current = lexer.nextToken(); this.rules = []; this.errors = []; this.erroring = false; this.panicMode = false; } // Helper functions /** * Adds an error message. The current skip rule will be marked as erroring. * * @param span the range of the error * @param message the message to report * @param panic if true, all further errors will be silenced * until panic mode is disabled again */ private errorAt(span: Span, message: string, panic: boolean) { if (!this.panicMode) { this.errors.push({span, message,}); } this.panicMode ||= panic; this.erroring = true; } /** * Adds an error message for an error occurring at the previous token * (which was just consumed). * * @param message the message to report * @param panic if true, all further errors will be silenced * until panic mode is disabled again */ private error(message: string, panic: boolean) { this.errorAt(this.previous.span, message, panic); } /** * Adds an error message for an error occurring at the current token * (which has not been consumed yet). * * @param message the message to report * @param panic if true, all further errors will be silenced * until panic mode is disabled again */ private errorAtCurrent(message: string, panic: boolean) { this.errorAt(this.current.span, message, panic); } /** * Consumes the current token, which can then be accessed at previous. * The next token will be at current after this call. * * If a token of type error is found, issues an error message. */ private consume() { this.previous = this.current; // Intentionally ignoring `error` tokens here; // by handling those in later privates with more context (match(), expect(), ...), // the user gets better errors this.current = this.lexer.nextToken(); } /** * Checks the current token (that has not been consumed yet) against a set of expected token types. * * @param expected the set of expected token types * @return whether the actual current token matches any expected token type */ private match(expected: readonly TokenType[]): boolean { if (expected.includes(this.current.type)) { this.consume(); return true; } else { return false; } } /** * Checks the current token (that has not been consumed yet) against a set of expected token types. * * If there is no match, issues an error message which will be prepended to , got: . * * @param expected the set of expected token types * @param message the error message to report in case the actual token doesn't match * @param panic if true, all further errors will be silenced * until panic mode is disabled again */ private expect(expected: readonly TokenType[], message: string, panic: boolean) { if (!this.match(expected)) { this.errorAtCurrent(message.concat(this.current.type === "error" ? `, got: ${JSON.stringify(this.current.value)}` : `, got: \`${this.current.type}\``), panic); } } /** * Synchronize with the next rule block and disable panic mode. * Skips all tokens until the if keyword is found. */ private synchronize() { this.panicMode = false; while (!this.isEof()) { if (this.current.type === "if") { return; } this.consume(); } } /** * @return whether the parser has reached the end of input */ private isEof(): boolean { return this.current.type === "eof"; } // Parsing functions /** * Parse the config. Should only ever be called once on a given * Parser instance. */ public parse(): { rules: AdvancedSkipRule[]; errors: ParseError[] } { while (!this.isEof()) { this.erroring = false; const rule = this.parseRule(); if (!this.erroring && rule) { this.rules.push(rule); } if (this.panicMode) { this.synchronize(); } } return { rules: this.rules, errors: this.errors, }; } private parseRule(): AdvancedSkipRule | null { const rule: AdvancedSkipRule = { predicate: null, skipOption: null, comments: [], }; while (this.match(["comment"])) { rule.comments.push(this.previous.value.trim()); } this.expect(["if"], rule.comments.length !== 0 ? "expected `if` after `comment`" : "expected `if`", true); rule.predicate = this.parsePredicate(); this.expect(["disabled", "show overlay", "manual skip", "auto skip"], "expected skip option after condition", true); switch (this.previous.type) { case "disabled": rule.skipOption = CategorySkipOption.Disabled; break; case "show overlay": rule.skipOption = CategorySkipOption.ShowOverlay; break; case "manual skip": rule.skipOption = CategorySkipOption.ManualSkip; break; case "auto skip": rule.skipOption = CategorySkipOption.AutoSkip; break; default: // Ignore, should have already errored } return rule; } private parsePredicate(): AdvancedSkipPredicate | null { return this.parseOr(); } private parseOr(): AdvancedSkipPredicate | null { let left = this.parseAnd(); while (this.match(["or"])) { const right = this.parseAnd(); left = { kind: "operator", operator: PredicateOperator.Or, left, right, }; } return left; } private parseAnd(): AdvancedSkipPredicate | null { let left = this.parseUnary(); while (this.match(["and"])) { const right = this.parseUnary(); left = { kind: "operator", operator: PredicateOperator.And, left, right, }; } return left; } private parseUnary(): AdvancedSkipPredicate | null { if (this.match(["not"])) { const predicate = this.parseUnary(); return predicate ? invertPredicate(predicate) : null; } return this.parsePrimary(); } private parsePrimary(): AdvancedSkipPredicate | null { if (this.match(["("])) { const predicate = this.parsePredicate(); this.expect([")"], "expected `)` after condition", true); return predicate; } else { return this.parseCheck(); } } private parseCheck(): AdvancedSkipCheck | null { this.expect(SKIP_RULE_ATTRIBUTES, `expected attribute after \`${this.previous.type}\``, true); if (this.erroring) { return null; } const attribute = this.previous.type as SkipRuleAttribute; this.expect(SKIP_RULE_OPERATORS, `expected operator after \`${attribute}\``, true); if (this.erroring) { return null; } const operator = this.previous.type as SkipRuleOperator; this.expect(["string", "number"], `expected string or number after \`${operator}\``, true); if (this.erroring) { return null; } const value = this.previous.type === "number" ? Number(this.previous.value) : this.previous.value; if ([SkipRuleOperator.Equal, SkipRuleOperator.NotEqual].includes(operator)) { if (attribute === SkipRuleAttribute.Category && !CompileConfig.categoryList.includes(value as string)) { this.error(`unknown category: \`${value}\``, false); return null; } else if (attribute === SkipRuleAttribute.ActionType && !ActionTypes.includes(value as ActionType)) { this.error(`unknown action type: \`${value}\``, false); return null; } else if (attribute === SkipRuleAttribute.Source && !["local", "youtube", "autogenerated", "server"].includes(value as string)) { this.error(`unknown chapter source: \`${value}\``, false); return null; } } return { kind: "check", attribute, operator, value, }; } } export function parseConfig(config: string): { rules: AdvancedSkipRule[]; errors: ParseError[] } { const parser = new Parser(new Lexer(config)); return parser.parse(); } export function configToText(config: AdvancedSkipRule[]): string { let result = ""; for (const rule of config) { for (const comment of rule.comments) { result += "// " + comment + "\n"; } result += "if "; result += predicateToText(rule.predicate, null); switch (rule.skipOption) { case CategorySkipOption.Disabled: result += "\nDisabled"; break; case CategorySkipOption.ShowOverlay: result += "\nShow Overlay"; break; case CategorySkipOption.ManualSkip: result += "\nManual Skip"; break; case CategorySkipOption.AutoSkip: result += "\nAuto Skip"; break; default: return null; // Invalid skip option } result += "\n\n"; } return result.trim(); } function predicateToText(predicate: AdvancedSkipPredicate, outerPrecedence: "or" | "and" | "not" | null): string { if (predicate.kind === "check") { return `${predicate.attribute} ${predicate.operator} ${JSON.stringify(predicate.value)}`; } else if (predicate.displayInverted) { // Should always be fine, considering `not` has the highest precedence return `not ${predicateToText(invertPredicate(predicate), "not")}`; } else { let text: string; if (predicate.operator === PredicateOperator.And) { text = `${predicateToText(predicate.left, "and")} and ${predicateToText(predicate.right, "and")}`; } else { // Or text = `${predicateToText(predicate.left, "or")} or ${predicateToText(predicate.right, "or")}`; } return outerPrecedence !== null && outerPrecedence !== predicate.operator ? `(${text})` : text; } } function invertPredicate(predicate: AdvancedSkipPredicate): AdvancedSkipPredicate { if (predicate.kind === "check") { return { ...predicate, operator: INVERTED_SKIP_RULE_OPERATORS[predicate.operator], }; } else { // not (a and b) == (not a or not b) // not (a or b) == (not a and not b) return { kind: "operator", operator: predicate.operator === "and" ? PredicateOperator.Or : PredicateOperator.And, left: predicate.left ? invertPredicate(predicate.left) : null, right: predicate.right ? invertPredicate(predicate.right) : null, displayInverted: !predicate.displayInverted, }; } } ================================================ FILE: src/utils/skipRule.type.ts ================================================ import type { CategorySkipOption } from "../types"; export interface Permission { canSubmit: boolean; } // Note that attributes that are prefixes of other attributes (like `time.start`) need to be ordered *after* // the longer attributes, because these are matched sequentially. Using the longer attribute would otherwise result // in an error token. export enum SkipRuleAttribute { StartTimePercent = "time.startPercent", StartTime = "time.start", EndTimePercent = "time.endPercent", EndTime = "time.end", DurationPercent = "time.durationPercent", Duration = "time.duration", Category = "category", ActionType = "actionType", Description = "chapter.name", Source = "chapter.source", ChannelID = "channel.id", ChannelName = "channel.name", VideoDuration = "video.duration", Title = "video.title" } // Note that operators that are prefixes of other attributes (like `<`) need to be ordered *after* the longer // operators, because these are matched sequentially. Using the longer operator would otherwise result // in an error token. export enum SkipRuleOperator { LessOrEqual = "<=", Less = "<", GreaterOrEqual = ">=", Greater = ">", NotEqual = "!=", Equal = "==", NotContains = "!*=", Contains = "*=", NotRegex = "!~=", Regex = "~=", NotRegexIgnoreCase = "!~i=", RegexIgnoreCase = "~i=" } export interface AdvancedSkipCheck { kind: "check"; attribute: SkipRuleAttribute; operator: SkipRuleOperator; value: string | number; } export enum PredicateOperator { And = "and", Or = "or", } export interface AdvancedSkipOperator { kind: "operator"; operator: PredicateOperator; left: AdvancedSkipPredicate; right: AdvancedSkipPredicate; displayInverted?: boolean; } export type AdvancedSkipPredicate = AdvancedSkipCheck | AdvancedSkipOperator; export interface AdvancedSkipRule { predicate: AdvancedSkipPredicate; skipOption: CategorySkipOption; comments: string[]; } ================================================ FILE: src/utils/thumbnails.ts ================================================ import { extractVideoID, isOnInvidious } from "../../maze-utils/src/video"; import Config from "../config"; import { getHasStartSegment, getVideoLabel } from "./videoLabels"; import { getThumbnailSelector, setThumbnailListener } from "../../maze-utils/src/thumbnailManagement"; import { VideoID } from "../types"; import { getSegmentsForVideo } from "./segmentData"; import { onMobile } from "../../maze-utils/src/pageInfo"; export async function handleThumbnails(thumbnails: HTMLImageElement[]): Promise { await Promise.all(thumbnails.map((t) => { labelThumbnail(t); setupThumbnailHover(t); })); } export async function labelThumbnail(thumbnail: HTMLImageElement): Promise { if (!Config.config?.fullVideoSegments || !Config.config?.fullVideoLabelsOnThumbnails) { hideThumbnailLabel(thumbnail); return null; } const videoID = await extractVideoIDFromElement(thumbnail); if (!videoID) { hideThumbnailLabel(thumbnail); return null; } const category = await getVideoLabel(videoID); if (!category) { hideThumbnailLabel(thumbnail); return null; } const { overlay, text } = createOrGetThumbnail(thumbnail); overlay.style.setProperty('--category-color', `var(--sb-category-preview-${category}, var(--sb-category-${category}))`); overlay.style.setProperty('--category-text-color', `var(--sb-category-text-preview-${category}, var(--sb-category-text-${category}))`); text.innerText = chrome.i18n.getMessage(`category_${category}`); overlay.classList.add("sponsorThumbnailLabelVisible"); return overlay; } export async function setupThumbnailHover(thumbnail: HTMLImageElement): Promise { // Cache would be reset every load due to no SPA if (isOnInvidious()) return; const mainElement = thumbnail.closest("#dismissible") as HTMLElement; if (mainElement) { mainElement.removeEventListener("mouseenter", thumbnailHoverListener); mainElement.addEventListener("mouseenter", thumbnailHoverListener); } } function thumbnailHoverListener(e: MouseEvent) { if (!chrome.runtime?.id) return; const thumbnail = (e.target as HTMLElement).querySelector(getThumbnailSelector()) as HTMLImageElement; if (!thumbnail) return; // Pre-fetch data for this video let fetched = false; const preFetch = async () => { fetched = true; const videoID = await extractVideoIDFromElement(thumbnail); if (videoID && await getHasStartSegment(videoID)) { void getSegmentsForVideo(videoID, false); } }; const timeout = setTimeout(preFetch, 100); const onMouseDown = () => { clearTimeout(timeout); if (!fetched) { preFetch(); } }; e.target.addEventListener("mousedown", onMouseDown, { once: true }); e.target.addEventListener("mouseleave", () => { clearTimeout(timeout); e.target.removeEventListener("mousedown", onMouseDown); }, { once: true }); } function getLink(thumbnail: HTMLImageElement): HTMLAnchorElement | null { if (isOnInvidious()) { return thumbnail.parentElement as HTMLAnchorElement | null; } else if (!onMobile()) { const link = thumbnail.querySelector("a#thumbnail, a.reel-item-endpoint, a.yt-lockup-metadata-view-model__title, a.yt-lockup-metadata-view-model__title-link, a.yt-lockup-view-model__content-image, a.yt-lockup-metadata-view-model-wiz__title") as HTMLAnchorElement; if (link) { return link; } else if (thumbnail.nodeName === "YTD-HERO-PLAYLIST-THUMBNAIL-RENDERER" || thumbnail.nodeName === "YT-THUMBNAIL-VIEW-MODEL" ) { return thumbnail.closest("a") as HTMLAnchorElement; } else { return null; } } else { // Big thumbnails, compact thumbnails, shorts, channel feature, playlist header return thumbnail.querySelector("a.media-item-thumbnail-container, a.compact-media-item-image, a.reel-item-endpoint, :scope > a, .amsterdam-playlist-thumbnail-wrapper > a") as HTMLAnchorElement; } } async function extractVideoIDFromElement(thumbnail: HTMLImageElement): Promise { const link = getLink(thumbnail); if (!link || link.nodeName !== "A" || !link.href) return null; // no link found return await extractVideoID(link); } function getOldThumbnailLabel(thumbnail: HTMLImageElement): HTMLElement | null { return thumbnail.querySelector(".sponsorThumbnailLabel") as HTMLElement | null; } function hideThumbnailLabel(thumbnail: HTMLImageElement): void { const oldLabel = getOldThumbnailLabel(thumbnail); if (oldLabel) { oldLabel.classList.remove("sponsorThumbnailLabelVisible"); } } function createOrGetThumbnail(thumbnail: HTMLImageElement): { overlay: HTMLElement; text: HTMLElement } { const oldElement = getOldThumbnailLabel(thumbnail); if (oldElement) { return { overlay: oldElement as HTMLElement, text: oldElement.querySelector("span") as HTMLElement }; } const overlay = document.createElement("div") as HTMLElement; overlay.classList.add("sponsorThumbnailLabel"); // Disable hover autoplay overlay.addEventListener("pointerenter", (e) => { e.stopPropagation(); thumbnail.dispatchEvent(new PointerEvent("pointerleave", { bubbles: true })); }); overlay.addEventListener("pointerleave", (e) => { e.stopPropagation(); thumbnail.dispatchEvent(new PointerEvent("pointerenter", { bubbles: true })); }); const icon = createSBIconElement(); const text = document.createElement("span"); overlay.appendChild(icon); overlay.appendChild(text); thumbnail.appendChild(overlay); return { overlay, text }; } function createSBIconElement(): SVGSVGElement { const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); svg.setAttribute("viewBox", "0 0 565.15 568"); const use = document.createElementNS("http://www.w3.org/2000/svg", "use"); use.setAttribute("href", "#SponsorBlockIcon"); svg.appendChild(use); return svg; } // Inserts the icon svg definition, so it can be used elsewhere function insertSBIconDefinition() { const container = document.createElement("span"); // svg from /public/icons/PlayerStartIconSponsorBlocker.svg, with useless stuff removed container.innerHTML = ` `; document.body.appendChild(container.children[0]); } export function setupThumbnailListener(): void { setThumbnailListener(handleThumbnails, () => { insertSBIconDefinition(); }, () => Config.isReady()); } ================================================ FILE: src/utils/urlParser.ts ================================================ export function getStartTimeFromUrl(url: string): number { const urlParams = new URLSearchParams(url); const time = urlParams?.get('t') || urlParams?.get('time_continue'); return urlTimeToSeconds(time); } export function urlTimeToSeconds(time: string): number { if (!time) { return 0; } const re = /(?:(\d{1,3})h)?(?:(\d{1,2})m)?(\d+)s?/; const match = re.exec(time); if (match) { const hours = parseInt(match[1] ?? '0', 10); const minutes = parseInt(match[2] ?? '0', 10); const seconds = parseInt(match[3] ?? '0', 10); return hours * 3600 + minutes * 60 + seconds; } else if (/\d+/.test(time)) { return parseInt(time, 10); } else { return 0; } } ================================================ FILE: src/utils/videoLabels.ts ================================================ import { Category, CategorySkipOption, VideoID } from "../types"; import { getHash } from "../../maze-utils/src/hash"; import { logWarn } from "./logger"; import { asyncRequestToServer } from "./requests"; import { getCategorySelection } from "./skipRule"; import { FetchResponse, logRequest } from "../../maze-utils/src/background-request-proxy"; export interface VideoLabelsCacheData { category: Category; hasStartSegment: boolean; } export interface LabelCacheEntry { timestamp: number; videos: Record; } const labelCache: Record = {}; const cacheLimit = 1000; async function getLabelHashBlock(hashPrefix: string): Promise { // Check cache const cachedEntry = labelCache[hashPrefix]; if (cachedEntry) { return cachedEntry; } let response: FetchResponse; try { response = await asyncRequestToServer("GET", `/api/videoLabels/${hashPrefix}?hasStartSegment=true`); } catch (e) { console.error("[SB] Caught error while fetching video labels", e) return null; } if (response.status !== 200) { logRequest(response, "SB", "video labels"); // No video labels or server down labelCache[hashPrefix] = { timestamp: Date.now(), videos: {}, }; return null; } try { const data = JSON.parse(response.responseText); const newEntry: LabelCacheEntry = { timestamp: Date.now(), videos: Object.fromEntries(data.map(video => [video.videoID, { category: video.segments[0]?.category, hasStartSegment: video.hasStartSegment }])), }; labelCache[hashPrefix] = newEntry; if (Object.keys(labelCache).length > cacheLimit) { // Remove oldest entry const oldestEntry = Object.entries(labelCache).reduce((a, b) => a[1].timestamp < b[1].timestamp ? a : b); delete labelCache[oldestEntry[0]]; } return newEntry; } catch (e) { logWarn(`Error parsing video labels: ${e}`); return null; } } export async function getVideoLabel(videoID: VideoID): Promise { const prefix = (await getHash(videoID, 1)).slice(0, 4); const result = await getLabelHashBlock(prefix); if (result) { const category = result.videos[videoID]?.category; if (category && getCategorySelection(result.videos[videoID]).option !== CategorySkipOption.Disabled) { return category; } else { return null; } } return null; } export async function getHasStartSegment(videoID: VideoID): Promise { const prefix = (await getHash(videoID, 1)).slice(0, 4); const result = await getLabelHashBlock(prefix); if (result) { return result?.videos[videoID]?.hasStartSegment ?? false; } return null; } ================================================ FILE: src/utils/warnings.ts ================================================ import { objectToURI } from "../../maze-utils/src"; import { FetchResponse, logRequest } from "../../maze-utils/src/background-request-proxy"; import { formatJSErrorMessage, getLongErrorMessage } from "../../maze-utils/src/formating"; import { getHash } from "../../maze-utils/src/hash"; import Config from "../config"; import GenericNotice, { NoticeOptions } from "../render/GenericNotice"; import { ContentContainer } from "../types"; import { asyncRequestToServer } from "./requests"; export interface ChatConfig { displayName: string; composerInitialValue?: string; customDescription?: string; } export async function openWarningDialog(contentContainer: ContentContainer): Promise { let userInfo: FetchResponse; try { userInfo = await asyncRequestToServer("GET", "/api/userInfo", { publicUserID: await getHash(Config.config.userID), values: ["warningReason"] }); } catch (e) { console.error("[SB] Caught error while trying to fetch user's active warnings", e) return; } if (userInfo.ok) { const warningReason = JSON.parse(userInfo.responseText)?.warningReason; let userName = ""; try { const userNameData = await asyncRequestToServer("GET", "/api/getUsername?userID=" + Config.config.userID); userName = userNameData.ok ? JSON.parse(userNameData.responseText).userName : ""; } catch (e) { console.warn("[SB] Caught non-fatal error while trying to resolve user's username", e); } const publicUserID = await getHash(Config.config.userID); let notice: GenericNotice = null; const options: NoticeOptions = { title: chrome.i18n.getMessage("deArrowMessageRecieved"), textBoxes: [{ text: chrome.i18n.getMessage("warningChatInfo"), icon: null }, ...warningReason.split("\n").map((reason) => ({ text: reason, icon: null }))], buttons: [{ name: chrome.i18n.getMessage("questionButton"), listener: () => openChat({ displayName: `${userName ? userName : ``}${userName !== publicUserID ? ` | ${publicUserID}` : ``}` }) }, { name: chrome.i18n.getMessage("warningConfirmButton"), listener: async () => { let result: FetchResponse; try { result = await asyncRequestToServer("POST", "/api/warnUser", { userID: Config.config.userID, enabled: false }); } catch (e) { console.error("[SB] Caught error while trying to acknowledge user's active warning", e); alert(formatJSErrorMessage(e)); } if (result.ok) { notice?.close(); } else { logRequest(result, "SB", "warning acknowledgement"); alert(getLongErrorMessage(result.status, result.responseText)); } } }], timed: false }; notice = new GenericNotice(contentContainer, "warningNotice", options); } else { logRequest(userInfo, "SB", "user's active warnings"); } } export function openChat(config: ChatConfig): void { window.open("https://chat.sponsor.ajay.app/#" + objectToURI("", config, false)); } ================================================ FILE: src/utils.ts ================================================ import Config, { VideoDownvotes } from "./config"; import { SponsorTime, BackgroundScriptContainer, Registration, VideoID, SponsorHideType } from "./types"; import { getHash, HashedValue } from "../maze-utils/src/hash"; import { waitFor } from "../maze-utils/src"; import { findValidElementFromSelector } from "../maze-utils/src/dom"; import { isSafari } from "../maze-utils/src/config"; import { asyncRequestToServer } from "./utils/requests"; import { FetchResponse, logRequest } from "../maze-utils/src/background-request-proxy"; import { formatJSErrorMessage, getLongErrorMessage } from "../maze-utils/src/formating"; export default class Utils { // Contains functions needed from the background script backgroundScriptContainer: BackgroundScriptContainer | null; // Used to add content scripts and CSS required js = [ "./js/content.js" ]; css = [ "content.css", "./libs/Source+Sans+Pro.css", "popup.css", "shared.css" ]; constructor(backgroundScriptContainer: BackgroundScriptContainer = null) { this.backgroundScriptContainer = backgroundScriptContainer; } async wait(condition: () => T, timeout = 5000, check = 100): Promise { return waitFor(condition, timeout, check); } containsPermission(permissions: chrome.permissions.Permissions): Promise { return new Promise((resolve) => { chrome.permissions.contains(permissions, resolve) }); } /** * Asks for the optional permissions required for all extra sites. * It also starts the content script registrations. * * For now, it is just SB.config.invidiousInstances. * * @param {CallableFunction} callback */ setupExtraSitePermissions(callback: (granted: boolean) => void): void { const permissions = []; if (isSafari()) { permissions.push("webNavigation"); } chrome.permissions.request({ origins: this.getPermissionRegex(), permissions: permissions }, async (granted) => { if (granted) { this.setupExtraSiteContentScripts(); } else { this.removeExtraSiteRegistration(); } callback(granted); }); } getExtraSiteRegistration(): Registration { return { message: "registerContentScript", id: "invidious", allFrames: true, js: this.js, css: this.css, matches: this.getPermissionRegex() }; } /** * Registers the content scripts for the extra sites. * Will use a different method depending on the browser. * This is called by setupExtraSitePermissions(). * * For now, it is just SB.config.invidiousInstances. */ setupExtraSiteContentScripts(): void { const registration = this.getExtraSiteRegistration(); if (this.backgroundScriptContainer) { this.backgroundScriptContainer.registerFirefoxContentScript(registration); } else { chrome.runtime.sendMessage(registration); } } /** * Removes the permission and content script registration. */ removeExtraSiteRegistration(): void { const id = "invidious"; if (this.backgroundScriptContainer) { this.backgroundScriptContainer.unregisterFirefoxContentScript(id); } else { chrome.runtime.sendMessage({ message: "unregisterContentScript", id: id }); } chrome.permissions.remove({ origins: this.getPermissionRegex() }); } applyInvidiousPermissions(enable: boolean, option = "supportInvidious"): Promise { return new Promise((resolve) => { if (enable) { this.setupExtraSitePermissions((granted) => { if (!granted) { Config.config[option] = false; } resolve(granted); }); } else { this.removeExtraSiteRegistration(); resolve(false); } }); } containsInvidiousPermission(): Promise { return new Promise((resolve) => { const permissions = []; if (isSafari()) { permissions.push("webNavigation"); } chrome.permissions.contains({ origins: this.getPermissionRegex(), permissions: permissions }, function (result) { resolve(result); }); }) } /** * Merges any overlapping timestamp ranges into single segments and returns them as a new array. */ getMergedTimestamps(timestamps: number[][]): [number, number][] { let deduped: [number, number][] = []; // Cases ([] = another segment, <> = current range): // [<]>, <[>], <[]>, [<>], [<][>] timestamps.forEach((range) => { // Find segments the current range overlaps const startOverlaps = deduped.findIndex((other) => range[0] >= other[0] && range[0] <= other[1]); const endOverlaps = deduped.findIndex((other) => range[1] >= other[0] && range[1] <= other[1]); if (~startOverlaps && ~endOverlaps) { // [<][>] Both the start and end of this range overlap another segment // [<>] This range is already entirely contained within an existing segment if (startOverlaps === endOverlaps) return; // Remove the range with the higher index first to avoid the index shifting const other1 = deduped.splice(Math.max(startOverlaps, endOverlaps), 1)[0]; const other2 = deduped.splice(Math.min(startOverlaps, endOverlaps), 1)[0]; // Insert a new segment spanning the start and end of the range deduped.push([Math.min(other1[0], other2[0]), Math.max(other1[1], other2[1])]); } else if (~startOverlaps) { // [<]> The start of this range overlaps another segment, extend its end deduped[startOverlaps][1] = range[1]; } else if (~endOverlaps) { // <[>] The end of this range overlaps another segment, extend its beginning deduped[endOverlaps][0] = range[0]; } else { // No overlaps, just push in a copy deduped.push(range.slice() as [number, number]); } // <[]> Remove other segments contained within this range deduped = deduped.filter((other) => !(other[0] > range[0] && other[1] < range[1])); }); return deduped; } /** * Returns the total duration of the timestamps, taking into account overlaps. */ getTimestampsDuration(timestamps: number[][]): number { return this.getMergedTimestamps(timestamps).reduce((acc, range) => { return acc + range[1] - range[0]; }, 0); } getSponsorIndexFromUUID(sponsorTimes: SponsorTime[], UUID: string): number { for (let i = 0; i < sponsorTimes.length; i++) { if (sponsorTimes[i].UUID && (sponsorTimes[i].UUID.startsWith(UUID) || UUID.startsWith(sponsorTimes[i].UUID))) { return i; } } return -1; } getSponsorTimeFromUUID(sponsorTimes: SponsorTime[], UUID: string): SponsorTime { return sponsorTimes[this.getSponsorIndexFromUUID(sponsorTimes, UUID)]; } /** * @returns {String[]} Domains in regex form */ getPermissionRegex(domains: string[] = []): string[] { const permissionRegex: string[] = []; if (domains.length === 0) { domains = [...Config.config.invidiousInstances]; } for (const url of domains) { permissionRegex.push("https://*." + url + "/*"); permissionRegex.push("http://*." + url + "/*"); } return permissionRegex; } findReferenceNode(): HTMLElement { const selectors = [ "#player-container-id", // Mobile YouTube "#movie_player", ".html5-video-player", // May 2023 Card-Based YouTube Layout "#c4-player", // Channel Trailer "#player-container", // Preview on hover "#main-panel.ytmusic-player-page", // YouTube music "#player-container .video-js", // Invidious ".main-video-section > .video-container", // Cloudtube ".shaka-video-container", // Piped "#player-container.ytk-player", // YT Kids "#id-tv-container" // YTTV ]; let referenceNode = findValidElementFromSelector(selectors) if (referenceNode == null) { //for embeds const player = document.getElementById("player"); referenceNode = player?.firstChild as HTMLElement; if (referenceNode) { let index = 1; //find the child that is the video player (sometimes it is not the first) while (index < player.children.length && (!referenceNode.classList?.contains("html5-video-player") || !referenceNode.classList?.contains("ytp-embed"))) { referenceNode = player.children[index] as HTMLElement; index++; } } } return referenceNode; } isContentScript(): boolean { return window.location.protocol === "http:" || window.location.protocol === "https:"; } isHex(num: string): boolean { return Boolean(num.match(/^[0-9a-f]+$/i)); } async addHiddenSegment(videoID: VideoID, segmentUUID: string, hidden: SponsorHideType) { if ((chrome.extension.inIncognitoContext && !Config.config.trackDownvotesInPrivate) || !Config.config.trackDownvotes) return; if (segmentUUID.length < 60) { let segmentIDData: FetchResponse; try { segmentIDData = await asyncRequestToServer("GET", "/api/segmentID", { UUID: segmentUUID, videoID }); } catch (e) { console.error("[SB] Caught error while trying to resolve the segment UUID to be hidden", e); alert(`${chrome.i18n.getMessage("segmentHideFailed")}\n${formatJSErrorMessage(e)}`); return; } if (segmentIDData.ok && segmentIDData.responseText) { segmentUUID = segmentIDData.responseText; } else { logRequest(segmentIDData, "SB", "segment UUID resolution"); alert(`${chrome.i18n.getMessage("segmentHideFailed")}\n${getLongErrorMessage(segmentIDData.status, segmentIDData.responseText)}`); return; } } const hashedVideoID = (await getHash(videoID, 1)).slice(0, 4) as VideoID & HashedValue; const UUIDHash = await getHash(segmentUUID, 1); const allDownvotes = Config.local.downvotedSegments; const currentVideoData = allDownvotes[hashedVideoID] || { segments: [], lastAccess: 0 }; currentVideoData.lastAccess = Date.now(); const existingData = currentVideoData.segments.find((segment) => segment.uuid === UUIDHash); if (hidden === SponsorHideType.Visible) { currentVideoData.segments.splice(currentVideoData.segments.indexOf(existingData), 1); if (currentVideoData.segments.length === 0) { delete allDownvotes[hashedVideoID]; } } else { if (existingData) { existingData.hidden = hidden; } else { currentVideoData.segments.push({ uuid: UUIDHash, hidden }); } allDownvotes[hashedVideoID] = currentVideoData; } const entries = Object.entries(allDownvotes); if (entries.length > 10000) { let min: [string, VideoDownvotes] = null; for (let i = 0; i < entries[0].length; i++) { if (min === null || entries[i][1].lastAccess < min[1].lastAccess) { min = entries[i]; } } delete allDownvotes[min[0]]; } Config.forceLocalUpdate("downvotedSegments"); } } ================================================ FILE: test/exporter.test.ts ================================================ /** * @jest-environment jsdom */ import { ActionType, Category, SegmentUUID, SponsorSourceType, SponsorTime } from "../src/types"; import { exportTimes, importTimes } from "../src/utils/exporter"; describe("Export segments", () => { it("Some segments", () => { const segments: SponsorTime[] = [{ segment: [0, 10], category: "chapter" as Category, actionType: ActionType.Chapter, description: "Chapter 1", source: SponsorSourceType.Server, UUID: "1" as SegmentUUID }, { segment: [20, 20], category: "poi_highlight" as Category, actionType: ActionType.Poi, description: "Highlight", source: SponsorSourceType.Server, UUID: "2" as SegmentUUID }, { segment: [30, 40], category: "sponsor" as Category, actionType: ActionType.Skip, description: "Sponsor", // Force a description since chrome is not defined source: SponsorSourceType.Server, UUID: "3" as SegmentUUID }, { segment: [50, 60], category: "selfpromo" as Category, actionType: ActionType.Mute, description: "Selfpromo", source: SponsorSourceType.Server, UUID: "4" as SegmentUUID }, { segment: [0, 0], category: "selfpromo" as Category, actionType: ActionType.Full, description: "Selfpromo", source: SponsorSourceType.Server, UUID: "5" as SegmentUUID }, { segment: [80, 90], category: "interaction" as Category, actionType: ActionType.Skip, description: "Interaction", source: SponsorSourceType.YouTube, UUID: "6" as SegmentUUID }]; const result = exportTimes(segments); expect(result).toBe( "0:00.000 - 0:10.000 Chapter 1\n" + "0:20.000 Highlight\n" + "0:30.000 - 0:40.000 Sponsor" ); }); }); describe("Import segments", () => { it("1:20 to 1:21 thing", () => { const input = ` 1:20 to 1:21 thing 1:25 to 1:28 another thing`; const result = importTimes(input, 120); expect(result).toMatchObject([{ segment: [80, 81], description: "thing", category: "chapter" as Category }, { segment: [85, 88], description: "another thing", category: "chapter" as Category }]); }); it("thing 1:20 to 1:21", () => { const input = ` thing 1:20 to 1:21 another thing 1:25 to 1:28 ext`; const result = importTimes(input, 120); expect(result).toMatchObject([{ segment: [80, 81], description: "thing", category: "chapter" as Category }, { segment: [85, 88], description: "another thing", category: "chapter" as Category }]); }); it("1:20 - 1:21 thing", () => { const input = ` 1:20 - 1:21 thing 1:25 - 1:28 another thing`; const result = importTimes(input, 120); expect(result).toMatchObject([{ segment: [80, 81], description: "thing", category: "chapter" as Category }, { segment: [85, 88], description: "another thing", category: "chapter" as Category }]); }); it("1:20 1:21 thing", () => { const input = ` 1:20 1:21 thing 1:25 1:28 another thing`; const result = importTimes(input, 120); expect(result).toMatchObject([{ segment: [80, 81], description: "thing", category: "chapter" as Category }, { segment: [85, 88], description: "another thing", category: "chapter" as Category }]); }); it("1:20 thing", () => { const input = ` 1:20 thing 1:25 another thing`; const result = importTimes(input, 120); expect(result).toMatchObject([{ segment: [80, 85], description: "thing", category: "chapter" as Category }, { segment: [85, 120], description: "another thing", category: "chapter" as Category }]); }); it("1:20: thing", () => { const input = ` 1:20: thing 1:25: another thing`; const result = importTimes(input, 120); expect(result).toMatchObject([{ segment: [80, 85], description: "thing", category: "chapter" as Category }, { segment: [85, 120], description: "another thing", category: "chapter" as Category }]); }); it("1:20 (thing)", () => { const input = ` 1:20 (thing) 1:25 (another thing)`; const result = importTimes(input, 120); expect(result).toMatchObject([{ segment: [80, 85], description: "thing", category: "chapter" as Category }, { segment: [85, 120], description: "another thing", category: "chapter" as Category }]); }); it("thing 1:20", () => { const input = ` thing 1:20 another thing 1:25`; const result = importTimes(input, 120); expect(result).toMatchObject([{ segment: [80, 85], description: "thing", category: "chapter" as Category }, { segment: [85, 120], description: "another thing", category: "chapter" as Category }]); }); it("thing at 1:20", () => { const input = ` thing at 1:20 another thing at 1:25`; const result = importTimes(input, 120); expect(result).toMatchObject([{ segment: [80, 85], description: "thing", category: "chapter" as Category }, { segment: [85, 120], description: "another thing", category: "chapter" as Category }]); }); it("thing at 1s", () => { const input = ` thing at 1s another thing at 5s`; const result = importTimes(input, 120); expect(result).toMatchObject([{ segment: [1, 5], description: "thing", category: "chapter" as Category }, { segment: [5, 120], description: "another thing", category: "chapter" as Category }]); }); it("thing at 1 second", () => { const input = ` thing at 1 second another thing at 5 seconds`; const result = importTimes(input, 120); expect(result).toMatchObject([{ segment: [1, 5], description: "thing", category: "chapter" as Category }, { segment: [5, 120], description: "another thing", category: "chapter" as Category }]); }); it ("22. 2:04:22 some name", () => { const input = ` 22. 2:04:22 some name 23. 2:04:22.23 some other name`; const result = importTimes(input, 8000); expect(result).toMatchObject([{ segment: [7462, 7462.23], description: "some name", category: "chapter" as Category }, { segment: [7462.23, 8000], description: "some other name", category: "chapter" as Category }]); }); it ("00:00", () => { const input = ` 00:00 Cap 1 00:10 Cap 2 00:12 Cap 3`; const result = importTimes(input, 8000); expect(result).toMatchObject([{ segment: [0, 10], description: "Cap 1", category: "chapter" as Category }, { segment: [10, 12], description: "Cap 2", category: "chapter" as Category }, { segment: [12, 8000], description: "Cap 3", category: "chapter" as Category }]); }); it ("0:00 G¹ (Tangent Continuity)", () => { const input = ` 0:00 G¹ (Tangent Continuity) 0:01 G² (Tangent Continuity)`; const result = importTimes(input, 8000); expect(result).toMatchObject([{ segment: [0, 1], description: "G¹ (Tangent Continuity)", category: "chapter" as Category }, { segment: [1, 8000], description: "G² (Tangent Continuity)", category: "chapter" as Category }]); }); it ("((Some name) 1:20)", () => { const input = ` ((Some name) 1:20) ((Some other name) 1:25)`; const result = importTimes(input, 8000); expect(result).toMatchObject([{ segment: [80, 85], description: "Some name", category: "chapter" as Category }, { segment: [85, 8000], description: "Some other name", category: "chapter" as Category }]); }); }); ================================================ FILE: test/previewBar.test.ts ================================================ /** * @jest-environment jsdom */ import PreviewBar, { PreviewBarSegment } from "../src/js-components/previewBar"; describe("createChapterRenderGroups", () => { let previewBar: PreviewBar; beforeEach(() => { previewBar = new PreviewBar(null, null, null, null, null, null, true); }) it("Two unrelated times", () => { previewBar.videoDuration = 315; const groups = previewBar.createChapterRenderGroups([{ segment: [2, 30], category: "sponsor", actionType: "skip", unsubmitted: false, showLarger: false, description: "" }, { segment: [50, 80], category: "sponsor", actionType: "skip", unsubmitted: false, showLarger: false, description: "" }] as PreviewBarSegment[]); expect(groups).toStrictEqual([{ segment: [0, 2], originalDuration: 0, actionType: null }, { segment: [2, 30], originalDuration: 30 - 2, actionType: "skip" }, { segment: [30, 50], originalDuration: 0, actionType: null }, { segment: [50, 80], originalDuration: 80 - 50, actionType: "skip" }, { segment: [80, 315], originalDuration: 0, actionType: null }]); }); it("Small time in bigger time", () => { previewBar.videoDuration = 315; const groups = previewBar.createChapterRenderGroups([{ segment: [2.52, 30], category: "sponsor", actionType: "skip", unsubmitted: false, showLarger: false, description: "" }, { segment: [20, 25], category: "sponsor", actionType: "skip", unsubmitted: false, showLarger: false, description: "" }] as PreviewBarSegment[]); expect(groups).toStrictEqual([{ segment: [0, 2.52], originalDuration: 0, actionType: null }, { segment: [2.52, 20], originalDuration: 30 - 2.52, actionType: "skip" }, { segment: [20, 25], originalDuration: 25 - 20, actionType: "skip" }, { segment: [25, 30], originalDuration: 30 - 2.52, actionType: "skip" }, { segment: [30, 315], originalDuration: 0, actionType: null }]); }); it("Same start time", () => { previewBar.videoDuration = 315; const groups = previewBar.createChapterRenderGroups([{ segment: [2.52, 30], category: "sponsor", actionType: "skip", unsubmitted: false, showLarger: false, description: "" }, { segment: [2.52, 40], category: "sponsor", actionType: "skip", unsubmitted: false, showLarger: false, description: "" }] as PreviewBarSegment[]); expect(groups).toStrictEqual([{ segment: [0, 2.52], originalDuration: 0, actionType: null }, { segment: [2.52, 30], originalDuration: 30 - 2.52, actionType: "skip" }, { segment: [30, 40], originalDuration: 40 - 2.52, actionType: "skip" }, { segment: [40, 315], originalDuration: 0, actionType: null }]); }); it("Lots of overlapping segments", () => { previewBar.videoDuration = 315.061; const groups = previewBar.createChapterRenderGroups([ { "category": "chapter", "actionType": "chapter", "segment": [ 0, 49.977 ], "locked": 0, "votes": 0, "videoDuration": 315.061, "userID": "b1919787a85cd422af07136a913830eda1364d32e8a9e12104cf5e3bad8f6f45", "description": "Start of video" }, { "category": "sponsor", "actionType": "skip", "segment": [ 2.926, 5 ], "locked": 1, "votes": 2, "videoDuration": 316, "userID": "938444fccfdb7272fd871b7f98c27ea9e5e806681db421bb69452e6a42730c20", "description": "" }, { "category": "chapter", "actionType": "chapter", "segment": [ 14.487, 37.133 ], "locked": 0, "votes": 0, "videoDuration": 315.061, "userID": "b1919787a85cd422af07136a913830eda1364d32e8a9e12104cf5e3bad8f6f45", "description": "Subset of start" }, { "category": "sponsor", "actionType": "skip", "segment": [ 23.450537, 34.486084 ], "locked": 0, "votes": -1, "videoDuration": 315.061, "userID": "938444fccfdb7272fd871b7f98c27ea9e5e806681db421bb69452e6a42730c20", "description": "" }, { "category": "interaction", "actionType": "skip", "segment": [ 50.015343, 56.775314 ], "locked": 0, "votes": 0, "videoDuration": 315.061, "userID": "b2a85e8cdfbf21dd504babbcaca7f751b55a5a2df8179c1a83a121d0f5d56c0e", "description": "" }, { "category": "sponsor", "actionType": "skip", "segment": [ 62.51888, 74.33331 ], "locked": 0, "votes": -1, "videoDuration": 316, "userID": "938444fccfdb7272fd871b7f98c27ea9e5e806681db421bb69452e6a42730c20", "description": "" }, { "category": "sponsor", "actionType": "skip", "segment": [ 88.71328, 96.05933 ], "locked": 0, "votes": 0, "videoDuration": 315.061, "userID": "6c08c092db2b7a31210717cc1f2652e7e97d032e03c82b029a27c81cead1f90c", "description": "" }, { "category": "sponsor", "actionType": "skip", "segment": [ 101.50703, 115.088326 ], "votes": 0, "videoDuration": 315.061, "userID": "2db207ad4b7a535a548fab293f4567bf97373997e67aadb47df8f91b673f6e53", "description": "" }, { "category": "sponsor", "actionType": "skip", "segment": [ 122.211845, 137.42178 ], "locked": 0, "votes": 1, "videoDuration": 0, "userID": "0312cbfa514d9d2dfb737816dc45f52aba7c23f0a3f0911273a6993b2cb57fcc", "description": "" }, { "category": "sponsor", "actionType": "skip", "segment": [ 144.08913, 160.14084 ], "locked": 0, "votes": -1, "videoDuration": 316, "userID": "938444fccfdb7272fd871b7f98c27ea9e5e806681db421bb69452e6a42730c20", "description": "" }, { "category": "sponsor", "actionType": "skip", "segment": [ 164.22084, 170.98082 ], "locked": 0, "votes": 0, "videoDuration": 315.061, "userID": "845c4377060d5801f5324f8e1be1e8373bfd9addcf6c68fc5a3c038111b506a3", "description": "" }, { "category": "sponsor", "actionType": "skip", "segment": [ 180.56674, 189.16516 ], "locked": 0, "votes": -1, "videoDuration": 315.061, "userID": "7c6b015687db7800c05756a0fd226fd8d101f5a1e1bfb1e5d97c440331fd6cb7", "description": "" }, { "category": "sponsor", "actionType": "skip", "segment": [ 204.10468, 211.87865 ], "locked": 0, "votes": 0, "videoDuration": 315.061, "userID": "3472e8ee00b5da957377ae32d59ddd3095c2b634c2c0c970dfabfb81d143699f", "description": "" }, { "category": "sponsor", "actionType": "skip", "segment": [ 214.92064, 222.0186 ], "locked": 0, "votes": 0, "videoDuration": 0, "userID": "62a00dffb344d27de7adf8ea32801c2fc0580087dc8d282837923e4bda6a1745", "description": "" }, { "category": "sponsor", "actionType": "skip", "segment": [ 233.0754, 244.56734 ], "locked": 0, "votes": -1, "videoDuration": 315, "userID": "dcf7fb0a6c071d5a93273ebcbecaee566e0ff98181057a36ed855e9b92bf25ea", "description": "" }, { "category": "sponsor", "actionType": "skip", "segment": [ 260.64053, 269.35938 ], "locked": 0, "votes": 0, "videoDuration": 315.061, "userID": "e0238059ae4e711567af5b08a3afecfe45601c995b0ea2f37ca43f15fca4e298", "description": "" }, { "category": "sponsor", "actionType": "skip", "segment": [ 288.686, 301.96 ], "locked": 0, "votes": 0, "videoDuration": 315.061, "userID": "e0238059ae4e711567af5b08a3afecfe45601c995b0ea2f37ca43f15fca4e298", "description": "" }, { "category": "sponsor", "actionType": "skip", "segment": [ 288.686, 295 ], "locked": 0, "votes": 0, "videoDuration": 315.061, "userID": "e0238059ae4e711567af5b08a3afecfe45601c995b0ea2f37ca43f15fca4e298", "description": "" }] as unknown as PreviewBarSegment[]); expect(groups).toStrictEqual([ { "segment": [ 0, 2.926 ], "originalDuration": 49.977, "actionType": "chapter" }, { "segment": [ 2.926, 5 ], "originalDuration": 2.074, "actionType": "skip" }, { "segment": [ 5, 14.487 ], "originalDuration": 49.977, "actionType": "chapter" }, { "segment": [ 14.487, 23.450537 ], "originalDuration": 22.646, "actionType": "chapter" }, { "segment": [ 23.450537, 34.486084 ], "originalDuration": 11.035546999999998, "actionType": "skip" }, { "segment": [ 34.486084, 37.133 ], "originalDuration": 22.646, "actionType": "chapter" }, { "segment": [ 37.133, 49.977 ], "originalDuration": 49.977, "actionType": "chapter" }, { "segment": [ 49.977, 50.015343 ], "originalDuration": 0, "actionType": null }, { "segment": [ 50.015343, 56.775314 ], "originalDuration": 6.759971, "actionType": "skip" }, { "segment": [ 56.775314, 62.51888 ], "originalDuration": 0, "actionType": null }, { "segment": [ 62.51888, 74.33331 ], "originalDuration": 11.814429999999994, "actionType": "skip" }, { "segment": [ 74.33331, 88.71328 ], "originalDuration": 0, "actionType": null }, { "segment": [ 88.71328, 96.05933 ], "originalDuration": 7.346050000000005, "actionType": "skip" }, { "segment": [ 96.05933, 101.50703 ], "originalDuration": 0, "actionType": null }, { "segment": [ 101.50703, 115.088326 ], "originalDuration": 13.581295999999995, "actionType": "skip" }, { "segment": [ 115.088326, 122.211845 ], "originalDuration": 0, "actionType": null }, { "segment": [ 122.211845, 137.42178 ], "originalDuration": 15.209935000000016, "actionType": "skip" }, { "segment": [ 137.42178, 144.08913 ], "originalDuration": 0, "actionType": null }, { "segment": [ 144.08913, 160.14084 ], "originalDuration": 16.051709999999986, "actionType": "skip" }, { "segment": [ 160.14084, 164.22084 ], "originalDuration": 0, "actionType": null }, { "segment": [ 164.22084, 170.98082 ], "originalDuration": 6.759979999999985, "actionType": "skip" }, { "segment": [ 170.98082, 180.56674 ], "originalDuration": 0, "actionType": null }, { "segment": [ 180.56674, 189.16516 ], "originalDuration": 8.598419999999976, "actionType": "skip" }, { "segment": [ 189.16516, 204.10468 ], "originalDuration": 0, "actionType": null }, { "segment": [ 204.10468, 211.87865 ], "originalDuration": 7.773969999999991, "actionType": "skip" }, { "segment": [ 211.87865, 214.92064 ], "originalDuration": 0, "actionType": null }, { "segment": [ 214.92064, 222.0186 ], "originalDuration": 7.0979600000000005, "actionType": "skip" }, { "segment": [ 222.0186, 233.0754 ], "originalDuration": 0, "actionType": null }, { "segment": [ 233.0754, 244.56734 ], "originalDuration": 11.49194, "actionType": "skip" }, { "segment": [ 244.56734, 260.64053 ], "originalDuration": 0, "actionType": null }, { "segment": [ 260.64053, 269.35938 ], "originalDuration": 8.718849999999975, "actionType": "skip" }, { "segment": [ 269.35938, 288.686 ], "originalDuration": 0, "actionType": null }, { "segment": [ 288.686, 295 ], "originalDuration": 6.314000000000021, "actionType": "skip" }, { "segment": [ 295, 301.96 ], "originalDuration": 13.274000000000001, "actionType": "skip" }, { "segment": [ 301.96, 315.061 ], "originalDuration": 0, "actionType": null } ]); }) it("Multiple overlapping", () => { previewBar.videoDuration = 3615.161; const groups = previewBar.createChapterRenderGroups([{ "segment": [ 160, 2797.323 ], "category": "chooseACategory", "actionType": "skip", "unsubmitted": true, "showLarger": false, },{ "segment": [ 169, 3432.255 ], "category": "chooseACategory", "actionType": "skip", "unsubmitted": true, "showLarger": false, },{ "segment": [ 169, 3412.413 ], "category": "chooseACategory", "actionType": "skip", "unsubmitted": true, "showLarger": false, },{ "segment": [ 1594.92, 1674.286 ], "category": "sponsor", "actionType": "skip", "unsubmitted": false, "showLarger": false, } ] as unknown as PreviewBarSegment[]); expect(groups).toStrictEqual([ { "segment": [ 0, 160 ], "originalDuration": 0, "actionType": null }, { "segment": [ 160, 169 ], "originalDuration": 2637.323, "actionType": "skip" }, { "segment": [ 169, 1594.92 ], "originalDuration": 3243.413, "actionType": "skip" }, { "segment": [ 1594.92, 1674.286 ], "originalDuration": 79.36599999999999, "actionType": "skip" }, { "segment": [ 1674.286, 3412.413 ], "originalDuration": 3243.413, "actionType": "skip" }, { "segment": [ 3412.413, 3432.255 ], "originalDuration": 3263.255, "actionType": "skip" }, { "segment": [ 3432.255, 3615.161 ], "originalDuration": 0, "actionType": null } ]); }); }) ================================================ FILE: test/selenium.test.ts ================================================ import { Builder, By, until, WebDriver, WebElement } from "selenium-webdriver"; import * as Chrome from "selenium-webdriver/chrome"; import * as Path from "path"; import * as fs from "fs"; xtest("Selenium Chrome test", async () => { let driver: WebDriver; try { driver = await setup(); } catch (e) { console.warn("A browser is probably not installed, skipping selenium tests"); console.warn(e); if (String(e).includes("This version of ChromeDriver only supports")) { // Count as failure throw e; } return; } try { await waitForInstall(driver); // This video has no ads await goToVideo(driver, "jNQXAC9IVRw"); await createSegment(driver, "4", "10.33", "0:04.000 to 0:10.330"); await editSegments(driver, 0, "0:04.000", "0:10.330", "5", "13.211", "0:05.000 to 0:13.211", false); await autoskipSegment(driver, 5, 13.211); await setSegmentCategory(driver, 0, 1, false); await setSegmentActionType(driver, 0, 1, false); await editSegments(driver, 0, "0:05.000", "0:13.211", "5", "7.5", "0:05.000 to 0:07.500", false); await muteSkipSegment(driver, 5, 7.5); // Full video await setSegmentActionType(driver, 0, 2, false); await driver.wait(until.elementIsNotVisible(await getDisplayTimeBox(driver, 0))); await toggleWhitelist(driver); await toggleWhitelist(driver); } catch (e) { // Save file incase there is a layout change const source = await driver.getPageSource(); if (!fs.existsSync("./test-results")) fs.mkdirSync("./test-results"); fs.writeFileSync("./test-results/source.html", source); throw e; } finally { await driver.quit(); } }, 100_000); async function setup(): Promise { const options = new Chrome.Options(); options.addArguments("--load-extension=" + Path.join(__dirname, "../dist/")); options.addArguments("--mute-audio"); options.addArguments("--disable-features=PreloadMediaEngagementData, MediaEngagementBypassAutoplayPolicies"); options.addArguments("--headless=new"); options.addArguments("--window-size=1920,1080"); const driver = await new Builder().forBrowser("chrome").setChromeOptions(options).build(); driver.manage().setTimeouts({ implicit: 5000 }); return driver; } async function waitForInstall(driver: WebDriver, startingTab = 0): Promise { // Selenium only knows about the one tab it's on, // so we can't wait for the help page to appear await driver.sleep(3000); const handles = await driver.getAllWindowHandles(); await driver.switchTo().window(handles[startingTab]); } async function goToVideo(driver: WebDriver, videoId: string): Promise { await driver.get("https://www.youtube.com/watch?v=" + videoId); await driver.wait(until.elementIsVisible(await driver.findElement(By.css(".ytd-video-primary-info-renderer, #above-the-fold")))); } async function createSegment(driver: WebDriver, startTime: string, endTime: string, expectedDisplayedTime: string): Promise { const startSegmentButton = await driver.findElement(By.id("startSegmentButton")); const cancelSegmentButton = await driver.findElement(By.id("cancelSegmentButton")); await driver.executeScript("document.querySelector('video').currentTime = " + startTime); await startSegmentButton.click(); await driver.wait(until.elementIsVisible(cancelSegmentButton)); await driver.executeScript("document.querySelector('video').currentTime = " + endTime); await startSegmentButton.click(); await driver.wait(until.elementIsNotVisible(cancelSegmentButton)); const submitButton = await driver.findElement(By.id("submitButton")); await submitButton.click(); const sponsorTimeDisplays = await driver.findElements(By.className("sponsorTimeDisplay")); const sponsorTimeDisplay = sponsorTimeDisplays[sponsorTimeDisplays.length - 1]; await driver.wait(until.elementTextIs(sponsorTimeDisplay, expectedDisplayedTime)); } async function editSegments(driver: WebDriver, index: number, expectedStartTimeBox: string, expectedEndTimeBox: string, startTime: string, endTime: string, expectedDisplayedTime: string, openSubmitBox: boolean): Promise { if (openSubmitBox) { const submitButton = await driver.findElement(By.id("submitButton")); await submitButton.click(); } let editButton = await driver.findElement(By.id("sponsorTimeEditButtonSubmissionNotice" + index)); const sponsorTimeDisplay = await getDisplayTimeBox(driver, index); await sponsorTimeDisplay.click(); // Ensure edit time appears await driver.findElement(By.id("submittingTime0SubmissionNotice" + index)); // Try the edit button too await editButton.click(); await editButton.click(); const startTimeBox = await getStartTimeBox(driver, index, expectedStartTimeBox); await startTimeBox.clear(); await startTimeBox.sendKeys(startTime); const endTimeBox = await getEndTimeBox(driver, index, expectedEndTimeBox); await endTimeBox.clear(); await endTimeBox.sendKeys(endTime); await driver.sleep(1000); editButton = await driver.findElement(By.id("sponsorTimeEditButtonSubmissionNotice" + index)); await editButton.click(); await getDisplayTimeBox(driver, index, expectedDisplayedTime); } async function getStartTimeBox(driver: WebDriver, index: number, expectedStartTimeBox: string): Promise { const startTimeBox = await driver.findElement(By.id("submittingTime0SubmissionNotice" + index)); expect((await startTimeBox.getAttribute("value"))).toBe(expectedStartTimeBox); return startTimeBox; } async function getEndTimeBox(driver: WebDriver, index: number, expectedEndTimeBox: string): Promise { const endTimeBox = await driver.findElement(By.id("submittingTime1SubmissionNotice" + index)); expect((await endTimeBox.getAttribute("value"))).toBe(expectedEndTimeBox); return endTimeBox; } async function getDisplayTimeBox(driver: WebDriver, index: number, expectedDisplayedTime?: string): Promise { const sponsorTimeDisplay = (await driver.findElements(By.className("sponsorTimeDisplay")))[index]; if (expectedDisplayedTime) { driver.wait(until.elementTextIs(sponsorTimeDisplay, expectedDisplayedTime)); } return sponsorTimeDisplay; } async function setSegmentCategory(driver: WebDriver, index: number, categoryIndex: number, openSubmitBox: boolean): Promise { if (openSubmitBox) { const submitButton = await driver.findElement(By.id("submitButton")); await submitButton.click(); } const categorySelection = await driver.findElement(By.css(`#sponsorTimeCategoriesSubmissionNotice${index} > option:nth-child(${categoryIndex + 1})`)); await categorySelection.click(); } async function setSegmentActionType(driver: WebDriver, index: number, actionTypeIndex: number, openSubmitBox: boolean): Promise { if (openSubmitBox) { const submitButton = await driver.findElement(By.id("submitButton")); await submitButton.click(); } const actionTypeSelection = await driver.findElement(By.css(`#sponsorTimeActionTypesSubmissionNotice${index} > option:nth-child(${actionTypeIndex + 1})`)); await actionTypeSelection.click(); } async function autoskipSegment(driver: WebDriver, startTime: number, endTime: number): Promise { const video = await driver.findElement(By.css("video")); await driver.executeScript("document.querySelector('video').currentTime = " + (startTime - 0.5)); await driver.executeScript("document.querySelector('video').play()"); await driver.sleep(1300); expect(parseFloat(await video.getAttribute("currentTime"))).toBeGreaterThan(endTime); await driver.executeScript("document.querySelector('video').pause()"); } async function muteSkipSegment(driver: WebDriver, startTime: number, endTime: number): Promise { const duration = endTime - startTime; const video = await driver.findElement(By.css("video")); await driver.executeScript("document.querySelector('video').currentTime = " + (startTime - 0.5)); await driver.executeScript("document.querySelector('video').play()"); await driver.sleep(1300); expect(await video.getAttribute("muted")).toEqual("true"); await driver.sleep(duration * 1000 + 300); expect(await video.getAttribute("muted")).toBeNull(); // Default is null for some reason await driver.executeScript("document.querySelector('video').pause()"); } async function toggleWhitelist(driver: WebDriver): Promise { const popupButton = await driver.findElement(By.id("infoButton")); const rightControls = await driver.findElement(By.css(".ytp-right-controls")); await driver.actions().move({ origin: rightControls }).perform(); if ((await popupButton.getCssValue("display")) !== "none") { await driver.actions().move({ origin: popupButton }).perform(); await popupButton.click(); } const popupFrame = await driver.findElement(By.css("#sponsorBlockPopupContainer iframe")); await driver.switchTo().frame(popupFrame); const whitelistButton = await driver.findElement(By.id("whitelistButton")); await driver.wait(until.elementIsVisible(whitelistButton)); const whitelistText = await driver.findElement(By.id("whitelistChannel")); const whitelistDisplayed = await whitelistText.isDisplayed(); await whitelistButton.click(); if (whitelistDisplayed) { const unwhitelistText = await driver.findElement(By.id("unwhitelistChannel")); await driver.wait(until.elementIsVisible(unwhitelistText)); } else { await driver.wait(until.elementIsVisible(whitelistText)); } await driver.switchTo().defaultContent(); } ================================================ FILE: test/urlParser.test.ts ================================================ import { getStartTimeFromUrl } from '../src/utils/urlParser'; describe("getStartTimeFromUrl", () => { it("parses with a number", () => { expect(getStartTimeFromUrl("https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=123")).toBe(123); }); it("parses with seconds", () => { expect(getStartTimeFromUrl("https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=123s")).toBe(123); }); it("parses with minutes", () => { expect(getStartTimeFromUrl("https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=23m3s")).toBe(23 * 60 + 3); }); it("parses with hours", () => { expect(getStartTimeFromUrl("https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=1h2m3s")).toBe(1 * 60 * 60 + 2 * 60 + 3); }); it("works with time_continue", () => { expect(getStartTimeFromUrl("https://www.youtube.com/watch?v=dQw4w9WgXcQ&time_continue=123")).toBe(123); }); it("works with no time", () => { expect(getStartTimeFromUrl("https://www.youtube.com/watch?v=dQw4w9WgXcQ")).toBe(0); }); }); ================================================ FILE: tsconfig-production.json ================================================ { "compilerOptions": { "module": "commonjs", "target": "es6", "noImplicitAny": false, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "sourceMap": true, "outDir": "dist/js", "noEmitOnError": false, "typeRoots": [ "node_modules/@types" ], "resolveJsonModule": true, "jsx": "react", "lib": [ "es2019", "dom", "dom.iterable" ] }, "include": [ "src/**/*" ] } ================================================ FILE: tsconfig.json ================================================ { "compilerOptions": { "module": "commonjs", "target": "es6", "noImplicitAny": false, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "sourceMap": true, "outDir": "dist/js", "noEmitOnError": false, "typeRoots": [ "node_modules/@types" ], "resolveJsonModule": true, "jsx": "react", "lib": [ "es2020", "dom", "dom.iterable" ] }, "include": [ "src/**/*" ] } ================================================ FILE: webpack/configDiffPlugin.js ================================================ /* eslint-disable @typescript-eslint/no-var-requires */ const { readFile } = require("fs/promises") let logger; const readFileContents = (name) => readFile(name) .then(data => JSON.parse(data)) // partialDeepEquals from ajayyy/SponsorBlockServer function partialDeepEquals (actual, expected, logger) { // loop over key, value of expected let failed = false; for (const [ key, value ] of Object.entries(expected)) { if (key === "serverAddress" || key === "testingServerAddress" || key === "serverAddressComment" || key === "freeChapterAccess") continue // if value is object, recurse const actualValue = actual?.[key] if (typeof value !== "string" && Array.isArray(value)) { if (!arrayPartialDeepEquals(actualValue, value)) { printActualExpected(key, actualValue, value, logger) failed = true } } else if (typeof value === "object") { if (partialDeepEquals(actualValue, value, logger)) { console.log("obj failed") printActualExpected(key, actualValue, value, logger) failed = true } } else if (actualValue !== value) { printActualExpected(key, actualValue, value, logger) failed = true } } return failed } const arrayPartialDeepEquals = (actual, expected) => expected.every(a => actual?.includes(a)) function printActualExpected(key, actual, expected, logger) { logger.error(`Differing value for: ${key}`) logger.error(`Actual: ${JSON.stringify(actual)}`) logger.error(`Expected: ${JSON.stringify(expected)}`) } class configDiffPlugin { apply(compiler) { // eslint-disable-next-line @typescript-eslint/no-unused-vars compiler.hooks.done.tapAsync("configDiffPlugin", async (stats, callback) => { logger = compiler.getInfrastructureLogger('configDiffPlugin') logger.log('Checking for config.json diff...') // check example const exampleConfig = await readFileContents("./config.json.example") const currentConfig = await readFileContents("./config.json") const difference = partialDeepEquals(currentConfig, exampleConfig, logger) if (difference) { logger.warn("config.json is missing values from config.json.example") } else { logger.info("config.json is not missing any values from config.json.example") } callback() }) } } module.exports = configDiffPlugin; ================================================ FILE: webpack/webpack.common.js ================================================ /* eslint-disable @typescript-eslint/no-var-requires */ // eslint-disable-next-line @typescript-eslint/no-unused-vars const webpack = require("webpack"); const path = require('path'); const CopyPlugin = require('copy-webpack-plugin'); const BuildManifest = require('./webpack.manifest'); const srcDir = '../src/'; const fs = require("fs"); const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin'); const configDiffPlugin = require('./configDiffPlugin'); const edgeLanguages = [ "de", "en", "es", "fr", "pl", "pt_BR", "ro", "ru", "sk", "sv", "tr", "uk", "zh_CN" ] module.exports = env => { const documentScriptBuild = webpack({ entry: { document: path.join(__dirname, srcDir + 'document.ts') }, output: { path: path.join(__dirname, '../dist/js'), }, module: { rules: [ { test: /\.tsx?$/, loader: 'ts-loader', exclude: /node_modules/, resourceQuery: { not: [/raw/] }, options: { // disable type checker for user in fork plugin transpileOnly: true, configFile: env.mode === "production" ? "tsconfig-production.json" : "tsconfig.json" } }, ] }, resolve: { extensions: ['.ts', '.tsx', '.js'] }, plugins: [ // Don't fork TS checker for document script to speed up // new ForkTsCheckerWebpackPlugin() ] }); class DocumentScriptCompiler { currentWatching = null; /** * * @param {webpack.Compiler} compiler */ apply(compiler) { compiler.hooks.beforeCompile.tapAsync({ name: 'DocumentScriptCompiler' }, (compiler, callback) => { if (env.WEBPACK_WATCH) { let first = true; if (!this.currentWatching) { this.currentWatching = documentScriptBuild.watch({}, () => { if (first) { first = false; callback(); } }); } else { callback(); } } else { documentScriptBuild.close(() => { documentScriptBuild.run(() => { callback(); }); }); } }); } } return { entry: { popup: path.join(__dirname, srcDir + 'popup/popup.tsx'), background: path.join(__dirname, srcDir + 'background.ts'), content: path.join(__dirname, srcDir + 'content.ts'), options: path.join(__dirname, srcDir + 'options.ts'), help: path.join(__dirname, srcDir + 'help.ts'), permissions: path.join(__dirname, srcDir + 'permissions.ts'), }, output: { path: path.join(__dirname, '../dist/js'), }, module: { rules: [ { test: /\.tsx?$/, loader: 'ts-loader', exclude: /node_modules/, resourceQuery: { not: [/raw/] }, options: { // disable type checker for user in fork plugin transpileOnly: true, configFile: env.mode === "production" ? "tsconfig-production.json" : "tsconfig.json" } }, { test: /js(\/|\\)document\.js$/, type: 'asset/source' } ] }, resolve: { extensions: ['.ts', '.tsx', '.js'], symlinks: false }, plugins: [ // Prehook to start building document script before normal build new DocumentScriptCompiler(), // fork TS checker new ForkTsCheckerWebpackPlugin(), // exclude locale files in moment new CopyPlugin({ patterns: [ { from: '.', to: '../', globOptions: { ignore: ['manifest.json', '**/.git/**', '**/crowdin.yml'], }, context: './public', filter: async (path) => { if (path.match(/(\/|\\)_locales(\/|\\).+/)) { if (env.browser.toLowerCase() === "edge" && !edgeLanguages.includes(path.match(/(?<=\/_locales\/)[^/]+(?=\/[^/]+$)/)[0])) { return false; } const data = await fs.promises.readFile(path); const parsed = JSON.parse(data.toString()); return parsed.fullName && parsed.Description; } else { return true; } }, transform(content, path) { if (path.match(/(\/|\\)_locales(\/|\\).+/)) { const parsed = JSON.parse(content.toString()); if (env.browser.toLowerCase() === "safari") { parsed.fullName.message = parsed.fullName.message.match(/^.+(?= [-–])/)?.[0] || parsed.fullName.message; if (parsed.fullName.message.length > 50) { parsed.fullName.message = parsed.fullName.message.slice(0, 47) + "..."; } parsed.Description.message = parsed.Description.message.match(/^.+(?=\. )/)?.[0] || parsed.Description.message; if (parsed.Description.message.length > 80) { parsed.Description.message = parsed.Description.message.slice(0, 77) + "..."; } } if (env.browser.toLowerCase() === "edge") { parsed.Description.message = parsed.Description.message.match(/^.+(?=\. )/)?.[0] || parsed.Description.message; if (parsed.Description.message.length > 132) { parsed.Description.message = parsed.Description.message.slice(0, 129) + "..."; } } return Buffer.from(JSON.stringify(parsed)); } return content; } } ] }), new BuildManifest({ browser: env.browser, pretty: env.mode === "production", stream: env.stream, autoupdate: env.autoupdate, }), new configDiffPlugin() ], performance: { hints: false, maxEntrypointSize: 512000, maxAssetSize: 512000 } }; }; ================================================ FILE: webpack/webpack.dev.js ================================================ /* eslint-disable @typescript-eslint/no-var-requires */ const { merge } = require('webpack-merge'); const common = require('./webpack.common.js'); module.exports = env => merge(common(env), { devtool: 'inline-source-map', mode: 'development' }); ================================================ FILE: webpack/webpack.manifest.js ================================================ /* eslint-disable @typescript-eslint/no-var-requires */ // eslint-disable-next-line @typescript-eslint/no-unused-vars const webpack = require("webpack"); const path = require('path'); const { validate } = require('schema-utils'); const fs = require('fs'); const manifest = require("../manifest/manifest.json"); const firefoxManifestExtra = require("../manifest/firefox-manifest-extra.json"); const chromeManifestExtra = require("../manifest/chrome-manifest-extra.json"); const safariManifestExtra = require("../manifest/safari-manifest-extra.json"); const betaManifestExtra = require("../manifest/beta-manifest-extra.json"); const firefoxBetaManifestExtra = require("../manifest/firefox-beta-manifest-extra.json"); const manifestV2ManifestExtra = require("../manifest/manifest-v2-extra.json"); // schema for options object const schema = { type: 'object', properties: { browser: { type: 'string' }, pretty: { type: 'boolean' }, stream: { type: 'string' }, autoupdate: { type: 'boolean', } } }; class BuildManifest { constructor (options = {}) { validate(schema, options, "Build Manifest Plugin"); this.options = options; } apply() { const distFolder = path.resolve(__dirname, "../dist/"); const distManifestFile = path.resolve(distFolder, "manifest.json"); const [owner, repo_name] = (process.env.GITHUB_REPOSITORY ?? "ajayyy/SponsorBlock").split("/"); // Add missing manifest elements if (this.options.browser.toLowerCase() === "firefox") { mergeObjects(manifest, manifestV2ManifestExtra); mergeObjects(manifest, firefoxManifestExtra); } else if (this.options.browser.toLowerCase() === "chrome" || this.options.browser.toLowerCase() === "chromium" || this.options.browser.toLowerCase() === "edge") { mergeObjects(manifest, chromeManifestExtra); } else if (this.options.browser.toLowerCase() === "safari") { mergeObjects(manifest, manifestV2ManifestExtra); mergeObjects(manifest, safariManifestExtra); manifest.optional_permissions = manifest.optional_permissions.filter((a) => a !== "*://*/*"); } if (this.options.stream === "beta") { mergeObjects(manifest, betaManifestExtra); if (this.options.browser.toLowerCase() === "firefox") { mergeObjects(manifest, firefoxBetaManifestExtra); } } if (this.options.autoupdate === true && this.options.browser.toLowerCase() === "firefox") { manifest.browser_specific_settings.gecko.update_url = `https://${owner.toLowerCase()}.github.io/${repo_name}/updates.json`; } let result = JSON.stringify(manifest); if (this.options.pretty) result = JSON.stringify(manifest, null, 2); fs.mkdirSync(distFolder, {recursive: true}); fs.writeFileSync(distManifestFile, result); } } function mergeObjects(object1, object2) { for (const key in object2) { if (key in object1) { if (Array.isArray(object1[key])) { object1[key] = object1[key].concat(object2[key]); } else if (typeof object1[key] == 'object') { mergeObjects(object1[key], object2[key]); } else { object1[key] = object2[key]; } } else { object1[key] = object2[key]; } } } module.exports = BuildManifest; ================================================ FILE: webpack/webpack.prod.js ================================================ /* eslint-disable @typescript-eslint/no-var-requires */ const { SourceMapDevToolPlugin } = require('webpack'); const { merge } = require('webpack-merge'); const common = require('./webpack.common.js'); async function createGHPSourceMapURL(env) { const manifest = require("../manifest/manifest.json"); const version = manifest.version; const [owner, repo_name] = (process.env.GITHUB_REPOSITORY ?? "ajayyy/SponsorBlock").split("/"); const ghpUrl = `https://${owner.toLowerCase()}.github.io/${repo_name}/${env.browser}${env.stream === "beta" ? "-beta" : ""}/${version}/`; // make a request to the url and check if we got redirected // firefox doesn't seem to like getting redirected on a source map request try { const resp = await fetch(ghpUrl); return resp.url; } catch { return ghpUrl; } } module.exports = async env => { let mode = "production"; env.mode = mode; return merge(common(env), { mode, ...(env.ghpSourceMaps ? { devtool: false, plugins: [new SourceMapDevToolPlugin({ publicPath: await createGHPSourceMapURL(env), filename: '[file].map[query]', })], } : { devtool: "source-map", } ), }); };