diff --git a/.babelrc b/.babelrc new file mode 100644 index 0000000..5b381b9 --- /dev/null +++ b/.babelrc @@ -0,0 +1,16 @@ +{ + "presets": [ + [ + "@babel/env", + { + "targets": { + "chrome": "130", + "node": "20.9.0" + } + } + ] + ], + "plugins": [ + "@babel/plugin-transform-class-properties" + ] +} diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..db088e3 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,5 @@ +.gitignore +.prettierrc +Dockerfile +LICENSE +README.md diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..4a7ea30 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,12 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.md] +trim_trailing_whitespace = false diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6630251 --- /dev/null +++ b/.gitignore @@ -0,0 +1,31 @@ +.DS_Store +dist/electron/* +storyboards/* +dashFiles/* +static/dashFiles +static/storyboards +static/dashFiles/* +static/storyboards/* +dist/web/* +build/* +!build/icons +coverage +node_modules/ +npm-debug.log +npm-debug.log.* +thumbs.db +!.gitkeep +data/tmp/ +.tmp/ +tmp/ +.cache +dist +coverage +__coverage__ +csak-timelog.json +.idea/ +debug/ +assets/ +# Lefthook +lefthook-local.yml +*.bak diff --git a/.stylelintignore b/.stylelintignore new file mode 100644 index 0000000..18256bd --- /dev/null +++ b/.stylelintignore @@ -0,0 +1,7 @@ +src/data/ +src/datastores/ +src/main/ +src/renderer/videoJS.css +dist/ +static/ +node_modules/ diff --git a/.stylelintrc.json b/.stylelintrc.json new file mode 100644 index 0000000..8b2065b --- /dev/null +++ b/.stylelintrc.json @@ -0,0 +1,35 @@ +{ + "plugins": ["stylelint-use-logical-spec", "@double-great/stylelint-a11y"], + "extends": ["stylelint-config-standard", "stylelint-config-sass-guidelines"], + "overrides": [ + { + "files": ["**/*.scss"], + "customSyntax": "postcss-scss", + "rules": { + "max-nesting-depth": null, + "selector-max-compound-selectors": null + } + }, + { + "files": ["**/*.css"], + "rules": { + } + } + ], + "rules": { + "selector-no-qualifying-type": [ + true, { + "ignore": ["attribute"] + }], + "selector-class-pattern": null, + "selector-id-pattern": null, + "selector-pseudo-class-no-unknown": [ + true, + { + "ignorePseudoClasses": ["deep", "global"] + } + ], + "a11y/no-outline-none": true, + "liberty/use-logical-spec": ["always", { "except": ["float"] }] + } +} diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..5dc5d72 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,11 @@ +{ + "recommendations": [ + "editorconfig.editorconfig", + "dbaeumer.vscode-eslint", + "stylelint.vscode-stylelint", + "syler.sass-indented", + "redhat.vscode-yaml", + "vue.volar", + "eamodio.gitlens" + ] +} diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..2f3cb81 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,23 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "dev-runner (Electron)", + "type": "node", + "request": "launch", + "program": "${workspaceFolder}/_scripts/dev-runner.js", + "args": ["--remote-debug"] + }, + { + "name": "Attach to renderer process (Electron)", + "type": "chrome", + "request": "attach", + "port": 9223, + "webRoot": "http://localhost:9080", + "sourceMapPathOverrides": { + "webpack://freetube/./~/*": "${workspaceFolder}/node_modules/*", + "webpack://freetube/./*": "${workspaceFolder}/*" + } + } + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..8e415af --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,34 @@ +{ + "stylelint.packageManager": "yarn", + "stylelint.snippet": [ + "css", + "less", + "postcss", + "sass", + "scss" + ], + "stylelint.validate": [ + "css", + "less", + "postcss", + "scss" + ], + "eslint.packageManager": "yarn", + "eslint.probe": [ + "javascript", + "vue", + "json", + "jsonc", + "yml", + "yaml" + ], + "eslint.validate": [ + "javascript", + "vue", + "json", + "jsonc", + "yml", + "yaml" + ], + "javascript.preferences.importModuleSpecifier": "relative" +} diff --git a/.whitesource b/.whitesource new file mode 100644 index 0000000..9b3d393 --- /dev/null +++ b/.whitesource @@ -0,0 +1,8 @@ +########################################################## +#### WhiteSource "Bolt for Github" configuration file #### +########################################################## + +# Configuration # +#---------------# +ws.repo.scan=true +vulnerable.check.run.conclusion.level=failure diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..32a86cb --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,27 @@ +# Code Contributions + +## Before starting to code + Please follow these guidelines before starting to code you feature or bugfix. + * If you want to implement a bugfix or feature request from an existing issue, please comment on that issue that you will work on it. This helps us to coordinate what needs to be done and what not. + * If you want to implement a feature request without an existing issue, please create an issue, so we know what you are working on and discuss the feature. + * For major feature implementations make sure you are able to maintain your code in the future in regard to bugs and possible code conflicts in future updates. Optionally you could join the [Matrix](https://matrix.to/#/+freetube:matrix.org) channel, so you will hear instantly if something needs to be worked on. + +## Before your Pull Request +Please follow these guidelines before sending your pull request and making contributions. +* When you submit a pull request, you agree that your code is published under the [GNU Affero General Public License](https://www.gnu.org/licenses/agpl-3.0.html) +* Please link the issue you are referring to. +* Do not include non-free software or modules with your code. +* Make sure your pull request is set up to merge your branch to FreeTube's development branch. +* Make sure your branch is up to date with the development branch before submitting your pull request. +* Stick to a similar style of code already in the project. Please look at current code to get an idea on how to do this. +* Follow [ES6](http://es6-features.org/) standards in your code. Ex: Use `let` and `const` instead of `var`. Do not use `function(response){//code}` for callbacks, use `(response) => {//code}`. +* Comment your code when necessary. Follow the [JavaScript Documentation and Comments Standard](https://www.drupal.org/docs/develop/standards/javascript/javascript-api-documentation-and-comment-standards) for functions. +* Please follow proper Vue structure when creating new code / components. Use existing code as well as the [Vue.js Guide](https://vuejs.org/v2/guide/) for reference. +* Please test your code. Make sure new features work as well as existing core features such as watching videos or loading subscriptions. New features need to work with both the Local API as well as the Invidious API +* Please make sure your code does not violate any standards set by our linter. It's up to you to make fixes whenever necessary. You can run `npm run lint` to check locally and `npm run lint-fix` to automatically fix smaller issues. +* Please limit the amount of Node Modules that you introduce into the project. Only include them when **absolutely necessary** for your code to work (Ex: Using nedb for databases) or if a module provides similar functionality to what you are trying to achieve (Ex: Using autolinker to create links to outside URLs instead of writing the functionality myself). +* Please try to stay involved with the community and maintain your code. We are only a handful of developers working on FreeTube in our spare time. We do not have time to work on everything, and it would be nice if you can maintain your code when necessary. + +# Setting up Your Environment + +Check out the [wiki](https://docs.freetubeapp.io/development/getting-started/) page to learn how to set up your environment and get started. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..d81ffe3 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,25 @@ + +## Dependency Stage ## +FROM node:18-alpine AS dep +WORKDIR /app +COPY package.json ./package.json +COPY yarn.lock ./yarn.lock +# copy `dist` if it exists already +COPY dis[t]/web ./dist/web +# git is needed for jinter +RUN apk add git +# don't rebuild if you don't have to +RUN if [ ! -d 'dist/web' ]; then yarn ci; fi + +## Build Stage ## +FROM node:18-alpine AS build +WORKDIR /app +COPY . . +COPY --from=dep /app/dis[t]/web ./dist/web +COPY --from=dep /app/node_module[s] ./node_modules +# don't rebuild if you don't have to +RUN if [ ! -d 'dist/web' ]; then yarn pack:web; fi + +## App Stage ## +FROM nginx:latest as app +COPY --from=build /app/dist/web /usr/share/nginx/html diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0ad25db --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are 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. + + 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. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + 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 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 work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero 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 Affero 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 Affero 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 Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + 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 AGPL, see +. diff --git a/README.md b/README.md index 1364564..8c9958f 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,144 @@ -# freetube +

+ FreeTube Logo +

+

+An open source YouTube player built with privacy in mind. +

-Ad & Account Free Youtube App for Android \ No newline at end of file +

+ + Build Status + + + izzyondroid version + + +Translation status + +

+
+

ScreenshotsHow does it work?FeaturesBuilding and testingContributingLocalizationContactDonateLicense

+

WebsiteBlogDocumentationFAQDiscussions

+
+ +FreeTube Android is an open source YouTube player built with privacy in mind. Use YouTube without advertisements and prevent Google from tracking you with their cookies and JavaScript. +Available as an APK and as a PWA (progressive web app). FreeTube Android is a fork of [FreeTube](https://www.github.com/FreeTubeApp). + +> [!NOTE] +> FreeTube Android is currently in Beta. While it should work well for most users, there are still bugs and missing features that need to be addressed. + +

+ + Get it on IzzyOnDroid + +

+ +

Download FreeTube Android

+ +
+ +## How does it work? +The APK uses a built in extractor to grab and serve data / videos, and can optionally use the [Invidious API](https://github.com/iv-org/invidious). The PWA *only* uses the Invidious API. No official YouTube APIs are used to obtain data. Your subscriptions and history are stored locally on your device and are never sent out. + +## Features +* Watch videos without ads +* Use YouTube without Google tracking you using cookies and JavaScript +* Subscribe to channels without an account +* Connect to an externally setup proxy such as Tor +* View and search your local subscriptions, history, and saved videos +* Organize your subscriptions into "Profiles" to create a more focused feed +* Export & import subscriptions +* Youtube Trending +* Youtube Chapters +* Most popular videos page based on the set Invidious instance +* SponsorBlock +* Full Theme support +* Keyboard shortcuts +* Option to show only family friendly content +* Show/hide functionality or elements within the app using the distraction free settings + +Go to [FreeTube's Documentation](https://docs.freetubeapp.io/) if you'd like to know more about how to operate FreeTube and its features. + +## Screenshots +watching video trending videos subscription feed + + +### Automated Builds (Nightly / Weekly) +Builds are automatically created from changes to our development branch via [GitHub Actions](https://github.com/MarmadileManteater/FreeTubeCordova/actions/workflows/buildCordova.yml). + +The first build with a green check mark is the latest build. You will need to have a GitHub account to download these builds. + +## How to build and test +### Commands for the APK +```bash +# 📦 Packs the project using `webpack.android.config.js` +yarn pack:android +# 🤖 Packs the botguard script +yarn pack:botGuardScript:android +# 🚧 for development +yarn pack:android:dev +``` +> [!NOTE] +> These commands only build the assets necessary for the project located in `android/` to be built. In order to obtain a complete build, you will need to build the project located in `android/` with `gradle`. +### Commands for the PWA +```bash +# 🐛 Debugs the project using `webpack.web.config.js` +yarn dev:web +# 📦 Packs the project using `webpack.web.config.js` +yarn pack:web +``` + +### Commands for the PWA Docker Image +```bash + +# 💨 Creates and runs the image locally. Add `--platform=linux/arm64` to docker build for ARM64 devices including Apple Silicon +docker build -t freetubecordova . # Warning, might take a while on Apple Silicon +docker run --name ftcordova -d -p 8080:80 freetubecordova + +# ⬇ Pulls the latest from the Github Container Registry (ghcr.io) +docker pull ghcr.io/marmadilemanteater/freetubecordova:latest +# 👟 Runs the image from ghcr.io +docker run --name ftcordova -d -p 8080:80 ghcr.io/marmadilemanteater/freetubecordova:latest + +# 🏃 Runs the image from Docker Hub. +docker run --name ftcordova -d -p 8080:80 owentruong/freetubecordova:latest + +# 🏃‍♂️ Runs the image from Docker Hub (ARM64) +docker run --platform=linux/arm64 --name ftcordova -d -p 8080:80 owentruong/freetubecordova:latest-arm64 +``` +## Contributing + +**NOTICE: MOST CHANGES SHOULD PROBABLY BE MADE TO [UPSTREAM](https://www.github.com/freetubeapp/freetube) UNLESS DIRECTLY RELATED TO CORDOVA CODE OR WORKFLOWS.** + +If you like to get your hands dirty and want to contribute, we would love to +have your help. Send a pull request and someone will review your code. Please +follow the [Contribution +Guidelines](https://github.com/MarmadileManteater/FreeTubeCordova/blob/development/CONTRIBUTING.md) +before sending your pull request. + + +## Localization + +Translation status + + +If you'd like to localize FreeTube Android, please send submissions to [FreeTube's weblate](https://hosted.weblate.org/engage/free-tube/). + +## Contact +If you ever have any questions, feel free to make an issue here on GitHub. + +## Upstream Donations +If you enjoy using FreeTube Android, you're welcome to leave a donation using the following methods to support upstream development and maintenance. + +* Bitcoin Address: `1Lih7Ho5gnxb1CwPD4o59ss78pwo2T91eS` + +While your donations are much appreciated, only donate if you really want to. Donations are used for keeping the website up and running and eventual code signing costs. + +## License +[![GNU AGPLv3 Image](https://www.gnu.org/graphics/agplv3-155x51.png)](https://www.gnu.org/licenses/agpl-3.0.html) + +FreeTube is Free Software: You can use, study share and improve it at your +will. Specifically you can redistribute and/or modify it under the terms of the +[GNU Affero General Public License](https://www.gnu.org/licenses/agpl-3.0.html) as +published by the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. diff --git a/_icons/.icon-set/background.png b/_icons/.icon-set/background.png new file mode 100644 index 0000000..23a4f00 Binary files /dev/null and b/_icons/.icon-set/background.png differ diff --git a/_icons/.icon-set/background_128x128.png b/_icons/.icon-set/background_128x128.png new file mode 100644 index 0000000..5917ef3 Binary files /dev/null and b/_icons/.icon-set/background_128x128.png differ diff --git a/_icons/.icon-set/background_16x16.png b/_icons/.icon-set/background_16x16.png new file mode 100644 index 0000000..b9d2024 Binary files /dev/null and b/_icons/.icon-set/background_16x16.png differ diff --git a/_icons/.icon-set/background_32x32.png b/_icons/.icon-set/background_32x32.png new file mode 100644 index 0000000..bbb05af Binary files /dev/null and b/_icons/.icon-set/background_32x32.png differ diff --git a/_icons/.icon-set/background_48x48.png b/_icons/.icon-set/background_48x48.png new file mode 100644 index 0000000..dda9e01 Binary files /dev/null and b/_icons/.icon-set/background_48x48.png differ diff --git a/_icons/.icon-set/background_64x64.png b/_icons/.icon-set/background_64x64.png new file mode 100644 index 0000000..c107c20 Binary files /dev/null and b/_icons/.icon-set/background_64x64.png differ diff --git a/_icons/.icon-set/iconColor_256.png b/_icons/.icon-set/iconColor_256.png new file mode 100644 index 0000000..758e4fd Binary files /dev/null and b/_icons/.icon-set/iconColor_256.png differ diff --git a/_icons/.icon-set/iconColor_256_padded.png b/_icons/.icon-set/iconColor_256_padded.png new file mode 100644 index 0000000..fb5c4b8 Binary files /dev/null and b/_icons/.icon-set/iconColor_256_padded.png differ diff --git a/_icons/.icon-set/icon_128x128.png b/_icons/.icon-set/icon_128x128.png new file mode 100644 index 0000000..79a2f84 Binary files /dev/null and b/_icons/.icon-set/icon_128x128.png differ diff --git a/_icons/.icon-set/icon_128x128_padded.png b/_icons/.icon-set/icon_128x128_padded.png new file mode 100644 index 0000000..20631d1 Binary files /dev/null and b/_icons/.icon-set/icon_128x128_padded.png differ diff --git a/_icons/.icon-set/icon_16x16.png b/_icons/.icon-set/icon_16x16.png new file mode 100644 index 0000000..6a3daea Binary files /dev/null and b/_icons/.icon-set/icon_16x16.png differ diff --git a/_icons/.icon-set/icon_16x16_padded.png b/_icons/.icon-set/icon_16x16_padded.png new file mode 100644 index 0000000..3049ea8 Binary files /dev/null and b/_icons/.icon-set/icon_16x16_padded.png differ diff --git a/_icons/.icon-set/icon_32x32.png b/_icons/.icon-set/icon_32x32.png new file mode 100644 index 0000000..374fb61 Binary files /dev/null and b/_icons/.icon-set/icon_32x32.png differ diff --git a/_icons/.icon-set/icon_32x32_padded.png b/_icons/.icon-set/icon_32x32_padded.png new file mode 100644 index 0000000..210ad05 Binary files /dev/null and b/_icons/.icon-set/icon_32x32_padded.png differ diff --git a/_icons/.icon-set/icon_48x48.png b/_icons/.icon-set/icon_48x48.png new file mode 100644 index 0000000..8ce9af1 Binary files /dev/null and b/_icons/.icon-set/icon_48x48.png differ diff --git a/_icons/.icon-set/icon_48x48_padded.png b/_icons/.icon-set/icon_48x48_padded.png new file mode 100644 index 0000000..8005764 Binary files /dev/null and b/_icons/.icon-set/icon_48x48_padded.png differ diff --git a/_icons/.icon-set/icon_64x64.png b/_icons/.icon-set/icon_64x64.png new file mode 100644 index 0000000..2419b7e Binary files /dev/null and b/_icons/.icon-set/icon_64x64.png differ diff --git a/_icons/.icon-set/icon_64x64_padded.png b/_icons/.icon-set/icon_64x64_padded.png new file mode 100644 index 0000000..74f27c3 Binary files /dev/null and b/_icons/.icon-set/icon_64x64_padded.png differ diff --git a/_icons/192x192.png b/_icons/192x192.png new file mode 100644 index 0000000..fd10580 Binary files /dev/null and b/_icons/192x192.png differ diff --git a/_icons/256x256.png b/_icons/256x256.png new file mode 100644 index 0000000..1cfc859 Binary files /dev/null and b/_icons/256x256.png differ diff --git a/_icons/512x512.png b/_icons/512x512.png new file mode 100644 index 0000000..9f580c5 Binary files /dev/null and b/_icons/512x512.png differ diff --git a/_icons/icon.icns b/_icons/icon.icns new file mode 100644 index 0000000..7f40fce Binary files /dev/null and b/_icons/icon.icns differ diff --git a/_icons/icon.svg b/_icons/icon.svg new file mode 100644 index 0000000..871bb00 --- /dev/null +++ b/_icons/icon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/iconBlack.svg b/_icons/iconBlack.svg new file mode 100644 index 0000000..25dc9aa --- /dev/null +++ b/_icons/iconBlack.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/iconBlackSmall.svg b/_icons/iconBlackSmall.svg new file mode 100644 index 0000000..cd569f1 --- /dev/null +++ b/_icons/iconBlackSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/iconCatppuccinFrappeDarkSmall.svg b/_icons/iconCatppuccinFrappeDarkSmall.svg new file mode 100644 index 0000000..c27e4b4 --- /dev/null +++ b/_icons/iconCatppuccinFrappeDarkSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/iconCatppuccinFrappeLightSmall.svg b/_icons/iconCatppuccinFrappeLightSmall.svg new file mode 100644 index 0000000..d0a3892 --- /dev/null +++ b/_icons/iconCatppuccinFrappeLightSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/iconCatppuccinMochaDarkSmall.svg b/_icons/iconCatppuccinMochaDarkSmall.svg new file mode 100644 index 0000000..5607b26 --- /dev/null +++ b/_icons/iconCatppuccinMochaDarkSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/iconCatppuccinMochaLightSmall.svg b/_icons/iconCatppuccinMochaLightSmall.svg new file mode 100644 index 0000000..2ae10e8 --- /dev/null +++ b/_icons/iconCatppuccinMochaLightSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/iconColor.icns b/_icons/iconColor.icns new file mode 100644 index 0000000..e4cc274 Binary files /dev/null and b/_icons/iconColor.icns differ diff --git a/_icons/iconColor.ico b/_icons/iconColor.ico new file mode 100644 index 0000000..e04db49 Binary files /dev/null and b/_icons/iconColor.ico differ diff --git a/_icons/iconColor.png b/_icons/iconColor.png new file mode 100644 index 0000000..407353a Binary files /dev/null and b/_icons/iconColor.png differ diff --git a/_icons/iconColor.svg b/_icons/iconColor.svg new file mode 100644 index 0000000..013d30a --- /dev/null +++ b/_icons/iconColor.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/iconColorSmall.svg b/_icons/iconColorSmall.svg new file mode 100644 index 0000000..7babd8b --- /dev/null +++ b/_icons/iconColorSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/iconDraculaDarkSmall.svg b/_icons/iconDraculaDarkSmall.svg new file mode 100644 index 0000000..a203848 --- /dev/null +++ b/_icons/iconDraculaDarkSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/iconDraculaLightSmall.svg b/_icons/iconDraculaLightSmall.svg new file mode 100644 index 0000000..a02231b --- /dev/null +++ b/_icons/iconDraculaLightSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/iconGruvboxDarkSmall.svg b/_icons/iconGruvboxDarkSmall.svg new file mode 100644 index 0000000..e6dd6ad --- /dev/null +++ b/_icons/iconGruvboxDarkSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/iconGruvboxLightSmall.svg b/_icons/iconGruvboxLightSmall.svg new file mode 100644 index 0000000..a08e5c3 --- /dev/null +++ b/_icons/iconGruvboxLightSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/iconMac.icns b/_icons/iconMac.icns new file mode 100644 index 0000000..c49e2e4 Binary files /dev/null and b/_icons/iconMac.icns differ diff --git a/_icons/iconNordicLightSmall.svg b/_icons/iconNordicLightSmall.svg new file mode 100644 index 0000000..b5dd535 --- /dev/null +++ b/_icons/iconNordicLightSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/iconSolarizedDarkSmall.svg b/_icons/iconSolarizedDarkSmall.svg new file mode 100644 index 0000000..46e685e --- /dev/null +++ b/_icons/iconSolarizedDarkSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/iconSolarizedLightSmall.svg b/_icons/iconSolarizedLightSmall.svg new file mode 100644 index 0000000..584b8b8 --- /dev/null +++ b/_icons/iconSolarizedLightSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/iconWhite.svg b/_icons/iconWhite.svg new file mode 100644 index 0000000..6267305 --- /dev/null +++ b/_icons/iconWhite.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/iconWhiteSmall.svg b/_icons/iconWhiteSmall.svg new file mode 100644 index 0000000..ecc99d8 --- /dev/null +++ b/_icons/iconWhiteSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/logoBlack.svg b/_icons/logoBlack.svg new file mode 100644 index 0000000..08c0d9d --- /dev/null +++ b/_icons/logoBlack.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/logoColor.svg b/_icons/logoColor.svg new file mode 100644 index 0000000..09a2399 --- /dev/null +++ b/_icons/logoColor.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/logoWhite.svg b/_icons/logoWhite.svg new file mode 100644 index 0000000..e67d2c4 --- /dev/null +++ b/_icons/logoWhite.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/mejs-controls.svg b/_icons/mejs-controls.svg new file mode 100644 index 0000000..1cd47e8 --- /dev/null +++ b/_icons/mejs-controls.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/textBlack.svg b/_icons/textBlack.svg new file mode 100644 index 0000000..5569986 --- /dev/null +++ b/_icons/textBlack.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/textBlackSmall.svg b/_icons/textBlackSmall.svg new file mode 100644 index 0000000..494a206 --- /dev/null +++ b/_icons/textBlackSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/textCatppuccinFrappeDarkSmall.svg b/_icons/textCatppuccinFrappeDarkSmall.svg new file mode 100644 index 0000000..b67b41a --- /dev/null +++ b/_icons/textCatppuccinFrappeDarkSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/textCatppuccinFrappeLightSmall.svg b/_icons/textCatppuccinFrappeLightSmall.svg new file mode 100644 index 0000000..47d0d38 --- /dev/null +++ b/_icons/textCatppuccinFrappeLightSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/textCatppuccinMochaDarkSmall.svg b/_icons/textCatppuccinMochaDarkSmall.svg new file mode 100644 index 0000000..b9c2cfc --- /dev/null +++ b/_icons/textCatppuccinMochaDarkSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/textCatppuccinMochaLightSmall.svg b/_icons/textCatppuccinMochaLightSmall.svg new file mode 100644 index 0000000..407fef3 --- /dev/null +++ b/_icons/textCatppuccinMochaLightSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/textColor.svg b/_icons/textColor.svg new file mode 100644 index 0000000..0a02333 --- /dev/null +++ b/_icons/textColor.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/textColorSmall.svg b/_icons/textColorSmall.svg new file mode 100644 index 0000000..9390084 --- /dev/null +++ b/_icons/textColorSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/textDraculaDarkSmall.svg b/_icons/textDraculaDarkSmall.svg new file mode 100644 index 0000000..a3c73e1 --- /dev/null +++ b/_icons/textDraculaDarkSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/textDraculaLightSmall.svg b/_icons/textDraculaLightSmall.svg new file mode 100644 index 0000000..1206d4d --- /dev/null +++ b/_icons/textDraculaLightSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/textGruvboxDarkSmall.svg b/_icons/textGruvboxDarkSmall.svg new file mode 100644 index 0000000..00e3080 --- /dev/null +++ b/_icons/textGruvboxDarkSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/textGruvboxLightSmall.svg b/_icons/textGruvboxLightSmall.svg new file mode 100644 index 0000000..434c116 --- /dev/null +++ b/_icons/textGruvboxLightSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/textNordicLightSmall.svg b/_icons/textNordicLightSmall.svg new file mode 100644 index 0000000..b7b97ba --- /dev/null +++ b/_icons/textNordicLightSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/textSolarizedDarkSmall.svg b/_icons/textSolarizedDarkSmall.svg new file mode 100644 index 0000000..2d57d96 --- /dev/null +++ b/_icons/textSolarizedDarkSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/textSolarizedLightSmall.svg b/_icons/textSolarizedLightSmall.svg new file mode 100644 index 0000000..b6906ee --- /dev/null +++ b/_icons/textSolarizedLightSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/textWhite.svg b/_icons/textWhite.svg new file mode 100644 index 0000000..a00bff6 --- /dev/null +++ b/_icons/textWhite.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_icons/textWhiteSmall.svg b/_icons/textWhiteSmall.svg new file mode 100644 index 0000000..5cec3ef --- /dev/null +++ b/_icons/textWhiteSmall.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/_scripts/ProcessLocalesPlugin.js b/_scripts/ProcessLocalesPlugin.js new file mode 100644 index 0000000..d08bb37 --- /dev/null +++ b/_scripts/ProcessLocalesPlugin.js @@ -0,0 +1,190 @@ +const { existsSync, readFileSync } = require('fs') +const { readFile } = require('fs/promises') +const { join } = require('path') +const { brotliCompress, constants } = require('zlib') +const { promisify } = require('util') +const { load: loadYaml } = require('js-yaml') + +const brotliCompressAsync = promisify(brotliCompress) + +const PLUGIN_NAME = 'ProcessLocalesPlugin' + +class ProcessLocalesPlugin { + constructor(options = {}) { + this.compress = !!options.compress + this.hotReload = !!options.hotReload + + if (typeof options.inputDir !== 'string') { + throw new Error('ProcessLocalesPlugin: no input directory `inputDir` specified.') + } else if (!existsSync(options.inputDir)) { + throw new Error('ProcessLocalesPlugin: the specified input directory does not exist.') + } + this.inputDir = options.inputDir + + if (typeof options.outputDir !== 'string') { + throw new Error('ProcessLocalesPlugin: no output directory `outputDir` specified.') + } + this.outputDir = options.outputDir + + /** @type {Map} */ + this.locales = new Map() + this.localeNames = [] + + /** @type {Map} */ + this.cache = new Map() + + this.filePaths = [] + this.previousTimestamps = new Map() + this.startTime = Date.now() + + /** @type {(updatedLocales: [string, string][]) => void|null} */ + this.notifyLocaleChange = null + + this.loadLocales() + } + + /** @param {import('webpack').Compiler} compiler */ + apply(compiler) { + const { CachedSource, RawSource } = compiler.webpack.sources + const { Compilation, DefinePlugin } = compiler.webpack + + new DefinePlugin({ + 'process.env.HOT_RELOAD_LOCALES': this.hotReload + }).apply(compiler) + + compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { + const IS_DEV_SERVER = !!compiler.watching + + compilation.hooks.processAssets.tapPromise({ + name: PLUGIN_NAME, + stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL + }, async (_assets) => { + // While running in the webpack dev server, this hook gets called for every incremental build. + // For incremental builds we can return the already processed versions, which saves time + // and makes webpack treat them as cached + const promises = [] + + /** @type {[string, string][]} */ + const updatedLocales = [] + if (this.hotReload && !this.notifyLocaleChange) { + console.warn('ProcessLocalesPlugin: Unable to live reload locales as `notifyLocaleChange` is not set.') + } + + for (let [locale, data] of this.locales) { + // eslint-disable-next-line no-async-promise-executor + promises.push(new Promise(async (resolve) => { + if (IS_DEV_SERVER && compiler.fileTimestamps) { + const filePath = join(this.inputDir, `${locale}.yaml`) + + const timestamp = compiler.fileTimestamps.get(filePath)?.safeTime + + if (timestamp && timestamp > (this.previousTimestamps.get(locale) ?? this.startTime)) { + this.previousTimestamps.set(locale, timestamp) + + const contents = await readFile(filePath, 'utf-8') + data = loadYaml(contents) + } else { + const { filename, source } = this.cache.get(locale) + compilation.emitAsset(filename, source, { minimized: true }) + resolve() + return + } + } + + this.removeEmptyValues(data) + + let filename = `${this.outputDir}/${locale}.json` + let output = JSON.stringify(data) + + if (this.hotReload && compiler.fileTimestamps) { + updatedLocales.push([locale, output]) + } + + if (this.compress) { + filename += '.br' + output = await this.compressLocale(output) + } + + let source = new RawSource(output) + + if (IS_DEV_SERVER) { + source = new CachedSource(source) + this.cache.set(locale, { filename, source }) + + // we don't need the unmodified sources anymore, as we use the cache `this.cache` + // so we can clear this to free some memory + this.locales.set(locale, null) + } + + compilation.emitAsset(filename, source, { minimized: true }) + + resolve() + })) + } + + await Promise.all(promises) + + if (this.hotReload && this.notifyLocaleChange && updatedLocales.length > 0) { + this.notifyLocaleChange(updatedLocales) + } + }) + }) + + compiler.hooks.afterCompile.tap(PLUGIN_NAME, (compilation) => { + // eslint-disable-next-line no-extra-boolean-cast + if (!!compiler.watching) { + // watch locale files for changes + compilation.fileDependencies.addAll(this.filePaths) + } + }) + } + + loadLocales() { + const activeLocales = JSON.parse(readFileSync(`${this.inputDir}/activeLocales.json`)) + + for (const locale of activeLocales) { + const filePath = join(this.inputDir, `${locale}.yaml`) + + this.filePaths.push(filePath) + + const contents = readFileSync(filePath, 'utf-8') + const data = loadYaml(contents) + this.locales.set(locale, data) + + this.localeNames.push(data['Locale Name'] ?? locale) + } + } + + async compressLocale(data) { + const buffer = Buffer.from(data, 'utf-8') + + return await brotliCompressAsync(buffer, { + params: { + [constants.BROTLI_PARAM_MODE]: constants.BROTLI_MODE_TEXT, + [constants.BROTLI_PARAM_QUALITY]: constants.BROTLI_MAX_QUALITY, + [constants.BROTLI_PARAM_SIZE_HINT]: buffer.byteLength + } + }) + } + + /** + * vue-i18n doesn't fallback if the translation is an empty string + * so we want to get rid of them and also remove the empty objects that can get left behind + * if we've removed all the keys and values in them + * @param {object|string} data + */ + removeEmptyValues(data) { + for (const key of Object.keys(data)) { + const value = data[key] + if (typeof value === 'object') { + this.removeEmptyValues(value) + } + + if (!value || (typeof value === 'object' && Object.keys(value).length === 0)) { + delete data[key] + } + } + } +} + +module.exports = ProcessLocalesPlugin diff --git a/_scripts/_empty.js b/_scripts/_empty.js new file mode 100644 index 0000000..e69de29 diff --git a/_scripts/_localforage.js b/_scripts/_localforage.js new file mode 100644 index 0000000..7dc3129 --- /dev/null +++ b/_scripts/_localforage.js @@ -0,0 +1,31 @@ + +import { readFile, writeFile } from '../src/renderer/helpers/android' + +export function createInstance(_kwargs) { + return { + async getItem(key) { + const dataLocationFile = await readFile('data://', 'data-location.json') + if (dataLocationFile !== '') { + const locationInfo = JSON.parse(dataLocationFile) + const locationMap = Object.fromEntries(locationInfo.files.map((file) => { return [file.fileName, file.uri] })) + if (key in locationMap) { + return await readFile(locationMap[key]) + } + } + const data = await readFile('data://', key) + return data + }, + async setItem(key, value) { + const dataLocationFile = await readFile('data://', 'data-location.json') + if (dataLocationFile !== '') { + const locationInfo = JSON.parse(dataLocationFile) + const locationMap = Object.fromEntries(locationInfo.files.map((file) => { return [file.fileName, file.uri] })) + if (key in locationMap) { + await writeFile(locationMap[key], value) + return + } + } + await writeFile('data://', key, value) + } + } +} diff --git a/_scripts/_setAppSplashTheme.mjs b/_scripts/_setAppSplashTheme.mjs new file mode 100644 index 0000000..95e455b --- /dev/null +++ b/_scripts/_setAppSplashTheme.mjs @@ -0,0 +1,124 @@ + +import { readFile, readdir, writeFile } from 'fs/promises' +import { join } from 'path' +import { fileURLToPath } from 'url' + + +// sets the splashscreen & icon to one of three predefined themes (this makes it easier to tell, at a glance, which one is open) +// - release (the default production look) +// - nightly +// OR +// - development + +const COLOURS = { + RELEASE: { + primary: '#f04242', + secondary: '#14a4df', + back: '#E4E4E4', + backDark: '#212121' + }, + // catppucin mocha theme colours + NIGHTLY: { + primary: '#cdd6f4', + secondary: '#cdd6f4', + back: '#1e1e2e', + backDark: '#1e1e2e' + }, + // inverted release colours + DEVELOPMENT: { + primary: '#E4E4E4', + secondary: '#E4E4E4', + back: '#f04242', + backDark: '#f04242' + }, + // blue from the logo as the background colour + RC: { + primary: '#E4E4E4', + secondary: '#E4E4E4', + back: '#14a4df', + backDark: '#14a4df' + }, + // solarised dark + FEATURE_BRANCH: { + primary: '#E4E4E4', + secondary: '#E4E4E4', + back: '#204b56', + backDark: '#204b56' + } +} +let colour = 'RELEASE' +for (const key in COLOURS) { + if (process.argv.indexOf(`--${key.toLowerCase().replaceAll('_', '-')}`) !== -1) { + colour = key + } +} + +const currentTheme = COLOURS[colour] + +const scriptDir = fileURLToPath(import.meta.url) +const drawablePath = join(scriptDir, '../../android/app/src/main/res/drawable/') + +const foreground = join(drawablePath, 'ic_launcher_foreground.xml') +let foregroundXML = (await readFile(foreground)).toString() +foregroundXML = foregroundXML.replace(//g, `android:fillColor="${currentTheme.back}" />`) +await writeFile(background, backgroundXML) + +/** + * @warning name is passed into regex unsantised; should never be given user input + * @param {string} xml + * @param {string} name + * @param {string} value + */ +function replaceItem(xml, name, value) { + return xml.replace(new RegExp(`[^"]*?<\/item>`), `${value}`) +} + +async function constructThemePath(isDark = false, version = 0) { + const resDirectory = join(scriptDir, '..', '..', 'android/app/src/main/res/') + const files = await readdir(resDirectory) + const versionsListed = files + .filter(file => file.startsWith(`values${isDark ? '-night-' : '-'}v`)) + .map(file => parseInt(file.split('-v')[1])) + if (versionsListed.indexOf(version) !== -1) { + return join(resDirectory, `values${isDark ? '-night-' : '-'}v${version}`, 'themes.xml') + } else { + return join(resDirectory, 'values', 'themes.xml') + } +} + +async function setValuesForThemeFile(values, isDark = false, version = 0) { + const themePath = await constructThemePath(isDark, version) + let themeXml = (await readFile(themePath)).toString() + for (const key in values) { + themeXml = replaceItem(themeXml, key, values[key]) + } + await writeFile(themePath, themeXml) +} + + +await setValuesForThemeFile({ + windowSplashScreenBackground: currentTheme.back, + windowSplashScreenIconBackgroundColor: currentTheme.back +}, false, 31) + +await setValuesForThemeFile({ + windowSplashScreenBackground: currentTheme.backDark, + windowSplashScreenIconBackgroundColor: currentTheme.backDark +}, true, 31) + +await setValuesForThemeFile({ + windowSplashScreenBackground: currentTheme.back, + windowSplashScreenIconBackgroundColor: currentTheme.back +}, false, 33) + +await setValuesForThemeFile({ + windowSplashScreenBackground: currentTheme.backDark, + windowSplashScreenIconBackgroundColor: currentTheme.backDark +}, true, 33) diff --git a/_scripts/add-iv-supported-links.js b/_scripts/add-iv-supported-links.js new file mode 100644 index 0000000..d3c0a9d --- /dev/null +++ b/_scripts/add-iv-supported-links.js @@ -0,0 +1,14 @@ + +const { readFile, writeFile } = require('fs/promises') +const { join } = require('path') + +;(async () => { + const manifest = (await readFile(join(__dirname, '../android/app/src/main/AndroidManifest.xml'))).toString() + const invidiousInstances = JSON.parse((await readFile(join(__dirname, '../static/invidious-instances.json'))).toString()) + const supportedLinks = manifest.match(/[\s\S]*?/gm) + const instancesXml = invidiousInstances.map(({ url, cors}) => { + return `` + }).join('\n ') + const postManifest = manifest.replace(supportedLinks[0], `\n ${instancesXml}\n `) + await writeFile(join(__dirname, '../android/app/src/main/AndroidManifest.xml'), postManifest) +})() diff --git a/_scripts/build.js b/_scripts/build.js new file mode 100644 index 0000000..ee1b7fa --- /dev/null +++ b/_scripts/build.js @@ -0,0 +1,53 @@ +const os = require('os') +const builder = require('electron-builder') +const config = require('./ebuilder.config.js') + +const Platform = builder.Platform +const Arch = builder.Arch +const args = process.argv + +let targets +const platform = os.platform() + +if (platform === 'darwin') { + let arch = Arch.x64 + + if (args[2] === 'arm64') { + arch = Arch.arm64 + } + + targets = Platform.MAC.createTarget(['DMG', 'zip', '7z'], arch) +} else if (platform === 'win32') { + let arch = Arch.x64 + + if (args[2] === 'arm64') { + arch = Arch.arm64 + } + + targets = Platform.WINDOWS.createTarget(['nsis', 'zip', '7z', 'portable'], arch) +} else if (platform === 'linux') { + let arch = Arch.x64 + + if (args[2] === 'arm64') { + arch = Arch.arm64 + } + + if (args[2] === 'arm32') { + arch = Arch.armv7l + } + + targets = Platform.LINUX.createTarget(['deb', 'zip', '7z', 'rpm', 'AppImage', 'pacman'], arch) +} + +builder + .build({ + targets, + config, + publish: 'never' + }) + .then(m => { + console.log(m) + }) + .catch(e => { + console.error(e) + }) diff --git a/_scripts/clean.mjs b/_scripts/clean.mjs new file mode 100644 index 0000000..b4ac899 --- /dev/null +++ b/_scripts/clean.mjs @@ -0,0 +1,10 @@ +import { rm } from 'fs/promises' +import { join } from 'path' + +const BUILD_PATH = join(import.meta.dirname, '..', 'build') +const DIST_PATH = join(import.meta.dirname, '..', 'dist') + +await Promise.all([ + rm(BUILD_PATH, { recursive: true, force: true }), + rm(DIST_PATH, { recursive: true, force: true }) +]) diff --git a/_scripts/dev-runner.js b/_scripts/dev-runner.js new file mode 100644 index 0000000..15d9b35 --- /dev/null +++ b/_scripts/dev-runner.js @@ -0,0 +1,215 @@ +process.env.NODE_ENV = 'development' + +const electron = require('electron') +const webpack = require('webpack') +const WebpackDevServer = require('webpack-dev-server') +const kill = require('tree-kill') + +const path = require('path') +const { spawn } = require('child_process') + +const ProcessLocalesPlugin = require('./ProcessLocalesPlugin') + +let electronProcess = null +let manualRestart = null + +const remoteDebugging = process.argv.indexOf('--remote-debug') !== -1 +const web = process.argv.indexOf('--web') !== -1 + +let mainConfig +let rendererConfig +let botGuardScriptConfig +let webConfig +let SHAKA_LOCALES_TO_BE_BUNDLED + +if (!web) { + mainConfig = require('./webpack.main.config') + rendererConfig = require('./webpack.renderer.config') + botGuardScriptConfig = require('./webpack.botGuardScript.config') + + SHAKA_LOCALES_TO_BE_BUNDLED = rendererConfig.SHAKA_LOCALES_TO_BE_BUNDLED + delete rendererConfig.SHAKA_LOCALES_TO_BE_BUNDLED +} else { + webConfig = require('./webpack.web.config') +} + +if (remoteDebugging) { + // disable dvtools open in electron + process.env.RENDERER_REMOTE_DEBUGGING = true +} + +// Define exit code for relaunch and set it in the environment +const relaunchExitCode = 69 +process.env.FREETUBE_RELAUNCH_EXIT_CODE = relaunchExitCode + +const port = 9080 + +async function killElectron(pid) { + return new Promise((resolve, reject) => { + if (pid) { + kill(pid, err => { + if (err) reject(err) + + resolve() + }) + } else { + resolve() + } + }) +} + +async function restartElectron() { + console.log('\nStarting electron...') + + const { pid } = electronProcess || {} + await killElectron(pid) + + electronProcess = spawn(electron, [ + path.join(__dirname, '../dist/main.js'), + // '--enable-logging', // Enable to show logs from all electron processes + remoteDebugging ? '--inspect=9222' : '', + remoteDebugging ? '--remote-debugging-port=9223' : '' + ], + // { stdio: 'inherit' } // required for logs to actually appear in the stdout + ) + + electronProcess.on('exit', (code, _) => { + if (code === relaunchExitCode) { + electronProcess = null + restartElectron() + return + } + + if (!manualRestart) process.exit(0) + }) +} + +/** + * @param {import('webpack').Compiler} compiler + * @param {WebpackDevServer} devServer + */ +function setupNotifyLocaleUpdate(compiler, devServer) { + const notifyLocaleChange = (updatedLocales) => { + devServer.sendMessage(devServer.webSocketServer.clients, 'freetube-locale-update', updatedLocales) + } + + compiler.options.plugins + .filter(plugin => plugin instanceof ProcessLocalesPlugin) + .forEach((/** @type {ProcessLocalesPlugin} */plugin) => { + plugin.notifyLocaleChange = notifyLocaleChange + }) +} + +function startBotGuardScript() { + webpack(botGuardScriptConfig, (err) => { + if (err) console.error(err) + + console.log(`\nCompiled ${botGuardScriptConfig.name} script!`) + }) +} + +function startMain() { + const compiler = webpack(mainConfig) + const { name } = compiler + + compiler.hooks.afterEmit.tap('afterEmit', async () => { + console.log(`\nCompiled ${name} script!`) + + manualRestart = true + await restartElectron() + setTimeout(() => { + manualRestart = false + }, 2500) + + console.log(`\nWatching file changes for ${name} script...`) + }) + + compiler.watch({ + aggregateTimeout: 500, + }, + err => { + if (err) console.error(err) + }) +} + +function startRenderer(callback) { + const compiler = webpack(rendererConfig) + const { name } = compiler + + compiler.hooks.afterEmit.tap('afterEmit', () => { + console.log(`\nCompiled ${name} script!`) + console.log(`\nWatching file changes for ${name} script...`) + }) + + const server = new WebpackDevServer({ + static: [ + { + directory: path.resolve(__dirname, '..', 'static'), + watch: { + ignored: [ + /(dashFiles|storyboards)\/*/, + '/**/.DS_Store', + '**/static/locales/*' + ] + }, + publicPath: '/static' + }, + { + directory: path.resolve(__dirname, '..', 'node_modules', 'shaka-player', 'ui', 'locales'), + publicPath: '/static/shaka-player-locales', + watch: { + // Ignore everything that isn't one of the locales that we would bundle in production mode + ignored: `**/!(${SHAKA_LOCALES_TO_BE_BUNDLED.join('|')}).json` + } + } + ], + port + }, compiler) + + server.startCallback(err => { + if (err) console.error(err) + + setupNotifyLocaleUpdate(compiler, server) + + callback() + }) +} + +function startWeb () { + const compiler = webpack(webConfig) + const { name } = compiler + + compiler.hooks.afterEmit.tap('afterEmit', () => { + console.log(`\nCompiled ${name} script!`) + console.log(`\nWatching file changes for ${name} script...`) + }) + + const server = new WebpackDevServer({ + open: true, + static: { + directory: path.resolve(__dirname, '..', 'static'), + watch: { + ignored: [ + /(dashFiles|storyboards)\/*/, + '/**/.DS_Store', + '**/static/locales/*' + ] + } + }, + port + }, compiler) + + server.startCallback(err => { + if (err) console.error(err) + + setupNotifyLocaleUpdate(compiler, server) + }) +} +if (!web) { + startRenderer(() => { + startBotGuardScript() + startMain() + }) +} else { + startWeb() +} diff --git a/_scripts/ebuilder.config.js b/_scripts/ebuilder.config.js new file mode 100644 index 0000000..14d0d9d --- /dev/null +++ b/_scripts/ebuilder.config.js @@ -0,0 +1,94 @@ +const { name, productName } = require('../package.json') + +const config = { + appId: `io.freetubeapp.${name}`, + copyright: 'Copyleft © 2020-2025 freetubeapp@protonmail.com', + // asar: false, + // compression: 'store', + productName, + directories: { + output: './build/', + }, + protocols: [ + { + name: 'FreeTube', + schemes: [ + 'freetube' + ] + } + ], + files: [ + '_icons/iconColor.*', + 'icon.svg', + './dist/**/*', + '!dist/web/*', + '!node_modules/**/*', + ], + dmg: { + contents: [ + { + path: '/Applications', + type: 'link', + x: 410, + y: 230, + }, + { + type: 'file', + x: 130, + y: 230, + }, + ], + window: { + height: 380, + width: 540, + } + }, + linux: { + category: 'Network', + icon: '_icons/icon.svg', + target: ['deb', 'zip', '7z', 'rpm', 'AppImage', 'pacman'], + }, + // See the following issues for more information + // https://github.com/jordansissel/fpm/issues/1503 + // https://github.com/jgraph/drawio-desktop/issues/259 + rpm: { + fpm: ['--rpm-rpmbuild-define=_build_id_links none'] + }, + deb: { + depends: [ + 'libgtk-3-0', + 'libnotify4', + 'libnss3', + 'libxss1', + 'libxtst6', + 'xdg-utils', + 'libatspi2.0-0', + 'libuuid1', + 'libsecret-1-0' + ] + }, + mac: { + category: 'public.app-category.utilities', + icon: '_icons/iconMac.icns', + target: ['dmg', 'zip', '7z'], + type: 'distribution', + extendInfo: { + CFBundleURLTypes: [ + 'freetube' + ], + CFBundleURLSchemes: [ + 'freetube' + ] + } + }, + win: { + icon: '_icons/icon.ico', + target: ['nsis', 'zip', '7z', 'portable'], + }, + nsis: { + allowToChangeInstallationDirectory: true, + oneClick: false, + }, +} + +module.exports = config diff --git a/_scripts/eslint-rules/plugin.mjs b/_scripts/eslint-rules/plugin.mjs new file mode 100644 index 0000000..451cd50 --- /dev/null +++ b/_scripts/eslint-rules/plugin.mjs @@ -0,0 +1,11 @@ +import preferUseI18nPolyfillRule from './prefer-use-i18n-polyfill-rule.mjs' + +export default { + meta: { + name: 'eslint-plugin-freetube', + version: '1.0' + }, + rules: { + 'prefer-use-i18n-polyfill': preferUseI18nPolyfillRule + } +} diff --git a/_scripts/eslint-rules/prefer-use-i18n-polyfill-rule.mjs b/_scripts/eslint-rules/prefer-use-i18n-polyfill-rule.mjs new file mode 100644 index 0000000..1d27f74 --- /dev/null +++ b/_scripts/eslint-rules/prefer-use-i18n-polyfill-rule.mjs @@ -0,0 +1,62 @@ +import { dirname, relative, resolve } from 'path' + +const polyfillPath = resolve(import.meta.dirname, '../../src/renderer/composables/use-i18n-polyfill') + +function getRelativePolyfillPath(filePath) { + const relativePath = relative(dirname(filePath), polyfillPath).replaceAll('\\', '/') + + if (relativePath[0] !== '.') { + return `./${relativePath}` + } + + return relativePath +} + +/** @type {import('eslint').Rule.RuleModule} */ +export default { + meta: { + type: 'problem', + fixable: 'code' + }, + create(context) { + return { + 'ImportDeclaration[source.value="vue-i18n"]'(node) { + const specifierIndex = node.specifiers.findIndex(specifier => specifier.type === 'ImportSpecifier' && specifier.imported.name === 'useI18n') + + if (specifierIndex !== -1) { + context.report({ + node: node.specifiers.length === 1 ? node : node.specifiers[specifierIndex], + message: "Please use FreeTube's useI18n polyfill, as vue-i18n's useI18n composable does not work when the vue-i18n is in legacy mode, which is needed for components using the Options API.", + fix: context.physicalFilename === '' + ? undefined + : (fixer) => { + const relativePath = getRelativePolyfillPath(context.physicalFilename) + + // If the import only imports `useI18n`, we can just update the source/from text + // Else we need to create a new import for `useI18n` and remove useI18n from the original one + if (node.specifiers.length === 1) { + return fixer.replaceText(node.source, `'${relativePath}'`) + } else { + const specifier = node.specifiers[specifierIndex] + + let specifierText = 'useI18n' + + if (specifier.imported.name !== specifier.local.name) { + specifierText += ` as ${specifier.local.name}` + } + + return [ + fixer.removeRange([ + specifierIndex === 0 ? specifier.start : node.specifiers[specifierIndex - 1].end, + specifierIndex === node.specifiers.length - 1 ? specifier.end : node.specifiers[specifierIndex + 1].start + ]), + fixer.insertTextAfter(node, `\nimport { ${specifierText} } from '${relativePath}'`) + ] + } + } + }) + } + } + } + } +} diff --git a/_scripts/getInstances.js b/_scripts/getInstances.js new file mode 100644 index 0000000..d1b5bdb --- /dev/null +++ b/_scripts/getInstances.js @@ -0,0 +1,16 @@ +const fs = require('fs/promises') +const invidiousApiUrl = 'https://api.invidious.io/instances.json' + +fetch(invidiousApiUrl).then(e => e.json()).then(res => { + const data = res.filter((instance) => { + return !(instance[0].includes('.onion') || + instance[0].includes('.i2p') || + !instance[1].api) + }).map((instance) => { + return { + url: instance[1].uri.replace(/\/$/, ''), + cors: instance[1].cors + } + }) + fs.writeFile('././static/invidious-instances.json', JSON.stringify(data, null, 2)) +}) diff --git a/_scripts/getRegions.mjs b/_scripts/getRegions.mjs new file mode 100644 index 0000000..5b36a05 --- /dev/null +++ b/_scripts/getRegions.mjs @@ -0,0 +1,162 @@ +/** + * This script updates the files in static/geolocations with the available locations on YouTube. + * + * It tries to map every active FreeTube language (static/locales/activelocales.json) + * to it's equivalent on YouTube. + * + * It then uses those language mappings, + * to scrape the location selection menu on the YouTube website, in every mapped language. + * + * All languages it couldn't find on YouTube, that don't have manually added mapping, + * get logged to the console, as well as all unmapped YouTube languages. + */ + +import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs' +import { Innertube, Misc } from 'youtubei.js' + +const STATIC_DIRECTORY = `${import.meta.dirname}/../static` + +const activeLanguagesPath = `${STATIC_DIRECTORY}/locales/activeLocales.json` +/** @type {string[]} */ +const activeLanguages = JSON.parse(readFileSync(activeLanguagesPath, { encoding: 'utf8' })) + +// en-US is en on YouTube +const initialResponse = await scrapeLanguage('en') + +// Scrape language menu in en-US + +/** @type {string[]} */ +const youTubeLanguages = initialResponse.data.actions[0].openPopupAction.popup.multiPageMenuRenderer.sections[0].multiPageMenuSectionRenderer.items[2].compactLinkRenderer.serviceEndpoint.signalServiceEndpoint.actions[0].getMultiPageMenuAction.menu.multiPageMenuRenderer.sections[0].multiPageMenuSectionRenderer.items + .map(({ compactLinkRenderer }) => { + return compactLinkRenderer.serviceEndpoint.signalServiceEndpoint.actions[0].selectLanguageCommand.hl + }) + +// map FreeTube languages to their YouTube equivalents + +const foundLanguageNames = ['en-US'] +const unusedYouTubeLanguageNames = [] +const languagesToScrape = [] + +for (const language of youTubeLanguages) { + if (activeLanguages.includes(language)) { + foundLanguageNames.push(language) + languagesToScrape.push({ + youTube: language, + freeTube: language + }) + // eslint-disable-next-line @stylistic/brace-style + } + // special cases + else if (language === 'de') { + foundLanguageNames.push('de-DE') + languagesToScrape.push({ + youTube: 'de', + freeTube: 'de-DE' + }) + } else if (language === 'fr') { + foundLanguageNames.push('fr-FR') + languagesToScrape.push({ + youTube: 'fr', + freeTube: 'fr-FR' + }) + } else if (language === 'no') { + // according to https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes + // "no" is the macro language for "nb" and "nn" + foundLanguageNames.push('nb-NO', 'nn') + languagesToScrape.push({ + youTube: 'no', + freeTube: 'nb-NO' + }) + languagesToScrape.push({ + youTube: 'no', + freeTube: 'nn' + }) + } else if (language === 'iw') { + // according to https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes + // "iw" is the old/original code for Hebrew, these days it's "he" + foundLanguageNames.push('he') + languagesToScrape.push({ + youTube: 'iw', + freeTube: 'he' + }) + } else if (language === 'es-419') { + foundLanguageNames.push('es-AR', 'es-MX') + languagesToScrape.push({ + youTube: 'es-419', + freeTube: 'es-AR' + }) + languagesToScrape.push({ + youTube: 'es-419', + freeTube: 'es-MX' + }) + } else if (language !== 'en') { + unusedYouTubeLanguageNames.push(language) + } +} + +foundLanguageNames.push('pt-BR') +languagesToScrape.push({ + youTube: 'pt', + freeTube: 'pt-BR' +}) + +console.log("Active FreeTube languages that aren't available on YouTube:") +console.log(activeLanguages.filter(lang => !foundLanguageNames.includes(lang)).sort()) + +console.log("YouTube languages that don't have an equivalent active FreeTube language:") +console.log(unusedYouTubeLanguageNames.sort()) + +// Scrape the location menu in various languages and write files to the file system + +rmSync(`${STATIC_DIRECTORY}/geolocations`, { recursive: true }) +mkdirSync(`${STATIC_DIRECTORY}/geolocations`) + +processGeolocations('en-US', 'en', initialResponse) + +for (const { youTube, freeTube } of languagesToScrape) { + const response = await scrapeLanguage(youTube) + + processGeolocations(freeTube, youTube, response) +} + +async function scrapeLanguage(youTubeLanguageCode) { + const session = await Innertube.create({ + retrieve_player: false, + generate_session_locally: true, + lang: youTubeLanguageCode + }) + + return await session.actions.execute('/account/account_menu') +} + +function processGeolocations(freeTubeLanguage, youTubeLanguage, response) { + const geolocations = response.data.actions[0].openPopupAction.popup.multiPageMenuRenderer.sections[0].multiPageMenuSectionRenderer.items[4].compactLinkRenderer.serviceEndpoint.signalServiceEndpoint.actions[0].getMultiPageMenuAction.menu.multiPageMenuRenderer.sections[0].multiPageMenuSectionRenderer.items + .map(({ compactLinkRenderer }) => { + return { + name: new Misc.Text(compactLinkRenderer.title).toString().trim(), + code: compactLinkRenderer.serviceEndpoint.signalServiceEndpoint.actions[0].selectCountryCommand.gl + } + }) + + const normalisedFreeTubeLanguage = freeTubeLanguage.replace('_', '-') + + // give Intl.Collator 4 locales, in the hopes that it supports one of them + // deduplicate the list so it doesn't have to do duplicate work + const localeSet = new Set() + localeSet.add(normalisedFreeTubeLanguage) + localeSet.add(youTubeLanguage) + localeSet.add(normalisedFreeTubeLanguage.split('-')[0]) + localeSet.add(youTubeLanguage.split('-')[0]) + + const locales = Array.from(localeSet) + + // only sort if node supports sorting the language, otherwise hope that YouTube's sorting was correct + // node 20.3.1 doesn't support sorting `eu` + if (Intl.Collator.supportedLocalesOf(locales).length > 0) { + const collator = new Intl.Collator(locales) + + geolocations.sort((a, b) => collator.compare(a.name, b.name)) + } + + writeFileSync(`${STATIC_DIRECTORY}/geolocations/${freeTubeLanguage}.json`, JSON.stringify(geolocations)) +} diff --git a/_scripts/getShakaLocales.js b/_scripts/getShakaLocales.js new file mode 100644 index 0000000..644a13a --- /dev/null +++ b/_scripts/getShakaLocales.js @@ -0,0 +1,109 @@ +const { readFileSync, readdirSync } = require('fs') + +function getPreloadedLocales() { + const localesFile = readFileSync(`${__dirname}/../node_modules/shaka-player/dist/locales.js`, 'utf-8') + + const localesLine = localesFile.match(/^\/\/ LOCALES: ([\w ,-]+)$/m) + + if (!localesLine) { + throw new Error("Failed to parse shaka-player's preloaded locales") + } + + return localesLine[1].split(',').map(locale => locale.trim()) +} + +function getAllLocales() { + const filenames = readdirSync(`${__dirname}/../node_modules/shaka-player/ui/locales`) + + return new Set(filenames + .filter(filename => filename !== 'source.json' && filename.endsWith('.json')) + .map(filename => filename.replace('.json', ''))) +} + +/** + * Maps the shaka locales to FreeTube's active ones + * This allows us to know which locale files are actually needed + * and which shaka locale needs to be activated for a given FreeTube one. + * @param {Set} shakaLocales + * @param {string[]} freeTubeLocales + */ +function getMappings(shakaLocales, freeTubeLocales) { + /** + * @type {[string, string][]} + * Using this structure as it gets passed to `new Map()` in the player component + * The first element is the FreeTube locale, the second one is the shaka-player one + */ + const mappings = [] + + for (const locale of freeTubeLocales) { + if (shakaLocales.has(locale)) { + mappings.push([ + locale, + locale + ]) + } else if (shakaLocales.has(locale.split('-')[0])) { + mappings.push([ + locale, + locale.split('-')[0] + ]) + } + } + + // special cases + + mappings.push( + // according to https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes + // "no" is the macro language for "nb" and "nn" + [ + 'nb-NO', + 'no' + ], + [ + 'nn', + 'no' + ], + + // according to https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes + // "iw" is the old/original code for Hebrew, these days it's "he" + [ + 'he', + 'iw' + ], + + // not sure why we have pt, pt-PT and pt-BR in the FreeTube locales + // as pt and pt-PT are the same thing, but we should handle it here anyway + [ + 'pt', + 'pt-PT' + ] + ) + + return mappings +} + +function getShakaLocales() { + const shakaLocales = getAllLocales() + + /** @type {string[]} */ + const freeTubeLocales = JSON.parse(readFileSync(`${__dirname}/../static/locales/activeLocales.json`, 'utf-8')) + + const mappings = getMappings(shakaLocales, freeTubeLocales) + + const preloaded = getPreloadedLocales() + + const shakaMappings = mappings.map(mapping => mapping[1]) + + // use a set to deduplicate the list + // we don't need to bundle any locale files that are already embedded in shaka-player/preloaded + + /** @type {string[]} */ + const toBeBundled = [...new Set(shakaMappings.filter(locale => !preloaded.includes(locale)))] + + return { + SHAKA_LOCALE_MAPPINGS: mappings, + SHAKA_LOCALES_PREBUNDLED: preloaded, + SHAKA_LOCALES_TO_BE_BUNDLED: toBeBundled + } +} + +module.exports = getShakaLocales() diff --git a/_scripts/helpers.js b/_scripts/helpers.js new file mode 100644 index 0000000..8b70fea --- /dev/null +++ b/_scripts/helpers.js @@ -0,0 +1,32 @@ + +const exec = require('child_process').exec + +/** + * Calls `child_process`.exec, but it outputs + * all of the stdout live and can be awaited + * @param {string} command The command to be executed + * @returns + */ +function execWithLiveOutput (command) { + return new Promise((resolve, reject) => { + const execCall = exec(command, (error, stdout, stderr) => { + if (error) { + reject(error) + } + resolve() + }) + execCall.stdout.on('data', (data) => { + process.stdout.write(data) + }) + execCall.stderr.on('data', (data) => { + console.error(data) + }) + execCall.on('close', () => { + resolve() + }) + }) +} + +module.exports = { + execWithLiveOutput +} diff --git a/_scripts/injectAllowedPaths.mjs b/_scripts/injectAllowedPaths.mjs new file mode 100644 index 0000000..e5c1ce2 --- /dev/null +++ b/_scripts/injectAllowedPaths.mjs @@ -0,0 +1,48 @@ +/** + * Injects the paths that the renderer process is allowed to read into the main.js file, + * by replacing __FREETUBE_ALLOWED_PATHS__ with an array of strings with the paths. + * + * This allows the main process to validate the paths which the renderer process accesses, + * to ensure that it cannot access other files on the disk, without the users permission (e.g. file picker). + */ +import { closeSync, ftruncateSync, openSync, readFileSync, readdirSync, writeSync } from 'fs' +import { join, relative, resolve } from 'path' + +const distDirectory = resolve(import.meta.dirname, '..', 'dist') +const webDirectory = join(distDirectory, 'web') + +const paths = readdirSync(distDirectory, { + recursive: true, + withFileTypes: true +}) + .filter(dirent => { + // only include files not directories + return dirent.isFile() && + // disallow the renderer process/browser windows to read the main.js file + dirent.name !== 'main.js' && + dirent.name !== 'main.js.LICENSE.txt' && + // disallow the renderer process/browser windows to read the botGuardScript.js file + dirent.name !== 'botGuardScript.js' && + // filter out any web build files, in case the dist directory contains a web build + !dirent.parentPath.startsWith(webDirectory) + }) + .map(dirent => { + const joined = join(dirent.parentPath, dirent.name) + return '/' + relative(distDirectory, joined).replaceAll('\\', '/') + }) + +let fileHandle +try { + fileHandle = openSync(join(distDirectory, 'main.js'), 'r+') + + let contents = readFileSync(fileHandle, 'utf-8') + + contents = contents.replace('__FREETUBE_ALLOWED_PATHS__', JSON.stringify(paths)) + + ftruncateSync(fileHandle) + writeSync(fileHandle, contents, 0, 'utf-8') +} finally { + if (typeof fileHandle !== 'undefined') { + closeSync(fileHandle) + } +} diff --git a/_scripts/mime-db-shrinking-loader.js b/_scripts/mime-db-shrinking-loader.js new file mode 100644 index 0000000..491ccbe --- /dev/null +++ b/_scripts/mime-db-shrinking-loader.js @@ -0,0 +1,22 @@ +/** + * electron-context-menu only needs mime-db for its save as feature. + * As we only activate save image and save as image features, we can remove all other mimetypes, + * as they will never get used. + * Which results in quite a significant reduction in file size. + * @param {string} source + */ +module.exports = function (source) { + const original = JSON.parse(source) + + // Only the extensions field is needed, see: https://github.com/kevva/ext-list/blob/v2.2.2/index.js + + return JSON.stringify({ + 'image/apng': { extensions: original['image/apng'].extensions }, + 'image/avif': { extensions: original['image/avif'].extensions }, + 'image/gif': { extensions: original['image/gif'].extensions }, + 'image/jpeg': { extensions: original['image/jpeg'].extensions }, + 'image/png': { extensions: original['image/png'].extensions }, + 'image/svg+xml': { extensions: original['image/svg+xml'].extensions }, + 'image/webp': { extensions: original['image/webp'].extensions } + }) +} diff --git a/_scripts/patchShaka.mjs b/_scripts/patchShaka.mjs new file mode 100644 index 0000000..c558288 --- /dev/null +++ b/_scripts/patchShaka.mjs @@ -0,0 +1,134 @@ +// This script fixes shaka not exporting its type definitions and referencing remote google fonts in its CSS +// by adding an export line to the type definitions and downloading the fonts and updating the CSS to point to the local files +// this script only makes changes if they are needed, so running it multiple times doesn't cause any problems + +import { appendFileSync, closeSync, ftruncateSync, openSync, readFileSync, writeFileSync, writeSync } from 'fs' +import { resolve } from 'path' + +const SHAKA_DIST_DIR = resolve(import.meta.dirname, '../node_modules/shaka-player/dist') + +function fixTypes() { + let fixedTypes = false + + let fileHandleNormal + try { + fileHandleNormal = openSync(`${SHAKA_DIST_DIR}/shaka-player.ui.d.ts`, 'a+') + + const contents = readFileSync(fileHandleNormal, 'utf-8') + + // This script is run after every `yarn install`, even if shaka-player wasn't updated + // So we want to check first, if we actually need to make any changes + // or if the ones from the previous run are still intact + if (!contents.includes('export default shaka')) { + appendFileSync(fileHandleNormal, 'export default shaka;\n') + + fixedTypes = true + } + } finally { + if (typeof fileHandleNormal !== 'undefined') { + closeSync(fileHandleNormal) + } + } + + let fileHandleDebug + try { + fileHandleDebug = openSync(`${SHAKA_DIST_DIR}/shaka-player.ui.debug.d.ts`, 'a+') + + const contents = readFileSync(fileHandleDebug, 'utf-8') + + // This script is run after every `yarn install`, even if shaka-player wasn't updated + // So we want to check first, if we actually need to make any changes + // or if the ones from the previous run are still intact + if (!contents.includes('export default shaka')) { + appendFileSync(fileHandleDebug, 'export default shaka;\n') + + fixedTypes = true + } + } finally { + if (typeof fileHandleDebug !== 'undefined') { + closeSync(fileHandleDebug) + } + } + + if (fixedTypes) { + console.log('Fixed shaka-player types') + } +} + +async function removeRobotoFont() { + let cssFileHandle + try { + cssFileHandle = openSync(`${SHAKA_DIST_DIR}/controls.css`, 'r+') + + let cssContents = readFileSync(cssFileHandle, 'utf-8') + + const beforeReplacement = cssContents.length + cssContents = cssContents.replace(/@font-face{font-family:Roboto;[^}]+}/, '') + + if (cssContents.length !== beforeReplacement) { + ftruncateSync(cssFileHandle) + writeSync(cssFileHandle, cssContents, 0, 'utf-8') + + console.log('Removed shaka-player Roboto font, so it uses ours') + } + } finally { + if (typeof cssFileHandle !== 'undefined') { + closeSync(cssFileHandle) + } + } +} + +async function replaceAndDownloadMaterialIconsFont() { + let cssFileHandle + try { + cssFileHandle = openSync(`${SHAKA_DIST_DIR}/controls.css`, 'r+') + + let cssContents = readFileSync(cssFileHandle, 'utf-8') + + const fontFaceRegex = /@font-face{font-family:'Material Icons Round'[^}]+format\('opentype'\)}/ + + if (fontFaceRegex.test(cssContents)) { + const cssResponse = await fetch('https://fonts.googleapis.com/icon?family=Material+Icons+Round', { + headers: { + // Without the user-agent it returns the otf file instead of the woff2 one + 'user-agent': 'Firefox/125.0' + } + }) + + const text = await cssResponse.text() + + let newFontCSS = text.match(/(@font-face\s*{[^}]+})/)[1].replaceAll('\n', '') + + const urlMatch = newFontCSS.match(/https:\/\/fonts\.gstatic\.com\/s\/materialiconsround\/(?[^/]+)\/[^.]+\.(?\w+)/) + + const url = urlMatch[0] + const { version, extension } = urlMatch.groups + + const fontResponse = await fetch(url) + const fontContent = new Uint8Array(await fontResponse.arrayBuffer()) + + const filename = `shaka-materialiconsround-${version}.${extension}` + writeFileSync(`${SHAKA_DIST_DIR}/${filename}`, fontContent) + + newFontCSS = newFontCSS.replace(url, `./${filename}`) + + cssContents = cssContents.replace(fontFaceRegex, newFontCSS) + + ftruncateSync(cssFileHandle) + writeSync(cssFileHandle, cssContents, 0, 'utf-8') + + console.log('Changed shaka-player Material Icons Rounded font to use the smaller woff2 format instead of otf') + console.log('Downloaded shaka-player Material Icons Rounded font') + } + } catch (e) { + console.error(e) + } finally { + if (typeof cssFileHandle !== 'undefined') { + closeSync(cssFileHandle) + } + } +} + +fixTypes() +await removeRobotoFont() +await replaceAndDownloadMaterialIconsFont() diff --git a/_scripts/releaseAndroid.js b/_scripts/releaseAndroid.js new file mode 100644 index 0000000..6aa90c2 --- /dev/null +++ b/_scripts/releaseAndroid.js @@ -0,0 +1,105 @@ +// script to trigger release +// #region Imports +const { version } = require('../package.json') +const { promisify } = require('util') +const { fetch } = require('undici') +const { get } = require('prompt') +const { exec } = require('child_process') +const { randomUUID } = require('crypto') +const { writeFile, rm, readFile } = require('fs/promises') +// #endregion +;(async (get, exec) => { + const givenArguments = { dryRun: false } + for (let arg of process.argv) { + if (arg.startsWith('--version-number=')) { + givenArguments.versionNumber = arg.split('--version-number=')[1] + } + if (arg.startsWith('--number-of-commits=')) { + givenArguments.numberOfCommits = parseInt(arg.split('--number-of-commits=')[1]) + } + if (arg === '--dry-run') { + givenArguments.dryRun = true + } + if (arg.startsWith('--f=')) { + givenArguments.message = arg.split('--f=')[1] + } + } + if (givenArguments.dryRun) { + console.log('starting dry run') + } + const releases = await fetch('https://api.github.com/repos/MarmadileManteater/FreeTubeCordova/releases') + /** @type {Array<{tag_name: string}>} */ + const releasesJSON = await releases.json() + // #region Version Number + const latestTag = releasesJSON[0].tag_name + const [ _latestMajor, _latestMinor, _latestPatch, latestRun ] = latestTag.split('.') + const [ currentMajor, currentMinor, currentPatch ] = version.split('.') + const latestRunNumber = parseInt(latestRun) + const currentRunNumber = latestRunNumber + 1 + const defaultVersionNumber = `${currentMajor}.${currentMinor}.${currentPatch}.${currentRunNumber}` + // get version number from either the props or a prompt + let { versionNumber } = ('versionNumber' in givenArguments) ? givenArguments : await get({ + properties: { + versionNumber: { + pattern: /[0-9]*?.[0-9]*?.[0-9]*?.[0-9]*/, + message: 'Version number to release with', + default: defaultVersionNumber + } + } + }) + const buildNumber = versionNumber.split('.').at(-1) + if (versionNumber === 'default') { + versionNumber = defaultVersionNumber + } + // #endregion + if (!('message' in givenArguments)) { + // #region Latest Git History + const gitDiff = (await exec('git log origin/development...origin/release')).stdout + const numberOfCommits = ('numberOfCommits' in givenArguments) ? givenArguments.numberOfCommits : 3 + let accumulator = 0 + let mostRecentCommits = '' + for (let line of gitDiff.split('\n')) { + if (line.trim() === '') { + continue + } + if (line.startsWith('commit ')) { + mostRecentCommits += `\n` + accumulator++ + } + if (accumulator < numberOfCommits + 1) { + mostRecentCommits += `${line}\n` + } + } + mostRecentCommits = mostRecentCommits.trim() + // #endregion + givenArguments.message = mostRecentCommits + } else { + // message is in given arguments (a file was passed that needs to be read) + givenArguments.message = await readFile(givenArguments.message) + } + const commitMessage = `**Release ${versionNumber}** + + ${givenArguments.message} + + ... + + **Full Changelog**: https://github.com/MarmadileManteater/FreeTubeCordova/compare/${latestTag}...${versionNumber}` + // #region Commit changes to release branch + if (!givenArguments.dryRun) { + const fileId = randomUUID() + await writeFile(`commit_message_${fileId}.txt`, commitMessage) + await exec('git pull') + await exec('git checkout release') + await exec('git merge origin/development --no-commit --no-ff') + await exec(`git commit -F commit_message_${fileId}.txt`) + await rm(`commit_message_${fileId}.txt`) + } else { + // is a dry run + console.log(commitMessage) + console.log('------') + console.log('nothing committed: dry run') + } + // #endregion + +})(promisify(get), promisify(exec)) + diff --git a/_scripts/sigFrameConfig.js b/_scripts/sigFrameConfig.js new file mode 100644 index 0000000..c244fb2 --- /dev/null +++ b/_scripts/sigFrameConfig.js @@ -0,0 +1,13 @@ +const { hash } = require('crypto') +const { join } = require('path') +const { readFileSync } = require('fs') + +const path = join(__dirname, '../src/renderer/sigFrameScript.js') +const rawScript = readFileSync(path, 'utf8') + +const script = rawScript.split(/\r?\n/).map(line => line.trim()).filter(line => !line.startsWith('//')).join('') + +module.exports.sigFrameTemplateParameters = { + sigFrameSrc: `data:text/html,${encodeURIComponent(``)}`, + sigFrameCspHash: `sha512-${hash('sha512', script, 'base64')}` +} diff --git a/_scripts/sigViewConfig.js b/_scripts/sigViewConfig.js new file mode 100644 index 0000000..2669933 --- /dev/null +++ b/_scripts/sigViewConfig.js @@ -0,0 +1,15 @@ +const { hash } = require('crypto') +const { join } = require('path') +const { readFileSync } = require('fs') + +const path = join(__dirname, '../src/renderer/sigViewScript.js') +const rawScript = readFileSync(path, 'utf8') + +const script = process.env.NODE_ENV === 'development' + ? rawScript + : require('terser').minify_sync({ [path]: rawScript }).code + +module.exports.sigViewTemplateParameters = { + sigViewRaw: ``, + sigViewCspHash: `sha512-${hash('sha512', script, 'base64')}` +} diff --git a/_scripts/webpack.android.config.js b/_scripts/webpack.android.config.js new file mode 100644 index 0000000..cb6ac9c --- /dev/null +++ b/_scripts/webpack.android.config.js @@ -0,0 +1,236 @@ +const path = require('path') +const fs = require('fs') +const webpack = require('webpack') +const HtmlWebpackPlugin = require('html-webpack-plugin') +const VueLoaderPlugin = require('vue-loader/lib/plugin') +const CopyWebpackPlugin = require('copy-webpack-plugin') +const MiniCssExtractPlugin = require('mini-css-extract-plugin') +const JsonMinimizerPlugin = require('json-minimizer-webpack-plugin') +const CssMinimizerPlugin = require('css-minimizer-webpack-plugin') +const ProcessLocalesPlugin = require('./ProcessLocalesPlugin') +const { + SHAKA_LOCALE_MAPPINGS, + SHAKA_LOCALES_PREBUNDLED, + SHAKA_LOCALES_TO_BE_BUNDLED +} = require('./getShakaLocales') +const { sigViewTemplateParameters } = require('./sigViewConfig') + +const isDevMode = process.env.NODE_ENV === 'development' + +const { version: swiperVersion } = JSON.parse(fs.readFileSync(path.join(__dirname, '../node_modules/swiper/package.json'))) + +const config = { + name: 'web', + mode: process.env.NODE_ENV, + devtool: isDevMode ? 'eval-cheap-module-source-map' : false, + entry: { + web: path.join(__dirname, '../src/renderer/main.js'), + }, + output: { + path: path.join(__dirname, '../android/app/src/main/assets'), + filename: '[name].js', + }, + externals: { + android: 'Android' + }, + module: { + rules: [ + { + test: /\.js$/, + use: 'babel-loader', + exclude: /node_modules/, + }, + { + test: /\.vue$/, + loader: 'vue-loader', + options: { + compilerOptions: { + whitespace: 'condense', + } + } + }, + { + test: /\.scss$/, + use: [ + { + loader: MiniCssExtractPlugin.loader, + }, + { + loader: 'css-loader', + options: { + esModule: false + } + }, + { + loader: 'sass-loader', + options: { + implementation: require('sass') + } + }, + ], + }, + { + test: /\.css$/, + use: [ + { + loader: MiniCssExtractPlugin.loader + }, + { + loader: 'css-loader', + options: { + esModule: false + } + } + ], + }, + { + test: /\.html$/, + use: 'vue-html-loader', + }, + { + test: /\.(png|jpe?g|gif|tif?f|bmp|webp|svg)(\?.*)?$/, + type: 'asset/resource', + generator: { + filename: 'imgs/[name][ext]' + } + }, + { + test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, + type: 'asset/resource', + generator: { + filename: 'fonts/[name][ext]' + } + }, + ], + }, + // webpack defaults to only optimising the production builds, so having this here is fine + optimization: { + minimizer: [ + '...', // extend webpack's list instead of overwriting it + new JsonMinimizerPlugin({ + exclude: /\/locales\/.*\.json/ + }), + new CssMinimizerPlugin() + ] + }, + node: { + __dirname: true, + __filename: isDevMode, + }, + plugins: [ + new webpack.DefinePlugin({ + 'process.env.IS_ELECTRON': false, + 'process.env.IS_ELECTRON_MAIN': false, + 'process.env.IS_ANDROID': true, + 'process.env.IS_RELEASE': !isDevMode, + 'process.env.SUPPORTS_LOCAL_API': true, + 'process.env.SWIPER_VERSION': `'${swiperVersion}'`, + // video.js' vhs-utils supports both atob() in web browsers and Buffer in node + // As the FreeTube web build only runs in web browsers, we can override their check for atob() here: https://github.com/videojs/vhs-utils/blob/main/src/decode-b64-to-uint8-array.js#L3 + // overriding that check means we don't need to include a Buffer polyfill + // https://caniuse.com/atob-btoa + + // NOTE FOR THE FUTURE: this override won't work with vite as their define does a find and replace in the code for production builds, + // but uses globals in development builds to save build time, so this would replace the actual atob() function with true if used with vite + // this works in webpack as webpack does a find and replace in the source code for both development and production builds + // https://vitejs.dev/config/shared-options.html#define + // https://webpack.js.org/plugins/define-plugin/ + 'window.atob': true + }), + new webpack.ProvidePlugin({ + process: 'process/browser.js' + }), + new HtmlWebpackPlugin({ + excludeChunks: ['processTaskWorker'], + filename: 'index.html', + template: path.resolve(__dirname, '../src/index.ejs'), + nodeModules: false, + }), + new HtmlWebpackPlugin({ + filename: "decipher.html", + inject: false, + templateContent: sigViewTemplateParameters.sigViewRaw, + nodeModules: false + }), + new VueLoaderPlugin(), + new MiniCssExtractPlugin({ + filename: isDevMode ? '[name].css' : '[name].[contenthash].css', + chunkFilename: isDevMode ? '[id].css' : '[id].[contenthash].css', + }), + new CopyWebpackPlugin({ + patterns: [ + { + from: path.join(__dirname, '../node_modules/swiper/modules/{a11y,navigation,pagination}-element.css').replaceAll('\\', '/'), + to: `swiper-${swiperVersion}.css`, + context: path.join(__dirname, '../node_modules/swiper/modules'), + transformAll: (assets) => { + return Buffer.concat(assets.map(asset => asset.data)) + } + } + ] + }) + ], + resolve: { + alias: { + vue$: 'vue/dist/vue.runtime.esm.js', + 'portal-vue$': 'portal-vue/dist/portal-vue.esm.js', + + DB_HANDLERS_ELECTRON_RENDERER_OR_WEB$: path.resolve(__dirname, '../src/datastores/handlers/web.js'), + + // change to "shaka-player.ui.debug.js" to get debug logs (update jsconfig to get updated types) + 'shaka-player$': 'shaka-player/dist/shaka-player.ui.js', + 'localforage': path.resolve(__dirname, '_localforage.js') + }, + fallback: { + 'fs/promises': path.resolve(__dirname, '_empty.js'), + path: require.resolve('path-browserify'), + }, + extensions: ['.js', '.vue'] + }, + target: 'web', +} + +const processLocalesPlugin = new ProcessLocalesPlugin({ + compress: false, + inputDir: path.join(__dirname, '../static/locales'), + outputDir: 'static/locales', +}) +const processAndroidLocales = new ProcessLocalesPlugin({ + compress: false, + inputDir: path.join(__dirname, '../static/locales-android'), + outputDir: 'static/locales-android', +}) +config.plugins.push( + processLocalesPlugin, + processAndroidLocales, + new webpack.DefinePlugin({ + 'process.env.LOCALE_NAMES': JSON.stringify(processLocalesPlugin.localeNames), + 'process.env.GEOLOCATION_NAMES': JSON.stringify(fs.readdirSync(path.join(__dirname, '..', 'static', 'geolocations')).map(filename => filename.replace('.json', ''))), + 'process.env.SHAKA_LOCALE_MAPPINGS': JSON.stringify(SHAKA_LOCALE_MAPPINGS), + 'process.env.SHAKA_LOCALES_PREBUNDLED': JSON.stringify(SHAKA_LOCALES_PREBUNDLED) + }), + new CopyWebpackPlugin({ + patterns: [ + { + from: path.join(__dirname, '../static/pwabuilder-sw.js'), + to: path.join(__dirname, '../android/app/src/main/assets/pwabuilder-sw.js'), + }, + { + from: path.join(__dirname, '../static'), + to: path.join(__dirname, '../android/app/src/main/assets/static'), + globOptions: { + dot: true, + ignore: ['**/.*', '**/locales/**', '**/locales-android/**', '**/pwabuilder-sw.js', '**/dashFiles/**', '**/storyboards/**'], + }, + }, + { + from: path.join(__dirname, '../node_modules/shaka-player/ui/locales', `{${SHAKA_LOCALES_TO_BE_BUNDLED.join(',')}}.json`).replaceAll('\\', '/'), + to: path.join(__dirname, '../android/app/src/main/assets/static/shaka-player-locales'), + context: path.join(__dirname, '../node_modules/shaka-player/ui/locales') + } + ] + }) +) + + +module.exports = config diff --git a/_scripts/webpack.botGuardScript.android.config.js b/_scripts/webpack.botGuardScript.android.config.js new file mode 100644 index 0000000..d37a543 --- /dev/null +++ b/_scripts/webpack.botGuardScript.android.config.js @@ -0,0 +1,6 @@ +const config = require('./webpack.botGuardScript.config.js') +const { join } = require('path') + +config.output.path = join(__dirname, '../android/app/src/main/assets/') + +module.exports = config diff --git a/_scripts/webpack.botGuardScript.config.js b/_scripts/webpack.botGuardScript.config.js new file mode 100644 index 0000000..9b66ffc --- /dev/null +++ b/_scripts/webpack.botGuardScript.config.js @@ -0,0 +1,23 @@ +const path = require('path') + +/** @type {import('webpack').Configuration} */ +module.exports = { + name: 'botGuardScript', + // Always use production mode, as we use the output as a function body and the debug output doesn't work for that + mode: 'production', + devtool: false, + target: 'web', + entry: { + botGuardScript: path.join(__dirname, '../src/botGuardScript.js'), + }, + output: { + filename: '[name].js', + path: path.join(__dirname, '../dist'), + library: { + type: 'modern-module' + } + }, + experiments: { + outputModule: true + } +} diff --git a/_scripts/webpack.main.config.js b/_scripts/webpack.main.config.js new file mode 100644 index 0000000..c82358e --- /dev/null +++ b/_scripts/webpack.main.config.js @@ -0,0 +1,72 @@ +const path = require('path') +const webpack = require('webpack') +const CopyWebpackPlugin = require('copy-webpack-plugin') +const JsonMinimizerPlugin = require('json-minimizer-webpack-plugin') + +const isDevMode = process.env.NODE_ENV === 'development' + +const config = { + name: 'main', + mode: process.env.NODE_ENV, + devtool: isDevMode ? 'eval-cheap-module-source-map' : false, + entry: { + main: path.join(__dirname, '../src/main/index.js'), + }, + module: { + rules: [ + { + test: /\.js$/, + use: 'babel-loader', + exclude: /node_modules/, + }, + { + resource: path.resolve(__dirname, '../node_modules/mime-db/db.json'), + use: path.join(__dirname, 'mime-db-shrinking-loader.js') + } + ], + }, + // webpack defaults to only optimising the production builds, so having this here is fine + optimization: { + minimizer: [ + '...', // extend webpack's list instead of overwriting it + new JsonMinimizerPlugin({ + exclude: /\/locales\/.*\.json/ + }) + ] + }, + node: { + __dirname: isDevMode, + __filename: isDevMode + }, + plugins: [ + new webpack.DefinePlugin({ + 'process.env.IS_ELECTRON_MAIN': true + }) + ], + output: { + filename: '[name].js', + libraryTarget: 'commonjs2', + path: path.join(__dirname, '../dist'), + publicPath: '' + }, + target: 'electron-main', +} + +if (!isDevMode) { + config.plugins.push( + new CopyWebpackPlugin({ + patterns: [ + { + from: path.join(__dirname, '../static'), + to: path.join(__dirname, '../dist/static'), + globOptions: { + dot: true, + ignore: ['**/.*', '**/locales/**', '**/pwabuilder-sw.js', '**/manifest.json', '**/dashFiles/**', '**/storyboards/**'], + }, + }, + ] + }) + ) +} + +module.exports = config diff --git a/_scripts/webpack.renderer.config.js b/_scripts/webpack.renderer.config.js new file mode 100644 index 0000000..f3e8c8e --- /dev/null +++ b/_scripts/webpack.renderer.config.js @@ -0,0 +1,197 @@ +const path = require('path') +const { readFileSync, readdirSync } = require('fs') +const webpack = require('webpack') +const HtmlWebpackPlugin = require('html-webpack-plugin') +const VueLoaderPlugin = require('vue-loader/lib/plugin') +const MiniCssExtractPlugin = require('mini-css-extract-plugin') +const CssMinimizerPlugin = require('css-minimizer-webpack-plugin') +const ProcessLocalesPlugin = require('./ProcessLocalesPlugin') +const CopyWebpackPlugin = require('copy-webpack-plugin') +const { + SHAKA_LOCALE_MAPPINGS, + SHAKA_LOCALES_PREBUNDLED, + SHAKA_LOCALES_TO_BE_BUNDLED +} = require('./getShakaLocales') +const { sigFrameTemplateParameters } = require('./sigFrameConfig') + +const isDevMode = process.env.NODE_ENV === 'development' + +const { version: swiperVersion } = JSON.parse(readFileSync(path.join(__dirname, '../node_modules/swiper/package.json'))) + +const processLocalesPlugin = new ProcessLocalesPlugin({ + compress: !isDevMode, + hotReload: isDevMode, + inputDir: path.join(__dirname, '../static/locales'), + outputDir: 'static/locales', +}) + +const config = { + name: 'renderer', + mode: process.env.NODE_ENV, + devtool: isDevMode ? 'eval-cheap-module-source-map' : false, + entry: { + renderer: path.join(__dirname, '../src/renderer/main.js'), + }, + infrastructureLogging: { + // Only warnings and errors + // level: 'none' disable logging + // Please read https://webpack.js.org/configuration/other-options/#infrastructurelogginglevel + level: isDevMode ? 'info' : 'none' + }, + output: { + libraryTarget: 'commonjs2', + path: path.join(__dirname, '../dist'), + filename: '[name].js', + }, + module: { + rules: [ + { + test: /\.js$/, + use: 'babel-loader', + exclude: /node_modules/, + }, + { + test: /\.vue$/, + loader: 'vue-loader', + options: { + compilerOptions: { + whitespace: 'condense', + } + } + }, + { + test: /\.scss$/, + use: [ + { + loader: MiniCssExtractPlugin.loader, + }, + { + loader: 'css-loader', + options: { + esModule: false + } + }, + { + loader: 'sass-loader', + options: { + implementation: require('sass') + } + }, + ], + }, + { + test: /\.css$/, + use: [ + { + loader: MiniCssExtractPlugin.loader + }, + { + loader: 'css-loader', + options: { + esModule: false + } + } + ], + }, + { + test: /\.(png|jpe?g|gif|tif?f|bmp|webp|svg)(\?.*)?$/, + type: 'asset/resource', + generator: { + filename: 'imgs/[name][ext]' + } + }, + { + test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, + type: 'asset/resource', + generator: { + filename: 'fonts/[name][ext]' + } + }, + ], + }, + // webpack defaults to only optimising the production builds, so having this here is fine + optimization: { + minimizer: [ + '...', // extend webpack's list instead of overwriting it + new CssMinimizerPlugin() + ] + }, + node: { + __dirname: false, + __filename: false + }, + plugins: [ + processLocalesPlugin, + new webpack.DefinePlugin({ + 'process.env.IS_ELECTRON': true, + 'process.env.IS_ELECTRON_MAIN': false, + 'process.env.SUPPORTS_LOCAL_API': true, + 'process.env.LOCALE_NAMES': JSON.stringify(processLocalesPlugin.localeNames), + 'process.env.GEOLOCATION_NAMES': JSON.stringify(readdirSync(path.join(__dirname, '..', 'static', 'geolocations')).map(filename => filename.replace('.json', ''))), + 'process.env.SWIPER_VERSION': `'${swiperVersion}'`, + 'process.env.SHAKA_LOCALE_MAPPINGS': JSON.stringify(SHAKA_LOCALE_MAPPINGS), + 'process.env.SHAKA_LOCALES_PREBUNDLED': JSON.stringify(SHAKA_LOCALES_PREBUNDLED) + }), + new HtmlWebpackPlugin({ + filename: 'index.html', + template: path.resolve(__dirname, '../src/index.ejs'), + templateParameters: sigFrameTemplateParameters + }), + new VueLoaderPlugin(), + new MiniCssExtractPlugin({ + filename: isDevMode ? '[name].css' : '[name].[contenthash].css', + chunkFilename: isDevMode ? '[id].css' : '[id].[contenthash].css', + }), + new CopyWebpackPlugin({ + patterns: [ + { + from: path.join(__dirname, '../node_modules/swiper/modules/{a11y,navigation,pagination}-element.css').replaceAll('\\', '/'), + to: `swiper-${swiperVersion}.css`, + context: path.join(__dirname, '../node_modules/swiper/modules'), + transformAll: (assets) => { + return Buffer.concat(assets.map(asset => asset.data)) + } + }, + // Don't need to copy them in dev mode, + // as we configure WebpackDevServer to serve them + ...(isDevMode + ? [] + : [ + { + from: path.join(__dirname, '../node_modules/shaka-player/ui/locales', `{${SHAKA_LOCALES_TO_BE_BUNDLED.join(',')}}.json`).replaceAll('\\', '/'), + to: path.join(__dirname, '../dist/static/shaka-player-locales'), + context: path.join(__dirname, '../node_modules/shaka-player/ui/locales'), + transform: { + transformer: (input) => { + return JSON.stringify(JSON.parse(input.toString('utf-8'))) + } + } + } + ]) + ] + }) + ], + resolve: { + alias: { + vue$: 'vue/dist/vue.runtime.esm.js', + 'portal-vue$': 'portal-vue/dist/portal-vue.esm.js', + + DB_HANDLERS_ELECTRON_RENDERER_OR_WEB$: path.resolve(__dirname, '../src/datastores/handlers/electron.js'), + + 'youtubei.js$': 'youtubei.js/web', + + // change to "shaka-player.ui.debug.js" to get debug logs (update jsconfig to get updated types) + 'shaka-player$': 'shaka-player/dist/shaka-player.ui.js', + }, + extensions: ['.js', '.vue'] + }, + target: 'electron-renderer', +} + +if (isDevMode) { + // hack to pass it through to the dev-runner.js script + // gets removed there before the config object is passed to webpack + config.SHAKA_LOCALES_TO_BE_BUNDLED = SHAKA_LOCALES_TO_BE_BUNDLED +} + +module.exports = config diff --git a/_scripts/webpack.web.config.js b/_scripts/webpack.web.config.js new file mode 100644 index 0000000..85dcc9f --- /dev/null +++ b/_scripts/webpack.web.config.js @@ -0,0 +1,220 @@ +const path = require('path') +const fs = require('fs') +const webpack = require('webpack') +const HtmlWebpackPlugin = require('html-webpack-plugin') +const VueLoaderPlugin = require('vue-loader/lib/plugin') +const CopyWebpackPlugin = require('copy-webpack-plugin') +const MiniCssExtractPlugin = require('mini-css-extract-plugin') +const JsonMinimizerPlugin = require('json-minimizer-webpack-plugin') +const CssMinimizerPlugin = require('css-minimizer-webpack-plugin') +const ProcessLocalesPlugin = require('./ProcessLocalesPlugin') +const { + SHAKA_LOCALE_MAPPINGS, + SHAKA_LOCALES_PREBUNDLED, + SHAKA_LOCALES_TO_BE_BUNDLED +} = require('./getShakaLocales') + +const isDevMode = process.env.NODE_ENV === 'development' + +const { version: swiperVersion } = JSON.parse(fs.readFileSync(path.join(__dirname, '../node_modules/swiper/package.json'))) + +const config = { + name: 'web', + mode: process.env.NODE_ENV, + devtool: isDevMode ? 'eval-cheap-module-source-map' : false, + entry: { + web: path.join(__dirname, '../src/renderer/main.js'), + }, + output: { + path: path.join(__dirname, '../dist/web'), + filename: '[name].js', + }, + externals: { + android: '{}', + 'youtubei.js': '{}' + }, + module: { + rules: [ + { + test: /\.js$/, + use: 'babel-loader', + exclude: /node_modules/, + }, + { + test: /\.vue$/, + loader: 'vue-loader', + options: { + compilerOptions: { + whitespace: 'condense', + } + } + }, + { + test: /\.scss$/, + use: [ + { + loader: MiniCssExtractPlugin.loader, + }, + { + loader: 'css-loader', + options: { + esModule: false + } + }, + { + loader: 'sass-loader', + options: { + implementation: require('sass') + } + }, + ], + }, + { + test: /\.css$/, + use: [ + { + loader: MiniCssExtractPlugin.loader + }, + { + loader: 'css-loader', + options: { + esModule: false + } + } + ], + }, + { + test: /\.html$/, + use: 'vue-html-loader', + }, + { + test: /\.(png|jpe?g|gif|tif?f|bmp|webp|svg)(\?.*)?$/, + type: 'asset/resource', + generator: { + filename: 'imgs/[name][ext]' + } + }, + { + test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, + type: 'asset/resource', + generator: { + filename: 'fonts/[name][ext]' + } + }, + ], + }, + // webpack defaults to only optimising the production builds, so having this here is fine + optimization: { + minimizer: [ + '...', // extend webpack's list instead of overwriting it + new JsonMinimizerPlugin({ + exclude: /\/locales\/.*\.json/ + }), + new CssMinimizerPlugin() + ] + }, + node: { + __dirname: false, + __filename: false + }, + plugins: [ + new webpack.DefinePlugin({ + 'process.env.IS_ELECTRON': false, + 'process.env.IS_ELECTRON_MAIN': false, + 'process.env.SUPPORTS_LOCAL_API': false, + 'process.env.SWIPER_VERSION': `'${swiperVersion}'`, + 'process.env.IS_ANDROID': false, + 'process.env.IS_RELEASE': !isDevMode + }), + new webpack.ProvidePlugin({ + process: 'process/browser' + }), + new HtmlWebpackPlugin({ + excludeChunks: ['processTaskWorker'], + filename: 'index.html', + template: path.resolve(__dirname, '../src/index.ejs') + }), + new VueLoaderPlugin(), + new MiniCssExtractPlugin({ + filename: isDevMode ? '[name].css' : '[name].[contenthash].css', + chunkFilename: isDevMode ? '[id].css' : '[id].[contenthash].css', + }), + new CopyWebpackPlugin({ + patterns: [ + { + from: path.join(__dirname, '../node_modules/swiper/modules/{a11y,navigation,pagination}-element.css').replaceAll('\\', '/'), + to: `swiper-${swiperVersion}.css`, + context: path.join(__dirname, '../node_modules/swiper/modules'), + transformAll: (assets) => { + return Buffer.concat(assets.map(asset => asset.data)) + } + } + ] + }) + ], + resolve: { + alias: { + vue$: 'vue/dist/vue.runtime.esm.js', + 'portal-vue$': 'portal-vue/dist/portal-vue.esm.js', + + DB_HANDLERS_ELECTRON_RENDERER_OR_WEB$: path.resolve(__dirname, '../src/datastores/handlers/web.js'), + + // change to "shaka-player.ui.debug.js" to get debug logs (update jsconfig to get updated types) + 'shaka-player$': 'shaka-player/dist/shaka-player.ui.js', + }, + fallback: { + 'fs/promises': path.resolve(__dirname, '_empty.js'), + path: require.resolve('path-browserify'), + }, + extensions: ['.js', '.vue'] + }, + target: 'web', +} + +const processLocalesPlugin = new ProcessLocalesPlugin({ + compress: false, + hotReload: isDevMode, + inputDir: path.join(__dirname, '../static/locales'), + outputDir: 'static/locales', +}) + +config.plugins.push( + processLocalesPlugin, + new webpack.DefinePlugin({ + 'process.env.LOCALE_NAMES': JSON.stringify(processLocalesPlugin.localeNames), + 'process.env.GEOLOCATION_NAMES': JSON.stringify(fs.readdirSync(path.join(__dirname, '..', 'static', 'geolocations')).map(filename => filename.replace('.json', ''))), + 'process.env.SHAKA_LOCALE_MAPPINGS': JSON.stringify(SHAKA_LOCALE_MAPPINGS), + 'process.env.SHAKA_LOCALES_PREBUNDLED': JSON.stringify(SHAKA_LOCALES_PREBUNDLED) + }), + new CopyWebpackPlugin({ + patterns: [ + { + from: path.join(__dirname, '../_icons/192x192.png'), + to: path.join(__dirname, '../dist/web/static/_icons/192x192.png'), + }, + { + from: path.join(__dirname, '../_icons/512x512.png'), + to: path.join(__dirname, '../dist/web/static/_icons/512x512.png'), + }, + { + from: path.join(__dirname, '../static/pwabuilder-sw.js'), + to: path.join(__dirname, '../dist/web/pwabuilder-sw.js'), + }, + { + from: path.join(__dirname, '../static'), + to: path.join(__dirname, '../dist/web/static'), + globOptions: { + dot: true, + ignore: ['**/.*', '**/locales/**', '**/pwabuilder-sw.js', '**/dashFiles/**', '**/storyboards/**'], + }, + }, + { + from: path.join(__dirname, '../node_modules/shaka-player/ui/locales', `{${SHAKA_LOCALES_TO_BE_BUNDLED.join(',')}}.json`).replaceAll('\\', '/'), + to: path.join(__dirname, '../dist/web/static/shaka-player-locales'), + context: path.join(__dirname, '../node_modules/shaka-player/ui/locales') + } + ] + }) +) + +module.exports = config diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..aa724b7 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,15 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties diff --git a/android/app/.gitignore b/android/app/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/android/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..e8d1a7c --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,100 @@ +import groovy.json.JsonSlurper + + +class VersionInfo { + val appId: String + val version: String + val versionCode: Int + constructor(givenId: String, givenVersion: String, givenCode: Int) { + appId = givenId + version = givenVersion + versionCode = givenCode + } +} + +fun getVersionInfo(project: Project): VersionInfo { + val json = JsonSlurper() + val packageJsonPath = project.file("../../package.json") + + val packageJson = json.parse(packageJsonPath) as Map + val versionName = packageJson["version"] as String + val appName = "io.freetubeapp." + packageJson["name"] + val parts = versionName.split("-") + val numbers = parts[0].split(".") + val major = numbers[0].toInt() + val minor = numbers[1].toInt() + val patch = numbers[2].toInt() + var build = 0 + if (parts.size > 2) { + println(parts) + build = parts[2].toInt() + } else if (numbers.size > 3) { + build = numbers[3].toInt() + } + + val versionCode = major * 10000000 + minor * 10000000 + patch * 1000 + build + + return VersionInfo(appName, versionName, versionCode) +} + +val versionInfo = getVersionInfo(project) + +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") +} + +android { + signingConfigs { + getByName("debug") { + // inject signing config + }; + } + namespace = "io.freetubeapp.freetube" + compileSdk = 34 + dataBinding { + enable = true + } + defaultConfig { + applicationId = versionInfo.appId + minSdk = 24 + targetSdk = 34 + versionCode = versionInfo.versionCode + versionName = versionInfo.version + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + + } + + buildTypes { + release { + isMinifyEnabled = true + isShrinkResources = true + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + // in this case debug is just a name of a signing config + // the release workflow injects the release keystore info into the "debug" signing config + // i tried to add a signing config called "release", but i got build errors :( + signingConfig = signingConfigs.getByName("debug") + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + } + kotlinOptions { + jvmTarget = "1.8" + } + buildFeatures { + viewBinding = true + } +} + +dependencies { + + implementation("com.google.android.material:material:1.11.0") + implementation("androidx.media3:media3-ui:1.2.1") + +} diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 0000000..481bb43 --- /dev/null +++ b/android/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..30f74a5 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,106 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/java/io/freetubeapp/freetube/KeepAliveService.kt b/android/app/src/main/java/io/freetubeapp/freetube/KeepAliveService.kt new file mode 100644 index 0000000..f3e7e22 --- /dev/null +++ b/android/app/src/main/java/io/freetubeapp/freetube/KeepAliveService.kt @@ -0,0 +1,55 @@ +package io.freetubeapp.freetube + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.Service +import android.content.ComponentName +import android.content.Intent +import android.os.Build +import android.os.IBinder +import androidx.core.app.NotificationChannelCompat +import androidx.core.app.NotificationManagerCompat + + +class KeepAliveService : Service() { + companion object { + private val CHANNEL_ID = "keep_alive" + } + override fun onBind(intent: Intent?): IBinder? { + TODO("Not yet implemented") + } + override fun onCreate() { + super.onCreate() + val notificationManager = NotificationManagerCompat.from(applicationContext) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + val channel = NotificationChannel(CHANNEL_ID, "Keep Alive", NotificationManager.IMPORTANCE_MIN) + notificationManager.createNotificationChannel(channel) + } else { + val channel = NotificationChannelCompat.Builder(CHANNEL_ID, NotificationManager.IMPORTANCE_MIN).build() + notificationManager.createNotificationChannel(channel) + } + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + startForeground(1, + Notification.Builder(this.applicationContext, CHANNEL_ID) + .setContentTitle("FreeTube is running in the background.") + .setCategory(Notification.CATEGORY_SERVICE) + .setSmallIcon(R.drawable.ic_media_notification_icon) + .build()) + } else { + startForeground(1, + Notification.Builder(this.applicationContext) + .setContentTitle("FreeTube is running in the background.") + .setCategory(Notification.CATEGORY_SERVICE) + .build()) + } + } + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + super.onStartCommand(intent, flags, startId) + return START_STICKY + } + override fun startForegroundService(service: Intent?): ComponentName? { + return super.startForegroundService(service) + } +} diff --git a/android/app/src/main/java/io/freetubeapp/freetube/MainActivity.kt b/android/app/src/main/java/io/freetubeapp/freetube/MainActivity.kt new file mode 100644 index 0000000..3ba81ea --- /dev/null +++ b/android/app/src/main/java/io/freetubeapp/freetube/MainActivity.kt @@ -0,0 +1,453 @@ +package io.freetubeapp.freetube + +import android.annotation.SuppressLint +import android.app.Activity +import android.content.Intent +import android.content.res.Configuration +import android.graphics.Color +import android.os.Bundle +import android.view.View +import android.view.ViewGroup +import android.view.ViewTreeObserver +import android.webkit.ConsoleMessage +import android.webkit.WebChromeClient +import android.webkit.WebResourceRequest +import android.webkit.WebResourceResponse +import android.webkit.WebView +import android.webkit.WebViewClient +import android.widget.FrameLayout +import androidx.activity.addCallback +import androidx.activity.result.ActivityResult +import androidx.activity.result.ActivityResultLauncher +import androidx.activity.result.contract.ActivityResultContracts +import androidx.appcompat.app.AppCompatActivity +import androidx.core.app.ActivityCompat.OnRequestPermissionsResultCallback +import androidx.core.view.WindowCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.WindowInsetsControllerCompat +import io.freetubeapp.freetube.databinding.ActivityMainBinding +import io.freetubeapp.freetube.helpers.Promise +import io.freetubeapp.freetube.javascript.BotGuardJavascriptInterface +import io.freetubeapp.freetube.javascript.FreeTubeJavaScriptInterface +import io.freetubeapp.freetube.javascript.SigWebViewJavascriptInterface +import io.freetubeapp.freetube.javascript.dispatchEvent +import io.freetubeapp.freetube.webviews.BackgroundPlayWebView +import io.freetubeapp.freetube.webviews.BotGuardWebView +import io.freetubeapp.freetube.webviews.SigWebView +import org.json.JSONObject +import java.io.BufferedReader +import java.io.InputStreamReader +import java.net.HttpURLConnection +import java.net.URL +import java.net.URLEncoder +import java.util.UUID +import java.util.concurrent.BlockingQueue +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.ThreadPoolExecutor +import java.util.concurrent.TimeUnit + + +class MainActivity : AppCompatActivity() { + + // region Keep Alive service + private lateinit var keepAliveService: KeepAliveService + private lateinit var keepAliveIntent: Intent + // endregion + + // region JS interfaces + private lateinit var jsInterface: FreeTubeJavaScriptInterface + lateinit var sigJsInterface: SigWebViewJavascriptInterface + // endregion + + // region Bindings + private lateinit var binding: ActivityMainBinding + lateinit var webView: BackgroundPlayWebView + lateinit var sigWebView: SigWebView + lateinit var content: View + private var fullscreenView: View? = null + // endregion + + // region Callbacks + private lateinit var activityResultListeners: MutableList<(ActivityResult?) -> Unit> + private lateinit var activityResultLauncher: ActivityResultLauncher + // endregion + + // region State Information + var consoleMessages: MutableList = mutableListOf() + var showSplashScreen: Boolean = true + var darkMode: Boolean = false + var paused: Boolean = false + var isInAPrompt: Boolean = false + // endregion + + // region Thread Pool Executor + /* + * Gets the number of available cores + * (not always the same as the maximum number of cores) + */ + private val numberOfCores = Runtime.getRuntime().availableProcessors() + // Instantiates the queue of Runnables as a LinkedBlockingQueue + private val workQueue: BlockingQueue = LinkedBlockingQueue() + // Sets the amount of time an idle thread waits before terminating + private val keepAliveTime = 1 + // Sets the Time Unit to seconds + private val keepAliveTimeUnit: TimeUnit = TimeUnit.SECONDS + // Creates a thread pool manager + var threadPoolExecutor = ThreadPoolExecutor( + numberOfCores, // Initial pool size + numberOfCores, // Max pool size + keepAliveTime.toLong(), + keepAliveTimeUnit, + workQueue + ) + // endregion + + // region Overridden methods + + @SuppressLint("SetJavaScriptEnabled") + @Suppress("DEPRECATION") + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + when (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) { + Configuration.UI_MODE_NIGHT_NO -> { + darkMode = false + } + Configuration.UI_MODE_NIGHT_YES -> { + darkMode = true + } + } + + content = findViewById(android.R.id.content) + content.viewTreeObserver.addOnPreDrawListener( + object : ViewTreeObserver.OnPreDrawListener { + override fun onPreDraw(): Boolean { + // Check whether the initial data is ready. + return if (!showSplashScreen) { + // The content is ready. Start drawing. + content.viewTreeObserver.removeOnPreDrawListener(this) + true + } else { + // The content isn't ready. Suspend. + false + } + } + } + ) + + activityResultListeners = mutableListOf() + + activityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { + for (listener in activityResultListeners) { + listener(it) + } + // clear the listeners + activityResultListeners = mutableListOf() + } + + MediaControlsReceiver.notifyMediaSessionListeners = { + action -> + webView.dispatchEvent("media-$action") + } + + // this keeps android from shutting off the app to conserve battery + keepAliveService = KeepAliveService() + keepAliveIntent = Intent(this, keepAliveService.javaClass) + startService(keepAliveIntent) + + // this gets the controller for hiding and showing the system bars + WindowCompat.setDecorFitsSystemWindows(window, false) + val windowInsetsController = + WindowCompat.getInsetsController(window, window.decorView) + windowInsetsController.systemBarsBehavior = + WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE + + binding = ActivityMainBinding.inflate(layoutInflater) + setContentView(binding.root) + webView = binding.webView + webView.setBackgroundColor(Color.TRANSPARENT) + + // bind the back button to the web-view history + onBackPressedDispatcher.addCallback { + if (isInAPrompt) { + webView.dispatchEvent("exit-prompt") + jsInterface.exitPromptMode() + } else { + if (webView.canGoBack()) { + webView.goBack() + } else { + this@MainActivity.moveTaskToBack(true) + } + } + } + + webView.settings.javaScriptEnabled = true + + // this is the 🥃 special sauce that makes local api streaming a possibility + webView.settings.allowUniversalAccessFromFileURLs = true + webView.settings.allowFileAccessFromFileURLs = true + // allow playlist ▶auto-play in background + webView.settings.mediaPlaybackRequiresUserGesture = false + + jsInterface = FreeTubeJavaScriptInterface(this) + webView.addJavascriptInterface(jsInterface, "Android") + webView.webChromeClient = object: WebChromeClient() { + + override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean { + val messageData = JSONObject() + messageData.put("content", consoleMessage.message()) + messageData.put("level", consoleMessage.messageLevel()) + messageData.put("timestamp", System.currentTimeMillis()) + messageData.put("id", UUID.randomUUID()) + messageData.put("key", "${messageData["id"]}-${messageData["timestamp"]}") + messageData.put("sourceId", consoleMessage.sourceId()) + messageData.put("lineNumber", consoleMessage.lineNumber()) + consoleMessages.add(messageData) + webView.dispatchEvent("console-message", "data", messageData) + return super.onConsoleMessage(consoleMessage); + } + + override fun onShowCustomView(view: View?, callback: CustomViewCallback?) { + windowInsetsController.hide(WindowInsetsCompat.Type.systemBars()) + fullscreenView = view!! + view.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) + this@MainActivity.binding.root.addView(view) + webView.visibility = View.GONE + this@MainActivity.binding.root.fitsSystemWindows = false + webView.dispatchEvent("start-fullscreen") + } + + override fun onHideCustomView() { + webView.visibility = View.VISIBLE + this@MainActivity.binding.root.removeView(fullscreenView) + fullscreenView = null + windowInsetsController.show(WindowInsetsCompat.Type.systemBars()) + this@MainActivity.binding.root.fitsSystemWindows = true + webView.dispatchEvent("end-fullscreen") + } + } + webView.webViewClient = object: WebViewClient() { + + override fun shouldInterceptRequest( + view: WebView?, + request: WebResourceRequest? + ): WebResourceResponse? { + // TODO refactor this to work for video streaming + /* + // LEFTOVER iOS WORKAROUND CODE + if (request!!.requestHeaders.containsKey("x-user-agent")) { + with (URL(request!!.url.toString()).openConnection() as HttpURLConnection) { + requestMethod = request.method + val isClient5 = request.requestHeaders.containsKey("x-youtube-client-name") && request.requestHeaders["x-youtube-client-name"] == "5" + // map headers + for (header in request!!.requestHeaders) { + fun getReal(key: String, value: String): Array? { + if (key == "x-user-agent") { + return arrayOf("User-Agent", value) + } + if (key == "User-Agent") { + return null + } + if (key == "x-fta-request-id") { + return null + } + if (isClient5) { + if (key == "referrer") { + return null + } + if (key == "origin") { + return null + } + if (key == "Sec-Fetch-Site") { + return null + } + if (key == "Sec-Fetch-Mode") { + return null + } + if (key == "Sec-Fetch-Dest") { + return null + } + if (key == "sec-ch-ua") { + return null + } + if (key == "sec-ch-ua-mobile") { + return null + } + if (key == "sec-ch-ua-platform") { + return null + } + } + return arrayOf(key, value) + } + val real = getReal(header.key, header.value) + if (real !== null) { + setRequestProperty(real[0], real[1]) + } + } + if (request.requestHeaders.containsKey("x-fta-request-id")) { + if (pendingRequestBodies.containsKey(request.requestHeaders["x-fta-request-id"])) { + val body = pendingRequestBodies[request.requestHeaders["x-fta-request-id"]] + pendingRequestBodies.remove(request.requestHeaders["x-fta-request-id"]) + outputStream.write(body!!.toByteArray()) + } + } + // 🧝‍♀️ magic + return WebResourceResponse(this.contentType, this.contentEncoding, inputStream!!) + } + } + */ + return super.shouldInterceptRequest(view, request) + } + override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean { + if (request!!.url!!.scheme == "file") { + // don't send file url requests to a web browser (it will crash the app) + return true + } + val regex = """^https?:\/\/((www\.)?youtube\.com(\/embed)?|youtu\.be)\/.*$""" + + if (Regex(regex).containsMatchIn(request!!.url!!.toString())) { + webView.dispatchEvent("youtube-link", "link", request!!.url!!.toString()) + return true + } + // send all requests to a real web browser + val intent = Intent(Intent.ACTION_VIEW, request!!.url) + this@MainActivity.startActivity(intent) + return true + } + } + if (intent!!.data !== null) { + val url = intent!!.data.toString() + val host = intent!!.data!!.host.toString() + val intentPath = if (host != "youtube.com" && host != "youtu.be" && host != "m.youtube.com" && host != "www.youtube.com") { + url.replace("${intent!!.data!!.host}", "youtube.com") + } else { + url + } + val intentEncoded = URLEncoder.encode(intentPath) + webView.loadUrl("file:///android_asset/index.html?intent=${intentEncoded}") + } else { + webView.loadUrl("file:///android_asset/index.html") + } + + + sigWebView = binding.sigWebView + sigJsInterface = SigWebViewJavascriptInterface(sigWebView, jsInterface.jsCommunicator) + sigWebView.addJavascriptInterface(sigJsInterface, "Android") + sigWebView.settings.javaScriptEnabled = true + sigWebView.webChromeClient = object: WebChromeClient() { + + override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean { + val messageData = JSONObject() + messageData.put("content", consoleMessage.message()) + messageData.put("level", consoleMessage.messageLevel()) + messageData.put("timestamp", System.currentTimeMillis()) + messageData.put("id", UUID.randomUUID()) + messageData.put("key", "${messageData["id"]}-${messageData["timestamp"]}") + messageData.put("sourceId", consoleMessage.sourceId()) + messageData.put("lineNumber", consoleMessage.lineNumber()) + consoleMessages.add(messageData) + webView.dispatchEvent("console-message", "data", messageData) + return super.onConsoleMessage(consoleMessage) + } + } + sigWebView.loadUrl("file:///android_asset/decipher.html") + } + + override fun onConfigurationChanged(newConfig: Configuration) { + super.onConfigurationChanged(newConfig) + when (newConfig.uiMode and Configuration.UI_MODE_NIGHT_MASK) { + Configuration.UI_MODE_NIGHT_NO -> { + darkMode = false + webView.dispatchEvent("enabled-light-mode") + } + Configuration.UI_MODE_NIGHT_YES -> { + darkMode = true + webView.dispatchEvent("enabled-dark-mode") + } + } + } + + /** + * handles new intents which involve deep links (aka supported links) + */ + @SuppressLint("MissingSuperCall") + override fun onNewIntent(intent: Intent?) { + if (intent!!.data !== null) { + val uri = intent!!.data + val isYT = + uri!!.host!! == "www.youtube.com" || uri!!.host!! == "youtube.com" || uri!!.host!! == "m.youtube.com" || uri!!.host!! == "youtu.be" + val url = if (!isYT) { + uri.toString().replace(uri.host.toString(), "www.youtube.com") + } else { + uri + } + webView.dispatchEvent("youtube-link", "link", url.toString()) + } + } + + override fun onPause() { + super.onPause() + paused = true + webView.dispatchEvent("app-pause") + } + + override fun onResume() { + super.onResume() + paused = false + webView.dispatchEvent("app-resume") + } + + override fun onDestroy() { + // stop the keep alive service + stopService(keepAliveIntent) + // cancel media notification (if there is one) + jsInterface.cancelMediaNotification() + // clean up the web view + webView.destroy() + // call `super` + super.onDestroy() + } + + // endregion + + private fun listenForActivityResults(listener: (ActivityResult?) -> Unit) { + activityResultListeners.add(listener) + } + + fun launchIntent(intent: Intent): Promise { + return Promise(threadPoolExecutor, { + resolve, + reject -> + try { + listenForActivityResults { + resolve(it) + } + activityResultLauncher.launch(intent) + } catch (exception: Exception) { + reject(exception) + } + }) + } + + fun generateBgWebview(): BotGuardWebView { + val wv = BotGuardWebView(this) + wv.settings.javaScriptEnabled = true + wv.settings.allowUniversalAccessFromFileURLs = true + wv.webChromeClient = object: WebChromeClient() { + + override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean { + val messageData = JSONObject() + messageData.put("content", consoleMessage.message()) + messageData.put("level", consoleMessage.messageLevel()) + messageData.put("timestamp", System.currentTimeMillis()) + messageData.put("id", UUID.randomUUID()) + messageData.put("key", "${messageData["id"]}-${messageData["timestamp"]}") + messageData.put("sourceId", consoleMessage.sourceId()) + messageData.put("lineNumber", consoleMessage.lineNumber()) + consoleMessages.add(messageData) + webView.dispatchEvent("console-message", "data", messageData) + return super.onConsoleMessage(consoleMessage) + } + } + return wv + } +} diff --git a/android/app/src/main/java/io/freetubeapp/freetube/MediaControlsReceiver.kt b/android/app/src/main/java/io/freetubeapp/freetube/MediaControlsReceiver.kt new file mode 100644 index 0000000..66883de --- /dev/null +++ b/android/app/src/main/java/io/freetubeapp/freetube/MediaControlsReceiver.kt @@ -0,0 +1,20 @@ +package io.freetubeapp.freetube + +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent + +open class MediaControlsReceiver : BroadcastReceiver { + + constructor() { + } + companion object Static { + lateinit var notifyMediaSessionListeners: (String) -> Unit + } + + + override fun onReceive(context: Context?, intent: Intent?) { + val action = intent!!.action + notifyMediaSessionListeners(action!!) + } +} diff --git a/android/app/src/main/java/io/freetubeapp/freetube/helpers/AssetManagerExtensions.kt b/android/app/src/main/java/io/freetubeapp/freetube/helpers/AssetManagerExtensions.kt new file mode 100644 index 0000000..3803c22 --- /dev/null +++ b/android/app/src/main/java/io/freetubeapp/freetube/helpers/AssetManagerExtensions.kt @@ -0,0 +1,26 @@ +package io.freetubeapp.freetube.helpers + +import android.content.res.AssetManager +import java.io.BufferedReader +import java.io.InputStreamReader + +fun AssetManager.readText(assetName: String) : String { + val lines = mutableListOf() + val reader = BufferedReader(InputStreamReader(open(assetName))) + try { + var line = reader.readLine() + while(line != null) { + lines.add(line) + line = reader.readLine() + } + } catch (ex: Exception) { + // pass + } finally { + try { + reader.close() + } catch (ex: Exception) { + // pass + } + } + return lines.joinToString("\n") +} diff --git a/android/app/src/main/java/io/freetubeapp/freetube/helpers/ContentResolverExtensions.kt b/android/app/src/main/java/io/freetubeapp/freetube/helpers/ContentResolverExtensions.kt new file mode 100644 index 0000000..eb8aba8 --- /dev/null +++ b/android/app/src/main/java/io/freetubeapp/freetube/helpers/ContentResolverExtensions.kt @@ -0,0 +1,25 @@ +package io.freetubeapp.freetube.helpers + +import android.content.ContentResolver +import android.net.Uri + +fun ContentResolver.readBytes(uri: Uri): ByteArray { + val stream = openInputStream(uri) + val content = stream!!.readBytes() + stream.close() + return content +} + +fun ContentResolver.writeBytes(uri: Uri, bytes: ByteArray, writeMode: WriteMode = WriteMode.Truncate) { + val mode = if (writeMode == WriteMode.Truncate) { + "wt" + } else if (writeMode == WriteMode.Append) { + "wa" + } else { + "w" + } + val stream = openOutputStream(uri, mode) + stream!!.write(bytes) + stream.flush() + stream.close() +} diff --git a/android/app/src/main/java/io/freetubeapp/freetube/helpers/FileExtensions.kt b/android/app/src/main/java/io/freetubeapp/freetube/helpers/FileExtensions.kt new file mode 100644 index 0000000..e01d163 --- /dev/null +++ b/android/app/src/main/java/io/freetubeapp/freetube/helpers/FileExtensions.kt @@ -0,0 +1,25 @@ +package io.freetubeapp.freetube.helpers + +import java.io.File +import java.io.FileInputStream +import java.nio.charset.Charset + +enum class WriteMode { + Truncate, + Append +} + +fun File.readText(): String { + return FileInputStream(this).bufferedReader().use { it.readText() } +} + +fun File.writeText(content: String, writeMode: WriteMode = WriteMode.Truncate, createIfDoesntExist: Boolean = true) { + if (!this.exists() && createIfDoesntExist) { + createNewFile() + } + if (writeMode == WriteMode.Truncate) { + writeText(content, Charset.forName("utf-8")) + } else { + appendText(content, Charset.forName("utf-8")) + } +} diff --git a/android/app/src/main/java/io/freetubeapp/freetube/helpers/Promise.kt b/android/app/src/main/java/io/freetubeapp/freetube/helpers/Promise.kt new file mode 100644 index 0000000..c03c881 --- /dev/null +++ b/android/app/src/main/java/io/freetubeapp/freetube/helpers/Promise.kt @@ -0,0 +1,71 @@ +package io.freetubeapp.freetube.helpers + +import io.freetubeapp.freetube.javascript.AsyncJSCommunicator +import java.util.UUID.randomUUID +import java.util.concurrent.ThreadPoolExecutor + +class Promise { + private val successListeners: MutableList<(T) -> Unit> = mutableListOf() + private var successResult: T? = null + private val errorListeners: MutableList<(G) -> Unit> = mutableListOf() + private var errorResult: G? = null + private val id = "${randomUUID()}" + + constructor(executor: ThreadPoolExecutor, runnable: ((T) -> Unit, (G) -> Unit) -> Unit) { + executor.run { + runnable.invoke({ + result -> + notifySuccess(result) + }, { + result -> + notifyError(result) + }) + } + } + + fun addJsCommunicator(communicator: AsyncJSCommunicator) : String { + then { + communicator.resolve(id, "$it") + } + catch { + communicator.reject(id, "$it") + } + return id + } + + fun notifySuccess(result: T) { + successResult = result + successListeners.forEach { + listener -> + listener.invoke(result) + } + } + + fun notifyError(result: G) { + errorResult = result + errorListeners.forEach { + listener -> + listener.invoke(result) + } + } + + fun then(listener: (T) -> Unit): Promise { + if (successResult != null) { + // assume success result won't be unset + listener(successResult!!) + } else { + successListeners.add(listener) + } + return this + } + + fun catch(listener: (G) -> Unit): Promise { + if (errorResult != null) { + // assume success result won't be unset + listener(errorResult!!) + } else { + errorListeners.add(listener) + } + return this + } +} diff --git a/android/app/src/main/java/io/freetubeapp/freetube/helpers/StringExtensions.kt b/android/app/src/main/java/io/freetubeapp/freetube/helpers/StringExtensions.kt new file mode 100644 index 0000000..315a26c --- /dev/null +++ b/android/app/src/main/java/io/freetubeapp/freetube/helpers/StringExtensions.kt @@ -0,0 +1,24 @@ +package io.freetubeapp.freetube.helpers + +import android.graphics.Color + +fun String.hexToColour() : Int { + return if (length == 7) { + Color.rgb( + Integer.valueOf(substring(1, 3), 16), + Integer.valueOf(substring(3, 5), 16), + Integer.valueOf(substring(5, 7), 16) + ) + } else if (length == 4) { + val r = substring(1, 2) + val g = substring(2, 3) + val b = substring(3, 4) + Color.rgb( + Integer.valueOf("$r$r", 16), + Integer.valueOf("$g$g", 16), + Integer.valueOf("$b$b", 16) + ) + } else { + Color.TRANSPARENT + } +} diff --git a/android/app/src/main/java/io/freetubeapp/freetube/javascript/AsyncJSCommunicator.kt b/android/app/src/main/java/io/freetubeapp/freetube/javascript/AsyncJSCommunicator.kt new file mode 100644 index 0000000..75ac338 --- /dev/null +++ b/android/app/src/main/java/io/freetubeapp/freetube/javascript/AsyncJSCommunicator.kt @@ -0,0 +1,38 @@ +package io.freetubeapp.freetube.javascript + +import android.webkit.WebView +import java.util.UUID.randomUUID + +class AsyncJSCommunicator(givenWebView: WebView) { + private val webView = givenWebView + private var syncMessages: MutableMap = HashMap() + + /** + * @return the id of a promise on the window + */ + fun jsPromise(): String { + return "${randomUUID()}" + } + + /** + * resolves a js promise given the id + */ + fun resolve(id: String, message: String) { + syncMessages[id] = message + webView.dispatchEvent("$id-resolve") + } + + /** + * rejects a js promise given the id + */ + fun reject(id: String, message: String) { + syncMessages[id] = message + webView.dispatchEvent("$id-reject") + } + + fun getSyncMessage(promise: String): String { + val value = syncMessages[promise] + syncMessages.remove(promise) + return value!! + } +} diff --git a/android/app/src/main/java/io/freetubeapp/freetube/javascript/BotGuardJavascriptInterface.kt b/android/app/src/main/java/io/freetubeapp/freetube/javascript/BotGuardJavascriptInterface.kt new file mode 100644 index 0000000..fe87c1c --- /dev/null +++ b/android/app/src/main/java/io/freetubeapp/freetube/javascript/BotGuardJavascriptInterface.kt @@ -0,0 +1,36 @@ +package io.freetubeapp.freetube.javascript + +import android.webkit.JavascriptInterface +import io.freetubeapp.freetube.MainActivity + +class BotGuardJavascriptInterface(main: MainActivity) { + private var poToken: String? = null + private var tokenListeners: MutableList<(String) -> Unit> = mutableListOf() + val pendingRequestBodies: MutableMap = mutableMapOf() + + @JavascriptInterface + fun queueBody(id: String, body: String) { + pendingRequestBodies[id] = body + } + + @JavascriptInterface + fun returnToken(token: String) { + notify(token) + poToken = token + } + + fun notify(token: String) { + tokenListeners.forEach { + it(token) + } + tokenListeners = mutableListOf() + } + + fun onReturnToken(callback: (String) -> Unit) { + if (poToken != null) { + callback(poToken!!) + } else { + tokenListeners.add(callback) + } + } +} diff --git a/android/app/src/main/java/io/freetubeapp/freetube/javascript/FreeTubeJavaScriptInterface.kt b/android/app/src/main/java/io/freetubeapp/freetube/javascript/FreeTubeJavaScriptInterface.kt new file mode 100644 index 0000000..6f496ce --- /dev/null +++ b/android/app/src/main/java/io/freetubeapp/freetube/javascript/FreeTubeJavaScriptInterface.kt @@ -0,0 +1,770 @@ +package io.freetubeapp.freetube.javascript + +import android.annotation.SuppressLint +import android.app.Activity +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Intent +import android.graphics.BitmapFactory +import android.graphics.Color +import android.media.MediaMetadata +import android.media.session.MediaSession +import android.media.session.PlaybackState +import android.media.session.PlaybackState.STATE_PAUSED +import android.net.Uri +import android.os.Build +import android.provider.OpenableColumns +import android.view.WindowManager +import android.webkit.JavascriptInterface +import androidx.activity.result.ActivityResult +import android.webkit.WebView +import androidx.annotation.RequiresApi +import androidx.core.app.NotificationManagerCompat +import androidx.core.view.WindowCompat +import androidx.documentfile.provider.DocumentFile +import io.freetubeapp.freetube.MainActivity +import io.freetubeapp.freetube.MediaControlsReceiver +import io.freetubeapp.freetube.R +import io.freetubeapp.freetube.helpers.Promise +import io.freetubeapp.freetube.helpers.hexToColour +import io.freetubeapp.freetube.helpers.readBytes +import io.freetubeapp.freetube.helpers.readText +import io.freetubeapp.freetube.helpers.writeBytes +import io.freetubeapp.freetube.helpers.writeText +import io.freetubeapp.freetube.webviews.BotGuardWebView +import org.json.JSONObject +import java.io.File +import java.io.FileInputStream +import java.net.URL +import java.net.URLDecoder +import java.nio.charset.Charset +import java.util.UUID.* + + +class FreeTubeJavaScriptInterface { + private var context: MainActivity + private var mediaSession: MediaSession? + private var lastPosition: Long + private var lastState: Int + private var lastNotification: Notification? = null + private var keepScreenOn: Boolean = false + val jsCommunicator: AsyncJSCommunicator + + companion object { + private const val DATA_DIRECTORY = "data://" + private const val CHANNEL_ID = "media_controls" + private val NOTIFICATION_ID = (2..1000).random() + private val NOTIFICATION_TAG = String.format("%s", randomUUID()) + } + + constructor(main: MainActivity) { + context = main + mediaSession = null + lastPosition = 0 + lastState = PlaybackState.STATE_PLAYING + jsCommunicator = AsyncJSCommunicator(main.webView) + } + + // region Media Notifications + + /** + * retrieves actions for the media controls + * @param state the current state of the media controls (ex PlaybackState.STATE_PLAYING or PlaybackState.STATE_PAUSED + */ + private fun getActions(state: Int = lastState): Array { + var neutralAction = arrayOf("Pause", "pause") + var neutralIcon = androidx.media3.ui.R.drawable.exo_icon_pause + if (state == PlaybackState.STATE_PAUSED) { + neutralAction = arrayOf("Play", "play") + neutralIcon = androidx.media3.ui.R.drawable.exo_icon_play + } + return arrayOf( + Notification.Action.Builder( + androidx.media3.ui.R.drawable.exo_ic_skip_previous, + "Back", + PendingIntent.getBroadcast(context, 1, Intent(context, MediaControlsReceiver::class.java).setAction("previous"), PendingIntent.FLAG_IMMUTABLE) + ).build(), + Notification.Action.Builder( + neutralIcon, + neutralAction[0], + PendingIntent.getBroadcast(context, 1, Intent(context, MediaControlsReceiver::class.java).setAction(neutralAction[1]), PendingIntent.FLAG_IMMUTABLE) + ).build(), + Notification.Action.Builder( + androidx.media3.ui.R.drawable.exo_ic_skip_next, + "Next", + PendingIntent.getBroadcast(context, 1, Intent(context, MediaControlsReceiver::class.java).setAction("next"), PendingIntent.FLAG_IMMUTABLE) + ).build() + ) + } + + /** + * retrieves the media style for the media controls notification + */ + private fun getMediaStyle(): Notification.MediaStyle? { + if (mediaSession != null) { + return Notification.MediaStyle() + .setMediaSession(mediaSession!!.sessionToken).setShowActionsInCompactView(0, 1, 2) + } else { + return null + } + } + + /** + * Gets a fresh media controls notification given the current `mediaSession` + * @param actions a list of actions for the media controls (defaults to `getActions()`) + */ + @RequiresApi(Build.VERSION_CODES.O) + private fun getMediaControlsNotification(actions: Array = getActions()): Notification? { + val mediaStyle = getMediaStyle() + if (mediaStyle != null) { + // when clicking the notification, launch the app as if the user tapped on it in their launcher (open an existing instance if able) + val notificationIntent = Intent(Intent.ACTION_MAIN) + .addCategory(Intent.CATEGORY_LAUNCHER) + .setClass(context, MainActivity::class.java) + + // always reuse notification + if (lastNotification != null) { + lastNotification!!.actions = actions + return lastNotification + } + lastNotification = Notification.Builder(context, CHANNEL_ID) + .setStyle(getMediaStyle()) + .setSmallIcon(R.drawable.ic_media_notification_icon) + .addAction( + actions[0] + ) + .addAction( + actions[1] + ) + .addAction( + actions[2] + ) + .setContentIntent( + PendingIntent.getActivity( + context, 1, notificationIntent, + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE + ) + ) + .setDeleteIntent( + PendingIntent.getBroadcast(context, 1, Intent(context, MediaControlsReceiver::class.java).setAction("pause"), PendingIntent.FLAG_IMMUTABLE) + ) + .setVisibility(Notification.VISIBILITY_PUBLIC) + .build() + return lastNotification + } else { + return null + } + } + + /** + * pushes a notification + * @param notification the notification the be pushed (usually a media controls notification) + */ + @SuppressLint("MissingPermission") + private fun pushNotification(notification: Notification) { + if (lastNotification !== null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + // always set notifications to pause before sending another on android 13+ + setState(mediaSession!!, STATE_PAUSED) + } + val manager = NotificationManagerCompat.from(context) + manager.notify(NOTIFICATION_TAG, NOTIFICATION_ID, notification) + } + + /** + * sets the state of the media session + * @param session the current media session + * @param state the state of playback + * @param position the position in milliseconds of playback + */ + @SuppressLint("MissingPermission") + private fun setState(session: MediaSession, state: Int, position: Long? = null) { + + if (state != lastState) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { + // need to reissue a notification if we want to update the actions + var actions = getActions(state) + val notification = getMediaControlsNotification(actions) + pushNotification(notification!!) + } + } + lastState = state + var statePosition: Long + if (position == null) { + statePosition = lastPosition + } else { + statePosition = position + } + session.setPlaybackState( + PlaybackState.Builder() + .setState(state, statePosition, 0.0f) + .setActions(PlaybackState.ACTION_PLAY_PAUSE or PlaybackState.ACTION_PAUSE or PlaybackState.ACTION_SKIP_TO_NEXT or PlaybackState.ACTION_SKIP_TO_PREVIOUS or + PlaybackState.ACTION_PLAY_FROM_MEDIA_ID or + PlaybackState.ACTION_PLAY_FROM_SEARCH or PlaybackState.ACTION_SEEK_TO) + .build() + ) + } + + /** + * sets the metadata of the media session + * @param session the current media session + * @param trackName the video name + * @param artist the channel name + * @param duration duration in milliseconds + */ + @SuppressLint("MissingPermission") + @RequiresApi(Build.VERSION_CODES.O) + private fun setMetadata(session: MediaSession, trackName: String, artist: String, duration: Long, art: String?, pushNotification: Boolean = true) { + var notification: Notification? = null + if (pushNotification) { + notification = getMediaControlsNotification() + } + + if (art != null) { + // todo move this to a function and add try catch + val connection = URL(art).openConnection() + connection.connect() + val input = connection.getInputStream() + val bitmapArt = BitmapFactory.decodeStream(input) + // todo + session.setMetadata( + MediaMetadata.Builder() + .putString(MediaMetadata.METADATA_KEY_TITLE, trackName) + .putString(MediaMetadata.METADATA_KEY_ARTIST, artist) + .putBitmap(MediaMetadata.METADATA_KEY_ART, bitmapArt) + .putBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART, bitmapArt) + .putLong(MediaMetadata.METADATA_KEY_DURATION, duration) + .build() + ) + } else { + session.setMetadata( + MediaMetadata.Builder() + .putString(MediaMetadata.METADATA_KEY_TITLE, trackName) + .putString(MediaMetadata.METADATA_KEY_ARTIST, artist) + .putLong(MediaMetadata.METADATA_KEY_DURATION, duration) + .build() + ) + } + if (pushNotification && notification != null) { + pushNotification(notification) + } + } + + /** + * creates (or updates) a media session + * @param title the track name / video title + * @param artist the author / channel name + * @param duration the duration in milliseconds of the video + * @param thumbnail a URL to the thumbnail for the video + */ + @SuppressLint("MissingPermission") + @RequiresApi(Build.VERSION_CODES.O) + @JavascriptInterface + fun createMediaSession(title: String, artist: String, duration: Long = 0, thumbnail: String? = null) { + val notificationManager = NotificationManagerCompat.from(context) + val channel = notificationManager.getNotificationChannel(CHANNEL_ID, "Media Controls") + ?: NotificationChannel(CHANNEL_ID, "Media Controls", NotificationManager.IMPORTANCE_MIN) + + channel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE + var session: MediaSession + + // don't create multiple sessions or multiple channels + if (mediaSession == null) { + notificationManager.createNotificationChannel(channel) + // add the callbacks && listeners + + session = MediaSession(context, CHANNEL_ID) + session.isActive = true + mediaSession = session + session.setCallback(object : MediaSession.Callback() { + override fun onSkipToNext() { + super.onSkipToNext() + context.webView.dispatchEvent("media-next") + } + + override fun onSkipToPrevious() { + super.onSkipToPrevious() + context.webView.dispatchEvent("media-previous") + } + + override fun onSeekTo(pos: Long) { + super.onSeekTo(pos) + context.webView.dispatchEvent("media-seek", "position", pos) + } + + override fun onPlay() { + super.onPlay() + context.webView.dispatchEvent("media-play") + } + + override fun onPause() { + super.onPause() + context.webView.dispatchEvent("media-pause") + } + + }) + } else { + session = mediaSession!! + } + + val notification = getMediaControlsNotification() + // use the set metadata function without pushing a notification + setMetadata(session, title, artist, duration, thumbnail, false) + setState(session, PlaybackState.STATE_PLAYING) + + pushNotification(notification!!) + } + + /** + * updates the state of the active media session + * @param state the state; should be an Int (as a string because the java bridge) + * @param position the position; should be a Long (as a string because the java bridge) + */ + @JavascriptInterface + fun updateMediaSessionState(state: String?, position: String? = null) { + var givenState = state?.toInt() + if (state == null) { + givenState = lastState + } else { + } + if (position != null) { + lastPosition = position.toLong()!! + } + setState(mediaSession!!, givenState!!, position?.toLong()) + } + + /** + * updates the metadata of the active media session + * @param trackName the video title + * @param artist the channel name + * @param duration the length of the video in milliseconds + * @param art the URL to the video thumbnail + */ + @SuppressLint("NewApi") + @JavascriptInterface + fun updateMediaSessionData(trackName: String, artist: String, duration: Long, art: String? = null) { + setMetadata(mediaSession!!, trackName, artist, duration, art) + } + + /** + * cancels the active media notification + */ + @JavascriptInterface + fun cancelMediaNotification() { + val manager = NotificationManagerCompat.from(context) + manager.cancelAll() + } + + // endregion + + // region File Helpers + + /** + * @param directory a shortened directory uri + * @return a full directory uri + */ + @JavascriptInterface + fun getDirectory(directory: String): String { + val path = if (directory == DATA_DIRECTORY) { + // this is the directory cordova gave us access to before + context.getExternalFilesDir(null)!!.parent + } else { + directory + } + return path + } + + @JavascriptInterface + fun getFileNameFromUri(uri: String): String { + var result: String? = null + val cursor = context.contentResolver.query(Uri.parse(uri), null, null, null, null) + try { + if (cursor != null && cursor.moveToFirst()) { + val index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME) + if (index != -1) { + result = cursor.getString(index) + } + } + } finally { + cursor!!.close() + } + + if (result == null) { + result = uri.split(Regex("(/)|(%2F)")).last() + } + + return result + } + + @JavascriptInterface + fun revokePermissionForTree(treeUri: String) { + context.revokeUriPermission(Uri.parse(treeUri), Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION) + } + + @JavascriptInterface + fun listFilesInTree(tree: String): String { + val directory = DocumentFile.fromTreeUri(context, Uri.parse(tree)) + val files = directory!!.listFiles().joinToString(",") { file -> + "{ \"uri\": \"${file.uri}\", \"fileName\": \"${file.name}\", \"isFile\": ${file.isFile}, \"isDirectory\": ${file.isDirectory} }" + } + return "[$files]" + } + + @JavascriptInterface + fun createFileInTree(tree: String, fileName: String): String { + val directory = DocumentFile.fromTreeUri(context, Uri.parse(tree)) + return directory!!.createFile("*/*", fileName)!!.uri.toString() + } + + @JavascriptInterface + fun createDirectoryInTree(tree: String, fileName: String): String { + val directory = DocumentFile.fromTreeUri(context, Uri.parse(tree)) + return directory!!.createDirectory(fileName)!!.uri.toString() + } + + @JavascriptInterface + fun deleteFileInTree(fileUri: String): Boolean { + val file = DocumentFile.fromTreeUri(context, Uri.parse(fileUri)) + return file!!.delete() + } + + // endregion + + // region IO + /** + * reads a file from storage + */ + @JavascriptInterface + fun readFile(basedir: String, filename: String): String { + return Promise(context.threadPoolExecutor, { + resolve, + reject -> + try { + if (basedir.startsWith("content://")) { + resolve( + context.contentResolver + .readBytes(Uri.parse(basedir)) + .toString(Charset.forName("utf-8")) + ) + } else { + val path = getDirectory(basedir) + resolve(File(path, filename).readText()) + } + } catch (ex: Exception) { + reject(ex.stackTraceToString()) + } + }).addJsCommunicator(jsCommunicator) + } + + /** + * writes a file to storage + */ + @JavascriptInterface + fun writeFile(basedir: String, filename: String, content: String): String { + return Promise(context.threadPoolExecutor, { + resolve, + reject -> + try { + if (basedir.startsWith("content://")) { + // urls created by save dialog + context.contentResolver.writeBytes( + Uri.parse(basedir), + content.toByteArray() + ) + resolve("true") + } else { + val path = getDirectory(basedir) + File(path, filename).writeText(content) + resolve("true") + } + } catch (ex: Exception) { + reject(ex.stackTraceToString()) + } + }).addJsCommunicator(jsCommunicator) + } + // endregion + + // region Dialogs + /** + * requests a save dialog, resolves a js promise when done, resolves with `USER_CANCELED` if the user cancels + * @return a js promise id + */ + @JavascriptInterface + fun requestSaveDialog(fileName: String, fileType: String): String { + return Promise(context.threadPoolExecutor, { + resolve, + reject + -> + context.launchIntent( + Intent(Intent.ACTION_CREATE_DOCUMENT) + .addCategory(Intent.CATEGORY_OPENABLE) + .setType(fileType) + .putExtra(Intent.EXTRA_TITLE, fileName) + ).then { + if (it!!.resultCode == Activity.RESULT_CANCELED) { + resolve("USER_CANCELED") + } + try { + val payload = JSONObject() + payload.put("uri", it.data!!.data) + resolve(payload) + } catch (ex: Exception) { + reject(ex.toString()) + } + } + }).addJsCommunicator(jsCommunicator) + } + + @JavascriptInterface + fun requestOpenDialog(fileTypes: String): String { + return Promise(context.threadPoolExecutor, { + resolve, + reject -> + context.launchIntent( + Intent(Intent.ACTION_GET_CONTENT) + .setType("*/*") + .putExtra(Intent.EXTRA_MIME_TYPES, fileTypes.split(",").toTypedArray()) + ).then { + if (it!!.resultCode == Activity.RESULT_CANCELED) { + resolve("USER_CANCELED") + } + try { + val uri = it.data!!.data + val mimeType = context.contentResolver.getType(uri!!) + val fileName = getFileNameFromUri(uri.toString()) + val payload = JSONObject() + payload.put("uri", uri) + payload.put("type", mimeType) + payload.put("fileName", fileName) + resolve(payload) + } catch (ex: Exception) { + reject(ex.toString()) + } + } + }).addJsCommunicator(jsCommunicator) + } + + @JavascriptInterface + fun requestDirectoryAccessDialog(): String { + return Promise(context.threadPoolExecutor, { + resolve, + reject -> + context.launchIntent( + Intent(Intent.ACTION_OPEN_DOCUMENT_TREE) + ).then { + if (it!!.resultCode == Activity.RESULT_CANCELED) { + resolve("USER_CANCELED") + } + try { + val uri = it.data!!.data!! + context.contentResolver.takePersistableUriPermission( + uri, + Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION + ) + resolve(uri) + } catch (ex: Exception) { + reject(ex.toString()) + } + } + }).addJsCommunicator(jsCommunicator) + } + + // endregion + + // region System + + @JavascriptInterface + fun getLogs(): String { + var logs = "[" + for (message in context.consoleMessages) { + logs += "${message}," + } + // get rid of trailing comma + logs = logs.substring(0, logs.length - 1) + logs += "]" + return logs + } + + @JavascriptInterface + fun restart() { + context.finish() + context.startActivity(Intent(Intent.ACTION_MAIN) + .addCategory(Intent.CATEGORY_LAUNCHER) + .setClass(context, MainActivity::class.java)) + } + + /** + * hides the splashscreen + */ + @JavascriptInterface + fun hideSplashScreen() { + context.showSplashScreen = false + } + + @JavascriptInterface + fun enableKeepScreenOn() { + if (!keepScreenOn) { + keepScreenOn = true + context.runOnUiThread { + context.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + } + } + } + + @JavascriptInterface + fun disableKeepScreenOn() { + if (keepScreenOn) { + keepScreenOn = false + context.runOnUiThread { + context.window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + } + } + } + + /** + * used on the JS side for async js communication + */ + @JavascriptInterface + fun getSyncMessage(promise: String): String { + return jsCommunicator.getSyncMessage(promise) + } + + /** + * + */ + @JavascriptInterface + fun themeSystemUi(navigationHex: String, statusHex: String, navigationDarkMode: Boolean = true, statusDarkMode: Boolean = true) { + context.runOnUiThread { + val windowInsetsController = + WindowCompat.getInsetsController(context.window, context.window.decorView) + windowInsetsController.isAppearanceLightNavigationBars = !navigationDarkMode + windowInsetsController.isAppearanceLightStatusBars = !statusDarkMode + context.window.navigationBarColor = navigationHex.hexToColour() + context.window.statusBarColor = statusHex.hexToColour() + } + } + + @JavascriptInterface + fun getSystemTheme(): String { + if (context.darkMode) { + return "dark" + } else { + return "light" + } + } + + @JavascriptInterface + fun isAppPaused(): Boolean { + return context.paused + } + + @JavascriptInterface + fun enterPromptMode() { + context.webView.isVerticalScrollBarEnabled = false + context.isInAPrompt = true + } + + @JavascriptInterface + fun exitPromptMode() { + context.webView.isVerticalScrollBarEnabled = true + context.isInAPrompt = false + } + + @JavascriptInterface + fun setScale(scale: Int) { + context.webView.setScale(scale / 100.0) + } + + // endregion + + // region Data Extraction + + private fun getBotGuardScript(videoId: String, sessionContext: String, includeDebugMessage: Boolean = true): String { + val script = context.assets.readText("botGuardScript.js") + val functionName = script.split("export{")[1].split(" as default};")[0] + val exportSection = "export{${functionName} as default};" + val then = if (includeDebugMessage) { + "(TOKEN_RESULT) => { console.log(`Your potoken is \${TOKEN_RESULT}`); Android.returnToken(TOKEN_RESULT) }" + } else { + "(TOKEN_RESULT) => { Android.returnToken(TOKEN_RESULT) }" + } + val bakedScript = + script.replace(exportSection, "; ${functionName}(\"$videoId\", $sessionContext).then($then)") + return bakedScript + } + + @JavascriptInterface + fun generatePOToken(videoId: String, sessionContext: String): String { + return Promise(context.threadPoolExecutor, { + resolve, + reject + -> + context.runOnUiThread { + try { + val bgScript = getBotGuardScript(videoId, sessionContext) + val bgWv = context.generateBgWebview() + bgWv.jsInterface.onReturnToken { + run { + context.runOnUiThread { + resolve(it) + bgWv.destroy() + } + } + } + context.runOnUiThread { + bgWv.loadDataWithBaseURL( + "https://www.youtube.com/", + "", + "text/html", + "utf-8", + null + ) + } + } catch (exception: Exception) { + reject(exception.message!!) + } + } + }).addJsCommunicator(jsCommunicator) + } + + @JavascriptInterface + fun runDecipherScript(id: String, code: String): String { + // pass data to other webview + context.sigJsInterface.jsCommunicator.resolve(id, code) + // dispatch event to read data + context.sigWebView.dispatchEvent("message", "id", id) + return id + } + + // endregion + + /** + @JavascriptInterface + fun queueFetchBody(id: String, body: String) { + if (body != "undefined") { + context.pendingRequestBodies[id] = body + } + } + */ +} diff --git a/android/app/src/main/java/io/freetubeapp/freetube/javascript/SigWebViewJavascriptInterface.kt b/android/app/src/main/java/io/freetubeapp/freetube/javascript/SigWebViewJavascriptInterface.kt new file mode 100644 index 0000000..b5e9188 --- /dev/null +++ b/android/app/src/main/java/io/freetubeapp/freetube/javascript/SigWebViewJavascriptInterface.kt @@ -0,0 +1,30 @@ +package io.freetubeapp.freetube.javascript + +import android.util.JsonReader +import android.webkit.JavascriptInterface +import android.webkit.WebView +import io.freetubeapp.freetube.MainActivity +import io.freetubeapp.freetube.webviews.SigWebView +import org.json.JSONObject + +class SigWebViewJavascriptInterface( + webView: SigWebView, + private val remoteJSCommunicator: AsyncJSCommunicator +) { + val jsCommunicator = AsyncJSCommunicator(webView) + + @JavascriptInterface + fun readSync(id: String): String { + return jsCommunicator.getSyncMessage(id) + } + + @JavascriptInterface + fun resolve(id: String, message: String) { + remoteJSCommunicator.resolve(id, message) + } + + @JavascriptInterface + fun reject(id: String, message: String) { + remoteJSCommunicator.reject(id, message) + } +} diff --git a/android/app/src/main/java/io/freetubeapp/freetube/javascript/WebviewExtensions.kt b/android/app/src/main/java/io/freetubeapp/freetube/javascript/WebviewExtensions.kt new file mode 100644 index 0000000..60e73c8 --- /dev/null +++ b/android/app/src/main/java/io/freetubeapp/freetube/javascript/WebviewExtensions.kt @@ -0,0 +1,92 @@ +package io.freetubeapp.freetube.javascript + +import android.webkit.WebView +import org.json.JSONObject +import java.nio.charset.StandardCharsets + +/** + * fires and forgets javascript + * @param js javascript string to be evaluated + */ +fun WebView.fafJS(js: String) { + post { + loadUrl("javascript: $js") + } +} + +/** + * calls `window.dispatchEvent` with just the event name + */ +fun WebView.dispatchEvent(eventName: String) { + fafJS("window.dispatchEvent(new Event(\"$eventName\"))") +} + +/** + * calls `window.dispatchEvent` with the given json assigned to the event which is dispatched + */ +fun WebView.dispatchEvent(eventName: String, event: JSONObject) { + var js = "var tempVar = new Event(\"$eventName\");" + js += "Object.assign(tempVar, $event);" + js += "window.dispatchEvent(tempVar);" + fafJS(js) +} + +/** + * calls `window.dispatchEvent` with an event with a single custom key with a string value + */ +fun WebView.dispatchEvent(eventName: String, keyName: String, data: String) { + val wrapper = JSONObject() + wrapper.put(keyName, data) + dispatchEvent(eventName, wrapper) +} + +/** + * calls `window.dispatchEvent` with an event with a single custom key with a long value + */ +fun WebView.dispatchEvent(eventName: String, keyName: String, data: Long) { + val wrapper = JSONObject() + wrapper.put(keyName, data) + dispatchEvent(eventName, wrapper) +} + +/** + * calls `window.dispatchEvent` with an event with a single custom key with a JSON value + */ +fun WebView.dispatchEvent(eventName: String, keyName: String, data: JSONObject) { + val wrapper = JSONObject() + wrapper.put(keyName, data) + dispatchEvent(eventName, wrapper) +} + +/** + * encodes a string message for transport across the java bridge + * @param message the message to be encoded + */ +fun btoa(message: String): String { + return "atob(\"${String( + android.util.Base64.encode(message.toByteArray(), android.util.Base64.DEFAULT), + StandardCharsets.UTF_8 + )}\")" +} + +/** + * @param message the message to log + * @param level used in js as "console.$level" (ex: log, warn, error) + */ +fun WebView.consoleLog(message: String, level: String = "log") { + fafJS("console.$level(${btoa(message)})") +} + +fun WebView.consoleError(message: String) { + consoleLog(message, "error") +} + +fun WebView.consoleWarn(message: String) { + consoleLog(message, "warn") +} + +fun WebView.setScale(scale: Double) { + post { + setInitialScale((350 * scale).toInt()) + } +} diff --git a/android/app/src/main/java/io/freetubeapp/freetube/webviews/BackgroundPlayWebView.kt b/android/app/src/main/java/io/freetubeapp/freetube/webviews/BackgroundPlayWebView.kt new file mode 100644 index 0000000..d0c5b83 --- /dev/null +++ b/android/app/src/main/java/io/freetubeapp/freetube/webviews/BackgroundPlayWebView.kt @@ -0,0 +1,17 @@ +package io.freetubeapp.freetube.webviews + +import android.content.Context +import android.util.AttributeSet +import android.view.View +import android.webkit.WebView + +open class BackgroundPlayWebView @JvmOverloads constructor( + context: Context, attrs: AttributeSet? = null +) : WebView(context, attrs) { + private var once: Boolean = false + override fun onWindowVisibilityChanged(visibility: Int) { + if (once) return + if (visibility != View.GONE) super.onWindowVisibilityChanged(View.VISIBLE) + once = true + } +} diff --git a/android/app/src/main/java/io/freetubeapp/freetube/webviews/BotGuardWebView.kt b/android/app/src/main/java/io/freetubeapp/freetube/webviews/BotGuardWebView.kt new file mode 100644 index 0000000..3f08e6d --- /dev/null +++ b/android/app/src/main/java/io/freetubeapp/freetube/webviews/BotGuardWebView.kt @@ -0,0 +1,70 @@ +package io.freetubeapp.freetube.webviews + +import android.content.Context +import android.util.AttributeSet +import android.webkit.WebResourceRequest +import android.webkit.WebResourceResponse +import android.webkit.WebView +import android.webkit.WebViewClient +import io.freetubeapp.freetube.MainActivity +import io.freetubeapp.freetube.javascript.BotGuardJavascriptInterface +import io.freetubeapp.freetube.javascript.consoleLog +import java.net.HttpURLConnection +import java.net.URL + +class BotGuardWebView @JvmOverloads constructor( + context: Context, attrs: AttributeSet? = null +) : +// no need to communicate window visibility to botguard + BackgroundPlayWebView(context, attrs) { + val jsInterface = BotGuardJavascriptInterface(context as MainActivity) + init { + addJavascriptInterface(jsInterface, "Android") + webViewClient = object : WebViewClient() { + override fun shouldInterceptRequest( + view: WebView?, + request: WebResourceRequest? + ): WebResourceResponse? { + if (request!!.url.toString().startsWith("data:text/html") || request!!.url.toString().startsWith("https://www.youtube.com/api/jnn/v1/GenerateIT")) { + return super.shouldInterceptRequest(view, request) + } + with(URL(request.url.toString()).openConnection() as HttpURLConnection) { + requestMethod = request.method + // map headers + for (header in request!!.requestHeaders) { + setRequestProperty(header.key, header.value) + } + + if (url.toString().startsWith("https://www.youtube.com/youtubei/")) { + setRequestProperty("Referer", "https://www.youtube.com/") + setRequestProperty("Origin", "https://www.youtube.com") + setRequestProperty("Sec-Fetch-Site", "same-origin") + setRequestProperty("Sec-Fetch-Mode", "same-origin") + setRequestProperty("X-Youtube-Bootstrap-Logged-In", "false") + } + if (url.toString().startsWith("https://www.google.com/js/")) { + setRequestProperty("referer", "https://www.google.com/") + setRequestProperty("origin", "https://www.google.com") + setRequestProperty("Sec-Fetch-Dest", "script") + setRequestProperty("Sec-Fetch-Site", "cross-site") + setRequestProperty("Accept-Language", "*") + } + if (request.requestHeaders.containsKey("x-fta-request-id")) { + if (jsInterface.pendingRequestBodies.containsKey(request.requestHeaders["x-fta-request-id"])) { + val body = jsInterface.pendingRequestBodies[request.requestHeaders["x-fta-request-id"]] + jsInterface.pendingRequestBodies.remove(request.requestHeaders["x-fta-request-id"]) + outputStream.write(body!!.toByteArray()) + } + } + try { + // 🧝‍♀️ magic + return WebResourceResponse(this.contentType, this.contentEncoding, inputStream!!); + } catch (ex: Exception) { + consoleLog(ex.message!!, "error") + return super.shouldInterceptRequest(view, request) + } + } + } + } + } +} diff --git a/android/app/src/main/java/io/freetubeapp/freetube/webviews/SigWebView.kt b/android/app/src/main/java/io/freetubeapp/freetube/webviews/SigWebView.kt new file mode 100644 index 0000000..82ddcc8 --- /dev/null +++ b/android/app/src/main/java/io/freetubeapp/freetube/webviews/SigWebView.kt @@ -0,0 +1,31 @@ +package io.freetubeapp.freetube.webviews + +import android.content.Context +import android.util.AttributeSet +import android.webkit.WebResourceRequest +import android.webkit.WebResourceResponse +import android.webkit.WebView +import android.webkit.WebViewClient +import io.freetubeapp.freetube.MainActivity +import io.freetubeapp.freetube.javascript.consoleLog +import java.io.InputStream +import java.net.HttpURLConnection +import java.net.URL + +class SigWebView @JvmOverloads constructor( + context: Context, attrs: AttributeSet? = null +) : +// no need to communicate window visibility + BackgroundPlayWebView(context, attrs) { + init { + val mainActivity = (context as MainActivity) + webViewClient = object : WebViewClient() { + override fun shouldInterceptRequest( + view: WebView?, + request: WebResourceRequest? + ): WebResourceResponse? { + return null + } + } + } +} diff --git a/android/app/src/main/res/drawable/ic_launcher_background.xml b/android/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..a445390 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,17 @@ + + + + + diff --git a/android/app/src/main/res/drawable/ic_launcher_foreground.xml b/android/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..0d5f3fc --- /dev/null +++ b/android/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,10 @@ + + + + + + diff --git a/android/app/src/main/res/drawable/ic_media_notification_icon.xml b/android/app/src/main/res/drawable/ic_media_notification_icon.xml new file mode 100644 index 0000000..2d2afb0 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_media_notification_icon.xml @@ -0,0 +1,21 @@ + + + + + + + + diff --git a/android/app/src/main/res/layout/activity_main.xml b/android/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..87511c7 --- /dev/null +++ b/android/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,19 @@ + + + + + + diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..6f3b755 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..6f3b755 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 0000000..c209e78 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 0000000..b2dfe3d Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 0000000..4f0f1d6 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 0000000..62b611d Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 0000000..948a307 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..1b9a695 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 0000000..28d4b77 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..9287f50 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 0000000..aa7d642 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..9126ae3 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/android/app/src/main/res/values-land/dimens.xml b/android/app/src/main/res/values-land/dimens.xml new file mode 100644 index 0000000..22d7f00 --- /dev/null +++ b/android/app/src/main/res/values-land/dimens.xml @@ -0,0 +1,3 @@ + + 48dp + \ No newline at end of file diff --git a/android/app/src/main/res/values-night-v31/themes.xml b/android/app/src/main/res/values-night-v31/themes.xml new file mode 100644 index 0000000..dcc81e4 --- /dev/null +++ b/android/app/src/main/res/values-night-v31/themes.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/android/app/src/main/res/values-night-v33/themes.xml b/android/app/src/main/res/values-night-v33/themes.xml new file mode 100644 index 0000000..29999e1 --- /dev/null +++ b/android/app/src/main/res/values-night-v33/themes.xml @@ -0,0 +1,12 @@ + + + + + diff --git a/android/app/src/main/res/values-night/themes.xml b/android/app/src/main/res/values-night/themes.xml new file mode 100644 index 0000000..755d0f1 --- /dev/null +++ b/android/app/src/main/res/values-night/themes.xml @@ -0,0 +1,7 @@ + + + + \ No newline at end of file diff --git a/android/app/src/main/res/values-v23/themes.xml b/android/app/src/main/res/values-v23/themes.xml new file mode 100644 index 0000000..8934e3b --- /dev/null +++ b/android/app/src/main/res/values-v23/themes.xml @@ -0,0 +1,9 @@ + + + + diff --git a/android/app/src/main/res/values-v31/themes.xml b/android/app/src/main/res/values-v31/themes.xml new file mode 100644 index 0000000..f1e5311 --- /dev/null +++ b/android/app/src/main/res/values-v31/themes.xml @@ -0,0 +1,10 @@ + + + + + diff --git a/android/app/src/main/res/values-v33/themes.xml b/android/app/src/main/res/values-v33/themes.xml new file mode 100644 index 0000000..ebeddbb --- /dev/null +++ b/android/app/src/main/res/values-v33/themes.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/android/app/src/main/res/values-w1240dp/dimens.xml b/android/app/src/main/res/values-w1240dp/dimens.xml new file mode 100644 index 0000000..d73f4a3 --- /dev/null +++ b/android/app/src/main/res/values-w1240dp/dimens.xml @@ -0,0 +1,3 @@ + + 200dp + \ No newline at end of file diff --git a/android/app/src/main/res/values-w600dp/dimens.xml b/android/app/src/main/res/values-w600dp/dimens.xml new file mode 100644 index 0000000..22d7f00 --- /dev/null +++ b/android/app/src/main/res/values-w600dp/dimens.xml @@ -0,0 +1,3 @@ + + 48dp + \ No newline at end of file diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..c8524cd --- /dev/null +++ b/android/app/src/main/res/values/colors.xml @@ -0,0 +1,5 @@ + + + #FF000000 + #FFFFFFFF + \ No newline at end of file diff --git a/android/app/src/main/res/values/dimens.xml b/android/app/src/main/res/values/dimens.xml new file mode 100644 index 0000000..125df87 --- /dev/null +++ b/android/app/src/main/res/values/dimens.xml @@ -0,0 +1,3 @@ + + 16dp + \ No newline at end of file diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..83b6bf5 --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + FreeTube Android + \ No newline at end of file diff --git a/android/app/src/main/res/values/themes.xml b/android/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..f13763d --- /dev/null +++ b/android/app/src/main/res/values/themes.xml @@ -0,0 +1,9 @@ + + + + +