Compare commits

..

No commits in common. "master" and "v5.5.9" have entirely different histories.

611 changed files with 25232 additions and 28041 deletions

42
.eslintrc Normal file
View file

@ -0,0 +1,42 @@
{
"globals": {
"launchQueue": "readonly",
"FileSystemHandle": "readonly",
"FileSystemFileHandle": "readonly",
"FileSystemDirectoryHandle": "readonly",
"FileSystemWritableFileStream": "readonly",
"ClipboardItem": "readonly",
"queryLocalFonts": "readonly"
},
"env": {
"es2022": true,
"browser": true,
"worker": true,
"node": true,
"serviceworker": true
},
"rules": {
"n/no-callback-literal": 0
},
"extends": ["plugin:svelte/recommended", "standard"],
"plugins": ["svelte"],
"parser": "@typescript-eslint/parser",
"ignorePatterns": ["*.min.*", "*.build.*"],
"overrides": [
{
"files": ["*.svelte"],
"parser": "svelte-eslint-parser",
"rules": {
"svelte/indent": ["error", { "indent": 2, "indentScript": true }],
"no-self-assign": 0,
"a11y-media-has-caption": 0,
"no-use-before-define": 0,
"svelte/html-self-closing": ["error", "always"],
"svelte/html-closing-bracket-spacing": ["error", { "startTag": "never", "endTag": "never", "selfClosingTag": "always" }],
"svelte/html-quotes": [ "error", { "prefer": "single", "dynamic": { "quoted": false, "avoidInvalidUnquotedInHTML": false } }],
"svelte/shorthand-attribute": ["warn", { "prefer": "always" }],
"svelte/spaced-html-comment": ["error", "always"]
}
}
]
}

View file

@ -12,17 +12,17 @@ body:
options:
- label: >-
I have searched the [issue
tracker](https://github.com/hayase-app/ui/issues) for a bug report
tracker](https://github.com/ThaUnknown/miru/issues) for a bug report
that matches the one I want to file, without success.
required: true
- label: >-
I have searched the [frequently asked
questions](https://hayase.watch/faq) for a solution to my problem,
questions](https://github.com/ThaUnknown/miru/blob/master/docs/faq.md)
for a solution that fixes this problem, without success.
required: true
- label: >-
I have checked that I'm using the [latest
stable](https://github.com/hayase-app/ui/releases/latest) version
stable](https://github.com/ThaUnknown/miru/releases/latest) version
of the app.
required: true
- type: input

View file

@ -12,17 +12,17 @@ body:
options:
- label: >-
I have searched the [issue
tracker](https://github.com/hayase-app/ui/issues) for a bug report
tracker](https://github.com/ThaUnknown/miru/issues) for a bug report
that matches the one I want to file, without success.
required: true
- label: >-
I have searched the [features
list](https://hayase.watch/features) for this feature,
list](https://github.com/ThaUnknown/miru#features) for this feature,
and I couldn't find it.
required: true
- label: >-
I have checked that I'm using the [latest
stable](https://github.com/hayase-app/ui/releases/latest) version
stable](https://github.com/ThaUnknown/miru/releases/latest) version
of the app.
required: true
- type: textarea

View file

@ -1,39 +0,0 @@
name: Check
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
check:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
name: Install pnpm
- name: Install Node.js
uses: actions/setup-node@v4
with:
node-version: 22.19
cache: 'pnpm'
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Sync
run: pnpm run sync
- name: Lint
run: pnpm run lint
- name: Check GQL
run: pnpm run gql:check
- name: Check Svelte and TypeScript
run: pnpm run check

50
.github/workflows/main.yml vendored Normal file
View file

@ -0,0 +1,50 @@
name: Build/release
on:
push:
branches:
- 'main'
- 'master'
jobs:
release:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [windows-latest, ubuntu-latest, macos-latest]
steps:
- name: Install Setuptools for Python
if: matrix.os == 'macos-latest'
run: pip3 install setuptools --break-system-packages
- name: Check out Git repository
uses: actions/checkout@v3
with:
submodules: 'true'
token: ${{ secrets.MIRU_SUBMODULES_PAT }}
- name: Setup PNPM
uses: pnpm/action-setup@v4
with:
version: 8.6.3
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'pnpm'
- name: Install dependencies
run: cd electron && pnpm install --frozen-lockfile
- name: Build and Publish
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# CSC_LINK: ${{ secrets.APPLE_SIGNING_CERT }}
# API_KEY: ${{ secrets.APPLE_API_KEY }}
# APPLE_API_KEY: apple.p8
# APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
# APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
run: cd electron && npm run publish

14
.github/workflows/winget.yml vendored Normal file
View file

@ -0,0 +1,14 @@
name: Publish to WinGet
on:
release:
types: [released]
jobs:
publish:
runs-on: windows-latest
steps:
- name: WinGet Releaser
uses: vedantmgoyal2009/winget-releaser@v2
with:
identifier: ThaUnknown.Miru
installers-regex: '\installer.exe$'
token: ${{ secrets.WINGET_TOKEN }}

35
.gitignore vendored
View file

@ -1,26 +1,17 @@
node_modules
# Output
.output
.vercel
/.svelte-kit
/build
# OS
# OS Specific
.DS_Store
Thumbs.db
# Env
.env
.env.*
!.env.example
!.env.test
ideas.todo
# Build output
**/dist/
**/build/
# Vite
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
# Dependencies
node_modules
**/*.der
**/*.pem
**/*.keystore
**/*.jks
**/node_modules
**/git_modules/
*.mkv
*.webm
*src/routes/test/**
package-lock.json

6
.gitmodules vendored Normal file
View file

@ -0,0 +1,6 @@
[submodule "capacitor/git_modules/nodejs-mobile"]
path = capacitor/git_modules/nodejs-mobile
url = https://github.com/nodejs-mobile/nodejs-mobile
[submodule "electron/electron-dist"]
path = electron/electron-dist
url = https://github.com/hayase-app/electron-dist

2
.npmrc
View file

@ -1 +1 @@
engine-strict=true
node-linker=hoisted

View file

@ -1,13 +0,0 @@
{
"recommendations": [
"usernamehw.errorlens",
"dbaeumer.vscode-eslint",
"GraphQL.vscode-graphql-syntax",
"bierner.comment-tagged-templates",
"YoavBls.pretty-ts-errors",
"svelte.svelte-vscode", // 109.5.2 or older NOT NEWER
"ardenivanov.svelte-intellisense",
"Gruntfuggly.todo-tree",
"bradlc.vscode-tailwindcss"
]
}

39
.vscode/launch.json vendored
View file

@ -1,39 +0,0 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch Chromium",
"port": 8412,
"request": "launch",
"type": "chrome",
"url": "http://localhost:7344/",
"webRoot": "${workspaceFolder}/src",
"timeout": 60000,
"presentation": {
"hidden": true
}
},
{
"name": "Debug Renderer Process",
"port": 9222,
"request": "attach",
"type": "chrome",
"webRoot": "${workspaceFolder}/src",
"timeout": 60000,
"presentation": {
"hidden": false
}
}
],
"compounds": [
{
"name": "Attach",
"configurations": [
"Launch Chromium"
],
"presentation": {
"order": 1
}
}
]
}

43
.vscode/settings.json vendored
View file

@ -1,43 +1,4 @@
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "always"
},
"editor.formatOnSave": true,
"editor.linkedEditing": true,
"editor.tabSize": 2,
"eslint.format.enable": true,
"eslint.probe": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact",
"svelte",
"html"
],
"eslint.useESLintClass": true,
"eslint.useFlatConfig": true,
"eslint.validate": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact",
"svelte",
"html"
],
"javascript.preferences.importModuleSpecifierEnding": "minimal",
"javascript.preferences.quoteStyle": "single",
"javascript.suggest.autoImports": true,
"javascript.updateImportsOnFileMove.enabled": "always",
"javascript.validate.enable": true,
"extensions.ignoreRecommendations": false,
"svelte.plugin.svelte.format.config.singleQuote": true,
"svelte.plugin.svelte.format.enable": false,
"typescript.enablePromptUseWorkspaceTsdk": true,
"typescript.experimental.expandableHover": true,
"typescript.preferences.importModuleSpecifierEnding": "minimal",
"typescript.preferences.quoteStyle": "single",
"typescript.suggest.autoImports": true,
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.updateImportsOnFileMove.enabled": "always",
"typescript.validate.enable": true
"npm.exclude": "**/git_modules/**",
"java.configuration.updateBuildConfiguration": "interactive"
}

View file

@ -1,166 +1,25 @@
# Contributing Guidelines
*Pull requests, bug reports, and all other forms of contribution are welcomed and highly encouraged!* :octocat:
### Contents
* [Opening an Issue](#inbox_tray-opening-an-issue)
* [Feature Requests](#love_letter-feature-requests)
* [Triaging Issues](#mag-triaging-issues)
* [Submitting Pull Requests](#repeat-submitting-pull-requests)
* [Writing Commit Messages](#memo-writing-commit-messages)
* [Code Review](#white_check_mark-code-review)
* [Coding Style](#nail_care-coding-style)
* [Certificate of Origin](#medal_sports-certificate-of-origin)
* [Credits](#pray-credits)
> **This guide serves to set clear expectations for everyone involved with the project so that we can improve it together while also creating a welcoming space for everyone to participate. Following these guidelines will help ensure a positive experience for contributors and maintainers.**
## :inbox\_tray: Opening an Issue
Before [creating an issue](https://help.github.com/en/github/managing-your-work-on-github/creating-an-issue), check if you are using the latest version of the project. If you are not up-to-date, see if updating fixes your issue first.
### :lock: Reporting Security Issues
Review our [Security Policy](./SECURITY.md). **Do not** file a public issue for security vulnerabilities.
### :beetle: Bug Reports and Other Issues
A great way to contribute to the project is to send a detailed issue when you encounter a problem. We always appreciate a well-written, thorough bug report. :v:
In short, since you are most likely a developer, **provide a ticket that you would like to receive**.
* **Review the documentation and [Support Guide](./SUPPORT.md)** before opening a new issue.
* **Do not open a duplicate issue!** Search through existing issues to see if your issue has previously been reported. If your issue exists, comment with any additional information you have. You may simply note "I have this problem too", which helps prioritize the most common problems and requests.
* **Prefer using [reactions](https://github.blog/2016-03-10-add-reactions-to-pull-requests-issues-and-comments/)**, not comments, if you simply want to "+1" an existing issue.
* **Fully complete the provided issue template.** The bug report template requests all the information we need to quickly and efficiently address your issue. Be clear, concise, and descriptive. Provide as much information as you can, including steps to reproduce, stack traces, compiler errors, library versions, OS versions, and screenshots (if applicable).
* **Use [GitHub-flavored Markdown](https://help.github.com/en/github/writing-on-github/basic-writing-and-formatting-syntax).** Especially put code blocks and console outputs in backticks (\`\`\`). This improves readability.
## :love\_letter: Feature Requests
Feature requests are welcome! While we will consider all requests, we cannot guarantee your request will be accepted. We want to avoid [feature creep](https://en.wikipedia.org/wiki/Feature_creep). Your idea may be great, but also out-of-scope for the project. If accepted, we cannot make any commitments regarding the timeline for implementation and release. However, you are welcome to submit a pull request to help!
* **Do not open a duplicate feature request.** Search for existing feature requests first. If you find your feature (or one very similar) previously requested, comment on that issue.
* **Fully complete the provided issue template.** The feature request template asks for all necessary information for us to begin a productive conversation.
* Be precise about the proposed outcome of the feature and how it relates to existing features. Include implementation details if possible.
## :mag: Triaging Issues
You can triage issues which may include reproducing bug reports or asking for additional information, such as version numbers or reproduction instructions. Any help you can provide to quickly resolve an issue is very much appreciated!
## :repeat: Submitting Pull Requests
We **love** pull requests! Before [forking the repo](https://help.github.com/en/github/getting-started-with-github/fork-a-repo) and [creating a pull request](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/proposing-changes-to-your-work-with-pull-requests) for non-trivial changes, it is usually best to first open an issue to discuss the changes, or discuss your intended approach for solving the problem in the comments for an existing issue.
For most contributions, after your first pull request is accepted and merged, you will be [invited to the project](https://help.github.com/en/github/setting-up-and-managing-your-github-user-account/inviting-collaborators-to-a-personal-repository) and given **push access**. :tada:
*Note: All contributions will be licensed under the project's license.*
* **Smaller is better.** Submit **one** pull request per bug fix or feature. A pull request should contain isolated changes pertaining to a single bug fix or feature implementation. **Do not** refactor or reformat code that is unrelated to your change. It is better to **submit many small pull requests** rather than a single large one. Enormous pull requests will take enormous amounts of time to review, or may be rejected altogether.
* **Coordinate bigger changes.** For large and non-trivial changes, open an issue to discuss a strategy with the maintainers. Otherwise, you risk doing a lot of work for nothing!
* **Prioritize understanding over cleverness.** Write code clearly and concisely. Remember that source code usually gets written once and read often. Ensure the code is clear to the reader. The purpose and logic should be obvious to a reasonably skilled developer, otherwise you should add a comment that explains it.
* **Follow existing coding style and conventions.** Keep your code consistent with the style, formatting, and conventions in the rest of the code base. When possible, these will be enforced with a linter. Consistency makes it easier to review and modify in the future.
* **Include test coverage.** Add unit tests or UI tests when possible. Follow existing patterns for implementing tests.
* **Update the example project** if one exists to exercise any new functionality you have added.
* **Add documentation.** Document your changes with code doc comments or in existing guides.
* **Use the repo's default branch.** Branch from and [submit your pull request](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request-from-a-fork) to the repo's default branch. Usually this is `main`, but it could be `dev`, `develop`, or `master`.
* **[Resolve any merge conflicts](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/resolving-a-merge-conflict-on-github)** that occur.
* **Promptly address any CI failures**. If your pull request fails to build or pass tests, please push another commit to fix it.
* When writing comments, use properly constructed sentences, including punctuation.
* Use spaces, not tabs.
## :memo: Writing Commit Messages
Please [write a great commit message](https://chris.beams.io/posts/git-commit/).
1. Separate subject from body with a blank line
2. Limit the subject line to 50 characters
3. Capitalize the subject line
4. Do not end the subject line with a period
5. Use the imperative mood in the subject line (example: "Fix networking issue")
6. Wrap the body at about 72 characters
7. Use the body to explain **why**, *not what and how* (the code shows that!)
8. If applicable, prefix the title with the relevant component name in a semantic way. (examples: "fix: typo", "feat: add avatar")
```
docs: Short summary of changes in 50 chars or less
Add a more detailed explanation here, if necessary. Possibly give
some background about the issue being fixed, etc. The body of the
commit message can be several paragraphs. Further paragraphs come
after blank lines and please do proper word-wrap.
Wrap it to about 72 characters or so. In some contexts,
the first line is treated as the subject of the commit and the
rest of the text as the body. The blank line separating the summary
from the body is critical (unless you omit the body entirely);
various tools like `log`, `shortlog` and `rebase` can get confused
if you run the two together.
Explain the problem that this commit is solving. Focus on why you
are making this change as opposed to how or what. The code explains
how or what. Reviewers and your future self can read the patch,
but might not understand why a particular solution was implemented.
Are there side effects or other unintuitive consequences of this
change? Here's the place to explain them.
- Bullet points are okay, too
- A hyphen or asterisk should be used for the bullet, preceded
by a single space, with blank lines in between
Note the fixed or relevant GitHub issues at the end:
Resolves: #123
See also: #456, #789
```
## :white\_check\_mark: Code Review
* **Review the code, not the author.** Look for and suggest improvements without disparaging or insulting the author. Provide actionable feedback and explain your reasoning.
* **You are not your code.** When your code is critiqued, questioned, or constructively criticized, remember that you are not your code. Do not take code review personally.
* **Always do your best.** No one writes bugs on purpose. Do your best, and learn from your mistakes.
* Kindly note any violations to the guidelines specified in this document.
## :nail\_care: Coding Style
Consistency is the most important. Following the existing style, formatting, and naming conventions of the file you are modifying and of the overall project. Failure to do so will result in a prolonged review process that has to focus on updating the superficial aspects of your code, rather than improving its functionality and performance.
For example, if all private properties are prefixed with an underscore `_`, then new ones you add should be prefixed in the same way. Or, if methods are named using camelcase, like `thisIsMyNewMethod`, then do not diverge from that by writing `this_is_my_new_method`. You get the idea. If in doubt, please ask or search the codebase for something similar.
When possible, style and format will be enforced with a linter.
## :medal\_sports: Certificate of Origin
*Developer's Certificate of Origin 1.1*
By making a contribution to this project, I certify that:
> 1. The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or
> 2. The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or
> 3. The contribution was provided directly to me by some other person who certified (1), (2) or (3) and I have not modified it.
> 4. I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the source license(s) involved.
(a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
## [No Brown M\&M's](https://en.wikipedia.org/wiki/Van_Halen#Contract_riders)
(b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
If you are reading this, bravo dear user and (hopefully) contributor for making it this far! You are awesome. :100:
(c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
(d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
```

699
LICENSE
View file

@ -1,47 +1,674 @@
Business Source License 1.1
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Terms
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
The Licensor hereby grants you the right to copy, modify, create derivative
works, redistribute, and make non-production use of the Licensed Work. The
Licensor may make an Additional Use Grant, above, permitting limited
production use.
Preamble
Effective on the Change Date, or the fourth anniversary of the first publicly
available distribution of a specific version of the Licensed Work under this
License, whichever comes first, the Licensor hereby grants you rights under
the terms of the Change License, and the rights granted in the paragraph
above terminate.
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
If your use of the Licensed Work does not comply with the requirements
currently in effect as described in this License, you must purchase a
commercial license from the Licensor, its affiliated entities, or authorized
resellers, or you must refrain from using the Licensed Work.
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.
All copies of the original and modified Licensed Work, and derivative works
of the Licensed Work, are subject to this License. This License applies
separately for each version of the Licensed Work and the Change Date may vary
for each version of the Licensed Work released by Licensor.
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.
You must conspicuously display this License on each original or modified copy
of the Licensed Work. If you receive the Licensed Work in original or
modified form from a third party, the terms and conditions set forth in this
License apply to your use of that work.
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.
Any use of the Licensed Work in violation of this License will automatically
terminate your rights under this License for the current and all other
versions of the Licensed Work.
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.
This License does not grant you any right in any trademark or logo of
Licensor or its affiliates (provided that you may use a trademark or logo of
Licensor as expressly required by this License).
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.
TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
TITLE.
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.
Change Date: 2029-04-01
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.
On the date above, in accordance with the Business Source License, use of this software will be governed by the open source license GPL-3.0.
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/why-not-lgpl.html>.

228
README.md
View file

@ -1,158 +1,124 @@
<p align="center">
<a href="https://github.com/hayase-app/ui">
<img src="./static/logo_white.svg" width="300">
<a href="https://github.com/ThaUnknown/miru">
<img src="./web/static/logo_filled.svg" width="200">
</a>
</p>
<h1 align="center"><b>Hayase</b></h1>
<h1 align="center"><b>Miru</b></h1>
<h4 align="center"><b>Stream anime torrents instantly, real-time with no waiting for downloads to finish! 🍿</b></h4>
<h4 align="center"><b>Stream anime torrents, real-time with no waiting for downloads</b></h4>
<p align="center">
<a href="https://hayase.watch/#about">About</a>
<a href="https://hayase.watch/features/">Features</a>
<a href="https://hayase.watch/faq/">Frequently Asked Questions</a>
<a href="https://hayase.watch/download/">Download</a>
<a href="https://miru.watch/#about">About</a>
<a href="https://miru.watch/features/">Features</a>
<a href="https://miru.watch/faq/">Frequently Asked Questions</a>
<a href="#building-and-development">Building and Development</a>
<a href="https://miru.watch/download/">Download</a>
</p>
<p align="center">
<img src="./docs/out.gif" alt="showcase"><br>
<a href="https://discord.gg/Z87Nh7c4Ac">
<img src="https://img.shields.io/discord/953341991134064651?style=flat-square" alt="chat">
</a>
<a href="https://hayase.watch/download/">
<img alt="Download" src="https://img.shields.io/github/downloads/hayase-app/ui/total?style=flat-square">
<a href="https://miru.watch/download/">
<img alt="GitHub all releases" src="https://img.shields.io/github/downloads/ThaUnknown/miru/total?style=flat-square">
</a>
</p>
https://github.com/user-attachments/assets/bbbe2966-b773-4ebb-9d69-08248ae77ae4
## **About**
A pure JS BitTorrent streaming environment, with a built-in list manager. Imagine qBit + Taiga + MPV, all in a single package, but streamed real-time. Completly ad free with no tracking/data collection.
<p align="center">Formerly known as Miru.</p>
This app is meant to feel look, work and perform like a streaming website/app, while providing all the advantages of torrenting, like file downloads, higher download speeds, better video quality and quicker releases.
## ✨ About
Unlike qBit's sequential, seeking into undownloaded data will prioritise downloading that data, instead of flat out closing MPV.
## **Features**
### **Anime:**
- full AniList integration
- filter anime by name, genre, season, year, format, status
- view anime on your planning and watching list
- add and remove anime from your planning list
- automatically mark episodes as complete as you watch them
- view trailers/previews for anime
- score anime
- view anime relations
- automatically find torrents for desired episodes
- automatically detect what anime a torrent is
- view latest releases on any custom RSS
- airing schedule
- find anime by image [just paste an image into the app]
### **Video:**
- full subtitle support
- support for softcoded subtitles
- support for external subtitle files
- support for VTT, SSA, ASS, SUB, TXT subtitles
- subtitle display in PiP
- keybinds for all functions:
- **S** - seek forwards 90 seconds [skip opening]
- **R** - seek backwards 90 seconds
- **→** - seek forwards 2 seconds
- **←** - seek backwards 2 seconds
- **↑** - increase volume
- **↓** - decrease volume
- **M** - mute volume
- **C** - cycle through subtitle tracks
- **N** - play next episode [if available]
- **B** - play last episode [if available]
- **F** - toggle fullscreen
- **P** - toggle picture in picture
- **[** - increase playback speed
- **]** - decrease playback speed
- **\\** - reset playback speed to 1
- **I** - view video stats for nerds
- **`** - open keybinds UI
- editable keybinds **`** allows drag dropping any key
- miniplayer
- media session display
- media keys support
- Discord rich pressence
- preview thumbnails
- pause on lost focus
- autoplay next episode
- multi-audio support
- torrent download progress on the seek bar
### **Torrent:**
- select downloads folder
- specify download/upload speeds
- support for most popular BEP's
- support for custom torrent RSS feeds for latest releases
- change what resolution to find torrents in
- stream real-time with no waiting for downloads
- support for custom extensions for custom sources and trackers
**Hayase** is a modern app for streaming anime torrents in real-time, with no waiting for downloads to finish.
## **Linux Installation**
It is meant to feel look, work and perform like a premium streaming service, but with all the benefits of both streaming and torrenting, like file downloads, higher download speeds, better video quality, instant access to new releases, and features you wont find on typical streaming sites.
### Arch
## 🌟 Highlights
If you use paru:
```bash
paru -S miru-bin
```
* 📚 **Anime list integration:** Sync with AniList, Kitsu, ~~MAL~~, or use local storage.
* ⚡ **Instant torrent streaming:** Watch as you download, with extension support for custom sources.
* 📴 **Offline viewing:** Enjoy already-downloaded torrents anytime.
* 🎬 **Advanced video player:** Full support for all subtitle formats, softcoded and external tracks, and more.
* 👥 **Social features:** Connect with friends, join discussions, and watch together.
If you use yay:
***
```bash
yay -S miru-bin
```
## 🏆 Features
### Debian/Ubuntu
### 🎞️ Anime Management
* Effortlessly manage your anime list with support for AniList, Kitsu, ~~MAL~~, and local storage.
* Automatically track watched episodes.
* See what youre behind on, and discover sequels youve missed.
* Keep up to date and browse upcoming episodes with airing calendars.
* Edit entries (score, progress, status, favorite, etc.) even while offline.
* Search by image, name, genre, year, season, and more.
* View trailers, OP/ED themes, and detailed episode lists with thumbnails, descriptions and filler indicators.
<p align="center">
<img src='https://raw.githubusercontent.com/hayase-app/website/main/static/viewanime.webp' width='400px'></img>
</p>
### 🤝 Social & Community
* Instantly see which friends are following an anime or episode.
* See friends profiles and watch progress in the episodes list.
* Track your friends watch progress in real time.
* Join episode discussions and forums, even offline.
* Global app chat.
* Discord rich pressence.
* Host or join Watch Together lobbies with synced playback and chat.
### 🎥 Video Experience
* Full subtitle support.
* Softcoded, external and manually added subtitles.
* VTT, SSA, ASS, SUB, TXT formats.
* Subtitle display in PiP.
* Override default dialog styles.
* Override default fonts for Asian languages \[fix for bad torrents].
* Picture In Picture.
* PiP on lost visiblity.
* Pause on lost visibility.
* Specify preferred language for video and subtitle tracks.
* Remove video compression artifacts.
* Miniplayer.
* Media Session display.
* Media Keys support.
* Discord rich pressence.
* Seek and preview thumbnails.
* Autoplay next episode.
* Skip intro/outro, manually or automatically.
* Skip filler episodes automatically.
* Change playback rate.
* Browse playlist.
* Multi-track support for video, audio and subtitles.
* Editable keybinds for all player functions.
* Exponential volume \[better control at lower volumes].
* External player support.
<p align="center">
<img src='https://raw.githubusercontent.com/hayase-app/website/main/static/videoplayer.webp' width='400px'></img>
</p>
### 🧲 Torrents
* Stream torrents instantly, no waiting for full downloads.
* Download only what you need for playback.
* Choose your downloads folder and set speed/connection limits.
* Support for custom extensions, sources, and trackers.
* Specify download/upload speeds, ports and connections.
* Support for most popular BEP's.
* Persist torrents, cache progress, and rescan instantly.
* View detailed torrent and peer info.
* Batch downloads.
<p align="center">
<img src='https://raw.githubusercontent.com/hayase-app/website/main/static/modal.webp' width='400px'></img>
</p>
### ⚙️ Performance & Security
* Highly secure.
* Operates on a Zero Trust model.
* Protects data integrity and settings from external attacks.
* Protects from attacks via malicious torrent extensions.
* Uses up to date best security practices for native apps.
* Insanely performant.
* Fully hardware/GPU accelerated.
* GPU based shaders, animations and paints.
* Very low resource utilisation.
* Only loads code as required by user navigation.
* Unloads code not in use.
* Doesn't render unnecessary UI updates.
* Disables rendering when not visible.
* Doesn't render any UI when immersed in fullscreen video.
* Minimise to tray.
* In-app changelog.
* Custom themes.
<p align="center">
<img src='https://raw.githubusercontent.com/hayase-app/website/main/static/simple.webp' width='400px'></img>
</p>
- Download the `linux-Miru-version.deb` from the [releases](https://github.com/ThaUnknown/miru/releases/latest) page.
- Install the deb file with package manager.
```bash
apt install linux-Miru-*.deb
```
## **Building and Development**
Requires `Node 20` or above and `pnpm`. VSCode is recommended.
*good luck*
```js
pnpm i // to install
pnpm run dev // to develop
pnpm run build // to build
pnpm run sync && pnpm run lint && pnpm run gql:check && pnpm run check // to test
```
***
<h2 align="center">
<b>Enjoy streaming anime the way it should be! 🍿</b>
</h2>
Dependencies:
- Node 16 or above
- PNPM
- Docker
- Android Debug Bridge
- Java 18 or above [probably?]
- maybe others... have fun.

View file

@ -1,13 +0,0 @@
# Security Policy
If you discover a security issue, please bring it to our attention right away!
## Reporting a Vulnerability
Please **DO NOT** file a public issue to report a security vulberability, instead send your report privately to **casistaken@gmail.com**. This will help ensure that any vulnerabilities that are found can be [disclosed responsibly](https://en.wikipedia.org/wiki/Responsible_disclosure) to any affected parties.
## Supported Versions
Project versions that are currently being supported with security updates vary per project.
Please see specific project repositories for details.
If nothing is specified, only the latest major versions are supported.

View file

@ -1,31 +0,0 @@
# Support and Help
Need help getting started or using a project? Here's how.
## How to get help
Generally, we do not use GitHub as a support forum. For any usage questions that are not specific to the project itself, please ask on [Stack Overflow](https://stackoverflow.com) instead. By doing so, you are more likely to quickly solve your problem, and you will allow anyone else with the same question to find the answer. This also allows maintainers to focus on improving the project for others.
Please seek support in the following ways:
1. :book: **Read the documentation and other guides** for the project to see if you can figure it out on your own. These should be located in a root `docs/` directory. If there is an example project, explore that to learn how it works to see if you can answer your question.
2. :bulb: **Search for answers and ask questions on [Stack Overflow](https://stackoverflow.com).** This is the most appropriate place for debugging issues specific to your use of the project, or figuring out how to use the project in a specific way.
3. :memo: As a **last resort**, you may open an issue on GitHub to ask for help. However, please clearly explain what you are trying to do, and list what you have already attempted to solve the problem. Provide code samples, but **do not** attach your entire project for someone else to debug. Review our [contributing guidelines](./CONTRIBUTING.md).
## What NOT to do
Please **do not** do any the following:
1. :x: Do not reach out to the author or contributor on Twitter (or other social media) by tweeting or sending a direct message.
2. :x: Do not email the author or contributor.
3. :x: Do not open duplicate issues or litter an existing issue with +1's.
These are not appropriate avenues for seeking help or support with an open-source project. Please follow the guidelines in the previous section. Public questions get public answers, which benefits everyone in the community. ✌️
## Customer Support
I do not provide any sort of "customer support" for open-source projects. However, I am available for hire.

Binary file not shown.

View file

@ -1,5 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="430" height="430" viewBox="0 0 113.50625 113.50625" fill="currentColor">
<path d="M89.693749 72.830671v-19.84375l-18.520833-10.31875-14.552084-8.202083-33.072916 18.520833v19.84375l33.072916-18.520833ZM23.547916 47.695254l23.547916-13.229167L23.547916 21.23692Z" />
<path d="m23.547916 77.990044 33.072916 18.52084 33.072917-18.52084-18.520833-10.318746-14.552084 8.202083-14.552083-8.202083S23.547916 78.122337 23.547916 77.990044z" />
<path d="m56.620832 59.601503 10.054167 5.55625v.000001l-10.054167 5.55625-10.054166-5.55625v-.000001z"/>
</svg>

Before

Width:  |  Height:  |  Size: 617 B

View file

@ -1,5 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="250" height="284.50003" viewBox="0 0 66.145833 75.273966" fill="currentColor">
<path d="M66.145833 51.593751v-19.84375c-11.042319-6.141466-22.077514-12.295645-33.072917-18.520833C22.048611 19.402779 11.024305 25.57639 0 31.750001v19.84375c11.024305-6.173611 22.048611-12.347222 33.072916-18.520833 11.024306 6.173611 22.048611 12.347222 33.072917 18.520833ZM0 26.458334c7.849305-4.409722 15.698611-8.819445 23.547916-13.229167C15.698611 8.819445 7.849305 4.409722 0 0v26.458334Z"/>
<path d="M0 56.753124c11.024305 6.173613 22.048611 12.347227 33.072916 18.52084 11.024306-6.173613 22.048611-12.347227 33.072917-18.52084L47.625 46.434378c-4.850695 2.734028-9.701389 5.468055-14.552084 8.202083-4.850694-2.734028-9.701389-5.468055-14.552083-8.202083C12.352694 49.88272 6.229007 53.417285 0 56.753124Z"/>
<path d="M33.072916 38.364583c3.351389 1.852084 6.70278 3.704166 10.054167 5.556251-3.35139 1.852082-6.702778 3.704167-10.054167 5.55625-3.351388-1.852084-6.702779-3.704166-10.054166-5.556251 3.35139-1.852082 6.702777-3.704167 10.054166-5.55625z"/>
</svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

22
capacitor/.gitignore vendored Normal file
View file

@ -0,0 +1,22 @@
/node_modules/
android/*
!android/variables.gradle
!android/app
android/app/*
!android/app/build.gradle
!android/app/src
android/app/src/*
!android/app/src/main
android/app/src/main/*
!android/app/src/main/AndroidManifest.xml
!android/app/src/main/java
ios/
*.jks
*.pepk
*.bat
pepk.jar
encryption_public_key.pem
package-lock.json
.env
.DS_Store

View file

@ -0,0 +1,65 @@
apply plugin: 'com.android.application'
def verCode = 0
def jsonFile = file('../../../electron/package.json')
def parsedJson = new groovy.json.JsonSlurper().parseText(jsonFile.text)
def verName = parsedJson.version
def versions = verName.tokenize('.')
versions.each (code) -> {
verCode = (verCode*100) + Integer.parseInt(code)
}
android {
namespace "watch.miru"
compileSdk rootProject.ext.compileSdkVersion
defaultConfig {
applicationId "watch.miru"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode verCode
versionName verName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
flatDir{
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
implementation project(':capacitor-android')
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
implementation project(':capacitor-cordova-android-plugins')
}
apply from: 'capacitor.build.gradle'
try {
def servicesJSON = file('google-services.json')
if (servicesJSON.text) {
apply plugin: 'com.google.gms.google-services'
}
} catch(Exception e) {
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
}

View file

@ -0,0 +1,61 @@
<?xml version="1.0" encoding="utf-8" ?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:banner="@drawable/banner">
<activity
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode"
android:name=".MainActivity"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBarLaunch"
android:launchMode="singleTask"
android:resizeableActivity="true"
android:supportsPictureInPicture="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="tv.ouya.intent.category.APP" />
</intent-filter>
<intent-filter>
<data android:scheme="miru" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.BROWSABLE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
</provider>
</application>
<!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-feature android:name="android.software.leanback" android:required="false" />
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
</manifest>

View file

@ -0,0 +1,31 @@
package watch.miru;
import android.os.Bundle;
import android.webkit.ServiceWorkerClient;
import android.webkit.ServiceWorkerController;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
ServiceWorkerController swController = null;
swController = ServiceWorkerController.getInstance();
swController.setServiceWorkerClient(new ServiceWorkerClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebResourceRequest request) {
if (request.getUrl().toString().contains("index.html")) {
request.getRequestHeaders().put("Accept", "text/html");
}
return bridge.getLocalServer().shouldInterceptRequest(request);
}
});
}
}
}

View file

@ -0,0 +1,16 @@
ext {
minSdkVersion = 22
compileSdkVersion = 34
targetSdkVersion = 34
androidxActivityVersion = '1.8.0'
androidxAppCompatVersion = '1.6.1'
androidxCoordinatorLayoutVersion = '1.2.0'
androidxCoreVersion = '1.12.0'
androidxFragmentVersion = '1.6.2'
coreSplashScreenVersion = '1.0.1'
androidxWebkitVersion = '1.9.0'
junitVersion = '4.13.2'
androidxJunitVersion = '1.1.5'
androidxEspressoCoreVersion = '3.5.1'
cordovaAndroidVersion = '10.1.1'
}

View file

@ -0,0 +1,27 @@
const mode = process.env.NODE_ENV?.trim() || 'development'
const config = {
appId: 'watch.miru',
appName: 'Miru',
webDir: 'build',
android: {
buildOptions: {
keystorePath: './watch.miru',
keystorePassword: '',
keystoreAlias: 'watch.miru'
},
webContentsDebuggingEnabled: true
},
plugins: {
SplashScreen: { launchShowDuration: 0 },
CapacitorHttp: { enabled: false },
CapacitorNodeJS: { nodeDir: 'nodejs' }
},
server: {
cleartext: true
}
}
if (mode === 'development') config.server.url = 'http://localhost:5001/index.html'
module.exports = config

@ -0,0 +1 @@
Subproject commit 23c55996d50e0f750e4b013a51d212e98dc661ea

48
capacitor/package.json Normal file
View file

@ -0,0 +1,48 @@
{
"name": "capacitor",
"version": "1.1.0",
"private": true,
"scripts": {
"build:native": "cd public/nodejs/ && npm install && docker build -t android-build:latest . && docker run -v ${PWD}:/app/ -it android-build:latest /bin/bash /app/setup-deps.sh",
"build:app": "cross-env NODE_ENV=production run-s build:web build:native build:assets",
"build:web": "webpack build",
"build:assets": "capacitor-assets generate --iconBackgroundColor #e5204c --iconBackgroundColorDark #e5204c --splashBackgroundColor #e5204c --splashBackgroundColorDark #e5204c --android",
"dev:adb-port": "adb reverse tcp:5001 tcp:5001",
"dev:ios": "run-p dev:start cap-run:ios",
"dev:android": "cap run android",
"dev:android-port": "run-s dev:android dev:adb-port",
"dev:preview": "vite preview",
"dev:start": "run-p dev:webpack dev:android-port",
"dev:webpack": "webpack serve",
"test:e2e": "cross-env NODE_ENV=production run-s build:web dev:android"
},
"devDependencies": {
"@capacitor/assets": "github:thaunknown/capacitor-assets",
"@capacitor/cli": "^6.1.2",
"cordova-res": "^0.15.4",
"nodejs-mobile-gyp": "^0.4.0",
"npm-run-all": "^4.1.5",
"webpack-cli": "^5.1.4",
"webpack-merge": "^6.0.1"
},
"dependencies": {
"@capacitor/android": "^6.1.2",
"@capacitor/app": "^6.0.1",
"@capacitor/app-launcher": "^6.0.2",
"@capacitor/browser": "^6.0.2",
"@capacitor/core": "^6.1.2",
"@capacitor/device": "^6.0.1",
"@capacitor/ios": "^6.1.2",
"@capacitor/local-notifications": "^6.1.0",
"@capacitor/status-bar": "^6.0.1",
"capacitor-folder-picker": "^0.0.2",
"capacitor-intent-uri": "^0.0.1",
"capacitor-nodejs": "https://github.com/funniray/Capacitor-NodeJS/releases/download/nodejs-18/capacitor-nodejs-1.0.0-beta.6.tgz",
"capacitor-plugin-safe-area": "^3.0.3",
"common": "workspace:*",
"cordova-plugin-navigationbar": "^1.0.31",
"cordova-plugin-pip": "^0.0.2",
"cordova-plugin-screen-orientation": "^3.0.4",
"es6-promise-plugin": "^4.2.2"
}
}

View file

@ -0,0 +1,23 @@
FROM alpine:3.19 AS worker
RUN apk add curl unzip
RUN curl -L https://github.com/nodejs-mobile/nodejs-mobile/releases/download/v18.17.2/nodejs-mobile-v18.17.2-android.zip -o libnode.zip
RUN unzip libnode.zip
FROM saschpe/android-ndk:33-jdk17.0.8_7-ndk25.2.9519653-cmake3.22.1
COPY --from=worker ./nodejs-mobile* /opt/libnode
ENV LIBNODE_PATH=/opt/libnode
# Install nodejs 18 (same version as nodejs-mobile)
ARG NODE_MAJOR=18
RUN apt-get update
RUN apt-get install -y ca-certificates curl gnupg make
RUN mkdir -p /etc/apt/keyrings
RUN curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
RUN echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_$NODE_MAJOR.x nodistro main" | tee /etc/apt/sources.list.d/nodesource.list
RUN apt-get update
RUN apt-get install nodejs -y
WORKDIR /app

View file

@ -0,0 +1,9 @@
{
"name": "nodejs-capacitor-thread",
"private": true,
"dependencies": {
"utp-native": "^2.5.3"
},
"version": "1.0.0",
"main": "./index.js"
}

View file

@ -0,0 +1,54 @@
#!/bin/bash
# instructions
# Install Android NDK
# Set $ANDROID_NDK_PATH (example: ~/Android/Sdk/ndk/26.1.10909125)
# Download and extract android .zip for nodejs-mobile from https://github.com/nodejs-mobile/nodejs-mobile/releases/tag/v18.17.2
# Update LIBNODE_PATH
# npm install nodejs-mobile-gyp
# install other npm packages like normal
# run this script
if [ -d "node_modules" ]; then
echo "node_modules already exists, skipping npm install"
else
npm install
fi
toolchain_folder=$NDK_ROOT/toolchains/llvm/prebuilt/linux-x86_64/bin
export PATH=$toolchain_folder:$PATH
toolchain_target_archs=(armv7a aarch64 x86_64)
node_target_arch=(arm arm64 x64)
android_api_levels=(eabi24 "24" "24")
for ((i=0;i<${#toolchain_target_archs[@]};i++)); do
toolchain_target_arch=${toolchain_target_archs[i]}
node_target_arch=${node_target_arch[i]}
android_api_level=${android_api_levels[i]}
export CC=$toolchain_folder/${toolchain_target_arch}-linux-android${android_api_level}-clang
export CXX=$toolchain_folder/${toolchain_target_arch}-linux-android${android_api_level}-clang++
export LINK=$toolchain_folder/${toolchain_target_arch}-linux-android${android_api_level}-clang++
export AR=$toolchain_folder/llvm-ar
export npm_config_verbose=1
export npm_config_nodedir=${LIBNODE_PATH}
export npm_config_node_gyp=$(pwd)/node_modules/nodejs-mobile-gyp/bin/node-gyp.js
export npm_config_arch=${node_target_arch}
export npm_config_plaform=android
export npm_config_format=make-android
export npm_gyp_defines="target_arch=$node_target_arch v8_target_arch=$node_target_arch android_target_arch=$node_target_arch host_os=linux OS=android"
# --from-from-source is used by node-pre-gyp
echo "Rebuilding for $node_target_arch"
npm rebuild --build-from-source
for file in node_modules/*/build/Release/*.node; do
package=$(echo "$file" | cut -f 2 -d "/")
echo "moving prebuild for $package ($file)"
mkdir "node_modules/$package/prebuilds/android-$node_target_arch"
mv $file "node_modules/$package/prebuilds/android-$node_target_arch/node.napi.node"
rm -r "node_modules/$package/build/"
done
done

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

149
capacitor/src/capacitor.js Normal file
View file

@ -0,0 +1,149 @@
/* globals navigationbar, PictureInPicture */
import { StatusBar, Style } from '@capacitor/status-bar'
import { SafeArea } from 'capacitor-plugin-safe-area'
import { App } from '@capacitor/app'
import { Browser } from '@capacitor/browser'
import { IntentUri } from 'capacitor-intent-uri'
import { LocalNotifications } from '@capacitor/local-notifications'
import { Device } from '@capacitor/device'
import { FolderPicker } from 'capacitor-folder-picker'
import { toast } from 'svelte-sonner'
import IPC from './ipc.js'
IPC.on('open', url => Browser.open({ url }))
IPC.on('intent', async url => {
await IntentUri.openUri({ url })
IPC.emit('intent-end')
})
App.addListener('appUrlOpen', ({ url }) => handleProtocol(url))
let canShowNotifications = false
LocalNotifications.checkPermissions().then(async value => {
if (value) {
try {
await LocalNotifications.requestPermissions()
canShowNotifications = true
} catch (e) {
console.error(e)
}
}
})
let id = 0
IPC.on('notification', noti => {
/** @type {import('@capacitor/local-notifications').LocalNotificationSchema} */
const notification = {
title: noti.title,
body: noti.body,
id: id++,
attachments: [
{
id: '' + id++,
url: noti.icon
}
]
}
if (canShowNotifications) LocalNotifications.schedule({ notifications: [notification] })
})
IPC.on('get-device-info', async () => {
const deviceInfo = {
features: {},
info: await Device.getInfo(),
cpu: {},
ram: {}
}
IPC.emit('device-info', JSON.stringify(deviceInfo))
})
const STORAGE_TYPE_MAP = {
primary: '/sdcard/',
secondary: '/sdcard/'
}
IPC.on('dialog', async () => {
const result = await FolderPicker.chooseFolder()
const normalizedPath = decodeURIComponent(result.path)
const [, uri, ...path] = normalizedPath.split(':')
const [,, app, subpath, type, ...rest] = uri.split('/')
if (app !== 'com.android.externalstorage.documents') return toast.error('Unverified app', { description: 'Expected com.android.externalstorage.documents, got: ' + app })
if (rest.length) return toast.error('Unsupported uri', { description: 'Unxpected access type, got: tree/' + rest.join('/') })
if (subpath !== 'tree') return toast.error('Unsupported subpath type', { description: 'Expected tree subpath, got: ' + subpath })
let base = STORAGE_TYPE_MAP[type]
if (!base) {
if (!/[a-z0-9]{4}-[a-z0-9]{4}/i.test(type)) return toast.error('Unsupported storage type')
base = `/storage/${type}/`
}
IPC.emit('path', base + path.join(''))
})
// schema: miru://key/value
const protocolMap = {
auth: token => sendToken(token),
anime: id => IPC.emit('open-anime', id),
w2g: link => IPC.emit('w2glink', link),
schedule: () => IPC.emit('schedule'),
donate: () => Browser.open({ url: 'https://github.com/sponsors/ThaUnknown/' })
}
const protocolRx = /miru:\/\/([a-z0-9]+)\/(.*)/i
function handleProtocol (text) {
const match = text.match(protocolRx)
if (match) protocolMap[match[1]]?.(match[2])
}
function sendToken (line) {
let token = line.split('access_token=')[1].split('&token_type')[0]
if (token) {
if (token.endsWith('/')) token = token.slice(0, -1)
IPC.emit('altoken', token)
}
}
App.getLaunchUrl().then(res => {
if (location.hash !== '#skipAlLogin') {
location.hash = '#skipAlLogin'
if (res) handleProtocol(res.url)
} else {
location.hash = ''
}
})
SafeArea.addListener('safeAreaChanged', updateInsets)
screen.orientation.addEventListener('change', updateInsets)
async function updateInsets () {
const { insets } = await SafeArea.getSafeAreaInsets()
for (const [key, value] of Object.entries(insets)) {
document.documentElement.style.setProperty(`--safe-area-${key}`, `${value}px`)
}
}
updateInsets()
StatusBar.hide()
StatusBar.setStyle({ style: Style.Dark })
StatusBar.setOverlaysWebView({ overlay: true })
navigationbar.setUp(true)
// cordova screen orientation plugin is also used, and it patches global screen.orientation.lock
// hook into pip request, and use our own pip implementation, then instantly report exit pip
// this is more like DOM PiP, rather than video PiP
HTMLVideoElement.prototype.requestPictureInPicture = function () {
PictureInPicture.enter(this.videoWidth, this.videoHeight, success => {
this.dispatchEvent(new Event('leavepictureinpicture'))
if (success) document.querySelector('.content-wrapper').requestFullscreen()
}, err => {
this.dispatchEvent(new Event('leavepictureinpicture'))
console.error(err)
})
return Promise.resolve({})
}

35
capacitor/src/ipc.js Normal file
View file

@ -0,0 +1,35 @@
import { App } from '@capacitor/app'
import { NodeJS } from 'capacitor-nodejs'
import EventEmitter from 'events'
const ready = NodeJS.whenReady()
const main = new EventEmitter()
export default main
main.on('portRequest', async () => {
globalThis.port = {
onmessage: cb => {
NodeJS.addListener('ipc', ({ args }) => cb(args[0]))
},
postMessage: (data, b) => {
NodeJS.send({ eventName: 'ipc', args: [{ data }] })
}
}
await ready
NodeJS.send({ eventName: 'port-init', args: [localStorage.getItem('settings')] })
main.emit('port')
})
const [_platform, arch] = navigator.platform.split(' ')
globalThis.version = {
platform: globalThis.cordova?.platformId,
arch
}
main.once('version', async () => {
const { version } = await App.getInfo()
main.emit('version', version)
})

43
capacitor/src/main.js Normal file
View file

@ -0,0 +1,43 @@
import TorrentClient from 'common/modules/webtorrent.js'
import { channel } from 'bridge'
import { env } from 'node:process'
import { statfs } from 'fs/promises'
async function storageQuota (directory) {
const { bsize, bavail } = await statfs(directory)
return bsize * bavail
}
if (typeof localStorage === 'undefined') {
const data = {}
globalThis.localStorage = {
setItem: (k, v) => { data[k] = v },
getItem: (k) => data[k] || null
}
}
let client
channel.on('port-init', data => {
localStorage.setItem('settings', data)
const port = {
onmessage: _ => {},
postMessage: data => {
channel.send('ipc', { data })
}
}
let storedSettings = {}
try {
storedSettings = JSON.parse(localStorage.getItem('settings')) || {}
} catch (error) {}
channel.on('ipc', a => port.onmessage(a))
if (!client) {
client = new TorrentClient(channel, storageQuota, 'node', storedSettings.torrentPathNew || env.TMPDIR)
channel.emit('port', {
ports: [port]
})
}
})

13
capacitor/src/support.js Normal file
View file

@ -0,0 +1,13 @@
// feature support list, overriden per environment, capacitor
export const SUPPORTS = {
offscreenRender: false,
update: false,
angle: false,
doh: false,
discord: false,
keybinds: false,
isAndroid: true,
externalPlayer: false,
permamentNAT: false // no way of safely closing app
}

View file

@ -0,0 +1,57 @@
const commonConfig = require('common/webpack.config.cjs')
const { merge } = require('webpack-merge')
const { join, resolve } = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const mode = process.env.NODE_ENV?.trim() || 'development'
const alias = {
'@/modules/ipc.js': join(__dirname, 'src', 'ipc.js'),
'@/modules/support.js': join(__dirname, 'src', 'support.js')
}
/** @type {import('webpack').Configuration} */
const capacitorConfig = {
devtool: 'source-map',
entry: [join(__dirname, 'src', 'main.js')],
output: {
path: join(__dirname, 'build', 'nodejs'),
filename: 'index.js'
},
mode,
externals: {
'utp-native': 'require("utp-native")',
bridge: 'require("bridge")'
},
resolve: {
aliasFields: [],
mainFields: ['module', 'main', 'node'],
alias: {
...alias,
wrtc: false,
'node-datachannel': false,
'bittorrent-tracker/lib/client/http-tracker.js': resolve('../node_modules/bittorrent-tracker/lib/client/http-tracker.js'),
'webrtc-polyfill': false // no webrtc on mobile, need the resources
}
},
target: 'node',
devServer: {
devMiddleware: {
writeToDisk: true
},
hot: true,
client: {
overlay: { errors: true, warnings: false, runtimeErrors: false }
},
port: 5001
},
plugins: [
new CopyWebpackPlugin({
patterns: [
{ from: join(__dirname, 'public', 'nodejs') }
]
})
]
}
module.exports = [capacitorConfig, merge(commonConfig(__dirname, alias, 'browser', 'index'), { entry: [join(__dirname, 'src', 'capacitor.js')] })]

96
common/App.svelte Normal file
View file

@ -0,0 +1,96 @@
<script context='module'>
import { setContext } from 'svelte'
import { writable } from 'simple-store-svelte'
import { anilistClient } from '@/modules/anilist.js'
import IPC from '@/modules/ipc.js'
import { rss } from './views/TorrentSearch/TorrentModal.svelte'
export const page = writable('home')
export const view = writable(null)
export async function handleAnime (anime) {
view.set(null)
view.set((await anilistClient.searchIDSingle({ id: anime })).data.Media)
}
IPC.on('open-anime', handleAnime)
IPC.on('schedule', () => {
page.set('schedule')
})
let ignoreNext = false
function addPage (value, type) {
if (ignoreNext) {
ignoreNext = false
return
}
history.pushState({ type, value }, '', location.origin + location.pathname + '?id=' + Math.trunc(Math.random() * Number.MAX_SAFE_INTEGER).toString())
}
page.subscribe((value) => {
addPage(value, 'page')
})
view.subscribe((value) => {
addPage(value, 'view')
})
addPage('home', 'page')
window.addEventListener('popstate', e => {
const { state } = e
if (!state) return
ignoreNext = true
view.set(null)
rss.set(null)
if (document.fullscreenElement) document.exitFullscreen()
if (state.type === 'page') {
page.set(state.value)
} else {
view.set(state.value)
}
})
</script>
<script>
import Sidebar from './components/Sidebar.svelte'
import Router from './Router.svelte'
import ViewAnime from './views/ViewAnime/ViewAnime.svelte'
import TorrentModal from './views/TorrentSearch/TorrentModal.svelte'
import Menubar from './components/Menubar.svelte'
import { Toaster } from 'svelte-sonner'
import Logout from './components/Logout.svelte'
import Navbar from './components/Navbar.svelte'
setContext('view', view)
</script>
<div class='page-wrapper with-transitions bg-dark position-relative' data-sidebar-type='overlayed-all'>
<Menubar bind:page={$page} />
<ViewAnime />
<Logout />
<Sidebar bind:page={$page} />
<Toaster visibleToasts={6} position='top-right' theme='dark' richColors duration={10000} closeButton />
<div class='overflow-hidden content-wrapper h-full z-10'>
<TorrentModal />
<Router bind:page={$page} />
</div>
<Navbar bind:page={$page} />
</div>
<style>
.content-wrapper {
will-change: width;
top: 0 !important;
}
.page-wrapper > .content-wrapper {
margin-left: var(--sidebar-minimised) !important;
width: calc(100% - var(--sidebar-minimised)) !important;
transition: none !important;
}
.page-wrapper {
height: calc(100% - var(--navbar-height)) !important;
}
@media (min-width: 769px) {
.page-wrapper {
padding-left: max(var(--safe-area-left), env(safe-area-inset-left, 0)) !important;
}
}
</style>

41
common/Router.svelte Normal file
View file

@ -0,0 +1,41 @@
<script context='module'>
const mql = matchMedia('(min-width: 769px)')
const isMobile = readable(!mql.matches, set => {
const check = ({ matches }) => set(!matches)
mql.addEventListener('change', check)
return () => mql.removeEventListener('change', check)
})
</script>
<script>
import Home from './views/Home/Home.svelte'
import MediaHandler from './views/Player/MediaHandler.svelte'
import Settings from '@/views/Settings/Settings.svelte'
import WatchTogether from './views/WatchTogether/WatchTogether.svelte'
import Miniplayer from 'svelte-miniplayer'
import Search from './views/Search.svelte'
import AiringSchedule from './views/AiringSchedule.svelte'
import { readable } from 'simple-store-svelte'
export let page = 'home'
$: minwidth = $isMobile ? '200px' : '35rem'
$: maxwidth = $isMobile ? '200px' : '60rem'
</script>
<div class='w-full h-full position-absolute overflow-hidden'>
<Miniplayer active={page !== 'player'} class='bg-dark-light z-10 {page === 'player' ? 'h-full' : ''}' {minwidth} {maxwidth} width='300px' padding='2rem' resize={!$isMobile}>
<MediaHandler miniplayer={page !== 'player'} bind:page />
</Miniplayer>
</div>
{#if page === 'settings'}
<Settings />
{:else if page === 'home'}
<Home />
{:else if page === 'search'}
<Search />
{:else if page === 'schedule'}
<AiringSchedule />
{:else if page === 'watchtogether'}
<WatchTogether />
{/if}

View file

@ -0,0 +1,49 @@
<script context='module'>
import { click } from '@/modules/click.js'
import { writable } from 'simple-store-svelte'
export const logout = writable(false)
function confirm () {
localStorage.removeItem('ALviewer')
location.hash = ''
location.reload()
}
</script>
<script>
let modal
function close () {
$logout = false
}
function checkClose ({ keyCode }) {
if (keyCode === 27) close()
}
$: $logout && modal?.focus()
</script>
<div class='modal z-40' class:show={$logout}>
{#if $logout}
<div class='modal-dialog' on:pointerup|self={close} on:keydown={checkClose} tabindex='-1' role='button' bind:this={modal}>
<div class='modal-content d-flex justify-content-center flex-column'>
<button class='close pointer z-30 top-20 right-0 position-absolute' type='button' use:click={close}> &times; </button>
<h5 class='modal-title'>Log Out</h5>
<p>
Are You Sure You Want To Sign Out?
</p>
<div class='text-right mt-20'>
<button class='btn mr-5' type='button' on:click={close}>Cancel</button>
<button class='btn btn-danger' type='button' on:click={confirm}>Sign Out</button>
</div>
</div>
</div>
{/if}
</div>
<style>
.close {
top: 4rem !important;
left: unset !important;
right: 2.5rem !important;
}
</style>

View file

@ -0,0 +1,106 @@
<script>
import { persisted } from 'svelte-persisted-store'
import { getContext } from 'svelte'
import { click } from '@/modules/click.js'
import IPC from '@/modules/ipc.js'
export let page
const view = getContext('view')
function close () {
$view = null
page = 'home'
}
const debug = persisted('debug', '', {
serializer: {
parse: e => e,
stringify: e => e
}
})
</script>
<div class='w-full z-101 navbar bg-transparent border-0 p-0 d-flex'>
<div class='d-flex h-full draggable align-items-center text-center'>
{#if window.version?.platform !== 'darwin'}
<img src='./logo_filled.png' class='position-absolute w-50 h-50 m-10 pointer d-md-block d-none p-5' alt='ico' use:click={close} />
{/if}
</div>
<div class='window-controls d-flex position-absolute top-0 right-0 height-full'>
<button class='button max-button d-flex border-0 color-white align-items-center justify-content-center' on:click={() => IPC.emit('minimize')}><svg class='svg-controls' height='12' role='img' viewBox='0 0 12 12'width='12'><rect fill='currentColor' height='1' width='10' x='1' y='6' /></svg></button>
<button class='button restore-button d-flex border-0 color-white align-items-center justify-content-center' on:click={() => IPC.emit('maximize')}><svg class='svg-controls' height='12' role='img' viewBox='0 0 12 12'width='12'><rect fill='none' height='9' stroke='currentColor' width='9' x='1.5' y='1.5' /></svg></button>
<button class='button close-button d-flex border-0 color-white align-items-center justify-content-center' on:click={() => IPC.emit('close')}><svg class='svg-controls' height='12' role='img' viewBox='0 0 12 12'width='12'><polygon fill='currentColor' fill-rule='evenodd' points='11 1.576 6.583 6 11 10.424 10.424 11 6 6.583 1.576 11 1 10.424 5.417 6 1 1.576 1.576 1 6 5.417 10.424 1' /></svg></button>
</div>
</div>
{#if $debug}
<div class='ribbon right z-101 text-center position-fixed font-size-16 font-weight-bold'>Debug Mode!</div>
{/if}
<style>
.ribbon {
background: #f63220;
box-shadow: 0 0 0 999px #f63220;
clip-path: inset(0 -100%);
pointer-events: none;
min-width: 120px;
inset: 0 auto auto 0;
transform-origin: 100% 0;
transform: translate(-29.3%) rotate(-45deg);
}
.navbar {
--navbar-height: 32px !important;
}
.z-101 {
z-index: 101 !important
}
.draggable {
-webkit-app-region: drag;
color: var(--dm-text-muted-color);
font-size: 11.2px;
width: calc(env(titlebar-area-width, 100%) - 1px);
}
img {
top: 0;
-webkit-app-region: no-drag
}
svg {
width: 18px;
height: 18px;
width: 100%;
}
.navbar {
left: unset !important;
}
@media (pointer: none), (pointer: coarse) {
.navbar {
display: none !important;
height: 0;
}
}
.window-controls {
-webkit-app-region: no-drag;
backdrop-filter: blur(8px);
background: rgba(24, 24, 24, 0.1);
}
.window-controls .button {
background: transparent;
width: 46px;
height: 32px;
user-select: none;
}
.window-controls .button:hover {
background: rgba(128, 128, 128, 0.2);
}
.window-controls .button:active {
background: rgba(128, 128, 128, 0.4);
}
.close-button:hover {
background: #e81123 !important;
}
.close-button:active {
background: #f1707a !important;
}
.svg-controls {
width: 12px;
height: 12px;
}
</style>

View file

@ -0,0 +1,63 @@
<script>
import { getContext } from 'svelte'
import { media } from '../views/Player/MediaHandler.svelte'
import { click } from '@/modules/click.js'
import IPC from '@/modules/ipc.js'
import NavbarLink from './NavbarLink.svelte'
import { MagnifyingGlass } from 'svelte-radix'
import { Users, Clock, Settings, Heart, ListVideo } from 'lucide-svelte'
const view = getContext('view')
export let page
function close () {
$view = null
page = 'home'
}
</script>
<nav class='navbar navbar-fixed-bottom d-block d-md-none border-0 bg-dark'>
<div class='navbar-menu h-full d-flex flex-row justify-content-center align-items-center m-0 pb-5' class:animate={page !== 'player'}>
<img src='./logo_filled.png' class='w-50 h-50 m-10 pointer p-5' alt='ico' use:click={close} />
<NavbarLink click={() => { page = 'search' }} _page='search' css='ml-auto' icon='search' {page} let:active>
<MagnifyingGlass size='2rem' class='flex-shrink-0 p-5 w-30 h-30 m-5 rounded' stroke-width={active ? '2' : '0'} stroke='currentColor' />
</NavbarLink>
<NavbarLink click={() => { page = 'schedule' }} _page='schedule' icon='schedule' {page} let:active>
<Clock size='2rem' class='flex-shrink-0 p-5 w-30 h-30 m-5 rounded' strokeWidth={active ? '3.5' : '2'} />
</NavbarLink>
{#if $media?.media}
<NavbarLink click={() => { $view = $media.media }} icon='queue_music' {page} let:active>
<ListVideo size='2rem' class='flex-shrink-0 p-5 w-30 h-30 m-5 rounded' strokeWidth={active ? '3.5' : '2'} />
</NavbarLink>
{/if}
<NavbarLink click={() => { page = 'watchtogether' }} _page='watchtogether' icon='groups' {page} let:active>
<Users size='2rem' class='flex-shrink-0 p-5 w-30 h-30 m-5 rounded' strokeWidth={active ? '3.5' : '2'} />
</NavbarLink>
<NavbarLink click={() => { IPC.emit('open', 'https://github.com/sponsors/ThaUnknown/') }} icon='favorite' css='ml-auto donate' {page} let:active>
<Heart size='2rem' class='flex-shrink-0 p-5 w-30 h-30 m-5 rounded donate' strokeWidth={active ? '3.5' : '2'} fill='currentColor' />
</NavbarLink>
<NavbarLink click={() => { page = 'settings' }} _page='settings' icon='settings' {page} let:active>
<Settings size='2rem' class='flex-shrink-0 p-5 w-30 h-30 m-5 rounded' strokeWidth={active ? '3.5' : '2'} />
</NavbarLink>
</div>
</nav>
<style>
.navbar .animate :global(.donate) {
animation: glow 1s ease-in-out infinite alternate;
}
.navbar :global(.donate):active {
color: #fa68b6 !important;
}
.navbar :global(.donate) {
font-variation-settings: 'FILL' 1;
color: #fa68b6;
text-shadow: 0 0 1rem #fa68b6;
}
@keyframes glow {
from {
filter: drop-shadow(0 0 1rem #fa68b6);
}
to {
filter: drop-shadow(0 0 0.5rem #fa68b6);
}
}
</style>

View file

@ -0,0 +1,42 @@
<script>
import { click } from '@/modules/click.js'
let _click = () => {}
export { _click as click }
export let page
export let _page = ''
export let css = ''
export let icon = ''
</script>
<div
class='navbar-link navbar-link-with-icon pointer overflow-hidden {css}'
use:click={_click}>
<span class='rounded d-flex'>
<slot active={page === _page}>{icon}</slot>
</span>
</div>
<style>
.navbar-link > span {
color: #fff;
border-radius: 0.3rem;
}
.navbar-link > span {
color: #fff;
transition: background .8s cubic-bezier(0.25, 0.8, 0.25, 1), color .8s cubic-bezier(0.25, 0.8, 0.25, 1);
}
.navbar-link:active > span {
background: #fff;
color: var(--dark-color);
}
.navbar-link {
font-size: 1.4rem;
padding: 0.75rem;
height: 5.5rem;
}
</style>

View file

@ -0,0 +1,231 @@
<script context='module'>
const badgeKeys = ['search', 'genre', 'season', 'year', 'format', 'status', 'sort']
export function searchCleanup (search) {
return Object.fromEntries(Object.entries(search).map((entry) => {
return badgeKeys.includes(entry[0]) && entry
}).filter(a => a?.[1]))
}
</script>
<script>
import { traceAnime } from '@/modules/anime.js'
import { settings } from '@/modules/settings.js'
import { click } from '@/modules/click.js'
import { page } from '@/App.svelte'
import { toast } from 'svelte-sonner'
import { MagnifyingGlass, Image } from 'svelte-radix'
import { Type, Drama, Leaf, MonitorPlay, Tv, ArrowDownWideNarrow, Trash2, Tags, Grid3X3, Grid2X2 } from 'lucide-svelte'
export let search
let searchTextInput
let form
$: sanitisedSearch = Object.values(searchCleanup(search))
function searchClear () {
search = {
search: '',
genre: '',
season: '',
year: null,
format: '',
status: '',
sort: ''
}
searchTextInput.focus()
form.dispatchEvent(new Event('input', { bubbles: true }))
$page = 'search'
}
function handleFile ({ target }) {
const { files } = target
if (files?.[0]) {
toast.promise(traceAnime(files[0]), {
description: 'You can also paste an URL to an image.',
loading: 'Looking up anime for image...',
success: 'Found anime for image!',
error: 'Couldn\'t find anime for specified image! Try to remove black bars, or use a more detailed image.'
})
target.value = null
}
}
function changeCardMode (type) {
$settings.cards = type
form.dispatchEvent(new Event('input', { bubbles: true }))
}
</script>
<form class='container-fluid py-20 px-md-50 bg-dark pb-0 position-sticky top-0 search-container z-40' on:input bind:this={form}>
<div class='row'>
<div class='col-lg col-4 p-10 d-flex flex-column justify-content-end'>
<div class='pb-10 font-size-24 font-weight-semi-bold d-flex'>
<Type class='mr-10' size='3rem' />
Title
</div>
<div class='input-group'>
<div class='input-group-prepend'>
<MagnifyingGlass size='2.75rem' class='input-group-text bg-dark-light pr-0' />
</div>
<input
bind:this={searchTextInput}
type='search'
class='form-control bg-dark-light border-left-0 text-capitalize'
autocomplete='off'
bind:value={search.search}
data-option='search'
disabled={search.disableSearch}
placeholder='Any' />
</div>
</div>
<div class='col-lg col-4 p-10 d-flex flex-column justify-content-end'>
<div class='pb-10 font-size-24 font-weight-semi-bold d-flex'>
<Drama class='mr-10' size='3rem' />
Genre
</div>
<div class='input-group'>
<select class='form-control bg-dark-light' required bind:value={search.genre} disabled={search.disableSearch}>
<option value selected>Any</option>
<option value='Action'>Action</option>
<option value='Adventure'>Adventure</option>
<option value='Comedy'>Comedy</option>
<option value='Drama'>Drama</option>
<option value='Ecchi'>Ecchi</option>
<option value='Fantasy'>Fantasy</option>
<option value='Horror'>Horror</option>
<option value='Mahou Shoujo'>Mahou Shoujo</option>
<option value='Mecha'>Mecha</option>
<option value='Music'>Music</option>
<option value='Mystery'>Mystery</option>
<option value='Psychological'>Psychological</option>
<option value='Romance'>Romance</option>
<option value='Sci-Fi'>Sci-Fi</option>
<option value='Slice of Life'>Slice of Life</option>
<option value='Sports'>Sports</option>
<option value='Supernatural'>Supernatural</option>
<option value='Thriller'>Thriller</option>
</select>
</div>
</div>
<div class='col-lg col-4 p-10 d-flex flex-column justify-content-end'>
<div class='pb-10 font-size-24 font-weight-semi-bold d-flex'>
<Leaf class='mr-10' size='3rem' />
Season
</div>
<div class='input-group'>
<select class='form-control bg-dark-light border-right-dark' required bind:value={search.season} disabled={search.disableSearch}>
<option value selected>Any</option>
<option value='WINTER'>Winter</option>
<option value='SPRING'>Spring</option>
<option value='SUMMER'>Summer</option>
<option value='FALL'>Fall</option>
</select>
<datalist id='search-year'>
{#each Array(new Date().getFullYear() - 1940 + 2) as _, i}
{@const year = new Date().getFullYear() + 2 - i}
<option>{year}</option>
{/each}
</datalist>
<input type='number' inputmode='numeric' pattern='[0-9]*' placeholder='Any' min='1940' max='2100' list='search-year' class='bg-dark-light form-control' disabled={search.disableSearch} bind:value={search.year} />
</div>
</div>
<div class='col p-10 d-flex flex-column justify-content-end'>
<div class='pb-10 font-size-24 font-weight-semi-bold d-flex'>
<Tv class='mr-10' size='3rem' />
Format
</div>
<div class='input-group'>
<select class='form-control bg-dark-light' required bind:value={search.format} disabled={search.disableSearch}>
<option value selected>Any</option>
<option value='TV'>TV Show</option>
<option value='MOVIE'>Movie</option>
<option value='TV_SHORT'>TV Short</option>
<option value='OVA'>OVA</option>
<option value='ONA'>ONA</option>
</select>
</div>
</div>
<div class='col p-10 d-flex flex-column justify-content-end'>
<div class='pb-10 font-size-24 font-weight-semi-bold d-flex'>
<MonitorPlay class='mr-10' size='3rem' />
Status
</div>
<div class='input-group'>
<select class='form-control bg-dark-light' required bind:value={search.status} disabled={search.disableSearch}>
<option value selected>Any</option>
<option value='RELEASING'>Airing</option>
<option value='FINISHED'>Finished</option>
<option value='NOT_YET_RELEASED'>Not Yet Aired</option>
<option value='CANCELLED'>Cancelled</option>
</select>
</div>
</div>
<div class='col p-10 d-flex flex-column justify-content-end'>
<div class='pb-10 font-size-24 font-weight-semi-bold d-flex'>
<ArrowDownWideNarrow class='mr-10' size='3rem' />
Sort
</div>
<div class='input-group'>
<select class='form-control bg-dark-light' required bind:value={search.sort} disabled={search.disableSearch}>
<option value selected>Name</option>
<option value='START_DATE_DESC'>Release Date</option>
<option value='SCORE_DESC'>Score</option>
<option value='POPULARITY_DESC'>Popularity</option>
<option value='TRENDING_DESC'>Trending</option>
<option value='UPDATED_AT_DESC'>Updated Date</option>
</select>
</div>
</div>
<input type='file' class='d-none' id='search-image' accept='image/*' on:input|preventDefault|stopPropagation={handleFile} />
<div class='col-auto p-10 d-flex'>
<div class='align-self-end'>
<button class='btn btn-square bg-dark-light px-5 align-self-end border-0' type='button'>
<label for='search-image' class='pointer mb-0 d-flex align-items-center justify-content-center'>
<Image size='1.625rem' />
</label>
</button>
</div>
</div>
<div class='col-auto p-10 d-flex'>
<div class='align-self-end'>
<button class='btn btn-square bg-dark-light d-flex align-items-center justify-content-center px-5 align-self-end border-0' type='button' use:click={searchClear} class:text-primary={!!sanitisedSearch?.length || search.disableSearch || search.clearNext}>
<Trash2 size='1.625rem' />
</button>
</div>
</div>
</div>
<div class='w-full px-10 pt-10 h-50 d-flex flex-colum align-items-center'>
{#if sanitisedSearch?.length}
<Tags class='text-dark-light mr-20' size='3rem' />
{#each sanitisedSearch as badge}
<span class='badge bg-light border-0 py-5 px-10 text-capitalize mr-20 text-white text-nowrap'>{('' + badge).replace(/_/g, ' ').toLowerCase()}</span>
{/each}
{/if}
<span class='mr-10 filled ml-auto text-dark-light pointer' class:text-muted={$settings.cards === 'small'} use:click={() => changeCardMode('small')}><Grid3X3 size='2.25rem' /></span>
<span class='text-dark-light pointer' class:text-muted={$settings.cards === 'full'} use:click={() => changeCardMode('full')}><Grid2X2 size='2.25rem' /></span>
</div>
</form>
<style>
.input-group,
.container-fluid button, .pointer {
transition: scale 0.2s ease;
}
.input-group:hover, .pointer:hover {
scale: 1.08;
}
.container-fluid button:hover {
scale: 1.20;
}
input:not(:focus):invalid {
box-shadow: 0 0 0 0.2rem var(--danger-color) !important;
}
select.form-control:invalid {
color: var(--dm-input-placeholder-text-color);
}
.font-size-30 {
font-size: 3rem !important;
}
</style>

View file

@ -0,0 +1,131 @@
<script>
import { getContext } from 'svelte'
import { anilistClient } from '@/modules/anilist.js'
import { media } from '../views/Player/MediaHandler.svelte'
import { platformMap } from '@/views/Settings/Settings.svelte'
import { settings } from '@/modules/settings.js'
import { toast } from 'svelte-sonner'
import { logout } from './Logout.svelte'
import IPC from '@/modules/ipc.js'
import SidebarLink from './SidebarLink.svelte'
import { Clock, Download, Heart, Home, ListVideo, LogIn, Settings, Users } from 'lucide-svelte'
import { MagnifyingGlass } from 'svelte-radix'
let updateState = ''
IPC.on('update-available', () => {
updateState = 'downloading'
})
IPC.on('update-downloaded', () => {
updateState = 'ready'
})
const view = getContext('view')
export let page
function handleAlLogin () {
if (anilistClient.userID?.viewer?.data?.Viewer) {
$logout = true
} else {
IPC.emit('open', 'https://anilist.co/api/v2/oauth/authorize?client_id=4254&response_type=token') // Change redirect_url to miru://auth
if (platformMap[window.version.platform] === 'Linux') {
toast('Support Notification', {
description: "If your linux distribution doesn't support custom protocol handlers, you can simply paste the full URL into the app.",
duration: 300000
})
}
}
}
</script>
<div class='sidebar z-30 d-md-block' class:animated={$settings.expandingSidebar}>
<div class='sidebar-overlay pointer-events-none h-full position-absolute' />
<div class='sidebar-menu h-full d-flex flex-column justify-content-center align-items-center m-0 pb-5' class:animate={page !== 'player'}>
<SidebarLink click={handleAlLogin} icon='login' text={anilistClient.userID?.viewer?.data?.Viewer ? 'Logout' : 'Login With AniList'} css='mt-auto' {page} image={anilistClient.userID?.viewer?.data?.Viewer?.avatar.medium}>
<LogIn size='2rem' class='flex-shrink-0 p-5 w-30 h-30 m-5 rounded' />
</SidebarLink>
<SidebarLink click={() => { page = 'home' }} _page='home' text='Home' {page} let:active>
<Home size='2rem' class='flex-shrink-0 p-5 w-30 h-30 m-5 rounded' strokeWidth={active ? '3.5' : '2'} />
</SidebarLink>
<SidebarLink click={() => { page = 'search' }} _page='search' text='Search' {page} let:active>
<MagnifyingGlass size='2rem' class='flex-shrink-0 p-5 w-30 h-30 m-5 rounded' stroke-width={active ? '2' : '0'} stroke='currentColor' />
</SidebarLink>
<SidebarLink click={() => { page = 'schedule' }} _page='schedule' icon='schedule' text='Schedule' {page} let:active>
<Clock size='2rem' class='flex-shrink-0 p-5 w-30 h-30 m-5 rounded' strokeWidth={active ? '3.5' : '2'} />
</SidebarLink>
{#if $media?.media}
<SidebarLink click={() => { $view = $media.media }} icon='queue_music' text='Now Playing' {page} let:active>
<ListVideo size='2rem' class='flex-shrink-0 p-5 w-30 h-30 m-5 rounded' strokeWidth={active ? '3.5' : '2'} />
</SidebarLink>
{/if}
<SidebarLink click={() => { page = 'watchtogether' }} _page='watchtogether' icon='groups' text='Watch Together' {page} let:active>
<Users size='2rem' class='flex-shrink-0 p-5 w-30 h-30 m-5 rounded' strokeWidth={active ? '3.5' : '2'} />
</SidebarLink>
<SidebarLink click={() => { IPC.emit('open', 'https://github.com/sponsors/ThaUnknown/') }} icon='favorite' text='Support This App' css='mt-auto' {page} let:active>
<Heart size='2rem' class='flex-shrink-0 p-5 w-30 h-30 m-5 rounded donate' strokeWidth={active ? '3.5' : '2'} fill='currentColor' />
</SidebarLink>
{#if updateState === 'downloading'}
<SidebarLink click={() => { toast('Update is downloading...') }} icon='download' text='Update Downloading...' {page} let:active>
<Download size='2rem' class='flex-shrink-0 p-5 w-30 h-30 m-5 rounded' strokeWidth={active ? '3.5' : '2'} />
</SidebarLink>
{:else if updateState === 'ready'}
<SidebarLink click={() => { IPC.emit('quit-and-install') }} icon='download' text='Update Ready!' {page} let:active>
<Download size='2rem' class='flex-shrink-0 p-5 w-30 h-30 m-5 rounded update' strokeWidth={active ? '3.5' : '2'} />
</SidebarLink>
{/if}
<SidebarLink click={() => { page = 'settings' }} _page='settings' icon='settings' text='Settings' {page} let:active>
<Settings size='2rem' class='flex-shrink-0 p-5 w-30 h-30 m-5 rounded' strokeWidth={active ? '3.5' : '2'} />
</SidebarLink>
</div>
</div>
<style>
.sidebar .animate :global(.donate) {
animation: glow 1s ease-in-out infinite alternate;
}
.sidebar :global(.donate):hover {
color: #fa68b6 !important;
}
.sidebar :global(.donate) {
font-variation-settings: 'FILL' 1;
color: #fa68b6;
text-shadow: 0 0 1rem #fa68b6;
}
:global(.update) {
color: #47cb6a;
font-variation-settings: 'FILL' 1;
}
@keyframes glow {
from {
filter: drop-shadow(0 0 1rem #fa68b6);
}
to {
filter: drop-shadow(0 0 0.5rem #fa68b6);
}
}
.sidebar-menu {
padding-top: 10rem;
}
.sidebar {
transition: width .8s cubic-bezier(0.25, 0.8, 0.25, 1), left .8s cubic-bezier(0.25, 0.8, 0.25, 1) !important;
background: none !important;
overflow-y: unset;
overflow-x: visible;
left: unset;
}
.sidebar.animated:hover {
width: 22rem
}
.sidebar-overlay {
width: var(--sidebar-width);
transition: width .8s cubic-bezier(0.25, 0.8, 0.25, 1), left .8s cubic-bezier(0.25, 0.8, 0.25, 1) !important;
background: var(--sidebar-gradient);
backdrop-filter: blur(2px);
z-index: -1;
}
.sidebar.animated:hover .sidebar-overlay {
width: 63rem
}
</style>

View file

@ -0,0 +1,75 @@
<script>
import { click } from '@/modules/click.js'
let _click = () => {}
export { _click as click }
export let image = ''
export let page
export let _page = ''
export let css = ''
export let text = ''
export let icon = ''
</script>
<div class='sidebar-link sidebar-link-with-icon pointer overflow-hidden {css}'
use:click={_click}>
<span class='text-nowrap d-flex align-items-center w-full h-full'>
{#if image}
<span class='rounded d-flex'>
<img src={image} class='h-30 rounded' alt='logo' />
</span>
<span class='text ml-20'>{text}</span>
{:else}
<span class='rounded d-flex'>
<slot active={page === _page}>{icon}</slot>
</span>
<span class='text ml-20'>{text}</span>
{/if}
</span>
</div>
<style>
.text {
opacity: 1;
transition: opacity 0.8s cubic-bezier(0.25, 0.8, 0.25, 1);
display: inline-flex;
justify-content: center;
align-items: center;
}
.sidebar-link > span {
color: #fff;
border-radius: 0.3rem;
}
.sidebar-link > span > span:nth-child(1) {
color: #fff;
transition: background .8s cubic-bezier(0.25, 0.8, 0.25, 1), color .8s cubic-bezier(0.25, 0.8, 0.25, 1);
}
.sidebar-link:hover > span > span:nth-child(1) {
background: #fff;
color: var(--dark-color);
}
.sidebar-link {
width: 100%;
font-size: 1.4rem;
padding: 0.75rem 1.5rem;
height: 5.5rem;
}
.sidebar-link img {
font-size: 2.2rem;
width: 3rem;
height: 3rem;
margin: 0.5rem;
display: inline-flex;
justify-content: center;
align-items: center;
}
img {
margin-right: var(--sidebar-brand-image-margin-right);
}
</style>

View file

@ -0,0 +1,23 @@
<script>
import { getContext } from 'svelte'
import { TABS } from './Tabs.svelte'
const panel = {}
const { registerPanel, selectedPanel } = getContext(TABS)
registerPanel(panel)
</script>
{#if $selectedPanel === panel}
<slot />
{/if}
<style>
slot {
margin-bottom: 10px;
padding: 40px;
border: 1px solid #dee2e6;
border-radius: 0 0 .5rem .5rem;
border-top: 0;
}
</style>

View file

@ -0,0 +1,20 @@
<script>
import { getContext } from 'svelte'
import { TABS } from './Tabs.svelte'
import { click } from '@/modules/click.js'
const tab = {}
const { registerTab, selectTab, selectedTab } = getContext(TABS)
registerTab(tab)
</script>
<div class={'pointer my-5 rounded ' + ($selectedTab === tab ? 'bg-dark-light font-weight-bold' : '')} use:click={() => selectTab(tab)}>
<slot />
</div>
<style>
div {
transition: background .2s ease-in-out;
}
</style>

View file

@ -0,0 +1,3 @@
export { default as Tabs } from './Tabs.svelte'
export { default as TabLabel } from './TabLabel.svelte'
export { default as Tab } from './Tab.svelte'

View file

@ -0,0 +1,48 @@
<script context='module'>
export const TABS = {}
</script>
<script>
import { setContext, onDestroy } from 'svelte'
import { writable } from 'simple-store-svelte'
const tabs = []
const panels = []
const selectedTab = writable(null)
const selectedPanel = writable(null)
setContext(TABS, {
registerTab: tab => {
tabs.push(tab)
selectedTab.update(current => current || tab)
onDestroy(() => {
const i = tabs.indexOf(tab)
tabs.splice(i, 1)
selectedTab.update(current => (current === tab ? tabs[i] || tabs[tabs.length - 1] : current))
})
},
registerPanel: panel => {
panels.push(panel)
selectedPanel.update(current => current || panel)
onDestroy(() => {
const i = panels.indexOf(panel)
panels.splice(i, 1)
selectedPanel.update(current => (current === panel ? panels[i] || panels[panels.length - 1] : current))
})
},
selectTab: tab => {
const i = tabs.indexOf(tab)
selectedTab.set(tab)
selectedPanel.set(panels[i])
},
selectedTab,
selectedPanel
})
</script>
<slot />

View file

@ -0,0 +1,38 @@
<script>
import FullBanner from './FullBanner.svelte'
import SkeletonBanner from './SkeletonBanner.svelte'
export let data
function shuffle (array) {
let currentIndex = array.length
let randomIndex
while (currentIndex > 0) {
randomIndex = Math.floor(Math.random() * currentIndex--);
[array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]]
}
return array
}
function shuffleAndFilter (media) {
return shuffle(media).filter(media => media.bannerImage || media.trailer?.id).slice(0, 5)
}
</script>
<div class='w-full h-450 position-relative'>
<!-- really shit and hacky way of fixing scroll position jumping when banner changes height -->
<div class='position-absolute top-0 transparent h-450 opacity-0'>.</div>
{#await data}
<SkeletonBanner />
{:then { data }}
<FullBanner mediaList={shuffleAndFilter(data.Page.media)} />
{/await}
</div>
<style>
.opacity-0 {
opacity: 0;
}
</style>

View file

@ -0,0 +1,180 @@
<script>
import { formatMap, setStatus, playMedia } from '@/modules/anime.js'
import { anilistClient } from '@/modules/anilist.js'
import { click } from '@/modules/click.js'
import { alToken } from '@/modules/settings.js'
import { Bookmark, Heart } from 'lucide-svelte'
export let mediaList
let current = mediaList[0]
async function toggleStatus () {
if (!current.mediaListEntry) {
// add
const res = await setStatus('PLANNING', {}, current)
current.mediaListEntry = res.data.SaveMediaListEntry
} else {
// delete
anilistClient.delete({ id: current.mediaListEntry.id })
current.mediaListEntry = undefined
}
}
function toggleFavourite () {
anilistClient.favourite({ id: current.id })
current.isFavourite = !current.isFavourite
}
function currentIndex () {
return mediaList.indexOf(current)
}
function schedule (index) {
return setTimeout(() => {
current = mediaList[index % mediaList.length]
timeout = schedule(index + 1)
}, 15000)
}
let timeout = schedule(currentIndex() + 1)
function setCurrent (media) {
if (current === media) return
clearTimeout(timeout)
current = media
timeout = schedule(currentIndex() + 1)
}
</script>
{#key current}
<img src={current.bannerImage || `https://i.ytimg.com/vi/${current.trailer?.id}/maxresdefault.jpg` || ''} alt='banner' class='img-cover w-full h-full position-absolute' />
{/key}
<div class='gradient-bottom h-full position-absolute top-0 w-full' />
<div class='gradient-left h-full position-absolute top-0 w-800' />
<div class='pl-20 pb-20 justify-content-end d-flex flex-column h-full banner mw-full'>
<div class='text-white font-weight-bold font-size-40 title w-800 mw-full overflow-hidden'>
{current.title.userPreferred}
</div>
<div class='details text-white text-capitalize pt-15 pb-10 d-flex w-600 mw-full'>
<span class='text-nowrap d-flex align-items-center'>
{#if current.format}
{formatMap[current.format]}
{/if}
</span>
{#if current.episodes && current.episodes !== 1}
<span class='text-nowrap d-flex align-items-center'>
{#if current.mediaListEntry?.status === 'CURRENT' && current.mediaListEntry?.progress }
{current.mediaListEntry.progress} / {current.episodes} Episodes
{:else}
{current.episodes} Episodes
{/if}
</span>
{:else if current.duration}
<span class='text-nowrap d-flex align-items-center'>
{current.duration + ' Minutes'}
</span>
{/if}
{#if current.season || current.seasonYear}
<span class='text-nowrap d-flex align-items-center'>
{[current.season?.toLowerCase(), current.seasonYear].filter(s => s).join(' ')}
</span>
{/if}
</div>
<div class='text-muted description overflow-hidden w-600 mw-full'>
{current.description?.replace(/<[^>]*>/g, '')}
</div>
<div class='details text-white text-capitalize pt-15 pb-10 d-flex w-600 mw-full'>
{#each current.genres as genre}
<span class='text-nowrap d-flex align-items-center'>
{genre}
</span>
{/each}
</div>
<div class='d-flex flex-row pb-10 w-600 mw-full'>
<button class='btn bg-dark-light px-20 shadow-none border-0'
use:click={() => playMedia(current)}>
Watch Now
</button>
<button class='btn bg-dark-light btn-square ml-10 d-flex align-items-center justify-content-center shadow-none border-0' use:click={toggleFavourite} disabled={!alToken}>
<Heart fill={current.isFavourite ? 'currentColor' : 'transparent'} size='1.5rem' />
</button>
<button class='btn bg-dark-light btn-square ml-10 d-flex align-items-center justify-content-center shadow-none border-0' use:click={toggleStatus} disabled={!alToken}>
<Bookmark fill={current.mediaListEntry ? 'currentColor' : 'transparent'} size='1.5rem' />
</button>
</div>
<div class='d-flex'>
{#each mediaList as media}
{@const active = current === media}
<div class='pt-10 pb-5 badge-wrapper' class:pointer={!active} use:click={() => setCurrent(media)}>
<div class='rounded bg-dark-light mr-10 progress-badge overflow-hidden' class:active style='height: 3px;' style:width={active ? '5rem' : '2.7rem'}>
<div class='progress-content h-full' class:bg-white={active} />
</div>
</div>
{/each}
</div>
</div>
<style>
.gradient-bottom {
background: var(--banner-gradient-bottom);
}
.gradient-left {
background: var(--banner-gradient-left);
}
.progress-badge {
transition: width .8s ease;
}
.progress-badge.active .progress-content {
animation: fill 15s linear;
}
@keyframes fill {
from {
width: 0;
}
to {
width: 100%;
}
}
.w-800 {
width: 80rem
}
.details span + span::before {
content: '•';
padding: 0 .5rem;
font-size: .6rem;
align-self: center;
white-space: normal;
color: var(--dm-muted-text-color) !important;
}
.description {
display: -webkit-box !important;
-webkit-line-clamp: 4;
-webkit-box-orient: vertical;
}
.title {
display: -webkit-box !important;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
}
img, .gradient-bottom, .gradient-left {
z-index: -1;
}
.font-size-40 {
font-size: 4rem;
}
.banner, img {
animation: fadeIn ease .8s;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
button:hover, .badge-wrapper.pointer:hover .progress-badge {
background: #292d33 !important;
}
</style>

View file

@ -0,0 +1,11 @@
<div class='pl-20 pb-20 justify-content-end d-flex flex-column h-full w-600 mw-full banner'>
<div class='h-25 skeloader bg-dark-light w-500 mb-15 rounded'><div class='skeleloader-swipe' /></div>
<div class='my-20 d-flex h-10 w-250 skeloader bg-dark-light rounded'><div class='skeleloader-swipe' /></div>
<div class='h-10 w-450 skeloader bg-dark-light rounded mb-10'><div class='skeleloader-swipe' /></div>
<div class='h-10 w-350 skeloader bg-dark-light rounded mb-10'><div class='skeleloader-swipe' /></div>
<div class='h-10 w-300 skeloader bg-dark-light rounded mb-10'><div class='skeleloader-swipe' /></div>
<div class='h-10 w-250 skeloader bg-dark-light rounded mb-10'><div class='skeleloader-swipe' /></div>
<div class='my-20 d-flex h-10 w-150 skeloader bg-dark-light rounded'><div class='skeleloader-swipe' /></div>
<div class='mb-20 h-25 w-200 skeloader bg-dark-light rounded'><div class='skeleloader-swipe' /></div>
<div class='pb-10' />
</div>

View file

@ -0,0 +1,46 @@
<script>
import SkeletonCard from './SkeletonCard.svelte'
import SmallCard from './SmallCard.svelte'
import EpisodeSkeletonCard from './EpisodeSkeletonCard.svelte'
import FullCard from './FullCard.svelte'
import EpisodeCard from './EpisodeCard.svelte'
import FullSkeletonCard from './FullSkeletonCard.svelte'
import { settings } from '@/modules/settings.js'
import { anilistClient } from '@/modules/anilist.js'
export let card
const type = card.type || $settings.cards
</script>
{#if type === 'episode'}
{#await card.data}
<EpisodeSkeletonCard />
{:then data}
{#if data}
<EpisodeCard {data} />
{/if}
{/await}
{:else if type === 'full'}
{#await card.data}
<FullSkeletonCard />
{:then media}
{#if media}
<FullCard media={anilistClient.mediaCache[media.id]} />
{/if}
{/await}
{:else} <!-- type === 'small' -->
{#await card.data}
<SkeletonCard />
{:then media}
{#if media}
<SmallCard media={anilistClient.mediaCache[media.id]} />
{/if}
{/await}
{/if}

View file

@ -0,0 +1,111 @@
<script>
import { statusColorMap } from '@/modules/anime.js'
import EpisodePreviewCard from './EpisodePreviewCard.svelte'
import { hoverClick } from '@/modules/click.js'
import { since } from '@/modules/util.js'
import { getContext } from 'svelte'
import { liveAnimeEpisodeProgress } from '@/modules/animeprogress.js'
import { anilistClient } from '@/modules/anilist.js'
import { Play } from 'lucide-svelte'
export let data
let preview = false
/** @type {import('@/modules/al.d.ts').Media | null} */
const media = data.media && anilistClient.mediaCache[data.media.id]
const episodeThumbnail = ((!media?.mediaListEntry?.status || !(media.mediaListEntry.status === 'CURRENT' && media.mediaListEntry.progress < data.episode)) && data.episodeData?.image) || media?.bannerImage || media?.coverImage.extraLarge || ' '
const view = getContext('view')
function viewMedia () {
$view = media
}
function setHoverState (state) {
preview = state
}
const progress = liveAnimeEpisodeProgress(media?.id, data?.episode)
</script>
<div class='d-flex p-20 pb-10 position-relative episode-card' use:hoverClick={[data.onclick || viewMedia, setHoverState]} on:contextmenu|preventDefault={viewMedia} role='none'>
{#if preview}
<EpisodePreviewCard {data} />
{/if}
<div class='item d-flex flex-column h-full pointer content-visibility-auto'>
<div class='image h-200 w-full position-relative rounded overflow-hidden d-flex justify-content-between align-items-end text-white' class:bg-black={episodeThumbnail === ' '}>
<img loading='lazy' src={episodeThumbnail} alt='cover' class='cover-img w-full h-full position-absolute' style:--color={media?.coverImage?.color || '#1890ff'} />
<Play class='mb-5 ml-5 pl-10 pb-10 z-10' fill='currentColor' size='3rem' />
<div class='pr-15 pb-10 font-size-16 font-weight-medium z-10'>
{#if media?.duration}
{media.duration}m
{/if}
</div>
{#if $progress > 0}
<div class='progress container-fluid position-absolute' style='height: 2px; min-height: 2px;'>
<div class='progress-bar' style='width: {$progress}%' />
</div>
{/if}
</div>
<div class='row pt-15'>
<div class='col pr-10'>
<div class='text-white font-weight-very-bold font-size-16 title overflow-hidden'>
{#if media?.mediaListEntry?.status}
<div style:--statusColor={statusColorMap[media.mediaListEntry.status]} class='list-status-circle d-inline-flex overflow-hidden mr-5' title={media.mediaListEntry.status} />
{/if}
{media?.title.userPreferred || data.parseObject.anime_title}
</div>
<div class='text-muted font-size-12 title overflow-hidden'>
{data.episodeData?.title?.en || ''}
</div>
</div>
{#if data.episode}
<div class='col-auto d-flex flex-column align-items-end text-right'>
<div class='text-white font-weight-bold'>
Episode {data.episode}
</div>
{#if data.date}
<div class='text-muted font-size-12 title overflow-hidden'>
{since(data.date)}
</div>
{:else if data.similarity}
<div class='text-muted font-size-12 title overflow-hidden'>
{Math.round(data.similarity * 100)}%
</div>
{/if}
</div>
{/if}
</div>
</div>
</div>
<style>
.episode-card:hover {
z-index: 30;
/* fixes transform scaling on click causing z-index issues */
}
.title {
display: -webkit-box;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
}
.image:after {
background: var(--episode-card-gradient);
content:'';
position:absolute;
left:0; top:0;
width:100%; height:100%;
}
.item {
animation: 0.3s ease 0s 1 load-in;
width: 36rem;
contain-intrinsic-height: 25.7rem;
}
.cover-img {
background-color: var(--color) !important;
}
.list-status-circle {
background: var(--statusColor);
height: 1.1rem;
width: 1.1rem;
border-radius: 50%;
}
</style>

View file

@ -0,0 +1,132 @@
<script>
import { statusColorMap, formatMap } from '@/modules/anime.js'
import { since } from '@/modules/util'
import { liveAnimeEpisodeProgress } from '@/modules/animeprogress.js'
import { CalendarDays, Play, Tv } from 'lucide-svelte'
export let data
/** @type {import('@/modules/al.d.ts').Media | null} */
const media = data.media
const episodeThumbnail = ((!media?.mediaListEntry?.status || !(media.mediaListEntry.status === 'CURRENT' && media.mediaListEntry.progress < data.episode)) && data.episodeData?.image) || media?.bannerImage || media?.coverImage.extraLarge || ' '
let hide = true
const progress = liveAnimeEpisodeProgress(media?.id, data?.episode)
</script>
<div class='position-absolute w-400 mh-400 absolute-container top-0 m-auto bg-dark-light z-30 rounded overflow-hidden pointer d-flex flex-column'>
<div class='image h-200 w-full position-relative d-flex justify-content-between align-items-end text-white' class:bg-black={episodeThumbnail === ' '}>
<img loading='lazy' src={episodeThumbnail} alt='cover' class='img-cover w-full h-full position-absolute' style:--color={media?.coverImage.color || '#1890ff'} />
{#if data.episodeData?.video}
<video src={data.episodeData.video}
class='w-full position-absolute left-0'
class:d-none={hide}
playsinline
preload='none'
loop
muted
on:loadeddata={() => { hide = false }}
autoplay />
{/if}
<Play class='mb-5 ml-5 pl-10 pb-10 z-10' fill='currentColor' size='3rem' />
<div class='pr-20 pb-10 font-size-16 font-weight-medium z-10'>
{#if media?.duration}
{media.duration}m
{/if}
</div>
{#if $progress > 0}
<div class='progress container-fluid position-absolute mb-5'>
<div class='progress-bar' style='width: {$progress}%' />
</div>
{/if}
</div>
<div class='w-full d-flex flex-column flex-grow-1 px-20 pb-15'>
<div class='row pt-15'>
<div class='col pr-10'>
<div class='text-white font-weight-very-bold font-size-16 title overflow-hidden' title={data.media?.title.userPreferred || data.parseObject.anime_title}>
{#if media?.mediaListEntry?.status}
<div style:--statusColor={statusColorMap[media.mediaListEntry.status]} class='list-status-circle d-inline-flex overflow-hidden mr-5' title={media.mediaListEntry.status} />
{/if}
{data.media?.title.userPreferred || data.parseObject.anime_title}
</div>
<div class='text-muted font-size-12 title overflow-hidden' title={data.episodeData?.title?.en}>
{data.episodeData?.title?.en || ''}
</div>
</div>
{#if data.episode}
<div class='col-auto d-flex flex-column align-items-end text-right'>
<div class='text-white font-weight-bold'>
Episode {data.episode}
</div>
{#if data.date}
<div class='text-muted font-size-12 title overflow-hidden'>
{since(data.date)}
</div>
{:else if data.similarity}
<div class='text-muted font-size-12 title overflow-hidden'>
{Math.round(data.similarity * 100)}%
</div>
{/if}
</div>
{/if}
</div>
<div class='w-full text-muted description overflow-hidden pt-15'>
{data.episodeData?.description || media?.description?.replace(/<[^>]*>/g, '') || ''}
</div>
{#if media}
<div class='d-flex flex-row pt-15 font-weight-medium justify-content-between w-full text-muted'>
<div class='d-flex align-items-center' style='margin-left: -2px'>
<CalendarDays class='pr-5' size='2.6rem' />
<span class='line-height-1'>{media.seasonYear || 'N/A'}</span>
</div>
<div class='d-flex align-items-center'>
<span class='line-height-1'>{formatMap[media.format]}</span>
<Tv class='pl-5' size='2.6rem' />
</div>
</div>
{/if}
</div>
</div>
<style>
.description {
display: -webkit-box !important;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
}
@keyframes load-in {
from {
top: 1.2rem;
opacity: 0;
transform: scale(0.95);
}
to {
top: 0;
opacity: 1;
transform: scale(1);
}
}
.absolute-container {
animation: 0.3s ease 0s 1 load-in;
left: -100%;
right: -100%;
}
.title {
display: -webkit-box;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
}
.image:after {
content: '';
position: absolute;
left: 0 ; bottom: 0;
width: 100%; height: 100%;
background: var(--episode-preview-card-gradient);
}
.list-status-circle {
background: var(--statusColor);
height: 1.1rem;
width: 1.1rem;
border-radius: 50%;
}
</style>

View file

@ -0,0 +1,25 @@
<div class='d-flex p-20 pb-10 position-relative wrapper content-visibility-auto'>
<div class='item d-flex flex-column h-full'>
<div class='image h-200 w-full rounded skeloader bg-dark-light'><div class='skeleloader-swipe' /></div>
<div class='row pt-15'>
<div class='col-7'>
<div class='h-10 skeloader w-150 bg-dark-light rounded '><div class='skeleloader-swipe' /></div>
</div>
<div class='col-5 d-flex flex-column align-items-end'>
<div class='h-10 skeloader w-100 bg-dark-light mb-5 rounded'><div class='skeleloader-swipe' /></div>
<div class='h-10 skeloader w-50 bg-dark-light rounded'><div class='skeleloader-swipe' /></div>
</div>
</div>
</div>
</div>
<style>
.item {
animation: 0.3s ease 0s 1 load-in;
width: 36rem
}
.wrapper {
height: 28.7rem;
contain-intrinsic-height: 28.7rem;
}
</style>

View file

@ -0,0 +1,32 @@
<script>
export let promise
</script>
{#await promise then data}
{#if !data}
<div class='p-20 d-flex align-items-center justify-content-center w-full' style='height:35rem;'>
<div>
<h1 class='mb-5 text-white font-weight-bold text-center'>
Ooops!
</h1>
<div class='font-size-20 text-center text-muted'>
Looks like there's nothing here.
</div>
</div>
</div>
{/if}
{:catch error}
<div class='p-20 d-flex align-items-center justify-content-center w-full' style='height:35rem;'>
<div>
<h1 class='mb-5 text-white font-weight-bold text-center'>
Ooops!
</h1>
<div class='font-size-20 text-center text-muted'>
Looks like something went wrong!.
</div>
<div class='font-size-20 text-center text-muted'>
{error.message}
</div>
</div>
</div>
{/await}

View file

@ -0,0 +1,123 @@
<script>
import { getContext } from 'svelte'
import { formatMap, statusColorMap } from '@/modules/anime.js'
import { click } from '@/modules/click.js'
import { countdown } from '@/modules/util.js'
import { page } from '@/App.svelte'
/** @type {import('@/modules/al.d.ts').Media} */
export let media
const view = getContext('view')
function viewMedia () {
$view = media
}
</script>
<div class='d-flex px-20 py-10 position-relative justify-content-center' use:click={viewMedia}>
<div class='card m-0 p-0 overflow-hidden pointer content-visibility-auto full-card'
style:--color={media.coverImage.color || '#1890ff'}>
<div class='row h-full'>
<div class='col-4 img-col'>
<img loading='lazy' src={media.coverImage.extraLarge || ''} alt='cover' class='cover-img w-full h-full' />
</div>
<div class='col h-full card-grid'>
<div class='px-15 py-10 bg-very-dark'>
<h5 class='m-0 text-white text-capitalize font-weight-bold'>
{#if media.mediaListEntry?.status}
<div style:--statusColor={statusColorMap[media.mediaListEntry.status]} class='list-status-circle d-inline-flex overflow-hidden mr-5' title={media.mediaListEntry.status} />
{/if}
{media.title.userPreferred}
</h5>
{#if $page === 'schedule'}
<div class='py-5'>
{#if media.airingSchedule?.nodes?.[0]?.airingAt}
Episode {media.airingSchedule.nodes[0].episode } in
<span class='font-weight-bold text-light'>
{countdown(media.airingSchedule.nodes[0].airingAt - Date.now() / 1000)}
</span>
{:else}
&nbsp;
{/if}
</div>
{/if}
<p class='text-muted m-0 text-capitalize details'>
<span class='text-nowrap'>
{#if media.format === 'TV'}
TV Show
{:else if media.format}
{formatMap[media.format]}
{/if}
</span>
{#if media.episodes && media.episodes !== 1}
<span class='text-nowrap'>
{#if media.mediaListEntry?.status === 'CURRENT' && media.mediaListEntry?.progress }
{media.mediaListEntry.progress} / {media.episodes} Episodes
{:else}
{media.episodes} Episodes
{/if}
</span>
{:else if media.duration}
<span class='text-nowrap'>{media.duration + ' Minutes'}</span>
{/if}
{#if media.status}
<span class='text-nowrap'>{media.status?.toLowerCase().replace(/_/g, ' ')}</span>
{/if}
{#if media.season || media.seasonYear}
<span class='text-nowrap'>
{[media.season?.toLowerCase(), media.seasonYear].filter(s => s).join(' ')}
</span>
{/if}
</p>
</div>
<div class='overflow-y-auto px-15 pb-5 bg-very-dark card-desc pre-wrap'>
{media.description?.replace(/<[^>]*>/g, '') || ''}
</div>
{#if media.genres.length}
<div class='px-15 pb-10 pt-5 genres'>
{#each media.genres.slice(0, 3) as genre}
<span class='badge badge-pill badge-color text-dark mt-5 mr-5 font-weight-bold'>{genre}</span>
{/each}
</div>
{/if}
</div>
</div>
</div>
</div>
<style>
.pre-wrap {
white-space: pre-wrap
}
.details span + span::before {
content: ' • ';
white-space: normal;
}
.card {
animation: 0.3s ease 0s 1 load-in;
width: 52rem !important;
height: 27rem !important;
box-shadow: rgba(0, 4, 12, 0.3) 0px 7px 15px, rgba(0, 4, 12, 0.05) 0px 4px 4px;
contain-intrinsic-height: 27rem;
transition: transform 0.2s ease;
}
.card:hover{
transform: scale(1.05);
}
.card-grid {
display: grid;
grid-template-rows: auto 1fr auto;
}
.badge-color {
background-color: var(--color) !important;
border-color: var(--color) !important;
}
.cover-img {
background-color: var(--color) !important;
}
.list-status-circle {
background: var(--statusColor);
height: 1.1rem;
width: 1.1rem;
border-radius: 50%;
}
</style>

View file

@ -0,0 +1,21 @@
<div class='d-flex px-20 py-10 position-relative content-visibility-auto justify-content-center'>
<div class='card m-0 p-0 overflow-hidden full-card'>
<div class='row h-full'>
<div class='col-4 skeloader bg-dark-light'><div class='skeleloader-swipe' /></div>
<div class='col-8 bg-very-dark px-15 py-10'>
<div class='skeloader bg-dark-light w-300 h-25 rounded bg-dark mt-15'><div class='skeleloader-swipe' /></div>
<div class='skeloader bg-dark-light w-150 h-10 rounded bg-dark mt-15'><div class='skeleloader-swipe' /></div>
<div class='skeloader bg-dark-light w-150 h-10 rounded bg-dark mt-15'><div class='skeleloader-swipe' /></div>
</div>
</div>
</div>
</div>
<style>
.card {
animation: 0.3s ease 0s 1 load-in;
width: 50rem !important;
height: 27rem !important;
contain-intrinsic-height: 27rem;
}
</style>

View file

@ -0,0 +1,196 @@
<script>
import { formatMap, setStatus, playMedia } from '@/modules/anime.js'
import { anilistClient } from '@/modules/anilist.js'
import { click } from '@/modules/click.js'
import { alToken } from '@/modules/settings.js'
import { Bookmark, Heart, Play, VolumeX, Volume2 } from 'lucide-svelte'
/** @type {import('@/modules/al.d.ts').Media} */
export let media
let hide = true
/**
* @param {import('@/modules/al.d.ts').Media} media
*/
function getPlayButtonText (media) {
if (media.mediaListEntry) {
const { status, progress } = media.mediaListEntry
if (progress) {
if (status === 'COMPLETED') {
return 'Rewatch Now'
} else {
return 'Continue Now'
}
}
}
return 'Watch Now'
}
const playButtonText = getPlayButtonText(media)
async function toggleStatus () {
if (!media.mediaListEntry) {
// add
const res = await setStatus('PLANNING', {}, media)
media.mediaListEntry = res.data.SaveMediaListEntry
} else {
// delete
anilistClient.delete({ id: media.mediaListEntry.id })
media.mediaListEntry = undefined
}
}
function toggleFavourite () {
anilistClient.favourite({ id: media.id })
media.isFavourite = !media.isFavourite
}
function play () {
if (media.status === 'NOT_YET_RELEASED') return
playMedia(media)
}
let muted = true
function toggleMute () {
muted = !muted
}
</script>
<div class='position-absolute w-350 h-400 absolute-container top-0 bottom-0 m-auto bg-dark-light z-30 rounded overflow-hidden pointer'>
<div class='banner position-relative bg-black overflow-hidden'>
<img src={media.bannerImage || `https://i.ytimg.com/vi/${media.trailer?.id}/hqdefault.jpg` || ' '} alt='banner' class='img-cover w-full h-full' />
{#if media.trailer?.id}
<div class='position-absolute z-10 top-0 right-0 p-15' use:click={toggleMute}>
{#if muted}
<VolumeX size='2.2rem' fill='currentColor' />
{:else}
<Volume2 size='2.2rem' fill='currentColor' />
{/if}
</div>
<!-- indivious is nice because its faster, but not reliable -->
<!-- <video src={`https://inv.tux.pizza/latest_version?id=${media.trailer.id}&itag=18`}
class='w-full h-full position-absolute left-0'
class:d-none={hide}
playsinline
preload='none'
loop
use:volume
bind:muted
on:loadeddata={() => { hide = false }}
autoplay /> -->
<iframe
class='w-full border-0 position-absolute left-0'
class:d-none={hide}
title={media.title.userPreferred}
allow='autoplay'
on:load={() => { hide = false }}
src={`https://www.youtube-nocookie.com/embed/${media.trailer?.id}?autoplay=1&controls=0&mute=${muted ? 1 : 0}&disablekb=1&loop=1&vq=medium&playlist=${media.trailer?.id}&cc_lang_pref=ja`}
/>
{/if}
</div>
<div class='w-full px-20'>
<div class='font-size-24 font-weight-bold text-truncate d-inline-block w-full text-white' title={media.title.userPreferred}>
{media.title.userPreferred}
</div>
<div class='d-flex flex-row pt-5'>
<button class='btn btn-secondary flex-grow-1 text-dark font-weight-bold shadow-none border-0 d-flex align-items-center justify-content-center'
use:click={play}
disabled={media.status === 'NOT_YET_RELEASED'}>
<Play class='pr-10 z-10' fill='currentColor' size='2.2rem' />
{playButtonText}
</button>
<button class='btn btn-square ml-10 d-flex align-items-center justify-content-center shadow-none border-0' use:click={toggleFavourite} disabled={!alToken}>
<Heart fill={media.isFavourite ? 'currentColor' : 'transparent'} size='1.5rem' />
</button>
<button class='btn btn-square ml-10 d-flex align-items-center justify-content-center shadow-none border-0' use:click={toggleStatus} disabled={!alToken}>
<Bookmark fill={media.mediaListEntry ? 'currentColor' : 'transparent'} size='1.5rem' />
</button>
</div>
<div class='details text-white text-capitalize pt-15 pb-10 d-flex'>
<span class='text-nowrap d-flex align-items-center'>
{#if media.format}
{formatMap[media.format]}
{/if}
</span>
{#if media.episodes && media.episodes !== 1}
<span class='text-nowrap d-flex align-items-center'>
{#if media.mediaListEntry?.status === 'CURRENT' && media.mediaListEntry?.progress }
{media.mediaListEntry.progress} / {media.episodes} Episodes
{:else}
{media.episodes} Episodes
{/if}
</span>
{:else if media.duration}
<span class='text-nowrap d-flex align-items-center'>
{media.duration + ' Minutes'}
</span>
{/if}
{#if media.season || media.seasonYear}
<span class='text-nowrap d-flex align-items-center'>
{[media.season?.toLowerCase(), media.seasonYear].filter(s => s).join(' ')}
</span>
{/if}
</div>
<div class='w-full h-full text-muted description overflow-hidden'>
{media.description?.replace(/<[^>]*>/g, '')}
</div>
</div>
</div>
<style>
.description {
display: -webkit-box !important;
-webkit-line-clamp: 4;
-webkit-box-orient: vertical;
}
.details span + span::before {
content: '•';
padding: 0 .5rem;
font-size: .6rem;
align-self: center;
white-space: normal;
color: var(--dm-muted-text-color) !important;
}
.banner {
height: 45%
}
/* video {
object-fit: cover;
} */
.banner::after {
content: '';
position: absolute;
left: 0 ; bottom: 0;
margin-bottom: -1px;
width: 100%; height: 100% ;
background: var(--preview-card-gradient);
}
@keyframes load-in {
from {
bottom: -1.2rem;
opacity: 0;
transform: scale(0.95);
}
to {
bottom: 0;
opacity: 1;
transform: scale(1);
}
}
.absolute-container {
animation: 0.3s ease 0s 1 load-in;
left: -100%;
right: -100%;
}
@keyframes delayedShow {
to {
visibility: visible;
}
}
iframe {
height: 200%;
top: 50%;
transform: translate(0, -50%);
visibility: hidden;
animation: 0s linear 0.5s forwards delayedShow;
}
</style>

View file

@ -0,0 +1,19 @@
<div class='d-flex p-md-20 p-15 wrapper content-visibility-auto'>
<div class='item d-flex flex-column h-full small-card'>
<div class='img w-full rounded skeloader bg-dark-light'><div class='skeleloader-swipe' /></div>
<div class='skeloader rounded bg-dark-light h-10 w-150 mt-15'><div class='skeleloader-swipe' /></div>
<div class='skeloader rounded bg-dark-light h-10 w-100 mt-15'><div class='skeleloader-swipe' /></div>
</div>
</div>
<style>
.img {
width: 100%;
aspect-ratio: 230/331;
}
.item {
animation: 0.3s ease 0s 1 load-in;
width: 100%;
aspect-ratio: 152/296;
}
</style>

View file

@ -0,0 +1,90 @@
<script>
import { getContext } from 'svelte'
import PreviewCard from './PreviewCard.svelte'
import { formatMap, statusColorMap } from '@/modules/anime.js'
import { hoverClick } from '@/modules/click.js'
import { countdown } from '@/modules/util.js'
import { page } from '@/App.svelte'
import { CalendarDays, Tv } from 'lucide-svelte'
/** @type {import('@/modules/al.d.ts').Media} */
export let media
let preview = false
const view = getContext('view')
function viewMedia () {
$view = media
}
function setHoverState (state) {
preview = state
}
</script>
<div class='d-flex p-md-20 p-15 position-relative first-check' use:hoverClick={[viewMedia, setHoverState]}>
{#if preview}
<PreviewCard {media} />
{/if}
<div class='item small-card d-flex flex-column h-full pointer content-visibility-auto'>
{#if $page === 'schedule'}
<div class='w-full text-center pb-10'>
{#if media.airingSchedule?.nodes?.[0]?.airingAt}
Episode {media.airingSchedule.nodes[0].episode } in
<span class='font-weight-bold text-light'>
{countdown(media.airingSchedule.nodes[0].airingAt - Date.now() / 1000)}
</span>
{:else}
&nbsp;
{/if}
</div>
{/if}
<img loading='lazy' src={media.coverImage.extraLarge || ''} alt='cover' class='cover-img w-full rounded' style:--color={media.coverImage.color || '#1890ff'} />
<div class='text-white font-weight-very-bold font-size-16 pt-15 title overflow-hidden'>
{#if media.mediaListEntry?.status}
<div style:--statusColor={statusColorMap[media.mediaListEntry.status]} class='list-status-circle d-inline-flex overflow-hidden mr-5' title={media.mediaListEntry.status} />
{/if}
{media.title.userPreferred}
</div>
<div class='d-flex flex-row mt-auto pt-10 font-weight-medium justify-content-between w-full text-muted'>
<div class='d-flex align-items-center pr-5' style='margin-left: -1px'>
<CalendarDays class='pr-5' size='2.6rem' />
<span class='line-height-1'>{media.seasonYear || 'N/A'}</span>
</div>
<div class='d-flex align-items-center text-nowrap text-right'>
<span class='line-height-1'>{formatMap[media.format]}</span>
<Tv class='pl-5' size='2.6rem' />
</div>
</div>
</div>
</div>
<style>
.first-check:hover {
z-index: 30;
/* fixes transform scaling on click causing z-index issues */
}
.title {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
img {
width: 100%;
aspect-ratio: 230/331;
}
.item {
animation: 0.3s ease 0s 1 load-in;
width: 100%;
aspect-ratio: 152/296;
}
.cover-img {
background-color: var(--color) !important;
}
.list-status-circle {
background: var(--statusColor);
height: 1.1rem;
width: 1.1rem;
border-radius: 50%;
}
</style>

251
common/css.css Normal file
View file

@ -0,0 +1,251 @@
:root {
--accent-color: #e5204c;
--dm-link-text-color: var(--dm-muted-text-color) !important;
--dm-link-text-color-hover: var(--dm-text-color) !important;
--base-html-font-size: 50%;
--base-html-font-size-1600: 50%;
--base-html-font-size-1920: 62.5%;
--tooltip-width: 17rem;
--card-border-width: 0;
--sidebar-border-width: 0;
--input-border-width: 0;
--sidebar-minimised: 0px;
--sidebar-width: 0px;
--navbar-height: 7rem;
--dark-color-base-hue: 220deg !important;
--dark-color-base-saturation: 10% !important;
--dark-color-hsl: var(--dark-color-base-hue), var(--dark-color-base-saturation), 10% !important;
--dark-color-light: #25292F !important;
--dm-shadow: 0px 4px 7px rgba(0, 0, 0, 0.25);
--dm-input-border-color: none;
--gray-color-light: hsl(var(--gray-color-light-hsl));
--gray-color-light-hsl: var(--gray-color-base-hue), 10%, 28%;
--gray-color-base-hue: 216;
--safe-area-top: 0px;
--safe-area-left: 0px;
--sidebar-gradient: linear-gradient(90deg, #17191D 15.62%, rgba(23, 25, 29, 0.92) 36.46%, rgba(23, 25, 29, 0.619632) 70.83%, rgba(23, 25, 29, 0) 100%);
--banner-gradient-bottom: linear-gradient(0deg, #17191D 0%, #0000 15%, #0000 100%);
--banner-gradient-left: linear-gradient(90deg, #17191D 0%, rgba(23, 25, 29, 0.5) 75%, rgba(25, 28, 32, 0) 100%);
--torrent-card-gradient: linear-gradient(90deg, #17191C 32%, rgba(23, 25, 28, 0.90) 100%);
--episode-card-gradient: linear-gradient(180deg, rgba(0, 0, 0, 0) 77.08%, rgba(0, 0, 0, 0.7) 100%);
--episode-preview-card-gradient: linear-gradient(180deg, #0000 0%, #25292f00 80%, #25292f 95%, #25292f 100%);
--preview-card-gradient: linear-gradient(180deg, #0000 0%, #25292f00 80%, #25292fe3 95%, #25292f 100%);
--section-end-gradient: linear-gradient(270deg, #17191cff 0%, #17191c00 100%);
color-scheme: dark;
}
@font-face {
font-family: "Roboto";
src: /* webpackIgnore: true */ url(Roboto.ttf) format("truetype");
unicode-range: U+0000, U+0002, U+0009, U+000D, U+0020-007E, U+00A0-0377,
U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03E1,
U+03F0-052F, U+1AB0-1ABE, U+1D00-1DF5, U+1DFC-1F15, U+1F18-1F1D,
U+1F20-1F45, U+1F48-1F4D, U+1F50-1F57, U+1F59, U+1F5B, U+1F5D,
U+1F5F-1F7D, U+1F80-1FB4, U+1FB6-1FC4, U+1FC6-1FD3, U+1FD6-1FDB,
U+1FDD-1FEF, U+1FF2-1FF4, U+1FF6-1FFE, U+2000-2027, U+202F-205F,
U+2070-2071, U+2074-208E, U+2090-209C, U+20A0-20BE, U+20DB-20DC,
U+20E3, U+20E8, U+20F0, U+2100-2101, U+2103, U+2105-2106, U+2109,
U+2113, U+2116-2117, U+211E-2123, U+2125-2126, U+212A-212B, U+212E,
U+2132, U+213B, U+214D, U+214F-2189, U+2191, U+2193, U+2202, U+2206,
U+220F, U+2211-2212, U+221A, U+221E, U+222B, U+2248, U+2260,
U+2264-2265, U+2423, U+25CA, U+2669-266F, U+27E6-27EF, U+2B4E-2B4F,
U+2B5A-2B5F, U+2C60-2C7F, U+2DE0-2E42, U+A640-A69D, U+A69F,
U+A700-A7AD, U+A7B0-A7B1, U+A7F7-A7FF, U+A92E, U+AB30-AB5F,
U+AB64-AB65, U+EE01-EE02, U+F6C3, U+FB00-FB06, U+FE20-FE2D, U+FEFF,
U+FFFC-FFFD, U+1F16A-1F16B;
}
.dark-mode {
background-color: var(--dark-color) !important;
}
.h-30 {
width: 3rem;
height: 3rem;
}
@media (min-width: 769px) {
:root {
--sidebar-minimised: 7rem;
--sidebar-width: 7rem;
--navbar-height: 0px;
}
}
.line-height-1 {
line-height: 1;
}
.line-height-normal {
line-height: normal;
}
* {
-webkit-tap-highlight-color: transparent;
}
a[href]:active, button:not([disabled]):active, fieldset:not([disabled]):active, input:not([disabled], [type='range']):active, optgroup:not([disabled]):active, option:not([disabled]):active, select:not([disabled]):active, textarea:not([disabled]):active, details:active, [tabindex]:not([tabindex="-1"], .seekbar, .dropdown):active, [contenteditable]:active, [controls]:active {
transition: transform 0.1s ease-in-out;
transform: scale(0.95) !important;
}
.btn-secondary {
--dm-button-secondary-bg-color: #fff !important;
--dm-button-secondary-bg-color-hover: #ddd !important;
--dm-button-secondary-bg-color-focus: var(--dm-button-secondary-bg-color) !important;
}
[data-sonner-toaster][data-theme='dark'] {
--normal-bg: var(--dark-color) !important;
--normal-border: none !important;
--normal-text: var(--dm-base-text-color) !important;
/* --success-bg: var(--success-color) !important; */
--success-border: none !important;
/* --success-text: var(--lm-base-text-color) !important; */
/* --error-bg: hsl(358, 76%, 10%); */
--error-border: none !important;
/* --error-text: hsl(358, 100%, 81%); */
}
[data-sonner-toaster] [data-description] {
white-space: pre-wrap;
}
.z-100 {
z-index: 100;
}
.text-dark-light {
color: var(--gray-color-light);
}
.pointer {
cursor: pointer;
}
.h-10 {
height: 1rem !important;
}
.h-25 {
height: 2.5rem !important;
}
body {
scroll-behavior: smooth;
overscroll-behavior: none;
user-select: none;
font-family: 'Nunito Variable'
}
.font-weight-very-bold {
font-weight: 900;
}
.bg-black {
background: #000;
}
.btn:disabled {
opacity: 0.3 !important;
}
img {
-webkit-user-drag: none;
}
.select-all {
user-select: all;
}
img[src=''], img[src=' '] {
display: none;
}
::-webkit-inner-spin-button {
display: none;
}
*:focus-visible {
outline: none;
border-radius: 5px;
box-shadow: inset 0 0 0 1.5px #eee !important;
}
.btn-secondary:focus-visible {
box-shadow: inset 0 0 0 1.5px #000 !important;
}
.modal:focus-visible {
box-shadow: none !important;
}
.root {
animation: 0.3s ease 0s 1 load-in;
}
.content-visibility-auto {
content-visibility: auto;
}
.nav-hidden > .content-wrapper {
left: 0 !important;
width: 100% !important;
}
@keyframes skeleloader {
from {
background-position-x: 200%;
}
to {
background-position-x: -100%;
}
}
@keyframes load-in {
from {
transform: translateY(1.2rem) scale(0.95);
}
to {
transform: none
}
}
.skeloader {
position: relative;
overflow: hidden;
}
.skeloader .skeleloader-swipe {
height: 100%;
width: 100%;
background: linear-gradient(to right, transparent 0%, hsl(var(--dark-color-hsl)) 50%, transparent 100%);
background-repeat: no-repeat;
background-size: 200% 100%;
animation: skeleloader 1s infinite cubic-bezier(0.4, 0, 0.2, 1);
}
.align-content-start {
align-content: start;
}
.cover-img {
object-fit: cover;
}
.pre-wrap {
white-space: pre-wrap
}
.px-50 {
padding-left: 5rem;
padding-right: 5rem;
}
@media (min-width: 769px) {
.px-md-50 {
padding-left: 5rem !important;
padding-right: 5rem !important;
}
}

27
common/jsconfig.json Normal file
View file

@ -0,0 +1,27 @@
{
"compilerOptions": {
"checkJs": true,
"target": "ESNext",
"moduleResolution": "node",
"module": "ESNext",
"allowSyntheticDefaultImports": true,
"verbatimModuleSyntax": true,
"isolatedModules": true,
"resolveJsonModule": true,
"sourceMap": true,
"esModuleInterop": true,
"skipLibCheck": true,
"types": ["./types.d.ts"],
"baseUrl": "./",
"paths": {
"@/*": ["./*"],
"three": ["./types.d.ts"],
"rxjs": ["./types.d.ts"],
},
},
"exclude": [
"node_modules", "dist", "build", "git_modules", ".svelte-kit", "public", "android", "@types/three",
"**/node_modules", "**/dist", "**/build", "**/git_modules", "**/.svelte-kit", "**/public", "**/android", "**/@types/three",
"**/node_modules/*", "**/dist/*", "**/build/*", "**/git_modules/*", "**/.svelte-kit/*", "**/public/*", "**/android/*", "**@types/three/*.d.ts"
]
}

6
common/main.js Normal file
View file

@ -0,0 +1,6 @@
import App from './App.svelte'
import 'quartermoon/css/quartermoon-variables.css'
import '@fontsource-variable/nunito'
import './css.css'
export default new App({ target: document.body })

181
common/modules/al.d.ts vendored Normal file
View file

@ -0,0 +1,181 @@
export type Media = {
id: number
title: {
romaji?: string
english?: string
native?: string
userPreferred: string
}
description?: string
season?: string
seasonYear?: string
format: string
status: string
episodes?: number
duration?: number
averageScore?: number
genres?: string[]
isFavourite: boolean
coverImage?: {
extraLarge: string
color: string
medium: string
}
source?: string
countryOfOrigin?: string
isAdult?: boolean
bannerImage?: string
synonyms?: string[]
nextAiringEpisode?: {
episode: number
airingAt: number
}
startDate?: {
year: number
month?: number
day?: number
}
trailer?: {
id: string
site: string
}
streamingEpisodes?: {
title: string
thumbnail: string
}[]
mediaListEntry?: {
id: number
progress: number
repeat: number
status?: string
customLists?: string[]
score?: number
}
studios?: {
edges: {
node: {
name: string
}
}[]
}
airingSchedule?: {
nodes?: {
episode: number
airingAt: number
}[]
}
relations?: {
edges: {
relationType: string
node: {
id: number
title: {
userPreferred: string
}
type: string
status: string
format?: string
episodes?: number
synonyms?: string[]
season?: string
seasonYear?: number
startDate?: {
year: number
month?: number
day?: number
}
endDate?: {
year: number
month: number
day: number
}
}
}[]
}
// recommendations?: {
// edges?: {
// node: {
// media: {
// id: number
// title: {
// userPreferred: string
// }
// coverImage?: {
// medium: string
// }
// }
// }
// }[]
// }
}
export type Following = {
status: string
score: number
progress: number
user: {
name: string
avatar: {
medium: string
}
}
}
export type MediaListMedia = {
id: number
status: string
mediaListEntry: {
progress: number
}
nextAiringEpisode?: {
episode: number
}
relations?: {
edges: {
relationType: string
node: {
id: number
}
}[]
}
}
export type MediaListCollection = {
lists: {
status: string
entries: {
media: MediaListMedia
}[]
}[]
}
export type Viewer = {
avatar: {
medium: string
}
name: string
id: number
mediaListOptions?: {
animeList?: {
customLists?: string[]
}
}
}
export type Query<T> = {
data: T
}
export type PagedQuery<T> = Query<{
Page: {
pageInfo: {
total: number
perPage: number
currentPage: number
lastPage: number
hasNextPage: boolean
}
} & T
}>
// TODO: error responses and nullish values

759
common/modules/anilist.js Normal file
View file

@ -0,0 +1,759 @@
import lavenshtein from 'js-levenshtein'
import { writable } from 'simple-store-svelte'
import Bottleneck from 'bottleneck'
import { alToken } from '@/modules/settings.js'
import { toast } from 'svelte-sonner'
import { sleep } from './util.js'
import IPC from '@/modules/ipc.js'
import Debug from 'debug'
const debug = Debug('ui:anilist')
const codes = {
400: 'Bad Request',
401: 'Unauthorized',
402: 'Payment Required',
403: 'Forbidden',
404: 'Not Found',
406: 'Not Acceptable',
408: 'Request Time-out',
409: 'Conflict',
410: 'Gone',
412: 'Precondition Failed',
413: 'Request Entity Too Large',
429: 'Too Many Requests',
500: 'Internal Server Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Gateway Time-out',
505: 'HTTP Version Not Supported',
506: 'Variant Also Negotiates',
507: 'Insufficient Storage',
509: 'Bandwidth Limit Exceeded',
510: 'Not Extended',
511: 'Network Authentication Required'
}
function printError (error) {
debug(`Error: ${error.status || 429} - ${error.message || codes[error.status || 429]}`)
toast.error('Search Failed', {
description: `Failed making request to anilist!\nTry again in a minute.\n${error.status || 429} - ${error.message || codes[error.status || 429]}`,
duration: 3000
})
}
const date = new Date()
export const currentSeason = ['WINTER', 'SPRING', 'SUMMER', 'FALL'][Math.floor((date.getMonth() / 12) * 4) % 4]
export const currentYear = date.getFullYear()
/**
* @param {import('./al.d.ts').Media & {lavenshtein?: number}} media
* @param {string} name
*/
function getDistanceFromTitle (media, name) {
if (media) {
const titles = Object.values(media.title).filter(v => v).map(title => lavenshtein(title.toLowerCase(), name.toLowerCase()))
const synonyms = media.synonyms.filter(v => v).map(title => lavenshtein(title.toLowerCase(), name.toLowerCase()) + 2)
const distances = [...titles, ...synonyms]
const min = distances.reduce((prev, curr) => prev < curr ? prev : curr)
media.lavenshtein = min
return media
}
}
const queryObjects = /* js */`
id,
idMal,
title {
romaji,
english,
native,
userPreferred
},
description(asHtml: false),
season,
seasonYear,
format,
status,
episodes,
duration,
averageScore,
genres,
isFavourite,
coverImage {
extraLarge,
medium,
color
},
source,
countryOfOrigin,
isAdult,
bannerImage,
synonyms,
nextAiringEpisode {
timeUntilAiring,
episode
},
startDate {
year,
month,
day
},
trailer {
id,
site
},
streamingEpisodes {
title,
thumbnail
},
mediaListEntry {
id,
progress,
repeat,
status,
customLists(asArray: true),
score(format: POINT_10)
},
studios(isMain: true) {
nodes {
name
}
},
airingSchedule(page: 1, perPage: 1, notYetAired: true) {
nodes {
episode,
airingAt
}
},
relations {
edges {
relationType(version:2),
node {
id,
title {userPreferred},
coverImage {medium},
type,
status,
format,
episodes,
synonyms,
season,
seasonYear,
startDate {
year,
month,
day
},
endDate {
year,
month,
day
}
}
}
}`
// recommendations {
// edges {
// node {
// mediaRecommendation {
// id,
// title {
// userPreferred
// },
// coverImage {
// medium
// }
// }
// }
// }
// }
class AnilistClient {
limiter = new Bottleneck({
reservoir: 90,
reservoirRefreshAmount: 90,
reservoirRefreshInterval: 60 * 1000,
maxConcurrent: 10,
minTime: 100
})
rateLimitPromise = null
/** @type {import('simple-store-svelte').Writable<ReturnType<AnilistClient['getUserLists']>>} */
userLists = writable()
userID = alToken
/** @type {Record<number, import('./al.d.ts').Media>} */
mediaCache = {}
lastNotificationDate = Date.now() / 1000
constructor () {
debug('Initializing Anilist Client for ID ' + this.userID?.viewer?.data?.Viewer.id)
this.limiter.on('failed', async (error, jobInfo) => {
printError(error)
if (error.status === 500) return 1
if (!error.statusText) {
if (!this.rateLimitPromise) this.rateLimitPromise = sleep(61 * 1000).then(() => { this.rateLimitPromise = null })
return 61 * 1000
}
const time = ((error.headers.get('retry-after') || 60) + 1) * 1000
if (!this.rateLimitPromise) this.rateLimitPromise = sleep(time).then(() => { this.rateLimitPromise = null })
return time
})
if (this.userID?.viewer?.data?.Viewer) {
this.userLists.value = this.getUserLists()
// update userLists every 15 mins
setInterval(() => { this.userLists.value = this.getUserLists() }, 1000 * 60 * 15)
// check notifications every 5 mins
setInterval(() => { this.findNewNotifications() }, 1000 * 60 * 5)
}
}
/** @type {(options: RequestInit) => Promise<any>} */
handleRequest = this.limiter.wrap(async opts => {
await this.rateLimitPromise
let res = {}
try {
res = await fetch('https://graphql.anilist.co', opts)
} catch (e) {
if (!res || res.status !== 404) throw e
}
if (!res.ok && (res.status === 429 || res.status === 500)) {
throw res
}
let json = null
try {
json = await res.json()
} catch (error) {
if (res.ok) printError(error)
}
if (!res.ok && res.status !== 404) {
if (json) {
for (const error of json?.errors || []) {
printError(error)
}
} else {
printError(res)
}
}
return json
})
/**
* @param {string} query
* @param {Record<string, any>} variables
*/
alRequest (query, variables) {
/** @type {RequestInit} */
const options = {
method: 'POST',
credentials: 'omit',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
query: query.replace(/\s/g, '').replaceAll('&nbsp;', ' '),
variables: {
page: 1,
perPage: 30,
status_in: '[CURRENT,PLANNING]',
...variables
}
})
}
// @ts-ignore
if (alToken?.token) options.headers.Authorization = alToken.token
return this.handleRequest(options)
}
async alSearch (method) {
const res = await this.searchName(method)
const media = res.data.Page.media.map(media => getDistanceFromTitle(media, method.name))
if (!media.length) return null
return media.reduce((prev, curr) => prev.lavenshtein <= curr.lavenshtein ? prev : curr)
}
async findNewNotifications () {
debug('Checking for new notifications')
const res = await this.getNotifications()
const notifications = res.data.Page.notifications
const newNotifications = notifications.filter(({ createdAt }) => createdAt > this.lastNotificationDate)
this.lastNotificationDate = Date.now() / 1000
debug(`Found ${newNotifications.length} new notifications`)
for (const { media, episode, type } of newNotifications) {
const options = {
title: media.title.userPreferred,
body: type === 'AIRING' ? `Episode ${episode} is out in Japan, it should be available soon.` : 'Was recently added to AniList.',
icon: media.coverImage.medium,
data: { id: media.id }
}
IPC.emit('notification', options)
}
}
/**
* @param {{key: string, title: string, year?: string, isAdult: boolean}[]} flattenedTitles
**/
async alSearchCompound (flattenedTitles) {
debug(`Searching for ${flattenedTitles.length} titles via compound search`)
if (!flattenedTitles.length) return []
// isAdult doesn't need an extra variable, as the title is the same regardless of type, so we re-use the same variable for adult and non-adult requests
/** @type {Record<`v${number}`, string>} */
const requestVariables = flattenedTitles.reduce((obj, { title, isAdult }, i) => {
if (isAdult && i !== 0) return obj
obj[`v${i}`] = title
return obj
}, {})
const queryVariables = flattenedTitles.reduce((arr, { isAdult }, i) => {
if (isAdult && i !== 0) return arr
arr.push(`$v${i}: String`)
return arr
}, []).join(', ')
const fragmentQueries = flattenedTitles.map(({ year, isAdult }, i) => /* js */`
v${i}: Page(perPage: 10) {
media(type: ANIME, search: $v${(isAdult && i !== 0) ? i - 1 : i}, status_in: [RELEASING, FINISHED], isAdult: ${!!isAdult} ${year ? `, seasonYear: ${year}` : ''}) {
...med
}
}`)
const query = /* js */`
query(${queryVariables}) {
${fragmentQueries}
}
fragment&nbsp;med&nbsp;on&nbsp;Media {
id,
title {
romaji,
english,
native
},
synonyms
}`
/**
* @type {import('./al.d.ts').Query<Record<string, {media: import('./al.d.ts').Media[]}>>}
* @returns {Promise<[string, import('./al.d.ts').Media][]>}
* */
const res = await this.alRequest(query, requestVariables)
/** @type {Record<string, number>} */
const searchResults = {}
for (const [variableName, { media }] of Object.entries(res.data)) {
if (!media.length) continue
const titleObject = flattenedTitles[Number(variableName.slice(1))]
if (searchResults[titleObject.key]) continue
searchResults[titleObject.key] = media.map(media => getDistanceFromTitle(media, titleObject.title)).reduce((prev, curr) => prev.lavenshtein <= curr.lavenshtein ? prev : curr).id
}
const ids = Object.values(searchResults)
const search = await this.searchIDS({ id: ids, perPage: 50 })
return Object.entries(searchResults).map(([filename, id]) => [filename, search.data.Page.media.find(media => media.id === id)])
}
async alEntry (filemedia) {
// check if values exist
if (filemedia.media && alToken) {
const { media, failed } = filemedia
debug(`Checking entry for ${media.title.userPreferred}`)
debug(`Media viability: ${media.status}, Is from failed resolve: ${failed}`)
if (failed) return
if (media.status !== 'FINISHED' && media.status !== 'RELEASING') return
// check if media can even be watched, ex: it was resolved incorrectly
// some anime/OVA's can have a single episode, or some movies can have multiple episodes
const singleEpisode = ((!media.episodes && (Number(filemedia.episode) === 1 || isNaN(Number(filemedia.episode)))) || (media.format === 'MOVIE' && media.episodes === 1)) && 1 // movie check
const videoEpisode = Number(filemedia.episode) || singleEpisode
const mediaEpisode = media.episodes || media.nextAiringEpisode?.episode || singleEpisode
debug(`Episode viability: ${videoEpisode}, ${mediaEpisode}, ${singleEpisode}`)
if (!videoEpisode || !mediaEpisode) return
// check episode range, safety check if `failed` didn't catch this
if (videoEpisode > mediaEpisode) return
const lists = media.mediaListEntry?.customLists.filter(list => list.enabled).map(list => list.name) || []
const status = media.mediaListEntry?.status === 'REPEATING' ? 'REPEATING' : 'CURRENT'
const progress = media.mediaListEntry?.progress
debug(`User's progress: ${progress}, Media's progress: ${videoEpisode}`)
// check user's own watch progress
if (progress > videoEpisode) return
if (progress === videoEpisode && videoEpisode !== mediaEpisode && !singleEpisode) return
debug(`Updating entry for ${media.title.userPreferred}`)
const variables = {
repeat: media.mediaListEntry?.repeat || 0,
id: media.id,
status,
episode: videoEpisode,
lists
}
if (videoEpisode === mediaEpisode) {
variables.status = 'COMPLETED'
if (media.mediaListEntry?.status === 'REPEATING') variables.repeat = media.mediaListEntry.repeat + 1
}
if (!lists.includes('Watched using Miru')) {
variables.lists.push('Watched using Miru')
}
await this.entry(variables)
this.userLists.value = this.getUserLists()
}
}
async searchName (variables = {}) {
debug(`Searching name for ${variables.name}`)
const query = /* js */`
query($page: Int, $perPage: Int, $sort: [MediaSort], $name: String, $status: [MediaStatus], $year: Int, $isAdult: Boolean) {
Page(page: $page, perPage: $perPage) {
pageInfo {
hasNextPage
},
media(type: ANIME, search: $name, sort: $sort, status_in: $status, isAdult: $isAdult, format_not: MUSIC, seasonYear: $year) {
${queryObjects}
}
}
}`
variables.isAdult = variables.isAdult ?? false
/** @type {import('./al.d.ts').PagedQuery<{media: import('./al.d.ts').Media[]}>} */
const res = await this.alRequest(query, variables)
this.updateCache(res.data.Page.media)
return res
}
async searchIDSingle (variables) {
debug(`Searching for ID: ${variables.id}`)
const query = /* js */`
query($id: Int) {
Media(id: $id, type: ANIME) {
${queryObjects}
}
}`
/** @type {import('./al.d.ts').Query<{Media: import('./al.d.ts').Media}>} */
const res = await this.alRequest(query, variables)
this.updateCache([res.data.Media])
return res
}
async searchIDS (variables) {
debug(`Searching for IDs: ${variables.id.length}`)
const query = /* js */`
query($id: [Int], $page: Int, $perPage: Int, $status: [MediaStatus], $onList: Boolean, $sort: [MediaSort], $search: String, $season: MediaSeason, $year: Int, $genre: String, $format: MediaFormat) {
Page(page: $page, perPage: $perPage) {
pageInfo {
hasNextPage
},
media(id_in: $id, type: ANIME, status_in: $status, onList: $onList, search: $search, sort: $sort, season: $season, seasonYear: $year, genre: $genre, format: $format) {
${queryObjects}
}
}
}`
/** @type {import('./al.d.ts').PagedQuery<{media: import('./al.d.ts').Media[]}>} */
const res = await this.alRequest(query, variables)
this.updateCache(res.data.Page.media)
return res
}
/** @returns {Promise<import('./al.d.ts').PagedQuery<{ notifications: { id: number, type: string, createdAt: number, episode: number, media: import('./al.d.ts').Media}[] }>>} */
getNotifications (variables = {}) {
debug('Getting notifications')
const query = /* js */`
query($page: Int, $perPage: Int) {
Page(page: $page, perPage: $perPage) {
notifications(resetNotificationCount: false, type_in: [AIRING, RELATED_MEDIA_ADDITION]) {
...on&nbsp;AiringNotification {
id,
type,
episode,
createdAt,
media {
id,
title {
userPreferred
},
coverImage {
medium
}
}
},
...on&nbsp;RelatedMediaAdditionNotification {
id,
type,
createdAt,
media {
id,
title {
userPreferred
},
coverImage {
medium
}
}
}
}
}
}`
return this.alRequest(query, variables)
}
/** @returns {Promise<import('./al.d.ts').Query<{ Viewer: import('./al.d.ts').Viewer }>>} */
viewer (variables = {}) {
debug('Getting viewer')
const query = /* js */`
query {
Viewer {
avatar {
medium
},
name,
id,
mediaListOptions {
animeList {
customLists
}
}
}
}`
return this.alRequest(query, variables)
}
/** @returns {Promise<import('./al.d.ts').Query<{ MediaListCollection: import('./al.d.ts').MediaListCollection }>>} */
async getUserLists (variables = {}) {
debug('Getting user lists')
const userId = this.userID?.viewer?.data?.Viewer.id
variables.id = userId
const query = /* js */`
query($id: Int) {
MediaListCollection(userId: $id, type: ANIME, forceSingleCompletedList: true, sort: UPDATED_TIME_DESC) {
lists {
status,
entries {
media {
id,
status,
mediaListEntry {
progress
},
nextAiringEpisode {
episode
},
relations {
edges {
relationType(version:2)
node {
id
}
}
}
}
}
}
}
}`
// this doesn't need to be cached, as SearchIDStatus is already cached, which is the only thing that uses this
return await this.alRequest(query, variables)
}
/** @returns {Promise<import('./al.d.ts').Query<{ MediaList: { status: string, progress: number, repeat: number }}>>} */
async searchIDStatus (variables = {}) {
debug(`Searching for ID status: ${variables.id}`)
const userId = this.userID?.viewer?.data?.Viewer.id
variables.id = userId
const query = /* js */`
query($id: Int, $mediaId: Int) {
MediaList(userId: $id, mediaId: $mediaId) {
status,
progress,
repeat
}
}`
return await this.alRequest(query, variables)
}
async searchAiringSchedule (variables = {}) {
debug('Searching for airing schedule')
variables.to = (variables.from + 7 * 24 * 60 * 60)
const query = /* js */`
query($page: Int, $perPage: Int, $from: Int, $to: Int) {
Page(page: $page, perPage: $perPage) {
pageInfo {
hasNextPage
},
airingSchedules(airingAt_greater: $from, airingAt_lesser: $to) {
episode,
timeUntilAiring,
airingAt,
media {
${queryObjects}
}
}
}
}`
/** @type {import('./al.d.ts').PagedQuery<{ airingSchedules: { timeUntilAiring: number, airingAt: number, episode: number, media: import('./al.d.ts').Media}[]}>} */
const res = await this.alRequest(query, variables)
this.updateCache(res.data.Page.airingSchedules?.map(({ media }) => media))
return res
}
/** @returns {Promise<import('./al.d.ts').PagedQuery<{ airingSchedules: { airingAt: number, episode: number }[]}>>} */
episodes (variables = {}) {
debug(`Searching for episodes: ${variables.id}`)
const query = /* js */`
query($id: Int) {
Page(page: 1, perPage: 1000) {
airingSchedules(mediaId: $id) {
airingAt,
episode
}
}
}`
return this.alRequest(query, variables)
}
async search (variables = {}) {
debug(`Searching ${JSON.stringify(variables)}`)
variables.sort ||= 'SEARCH_MATCH'
const query = /* js */`
query($page: Int, $perPage: Int, $sort: [MediaSort], $search: String, $onList: Boolean, $status: MediaStatus, $status_not: MediaStatus, $season: MediaSeason, $year: Int, $genre: String, $format: MediaFormat) {
Page(page: $page, perPage: $perPage) {
pageInfo {
hasNextPage
},
media(type: ANIME, search: $search, sort: $sort, onList: $onList, status: $status, status_not: $status_not, season: $season, seasonYear: $year, genre: $genre, format: $format, format_not: MUSIC) {
${queryObjects}
}
}
}`
/** @type {import('./al.d.ts').PagedQuery<{media: import('./al.d.ts').Media[]}>} */
const res = await this.alRequest(query, variables)
this.updateCache(res.data.Page.media)
return res
}
/** @returns {Promise<import('./al.d.ts').Query<{ AiringSchedule: { airingAt: number }}>>} */
episodeDate (variables) {
debug(`Searching for episode date: ${variables.id}, ${variables.ep}`)
const query = /* js */`
query($id: Int, $ep: Int) {
AiringSchedule(mediaId: $id, episode: $ep) {
airingAt
}
}`
return this.alRequest(query, variables)
}
/** @returns {Promise<import('./al.d.ts').PagedQuery<{ mediaList: import('./al.d.ts').Following[]}>>} */
following (variables) {
debug('Getting following')
const query = /* js */`
query($id: Int) {
Page {
mediaList(mediaId: $id, isFollowing: true, sort: UPDATED_TIME_DESC) {
status,
score,
progress,
user {
name,
avatar {
medium
}
}
}
}
}`
return this.alRequest(query, variables)
}
entry (variables) {
debug(`Updating entry for ${variables.id}`)
const query = /* js */`
mutation($lists: [String], $id: Int, $status: MediaListStatus, $episode: Int, $repeat: Int, $score: Int) {
SaveMediaListEntry(mediaId: $id, status: $status, progress: $episode, repeat: $repeat, scoreRaw: $score, customLists: $lists) {
id,
status,
progress,
repeat
}
}`
return this.alRequest(query, variables)
}
delete (variables) {
debug(`Deleting entry for ${variables.id}`)
const query = /* js */`
mutation($id: Int) {
DeleteMediaListEntry(id: $id) {
deleted
}
}`
return this.alRequest(query, variables)
}
favourite (variables) {
debug(`Toggling favourite for ${variables.id}`)
const query = /* js */`
mutation($id: Int) {
ToggleFavourite(animeId: $id) { anime { nodes { id } } }
}`
return this.alRequest(query, variables)
}
customList (variables = {}) {
debug('Updating custom list')
variables.lists = [...variables.lists, 'Watched using Miru']
const query = /* js */`
mutation($lists: [String]) {
UpdateUser(animeListOptions: { customLists: $lists }) {
id
}
}`
return this.alRequest(query, variables)
}
/** @param {import('./al.d.ts').Media[]} medias */
updateCache (medias) {
this.mediaCache = { ...this.mediaCache, ...Object.fromEntries(medias.map(media => [media.id, media])) }
}
}
export const anilistClient = new AnilistClient()

244
common/modules/anime.js Normal file
View file

@ -0,0 +1,244 @@
import { DOMPARSER } from './util.js'
import { anilistClient } from './anilist.js'
import _anitomyscript from 'anitomyscript'
import { toast } from 'svelte-sonner'
import SectionsManager from './sections.js'
import { page } from '@/App.svelte'
import clipboard from './clipboard.js'
import { search, key } from '@/views/Search.svelte'
import { playAnime } from '@/views/TorrentSearch/TorrentModal.svelte'
const imageRx = /\.(jpeg|jpg|gif|png|webp)/i
clipboard.on('files', ({ detail }) => {
for (const file of detail) {
if (file.type.startsWith('image')) {
toast.promise(traceAnime(file), {
description: 'You can also paste an URL to an image.',
loading: 'Looking up anime for image...',
success: 'Found anime for image!',
error: 'Couldn\'t find anime for specified image! Try to remove black bars, or use a more detailed image.'
})
}
}
})
clipboard.on('text', ({ detail }) => {
for (const { type, text } of detail) {
let src = null
if (type === 'text/html') {
src = DOMPARSER(text, 'text/html').querySelectorAll('img')[0]?.src
} else if (imageRx.exec(text)) {
src = text
}
if (src) {
toast.promise(traceAnime(src), {
description: 'You can also paste an URL to an image.',
loading: 'Looking up anime for image...',
success: 'Found anime for image!',
error: 'Couldn\'t find anime for specified image! Try to remove black bars, or use a more detailed image.'
})
}
}
})
export async function traceAnime (image) { // WAIT lookup logic
let options
let url = `https://api.trace.moe/search?cutBorders&url=${image}`
if (image instanceof Blob) {
options = {
method: 'POST',
body: image,
headers: { 'Content-type': image.type }
}
url = 'https://api.trace.moe/search'
}
const res = await fetch(url, options)
const { result } = await res.json()
if (result?.length) {
const ids = result.map(({ anilist }) => anilist)
search.value = {
clearNext: true,
load: (page = 1, perPage = 50, variables = {}) => {
const res = anilistClient.searchIDS({ page, perPage, id: ids, ...SectionsManager.sanitiseObject(variables) }).then(res => {
for (const index in res.data?.Page?.media) {
const media = res.data.Page.media[index]
const counterpart = result.find(({ anilist }) => anilist === media.id)
res.data.Page.media[index] = {
media,
episode: counterpart.episode,
similarity: counterpart.similarity,
episodeData: {
image: counterpart.image,
video: counterpart.video
}
}
}
res.data?.Page?.media.sort((a, b) => b.similarity - a.similarity)
return res
})
return SectionsManager.wrapResponse(res, result.length, 'episode')
}
}
key.value = {}
page.value = 'search'
} else {
throw new Error('Search Failed \n Couldn\'t find anime for specified image! Try to remove black bars, or use a more detailed image.')
}
}
function constructChapters (results, duration) {
const chapters = results.map(result => {
const diff = duration - result.episodeLength
return {
start: (result.interval.startTime + diff) * 1000,
end: (result.interval.endTime + diff) * 1000,
text: result.skipType.toUpperCase()
}
})
const ed = chapters.find(({ text }) => text === 'ED')
const recap = chapters.find(({ text }) => text === 'RECAP')
if (recap) recap.text = 'Recap'
chapters.sort((a, b) => a - b)
if ((chapters[0].start | 0) !== 0) {
chapters.unshift({ start: 0, end: chapters[0].start, text: chapters[0].text === 'OP' ? 'Intro' : 'Episode' })
}
if (ed) {
if ((ed.end | 0) + 5000 - duration * 1000 < 0) {
chapters.push({ start: ed.end, end: duration * 1000, text: 'Preview' })
}
} else if ((chapters[chapters.length - 1].end | 0) + 5000 - duration * 1000 < 0) {
chapters.push({
start: chapters[chapters.length - 1].end,
end: duration * 1000,
text: 'Episode'
})
}
for (let i = 0, len = chapters.length - 2; i <= len; ++i) {
const current = chapters[i]
const next = chapters[i + 1]
if ((current.end | 0) !== (next.start | 0)) {
chapters.push({
start: current.end,
end: next.start,
text: 'Episode'
})
}
}
chapters.sort((a, b) => a.start - b.start)
return chapters
}
export async function getChaptersAniSkip (file, duration) {
const resAccurate = await fetch(`https://api.aniskip.com/v2/skip-times/${file.media.media.idMal}/${file.media.episode}/?episodeLength=${duration}&types=op&types=ed&types=recap`)
const jsonAccurate = await resAccurate.json()
const resRough = await fetch(`https://api.aniskip.com/v2/skip-times/${file.media.media.idMal}/${file.media.episode}/?episodeLength=0&types=op&types=ed&types=recap`)
const jsonRough = await resRough.json()
const map = {}
for (const result of [...jsonAccurate.results, ...jsonRough.results]) {
map[result.skipType] ||= result
}
const results = Object.values(map)
if (!results.length) return []
return constructChapters(results, duration)
}
export function getMediaMaxEp (media, playable) {
if (playable) {
return media.nextAiringEpisode?.episode - 1 || media.airingSchedule?.nodes?.[0]?.episode - 1 || media.episodes
} else {
return media.episodes || media.nextAiringEpisode?.episode - 1 || media.airingSchedule?.nodes?.[0]?.episode - 1
}
}
// utility method for correcting anitomyscript woes for what's needed
export async function anitomyscript (...args) {
// @ts-ignore
const res = await _anitomyscript(...args)
const parseObjs = Array.isArray(res) ? res : [res]
for (const obj of parseObjs) {
obj.anime_title ??= ''
const seasonMatch = obj.anime_title.match(/S(\d{2})E(\d{2})/)
if (seasonMatch) {
obj.anime_season = seasonMatch[1]
obj.episode_number = seasonMatch[2]
obj.anime_title = obj.anime_title.replace(/S(\d{2})E(\d{2})/, '')
}
const yearMatch = obj.anime_title.match(/ (19[5-9]\d|20\d{2})/)
if (yearMatch && Number(yearMatch[1]) <= (new Date().getUTCFullYear() + 1)) {
obj.anime_year = yearMatch[1]
obj.anime_title = obj.anime_title.replace(/ (19[5-9]\d|20\d{2})/, '')
}
if (Number(obj.anime_season) > 1) obj.anime_title += ' S' + obj.anime_season
}
return parseObjs
}
export const formatMap = {
TV: 'TV Series',
TV_SHORT: 'TV Short',
MOVIE: 'Movie',
SPECIAL: 'Special',
OVA: 'OVA',
ONA: 'ONA',
MUSIC: 'Music',
undefined: 'N/A',
null: 'N/A'
}
export const statusColorMap = {
CURRENT: 'rgb(61,180,242)',
PLANNING: 'rgb(247,154,99)',
COMPLETED: 'rgb(123,213,85)',
PAUSED: 'rgb(250,122,122)',
REPEATING: '#3baeea',
DROPPED: 'rgb(232,93,117)'
}
export async function playMedia (media) {
let ep = 1
if (media.mediaListEntry) {
const { status, progress } = media.mediaListEntry
if (progress) {
if (status === 'COMPLETED') {
await setStatus('REPEATING', { episode: 0 }, media)
} else {
ep = Math.min(getMediaMaxEp(media, true), progress + 1)
}
}
}
playAnime(media, ep, true)
media = null
}
export function setStatus (status, other = {}, media) {
const variables = {
id: media.id,
status,
...other
}
return anilistClient.entry(variables)
}
const episodeMetadataMap = {}
export async function getEpisodeMetadataForMedia (media) {
if (episodeMetadataMap[media.id]) return episodeMetadataMap[media.id]
const res = await fetch('https://api.ani.zip/mappings?anilist_id=' + media.id)
const { episodes } = await res.json()
episodeMetadataMap[media.id] = episodes
return episodes
}

View file

@ -0,0 +1,69 @@
import { writable, derived } from 'simple-store-svelte'
// Maximum number of entries to keep in LocalStorage
const maxEntries = 1000
// LocalStorage is structured as an array of objects with the following properties:
// mediaId, episode, currentTime, safeduration, createdAt, updatedAt
function loadFromLocalStorage () {
const data = localStorage.getItem('animeEpisodeProgress')
return data ? JSON.parse(data) : []
}
function saveToLocalStorage (data) {
localStorage.setItem('animeEpisodeProgress', JSON.stringify(data))
animeProgressStore.set(data)
}
const animeProgressStore = writable(loadFromLocalStorage())
// Return an object with the progress of each episode in percent (0-100), keyed by episode number
export function liveAnimeProgress (mediaId) {
return derived(animeProgressStore, (data) => {
if (!mediaId) return {}
const results = data.filter(item => item.mediaId === mediaId)
if (!results) return {}
// Return an object with the episode as the key and the progress as the value
return Object.fromEntries(results.map(result => [
result.episode,
Math.ceil(result.currentTime / result.safeduration * 100)
]))
})
}
// Return an individual episode's progress in percent (0-100)
export function liveAnimeEpisodeProgress (mediaId, episode) {
return derived(animeProgressStore, (data) => {
if (!mediaId || !episode) return 0
const result = data.find(item => item.mediaId === mediaId && item.episode === episode)
if (!result) return 0
return Math.ceil(result.currentTime / result.safeduration * 100)
})
}
// Return an individual episode's record { mediaId, episode, currentTime, safeduration, createdAt, updatedAt }
export function getAnimeProgress (mediaId, episode) {
const data = loadFromLocalStorage()
return data.find(item => item.mediaId === mediaId && item.episode === episode)
}
// Set an individual episode's progress
export function setAnimeProgress ({ mediaId, episode, currentTime, safeduration }) {
if (!mediaId || !episode || !currentTime || !safeduration) return
const data = loadFromLocalStorage()
// Update the existing entry or create a new one
const existing = data.find(item => item.mediaId === mediaId && item.episode === episode)
if (existing) {
existing.currentTime = currentTime
existing.safeduration = safeduration
existing.updatedAt = Date.now()
} else {
data.push({ mediaId, episode, currentTime, safeduration, createdAt: Date.now(), updatedAt: Date.now() })
}
// Remove the oldest entries if we have too many
while (data.length > maxEntries) {
const oldest = data.reduce((a, b) => a.updatedAt < b.updatedAt ? a : b)
data.splice(data.indexOf(oldest), 1)
}
saveToLocalStorage(data)
}

View file

@ -0,0 +1,250 @@
import { anilistClient } from './anilist.js'
import { anitomyscript } from './anime.js'
import { chunks } from './util.js'
import Debug from 'debug'
const debug = Debug('ui:animeresolver')
const postfix = {
1: 'st', 2: 'nd', 3: 'rd'
}
export default new class AnimeResolver {
// name: media cache from title resolving
animeNameCache = {}
/**
* @param {import('anitomyscript').AnitomyResult} obj
* @returns {string}
*/
getCacheKeyForTitle (obj) {
let key = obj.anime_title
if (obj.anime_year) key += obj.anime_year
return key
}
/**
* @param {string} title
* @returns {string[]}
*/
alternativeTitles (title) {
const titles = new Set()
let modified = title
// preemptively change S2 into Season 2 or 2nd Season, otherwise this will have accuracy issues
const seasonMatch = title.match(/ S(\d+)/)
if (seasonMatch) {
if (Number(seasonMatch[1]) === 1) { // if this is S1, remove the " S1" or " S01"
modified = title.replace(/ S(\d+)/, '')
titles.add(modified)
} else {
modified = title.replace(/ S(\d+)/, ` ${Number(seasonMatch[1])}${postfix[Number(seasonMatch[1])] || 'th'} Season`)
titles.add(modified)
titles.add(title.replace(/ S(\d+)/, ` Season ${Number(seasonMatch[1])}`))
}
} else {
titles.add(title)
}
// remove - :
const specialMatch = modified.match(/[-:]/g)
if (specialMatch) {
modified = modified.replace(/[-:]/g, '').replace(/[ ]{2,}/, ' ')
titles.add(modified)
}
// remove (TV)
const tvMatch = modified.match(/\(TV\)/)
if (tvMatch) {
modified = modified.replace('(TV)', '')
titles.add(modified)
}
return [...titles]
}
/**
* resolve anime name based on file name and store it
* @param {import('anitomyscript').AnitomyResult[]} parseObjects
*/
async findAnimesByTitle (parseObjects) {
if (!parseObjects.length) return
const titleObjects = parseObjects.map(obj => {
const key = this.getCacheKeyForTitle(obj)
const titleObjects = this.alternativeTitles(obj.anime_title).map(title => ({ title, year: obj.anime_year, key, isAdult: false }))
titleObjects.push({ ...titleObjects.at(-1), isAdult: true })
return titleObjects
}).flat()
debug(`Finding ${titleObjects.length} titles: ${titleObjects.map(obj => obj.title).join(', ')}`)
for (const chunk of chunks(titleObjects, 60)) {
// single title has a complexity of 8.1, al limits complexity to 500, so this can be at most 62, undercut it to 60, al pagination is 50, but at most we'll do 30 titles since isAduld duplicates each title
for (const [key, media] of await anilistClient.alSearchCompound(chunk)) {
debug(`Found ${key} as ${media.id}: ${media.title.userPreferred}`)
this.animeNameCache[key] = media
}
}
}
/**
* @param {number} id
*/
async getAnimeById (id) {
if (anilistClient.mediaCache[id]) return anilistClient.mediaCache[id]
const res = await anilistClient.searchIDSingle({ id })
return res.data.Media
}
// TODO: anidb aka true episodes need to be mapped to anilist episodes a bit better, shit like mushoku offsets caused by episode 0's in between seasons
/**
* @param {string | string[]} fileName
* @returns {Promise<any[]>}
*/
async resolveFileAnime (fileName) {
if (!fileName) return [{}]
const parseObjs = await anitomyscript(fileName)
const TYPE_EXCLUSIONS = ['ED', 'ENDING', 'NCED', 'NCOP', 'OP', 'OPENING', 'PREVIEW', 'PV']
/** @type {Record<string, import('anitomyscript').AnitomyResult>} */
const uniq = {}
for (const obj of parseObjs) {
const key = this.getCacheKeyForTitle(obj)
if (key in this.animeNameCache) continue // skip already resolved
if (obj.anime_type && TYPE_EXCLUSIONS.includes(obj.anime_type.toUpperCase())) continue // skip non-episode media
uniq[key] = obj
}
await this.findAnimesByTitle(Object.values(uniq))
const fileAnimes = []
for (const parseObj of parseObjs) {
let failed = false
let episode
let media = this.animeNameCache[this.getCacheKeyForTitle(parseObj)]
// resolve episode, if movie, dont.
const maxep = media?.nextAiringEpisode?.episode || media?.episodes
debug(`Resolving ${parseObj.anime_title} ${parseObj.episode_number} ${maxep} ${media?.title.userPreferred} ${media?.format}`)
if ((media?.format !== 'MOVIE' || maxep) && parseObj.episode_number) {
if (Array.isArray(parseObj.episode_number)) {
// is an episode range
if (parseInt(parseObj.episode_number[0]) === 1) {
debug('Range starts at 1')
// if it starts with #1 and overflows then it includes more than 1 season in a batch, cant fix this cleanly, name is parsed per file basis so this shouldnt be an issue
episode = `${parseObj.episode_number[0]} ~ ${parseObj.episode_number[1]}`
} else {
if (maxep && parseInt(parseObj.episode_number[1]) > maxep) {
// get root media to start at S1, instead of S2 or some OVA due to parsing errors
// this is most likely safe, if it was relative episodes then it would likely use an accurate title for the season
// if they didnt use an accurate title then its likely an absolute numbering scheme
// parent check is to break out of those incorrectly resolved OVA's
// if we used anime season to resolve anime name, then there's no need to march into prequel!
const prequel = !parseObj.anime_season && (this.findEdge(media, 'PREQUEL')?.node || ((media.format === 'OVA' || media.format === 'ONA') && this.findEdge(media, 'PARENT')?.node))
debug(`Prequel ${prequel && prequel.id}:${prequel && prequel.title.userPreferred}`)
const root = prequel && (await this.resolveSeason({ media: await this.getAnimeById(prequel.id), force: true })).media
debug(`Root ${root && root.id}:${root && root.title.userPreferred}`)
// if highest value is bigger than episode count or latest streamed episode +1 for safety, parseint to math.floor a number like 12.5 - specials - in 1 go
const result = await this.resolveSeason({ media: root || media, episode: parseObj.episode_number[1], increment: !parseObj.anime_season ? null : true })
debug(`Found rootMedia for ${parseObj.anime_title}: ${result.rootMedia.id}:${result.rootMedia.title.userPreferred} from ${media.id}:${media.title.userPreferred}`)
media = result.rootMedia
const diff = parseObj.episode_number[1] - result.episode
episode = `${parseObj.episode_number[0] - diff} ~ ${result.episode}`
failed = result.failed
if (failed) debug(`Failed to resolve ${parseObj.anime_title} ${parseObj.episode_number} ${media?.title.userPreferred}`)
} else {
// cant find ep count or range seems fine
episode = `${Number(parseObj.episode_number[0])} ~ ${Number(parseObj.episode_number[1])}`
}
}
} else {
if (maxep && parseInt(parseObj.episode_number) > maxep) {
// see big comment above
const prequel = !parseObj.anime_season && (this.findEdge(media, 'PREQUEL')?.node || ((media.format === 'OVA' || media.format === 'ONA') && this.findEdge(media, 'PARENT')?.node))
debug(`Prequel ${prequel && prequel.id}:${prequel && prequel.title.userPreferred}`)
const root = prequel && (await this.resolveSeason({ media: await this.getAnimeById(prequel.id), force: true })).media
debug(`Root ${root && root.id}:${root && root.title.userPreferred}`)
// value bigger than episode count
const result = await this.resolveSeason({ media: root || media, episode: parseInt(parseObj.episode_number), increment: !parseObj.anime_season ? null : true })
debug(`Found rootMedia for ${parseObj.anime_title}: ${result.rootMedia.id}:${result.rootMedia.title.userPreferred} from ${media.id}:${media.title.userPreferred}`)
media = result.rootMedia
episode = result.episode
failed = result.failed
if (failed) debug(`Failed to resolve ${parseObj.anime_title} ${parseObj.episode_number} ${media?.title.userPreferred}`)
} else {
// cant find ep count or episode seems fine
episode = Number(parseObj.episode_number)
}
}
}
debug(`Resolved ${parseObj.anime_title} ${parseObj.episode_number} ${episode} ${media?.id}:${media?.title.userPreferred}`)
fileAnimes.push({
episode: episode || parseObj.episode_number,
parseObject: parseObj,
media,
failed
})
}
return fileAnimes
}
/**
* @param {import('./al.js').Media} media
* @param {string} type
* @param {string[]} [formats]
* @param {boolean} [skip]
*/
findEdge (media, type, formats = ['TV', 'TV_SHORT'], skip) {
let res = media.relations.edges.find(edge => {
if (edge.relationType === type) {
return formats.includes(edge.node.format)
}
return false
})
// this is hit-miss
if (!res && !skip && type === 'SEQUEL') res = this.findEdge(media, type, formats = ['TV', 'TV_SHORT', 'OVA'], true)
return res
}
// note: this doesnt cover anime which uses partially relative and partially absolute episode number, BUT IT COULD!
/**
* @param {{ media: import('./al.js').Media , episode?:number, force?:boolean, increment?:boolean, offset?: number, rootMedia?: import('./al.js').Media }} opts
* @returns {Promise<{ media: import('./al.js').Media, episode: number, offset: number, increment: boolean, rootMedia: import('./al.js').Media, failed?: boolean }>}
*/
async resolveSeason (opts) {
// media, episode, increment, offset, force
if (!opts.media || !(opts.episode || opts.force)) throw new Error('No episode or media for season resolve!')
let { media, episode, increment, offset = 0, rootMedia = opts.media, force } = opts
const rootHighest = (rootMedia.nextAiringEpisode?.episode || rootMedia.episodes)
const prequel = !increment && this.findEdge(media, 'PREQUEL')?.node
const sequel = !prequel && (increment || increment == null) && this.findEdge(media, 'SEQUEL')?.node
const edge = prequel || sequel
increment = increment ?? !prequel
if (!edge) {
const obj = { media, episode: episode - offset, offset, increment, rootMedia, failed: true }
if (!force) debug(`Failed to resolve ${media.id}:${media.title.userPreferred} ${episode} ${increment} ${offset} ${rootMedia.id}:${rootMedia.title.userPreferred}`)
return obj
}
media = await this.getAnimeById(edge.id)
const highest = media.nextAiringEpisode?.episode || media.episodes
const diff = episode - (highest + offset)
offset += increment ? rootHighest : highest
if (increment) rootMedia = media
// force marches till end of tree, no need for checks
if (!force && diff <= rootHighest) {
episode -= offset
return { media, episode, offset, increment, rootMedia }
}
return this.resolveSeason({ media, episode, increment, offset, rootMedia, force })
}
}()

253
common/modules/click.js Normal file
View file

@ -0,0 +1,253 @@
import { SUPPORTS } from '@/modules/support.js'
let lastTapElement = null
let lastHoverElement = null
const noop = _ => {}
document.addEventListener('pointerup', () => {
setTimeout(() => {
lastTapElement?.(false)
lastTapElement = null
lastHoverElement?.(false)
lastHoverElement = null
})
})
/** @typedef {{element: Element, x: number, y: number, inViewport: boolean}} ElementPosition */
/**
* Adds click event listener to the specified node.
* @param {HTMLElement} node - The node to attach the click event listener to.
* @param {Function} [cb=noop] - The callback function to be executed on click.
*/
export function click (node, cb = noop) {
node.tabIndex = 0
node.role = 'button'
node.addEventListener('click', e => {
e.stopPropagation()
navigator.vibrate(15)
cb(e)
})
node.addEventListener('pointerup', e => {
e.stopPropagation()
})
node.addEventListener('pointerleave', e => {
e.stopPropagation()
})
if (!SUPPORTS.isAndroid) {
node.addEventListener('keydown', e => {
if (e.key === 'Enter') {
e.stopPropagation()
cb(e)
}
})
}
}
// TODO: this needs to be re-written.... again... it should detect pointer type and have separate functionality for mouse and touch and none for dpad
/**
* Adds hover and click event listeners to the specified node.
* @param {HTMLElement} node - The node to attach the event listeners to.
*/
export function hoverClick (node, [cb = noop, hoverUpdate = noop]) {
let pointerType = 'touch'
node.tabIndex = 0
node.role = 'button'
node.addEventListener('pointerenter', e => {
lastHoverElement?.(false)
lastTapElement?.(false)
hoverUpdate(true)
lastHoverElement = hoverUpdate
pointerType = e.pointerType
})
node.addEventListener('click', e => {
e.stopPropagation()
if (pointerType === 'mouse') return cb(e)
lastTapElement?.(false)
if (lastTapElement === hoverUpdate) {
lastTapElement = null
navigator.vibrate(15)
hoverUpdate(false)
cb(e)
} else {
lastTapElement = hoverUpdate
}
})
node.addEventListener('keydown', e => {
if (e.key === 'Enter') {
e.stopPropagation()
lastTapElement?.(false)
if (lastTapElement === hoverUpdate) {
lastTapElement = null
cb(e)
} else {
hoverUpdate(true)
if (!SUPPORTS.isAndroid) lastTapElement = hoverUpdate
}
}
})
node.addEventListener('pointerup', e => {
e.stopPropagation()
if (e.pointerType === 'mouse') setTimeout(() => hoverUpdate(false))
})
node.addEventListener('pointerleave', e => {
lastHoverElement = hoverUpdate
if (e.pointerType === 'mouse') hoverUpdate(false)
})
node.addEventListener('pointermove', e => {
if (e.pointerType === 'touch') hoverUpdate(false)
})
}
const Directions = { up: 1, right: 2, down: 3, left: 4 }
// const InverseDirections = { up: 'down', down: 'up', left: 'right', right: 'left' }
const DirectionKeyMap = { ArrowDown: 'down', ArrowUp: 'up', ArrowLeft: 'left', ArrowRight: 'right' }
/**
* Calculates the direction between two points.
* @param {Object} anchor - The anchor point.
* @param {Object} relative - The relative point.
* @returns {number} - The direction between the two points.
*/
function getDirection (anchor, relative) {
return Math.round((Math.atan2(relative.y - anchor.y, relative.x - anchor.x) * 180 / Math.PI + 180) / 90) || 4
}
/**
* Calculates the distance between two points.
* @param {Object} anchor - The anchor point.
* @param {Object} relative - The relative point.
* @returns {number} - The distance between the two points.
*/
function getDistance (anchor, relative) {
return Math.hypot(relative.x - anchor.x, relative.y - anchor.y)
}
/**
* Gets keyboard-focusable elements within a specified element.
* @param {Element} [element=document.body] - The element to search within.
* @returns {Element[]} - An array of keyboard-focusable elements.
*/
function getKeyboardFocusableElements (element = document.body) {
return [...element.querySelectorAll('a[href], button:not([disabled]), fieldset:not([disabled]), input:not([disabled]), optgroup:not([disabled]), option:not([disabled]), select:not([disabled]), textarea:not([disabled]), details, [tabindex]:not([tabindex="-1"], [disabled]), [contenteditable], [controls]')].filter(
el => !el.getAttribute('aria-hidden')
)
}
/**
* Gets the position of an element.
* @param {Element} element - The element to get the position of.
* @returns {ElementPosition} - The position of the element.
*/
function getElementPosition (element) {
const { x, y, width, height, top, left, bottom, right } = element.getBoundingClientRect()
const inViewport = isInViewport({ top, left, bottom, right, width, height })
return { element, x: x + width * 0.5, y: y + height * 0.5, inViewport }
}
/**
* Gets the positions of all focusable elements.
* @returns {ElementPosition[]} - An array of element positions.
*/
function getFocusableElementPositions () {
const elements = []
for (const element of getKeyboardFocusableElements(document.querySelector('.modal.show') ?? document.body)) {
const position = getElementPosition(element)
if (position) elements.push(position)
}
return elements
}
/**
* Checks if an element is within the viewport.
* @param {Object} rect - The coordinates of the element.
* @returns {boolean} - True if the element is within the viewport, false otherwise.
*/
function isInViewport ({ top, left, bottom, right, width, height }) {
return top + height >= 0 && left + width >= 0 && bottom - height <= window.innerHeight && right - width <= window.innerWidth
}
// function isVisible ({ top, left, bottom, right }, element) {
// for (const [x, y] of [[left, top], [right, top], [left, bottom], [right, bottom]]) {
// if (document.elementFromPoint(x, y)?.isSameNode(element)) return true
// }
// return false
// }
/**
* @param {ElementPosition[]} keyboardFocusable
* @param {ElementPosition} currentElement
* @param {string} direction
* @returns {ElementPosition[]}
*/
function getElementsInDesiredDirection (keyboardFocusable, currentElement, direction) {
// first try finding visible elements in desired direction
return keyboardFocusable.filter(position => {
// in order of computation cost
if (position.element === currentElement.element) return false
if (getDirection(currentElement, position) !== Directions[direction]) return false
// filters out elements which are in the viewport, but are overlayed by other elements like a modal
if (position.inViewport && !position.element.checkVisibility()) return false
if (!position.inViewport && direction === 'right') return false // HACK: prevent right navigation from going to offscreen elements, but allow vertical elements!
return true
})
}
/**
* Navigates using D-pad keys.
* @param {string} [direction='up'] - The direction to navigate.
*/
function navigateDPad (direction = 'up') {
const keyboardFocusable = getFocusableElementPositions()
const currentElement = !document.activeElement || document.activeElement === document.body ? keyboardFocusable[0] : getElementPosition(document.activeElement)
const elementsInDesiredDirection = getElementsInDesiredDirection(keyboardFocusable, currentElement, direction)
// if there are elements in desired direction
if (elementsInDesiredDirection.length) {
const closestElement = elementsInDesiredDirection.reduce((reducer, position) => {
const distance = getDistance(currentElement, position)
if (distance < reducer.distance) return { distance, element: position.element }
return reducer
}, { distance: Infinity, element: null })
/** @type {{element: HTMLElement}} */
const { element } = closestElement
const isInput = element.matches('input[type=text], input[type=url], input[type=number], textarea')
// make readonly
let wasReadOnly = false
if (isInput) {
wasReadOnly = element.readOnly
element.readOnly = true
}
element.focus()
if (isInput && !wasReadOnly) setTimeout(() => { element.readOnly = false })
element.scrollIntoView({ block: 'center', inline: 'center', behavior: 'smooth' })
// return
}
// no elements in desired direction, go to opposite end [wrap around] // this wasnt a good idea in the long run
// const elementsInOppositeDirection = getElementsInDesiredDirection(keyboardFocusable, currentElement, InverseDirections[direction])
// if (elementsInOppositeDirection.length) {
// const furthestElement = elementsInOppositeDirection.reduce((reducer, position) => {
// const distance = getDistance(currentElement, position)
// if (distance > reducer.distance) return { distance, element: position.element }
// return reducer
// }, { distance: -Infinity, element: null })
// furthestElement.element.focus()
// }
}
// hacky, but make sure keybinds system loads first so it can prevent this from running
queueMicrotask(() => {
document.addEventListener('keydown', e => {
if (DirectionKeyMap[e.key]) {
e.preventDefault()
navigateDPad(DirectionKeyMap[e.key])
}
})
})

View file

@ -0,0 +1,31 @@
import 'browser-event-target-emitter'
export default new class extends EventTarget {
constructor () {
super()
window.on('drop', this.handleTransfer.bind(this))
window.on('paste', this.handleTransfer.bind(this))
window.on('dragover', e => e.preventDefault())
}
async handleTransfer ({ dataTransfer, clipboardData }) {
const promises = [...(dataTransfer || clipboardData).items].map(item => {
const type = item.type
return new Promise(resolve => item.kind === 'string' ? item.getAsString(text => resolve({ text, type })) : resolve(item.getAsFile()))
})
const items = await Promise.all(promises)
const files = []
const text = []
for (const item of items) {
if (item instanceof Blob) {
files.push(item)
} else {
text.push(item)
}
}
if (files.length) this.emit('files', files)
if (text.length) this.emit('text', text)
}
}()

View file

@ -1,23 +1,15 @@
/* eslint-env browser */
/* eslint-disable */
// @ts-nocheck
// patched version of debug because there's actually not a way to disable colors globally!
import humanize from 'ms'
/**
* This is the web browser implementation of `debug()`.
*/
const exports = {}
const module = { exports }
const formatters = {}
exports.formatArgs = formatArgs
exports.save = save
exports.load = load
exports.humanize = humanize
exports.useColors = useColors
exports.storage = localstorage()
exports.formatters = formatters
exports.destroy = (() => {
let warned = false
@ -35,6 +27,8 @@ exports.destroy = (() => {
exports.colors = [6, 2, 3, 4, 5, 1]
const { formatters = {} } = module.exports
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
@ -43,6 +37,7 @@ exports.colors = [6, 2, 3, 4, 5, 1]
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
// eslint-disable-next-line complexity
function useColors () {
return true
}
@ -75,7 +70,7 @@ function formatArgs (args) {
*
* @api public
*/
exports.log = console.log || console.debug || (() => {})
exports.log = console.debug || console.log || (() => {})
/**
* Save `namespaces`.
@ -92,7 +87,7 @@ function save (namespaces) {
}
} catch (error) {
// Swallow
// (@Qix-) should we be logging these?
// XXX (@Qix-) should we be logging these?
}
}
@ -108,7 +103,7 @@ function load () {
r = exports.storage.getItem('debug')
} catch (error) {
// Swallow
// (@Qix-) should we be logging these?
// XXX (@Qix-) should we be logging these?
}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
@ -137,7 +132,7 @@ function localstorage () {
return localStorage
} catch (error) {
// Swallow
// (@Qix-) should we be logging these?
// XXX (@Qix-) should we be logging these?
}
}
@ -153,16 +148,6 @@ formatters.j = function (v) {
}
}
formatters.O = function (v) {
try {
return v && typeof v === 'object' ? JSON.stringify(v, null, 2) : v
} catch (error) {
return '[UnexpectedJSONParseError]: ' + error.message
}
}
formatters.o = formatters.j
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
@ -175,7 +160,7 @@ function setup (env) {
createDebug.disable = disable
createDebug.enable = enable
createDebug.enabled = enabled
createDebug.humanize = humanize
createDebug.humanize = require('ms')
createDebug.destroy = destroy
Object.keys(env).forEach(key => {
@ -194,7 +179,7 @@ function setup (env) {
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
createDebug.formatters = formatters
createDebug.formatters = {}
/**
* Selects a color for a debug namespace
@ -248,16 +233,8 @@ function setup (env) {
if (typeof args[0] !== 'string') {
// Anything else let's inspect with %O
args.unshift('%O')
} else {
for (let i = 1; i < args.length; i++) {
if (typeof args[i] === 'object') {
args[0] += ' %j'
}
}
}
// Apply any `formatters` transformations
let index = 0
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
@ -289,7 +266,7 @@ function setup (env) {
debug.useColors = createDebug.useColors()
debug.color = createDebug.selectColor(namespace)
debug.extend = extend
debug.destroy = createDebug.destroy // Temporary. Will be removed in the next major release.
debug.destroy = createDebug.destroy // XXX Temporary. Will be removed in the next major release.
Object.defineProperty(debug, 'enabled', {
enumerable: true,
@ -425,7 +402,7 @@ function setup (env) {
*/
function coerce (val) {
if (val instanceof Error) {
return val.stack ?? val.message
return val.stack || val.message
}
return val
}
@ -443,4 +420,4 @@ function setup (env) {
return createDebug
}
export default setup(exports)
module.exports = setup(exports)

View file

@ -0,0 +1,244 @@
import { settings } from '@/modules/settings.js'
import { sleep } from '../util.js'
import { anilistClient } from '../anilist.js'
import { anitomyscript } from '../anime.js'
import { client } from '@/modules/torrent.js'
import { extensionsWorker } from '@/views/Settings/TorrentSettings.svelte'
import { toast } from 'svelte-sonner'
import Debug from 'debug'
const debug = Debug('ui:extensions')
const exclusions = ['DTS', 'TrueHD', '[EMBER]']
const isDev = location.hostname === 'localhost'
const video = document.createElement('video')
if (!isDev && !video.canPlayType('video/mp4; codecs="hev1.1.6.L93.B0"')) {
exclusions.push('HEVC', 'x265', 'H.265')
}
if (!isDev && !video.canPlayType('audio/mp4; codecs="ac-3"')) {
exclusions.push('AC3', 'AC-3')
}
if (!('audioTracks' in HTMLVideoElement.prototype)) {
exclusions.push('DUAL')
}
video.remove()
/** @typedef {import('@thaunknown/ani-resourced/sources/types.d.ts').Options} Options */
/** @typedef {import('@thaunknown/ani-resourced/sources/types.d.ts').Result} Result */
/**
* @param {{media: import('../al.js').Media, episode?: number, batch: boolean, movie: boolean, resolution: string}} opts
* @returns {Promise<(Result & { parseObject: import('anitomyscript').AnitomyResult })[]>}
* **/
export default async function getResultsFromExtensions ({ media, episode, batch, movie, resolution }) {
const worker = await /** @type {ReturnType<import('@/modules/extensions/worker.js').loadExtensions>} */(extensionsWorker)
if (!(await worker.metadata)?.length) {
debug('No torrent sources configured')
throw new Error('No torrent sources configured. Add extensions in settings.')
}
debug(`Fetching sources for ${media.id}:${media.title.userPreferred} ${episode} ${batch} ${movie} ${resolution}`)
const aniDBMeta = await ALToAniDB(media)
const anidbAid = aniDBMeta?.mappings?.anidb_id
const anidbEid = anidbAid && (await ALtoAniDBEpisode({ media, episode }, aniDBMeta))?.anidbEid
debug(`AniDB Mapping: ${anidbAid} ${anidbEid}`)
/** @type {Options} */
const options = {
anilistId: media.id,
episodeCount: media.episodes,
episode,
anidbAid,
anidbEid,
titles: createTitles(media),
resolution,
exclusions: settings.value.enableExternal ? [] : exclusions
}
const { results, errors } = await worker.query(options, { movie, batch }, settings.value.sources)
debug(`Found ${results.length} results`)
for (const error of errors) {
debug(`Source Fetch Failed: ${error}`)
toast.error('Source Fetch Failed!', {
description: error
})
}
const deduped = dedupe(results)
if (!deduped?.length) throw new Error('No results found. Try specifying a torrent manually.')
const parseObjects = await anitomyscript(deduped.map(({ title }) => title))
// @ts-ignore
for (const i in parseObjects) deduped[i].parseObject = parseObjects[i]
return updatePeerCounts(deduped)
}
async function updatePeerCounts (entries) {
const id = Math.trunc(Math.random() * Number.MAX_SAFE_INTEGER).toString()
debug(`Updating peer counts for ${entries.length} entries`)
const updated = await Promise.race([
new Promise(resolve => {
function check ({ detail }) {
if (detail.id !== id) return
debug('Got scrape response')
client.removeListener('scrape', check)
resolve(detail.result)
}
client.on('scrape', check)
client.send('scrape', { id, infoHashes: entries.map(({ hash }) => hash) })
}),
sleep(15000)
])
debug('Scrape complete')
for (const { hash, complete, downloaded, incomplete } of updated || []) {
const found = entries.find(mapped => mapped.hash === hash)
found.downloads = downloaded
found.leechers = incomplete
found.seeders = complete
}
debug(`Found ${(updated || []).length} entries: ${JSON.stringify(updated)}`)
return entries
}
/** @param {import('../al.js').Media} media */
async function ALToAniDB (media) {
const mappingsResponse = await fetch('https://api.ani.zip/mappings?anilist_id=' + media.id)
const json = await mappingsResponse.json()
if (json.mappings?.anidb_id) return json
const parentID = getParentForSpecial(media)
if (!parentID) return
const parentResponse = await fetch('https://api.ani.zip/mappings?anilist_id=' + parentID)
return parentResponse.json()
}
/** @param {import('../al.js').Media} media */
function getParentForSpecial (media) {
if (!['SPECIAL', 'OVA', 'ONA'].some(format => media.format === format)) return false
const animeRelations = media.relations.edges.filter(({ node }) => node.type === 'ANIME')
return getRelation(animeRelations, 'PARENT') || getRelation(animeRelations, 'PREQUEL') || getRelation(animeRelations, 'SEQUEL')
}
function getRelation (list, type) {
return list.find(({ relationType }) => relationType === type)?.node.id
}
// TODO: https://anilist.co/anime/13055/
/**
* @param {{media: import('../al.js').Media, episode: number}} param0
* @param {{episodes: any, episodeCount: number, specialCount: number}} param1
* */
async function ALtoAniDBEpisode ({ media, episode }, { episodes, episodeCount, specialCount }) {
debug(`Fetching AniDB episode for ${media.id}:${media.title.userPreferred} ${episode}`)
if (!episode || !Object.values(episodes).length) return
// if media has no specials or their episode counts don't match
if (!specialCount || (media.episodes && media.episodes === episodeCount && episodes[Number(episode)])) {
debug('No specials found, or episode count matches between AL and AniDB')
return episodes[Number(episode)]
}
debug(`Episode count mismatch between AL and AniDB for ${media.id}:${media.title.userPreferred}`)
const res = await anilistClient.episodeDate({ id: media.id, ep: episode })
// TODO: if media only has one episode, and airdate doesn't exist use start/release/end dates
const alDate = new Date((res.data.AiringSchedule?.airingAt || 0) * 1000)
debug(`AL Airdate: ${alDate}`)
return episodeByAirDate(alDate, episodes, episode)
}
/**
* @param {Date} alDate
* @param {any} episodes
* @param {number} episode
**/
export function episodeByAirDate (alDate, episodes, episode) {
// TODO handle special cases where anilist reports that 3 episodes aired at the same time because of pre-releases
if (!+alDate) return episodes[Number(episode)] || episodes[1] // what the fuck, are you braindead anilist?, the source episode number to play is from an array created from AL ep count, so how come it's missing?
// 1 is key for episod 1, not index
// find closest episodes by air date, multiple episodes can have the same air date distance
// ineffcient but reliable
const closestEpisodes = Object.values(episodes).reduce((prev, curr) => {
if (!prev[0]) return [curr]
const prevDate = Math.abs(+new Date(prev[0]?.airdate) - +alDate)
const currDate = Math.abs(+new Date(curr.airdate) - +alDate)
if (prevDate === currDate) {
prev.push(curr)
return prev
}
if (currDate < prevDate) return [curr]
return prev
}, [])
return closestEpisodes.reduce((prev, curr) => {
return Math.abs(curr.episodeNumber - episode) < Math.abs(prev.episodeNumber - episode) ? curr : prev
})
}
/** @param {import('../al.js').Media} media */
function createTitles (media) {
// group and de-duplicate
const grouped = [...new Set(
Object.values(media.title)
.concat(media.synonyms)
.filter(name => name != null && name.length > 3)
)]
const titles = []
/** @param {string} title */
const appendTitle = title => {
// replace & with encoded
// title = title.replace(/&/g, '%26').replace(/\?/g, '%3F').replace(/#/g, '%23')
titles.push(title)
// replace Season 2 with S2, else replace 2nd Season with S2, but keep the original title
const match1 = title.match(/(\d)(?:nd|rd|th) Season/i)
const match2 = title.match(/Season (\d)/i)
if (match2) {
titles.push(title.replace(/Season \d/i, `S${match2[1]}`))
} else if (match1) {
titles.push(title.replace(/(\d)(?:nd|rd|th) Season/i, `S${match1[1]}`))
}
}
for (const t of grouped) {
appendTitle(t)
if (t.includes('-')) appendTitle(t.replaceAll('-', ''))
}
return titles
}
/** @param {Result[]} entries */
function dedupe (entries) {
/** @type {Record<string, Result>} */
const deduped = {}
for (const entry of entries) {
if (deduped[entry.hash]) {
const dupe = deduped[entry.hash]
dupe.title ??= entry.title
dupe.link ??= entry.link
dupe.id ||= entry.id
dupe.seeders ||= entry.seeders >= 30000 ? 0 : entry.seeders
dupe.leechers ||= entry.leechers >= 30000 ? 0 : entry.leechers
dupe.downloads ||= entry.downloads
dupe.size ||= entry.size
dupe.verified ||= entry.verified
dupe.date ||= entry.date
dupe.type ??= entry.type
} else {
deduped[entry.hash] = entry
}
}
return Object.values(deduped)
}

View file

@ -0,0 +1,79 @@
import { expose, proxy } from 'comlink'
/** @typedef {import('@thaunknown/ani-resourced/sources/types.d.ts').Options} Options */
/** @typedef {import('@thaunknown/ani-resourced/sources/types.d.ts').Result} Result */
/** @typedef {import('@thaunknown/ani-resourced/sources/abstract.js').default} AbstractSource */
class Extensions {
sources
metadata
/** @param {AbstractSource[]} sources */
constructor (sources) {
this.sources = sources
this.metadata = sources.map(({ accuracy, name, description, config }) => ({ accuracy, name, description, config }))
}
/**
* @param {Options} options
* @param {{ movie: boolean, batch: boolean }} types
* @param {Record<string, boolean>} sourcesToQuery
*/
async query (options, types, sourcesToQuery) {
/** @type {Promise<{ results: Result[], errors: string[] }>[]} */
const promises = []
for (const source of Object.values(this.sources)) {
if (!sourcesToQuery[source.name]) continue
promises.push(this._querySource(source, options, types))
}
/** @type {Result[]} */
const results = []
const errors = []
for (const res of await Promise.all(promises)) {
results.push(...res.results)
errors.push(...res.errors)
}
return { results, errors }
}
/**
* @param {AbstractSource} source
* @param {Options} options
* @param {{ movie: boolean, batch: boolean }} types
* @returns {Promise<{ results: Result[], errors: string[] }>}
*/
async _querySource (source, options, { movie, batch }) {
const promises = []
promises.push(source.single(options))
if (movie) promises.push(source.movie(options))
if (batch) promises.push(source.batch(options))
const results = []
const errors = []
for (const result of await Promise.allSettled(promises)) {
if (result.status === 'fulfilled') {
results.push(...result.value)
} else {
console.error(result)
errors.push('Source ' + source.name + ' failed to load results:\n' + result.reason.message)
}
}
return { results, errors }
}
}
/** @param {string[]} extensions */
export async function loadExtensions (extensions) {
const sources = (await Promise.all(extensions.map(async extension => {
try {
if (!extension.startsWith('http')) extension = `https://esm.sh/${extension}`
return Object.values(await import(/* webpackIgnore: true */extension))
} catch (error) {
return []
}
}))).flat()
return proxy(new Extensions(sources))
}
expose(loadExtensions)

1
common/modules/ipc.js Normal file
View file

@ -0,0 +1 @@
export default window.IPC

76
common/modules/parser.js Normal file
View file

@ -0,0 +1,76 @@
import Metadata from 'matroska-metadata'
import Debug from 'debug'
import { arr2hex, hex2bin } from 'uint8-util'
import { fontRx } from './util.js'
import { SUPPORTS } from '@/modules/support.js'
const debug = Debug('torrent:parser')
export default class Parser {
parsed = false
/** @type {Metadata} */
metadata = null
client = null
file = null
destroyed = false
constructor (client, file) {
debug('Initializing parser for file: ' + file.name)
this.client = client
this.file = file
this.metadata = new Metadata(file)
this.metadata.getTracks().then(tracks => {
if (this.destroyed) return
debug('Tracks received: ' + tracks)
if (!tracks.length) {
this.parsed = true
this.destroy()
} else {
this.client.dispatch('tracks', tracks)
}
})
this.metadata.getChapters().then(chapters => {
if (this.destroyed) return
debug(`Found ${chapters.length} chapters`)
this.client.dispatch('chapters', chapters)
})
this.metadata.getAttachments().then(files => {
if (this.destroyed) return
debug(`Found ${files.length} attachments`)
for (const file of files) {
if (fontRx.test(file.filename) || file.mimetype?.toLowerCase().includes('font')) {
const data = hex2bin(arr2hex(file.data))
if (SUPPORTS.isAndroid && data.length > 15_000_000) {
debug('Skipping large font file on Android: ' + file.filename)
continue
}
this.client.dispatch('file', data)
}
}
})
this.metadata.on('subtitle', (subtitle, trackNumber) => {
if (this.destroyed) return
debug(`Found subtitle for track: ${trackNumber}: ${subtitle.text}`)
this.client.dispatch('subtitle', { subtitle, trackNumber })
})
if (this.file.name.endsWith('.mkv') || this.file.name.endsWith('.webm')) {
this.file.on('iterator', ({ iterator }, cb) => {
if (this.destroyed) return cb(iterator)
cb(this.metadata.parseStream(iterator))
})
} else {
debug('Unsupported file format: ' + this.file.name)
}
}
destroy () {
debug('Destroying Parser')
this.destroyed = true
// Add any additional cleanup code here
}
}

145
common/modules/rss.js Normal file
View file

@ -0,0 +1,145 @@
import { DOMPARSER } from '@/modules/util.js'
import { settings } from '@/modules/settings.js'
import { toast } from 'svelte-sonner'
import { add } from '@/modules/torrent.js'
import { getEpisodeMetadataForMedia } from './anime.js'
import AnimeResolver from '@/modules/animeresolver.js'
import { hasNextPage } from '@/modules/sections.js'
import IPC from '@/modules/ipc.js'
import Debug from 'debug'
const debug = Debug('ui:rss')
export function parseRSSNodes (nodes) {
return nodes.map(item => {
const pubDate = item.querySelector('pubDate')?.textContent
return {
title: item.querySelector('title')?.textContent || '?',
link: item.querySelector('enclosure')?.attributes.url.value || item.querySelector('link')?.textContent || '?',
seeders: item.querySelector('seeders')?.textContent ?? '?',
leechers: item.querySelector('leechers')?.textContent ?? '?',
downloads: item.querySelector('downloads')?.textContent ?? '?',
size: item.querySelector('size')?.textContent ?? '?',
date: pubDate && new Date(pubDate)
}
})
}
const rssmap = {
SubsPlease: settings.value.toshoURL + 'rss2?qx=1&q="[SubsPlease] "',
'Erai-raws [Multi-Sub]': settings.value.toshoURL + 'rss2?qx=1&q="[Erai-raws] "',
'Yameii [Dubbed]': settings.value.toshoURL + 'rss2?qx=1&q="[Yameii] "',
'Judas [Small Size]': settings.value.toshoURL + 'rss2?qx=1&q="[Judas] "'
}
export function getReleasesRSSurl (val) {
const rss = rssmap[val] || val
return rss && new URL(rssmap[val] ? `${rss}${settings.value.rssQuality ? `"${settings.value.rssQuality}"` : ''}` : rss)
}
export async function getRSSContent (url) {
if (!url) return null
const res = await fetch(url)
if (!res.ok) {
debug(`Failed to fetch RSS feed: ${res.statusText}`)
throw new Error(res.statusText)
}
return DOMPARSER(await res.text(), 'text/xml')
}
class RSSMediaManager {
constructor () {
this.resultMap = {}
}
getMediaForRSS (page, perPage, url, ignoreErrors) {
const res = this._getMediaForRSS(page, perPage, url)
if (!ignoreErrors) {
res.catch(e => {
toast.error('Search Failed', {
description: 'Failed to load media for home feed!\n' + e.message
})
debug('Failed to load media for home feed', e.stack)
})
}
return Array.from({ length: perPage }, (_, i) => ({ type: 'episode', data: this.fromPending(res, i) }))
}
async fromPending (result, i) {
const array = await result
return array[i]
}
async getContentChanged (page, perPage, url) {
const content = await getRSSContent(getReleasesRSSurl(url))
if (!content) return false
const pubDate = +(new Date(content.querySelector('pubDate').textContent)) * page * perPage
if (this.resultMap[url]?.date === pubDate) return false
return { content, pubDate }
}
async _getMediaForRSS (page, perPage, url) {
debug(`Getting media for RSS feed ${url} page ${page} perPage ${perPage}`)
const changed = await this.getContentChanged(page, perPage, url)
if (!changed) return this.resultMap[url].result
debug(`Feed ${url} has changed, updating`)
const index = (page - 1) * perPage
const targetPage = [...changed.content.querySelectorAll('item')].slice(index, index + perPage)
const items = parseRSSNodes(targetPage)
hasNextPage.value = items.length === perPage
const result = this.structureResolveResults(items)
this.findNewReleasesAndNotify(result, this.resultMap[url]?.date)
this.resultMap[url] = {
date: changed.pubDate,
result
}
return result
}
async findNewReleasesAndNotify (results, oldDate) {
if (!oldDate) return
const res = await Promise.all(await results)
const newReleases = res.filter(({ date }) => date > oldDate)
debug(`Found ${newReleases.length} new releases, notifying...`)
for (const { media, parseObject, episode } of newReleases) {
const options = {
title: media?.title.userPreferred || parseObject.anime_title,
body: `Episode ${episode || 1} is out!`,
icon: media?.coverImage.medium,
data: { id: media?.id }
}
IPC.emit('notification', options)
}
}
async structureResolveResults (items) {
const results = await AnimeResolver.resolveFileAnime(items.map(item => item.title))
return results.map(async (result, i) => {
const res = {
...result,
episodeData: undefined,
date: undefined,
onclick: undefined
}
if (res.media?.id) {
try {
res.episodeData = (await getEpisodeMetadataForMedia(res.media))?.[res.episode]
} catch (e) {
debug(`Warn: failed fetching episode metadata for ${res.media.title.userPreferred} episode ${res.episode}: ${e.stack}`)
}
}
res.date = items[i].date
res.onclick = () => add(items[i].link)
return res
})
}
}
export const RSSManager = new RSSMediaManager()

40
common/modules/scroll.js Normal file
View file

@ -0,0 +1,40 @@
import { settings } from '@/modules/settings.js'
export default function (t, { speed = 120, smooth = 10 } = {}) {
if (!settings.value.smoothScroll) return
let moving = false
let pos = 0
let scrollTop = 0
let lastTime = null
t.addEventListener('wheel', e => {
e.preventDefault()
// is trackpad
const spd = (e.deltaY !== (e.deltaY | 0) || e.wheelDelta % 10 !== 0) ? speed / 10 : speed
pos = Math.max(0, Math.min(pos - Math.max(-1, Math.min(1, e.deltaY * -1)) * spd, (t.scrollHeight - t.clientHeight) + (smooth * 2)))
if (!moving) {
lastTime = null
update()
}
}, { capture: true, passive: false })
function getDeltaTime () {
const now = performance.now()
if (!lastTime) {
lastTime = now
return 1
}
const deltaTime = now - lastTime
lastTime = now
return deltaTime / 14
}
t.addEventListener('pointerup', () => { pos = scrollTop = t.scrollTop })
function update () {
const delta = pos - scrollTop === smooth * 2 ? 0 : ((pos - scrollTop) / smooth) * getDeltaTime()
scrollTop += delta
t.scrollTo(0, scrollTop < 1.3 ? 0 : scrollTop)
moving = Math.abs(delta) > 0.1 && !!requestAnimationFrame(update)
}
}

195
common/modules/sections.js Normal file
View file

@ -0,0 +1,195 @@
import { anilistClient, currentSeason, currentYear } from '@/modules/anilist.js'
import { writable } from 'simple-store-svelte'
import { settings, alToken } from '@/modules/settings.js'
import { RSSManager } from '@/modules/rss.js'
export const hasNextPage = writable(true)
export default class SectionsManager {
constructor (data = []) {
this.sections = []
for (const section of data) this.add(section)
}
/**
* @param {object} data
*/
add (data) {
if (!data) return
const { title, variables = {}, type, load = SectionsManager.createFallbackLoad(variables, type), preview = writable() } = data
const section = { ...data, load, title, preview, variables }
this.sections.push(section)
return section
}
static createFallbackLoad (variables, type) {
return (page = 1, perPage = 50, search = variables) => {
const options = { page, perPage, ...SectionsManager.sanitiseObject(search) }
const res = anilistClient.search(options)
return SectionsManager.wrapResponse(res, perPage, type)
}
}
static wrapResponse (res, length, type) {
res.then(res => {
hasNextPage.value = res?.data?.Page.pageInfo.hasNextPage
})
return Array.from({ length }, (_, i) => ({ type, data: SectionsManager.fromPending(res, i) }))
}
static sanitiseObject (object = {}) {
const safe = {}
for (const [key, value] of Object.entries(object)) {
if (value) safe[key] = value
}
return safe
}
static async fromPending (arr, i) {
const { data } = await arr
return data?.Page.media[i]
}
}
// list of all possible home screen sections
export let sections = []
settings.subscribe(() => {
for (const section of sections) clearInterval(section.interval)
sections = createSections()
})
function createSections () {
return [
// RSS feeds
...settings.value.rssFeedsNew.map(([title, url]) => {
const section = {
title,
load: (page = 1, perPage = 12) => RSSManager.getMediaForRSS(page, perPage, url),
preview: writable(RSSManager.getMediaForRSS(1, 12, url)),
variables: { disableSearch: true },
isRSS: true
}
// update every 30 seconds
section.interval = setInterval(async () => {
if (await RSSManager.getContentChanged(1, 12, url)) {
section.preview.value = RSSManager.getMediaForRSS(1, 12, url, true)
}
}, 30000)
return section
}),
// user specific sections
{
title: 'Continue Watching',
load: (page = 1, perPage = 50, variables = {}) => {
const res = anilistClient.userLists.value.then(async res => {
const mediaList = res.data.MediaListCollection.lists.reduce((filtered, { status, entries }) => {
return (status === 'CURRENT' || status === 'REPEATING') ? filtered.concat(entries) : filtered
}, [])
const ids = mediaList.filter(({ media }) => {
if (media.status === 'FINISHED') return true
return media.mediaListEntry?.progress < media.nextAiringEpisode?.episode - 1
}).map(({ media }) => media.id)
if (!ids.length) return {}
// if custom search is used, respect it, otherwise sort by last updated
if (Object.values(variables).length !== 0) {
return anilistClient.searchIDS({ page, perPage, id: ids, ...SectionsManager.sanitiseObject(variables) })
}
const index = (page - 1) * perPage
const idsRes = await anilistClient.searchIDS({ page, perPage, id: ids.slice(index, index + perPage), ...SectionsManager.sanitiseObject(variables) })
idsRes.data.Page.media.sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id))
return idsRes
})
return SectionsManager.wrapResponse(res, perPage)
},
hide: !alToken
},
{
title: 'Sequels You Missed',
load: (page = 1, perPage = 50, variables = {}) => {
const res = anilistClient.userLists.value.then(res => {
const mediaList = res.data.MediaListCollection.lists.find(({ status }) => status === 'COMPLETED')?.entries
if (!mediaList) return {}
const ids = mediaList.flatMap(({ media }) => {
return media.relations.edges.filter(edge => edge.relationType === 'SEQUEL')
}).map(({ node }) => node.id)
if (!ids.length) return {}
return anilistClient.searchIDS({ page, perPage, id: ids, ...SectionsManager.sanitiseObject(variables), status: ['FINISHED', 'RELEASING'], onList: false })
})
return SectionsManager.wrapResponse(res, perPage)
},
hide: !alToken
},
{
title: 'Your List',
load: (page = 1, perPage = 50, variables = {}) => {
const res = anilistClient.userLists.value.then(res => {
const ids = res.data.MediaListCollection.lists.find(({ status }) => status === 'PLANNING')?.entries.map(({ media }) => media.id)
if (!ids) return {}
return anilistClient.searchIDS({ page, perPage, id: ids, ...SectionsManager.sanitiseObject(variables) })
})
return SectionsManager.wrapResponse(res, perPage)
},
hide: !alToken
},
{
title: 'Completed List',
load: (page = 1, perPage = 50, variables = {}) => {
const res = anilistClient.userLists.value.then(res => {
const ids = res.data.MediaListCollection.lists.find(({ status }) => status === 'COMPLETED')?.entries.map(({ media }) => media.id)
if (!ids) return {}
return anilistClient.searchIDS({ page, perPage, id: ids, ...SectionsManager.sanitiseObject(variables) })
})
return SectionsManager.wrapResponse(res, perPage)
},
hide: !alToken
},
{
title: 'Paused List',
load: (page = 1, perPage = 50, variables = {}) => {
const res = anilistClient.userLists.value.then(res => {
const ids = res.data.MediaListCollection.lists.find(({ status }) => status === 'PAUSED')?.entries.map(({ media }) => media.id)
if (!ids) return {}
return anilistClient.searchIDS({ page, perPage, id: ids, ...SectionsManager.sanitiseObject(variables) })
})
return SectionsManager.wrapResponse(res, perPage)
},
hide: !alToken
},
{
title: 'Dropped List',
load: (page = 1, perPage = 50, variables = {}) => {
const res = anilistClient.userLists.value.then(res => {
const ids = res.data.MediaListCollection.lists.find(({ status }) => status === 'DROPPED')?.entries.map(({ media }) => media.id)
if (!ids) return {}
return anilistClient.searchIDS({ page, perPage, id: ids, ...SectionsManager.sanitiseObject(variables) })
})
return SectionsManager.wrapResponse(res, perPage)
},
hide: !alToken
},
{
title: 'Currently Watching List',
load: (page = 1, perPage = 50, variables = {}) => {
const res = anilistClient.userLists.value.then(res => {
const ids = res.data.MediaListCollection.lists.find(({ status }) => status === 'CURRENT')?.entries.map(({ media }) => media.id)
if (!ids) return {}
return anilistClient.searchIDS({ page, perPage, id: ids, ...SectionsManager.sanitiseObject(variables) })
})
return SectionsManager.wrapResponse(res, perPage)
},
hide: !alToken
},
// common, non-user specific sections
{ title: 'Popular This Season', variables: { sort: 'POPULARITY_DESC', season: currentSeason, year: currentYear } },
{ title: 'Trending Now', variables: { sort: 'TRENDING_DESC' } },
{ title: 'All Time Popular', variables: { sort: 'POPULARITY_DESC' } },
{ title: 'Romance', variables: { sort: 'TRENDING_DESC', genre: 'Romance' } },
{ title: 'Action', variables: { sort: 'TRENDING_DESC', genre: 'Action' } },
{ title: 'Adventure', variables: { sort: 'TRENDING_DESC', genre: 'Adventure' } },
{ title: 'Fantasy', variables: { sort: 'TRENDING_DESC', genre: 'Fantasy' } }
]
}

View file

@ -0,0 +1,70 @@
import { writable } from 'simple-store-svelte'
import { defaults } from './util.js'
import IPC from '@/modules/ipc.js'
import { anilistClient } from './anilist.js'
import { toast } from 'svelte-sonner'
import Debug from 'debug'
const debug = Debug('ui:anilist')
/** @type {{viewer: import('./al').Query<{Viewer: import('./al').Viewer}>, token: string} | null} */
export let alToken = JSON.parse(localStorage.getItem('ALviewer')) || null
let storedSettings = { ...defaults }
let scopedDefaults
try {
storedSettings = JSON.parse(localStorage.getItem('settings')) || { ...defaults }
} catch (e) {}
try {
scopedDefaults = {
homeSections: [...(storedSettings.rssFeedsNew || defaults.rssFeedsNew).map(([title]) => title), 'Continue Watching', 'Sequels You Missed', 'Your List', 'Popular This Season', 'Trending Now', 'All Time Popular', 'Romance', 'Action', 'Adventure', 'Fantasy', 'Comedy']
}
} catch (e) {
resetSettings()
location.reload()
}
/**
* @type {import('simple-store-svelte').Writable<typeof defaults>}
*/
export const settings = writable({ ...defaults, ...scopedDefaults, ...storedSettings })
settings.subscribe(value => {
localStorage.setItem('settings', JSON.stringify(value))
})
export function resetSettings () {
settings.value = { ...defaults, ...scopedDefaults }
}
window.addEventListener('paste', ({ clipboardData }) => {
if (clipboardData.items?.[0]) {
if (clipboardData.items[0].type === 'text/plain' && clipboardData.items[0].kind === 'string') {
clipboardData.items[0].getAsString(text => {
let token = text.split('access_token=')?.[1]?.split('&token_type')?.[0]
if (token) {
if (token.endsWith('/')) token = token.slice(0, -1)
handleToken(token)
}
})
}
}
})
IPC.on('altoken', handleToken)
async function handleToken (token) {
alToken = { token, viewer: null }
const viewer = await anilistClient.viewer({ token })
if (!viewer.data?.Viewer) {
toast.error('Failed to sign in with AniList. Please try again.', { description: JSON.stringify(viewer) })
debug(`Failed to sign in with AniList: ${JSON.stringify(viewer)}`)
return
}
const lists = viewer?.data?.Viewer?.mediaListOptions?.animeList?.customLists || []
if (!lists.includes('Watched using Miru')) {
await anilistClient.customList({ lists })
}
localStorage.setItem('ALviewer', JSON.stringify({ token, viewer }))
location.reload()
}

313
common/modules/subtitles.js Normal file
View file

@ -0,0 +1,313 @@
import JASSUB from 'jassub'
import { hex2arr, bin2hex } from 'uint8-util'
import { toTS, subRx, videoRx } from './util.js'
import { settings } from '@/modules/settings.js'
import { client } from '@/modules/torrent.js'
import clipboard from './clipboard.js'
import { SUPPORTS } from '@/modules/support.js'
const defaultHeader = `[Script Info]
Title: English (US)
ScriptType: v4.00+
WrapStyle: 0
PlayResX: 1280
PlayResY: 720
ScaledBorderAndShadow: yes
[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Default, ${settings.value.font?.name.toLowerCase() || 'Roboto Medium'},52,&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2.6,0,2,20,20,46,1
[Events]
`
const stylesRx = /^Style:[^,]*/gm
export default class Subtitles {
constructor (video, files, selected, onHeader) {
this.video = video
this.selected = selected || null
this.files = files || []
this.headers = []
this.tracks = []
this._tracksString = []
this._stylesMap = []
this.fonts = ['/Roboto.ttf']
this.renderer = null
this.parsed = false
this.stream = null
this.parser = null
this.current = 0
this.onHeader = onHeader
this.videoFiles = files.filter(file => videoRx.test(file.name))
this.subtitleFiles = []
this.timeout = null
this.handleFile = ({ detail }) => {
if (this.selected) {
const uint8 = hex2arr(bin2hex(detail))
this.fonts.push(uint8)
this.renderer?.addFont(uint8)
}
}
this.handleSubtitle = ({ detail }) => {
const { subtitle, trackNumber } = detail
if (this.selected) {
const string = JSON.stringify(subtitle)
if (this._tracksString[trackNumber] && !this._tracksString[trackNumber].has(string)) {
this._tracksString[trackNumber].add(string)
const assSub = this.constructSub(subtitle, this.headers[trackNumber].type !== 'ass', this.tracks[trackNumber].length, trackNumber)
this.tracks[trackNumber].push(assSub)
if (this.current === trackNumber) this.renderer?.createEvent(assSub)
}
}
}
this.handleTracks = ({ detail }) => {
if (this.selected) {
for (const track of detail) {
if (!this.tracks[track.number]) {
// overwrite webvtt or other header with custom one
if (track.type !== 'ass') track.header = defaultHeader
this.tracks[track.number] = []
this._tracksString[track.number] = new Set()
this.headers[track.number] = track
this._stylesMap[track.number] = {
Default: 0
}
const styleMatches = track.header.match(stylesRx)
for (let i = 0; i < styleMatches.length; ++i) {
const style = styleMatches[i].replace('Style:', '').trim()
this._stylesMap[track.number][style] = i + 1
}
this.onHeader()
}
}
this.initSubtitleRenderer()
const tracks = this.headers?.filter(t => t)
if (tracks?.length && settings.value.subtitleLanguage) {
if (tracks.length === 1) {
this.selectCaptions(tracks[0].number)
} else {
const wantedTrack = tracks.find(({ language }) => {
if (language == null) language = 'eng'
return language === settings.value.subtitleLanguage
})
if (wantedTrack) return this.selectCaptions(wantedTrack.number)
const englishTrack = tracks.find(({ language }) => language === null || language === 'eng')
if (englishTrack) return this.selectCaptions(englishTrack.number)
this.selectCaptions(tracks[0].number)
}
}
}
}
this.handleClipboardText = ({ detail }) => {
for (const { text, type } of detail) {
if (text.startsWith('[Script Info]')) this.addSingleSubtitleFile(new File([text], 'Subtitle', { type }))
}
}
this.handleClipboardFiles = ({ detail }) => {
for (const file of detail) {
if (subRx.test(file.name)) this.addSingleSubtitleFile(file)
}
}
this.handleSubtitleFile = ({ detail }) => {
this.addSingleSubtitleFile(new File([detail.data], detail.name))
}
client.on('tracks', this.handleTracks)
client.on('subtitle', this.handleSubtitle)
client.on('file', this.handleFile)
client.on('subtitleFile', this.handleSubtitleFile)
clipboard.on('text', this.handleClipboardText)
clipboard.on('files', this.handleClipboardFiles)
}
async addSingleSubtitleFile (file) {
// lets hope there's no more than 100 subtitle tracks in a file
const index = 100 + this.headers.length
this.subtitleFiles[index] = file
const type = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase()
const subname = file.name.slice(0, file.name.lastIndexOf('.'))
// sub name could contain video name with or without extension, possibly followed by lang, or not.
const name = subname.includes(this.selected.name)
? subname.replace(this.selected.name, '')
: subname.replace(this.selected.name.slice(0, this.selected.name.lastIndexOf('.')), '')
this.headers[index] = {
header: defaultHeader,
language: name.replace(/[,._-]/g, ' ').trim() || 'Track ' + index,
number: index,
type
}
this.onHeader()
this.tracks[index] = []
const subtitles = Subtitles.convertSubText(await file.text(), type)
if (type === 'ass') {
this.headers[index].header = subtitles
} else {
this.headers[index].header += subtitles.join('\n')
}
if (!this.current) {
this.current = index
this.initSubtitleRenderer()
this.selectCaptions(this.current)
this.onHeader()
}
}
initSubtitleRenderer () {
if (!this.renderer) {
const options = {
video: this.video,
subContent: defaultHeader,
fonts: this.fonts,
offscreenRender: SUPPORTS.offscreenRender,
libassMemoryLimit: 1024,
libassGlyphLimit: 80000,
maxRenderHeight: parseInt(settings.value.subtitleRenderHeight) || 0,
fallbackFont: settings.value.font?.name || 'roboto medium',
availableFonts: {
'roboto medium': './Roboto.ttf'
},
workerUrl: new URL('jassub/dist/jassub-worker.js', import.meta.url).toString(),
wasmUrl: new URL('jassub/dist/jassub-worker.wasm', import.meta.url).toString(),
legacyWasmUrl: new URL('jassub/dist/jassub-worker.wasm.js', import.meta.url).toString(),
modernWasmUrl: new URL('jassub/dist/jassub-worker-modern.wasm', import.meta.url).toString(),
useLocalFonts: settings.value.missingFont,
dropAllBlur: settings.value.disableSubtitleBlur
}
this.renderer = new JASSUB(options)
}
}
static convertSubText (text, type) {
const srtRx = /(?:\d+\r?\n)?(\S{9,12})\s?-->\s?(\S{9,12})(.*)\r?\n([\s\S]*)$/i
const srt = text => {
const subtitles = []
const replaced = text.replace(/\r/g, '')
for (const split of replaced.split(/\r?\n\r?\n/)) {
const match = split.match(srtRx)
if (match) {
// timestamps
match[1] = match[1].match(/.*[.,]\d{2}/)[0]
match[2] = match[2].match(/.*[.,]\d{2}/)[0]
if (match[1].length === 9) {
match[1] = '0:' + match[1]
} else {
if (match[1][0] === '0') {
match[1] = match[1].substring(1)
}
}
match[1].replace(',', '.')
if (match[2].length === 9) {
match[2] = '0:' + match[2]
} else {
if (match[2][0] === '0') {
match[2] = match[2].substring(1)
}
}
match[2].replace(',', '.')
// create array of all tags
const matches = match[4].match(/<[^>]+>/g)
if (matches) {
matches.forEach(matched => {
if (/<\//.test(matched)) { // check if its a closing tag
match[4] = match[4].replace(matched, matched.replace('</', '{\\').replace('>', '0}'))
} else {
match[4] = match[4].replace(matched, matched.replace('<', '{\\').replace('>', '1}'))
}
})
}
subtitles.push('Dialogue: 0,' + match[1].replace(',', '.') + ',' + match[2].replace(',', '.') + ',Default,,0,0,0,,' + match[4].replace(/\r?\n/g, '\\N'))
}
}
return subtitles
}
const subRx = /[{[](\d+)[}\]][{[](\d+)[}\]](.+)/i
const sub = text => {
const subtitles = []
const replaced = text.replace(/\r/g, '')
let frames = 1000 / Number(replaced.match(subRx)[3])
if (!frames || isNaN(frames)) frames = 41.708
for (const split of replaced.split('\r?\n')) {
const match = split.match(subRx)
if (match) subtitles.push('Dialogue: 0,' + toTS((match[1] * frames) / 1000, 1) + ',' + toTS((match[2] * frames) / 1000, 1) + ',Default,,0,0,0,,' + match[3].replace('|', '\\N'))
}
return subtitles
}
const subtitles = type === 'ass' ? text : []
if (type === 'ass') {
return subtitles
} else if (type === 'srt' || type === 'vtt') {
return srt(text)
} else if (type === 'sub') {
return sub(text)
} else {
// subbers have a tendency to not set the extensions properly
if (srtRx.test(text)) return srt(text)
if (subRx.test(text)) return sub(text)
}
}
constructSub (subtitle, isNotAss, subtitleIndex, trackNumber) {
if (isNotAss === true) { // converts VTT or other to SSA
const matches = subtitle.text.match(/<[^>]+>/g) // create array of all tags
if (matches) {
matches.forEach(match => {
if (/<\//.test(match)) { // check if its a closing tag
subtitle.text = subtitle.text.replace(match, match.replace('</', '{\\').replace('>', '0}'))
} else {
subtitle.text = subtitle.text.replace(match, match.replace('<', '{\\').replace('>', '1}'))
}
})
}
// replace all html special tags with normal ones
subtitle.text = subtitle.text.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&nbsp;/g, '\\h').replace(/\r?\n/g, '\\N')
}
return {
Start: subtitle.time,
Duration: subtitle.duration,
Style: this._stylesMap[trackNumber][subtitle.style || 'Default'] || 0,
Name: subtitle.name || '',
MarginL: Number(subtitle.marginL) || 0,
MarginR: Number(subtitle.marginR) || 0,
MarginV: Number(subtitle.marginV) || 0,
Effect: subtitle.effect || '',
Text: subtitle.text || '',
ReadOrder: 1,
Layer: Number(subtitle.layer) || 0,
_index: subtitleIndex
}
}
selectCaptions (trackNumber) {
if (trackNumber != null) {
this.current = Number(trackNumber)
this.onHeader()
if (this.headers) {
this.renderer?.setTrack(this.current !== -1 ? this.headers[this.current].header.slice(0, -1) : defaultHeader)
if (this.tracks[this.current]) {
if (this.renderer) for (const subtitle of this.tracks[this.current]) this.renderer.createEvent(subtitle)
}
}
}
}
destroy () {
client.off('tracks', this.handleTracks)
client.off('subtitle', this.handleSubtitle)
client.off('file', this.handleFile)
client.off('files', this.handleClipboardFiles)
client.off('text', this.handleClipboardText)
client.off('subtitleFile', this.handleSubtitleFile)
this.stream?.destroy()
this.parser?.destroy()
this.renderer?.destroy()
this.files = null
this.video = null
this.selected = null
this.tracks = null
this.headers = null
this.onHeader()
}
}

14
common/modules/support.js Normal file
View file

@ -0,0 +1,14 @@
// feature support list, overriden per environment, global
export const SUPPORTS = {
offscreenRender: true,
update: true,
angle: true,
doh: true,
discord: true,
keybinds: true,
extensions: true,
isAndroid: false,
externalPlayer: true,
permamentNAT: true
}

13
common/modules/themes.js Normal file
View file

@ -0,0 +1,13 @@
import { append, element } from 'svelte/internal'
import { writable } from 'simple-store-svelte'
const style = element('style')
style.id = 'customThemes'
append(document.head, style)
export const variables = writable(localStorage.getItem('theme') || '')
variables.subscribe(value => {
localStorage.setItem('theme', value)
style.textContent = `:root{${value.replace(/{|}/g, '')}}`
})

97
common/modules/torrent.js Normal file
View file

@ -0,0 +1,97 @@
import { files, media } from '../views/Player/MediaHandler.svelte'
import { page } from '@/App.svelte'
import { toast } from 'svelte-sonner'
import clipboard from './clipboard.js'
import IPC from '@/modules/ipc.js'
import 'browser-event-target-emitter'
import Debug from 'debug'
const debug = Debug('ui:torrent')
const torrentRx = /(^magnet:){1}|(^[A-F\d]{8,40}$){1}|(.*\.torrent$){1}/i
class TorrentWorker extends EventTarget {
constructor () {
super()
this.ready = new Promise(resolve => {
IPC.once('port', () => {
this.port = window.port
this.port.onmessage(this.handleMessage.bind(this))
resolve()
})
IPC.emit('portRequest')
})
clipboard.on('text', ({ detail }) => {
for (const { text } of detail) {
if (torrentRx.exec(text)) {
media.set(null)
add(text)
}
}
})
clipboard.on('files', async ({ detail }) => {
for (const file of detail) {
if (file.name.endsWith('.torrent')) {
media.set(null)
add(new Uint8Array(await file.arrayBuffer()))
}
}
})
}
handleMessage ({ data }) {
this.emit(data.type, data.data)
}
async send (type, data, transfer) {
await this.ready
debug(`Sending message ${type}`, data)
this.port.postMessage({ type, data }, transfer)
}
}
export const client = new TorrentWorker()
client.send('load', localStorage.getItem('torrent'))
client.on('files', ({ detail }) => {
files.set(detail)
})
client.on('error', ({ detail }) => {
debug(`Error: ${detail.message || detail}`)
toast.error('Torrent Error', { description: '' + (detail.message || detail) })
})
client.on('warn', ({ detail }) => {
debug(`Warn: ${detail.message || detail}`)
toast.warning('Torrent Warning', { description: '' + (detail.message || detail) })
})
client.on('info', ({ detail }) => {
debug(`Info: ${detail.message || detail}`)
toast('Torrent Info', { description: '' + (detail.message || detail) })
})
export async function add (torrentID, hide) {
if (torrentID) {
debug('Adding torrent', { torrentID })
if (torrentID.startsWith?.('magnet:')) {
localStorage.setItem('torrent', JSON.stringify(torrentID))
} else {
localStorage.setItem('torrent', torrentID)
}
files.set([])
if (!hide) page.set('player')
client.send('torrent', torrentID)
}
}
// external player for android
client.on('open', ({ detail }) => {
debug(`Open: ${detail}`)
IPC.emit('intent', detail)
})
IPC.on('intent-end', () => {
client.dispatch('externalWatched')
})

171
common/modules/util.js Normal file
View file

@ -0,0 +1,171 @@
import { SUPPORTS } from '@/modules/support.js'
export function countdown (s) {
const d = Math.floor(s / (3600 * 24))
s -= d * 3600 * 24
const h = Math.floor(s / 3600)
s -= h * 3600
const m = Math.floor(s / 60)
s -= m * 60
const tmp = []
if (d) tmp.push(d + 'd')
if (d || h) tmp.push(h + 'h')
if (d || h || m) tmp.push(m + 'm')
return tmp.join(' ')
}
const formatter = (typeof Intl !== 'undefined') && new Intl.RelativeTimeFormat('en')
const ranges = {
years: 3600 * 24 * 365,
months: 3600 * 24 * 30,
weeks: 3600 * 24 * 7,
days: 3600 * 24,
hours: 3600,
minutes: 60,
seconds: 1
}
/**
* @template T
* @param {T[]} arr
* @param {number} n
*/
export function * chunks (arr, n) {
for (let i = 0; i < arr.length; i += n) {
yield arr.slice(i, i + n)
}
}
/** @param {Date} date */
export function since (date) {
const secondsElapsed = (date.getTime() - Date.now()) / 1000
for (const key in ranges) {
if (ranges[key] < Math.abs(secondsElapsed)) {
const delta = secondsElapsed / ranges[key]
// @ts-ignore
return formatter.format(Math.round(delta), key)
}
}
}
const units = [' B', ' kB', ' MB', ' GB', ' TB']
export function fastPrettyBytes (num) {
if (isNaN(num)) return '0 B'
if (num < 1) return num + ' B'
const exponent = Math.min(Math.floor(Math.log(num) / Math.log(1000)), units.length - 1)
return Number((num / Math.pow(1000, exponent)).toFixed(2)) + units[exponent]
}
/** @type {DOMParser['parseFromString']} */
export const DOMPARSER = (typeof DOMParser !== 'undefined') && DOMParser.prototype.parseFromString.bind(new DOMParser())
export const sleep = t => new Promise(resolve => setTimeout(resolve, t).unref?.())
export function toTS (sec, full) {
if (isNaN(sec) || sec < 0) {
switch (full) {
case 1:
return '0:00:00.00'
case 2:
return '0:00:00'
case 3:
return '00:00'
default:
return '0:00'
}
}
const hours = Math.floor(sec / 3600)
/** @type {any} */
let minutes = Math.floor(sec / 60) - hours * 60
/** @type {any} */
let seconds = full === 1 ? (sec % 60).toFixed(2) : Math.floor(sec % 60)
if (minutes < 10 && (hours > 0 || full)) minutes = '0' + minutes
if (seconds < 10) seconds = '0' + seconds
return (hours > 0 || full === 1 || full === 2) ? hours + ':' + minutes + ':' + seconds : minutes + ':' + seconds
}
export function generateRandomHexCode (len) {
let hexCode = ''
while (hexCode.length < len) {
hexCode += (Math.round(Math.random() * 15)).toString(16)
}
return hexCode
}
export function throttle (fn, time) {
let wait = false
return (...args) => {
if (!wait) {
fn(...args)
wait = true
setTimeout(() => {
fn(...args)
wait = false
}, time).unref?.()
}
}
}
export function debounce (fn, time) {
let timeout
return (...args) => {
const later = () => {
timeout = null
fn(...args)
}
clearTimeout(timeout)
timeout = setTimeout(later, time)
timeout.unref?.()
}
}
export const defaults = {
volume: 1,
playerAutoplay: true,
playerPause: true,
playerAutocomplete: true,
playerDeband: false,
rssQuality: '1080',
rssFeedsNew: SUPPORTS.extensions ? [['New Releases', 'SubsPlease']] : [],
rssAutoplay: true,
torrentSpeed: 5,
torrentPersist: false,
torrentDHT: false,
torrentPeX: false,
torrentPort: 0,
torrentStreamedDownload: true,
dhtPort: 0,
missingFont: true,
maxConns: 50,
subtitleRenderHeight: SUPPORTS.isAndroid ? '720' : '0',
subtitleLanguage: 'eng',
audioLanguage: 'jpn',
enableDoH: false,
doHURL: 'https://cloudflare-dns.com/dns-query',
disableSubtitleBlur: SUPPORTS.isAndroid,
showDetailsInRPC: true,
smoothScroll: !SUPPORTS.isAndroid,
cards: 'small',
expandingSidebar: !SUPPORTS.isAndroid,
torrentPathNew: undefined,
font: undefined,
angle: 'default',
toshoURL: SUPPORTS.extensions ? decodeURIComponent(atob('aHR0cHM6Ly9mZWVkLmFuaW1ldG9zaG8ub3JnLw==')) : '',
extensions: SUPPORTS.extensions ? ['anisearch'] : [],
sources: {},
enableExternal: false,
playerPath: '',
playerSeek: 2,
playerSkip: false
}
export const subtitleExtensions = ['srt', 'vtt', 'ass', 'ssa', 'sub', 'txt']
export const subRx = new RegExp(`.(${subtitleExtensions.join('|')})$`, 'i')
export const videoExtensions = ['3g2', '3gp', 'asf', 'avi', 'dv', 'flv', 'gxf', 'm2ts', 'm4a', 'm4b', 'm4p', 'm4r', 'm4v', 'mkv', 'mov', 'mp4', 'mpd', 'mpeg', 'mpg', 'mxf', 'nut', 'ogm', 'ogv', 'swf', 'ts', 'vob', 'webm', 'wmv', 'wtv']
export const videoRx = new RegExp(`.(${videoExtensions.join('|')})$`, 'i')
// freetype supported
export const fontExtensions = ['ttf', 'ttc', 'woff', 'woff2', 'otf', 'cff', 'otc', 'pfa', 'pfb', 'pcf', 'fnt', 'bdf', 'pfr', 'eot']
export const fontRx = new RegExp(`.(${fontExtensions.join('|')})$`, 'i')

View file

@ -0,0 +1,397 @@
import { spawn } from 'node:child_process'
import Debug from 'debug'
import WebTorrent from 'webtorrent'
import querystring from 'querystring'
import HTTPTracker from 'bittorrent-tracker/lib/client/http-tracker.js'
import { hex2bin, arr2hex, text2arr } from 'uint8-util'
import Parser from './parser.js'
import { defaults, fontRx, sleep, subRx, videoRx } from './util.js'
import { SUPPORTS } from '@/modules/support.js'
// HACK: this is https only, but electron doesnt run in https, weirdge
if (!globalThis.FileSystemFileHandle) globalThis.FileSystemFileHandle = false
const querystringStringify = obj => {
let ret = querystring.stringify(obj, null, null, { encodeURIComponent: escape })
ret = ret.replace(/[@*/+]/g, char => // `escape` doesn't encode the characters @*/+ so we do it manually
`%${char.charCodeAt(0).toString(16).toUpperCase()}`)
return ret
}
const debug = Debug('torrent:worker')
const ANNOUNCE = [
atob('d3NzOi8vdHJhY2tlci5vcGVud2VidG9ycmVudC5jb20='),
atob('d3NzOi8vdHJhY2tlci53ZWJ0b3JyZW50LmRldg=='),
atob('d3NzOi8vdHJhY2tlci5maWxlcy5mbTo3MDczL2Fubm91bmNl'),
atob('d3NzOi8vdHJhY2tlci5idG9ycmVudC54eXov'),
atob('dWRwOi8vb3Blbi5zdGVhbHRoLnNpOjgwL2Fubm91bmNl'),
atob('aHR0cDovL255YWEudHJhY2tlci53Zjo3Nzc3L2Fubm91bmNl'),
atob('dWRwOi8vdHJhY2tlci5vcGVudHJhY2tyLm9yZzoxMzM3L2Fubm91bmNl'),
atob('dWRwOi8vZXhvZHVzLmRlc3luYy5jb206Njk2OS9hbm5vdW5jZQ=='),
atob('dWRwOi8vdHJhY2tlci5jb3BwZXJzdXJmZXIudGs6Njk2OS9hbm5vdW5jZQ=='),
atob('dWRwOi8vOS5yYXJiZy50bzoyNzEwL2Fubm91bmNl'),
atob('dWRwOi8vdHJhY2tlci50b3JyZW50LmV1Lm9yZzo0NTEvYW5ub3VuY2U='),
atob('aHR0cDovL29wZW4uYWNnbnh0cmFja2VyLmNvbTo4MC9hbm5vdW5jZQ=='),
atob('aHR0cDovL2FuaWRleC5tb2U6Njk2OS9hbm5vdW5jZQ=='),
atob('aHR0cDovL3RyYWNrZXIuYW5pcmVuYS5jb206ODAvYW5ub3VuY2U=')
]
export default class TorrentClient extends WebTorrent {
static excludedErrorMessages = ['WebSocket', 'User-Initiated Abort, reason=', 'Connection failed.']
player = ''
/** @type {ReturnType<spawn>} */
playerProcess = null
torrentPath = ''
ipc
constructor (ipc, storageQuota, serverMode, torrentPath, controller) {
let storedSettings = {}
try {
storedSettings = JSON.parse(localStorage.getItem('settings')) || {}
} catch (error) {}
const settings = { ...defaults, ...storedSettings }
debug('Initializing TorrentClient with settings: ' + JSON.stringify(settings))
super({
dht: !settings.torrentDHT,
maxConns: settings.maxConns,
downloadLimit: settings.torrentSpeed * 1048576 || 0,
uploadLimit: settings.torrentSpeed * 1572864 || 0, // :trolled:
torrentPort: settings.torrentPort || 0,
dhtPort: settings.dhtPort || 0,
natUpnp: SUPPORTS.permamentNAT ? 'permanent' : true
})
this.ipc = ipc
this.torrentPath = torrentPath
this._ready = new Promise(resolve => {
ipc.on('port', ({ ports }) => {
if (this.message) return
this.message = ports[0].postMessage.bind(ports[0])
ports[0].onmessage = ({ data }) => {
debug(`Received IPC message ${data.type}: ${data.data}`)
if (data.type === 'load') this.loadLastTorrent(data.data)
if (data.type === 'destroy') this.destroy()
this.handleMessage({ data })
}
resolve()
})
ipc.on('destroy', this.destroy.bind(this))
})
ipc.on('player', (event, data) => {
this.player = data
})
ipc.on('torrentPath', (event, data) => {
this.torrentPath = data
})
this.settings = settings
this.serverMode = serverMode
this.storageQuota = storageQuota
this.current = null
this.parsed = false
setInterval(() => {
this.dispatch('stats', {
numPeers: (this.torrents.length && this.torrents[0].numPeers) || 0,
uploadSpeed: (this.torrents.length && this.torrents[0].uploadSpeed) || 0,
downloadSpeed: (this.torrents.length && this.torrents[0].downloadSpeed) || 0
})
}, 200)
setInterval(() => {
if (this.torrents[0]?.pieces) this.dispatch('progress', this.current?.progress)
}, 2000)
this.on('torrent', this.torrentReady.bind(this))
const createServer = controller => {
this.server = this.createServer({ controller }, serverMode)
this.server.listen(0, () => {})
}
if (controller) {
controller.then(createServer)
} else {
createServer()
}
this.tracker = new HTTPTracker({}, atob('aHR0cDovL255YWEudHJhY2tlci53Zjo3Nzc3L2Fubm91bmNl'))
process.on('uncaughtException', this.dispatchError.bind(this))
this.on('error', this.dispatchError.bind(this))
}
loadLastTorrent (t) {
debug('Loading last torrent: ' + t)
if (!t) return
let torrent
// this can be a magnet string, or a stringified array, lazy way of makign sure it works
try {
const parsed = JSON.parse(t)
if (typeof parsed === 'string') {
torrent = parsed
} else {
torrent = new Uint8Array(parsed)
}
} catch (e) {
torrent = t
}
if (torrent) this.addTorrent(torrent, JSON.parse(localStorage.getItem('lastFinished')))
}
async torrentReady (torrent) {
debug('Got torrent metadata: ' + torrent.name)
const files = torrent.files.map(file => {
return {
infoHash: torrent.infoHash,
name: file.name,
type: file.type,
size: file.size,
path: file.path,
url: this.serverMode === 'node' ? 'http://localhost:' + this.server.address().port + file.streamURL : file.streamURL
}
})
this.dispatch('files', files)
this.dispatch('magnet', { magnet: torrent.magnetURI, hash: torrent.infoHash })
setTimeout(() => {
if (torrent.destroyed) return
if (torrent.progress !== 1) {
if (torrent.numPeers === 0) this.dispatchError('No peers found for torrent, try using a different torrent.')
}
}, 10000).unref?.()
localStorage.setItem('torrent', JSON.stringify([...torrent.torrentFile])) // this won't work on mobile, but really it only speeds stuff up by ~1-2 seconds since magnet data doesn't need to be resolved
}
async findFontFiles (targetFile) {
const files = this.torrents[0].files
const fontFiles = files.filter(file => fontRx.test(file.name))
const map = {}
// deduplicate fonts
// some releases have duplicate fonts for diff languages
// if they have different chars, we can't find that out anyways
// so some chars might fail, on REALLY bad releases
for (const file of fontFiles) {
map[file.name] = file
}
debug(`Found ${Object.keys(map).length} font files`)
for (const file of Object.values(map)) {
const data = await file.arrayBuffer()
if (targetFile !== this.current) return
this.dispatch('file', { data: new Uint8Array(data) }, [data])
}
}
async findSubtitleFiles (targetFile) {
const files = this.torrents[0].files
const videoFiles = files.filter(file => videoRx.test(file.name))
const videoName = targetFile.name.substring(0, targetFile.name.lastIndexOf('.')) || targetFile.name
// array of subtitle files that match video name, or all subtitle files when only 1 vid file
const subfiles = files.filter(file => {
return subRx.test(file.name) && (videoFiles.length === 1 ? true : file.name.includes(videoName))
})
debug(`Found ${subfiles.length} subtitle files`)
for (const file of subfiles) {
const data = await file.arrayBuffer()
if (targetFile !== this.current) return
this.dispatch('subtitleFile', { name: file.name, data: new Uint8Array(data) }, [data])
}
}
async _scrape ({ id, infoHashes }) {
debug(`Scraping ${infoHashes.length} hashes, id: ${id}`)
// this seems to give the best speed, and lowest failure rate
const MAX_ANNOUNCE_LENGTH = 1300 // it's likely 2048, but lets undercut it
const RATE_LIMIT = 200 // ms
const ANNOUNCE_LENGTH = this.tracker.scrapeUrl.length
let batch = []
let currentLength = ANNOUNCE_LENGTH // fuzz the size a little so we don't always request the same amt of hashes
const results = []
const scrape = async () => {
if (results.length) await sleep(RATE_LIMIT)
const result = await new Promise(resolve => {
this.tracker._request(this.tracker.scrapeUrl, { info_hash: batch }, (err, data) => {
if (err) {
const error = this._errorToString(err)
debug('Failed to scrape: ' + error)
this.dispatch('warn', `Failed to update seeder counts: ${error}`)
return resolve([])
}
const { files } = data
const result = []
debug(`Scraped ${Object.keys(files || {}).length} hashes, id: ${id}`)
for (const [key, data] of Object.entries(files || {})) {
result.push({ hash: key.length !== 40 ? arr2hex(text2arr(key)) : key, ...data })
}
resolve(result)
})
})
results.push(...result)
batch = []
currentLength = ANNOUNCE_LENGTH
}
for (const infoHash of infoHashes.sort(() => 0.5 - Math.random()).map(infoHash => hex2bin(infoHash))) {
const qsLength = querystringStringify({ info_hash: infoHash }).length + 1 // qs length + 1 for the & or ? separator
if (currentLength + qsLength > MAX_ANNOUNCE_LENGTH) {
await scrape()
}
batch.push(infoHash)
currentLength += qsLength
}
if (batch.length) await scrape()
debug(`Scraped ${results.length} hashes, id: ${id}`)
this.dispatch('scrape', { id, result: results })
}
_errorToString (e) {
if (typeof Event !== 'undefined' && e instanceof Event) {
if (e.error) return this._errorToString(e.error)
if (e.message) return this._errorToString(e.message)
if (e.reason) return this._errorToString(e.reason)
return JSON.stringify(e)
}
if (typeof Error !== 'undefined' && e instanceof Error) {
if (e.message) return this._errorToString(e.message)
if (e.cause) return this._errorToString(e.cause)
if (e.reason) return this._errorToString(e.reason)
if (e.name) return this._errorToString(e.name)
return JSON.stringify(e)
}
if (typeof e !== 'string') return JSON.stringify(e)
return e
}
dispatchError (e) {
const error = this._errorToString(e)
for (const exclude of TorrentClient.excludedErrorMessages) {
if (error.startsWith(exclude)) return
}
debug('Error: ' + error)
this.dispatch('error', error)
}
async addTorrent (data, skipVerify = false) {
debug('Adding torrent: ' + data)
const existing = await this.get(data)
if (existing) {
if (existing.ready) this.torrentReady(existing)
return
}
localStorage.setItem('lastFinished', 'false')
if (this.torrents.length) {
await this.remove(this.torrents[0], { destroyStore: !this.settings.torrentPersist })
}
const torrent = await this.add(data, {
private: this.settings.torrentPeX,
path: this.torrentPath || undefined,
skipVerify,
announce: ANNOUNCE,
deselect: this.settings.torrentStreamedDownload
})
torrent.once('verified', () => {
if (!torrent.ready && !skipVerify) this.dispatch('info', 'Detected already downloaded files. Verifying file integrity. This might take a minute...')
})
setTimeout(() => {
if (torrent.destroyed || skipVerify) return
if (!torrent.progress && !torrent.ready) {
if (torrent.numPeers === 0) this.dispatchError('No peers found for torrent, try using a different torrent.')
}
}, 10000).unref?.()
torrent.once('done', () => {
if (this.settings.torrentPathNew) localStorage.setItem('lastFinished', 'true')
})
}
async handleMessage ({ data }) {
switch (data.type) {
case 'current': {
if (data.data) {
const torrent = await this.get(data.data.current.infoHash)
if (!torrent || torrent.destroyed) return
const found = torrent.files.find(file => file.path === data.data.current.path)
if (!found || found._destroyed) return
if (this.playerProcess) {
this.playerProcess.kill()
this.playerProcess = null
}
if (this.current) {
this.current.removeAllListeners('stream')
if (!this.current._destroyed) this.current.deselect()
}
this.parser?.destroy()
found.select()
if (found.length > await this.storageQuota(torrent.path)) {
this.dispatchError('File Too Big! This File Exceeds The Selected Drive\'s Available Space. Change Download Location In Torrent Settings To A Drive With More Space And Restart The App!')
}
this.current = found
if (data.data.external) {
if (this.player) {
this.playerProcess = spawn(this.player, ['' + new URL('http://localhost:' + this.server.address().port + found.streamURL)])
this.playerProcess.stdout.on('data', () => {})
const startTime = Date.now()
this.playerProcess.once('close', () => {
this.playerProcess = null
const seconds = (Date.now() - startTime) / 1000
this.dispatch('externalWatched', seconds)
})
return
}
if (SUPPORTS.isAndroid) {
this.dispatch('open', `intent://localhost:${this.server.address().port}${found.streamURL}#Intent;type=video/any;scheme=http;end;`)
return
}
}
this.parser = new Parser(this, found)
this.findSubtitleFiles(found)
this.findFontFiles(found)
}
break
}
case 'scrape': {
this._scrape(data.data)
break
}
case 'torrent': {
this.addTorrent(data.data)
break
}
case 'debug': {
Debug.disable()
if (data.data) Debug.enable(data.data)
}
}
}
async dispatch (type, data, transfer) {
await this._ready
this.message?.({ type, data }, transfer)
}
destroy () {
debug('Destroying TorrentClient')
if (this.destroyed) return
this.parser?.destroy()
this.server.close()
super.destroy(() => {
this.ipc.send('destroyed')
})
}
}

29
common/package.json Normal file
View file

@ -0,0 +1,29 @@
{
"name": "common",
"private": true,
"dependencies": {
"@fontsource-variable/nunito": "^5.0.18",
"@thaunknown/ani-resourced": "^1.0.3",
"anitomyscript": "github:ThaUnknown/anitomyscript#42290c4b3f256893be08a4e89051f448ff5e9d00",
"bottleneck": "^2.19.5",
"browser-event-target-emitter": "^1.0.1",
"comlink": "^4.4.1",
"jassub": "^1.7.17",
"js-levenshtein": "^1.1.6",
"lucide-svelte": "^0.429.0",
"p2pt": "github:ThaUnknown/p2pt#modernise",
"perfect-seekbar": "^1.1.0",
"quartermoon": "^1.2.3",
"simple-font-select": "^1.0.1",
"simple-store-svelte": "^1.0.6",
"svelte": "^4.2.12",
"svelte-keybinds": "^1.0.9",
"svelte-loader": "^3.1.9",
"svelte-miniplayer": "^1.0.5",
"svelte-persisted-store": "^0.11.0",
"svelte-radix": "^1.1.0",
"svelte-sonner": "^0.3.19",
"video-deband": "^1.0.5",
"webpack-merge": "^5.10.0"
}
}

BIN
common/public/Roboto.ttf Normal file

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1 MiB

View file

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
width="39.147381mm"
height="39.147381mm"
viewBox="0 0 39.147381 39.14738"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<g aria-label="みる" transform="matrix(1.8923544,0,0,1.8923544,-125.56938,-95.152054)" style="fill:#e5204c">
<path d="m 76.79068,62.020505 -0.733118,1.300869 q -0.865408,-0.479558 -1.802475,-0.903994 -0.799263,1.631599 -1.956817,3.158467 l -1.25126,-0.76619 q 1.113456,-1.394576 1.841061,-2.954517 -0.942579,-0.374827 -2.067059,-0.600825 -0.777214,1.774915 -1.389064,2.359203 -0.61185,0.578777 -1.273309,0.578777 -0.744141,0 -1.273308,-0.529167 -0.529167,-0.529167 -0.529167,-1.30087 0,-0.981164 0.964627,-1.785939 0.97014,-0.810287 2.574178,-0.859897 0.474046,-1.063846 0.881946,-2.166278 -1.510332,0.4079 -2.508032,0.529167 l -0.369315,-1.350478 q 1.670184,-0.198438 4.018363,-0.959116 l 0.617362,1.12448 q -0.01102,0.115756 -1.141017,2.971054 0.986677,0.209462 2.011938,0.600825 0.314193,-1.113456 0.48507,-2.585202 l 1.422137,0.28112 q -0.181901,1.515843 -0.551216,2.844273 1.129993,0.518143 2.028475,1.014238 z m -7.573706,-0.788239 q -0.650435,0.132292 -1.025262,0.512631 -0.369314,0.374826 -0.369314,0.677995 0,0.319705 0.314193,0.319705 0.159852,0 0.474045,-0.380339 0.319706,-0.380339 0.606338,-1.129992 z" />
<path d="m 83.118637,59.325059 q 0.48507,-0.115755 0.942579,-0.115755 1.367016,0 2.171791,0.926042 0.810287,0.920531 0.810287,2.171791 0,1.394576 -1.063846,2.287546 -1.058335,0.887457 -2.689934,0.887457 -1.27882,0 -2.039498,-0.617362 -0.755166,-0.617361 -0.755166,-1.488282 0,-0.749654 0.545704,-1.25126 0.551215,-0.501607 1.295357,-0.501607 1.433161,0 2.37574,2.033987 0.837848,-0.396876 0.837848,-1.284333 0,-1.769403 -1.934767,-1.769403 -1.069359,0 -1.934768,0.474045 -0.865409,0.474046 -2.149742,1.890671 l -1.096919,-1.080383 q 2.596226,-2.463935 4.497921,-4.503434 -1.58199,0.159853 -2.745055,0.132292 l -0.28112,-1.477258 q 0.424436,0.02205 0.865409,0.02205 1.741842,0 4.056948,-0.385851 l 0.68902,1.152041 q -0.9977,1.074871 -2.397789,2.497008 z m 0.170877,4.718408 q -0.474045,-0.992189 -0.953603,-0.992189 -0.35829,0 -0.35829,0.308681 0,0.259071 0.336241,0.474046 0.341754,0.209462 0.975652,0.209462 z" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.3 KiB

53
common/types.d.ts vendored Normal file
View file

@ -0,0 +1,53 @@
import type { SvelteComponentTyped } from 'svelte'
export {}
type Track = {
selected: boolean
enabled: boolean
id: string
kind: string
label: string
language: string
}
declare global {
interface Window {
IPC: any
port: MessagePort
version: {
platform: string
arch: string
}
}
interface EventTarget {
on: (type: string, callback: (any) => void, options?: boolean | {}) => void
once: (type: string, callback: (any) => void, options?: boolean | {}) => void
emit: (type: string, data?: any) => void
dispatch: (type: string, data?: any) => void
removeListener: (type: string, callback: (any) => void) => void
off: (type: string, callback: (any) => void) => void
}
interface HTMLMediaElement {
videoTracks: Track[]
audioTracks: Track[]
}
interface ScreenOrientation {
lock: Function
}
namespace svelteHTML {
interface HTMLAttributes {
'on:leavepictureinpicture'?: (
event: Event<{
target: EventTarget;
}>
) => void;
}
}
}
declare module '*.svelte' {
export default SvelteComponentTyped
}

View file

@ -0,0 +1,41 @@
<script context='module'>
import SectionsManager from '@/modules/sections.js'
import Search, { search } from './Search.svelte'
import { anilistClient, currentSeason, currentYear } from '@/modules/anilist.js'
const vars = { format: 'TV', season: currentSeason, year: currentYear }
async function fetchAllScheduleEntries (_variables) {
const variables = { ..._variables }
const results = { data: { Page: { media: [], pageInfo: { hasNextPage: false } } } }
const opts = { ...vars, ...SectionsManager.sanitiseObject(variables) }
for (let page = 1, hasNextPage = true; hasNextPage && page < 5; ++page) {
const res = await anilistClient.search({ ...opts, page, perPage: 50 })
hasNextPage = res.data.Page.pageInfo.hasNextPage
results.data.Page.media = results.data.Page.media.concat(res.data.Page.media)
}
const seasons = ['WINTER', 'SPRING', 'SUMMER', 'FALL']
const season = seasons.at(seasons.indexOf(vars.season) - 1)
const year = vars.season === 'WINTER' ? vars.year - 1 : vars.year
const res = await anilistClient.search({ format: 'TV', ...SectionsManager.sanitiseObject(variables), year, season, status: 'RELEASING', page: 1, perPage: 50 })
results.data.Page.media = results.data.Page.media.concat(res.data.Page.media)
// filter out entries without airing schedule and duplicates [only allow first occurence]
results.data.Page.media = results.data.Page.media.filter((media, index, self) => media.airingSchedule?.nodes?.[0]?.airingAt && self.findIndex(m => m.id === media.id) === index)
results.data.Page.media.sort((a, b) => a.airingSchedule?.nodes?.[0]?.airingAt - b.airingSchedule?.nodes?.[0]?.airingAt)
return results
}
</script>
<script>
$search = {
...vars,
load: (_, __, variables) => SectionsManager.wrapResponse(fetchAllScheduleEntries(variables), 150)
}
</script>
<Search />

View file

@ -0,0 +1,46 @@
<script context='module'>
import SectionsManager, { sections } from '@/modules/sections.js'
import { settings } from '@/modules/settings.js'
import { anilistClient, currentSeason, currentYear } from '@/modules/anilist.js'
const bannerData = anilistClient.search({ method: 'Search', sort: 'POPULARITY_DESC', perPage: 15, onList: false, season: currentSeason, year: currentYear, status_not: 'NOT_YET_RELEASED' })
const manager = new SectionsManager()
const mappedSections = {}
for (const section of sections) {
mappedSections[section.title] = section
}
for (const sectionTitle of settings.value.homeSections) manager.add(mappedSections[sectionTitle])
if (anilistClient.userID?.viewer?.data?.Viewer) {
const userSections = ['Continue Watching', 'Sequels You Missed', 'Your List', 'Completed List', 'Paused List', 'Dropped List', 'Currently Watching List']
anilistClient.userLists.subscribe(value => {
if (!value) return
for (const section of manager.sections) {
// remove preview value, to force UI to re-request data, which updates it once in viewport
if (userSections.includes(section.title)) section.preview.value = section.load(1, 15)
}
})
}
</script>
<script>
import Section from './Section.svelte'
import Banner from '@/components/banner/Banner.svelte'
import smoothScroll from '@/modules/scroll.js'
</script>
<div class='h-full w-full overflow-y-scroll root overflow-x-hidden' use:smoothScroll>
<Banner data={bannerData} />
<div class='d-flex flex-column h-full w-full'>
{#each manager.sections as section, i (i)}
{#if !section.hide}
<Section bind:opts={section} />
{/if}
{/each}
</div>
</div>

View file

@ -0,0 +1,81 @@
<script context='module'>
const fakecards = Array.from({ length: 15 }, () => ({ data: new Promise(() => {}) }))
</script>
<script>
import Card from '@/components/cards/Card.svelte'
import ErrorCard from '@/components/cards/ErrorCard.svelte'
import { search } from '../Search.svelte'
import { page } from '@/App.svelte'
import { click } from '@/modules/click.js'
export let opts
function deferredLoad (element) {
const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) {
if (!opts.preview.value) opts.preview.value = opts.load(1, 15)
observer.unobserve(element)
}
}, { threshold: 0 })
observer.observe(element)
return { destroy () { observer.unobserve(element) } }
}
function _click () {
$search = {
...opts.variables,
load: opts.load
}
$page = 'search'
}
const preview = opts.preview
</script>
<span class='d-flex px-20 align-items-end pointer text-decoration-none text-muted'
use:deferredLoad>
<div class='font-size-24 font-weight-semi-bold' use:click={_click}>{opts.title}</div>
<div class='pr-10 ml-auto font-size-12' use:click={_click}>View More</div>
</span>
<div class='position-relative'>
<div class='pb-10 w-full d-flex flex-row justify-content-start gallery' class:isRSS={opts.isRSS}>
{#each $preview || fakecards as card}
<Card {card} />
{/each}
{#if $preview?.length}
<ErrorCard promise={$preview[0].data} />
{/if}
</div>
</div>
<style>
.gallery :global(.first-check:first-child) :global(.absolute-container) {
left: -48% !important
}
.text-muted:hover {
color: var(--dm-link-text-color-hover) !important;
}
.gallery:after {
content: '';
position: absolute;
right: 0;
height: 100%;
width: 8rem;
background: var(--section-end-gradient);
pointer-events: none;
}
.gallery {
overflow-x: scroll;
flex-shrink: 0;
}
.gallery.isRSS {
overflow-x: clip;
}
.gallery :global(.item.small-card) {
width: 19rem !important
}
.gallery::-webkit-scrollbar {
display: none;
}
</style>

View file

@ -0,0 +1,268 @@
<script context='module'>
import { writable } from 'simple-store-svelte'
import AnimeResolver from '@/modules/animeresolver.js'
import { videoRx } from '@/modules/util.js'
import { tick } from 'svelte'
import { state } from '../WatchTogether/WatchTogether.svelte'
import IPC from '@/modules/ipc.js'
import Debug from 'debug'
const debug = Debug('ui:mediahandler')
const episodeRx = /Episode (\d+) - (.*)/
export const media = writable(null)
const nowPlaying = writable({})
export const files = writable([])
const processed = writable([])
const noop = () => {}
let playFile
media.subscribe((media) => {
handleMedia(media || {})
return noop
})
function handleCurrent ({ detail }) {
media.set(detail.media)
}
export function findInCurrent (obj) {
const oldNowPlaying = nowPlaying.value
if (oldNowPlaying.media?.id === obj.media.id && oldNowPlaying.episode === obj.episode) return false
const fileList = files.value
const targetFile = fileList.find(file => file.media?.media?.id === obj.media.id &&
(file.media?.episode === obj.episode || obj.media.episodes === 1 || (!obj.media.episodes && (obj.episode === 1 || !obj.episode) && (oldNowPlaying.episode === 1 || !oldNowPlaying.episode))) // movie check
)
if (!targetFile) return false
if (oldNowPlaying.media?.id !== obj.media.id) {
// mediachange, filelist change
media.set({ media: obj.media, episode: obj.episode })
handleFiles(fileList)
} else {
playFile(targetFile)
}
return true
}
function handleMedia ({ media, episode, parseObject }) {
if (media) {
const ep = Number(episode || parseObject?.episode_number) || null
const streamingEpisode = media?.streamingEpisodes.find(episode => {
const match = episodeRx.exec(episode.title)
return match && Number(match[1]) === ep
})
const np = {
media,
title: media?.title.userPreferred || parseObject.anime_title,
episode: ep,
episodeTitle: streamingEpisode && episodeRx.exec(streamingEpisode.title)[2],
thumbnail: streamingEpisode?.thumbnail || media?.coverImage.extraLarge
}
setDiscordRPC(np)
setMediaSession(np)
nowPlaying.set(np)
}
}
const TYPE_EXCLUSIONS = ['ED', 'ENDING', 'NCED', 'NCOP', 'OP', 'OPENING', 'PREVIEW', 'PV']
// find best media in batch to play
// currently in progress or unwatched
// tv, movie, ona, ova
function findPreferredPlaybackMedia (videoFiles) {
for (const { media } of videoFiles) {
if (media.media?.mediaListEntry?.status === 'CURRENT') return { media: media.media, episode: (media.media.mediaListEntry.progress || 0) + 1 }
}
for (const { media } of videoFiles) {
if (media.media?.mediaListEntry?.status === 'REPEATING') return { media: media.media, episode: (media.media.mediaListEntry.progress || 0) + 1 }
}
let lowestPlanning
for (const { media, episode } of videoFiles) {
if (media.media?.mediaListEntry?.status === 'PLANNING' && (!lowestPlanning || episode > lowestPlanning.episode)) lowestPlanning = { media: media.media, episode }
}
if (lowestPlanning) return lowestPlanning
// unwatched
for (const format of ['TV', 'MOVIE', 'ONA', 'OVA']) {
let lowestUnwatched
for (const { media, episode } of videoFiles) {
if (media.media?.format === format && !media.media.mediaListEntry && (!lowestUnwatched || episode > lowestUnwatched.episode)) lowestUnwatched = { media: media.media, episode }
}
if (lowestUnwatched) return lowestUnwatched
}
// highest occurence if all else fails - unlikely
const max = highestOccurence(videoFiles, file => file.media.media?.id).media
if (max?.media) {
return { media: max.media, episode: (max.media.mediaListEntry?.progress + 1 || 1) }
}
}
function fileListToDebug (files) {
return files.map(({ name, media, url }) => `\n${name} ${media?.parseObject.anime_title} ${media?.parseObject.episode_number} ${media?.media?.title.userPreferred} ${media?.episode}`).join('')
}
async function handleFiles (files) {
debug(`Got ${files.length} files`, fileListToDebug(files))
if (!files?.length) return processed.set(files)
let videoFiles = []
const otherFiles = []
for (const file of files) {
if (videoRx.test(file.name)) {
videoFiles.push(file)
} else {
otherFiles.push(file)
}
}
let nowPlaying = media.value
const resolved = await AnimeResolver.resolveFileAnime(videoFiles.map(file => file.name))
videoFiles.map(file => {
file.media = resolved.find(({ parseObject }) => file.name.includes(parseObject.file_name))
return file
})
videoFiles = videoFiles.filter(file => !TYPE_EXCLUSIONS.includes(file.media.parseObject.anime_type?.toUpperCase()))
if (nowPlaying?.verified && videoFiles.length === 1) {
debug('Media was verified, skipping verification')
videoFiles[0].media.media = nowPlaying.media
if (nowPlaying.episode) videoFiles[0].media.episode = nowPlaying.episode
}
debug(`Resolved ${videoFiles.length} video files`, fileListToDebug(videoFiles))
if (!nowPlaying) {
nowPlaying = findPreferredPlaybackMedia(videoFiles)
debug(`Found preferred playback media: ${nowPlaying.media?.id}:${nowPlaying.media?.title.userPreferred} ${nowPlaying.episode}`)
}
const filtered = nowPlaying?.media && videoFiles.filter(file => file.media?.media?.id && file.media?.media?.id === nowPlaying.media.id)
debug(`Filtered ${filtered?.length} files based on media`, fileListToDebug(filtered))
let result
if (filtered?.length) {
result = filtered
} else {
const max = highestOccurence(videoFiles, file => file.media.parseObject.anime_title).media.parseObject.anime_title
debug(`Highest occurence anime title: ${max}`)
result = videoFiles.filter(file => file.media.parseObject.anime_title === max)
}
result.sort((a, b) => a.media.episode - b.media.episode)
result.sort((a, b) => (b.media.parseObject.anime_season ?? 1) - (a.media.parseObject.anime_season ?? 1))
debug(`Sorted ${result.length} files`, fileListToDebug(result))
processed.set([...result, ...otherFiles])
await tick()
const file = (nowPlaying?.episode && (result.find(({ media }) => media.episode === nowPlaying.episode) || result.find(({ media }) => media.episode === 1))) || result[0]
if (nowPlaying) nowPlaying.episode = file.media.parseObject.episode_number
media.set(nowPlaying)
playFile(file || 0)
}
// find element with most occurences in array according to map function
const highestOccurence = (arr = [], mapfn = a => a) => arr.reduce((acc, el) => {
const mapped = mapfn(el)
acc.sums[mapped] = (acc.sums[mapped] || 0) + 1
acc.max = (acc.max !== undefined ? acc.sums[mapfn(acc.max)] : -1) > acc.sums[mapped] ? acc.max : el
return acc
}, { sums: {} }).max
files.subscribe((files = []) => {
handleFiles(files)
return noop
})
function setMediaSession (nowPlaying) {
if (typeof MediaMetadata === 'undefined') return
const name = [nowPlaying.title, nowPlaying.episode, nowPlaying.episodeTitle, 'Miru'].filter(i => i).join(' - ')
const metadata =
nowPlaying.thumbnail
? new MediaMetadata({
title: name,
artwork: [
{
src: nowPlaying.thumbnail,
sizes: '256x256',
type: 'image/jpg'
}
]
})
: new MediaMetadata({ title: name })
navigator.mediaSession.metadata = metadata
}
function setDiscordRPC (np = nowPlaying.value) {
const w2g = state.value?.code
const details = [np.title, np.episodeTitle].filter(i => i).join(' - ') || undefined
const activity = {
details,
state: details && 'Watching Episode ' + ((!np.media?.episodes && np.episode) || ''),
timestamps: {
start: Date.now()
},
party: {
size: (np.episode && np.media?.episodes && [np.episode, np.media.episodes]) || undefined
},
assets: {
large_text: np.title,
large_image: np.thumbnail,
small_image: 'logo',
small_text: 'https://github.com/ThaUnknown/miru'
},
instance: true,
type: 3
}
// cannot have buttons and secrets at once
if (w2g) {
activity.secrets = {
join: w2g,
match: w2g + 'm'
}
activity.party.id = w2g + 'p'
} else {
activity.buttons = [
{
label: 'Download app',
url: 'https://github.com/ThaUnknown/miru/releases/latest'
},
{
label: 'Watch on Miru',
url: `miru://anime/${np.media?.id}`
}
]
}
IPC.emit('discord', { activity })
}
state.subscribe(() => {
setDiscordRPC()
return noop
})
</script>
<script>
import Player from './Player.svelte'
export let miniplayer = false
export let page = 'home'
</script>
<Player files={$processed} {miniplayer} media={$nowPlaying} bind:playFile bind:page on:current={handleCurrent} />

Some files were not shown because too many files have changed in this diff Show more