Compare commits

..

21 Commits

Author SHA1 Message Date
PLUJA
5975e42081
Update README.md 2020-08-26 08:45:15 +02:00
PLUJA
65d9ee87c4
Update README.md 2020-08-26 08:44:07 +02:00
PLUJA
4908a5eef3
Delete data_export.json 2020-08-23 08:24:13 +02:00
PLUJA
39a9dd7c58
Update README.md 2020-08-17 08:09:25 +02:00
PLUJA
de83ef3b68
Update README.md 2020-08-16 21:43:53 +02:00
PLUJA
0304fc385c
Update README.md 2020-08-16 21:38:31 +02:00
PLUJA
c39b84da05
Update README.md 2020-08-16 21:37:04 +02:00
PLUJA
bde147054c
Update README.md 2020-08-16 15:40:31 +02:00
PLUJA
ee81d2695f
Update README.md 2020-08-16 15:40:03 +02:00
PLUJA
aa43d51b85
Update README.md 2020-08-16 15:34:04 +02:00
PLUJA
75155e455e
Update README.md 2020-08-16 15:24:47 +02:00
PLUJA
c9f7cacb10
Update README.md 2020-08-16 15:24:26 +02:00
PLUJA
593f9cea34
Update README.md 2020-08-16 15:23:40 +02:00
PLUJA
a4f8fd2b49
Great progress! 2020-08-16 15:23:21 +02:00
PLUJA
270ed2ac3e
Update README.md 2020-08-04 23:21:31 +02:00
PLUJA
487b532d3e
Update README.md 2020-08-04 23:21:14 +02:00
PLUJA
5f46236f66
Update README.md 2020-08-02 09:49:48 +02:00
PLUJA
bc87412921
Update CHANGELOG.md 2020-08-02 09:46:17 +02:00
PLUJA
06735de0ce
Update README.md 2020-07-31 12:46:17 +02:00
PLUJA
7423e0ce50
New version - 2020.07.31 2020-07-31 12:40:49 +02:00
PLUJA
890b77e842
New version - 2020.07.31 2020-07-31 12:40:18 +02:00
105 changed files with 1123 additions and 7580 deletions

View File

@ -1,18 +0,0 @@
version: 2.1
orbs:
python: circleci/python@1.0.0
jobs:
build-and-test:
executor: python/default
steps:
- checkout
- python/install-packages:
pkg-manager: pip
# TODO: Tests
workflows:
main:
jobs:
- build-and-test

View File

@ -1,11 +0,0 @@
.circleci
.git
.github
.gitignore
cache
Dockerfile
docker-compose.yml
LICENSE
*.md
dockerhash.txt
app/static

View File

@ -1,37 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.

View File

@ -1,20 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: feature request
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

View File

@ -1,12 +0,0 @@
version: 2
updates:
# Maintain dependencies for GitHub Actions
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
# Maintain dependencies for pip
- package-ecosystem: "pip"
directory: "/"
schedule:
interval: "daily"

View File

@ -1,133 +0,0 @@
name: Docker Multi-Architecture Build
on:
push:
paths-ignore:
- "**.md"
branches:
- dev-indep
jobs:
cpython-build-docker:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2.3.4
with:
fetch-depth: 0
- name: Set up QEMU
uses: docker/setup-qemu-action@v1.2.0
with:
platforms: all
- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v1.5.1
with:
version: latest
- name: Login to DockerHub
uses: docker/login-action@v1.10.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Get hash of latest image
run: docker pull python:3-alpine && docker inspect --format='{{index .RepoDigests 0}}' python:3-alpine > dockerhash.txt
- name: Write the current version to a file
run: "{ git describe --tags --abbrev=0 & date +\"%d-%m-%y\" & git rev-list HEAD --max-count=1 --abbrev-commit;} > version.txt"
- name: cache docker cache
uses: actions/cache@v2.1.6
with:
path: ${{ github.workspace }}/cache
key: ${{ runner.os }}-docker-cpython-${{ hashFiles('**/requirements.txt') }}-${{ hashFiles('**/dockerhash.txt') }}
restore-keys: |
${{ runner.os }}-docker-cpython-
- name: Build and push
uses: docker/build-push-action@v2.6.1
with:
context: .
file: ./Dockerfile
platforms: linux/amd64,linux/arm64
push: true
tags: ytorg/yotter:latest
cache-from: type=local,src=cache
cache-to: type=local,dest=cache
pypy-build-docker:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2.3.4
with:
fetch-depth: 0
- name: Set up QEMU
uses: docker/setup-qemu-action@v1.2.0
with:
platforms: all
- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v1.5.1
with:
version: latest
- name: Login to DockerHub
uses: docker/login-action@v1.10.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Get hash of latest image
run: docker pull pypy:3-slim-buster && docker inspect --format='{{index .RepoDigests 0}}' pypy:3-slim-buster > dockerhash.txt
- name: Write the current version to a file
run: "{ git describe --tags --abbrev=0 & date +\"%d-%m-%y\" & git rev-list HEAD --max-count=1 --abbrev-commit;} > version.txt"
- name: cache docker cache
uses: actions/cache@v2.1.6
with:
path: ${{ github.workspace }}/cache
key: ${{ runner.os }}-docker-pypy-${{ hashFiles('**/requirements.txt') }}-${{ hashFiles('**/dockerhash.txt') }}
restore-keys: |
${{ runner.os }}-docker-pypy-
- name: Build and push
uses: docker/build-push-action@v2.6.1
with:
context: .
file: ./pypy.Dockerfile
platforms: linux/amd64,linux/arm64
push: true
tags: ytorg/yotter:pypy
cache-from: type=local,src=cache
cache-to: type=local,dest=cache
nginx-build-docker:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2.3.4
with:
fetch-depth: 0
- name: Set up QEMU
uses: docker/setup-qemu-action@v1.2.0
with:
platforms: all
- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v1.5.1
with:
version: latest
- name: Login to DockerHub
uses: docker/login-action@v1.10.0
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Get hash of latest image
run: docker pull nginx:mainline-alpine && docker inspect --format='{{index .RepoDigests 0}}' nginx:mainline-alpine > dockerhash.txt
- name: Write the current version to a file
run: "{ git describe --tags --abbrev=0 & date +\"%d-%m-%y\" & git rev-list HEAD --max-count=1 --abbrev-commit;} > version.txt"
- name: cache docker cache
uses: actions/cache@v2.1.6
with:
path: ${{ github.workspace }}/cache
key: ${{ runner.os }}-docker-nginx-${{ hashFiles('**/dockerhash.txt') }}
restore-keys: |
${{ runner.os }}-docker-nginx-
- name: Build and push
uses: docker/build-push-action@v2.6.1
with:
context: .
file: ./Dockerfile
platforms: linux/amd64,linux/arm64
push: true
tags: ytorg/nginx:latest
cache-from: type=local,src=cache
cache-to: type=local,dest=cache

16
.gitignore vendored
View File

@ -144,18 +144,4 @@ dmypy.json
# pytype static type analyzer
.pytype/
# Added
data_export.json
.env
.envo
SELF-HOSTING.md
README.md
/misc
misc/*
/misc/*
app/cache/*
app/cache
./app/cache/*
./app/cache
.github/ISSUE_TEMPLATE/
.github/ISSUE_TEMPLATE/*
# End of https://www.toptal.com/developers/gitignore/api/python

75
CHANGELOG.md Normal file
View File

@ -0,0 +1,75 @@
## Unreleased
- [ ] General: Break dependence with Invidious API - [Reason](https://github.com/iv-org/invidious/issues/1320)
- [ ] General: Import data from JSON file.
- [ ] Database: Improve following logic.
- [ ] Configuration page: Disable retweets.
- [ ] Configuration page: Disable loading media content.
- [ ] Configuration page: Dark mode.
- [ ] Configuration page: Change Invidious / Nitter instance.
- [ ] Youtube: Follow management page.
##### Long term
- See cited posts (if any).
- Share a tweet.
- Play media from Parasitter.
- Create following lists.
## [0.2.1] - 2020-07-31
### Added
- [x] Youtube: New video page - Watch videos without exiting Parasitter.
- [x] Youtube: Improved search - You can now search for channels and videos.
### Changed
- [x] General: Improved code structure.
- [x] Efficiency: Minor improvements
## [0.2.0] - 2020-07-29
### Added
- [x] Export your followed accounts (Youtube and Twitter) to a JSON file
- [x] Youtube: follow Youtube accounts.
- [x] Youtube: Manage suscriptions
- [x] Youtube: Show video time duration
### Changed
- [x] Efficiency: improvements. ~1s reduction on fetching time.
- [x] General: Minor UI changes.
### Fixed
- [x] Twitter: Saving posts didn't work on 2020.07.24 update.
## [0.1.0] - 2020-07-19
### Added
- [x] Twitter: Ability to save posts.
- [x] Twitter: Ability to remove a saved post.
- [x] Twitter: Open the original post on Nitter.
- [x] General: Error pages: Error 500, Error 405
### Changed
- [x] Efficiency: Significant improvement on fetching feed efficiency - Parallelism applied.
- [x] General: Changelogs now using [Keep a changelog](https://keepachangelog.com/en/1.0.0/) style.
### Fixed
- [x] Twitter: "Saved" menu element logged out instead of showing saved posts.
## [0.0.2] - 2020-07-14
### Added
- [x] Twitter: First implementation of saved posts - Not working yet.
- [x] Twitter: Empty feed now shows a notice.
- [x] Twitter: Pinned posts are now marked as it.
- [x] General: Error 404 page.
- [x] General: Requirements.txt file for a better installation and update experience.
### Changed
- [x] Twitter: More flexible user search. Search by username and show a list of possible results.
- [x] General: Minor UI fixes.
- [x] Efficiency: Fetching of accounts in a slightly more efficient way.
## [0.0.1] - 2020-07-13
### Added
- [x] Ability to follow accounts.
- [x] Ability to unfollow accounts.
- [x] Ability to register users.
- [x] Ability to visit a user profile.
- [x] Search a user by its exact username.

View File

@ -1,37 +0,0 @@
FROM python:3-alpine AS base
# Image to Build Dependencies
FROM base AS builder
WORKDIR /usr/src/app
COPY ./requirements.txt /usr/src/app
# Build Dependencies
RUN apk --no-cache add gcc musl-dev libffi-dev openssl-dev libxml2-dev libxslt-dev file llvm-dev make g++ cargo rust
# Python Dependencies
RUN pip install --no-cache-dir --prefix=/install wheel cryptography gunicorn pymysql
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt
# Runtime Environment Image
FROM base
WORKDIR /usr/src/app
# Runtime Dependencies
RUN apk --no-cache add libxml2 libxslt
COPY --from=builder /install /usr/local
COPY . .
RUN flask db init \
&& flask db migrate \
&& flask db upgrade
CMD flask db stamp head \
&& flask db migrate \
&& flask db upgrade \
&& gunicorn -b 0.0.0.0:5000 -w 4 yotter:app
EXPOSE 5000

619
LICENSE
View File

@ -1,619 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
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

287
README.md
View File

@ -1,186 +1,167 @@
## This project is no longer maintained. Visit [this repo](https://github.com/TeamPiped/Piped) for an alternative.
# Parasitter
<p align="center"> <img width="150" src="app/static/img/logo.png"> </img></p>
<p align="center"> Twitter and Youtube via RSS with privacy </p>
<br>
<p align="center"> <img width="700" src="app/static/img/banner.png"> </img></p>
<p align="center">
<a href="https://www.gnu.org/licenses/gpl-3.0"><img alt="License: GPL v3" src="https://img.shields.io/badge/License-AGPLv3-blue.svg"></img></a>
<a href="https://github.com/pluja/Yotter"><img alt="Development state" src="https://img.shields.io/badge/State-Beta-blue.svg"></img></a>
<a href="https://github.com/pluja/Yotter/pulls"><img alt="Pull Requests Welcome" src="https://img.shields.io/badge/PRs-Welcome-green.svg"></img></a>
<a href="https://git.kavin.rocks/kavin/Yotter"><img alt="Mirror 1" src="https://img.shields.io/badge/Mirror1-git.kavin.rocks-teal"></img></a>
<a href="https://84.38.177.154/libremirrors/ytorg/Yotter"><img alt="Mirror 2" src="https://img.shields.io/badge/Mirror2-git.rip-purple"></img></a>
</p>
#### **IMPORTANT** If you want to try out the latest features you should look at [**this branch**](https://github.com/pluja/Parasitter/tree/dev-indep). Master branch is currently inactive!
Yotter allows you to follow and gather all the content from your favorite Twitter and YouTube accounts in a *beautiful* feed so you can stay up to date without compromising your privacy at all. Yotter is written with Python and Flask and uses Semantic-UI as its CSS framework.
## BREAKING DEPENDENCE WITH INVIDIOUS
A [**new branch**](https://github.com/pluja/Parasitter/tree/dev-indep) is being developed where I've broke dependence on Invidious.
Yotter is possible thanks to several open-source projects that are listed on the [Powered by](#powered-by) section. Make sure to check out those awesome projects!
Progress:
- [x] Video data.
- [x] Video playing
- [x] Proxy video - no Google/Youtube connections on client. [2020.08.16]
- [ ] Offer alternative to Youtube RSS.
- [ ] Search
# Index:
* [Why](#why)
# What is Parasitter?
Parasitter allows you to follow your favorite Twitter and YouTube accounts with full privacy. Parasitter (first version, this is [now being changed](https://github.com/pluja/Parasitter/blob/dev-indep/README.md)!) uses [Nitter's](https://nitter.net/) and [Invidious](invidio.us) rss feeds in order to gather the latest content from your favourite accounts and builds a *beautiful* feed. We will never connect you to Twitter or YouTube in any way, so your privacy is safe when using Parasitter. Parasitter is written in Python and Flask and uses Semantic-UI as its CSS framework.
Parasitter doesn't try to compete with Nitter nor Invidious. It serves as a complement, as it beneficiates from them. Parasitter is not a Twitter viewer as Nitter is or a YouTube frontend as Invidious. Instead Parasitter gathers all your accounts in one place so you can stay tuned with their latest content.
Parasitter is possible thanks to several open-source projects that are listed on the [Powered by](#powered-by) section. Make sure to check out those awesome projects!
## Index:
* [Features](#features)
* [Roadmap](#roadmap)
* [FAQ](#FAQ)
* [Privacy and Security](#privacy)
* [Public instances](#public-instances)
* [Self hosting](https://github.com/ytorg/Yotter/blob/dev-indep/SELF-HOSTING.md)
* [Contributing and contact](#contributing)
* [Security](#security)
* [Privacy](#privacy)
* [Self hosting](#self-hosting)
* [Local](#local)
* [Update](#updating-to-new-versions)
* [Server](#server)
* [Powered by](#powered-by)
* [Donate](#donate)
* [Screenshots](#screenshots)
* [Redirect Extensions](#redirect)
* [Donate](#donate-) (Please read!)
# Why
Youtube and Twitter are well-known by their invasive and data-stealing *'privacy policies'*. You give them a **lot** of data; from ideology to music taste, your likes and dislikes, your free-time schedule, and much more than you think. This much data gives such companies a control over you that you would never thought.
## Features:
* No JavaScript.
* 0 connections to Twitter or Youtube.
* Uses RSS feeds (could be expanded to more social networks)
* Follow Twitter accounts.
* Follow Youtube accounts.
* Watch Youtube videos.
* Save your favourite Tweets.
* Save your favourite Youtube videos [Coming soon!]
* Tor-friendly.
* Terminal-friendly.
* Easy 1 minute self-hosting deploy.
* No need for domain, runs locally.
> And many more to come!
With the *particular* data about you, they can get money from the highest bidder and target advertisements. This could seem *not-as-bad* but it gets worse. They can sell this data to some company that, with such knowledge about you, could harm your future in a way you can't imagine. What if you are watching self-help videos on Youtube and this data ends on you insurance hands? Would they raise your fee because they consider you are not *emotionally stable*? We can think of thousands of examples like this, where the data ends in the wrong hands and harms you in an unexpected way.
## Security
Only the hash of your password is stored on the database. Also no personal information of any kind is kept on the app itself, if a hacker gets access to it only thing they could do would be to follow/unfollow some accounts.
Further more, they don't care about **what you in particular watch**, this is only sold to the highest bidder who then may or may not do the harm. What they care more about is **what people watch** this is the important data and the one that allows to manipulate, bias, censor, etc.
I always recommend self-hosting, as you will be the only person with access to the data.
So we need platforms and spaces where we can freely watch and listen content without these watchful eyes upon us. Ideally, everyone would use a free (as in freedom) and decentralized platform like [Peertube](https://joinpeertube.org/), [Odysee](https://odysee.com/), [Mastodon](https://joinmastodon.org/) or [Pleroma](https://pleroma.social/) but things are not like this. The main multimedia content factory is Youtube and the microblogging king is Twitter. So we will do whatever is possible to be able to watch and read the content and avoid the surveillance that seeks us these days. We will resist.
## Privacy
Parasitter cares about your privacy, and for this it will never make any connection to Twitter or Youtube. We make use of rss feeds to fetch all the tweets and videos from your followed accounts. If you want to use a specific Nitter or Invidious instance you can replace it at the top of the file `app/routes.py`.
# Features:
- [x] No Ads.
- [x] No Javascript needed*
- [x] Minimalist.
- [x] Search on Twitter and Youtube.
- [x] Zero connections to Google/Twitter on the client.
- [x] Follow Twitter accounts.
- [x] Follow Youtube accounts.
- [x] Play Youtube videos on background on Android.
- [x] Play only audio from youtube to save data.
- [x] Save your favourite Tweets.
- [x] Tor-friendly.
- [x] Terminal-browser friendly.
- [x] Fair non-adictive UX - No recommendations, no trending, no tops. Just your feed and your searches.
*Video player is VideoJS, which uses JavaScript. But if JavaScript is disabled Yotter still works perfectly and uses the default HTML video player.
### Roadmap
The following features are planned to be implemented in the near future:
* [ ] Improve performance and efficiency
#### Youtube specific:
* [ ] Subtitles
* [ ] > 720p Quality
* [ ] Save youtube videos
* [ ] Support for live streams
#### Twitter specific:
* [ ] Translations
# FAQ
### What's the difference between this and Invidious?
At first I started working on this project as a solution for following Twitter accounts (a thing that can't be done with Nitter) and getting a Twitter-like feed. Weeks later the leader of Invidious, Omar Roth, announced that he was stepping away from the project. As an Invidious active user, this made me think that a new alternative was needed for the community and also an alternative with an easier programming language for most people (as Invidious is written in Crystal). So I started developing a '*written-in-python Invidious alternative*' and it went quite well.
I hope that this project can prosper, gain contributors, new instances and create a good community around it.
### Why do I have to register to use Yotter?
Registering has two main reasons:
1. Yotter is in a **beta** state. This means that we will be incrementally increasing the capacity of the servers so we can empirically know how many users a Yotter server can handle. Also, there is no **big server** with capacity for handling any arbitrary ammount of users and serving video/data to those at the moment. For this, we decided to have a registration form so we could limit the users.
2. Yotter allows users to follow accounts and have a custom feed. This needs an account to save your followed users and generate a feed.
Admins are allowed to remove restrictions on any page they want. [Check this section](https://github.com/ytorg/Yotter/blob/dev-indep/SELF-HOSTING.md#removing-log-in-restrictions) to learn how.
If you want to use Yotter, it is recommended to self-host your own instance. You can use it for personal use or open it to the world. Self-hosting makes Yotter stronger and gives you full power. See [self hosting guide](https://github.com/ytorg/Yotter/blob/dev-indep/SELF-HOSTING.md).
### Will you ever implement video recommendations, trending videos, etc?
No. From my point of view, these are toxic features. I, and every user, should be using all *social media* to get the content **they** want. Recomendations, trending, autoplay next video, etc. are all features designed to trap users on using the app, to make them forget about the time spent there and to create an addiction to it. No, I won't implement any toxic features on Yotter. Yotter will keep the UI clean, fast and simple.
You get your feed from followed accounts and you can search for any video you like. Only thing I would consider implementing would be some kind of page where you can ask for recommendations for a particular video. This way the user would, voluntarily, ask for the recommendations rather than having a temptation to click on a new, youtube-bias-recommended video.
Please read: [1](https://arxiv.org/abs/1912.11211), [2](https://medium.com/dataseries/how-youtube-is-addictive-259d5c575883), [3](https://www.their.tube/), [4](https://www.sciencedirect.com/science/article/pii/S1386505619308743?via%3Dihub)
# Privacy
#### Connections
Yotter cares about your privacy, and for this it will never make any connection to Twitter or Youtube on the client. Every request is proxied through the Yotter server; video streaming, photos, data gathering, scrapping, etc.
The Yotter server connects to Google (Youtube) and Nitter in order to gather all the necessary data. Then it serves it (proxyed through itself) to the client. This means that as a client, you will never connect to Google/Youtube/Twitter - the Yotter server will do it for you. So if you want to set up a Yotter server for privacy reasons I recommend you to set it up on a remote VPS so you don't share your IP with, or use a VPN on the server.
If you don't mind exposing your IP making requests to Google then you can set it up wherever you want. Even with this method you will **avoid all trackers, ads, heavy-loaded pages, etc**. - you can still stay safe if you use a VPN to hide your IP.
#### Your data
The only things the database stores are:
* Salted hash of the password
It is always recommended to set up a self-hosted instance. It is quite easy and conveninent and will give you full control over your data. The only data that is stored on the Database is:
* Hash of the password
* Username
* Email (Will be deprecated soon!)
* List of followed users
* List of saved posts
* Some user configurations
This data will never be used for any other purpose than offering the service to the user. It's not sent anywhere, never.
# Self hosting
#### Security
Only the salted hash of your password is stored in the database, so no admin can see or guess your plain-text password ever. Also, no personal information of any kind is required nor kept, if a hacker gets access to the database the only thing they could do would be to follow/unfollow some accounts. So there's no motivation in 'hacking' Yotter.
### Local
You don't need a server to run Parasitter. You can run it on your computer locally and own your (little) data. The installation process is done on a GNU/Linux environment, but should be pretty similar on other platforms.
I always recommend self-hosting, as you will be the only person with access to your data.
1. Install `python3`, `pip3`, `python3-venv` (optional) and `git`.
2. Clone this repository:
- `git clone https://github.com/pluja/Parasitter.git`
3. Navigate to the project folder:
- `cd Parasitter`
4. [Optional] Prepare a virtual environment and activate it:
> Important note: The **client** never connects to Google / Youtube however, the server does in order to gather all the necessary things!
> Python lets you create virtual environments. This allows you to avoid installing all the `pip` packages on your system.
If you don't mind about that, you can jump to step **5.** and ignore everything about "[env]".
- `python3 -m venv venv`
- `source venv/bin/activate`
> Now you are inside of the virtual environment for python. All instructions wiht [env] indicate that must be done inside the env if you decided to create one. From now on, you will always need to start the application from within the virtual env.
5. [env] Update pip
- `pip3 install --upgrade pip`
6. [env] Install the required libraries:
- `pip3 install -r requirements.txt`
> Use `sudo` or, preferably `--user`, if not working.
7. [env] Initialize and prepare the database.
- `flask db init`
- `flask db migrate`
- `flask db upgrade`
8. [env] Run the application.
- `flask run`
9. Go to "http://localhost:5000/" and enjoy.
# Public Instances
| Name |Server location|Status & Register|
| ------------ | ------------ | ------------ |
| https://yotter.xyz/ |Germany| [Go](https://yotter.xyz/status)|
| https://yotter.kavin.rocks/ |India| [Go](https://yotter.kavin.rocks/status)|
| https://yotter.jank.media/ |Germany| [Go](https://yotter.jank.media/status)|
### Updating to new versions:
**NOTE: Updating will never delete your database, your following list will not be erased.**
1. Navigate to the git repository (the one you cloned when installing).
2. Pull new changes:
- `git pull`
4. Install new packages (if any):
- `pip install -r requirements.txt`
> It may be that there are no new packages to install. In that case, all requirements will be satisfied.
# Contributing
Contributors are always welcome. You can help in many ways: Coding, organizing, designing, [donating](#donate), maintaining... You choose what you want to help with!
5. [opt] This next step is only needed if you are running a version previous to [2020-07-15](CHANGELOG.md). Then you will need to update the database:
- `flask db migrate`
- `flask db upgrade`
6. Done! You are on latest version.
> **See [CHANGELOG](CHANGELOG.md) for a list of changes.**
We have a [Matrix](https://matrix.org/) room where we discuss anything related with Yotter, feel free to enter the room and start talking or reading. You can choose a Matrix client from [this list of Matrix clients](https://matrix.org/clients/). Also you will need to choose an instance to host your account, you can find Matrix instances [here](https://www.hello-matrix.net/public_servers.php).
### Server
Another option is to host a Parasitter server so you can access it from anywhere or give access to your beloved friends/community. Installation is a little bit more complex than the [local](#local), but should be easy if you follow the steps.
<a href="https://matrix.to/#/!wqJnbUtEfitxtOsLFj:privacytools.io?via=privacytools.io&via=matrix.org"><img alt="Join Matrix" src="https://img.shields.io/badge/Join Room-Matrix-black.svg">
> WARNING: This section is under construction.
##### Installing the app:
1. Install base dependencies:
- `sudo apt-get -y update`
- `sudo apt-get -y install python3 python3-venv python3-dev`
- `sudo apt-get -y install mysql-server postfix supervisor nginx git`
> Installation of MySQL will require you to enter a *database root* password.
2. Install the application:
- `git clone https://github.com/pluja/Parasitter.git`
- `cd Parasitter`
3. Prepare the environment:
- `python3 -m venv venv`
- `source venv/bin/activate`
- (venv) $ `pip install -r requirements.txt`
4. Install deployment packages:
- (venv) `pip install gunicorn pymysql`
5. Edit the *.env* SECRET_KEY:
- `nano .env`
> This will open an editor. Make sure to change the SECRET_KEY to a string of your like. Make it random and long enough.
6. Set up FLASK_APP environment variable:
- `echo "export FLASK_APP=parasitter.py" >> ~/.profile`
#### Other platforms:
<a href="https://reddit.com/r/Yotter"><img alt="Join Matrix" src="https://img.shields.io/badge/Reddit-r/Yotter-orange.svg">
##### Database configuration:
1. Enter the MySQL command prompt:
- `mysql -u root -p`
> It will prompt for the "root" password. This password is the one you set on the MySQL installation.
2. Create the database:
- mysql> `create database parasitter character set utf8 collate utf8_bin;`
- mysql> `create user 'parasitter'@'localhost' identified by '<db-password>';`
> Replace `<db-password>` as the password for the database *parasitter* user. This one needs to match the password set on the DATABASE_URL in the *.env* file (See Step 5 of [App installation](installing-the-app))
- mysql> `grant all privileges on parasitter.* to 'parasitter'@'localhost';`
- mysql> `flush privileges;`
- mysql> `quit;`
3. Upgrade the database:
- (venv) `flask db upgrade`
# Powered by:
These are projects that either make Yotter possible as an **essential part** of it or that served as **inspiration for some parts** of the code.
#### TO BE CONTINUED!
* [Nitter](https://nitter.net/)
* [Youtube-local](https://github.com/user234683/youtube-local)
* [youtube-dlc](https://github.com/blackjack4494/yt-dlc)
### Powered by:
* [Nitter](https://nitter.net)
* [Invidious](https://invidio.us)
* [Flask](https://flask.palletsprojects.com/)
* [SQLAlchemy](https://docs.sqlalchemy.org/en/13/)
* [Semantic-UI](https://semantic-ui.com)
* [requests-futures](https://github.com/ross/requests-futures)
* [microblog](https://github.com/miguelgrinberg/microblog)
* [Video.js](https://videojs.com/)
* [Invidious](https://github.com/iv-org/invidious)
# [Donate](https://github.com/pluja/pluja/blob/main/SUPPORT.md)
### Donate 💌
Testing with a public instance will soon be needed, and I will need to set up a server for this. If I want that Parasitter to go public and host some users I will need a (relativelly) good server and this is somehow expensive for me. So any contribution will be really welcome!
[Click here to see donation options](https://github.com/pluja/pluja/blob/main/SUPPORT.md)
This project is completelly Open Source and is built on my own free time as a hobby. So if you like it, you can buy me a coffee!
This project is completely free and Open Source and will always be.
Donations are used to mantain the [yotter.xyz](https://yotter.xyz/) public instance. [This is the server](https://www.netcup.eu/bestellen/produkt.php?produkt=2598) that I have rented for now.
## Screenshots
#### Twitter / Tweets / Profiles
<p align="center"> <img width="720" src="https://i.imgur.com/tA15ciH.png"> </img></p>
<p align="center"> <img width="720" src="https://i.imgur.com/BYswFy6.png"> </img></p>
#### Twitter search
<p align="center"> <img width="720" src="https://i.imgur.com/KalBDa5.png"> </img></p>
#### Youtube feed
<p align="center"> <img width="720" src="https://i.imgur.com/rHsKl0e.png"> </img></p>
#### Youtube video page / Comments
<p align="center"> <img width="720" src="https://i.imgur.com/pQhLcvI.png"> </img></p>
<p align="center"> <img width="720" src="https://i.imgur.com/kZPGUdq.png"> </img></p>
#### Youtube channel page
<p align="center"> <img width="720" src="https://i.imgur.com/zybRB7X.png"> </img></p>
#### Youtube search
<p align="center"> <img width="720" src="https://i.imgur.com/XHCSNTP.png"> </img></p>
## Redirect
If you want to worry less and enjoy Yotter more, you can use any of the following extensions to redirect Youtube to Yotter automatically:
* [Youtter](https://addons.mozilla.org/en-US/firefox/addon/youtter/?utm_source=addons.mozilla.org&utm_medium=referral&utm_content=search) - Firefox
* [Privacy Redirect](https://addons.mozilla.org/en-US/firefox/addon/youtter/?utm_source=addons.mozilla.org&utm_medium=referral&utm_content=search) - Chromium
* Set Yotter as a Invidious instance on extension options.
* [HTTPSEverywhere](https://www.eff.org/https-everywhere) - Both
* You can set up redirects. Use a "http://youtube.com/ -> https://yotterinstance.xyz/" redirect.
- **Bitcoin**: `3EjaWjtsHz4WpbVL5Wx8Xg6MfyRRnKYj4e`
- **Monero**: `83hinYmUkMH2ANgdhxRupmakzLwN26ddePrLQvZv4E3Q1CWjq7MDzsKRcPqLPQwTvG3DdujyaxbKbMsf9VKVAmphMhsfndc`

View File

@ -1,377 +0,0 @@
<a href="https://github.com/pluja/Yotter"><img alt="Installation Working" src="https://img.shields.io/badge/Status-Working 2020.10.05-green.svg"></img></a>
<a href="https://github.com/pluja/Yotter"><img alt="Tested on Ubuntu" src="https://img.shields.io/badge/Tested On-Ubuntu Server 20.04LTS-blue.svg"></img></a>
# Why should I self host?
Self-hosting gives you the whole power over the service and the data. You can set up a server for your own personal use or share it with friends and family. Or, why not go further and share it with the whole world?
When you self-host you make internet stronger and more censorship resistant. If one Yotter instance goes down for any reason, there will be all other instances online and ready to host new users.
# Index
* [Pre-Installation](#pre-installation)
* [Installation](#installation)
* [Docker Installation](#docker)
* [Manual Installation](#manual-installation)
* [Configure the server](#configure-the-server)
* [Update](#updating-the-server)
* [Others](#other-configurations)
# First Steps
You will need a server of your own, it is recomended to rent a VPS server on any service you like. Minimum requirements for ~100 users are 2GB of RAM and a Linux Server. It is better if the server is dedicated as whole to Yotter as it will improve performance and security.
Everything that appears between `< >` needs to be changed by you. So for example if you see `<password>` you should change it for `yourPassword` without keeping the `< >`.
## Set up a user
First of all, you will need to set up a new user on the server. For security reasons you should **never** use a `root` user to set up a service. If you already have a non-root user you can use that one and skip the following steps.
We will create a user named `ubuntu` as I will be setting this up on an ubuntu machine. So, if you choose a different username make sure you replace it on future commands. We will create and login to the user as follows:
```
# adduser --gecos "" ubuntu
# usermod -aG sudo ubuntu
# su ubuntu
$ cd
```
If you now type `pwd` and hit enter, you shuould see that the current path is `/home/<user>/`
Now you should be logged in. Make sure to set up a good password. It is recommended to use ssh keys to log-in remotelly and disable the password login on all users.
# Installation
## Docker
### 1. Pre-Configuration
1. [Install docker](https://paste.ubuntu.com/p/KMDHqs3XvB/):
> Instructions for Ubuntu 20.04LTS. For any other systems there are plenty of guides on the internet.
2. [Install docker-compose](https://paste.ubuntu.com/p/pgqkPzCpJk/):
> General instructions for all Linux systems
3. You can check it was installed with `docker-compose --version`
4. Install nginx if not installed.
* `sudo apt install nginx`
### 2. Setting up Yotter
1. Run the following commands on your server:
```
git clone https://github.com/ytorg/Yotter && cd Yotter
docker-compose up -d
chown -R www-data:www-data /var/run/ytproxy
```
> You may need to use `sudo` for turning up the docker-compose
2. Configure nginx as a reverse proxy to your docker container:
* Create a new nginx configuration file:
- `sudo nano /etc/nginx/sites-enabled/yotter`
* Paste the content of [this file](https://paste.ubuntu.com/p/248hh6crWH/) to the config file.
- Change `<example.com>` by your domain.
* Generate a ssl certificate:
- Follow [Let's Encrypt](https://certbot.eff.org/lets-encrypt/ubuntufocal-nginx) guide **(Recommended)**
- Only steps `3`, `5`, `6` and `7a (first command only)` are needed.
* Reload nginx:
- `sudo service nginx reload`
3. You are now ready to use Yotter on your domain!
- **Note that you will need to set up your domain DNS to resolve to your server IP.**
##### Extra step:
- [Configure the server](#configure-the-server)
### How Update with Docker
```
$ docker-compose down
$ docker pull ytorg/yotter
$ docker-compose up -d
```
> `sudo` may be needed.
<hr>
## Manual installation
#### Step 1: Base setup
1. Connect to your server via SSH or direct access.
- `ssh ubuntu@<ipaddress>`
- [x] (Recommended) Set up password-less login with ssh-keys.
2. Install base dependencies:
* `sudo apt-get -y update`
* `sudo apt-get -y install python3 python3-venv python3-dev`
* `sudo apt-get -y install mysql-server supervisor nginx git`
> When installing MySQL-server it will prompt for a root password. This is the password for the root user of MySQL. Set up a password of your like, this will be the MySQL databases master password and will be required later, so don't forget it!
If after the MySQL-server installation you have not been prompted to create a password for the `root` user, run `sudo mysql_secure_installation`
3. Clone this repository and acccess folder:
* `git clone https://github.com/ytorg/Yotter`
* `cd Yotter`
4. Create a Python virtual environment and populate it with dependencies:
* `python3 -m venv venv`
* `source venv/bin/activate`
* `pip install wheel`
* `pip install cryptography`
* `pip install -r requirements.txt`
> You can edit the `yotter-config.json` file. [Check out all the options here](#configure-the-server)
5. Install gunicorn (production web server for Python apps) and pymysql:
`pip install gunicorn pymysql`
6. Set up the database tables:
* `flask db init`
* `flask db migrate`
* `flask db upgrade`
7. Set up `.env`
1. (PRE) Generate a **random string** and copy it to clipboard:
`python3 -c "import uuid; print(uuid.uuid4().hex)"`
2. Create a `.env` file on the root folder of the project (`/home/ubuntu/Yotter/.env`):
```
SECRET_KEY=<RandomString>
DATABASE_URL=mysql+pymysql://yotter:<db-password>@localhost:3306/yotter
```
Make sure you change `<RandomString>` for the previously generated random string. You can paste it as is, without any `"" or ''`. Also change `<db-password>`. `<db-password>` should be different from the password of the database root user (the one you set up on step 1.2). This password will be needed later.
#### Step 2: Setting up the MySQL Database:
* Open the MySQL prompt line (Use the previously set MySQL root password!)
`mysql -u root -p`
> Note that you are being prompted for the password of the MySQL root user, the one you set up on step 1.2, not the password you wrote on the `.env` file. The password on the `.env` is the password for the MySQL Yotter database.
> If you still have problems with the root user password try running `sudo mysql` and then run this query: `ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '<YOUR_PASSWORD>';`. This changes the password for the MySQL user `root` by `<YOUR_PASSWORD>`
Now you should be on the MySQL prompt line (`mysql>`). So let's create the databases:
> Change `<db-password>` for a password of your like. It will be the password for the dabase user `yotter`. Don't choose the same password as the root user of MySQL for security.
> The password `<db-password>` for the **yotter** user needs to match the password that you included in the `DATABASE_URL` variable in the `.env` file. If you want to change it, you can change it now.
```
mysql> create database yotter character set utf8 collate utf8_bin;
mysql> create user 'yotter'@'localhost' identified by '<db-password>';
mysql> grant all privileges on yotter.* to 'yotter'@'localhost';
mysql> flush privileges;
mysql> quit;
```
If your set up was correct, you should now be able to run:
* `flask db upgrade`
> If you get "No such command" error, run `source env/bin/activate` and try again.
#### Step 3: Setting up Gunicorn and Supervisor
When you run the server with flask run, you are using a web server that comes with Flask. This server is very useful during development, but it isn't a good choice to use for a production server because it wasn't built with performance and robustness in mind. Instead of the Flask development server, for this deployment I decided to use gunicorn, which is also a pure Python web server, but unlike Flask's, it is a robust production server that is used by a lot of people, while at the same time it is very easy to use. [ref](https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xvii-deployment-on-linux)
* Start yotter under Gunicorn and check it has no errors:
`gunicorn -b localhost:8000 -w 4 yotter:app`
Once you see that no errors appear, you can stop gunicorn by pressing `Ctrl+C`.
The supervisor utility uses configuration files that tell it what programs to monitor and how to restart them when necessary. Configuration files must be stored in /etc/supervisor/conf.d. Here is a configuration file for Yotter, which I'm going to call yotter.conf [ref](https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xvii-deployment-on-linux).
* Create a yotter.conf file on `/etc/supervisor/conf.d/`:
> You can run `sudo nano /etc/supervisor/conf.d/yotter.conf` and paste the text below:
> Make sure to fit any path and user to your system.
```
[program:yotter]
command=/home/ubuntu/Yotter/venv/bin/gunicorn -b localhost:8000 -w 4 yotter:app
directory=/home/ubuntu/Yotter
user=ubuntu
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
```
After you write this configuration file, you have to reload the supervisor service for it to be imported:
`sudo supervisorctl reload`
#### Step 4: Set up Nginx, http3 proxy and HTTPS
The Yotter application server powered by gunicorn is now running privately port 8000. Now we need to expose the application to the outside world by enabling public facing web server on ports 80 and 443, the two ports too need to be opened on the firewall to handle the web traffic of the application. I want this to be a secure deployment, so I'm going to configure port 80 to forward all traffic to port 443, which is going to be encrypted. [ref](https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xvii-deployment-on-linux).
First we will get and set up the `http3-ytproxy`. For this we will need to [install go](https://github.com/golang/go/wiki/Ubuntu) but if you are on Ubuntu 20.04 or you have `snap` installed you can just run `sudo snap install --classic go` to get `go` installed.
Then you will need to run the following commands:
```
cd $HOME
git clone https://github.com/FireMasterK/http3-ytproxy
cd http3-ytproxy
go build -ldflags "-s -w" main.go
mv main http3-ytproxy
mkdir socket
chown -R www-data:www-data socket
```
Now we will configure a `systemd` service to run the http3-ytproxy. For this you will need to `sudo nano /lib/systemd/system/http3-ytproxy.service` to start a the `nano` text editor. Now copy and paste this and save:
> IMPORTANT: You may need to change some paths to fit your system!
```
[Unit]
Description=Sleep service
ConditionPathExists=/home/ubuntu/http3-ytproxy/http3-ytproxy
After=network.target
[Service]
Type=simple
User=www-data
Group=www-data
LimitNOFILE=1024
Restart=on-failure
RestartSec=10
WorkingDirectory=/home/ubuntu/http3-ytproxy
ExecStart=/home/ubuntu/http3-ytproxy/http3-ytproxy
# make sure log directory exists and owned by syslog
PermissionsStartOnly=true
ExecStartPre=/bin/mkdir -p /var/log/http3-ytproxy
ExecStartPre=/bin/chown syslog:adm /var/log/http3-ytproxy
ExecStartPre=/bin/chmod 755 /var/log/http3-ytproxy
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=http3-ytproxy
[Install]
WantedBy=multi-user.target
```
> IMPORTANT NOTE: Some distros have the Nginx user as `nginx` instead of `www-data`, if this is the case you should change the `User=` and `Group=` variables from the service file.
Now you are ready to enable and start the service:
```
sudo systemctl enable http3-ytproxy.service
sudo systemctl start http3-ytproxy.service
```
If you did everything ok you should see no errors when running `sudo journalctl -f -u http3-ytproxy`.
Now we will set up Nginx. To do so:
* `sudo rm /etc/nginx/sites-enabled/default`
Create a new Nginx site, you can run `sudo nano /etc/nginx/sites-enabled/yotter`
And write this on it:
```
server {
server_name <yourdomain>;
location / {
proxy_pass http://localhost:8000;
}
location /static {
# handle static files directly, without forwarding to the application
alias </path/to>/Yotter/app/static;
expires 30d;
}
location ~ (^/videoplayback$|/videoplayback/|/vi/|/a/|/ytc/) {
proxy_pass http://unix:/home/ubuntu/http3-ytproxy/socket/http-proxy.sock;
add_header Access-Control-Allow-Origin *;
sendfile on;
tcp_nopush on;
aio_write on;
aio threads=default;
directio 512;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}
```
> Note: You may need to change the proxy-pass line to fit your system. It should point to the socket created on the `http3-ytproxy/socket` folder.
Make sure to replace `<yourdomain>` by the domain you are willing to use for your instance (i.e example.com). You can now edit `yotter-config.json` and set `isInstance` to `true`.
You will also need to change the `</path/to>` after `alias` to fit your system. You have to point to the Yotter folder, in this set up it would be `/home/ubuntu` as it is the location where we cloned the Yotter app. This alias is created to handle static files directly, without forwarding to the application.
Once done, you can run `sudo service nginx reload`. If everything so far went OK, you can now set the `isInstance` to `true` on the `yotter-config.json` file.
Now you need to install an SSL certificate on your server so you can use HTTPS. If you are running Ubuntu 20LTS or already have `snap` installed, you can proceed as follows:
1. `sudo snap install --classic certbot`
> Note that you will have to create an 'A Record' on the DNS of your domain to point to the IP of your server for this next step. If you don't know how to do it, [this guide might help you](https://www.namecheap.com/support/knowledgebase/article.aspx/319/2237/how-can-i-set-up-an-a-address-record-for-my-domain) as on most services the procedure is similar.
Now we will run certbot and we need to tell that we run an nginx server. Here you will be prompted which domain you want to create and install the certificate for, select your domain:
2. `sudo certbot --nginx`
[Follow this instructions to install certbot and generate an ssl certificate so your server can use HTTPS](https://certbot.eff.org/lets-encrypt/ubuntufocal-nginx)
Finally, once this is done, you should edit the `yotter` nginx config and change the `listen 443 ssl;` line to `listen 443 ssl http2;`
#### Updating the server
Updating the server should always be pretty easy. These steps need to be run on the Yotter folder and with the python virtual env activated.
```
(venv) $ git pull
(venv) $ sudo supervisorctl stop yotter
(venv) $ flask db migrate
(venv) $ flask db upgrade
(venv) $ pip install -r requirements.txt
(venv) $ sudo supervisorctl start yotter
```
* **IMPORTANT**: Make sure you have all set up on `yotter-config.json` once you finish the update.
<hr>
## Configure the server
You will find in the root folder of the project a file named `yotter-config.json`. This is the global config file for the Yotter server.
Currently available config is:
* **serverName**: Name of the server. Format: `example.com`
* **nitterInstance**: Nitter instance that will be used when fetching Twitter content. Format must be `https://<NitterInstance.tld>/`
* **maxInstanceUsers**: Max users on the instance. When set to `0` it closes registrations.
* **serverLocation**: Location of the server.
* **restrictPublicUsage**: When set to `false` the instance allows non-registered users to use some routes (i.e /watch?v=..., /ytsearch, /channel...). See [this section](https://github.com/pluja/Yotter/blob/dev-indep/SELF-HOSTING.md#removing-log-in-restrictions)
* **isInstance**: If your installation is on a server using Nginx, it must be True. Only false if running on a local machine. [See this link]()
* **maintenance_mode**: Activates a message on the server warning users of maintenance mode.
* **show_admin_message**: Shows a message from the admin with title as `admin_message_title` and body as `admin_message`
* **admin_user**: Username of the admin user.
* **max_old_user_days**: Maximum days for a user to be inactive, otherwise will be deleted if admin uses the action.
* **donation_url**: Adds a link to a donation method for the instance.
## Other configurations
### Removing log-in restrictions
> (NOT TESTED - COULD CRASH THE APP) Note that some routes make usage of the `current_user` variable to look if the current user is following some user or not, if you remove the restriction for such routes the app will crash. This will be solved on future releases.
For the example, let's allow for anyone to watch a video on our instance. Even if they aren't registered users. First we need to find the route that we want to allow, you can do it by navigating to the page and taking a look at the URL. Anything after the first `/` is the app route. When we're watching a video, the route is `/watch?v=<videoId>`.
Now on the file `routes.py` we will search for the code that the server runs when we navigate to that route. You can use the Find function on your text editor and search for `/watch`. Now, you will see that right below the definition of the route, `@app.route('/watch')`, there is a `@login_required` line. If you delete that line, no restriction will now be applied to that route.
But you must know that videos and images are proxied through the instance. So we will need to allow another route. For video streaming, the route is `/stream` and for images it is `/img`. So you just need to delete the `login_required` from those two other routes.
You can now reload the server and you will see that, without logging in, you can now watch videos.
### Increasing the channel name max size on the database (Only installations older than 2020.09.20)
On older versions the character limit for a Youtube suscritpion was 30. This caused some problems with channels that had a longer string for the channel name. Since 2020.09.20 version, this problem was solved, but for older installation the problem persists even if you update to the latest github version.
To solve this, we will need to modify our database and set up new character limits. Don't worry, it's easy.
First you need to open the MySQL prompt. This can be done wiht `mysql -u root -p`. It will prompt you the **mysql database root user password**, note that it is NOT the *sudo* password. Once you're in the MySQL prompt (`mysql>`) you can execute these commands:
1. `connect yotter;` - This will connect you to the yotter database.
2. `ALTER TABLE channel MODIFY COLUMN channelName VARCHAR(100);` - This alters the field `channelName` from the table `channel` and sets its limit to `100` characters.
3. `quit;`

1
app/cache/.ignore vendored
View File

@ -1 +0,0 @@
dummy file for clone and pull.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

View File

@ -1,27 +1,27 @@
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import ValidationError, DataRequired, EqualTo
from wtforms.validators import ValidationError, DataRequired, Email, EqualTo
from app.models import User
class LoginForm(FlaskForm):
style={'class': 'ui primary button'}
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
remember_me = BooleanField('Remember Me')
submit = SubmitField('Sign In', render_kw=style)
submit = SubmitField('Sign In')
class SearchForm(FlaskForm):
username = StringField('Username')
submit = SubmitField('Search')
class ChannelForm(FlaskForm):
search = StringField('')
channelId = StringField('')
submit = SubmitField('Search')
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
password2 = PasswordField(
'Repeat Password', validators=[DataRequired(), EqualTo('password')])
@ -32,5 +32,10 @@ class RegistrationForm(FlaskForm):
if user is not None:
raise ValidationError('Please use a different username.')
def validate_email(self, email):
user = User.query.filter_by(email=email.data).first()
if user is not None:
raise ValidationError('Please use a different email address.')
class EmptyForm(FlaskForm):
submit = SubmitField('Submit')

View File

@ -9,31 +9,19 @@ followers = db.Table('followers',
)
channel_association = db.Table('channel_association',
db.Column('channel_id', db.Integer, db.ForeignKey('channel.id')),
db.Column('channel_id', db.String, db.ForeignKey('channel.id')),
db.Column('user_id', db.Integer, db.ForeignKey('user.id'))
) # Association: CHANNEL --followed by--> [USERS]
twitter_association = db.Table('twitter_association',
db.Column('account_id', db.Integer, db.ForeignKey('twitterAccount.id')),
db.Column('user_id', db.Integer, db.ForeignKey('user.id'))
) # Association: ACCOUNT --followed by--> [USERS]
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
last_seen = db.Column(db.DateTime, default=datetime.utcnow())
is_admin = db.Column(db.Boolean, default=False, nullable=True)
posts = db.relationship('Post', backref='author', lazy='dynamic')
def __repr__(self):
return f'<User {self.username}>'
def set_last_seen(self):
self.last_seen = datetime.utcnow()
def set_admin_user(self):
self.is_admin = True
return '<User {}>'.format(self.username)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
@ -41,6 +29,7 @@ class User(UserMixin, db.Model):
def check_password(self, password):
return check_password_hash(self.password_hash, password)
# TWITTER
def follow(self, user):
if not self.is_following(user):
self.followed.append(user)
@ -59,27 +48,12 @@ class User(UserMixin, db.Model):
def saved_posts(self):
return Post.query.filter_by(user_id=self.id)
# TWITTER
def twitter_following_list(self):
return self.twitterFollowed.all()
def is_following_tw(self, uname):
temp_cid = twitterFollow.query.filter_by(username = uname).first()
if temp_cid is None:
return False
else:
following = self.twitter_following_list()
for f in following:
if f.username == uname:
return True
return False
# YOUTUBE
def youtube_following_list(self):
return self.youtubeFollowed.all()
def is_following_yt(self, cid):
temp_cid = youtubeFollow.query.filter_by(channelId = cid).first()
temp_cid = invidiousFollow.query.filter_by(channelId = cid).first()
if temp_cid is None:
return False
else:
@ -95,16 +69,11 @@ class User(UserMixin, db.Model):
secondaryjoin=(followers.c.followed_id == id),
backref=db.backref('followers', lazy='dynamic'), lazy='dynamic')
youtubeFollowed = db.relationship("youtubeFollow",
youtubeFollowed = db.relationship("invidiousFollow",
secondary=channel_association,
back_populates="followers",
lazy='dynamic')
twitterFollowed = db.relationship("twitterFollow",
secondary=twitter_association,
back_populates="followers",
lazy='dynamic')
@login.user_loader
def load_user(id):
@ -119,21 +88,14 @@ class twitterPost():
isRT = True
urlToPost = ""
validPost = True
content = ""
content = "El gato siguió a la liebre. Esto es un texto de ejemplo."
profilePic = "url"
timeStamp = "error"
userProfilePic = "1.png"
isReply = False
replyingUrl = "#"
replyingUser = "@nobody"
replyingTweetContent = ""
attachedImg = ""
replyAttachedImg = ""
class ytPost():
class invidiousPost():
channelName = 'Error'
channelUrl = '#'
channelId = '@'
videoUrl = '#'
videoTitle = '#'
videoThumb = '#'
@ -143,36 +105,24 @@ class ytPost():
id = 'isod'
class youtubeFollow(db.Model):
class invidiousFollow(db.Model):
__tablename__ = 'channel'
id = db.Column(db.Integer, primary_key=True)
channelId = db.Column(db.String(30), nullable=False)
channelName = db.Column(db.String(100))
channelId = db.Column(db.String(30), nullable=False, unique=True)
followers = db.relationship('User',
secondary=channel_association,
back_populates="youtubeFollowed")
def __repr__(self):
return f'<youtubeFollow {self.channelName}>'
class twitterFollow(db.Model):
__tablename__ = 'twitterAccount'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(100), nullable=False)
followers = db.relationship('User',
secondary=twitter_association,
back_populates="twitterFollowed")
def __repr__(self):
return f'<twitterFollow {self.username}>'
return '<invidiousFollow {}>'.format(self.channelId)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String(540))
body = db.Column(db.String(140))
timestamp = db.Column(db.String(100))
url = db.Column(db.String(550), unique=True)
username = db.Column(db.String(100))
url = db.Column(db.String(100), unique=True)
username = db.Column(db.String(24))
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
def __repr__(self):
return f'<Post {self.body}>'
return '<Post {}>'.format(self.body)

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 746 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

View File

@ -1 +0,0 @@
{"name":"","short_name":"","icons":[{"src":"/android-chrome-192x192.png","sizes":"192x192","type":"image/png"},{"src":"/android-chrome-512x512.png","sizes":"512x512","type":"image/png"}],"theme_color":"#ffffff","background_color":"#ffffff","display":"standalone"}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 72 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 58 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

View File

@ -1 +0,0 @@
.vjs-quality-selector .vjs-menu-button{margin:0;padding:0;height:100%;width:100%}.vjs-quality-selector .vjs-icon-placeholder{font-family:'VideoJS';font-weight:normal;font-style:normal}.vjs-quality-selector .vjs-icon-placeholder:before{content:'\f110'}.vjs-quality-changing .vjs-big-play-button{display:none}.vjs-quality-changing .vjs-control-bar{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;visibility:visible;opacity:1}

View File

@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 Semantic Org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,7 @@
# CSS Distribution
This repository is automatically synced with the main [Semantic UI](https://github.com/Semantic-Org/Semantic-UI) repository to provide lightweight CSS only version of Semantic UI.
This package **does not support theming** and includes generated CSS files of the default theme only.
You can view more on Semantic UI at [LearnSemantic.com](http://www.learnsemantic.com) and [Semantic-UI.com](http://www.semantic-ui.com)

View File

@ -0,0 +1,20 @@
{
"name": "semantic-ui-css",
"version": "2.4.1",
"title": "Semantic UI",
"description": "CSS Only distribution of Semantic UI",
"homepage": "http://www.semantic-ui.com",
"author": "Jack Lukic <jack@semantic-ui.com>",
"license": "MIT",
"main": "semantic.js",
"repository": {
"type": "git",
"url": "git://github.com/Semantic-Org/Semantic-UI-CSS.git"
},
"bugs": {
"url": "https://github.com/Semantic-Org/Semantic-UI/issues"
},
"dependencies": {
"jquery": "x.*"
}
}

View File

@ -1,67 +0,0 @@
.video-js-responsive-container.vjs-hd {
padding-top: 56.25%;
}
.video-js-responsive-container.vjs-sd {
padding-top: 75%;
}
.video-js-responsive-container {
width: 100%;
position: relative;
}
.video-js-responsive-container .video-js {
height: 100% !important;
width: 100% !important;
position: absolute;
top: 0;
left: 0;
}
.para-light-grey{
background-color: rgb(250, 82, 82);
}
.para-green{
background-color: lightgreen;
}
.twitter{
color: rgb(0, 166, 196) !important;
}
.youtube{
color: rgb(224, 32, 32) !important;
}
.video-title{
font-weight: bold;
font-size: 1.15em;
}
.break-word{
word-break: break-word;
}
.overflow-auto{
overflow: auto;
}
.menu{
width: 100% !important;
}
.control-me {
visibility: hidden;
cursor: not-allowed;
}
#toggle:checked ~ .control-me {
visibility: visible;
cursor: pointer;
}
.scroller {
position: fixed;
right: 80px;
bottom: 30px;
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,3 +0,0 @@
/* videojs-hotkeys v0.2.27 - https://github.com/ctd1500/videojs-hotkeys */
!function(e,t){"undefined"!=typeof window&&window.videojs?t(window.videojs):"function"==typeof define&&define.amd?define("videojs-hotkeys",["video.js"],function(e){return t(e.default||e)}):"undefined"!=typeof module&&module.exports&&(module.exports=t(require("video.js")))}(0,function(e){"use strict";"undefined"!=typeof window&&(window.videojs_hotkeys={version:"0.2.27"});(e.registerPlugin||e.plugin)("hotkeys",function(t){function n(e){return"function"==typeof s?s(e):s}function o(e){null!=e&&"function"==typeof e.then&&e.then(null,function(e){})}var r=this,u=r.el(),l=document,i={volumeStep:.1,seekStep:5,enableMute:!0,enableVolumeScroll:!0,enableHoverScroll:!1,enableFullscreen:!0,enableNumbers:!0,enableJogStyle:!1,alwaysCaptureHotkeys:!1,captureDocumentHotkeys:!1,documentHotkeysFocusElementFilter:function(){return!1},enableModifiersForNumbers:!0,enableInactiveFocus:!0,skipInitialFocus:!1,playPauseKey:function(e){return 32===e.which||179===e.which},rewindKey:function(e){return 37===e.which||177===e.which},forwardKey:function(e){return 39===e.which||176===e.which},volumeUpKey:function(e){return 38===e.which},volumeDownKey:function(e){return 40===e.which},muteKey:function(e){return 77===e.which},fullscreenKey:function(e){return 70===e.which},customKeys:{}},c=e.mergeOptions||e.util.mergeOptions,a=(t=c(i,t||{})).volumeStep,s=t.seekStep,m=t.enableMute,y=t.enableVolumeScroll,f=t.enableHoverScroll,v=t.enableFullscreen,d=t.enableNumbers,p=t.enableJogStyle,b=t.alwaysCaptureHotkeys,h=t.captureDocumentHotkeys,w=t.documentHotkeysFocusElementFilter,k=t.enableModifiersForNumbers,S=t.enableInactiveFocus,K=t.skipInitialFocus,F=e.VERSION;u.hasAttribute("tabIndex")||u.setAttribute("tabIndex","-1"),u.style.outline="none",!b&&r.autoplay()||K||r.one("play",function(){u.focus()}),S&&r.on("userinactive",function(){var e=function(){clearTimeout(t)},t=setTimeout(function(){r.off("useractive",e);var t=l.activeElement,n=u.querySelector(".vjs-control-bar");t&&t.parentElement==n&&u.focus()},10);r.one("useractive",e)}),r.on("play",function(){var e=u.querySelector(".iframeblocker");e&&""===e.style.display&&(e.style.display="block",e.style.bottom="39px")});var q=function(e){var i,c,s=e.which,y=e.preventDefault.bind(e),f=r.duration();if(r.controls()){var S=l.activeElement;if(b||h&&w(S)||S==u||S==u.querySelector(".vjs-tech")||S==u.querySelector(".vjs-control-bar")||S==u.querySelector(".iframeblocker"))switch(g(e,r)){case 1:y(),(b||h)&&e.stopPropagation(),r.paused()?o(r.play()):r.pause();break;case 2:i=!r.paused(),y(),i&&r.pause(),(c=r.currentTime()-n(e))<=0&&(c=0),r.currentTime(c),i&&o(r.play());break;case 3:i=!r.paused(),y(),i&&r.pause(),(c=r.currentTime()+n(e))>=f&&(c=i?f-.001:f),r.currentTime(c),i&&o(r.play());break;case 5:y(),p?(c=r.currentTime()-1,r.currentTime()<=1&&(c=0),r.currentTime(c)):r.volume(r.volume()-a);break;case 4:y(),p?((c=r.currentTime()+1)>=f&&(c=f),r.currentTime(c)):r.volume(r.volume()+a);break;case 6:m&&r.muted(!r.muted());break;case 7:v&&(r.isFullscreen()?r.exitFullscreen():r.requestFullscreen());break;default:if((s>47&&s<59||s>95&&s<106)&&(k||!(e.metaKey||e.ctrlKey||e.altKey))&&d){var K=48;s>95&&(K=96);var F=s-K;y(),r.currentTime(r.duration()*F*.1)}for(var q in t.customKeys){var j=t.customKeys[q];j&&j.key&&j.handler&&j.key(e)&&(y(),j.handler(r,t,e))}}}},j=!1,T=u.querySelector(".vjs-volume-menu-button")||u.querySelector(".vjs-volume-panel");null!=T&&(T.onmouseover=function(){j=!0},T.onmouseout=function(){j=!1});var E=function(e){if(f)t=0;else var t=l.activeElement;if(r.controls()&&(b||t==u||t==u.querySelector(".vjs-tech")||t==u.querySelector(".iframeblocker")||t==u.querySelector(".vjs-control-bar")||j)&&y){e=window.event||e;var n=Math.max(-1,Math.min(1,e.wheelDelta||-e.detail));e.preventDefault(),1==n?r.volume(r.volume()+a):-1==n&&r.volume(r.volume()-a)}},g=function(e,n){return t.playPauseKey(e,n)?1:t.rewindKey(e,n)?2:t.forwardKey(e,n)?3:t.volumeUpKey(e,n)?4:t.volumeDownKey(e,n)?5:t.muteKey(e,n)?6:t.fullscreenKey(e,n)?7:void 0};return r.on("keydown",q),r.on("dblclick",function(e){if(null!=F&&F<="7.1.0"&&r.controls()){var t=e.relatedTarget||e.toElement||l.activeElement;t!=u&&t!=u.querySelector(".vjs-tech")&&t!=u.querySelector(".iframeblocker")||v&&(r.isFullscreen()?r.exitFullscreen():r.requestFullscreen())}}),r.on("mousewheel",E),r.on("DOMMouseScroll",E),h&&document.addEventListener("keydown",function(e){q(e)}),this})});
//# sourceMappingURL=videojs.hotkeys.min.js.map

View File

@ -2,7 +2,7 @@
{% block content %}
<div style="margin-top: 2em;" class="ui one column centered grid">
<img alt="Error 404 Image" class="ui medium circular image" src="{{ url_for('static',filename='img/404.png') }}">
<img class="ui medium circular image" src="{{ url_for('static',filename='img/404.png') }}">
</div>
<div style="margin: 1.5em;" class="ui one column centered grid">
<h2 class="ui header">This page is not on the map.</h2>

View File

@ -2,7 +2,7 @@
{% block content %}
<div style="margin-top: 2em;" class="ui one column centered grid">
<img alt="Error 405 Image" class="ui medium circular image" src="{{ url_for('static',filename='img/405.png') }}">
<img class="ui medium circular image" src="{{ url_for('static',filename='img/405.png') }}">
</div>
<div style="margin: 1.5em;" class="ui one column centered grid">
<h2 class="ui header">You are not allowed to do this!</h2>

View File

@ -2,7 +2,7 @@
{% block content %}
<div style="margin-top: 2em;" class="ui one column centered grid">
<img alt="Error 500 Image" class="ui medium circular image" src="{{ url_for('static',filename='img/500.png') }}">
<img class="ui medium circular image" src="{{ url_for('static',filename='img/500.png') }}">
</div>
<div style="margin: 1.5em;" class="ui one column centered grid">
<h2 class="ui header">Something went wrong... But it's not your fault!</h2>

View File

@ -1,10 +0,0 @@
<div class="ui center aligned text container">
<div class="ui row">
<img alt="Closed registrations image" class="ui centered medium image" src="{{ url_for('static',filename='img/closed.png') }}">
</div>
<div class="ui row">
<h2 class="ui header">Registrations are currently closed.</h2>
<h5 class="ui centered header"><a href="https://github.com/ytorg/Yotter#why-do-i-have-to-register-to-use-yotter">Why do I have to register?</a></h5>
</div>
</div>

View File

@ -1,9 +1,9 @@
<div class="ui center aligned text container">
<div class="ui row">
<img alt="Empty feed image" class="ui image" src="{{ url_for('static',filename='img/empty.png') }}">
<div style="margin-top: 2em;" class="ui one column centered grid">
<div style="margin: 1.5em;" class="ui row">
<img class="ui medium circular image" src="{{ url_for('static',filename='img/empty.png') }}">
</div>
<div class="ui row">
<div style="margin: 1.5em;" class="ui row">
<h2 class="ui header">This feed is empty.</h2>
</div>
</div>

37
app/templates/_post.html Normal file
View File

@ -0,0 +1,37 @@
<div class="column"> <!--Start tweet-->
<div class="ui centered card">
<div class="content">
<div class="extra content">
<div class="left floated author">
<img class="ui avatar image" src="{{ url_for('static',filename='img/avatars/')}}{{range(1, 12) | random}}.png">
</div>
<a href="{{post.url}}"><span class="right floated star">
<i class="share square outline icon"></i>
</span></a>
</div>
<div class="header" id="author"><a href="user/{{post.op.replace('@','')}}">{{ post.op }}</a></div>
<div class="meta">
<span class="category" id="time"><i class="clock icon"></i> {{post.date}} </span>
<span class="category"><i class="retweet icon"></i> {{post.username}} retwitted</span>
</div>
<div class="description">
<p>{{post.content}}</p>
</div>
<div class="extra content">
<p>
<form class="ui form" action="{{ url_for('savePost', url=post.url.replace('/', '~')) }}" method="post">
<button type="submit" class="ui icon button">
<i class="bookmark outline icon"></i>
</button>
</form>
</p>
</div>
</div>
<!--<div class="extra content">
<i class="like icon"></i> 1000
<span> · · </span>
<i class="retweet icon"></i> 20
</div>-->
</div>
</div> <!--End tweet-->

View File

@ -0,0 +1,37 @@
<div class="column"> <!--Start tweet-->
<div class="ui centered card">
<div class="content">
<div class="extra content">
<div class="left floated author">
<img class="ui avatar image" src="{{ post.profilePic }}">
</div>
<a href="{{post.url}}"><span class="right floated star">
<i class="share square outline icon"></i>
</span></a>
</div>
<div class="header" id="author"><a href="user/{{post.op.replace('@','')}}">{{ post.op }}</a></div>
<div class="meta">
<span class="category" id="time"><i class="clock icon"></i> {{post.date}} </span>
{% if post.isPinned %}
<span class="category" id="time"><i class="map pin icon"></i> Pinned </span>
{%endif%}
</div>
<div class="description">
<p>{{post.content}}</p>
</div>
<div class="extra content">
<form class="ui form" action="{{ url_for('savePost', url=post.url.replace('/', '~')) }}" method="post">
<button type="submit" class="ui icon button">
<i class="bookmark outline icon"></i>
</button>
</form>
</div>
</div>
<!--<div class="extra content">
<i class="like icon"></i> 1000
<span> · · </span>
<i class="retweet icon"></i> 20
</div>-->
</div>
</div> <!--End tweet-->

View File

@ -3,7 +3,7 @@
<div class="content">
<div class="extra content">
<div class="left floated author">
<img alt="Avatar random" class="ui avatar image" src="{{ url_for('static',filename='img/avatars/')}}{{range(1, 12) | random}}.png">
<img class="ui avatar image" src="{{ url_for('static',filename='img/avatars/')}}{{range(1, 12) | random}}.png">
</div>
<a href="{{post.url}}"><span class="right floated star">

View File

@ -1,85 +0,0 @@
<div class="ui centered card"><!--Start tweet-->
<div class="content">
<div class="extra content">
<div class="left floated author">
<img alt="Avatar" class="ui avatar image" src="{{ post.profilePic }}">
</div>
<a target="_blank" href="{{post.url}}"><span class="right floated star">
<i class="share square outline icon"></i>
</span></a>
</div>
<div class="header" id="author"><a href="{{url_for('u', username=post.op.replace('@',''))}}">{{ post.op }}</a></div>
<div class="meta">
<span class="category" id="time"><i class="clock icon"></i> {{post.date}} </span>
{% if post.isPinned %}
<span class="category" id="time"><i class="map pin icon"></i> Pinned </span>
{%endif%}
{% if post.isRT %}
<span class="category"><i class="retweet icon"></i> {{post.username}}</span>
{%endif%}
</div>
<div style="margin-bottom: 15px;" class="description break-word">
<p>{{post.content | safe}}</p>
</div>
<div class="content">
{% if post.attachedImages %}
{%for img in post.attachedImages %}
<a target="_blank" href="{{img}}">
<img alt="Image attachment" class="ui centered fluid rounded medium image" src="{{img}}">
</a>
{%endfor%}
{% endif %}
{% if post.attachedVideo %}
<div class="ui segment"><p><i class="file video icon"></i> <b>This tweet has an attached video.</b></p></div>
{%endif%}
{% if post.isReply %}
{%if post.unavailableReply%}
<div class="ui card">
<div class="content">
<p> This tweet is unavailable. </p>
</div>
</div>
{%else%}
<div class="ui card">
<div class="content">
<div class="header"><a href="/{{post.replyingUser}}">{{post.replyingUser}}</a></div>
<div class="meta">{{post.replyingUser}}</div>
<div class="description break-word">
{{post.replyingTweetContent | safe}}
{% if post.replyAttachedImg %}
<a target="_blank" href="{{post.replyAttachedImg}}">
<img alt="Image attachment" class="ui centered fluid rounded medium image" src="{{post.replyAttachedImg}}">
</a>
{% endif %}
</div>
</div>
</div>
{%endif%}
{% endif %}
<p>
<form class="ui form" action="{{ url_for('savePost', url=post.url.replace('/', '~')) }}" method="post">
<button type="submit" class="mini ui icon button">
<i class="bookmark outline icon"></i>
</button>
</form>
</p>
</div>
</div>
<div class="extra content">
<span class="left floated">
<i class="red heart like icon"></i>
{{post.likes}}
<span> </span>
<i class="grey comment icon"></i>
{{post.comments}}
</span>
<span class="right floated">
<i class="blue retweet icon"></i>
{{post.retweets}}
<i class="grey quote left icon"></i>
{{post.quotes}}
</span>
</div>
</div> <!--End tweet-->

View File

@ -1,27 +0,0 @@
<div class="comment">
<a class="avatar" style="width: 32px; height: 32px;"><img src="{{ comment.thumbnail }}"></a>
<div class="content">
{% if comment.author == info.author %}
<a class="author" style="color: red;" href="{{comment.channel}}"><i class="red user circle icon"></i>{{comment.author}}</a>
{% else %}
<a class="author" href="{{comment.channel}}">{{comment.author}}</a>
{% endif %}
<div class="metadata">
<div class="date">{{comment.date}}</div>
</div>
<div class="text">
{{comment.text}}
</div>
<div class="metadata">
<div class="rating">
<i class="comment icon"></i>
{{comment.replies}}
</div>
<div class="rating">
<i class="thumbs up icon"></i>
{{comment.likes}}
</div>
</div>
</div>
</div>

View File

@ -1,38 +1,30 @@
<div class="ui card">
<a class="image" href="{{url_for('watch', v=video.id, _method='GET')}}">
<img src="{{video.videoThumb}}">
</a>
<div class="content">
<a class="header" href="{{url_for('watch', v=video.id, _method='GET')}}">{{video.videoTitle}}</a>
<div class="meta">
<a class="break-word" href="{{url_for('channel', id=video.channelId)}}">{{video.channelName}}</a>
<div class="card">
<div class="image">
<img src="{{video.videoThumb}}">
</div>
<div class="content">
<a class="video-title" href="{{url_for('video', id=video.id)}}">{{video.videoTitle}}</a>
<div class="meta">
<a href="{{video.channelUrl}}">{{video.channelName}}</a>
</div>
<div class="description">
{{video.description}}
</div>
</div>
</div>
<div class="extra content">
{% if video.isLive == "Livestream" or video.isLive %}
<span class="left floated like">
<i class="red circle icon"></i>
{{video.views}}
</span>
{% else %}
<span class="left floated like">
<i class="eye icon"></i>
{{video.views}}
</span>
{% endif %}
{% if video.timeStamp == "Scheduled" or video.isUpcoming %}
<span class="right floated star">
<i class="blue clock icon"></i>
{{video.timeStamp}}
</span>
{% else %}
<span class="right floated star">
<i class="clock icon"></i>
{{video.timeStamp}}
</span>
{% endif %}
<span class="right floated">
<i class="eye icon"></i>
{{video.views}}
</span>
<span class="right floated">
<i class="clock icon"></i>
{{video.timeStamp}}
</span>
<span>
<a href="{{video.videoUrl}}">
<i class="share square outline icon"></i>
Open
</a>
</span>
</div>
</div>

View File

@ -2,64 +2,66 @@
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{% if title %}
<title>{{ title }} - Yotter</title>
<title>{{ title }} - Parassiter</title>
{% else %}
<title>Yotter</title>
<title>Parasitter</title>
{% endif %}
<meta name="viewport" content="width=device-width">
<link rel="preload" as= "style" type= "text/css" href= "{{ url_for('static',filename='semantic/semantic.min.css') }}">
<link rel="stylesheet" type= "text/css" href="{{ url_for('static',filename='styles.css') }}">
<link rel="icon" href="{{ url_for('static',filename='favicons/favicon.ico') }}">
<link rel= "stylesheet" type= "text/css" href= "{{ url_for('static',filename='semantic/semantic.min.css') }}">
<link rel="stylesheet"href= "{{ url_for('static',filename='semantic/semantic.min.css') }}">
<style>
.twitter{
color: rgb(0, 166, 196) !important;
}
.youtube{
color: rgb(224, 32, 32) !important;
}
.video-title{
font-weight: bold;
font-size: 1.15em;
}
</style>
</head>
<body>
{% if config.maintenance_mode %}
<div class="ui info message">
<div class="header">
Server under maintenance.
</div>
<div class="ui stackable menu">
<div class="item">
<img src="{{ url_for('static',filename='img/logo.png') }}">
</div>
{% endif %}
<div class="ui icon menu overflow-auto">
<a href="{{ url_for('index') }}"><div class="item">
<img alt="Yotter simple logo" src="{{ url_for('static',filename='img/logo_simple.png') }}">
</div></a>
<a href="{{ url_for('index') }}" class="twitter item">Twitter</a>
{% if current_user.is_anonymous %}
<a href="{{ url_for('login') }}" class="item">Login</a>
{% else %}
<a href="{{ url_for('twitter') }}" class="twitter item"><i class="twitter icon"></i></a>
<a href="{{ url_for('search') }}" class="twitter item"><i class="search icon"></i></a>
<a href="{{ url_for('saved') }}" class="twitter item"><i class="bookmark icon"></i></a>
<a href="{{ url_for('youtube') }}" class="youtube item"><i class="youtube icon"></i></a>
<a href="{{ url_for('ytsearch') }}" class="youtube item"><i class="search icon"></i></a>
<div class="right menu">
<a href="{{ url_for('settings') }}" class="item"><i class="cog icon"></i></a>
<a href="{{ url_for('logout') }}" class="item"><i class="sign-out icon"></i></a>
</div>
<a href="{{ url_for('search') }}" class="twitter item">Search</a>
<a href="{{ url_for('following') }}" class="twitter item">Following</a>
<a href="{{ url_for('saved') }}" class="twitter item">Saved</a>
<a href="{{ url_for('invidious') }}" class="youtube item">Youtube</a>
<a href="{{ url_for('ytsearch') }}" class="youtube item">Search</a>
<a href="{{ url_for('logout') }}" class="item">Logout</a>
<a href="{{ url_for('settings') }}" class="item"><i class="cog icon"></i></a>
{% endif %}
</div>
{% with messages = get_flashed_messages() %}
{% if messages %}
<div class="text centered container ui">
<div class="ui info message">
<div class="header">
Information
</div>
<ul class="list">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
<div class="ui info message">
<div class="header">
Information
</div>
<ul class="list">
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
</div>
</ul>
{% endif %}
{% endwith %}
{% block content %}{% endblock %}
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
</body>
</html>

View File

@ -1,96 +0,0 @@
{% extends "base.html" %}
{% block content %}
<div class="ui center aligned text container">
<div class="ui centered vertical segment">
<h2 class="ui header">
<img src="{{data.avatar}}" class="ui circular image">
{{data.channel_name}}
</h2>
</div>
{% if data.short_description %}
<div class="ui vertical segment">
<p>{{data.short_description}}</p>
</div>
{%endif%}
<div class="ui vertical segment">
<!--<div class="ui tiny statistic">
<div class="value">
{%if data.approx_suscriber_count == None%}
<i class="user icon"></i> ?
{%else%}
<i class="user icon"></i> {{data.approx_subscriber_count}}
{%endif%}
</div>
<div class="label">
Followers
</div>
</div>-->
{% if restricted or current_user.is_authenticated %}
{% if not current_user.is_following_yt(data.channel_id) %}
<form action="{{ url_for('ytfollow', channelId=data.channel_id) }}" method="post">
<button type="submit" value="Submit" class="ui red button">
<i class="user icon"></i>
Subscribe
</button>
</form>
{% else %}
<form action="{{ url_for('ytunfollow', channelId=data.channel_id) }}" method="post">
<button type="submit" value="Submit" class="ui red active button">
<i class="user icon"></i>
Unsubscribe
</button>
</form>
{%endif%}
{%endif%}
</div>
</div>
<br>
<br>
{% if data['error'] != None %}
{% include '_empty_feed.html' %}
{% else %}
<div class="ui centered cards">
{% for video in data['items'] %}
<div class="ui card">
<a class="image" href="{{url_for('watch', v=video.id, _method='GET')}}">
<img src="{{video.thumbnail}}">
</a>
<div class="content">
<a class="header" href="{{url_for('watch', v=video.id, _method='GET')}}">{{video.title}}</a>
<div class="meta">
<a class="break-word" href="{{url_for('channel', id=video.channel_id)}}">{{data.channel_name}}</a>
</div>
</div>
<div class="extra content">
<span class="left floated like">
<i class="eye icon"></i>
{{video.approx_view_count}}
</span>
{%if video.duration == "PREMIERING NOW" or video.duration == "LIVE"%}
<span class="right floated star">
<i class="red circle icon"></i>
LIVE
</span>
{%else%}
<span class="right floated star">
<i class="clock icon"></i>
{{video.time_published}}
</span>
{%endif%}
</div>
</div>
{% endfor %}
</div>
{% endif %}
<br>
<div class="ui center aligned text container">
<a href="{{prev_page}}"> <button class="ui left attached button"><i class="angle red left icon"></i></button> </a>
<a href="{{next_page}}"> <button class="right attached ui button"><i class="angle red right icon"></i></button></a>
</div>
<br>
{% endblock %}

View File

@ -1,29 +1,35 @@
{% extends "base.html" %}
{% block content %}
<div class="ui text container">
<div class="row">
<h2 class="ui header">Following ({{ count }}):</h2>
</div>
<div class="ui relaxed divided list">
{% for acc in accounts %}
<div class="item">
<div class="right floated content">
<p>
<form action="{{ url_for('unfollow', username=acc.username) }}" method="post">
{{ form.hidden_tag() }}
{{ form.submit(value='Unfollow') }}
</form>
</p>
</div>
<div class="content">
<a href="{{ url_for('u',username=acc.username)}}" class="header">{{acc.username}}</a>
<div class="description">@{{acc.username}}</div>
</div>
</div>
{% endfor %}
<div style="margin: 0em;" class="ui one column centered grid">
<div style="margin-top: 1em;" class="row">
<img class="ui tiny circular image" src="{{ url_for('static',filename='img/avatars/')}}{{range(1, 12) | random}}.png">
</div>
<div style="margin: 1.5em;" class="row">
<h2 class="ui header">Accounts you follow ({{ count }}):</h2>
</div>
</div>
<hr>
<div style="margin: 0em;" class="ui one column centered grid">
<div class="ui middle aligned divided list">
{% for acc in accounts %}
<div class="item">
<div class="right floated content">
<p>
<form action="{{ url_for('unfollowList', username=acc.username) }}" method="post">
{{ form.hidden_tag() }}
{{ form.submit(value='Unfollow') }}
</form>
</p>
</div>
<img class="ui avatar image" src="{{ url_for('static',filename='img/avatars/')}}{{range(1, 12) | random}}.png">
<div class="content">
{{acc.username}}
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}

View File

@ -1,66 +0,0 @@
{% extends "base.html" %}
{% block content %}
<style>
.ui.button {
cursor: pointer;
display: inline-block;
min-height: 1em;
outline: none;
border: none;
vertical-align: baseline;
background: #E0E1E2 none;
color: rgba(0, 0, 0, 0.6);
font-family: 'Lato', 'Helvsetica Neue', Arial, Helvetica, sans-serif;
margin: 0em 0.25em 0em 0em;
padding: 0.78571429em 1.5em 0.78571429em;
text-transform: none;
text-shadow: none;
font-weight: bold;
line-height: 1em;
font-style: normal;
text-align: center;
text-decoration: none;
border-radius: 0.28571429rem;
-webkit-box-shadow: 0px 0px 0px 1px transparent inset, 0px 0em 0px 0px rgba(34, 36, 38, 0.15) inset;
box-shadow: 0px 0px 0px 1px transparent inset, 0px 0em 0px 0px rgba(34, 36, 38, 0.15) inset;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-transition: opacity 0.1s ease, background-color 0.1s ease, color 0.1s ease, background 0.1s ease, -webkit-box-shadow 0.1s ease;
transition: opacity 0.1s ease, background-color 0.1s ease, color 0.1s ease, background 0.1s ease, -webkit-box-shadow 0.1s ease;
transition: opacity 0.1s ease, background-color 0.1s ease, color 0.1s ease, box-shadow 0.1s ease, background 0.1s ease;
transition: opacity 0.1s ease, background-color 0.1s ease, color 0.1s ease, box-shadow 0.1s ease, background 0.1s ease, -webkit-box-shadow 0.1s ease;
will-change: '';
-webkit-tap-highlight-color: transparent;
}
</style>
{% if config.show_admin_message %}
<div class="text container ui">
<div class="ui warning message">
<div class="header">
{{config.admin_message_title|safe}}
</div>
{{config.admin_message|safe}}
</div>
</div>
{% endif %}
<div style="margin: 2em" class="ui one column centered grid">
<div class="row">
<div class="column">
<h2 class="ui center aligned header">
Welcome back, {{current_user.username}}!
<div class="sub header">Choose a platform</div>
</h2>
</div>
</div>
<div class="row">
<a style="padding: .2em" href="{{ url_for('twitter') }}"><button class="massive teal ui button">Twitter</button></a>
<a style="padding: .2em" href="{{ url_for('youtube') }}"><button class="massive red ui button">Youtube</button></a>
</div>
</div>
{% endblock %}

23
app/templates/index.html Normal file
View File

@ -0,0 +1,23 @@
{% extends "base.html" %}
{% block content %}
<div style="padding: 1.3em;" class="ui one column centered grid">
<h2 class="ui blue header">
Hi, {{ current_user.username }}
<div class="sub header">Following: {{ followedCount }}</div>
</h2>
</div>
<hr>
<div class="ui one column grid" id="card-container">
{% if posts %}
{% for post in posts %}
{% if post.isRT %}
{% include '_post.html' %}
{% else %}
{% include '_post_nort.html' %}
{% endif %}
{% endfor %}
{% else %}
<div>No posts</div>
{% endif %}
{% endblock %}

View File

@ -0,0 +1,15 @@
{% extends "base.html" %}
{% block content %}
<br>
<br>
{% if videos %}
<div class="ui centered cards">
{% for video in videos %}
{% include '_video_item.html' %}
{% endfor %}
</div>
{% else %}
{% include '_empty_feed.html' %}
{% endif %}
{% endblock %}

View File

@ -1,13 +1,13 @@
{% extends "base.html" %}
{% block content %}
<h2 class="ui centered header">LOGIN</h2>
<div class="text center aligned container ui" id="container">
<div class="text center aligned container ui">
<h2 class="ui centered header">Login</h2>
<div class="ui grid">
<div class="ui one column stackable center aligned page grid" id="container">
<div class="row">
<form class="ui form" action="" method="post" novalidate>
{{ form.hidden_tag() }}
<p>
<i class="user icon"></i>
{{ form.username.label }}<br>
{{ form.username(size=32) }}<br>
{% for error in form.username.errors %}
@ -15,7 +15,6 @@
{% endfor %}
</p>
<p>
<i class="key icon"></i>
{{ form.password.label }}<br>
{{ form.password(size=32) }}<br>
{% for error in form.password.errors %}
@ -26,8 +25,11 @@
<p>{{ form.submit() }}</p>
</form>
</div>
<div class="text center aligned container ui">
<a href="{{ url_for('register') }}"><button class="ui button">Register</button></a>
<div class="row">
<div class="ui compact centered message">
<p>New user? <a href="{{ url_for('register') }}">Click to Register!</a></p>
</div>
</div>
</div>
</div>
{% endblock %}

View File

@ -1,37 +1,39 @@
{% extends "base.html" %}
{% block content %}
{% if registrations %}
<h2 class="ui centered header">Register</h2>
<h5 class="ui centered header"><a href="https://github.com/ytorg/Yotter#why-do-i-have-to-register-to-use-yotter">Why do I have to register?</a></h5>
<div class="ui text container" id="container">
<form class="ui form" action="" method="post">
{{ form.hidden_tag() }}
<p>
{{ form.username.label }}<br>
{{ form.username(size=32) }}<br>
{% for error in form.username.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>
{{ form.password.label }}<br>
{{ form.password(size=32) }}<br>
{% for error in form.password.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>
{{ form.password2.label }}<br>
{{ form.password2(size=32) }}<br>
{% for error in form.password2.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>{{ form.submit() }}</p>
</form>
</div>
{% else %}
{% include '_closed_registrations.html' %}
{% endif %}
<h2 class="ui centered header">Register</h2>
<div class="ui one column centered grid" id="container">
<form class="ui form" action="" method="post">
{{ form.hidden_tag() }}
<p>
{{ form.username.label }}<br>
{{ form.username(size=32) }}<br>
{% for error in form.username.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>
{{ form.email.label }}<br>
{{ form.email(size=64) }}<br>
{% for error in form.email.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>
{{ form.password.label }}<br>
{{ form.password(size=32) }}<br>
{% for error in form.password.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>
{{ form.password2.label }}<br>
{{ form.password2(size=32) }}<br>
{% for error in form.password2.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>{{ form.submit() }}</p>
</form>
</div>
{% endblock %}

View File

@ -1,12 +1,12 @@
{% extends "base.html" %}
{% block content %}
<div class="ui text container">
<form class="center aligned ui form" action="" method="post" novalidate>
<div class="ui one column centered grid">
<form class="ui form" action="" method="post" novalidate>
{{ form.hidden_tag() }}
<p>
{{ form.username.label }}<br>
{{ form.username(size=32, autofocus=true) }}<br>
{{ form.username(size=32) }}<br>
{% for error in form.username.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
@ -15,21 +15,18 @@
</form>
{% if results %}
<div class="ui relaxed divided list">
<div style="margin: 0em;" class="ui one column centered grid">
<div class="ui center aligned divided list">
{% for res in results %}
<div class="item">
<img alt="Avatar" class="ui avatar image" src="{{ res.avatar }}">
<img class="ui avatar image" src="{{ url_for('static',filename='img/avatars/')}}{{range(1, 12) | random}}.png">
<div class="content">
{% if res.fullName|length > 20%}
<a class="header" href="/u/{{res.username}}">{{res.fullName[0:23]}}...</a>
{% else %}
<a class="header" href="/u/{{res.username}}">{{res.fullName}}</a>
{% endif %}
<div class="description">{{res.username}}</div>
<a href="/user/{{res}}">{{res}}</a>
</div>
</div>
{% endfor %}
</div>
</div>
{% endif %}
</div>

View File

@ -2,7 +2,7 @@
{% block content %}
<br>
<div class="ui center aligned text container">
<div class="ui one column centered grid">
<h2 class="ui icon header">
<i class="settings icon"></i>
<div class="content">
@ -11,43 +11,19 @@
</div>
</h2>
</div>
<hr>
<br>
<h2 class="ui centered header">
Imports can take up to 2 minutes.
<div class="sub header">You can still use Yotter.</div>
</h2>
<div class="ui center aligned text container">
<div class="ui segments">
<div class="ui segment">
<div class="item">
<i class="large download middle aligned icon"></i>
<div class="content">
<div class="description"><h5 class="ui header">Export data into JSON file</h5></div>
<a href="{{ url_for('export') }}" class="header">Export Data</a>
</div>
</div>
</div>
<div class="ui blue segment">
<i class="large upload middle aligned icon"></i>
<div class="ui one column centered grid">
<div class="ui relaxed divided list">
<div class="item">
<i class="large download middle aligned icon"></i>
<div class="content">
<div class="description"><h5 class="ui header">Import subscription data</h5></div>
<form action = "{{ url_for('importdata') }}" method = "POST" enctype = "multipart/form-data">
<input type = "file" name = "file"/>
<input type = "submit"/>
<br>
<label class="radio-inline">
<input type="radio" name="import_format" id="yotter" value="yotter" checked> Yotter
</label>
<label class="radio-inline" data-tooltip="Includes FreeTube, Invidious and NewPipe.">
<input type="radio" name="import_format" id="youtube" value="youtube"> Youtube
</label>
</form>
<a href="{{ url_for('export') }}" class="header">Export Data</a>
<div class="description">Export data into JSON file</div>
</div>
</div>
</div>
<!--<div class="item">
<div class="item">
<i class="large moon middle aligned icon"></i>
<div class="content">
<div class="ui slider checkbox">
@ -65,45 +41,7 @@
<div class="description">Show links instead</div>
</div>
</div>
</div>-->
<div class="ui segment">
<label for="toggle">I want to delete my account.</label>
<input type="checkbox" id="toggle">
<div class="control-me"><a href="/deleteme"><button class="ui red button">Delete account</button></a></div>
</div>
<!--
{% if admin %}
<div class="ui segment">
<h2 class="ui centered header">
Admin tools
</h2>
<label for="toggle">Delete accounts with last login older than {{config.max_old_user_days}} days.</label> <br>
<a href="/clear_inactive_users/{{current_user.password_hash}}"><button class="ui red button">Delete</button></a></div>
</div>
{% endif %}-->
<!-- INSTANCE INFO -->
<h1 class="ui header">{{config.serverName}} Info</h1>
<div class="ui segments">
<div class="ui segment">
<p><b>Total users:</b> {{info.totalUsers}}</p>
</div>
<div class="ui segment">
<p><b>Active users:</b> {{info.active}}</p>
</div>
<div class="ui segment">
<p><b>Server location:</b> {{config.serverLocation}}</p>
</div>
{% if config.donate_url %}
<div class="ui segment">
<p><a href="{{config.donate_url}}">Consider making a donation to the instance</a></p>
</div>
{% endif %}
<div class="ui segment">
<p><a href="https://github.com/pluja/Yotter#donate">Donate to the Yotter developer</a></p>
</div>
</div>
</div>
{% endblock %}

View File

@ -1,55 +0,0 @@
{% extends "base.html" %}
{% block content %}
<div class="ui text container center aligned centered">
<div class="ui placeholder segment">
<div class="ui two column stackable center aligned grid">
<div class="ui vertical divider">
{%if cani%}
:)
{%else%}
:(
{%endif%}
</div>
<div class="middle aligned row">
<div class="column">
<h3 class="ui header"> Capacity </h3>
<div class="ui icon header">
{%if cani%}
<i class="green users icon"></i>
{%else%}
<i class="red users icon"></i>
{%endif%}
{{count}}/{{max}}
</div>
</div>
<div class="column">
<div class="ui icon header">
<i class="user circle outline icon"></i>
Can I register?
<h5 class="ui centered header"><a href="https://github.com/ytorg/Yotter#why-do-i-have-to-register-to-use-yotter">Why do I have to register?</a></h5>
</div>
{%if cani%}
<a href="/register"><div class="ui green button">
Yes!
</div></a>
{%else%}
<a href="#!"><div class="ui disabled red button">
It's full!
</div></a>
{%endif%}
</div>
</div>
</div>
</div>
<div class="ui text container center aligned centered">
<div class="ui segments">
<div class="ui segment">
<p>Yotter version: <b><a href="https://github.com/ytorg/Yotter/tags">{{tag}}</a></b></p>
<p>Latest update: <b><a href="https://github.com/ytorg/Yotter/commits/">{{update}}</a></b></p>
<p>Commit hash: <b><a href="https://github.com/ytorg/Yotter/commits/">{{hash}}</a></b></p>
</div>
</div>
</div>
{%endblock%}

View File

@ -1,43 +0,0 @@
{% extends "base.html" %}
{% block content %}
<div class="text container centered">
<a style="padding: 1.3em; display: block;" href="{{ url_for('following') }}" class="ui small teal statistic">
<div class="value">
{{ followedCount }}
</div>
<div class="label">
Following
</div>
</a>
</div>
<div class="text container" id="card-container">
{% if posts %}
{% for post in posts %}
{% include '_twitter_post.html' %}
{% endfor %}
{% else %}
{% include '_empty_feed.html' %}
{% endif %}
<div class="scroller">
<a href="#top" class="ui button">
<i style="margin: 0;" class="chevron up icon"></i>
</a>
</div>
</div>
<div class="text container center aligned">
<div class="ui centered pagination menu">
{%for page in range(init_page, pages)%}
{% if page == actual_page%}
<a href="/twitter/{{page}}" class="active item">
{{page}}
</a>
{% else %}
<a href="/twitter/{{page}}" class="item">
{{page}}
</a>
{% endif %}
{% endfor %}
</div>
</div>
{% endblock %}

View File

@ -1,108 +1,54 @@
{% extends "base.html" %}
{% block content %}
<div class="ui text container center aligned">
<div class="ui segments">
<div class="ui centered vertical segment">
<h2 class="ui header">
<img src="{{user.profilePic}}" class="ui circular image">
{{user.profileFullName}} <span style="color:grey;font-size: small;">({{user.profileUsername}})</span>
</h2>
</div>
<div class="ui horizontal segments">
<div class="ui segment">
<div class="ui centered vertical segment">
<p>{{user.profileBio}}</p>
</div>
</div>
<div class="ui segment">
{% if not current_user.is_following_tw(user.profileUsername.replace('@','')) %}
<p>
<form action="{{ url_for('follow', username=user.profileUsername.replace('@','')) }}" method="post">
{{ form.hidden_tag() }}
{{ form.submit(value='Follow') }}
</form>
</p>
{% else %}
<p>
<form action="{{ url_for('unfollow', username=user.profileUsername.replace('@','')) }}" method="post">
{{ form.hidden_tag() }}
{{ form.submit(value='Unfollow') }}
</form>
</p>
{% endif %}
</div>
</div>
<div class="ui horizontal segments">
<div class="ui segment">
<div class="statistic">
<div class="value">
<b>{{user.followers}}</b>
</div>
<div class="label">
<b>FOLLOWERS</b>
</div>
</div>
</div>
<div class="ui segment">
<div class="statistic">
<div class="value">
<b>{{user.following}}</b>
</div>
<div class="label">
<b>FOLLOWING</b>
</div>
</div>
</div>
<div class="ui segment">
<div class="statistic">
<div class="value">
<b>{{user.tweets}}</b>
</div>
<div class="label">
<b>TWEETS</b>
</div>
</div>
</div>
<div class="ui segment">
<div class="statistic">
<div class="value">
<b>{{user.likes}}</b>
</div>
<div class="label">
<b>LIKES</b>
</div>
</div>
</div>
<div class="blue ui centered card">
<div class="content">
<div class="center aligned author">
<img class="ui avatar image" src="{{ posts[0].userProfilePic }}"> {{ twitterAt }}
</div>
<div style="margin: .1em" class="center aligned header"><a href="https://nitter.net/{{ user.username }}">{{ posts[0].twitterName }}</a></div>
<div class="center aligned description">
<a>
<i class="users icon"></i>
{{ user.followers.count() }}
</a>
</div>
</div>
<div class="extra content">
<div class="ui one column centered grid">
{% if user == current_user %}
<p><a>This is your profile</a></p>
{% elif not current_user.is_following(user) %}
<p>
<form action="{{ url_for('follow', username=user.username) }}" method="post">
{{ form.hidden_tag() }}
{{ form.submit(value='Follow') }}
</form>
</p>
{% else %}
<p>
<form action="{{ url_for('unfollow', username=user.username) }}" method="post">
{{ form.hidden_tag() }}
{{ form.submit(value='Unfollow') }}
</form>
</p>
{% endif %}
</div>
</div>
</div>
<div style="margin-top: 15px;" class="text container" id="card-container">
{% if not posts %}
<div style="margin-top: 20px;" class="ui container center aligned">
<h2> <i class="window close outline icon"></i> This feed is empty. </h3>
</div>
{% elif posts == 'Protected' %}
<div style="margin-top: 20px;" class="ui container center aligned">
<h2> <i class="lock icon"></i> This account's tweets are protected. </h3>
</div>
{% else %}
{% for post in posts %}
{% include '_twitter_post.html' %}
{% endfor %}
<div class="scroller">
<a href="#top" class="ui button">
<i style="margin: 0;" class="chevron up icon"></i>
</a>
</div>
<br>
<div class="ui center aligned text container">
<a href="/{{user.profileUsername}}/{{prev_page}}"> <button class="ui left attached button"><i class="angle blue left icon"></i></button> </a>
<a href="/{{user.profileUsername}}/{{page+1}}"> <button class="right attached ui button"><i class="angle blue right icon"></i></button></a>
</div>
<br>
{% endif %}
</div>
<div class="ui one column grid" id="card-container">
{% if not posts %}
{% include '_empty_feed.html' %}
{% else %}
{% for post in posts %}
{% if post.isRT %}
{% include '_post.html' %}
{% else %}
{% include '_post_nort.html' %}
{% endif %}
{% endfor %}
{% endif %}
</div>
{% endblock %}

View File

@ -1,275 +1,43 @@
<head>
<link rel="stylesheet" type= "text/css" href="{{ url_for('static',filename='video-js.min.css') }}">
<script src="{{ url_for('static',filename='video.min.js') }}"></script>
<link rel="stylesheet" type= "text/css" href="{{ url_for('static',filename='quality-selector.css') }}">
<script src="{{ url_for('static',filename='videojs-quality-selector.min.js') }}"></script>
</head>
{% extends "base.html" %}
{% block content %}
<div style="width: 80%;" class="ui container">
<div style="margin-top: 2em;" class="ui one column centered grid">
<iframe id='ivplayer' width='640' height='360' src='https://{{video.instance}}/embed/{{video.id}}' style='border:none;'>
</iframe>
{% if info.error == True %}
<div class="ui center aligned text container">
<div class="ui segment">
<h3 class="ui header"><i class="times icon"></i> ERROR WITH VIDEO </h3>
<h5 class="ui header">Try to reload the page. Most times this solves the error.</h5>
<h4 class="ui header">Other reasons.</h4>
<div class="ui list">
<div class="item">
<div class="header"><i class="calendar icon"> </i>Scheduled Video</div>
Scheduled videos are not supported.
</div>
<div class="item">
<div class="header"><i class="red circle icon"> </i>Livestream video</div>
Livestream videos are not yet supported.
</div>
<div class="item">
<div class="header">Other reasons</div>
If none of the above is the case, you might have found a bug. <a href="https://github.com/ytorg/Yotter/issues/new/choose">Report it!</a>
</div>
</div>
<p>Sorry for the inconveninet. Yotter is in a Beta state, so expect errors!</p>
</div>
</div>
{% else %}
{% if info.start_time != None %}
{% elif info.is_live != None %}
<!--<div class="video-js-responsive-container vjs-hd">
<video-js id=live width="1080" class="video-js vjs-default-skin" controls>
<source
src="#"
type="application/x-mpegURL">
</video-js>
</div>-->
<div class="ui center aligned text container">
<div class="ui segment">
<h3 class="ui header"><i class="red small circle icon"></i> LIVESTREAM VIDEO</h3>
<h4 class="ui header">FEATURE AVAILABLE SOON</h4>
<h5 class="ui header">Livestreams are under developent and still not supported on Yotter.</h5>
</div>
</div>
</div>
<div style="margin-top: 2em;" class="ui one column center aligned grid">
<a href="https://{{video.instance}}/watch?v={{video.id}}"><h2 class="ui header">{{video.title}}</h2></a>
</div>
<div style="margin-top: 2em;" class="ui one column center aligned grid">
<a target="_blank" href="https://{{video.instance}}{{video.authorUrl}}" class="ui image label">
<img src="{{video.authorThumb}}">
{%if video.author.__len__() > 8%}
{{video.author[0:8]+'...'}}
{%else%}
<div class="video-js-responsive-container vjs-hd">
<video-js id="video-1" class="video-js vjs-default-skin vjs-big-play-centered"
qualitySelector
controls
autofocus
data-setup='{ "playbackRates": [0.5, 1, 1.25, 1.5, 1.75, 2] }'
width="1080"
buffered
preload="none">
{% if config.isInstance %}
{% for source in info.formats %}
<source src="{{source.url}}" type="video/{{source.ext}}" label="{{source.format_note}}">
{% endfor %}
{% endif %}
<p class="vjs-no-js">To view this video please enable JavaScript, and consider upgrading to a web browser that
<a href="http://videojs.com/html5-video-support/" target="_blank">supports HTML5 video</a></p>
</video-js>
</div>
{{video.author}}
{%endif%}
</a>
<div class="ui segments">
<div class="ui segment">
<h2 class="ui header break-word">{{info.title}}</h2>
</div>
<div class="ui horizontal segments">
<div class="center aligned ui segment">
<a href="{{ url_for('channel', id=info.channel_id)}}">
<i class="user icon"></i> <b>{{info.uploader}}</b>
</a>
<div class="label">
<i class="user icon"></i>{{info.subscriber_count}}
</div>
</div>
<div class="center aligned ui segment">
<div class="ui mini statistic">
<div class="value">
<i class="grey eye icon"></i> <b>{{info.view_count}}</b>
</div>
<div class="label">
views
</div>
</div>
</div>
<div class="center aligned ui segment">
{% if info.average_rating | int > 2.5 %}
<div class="ui mini statistic">
<div class="value">
<i class="green thumbs up icon"></i> <b>{{info.average_rating}}/5</b>
</div>
<div class="label">
Total: {{info.total_likes}} votes
</div>
</div>
{% else %}
<div class="ui mini statistic">
<div class="value">
<i class="red thumbs down icon"></i> <b>{{info.average_rating}}/5</b>
</div>
<div class="label">
Total: {{info.total_likes}} votes
</div>
</div>
{% endif %}
</div>
</div>
<div class="ui label">
<i class="eye icon"></i> {{video.viewCount}}
</div>
<div class="ui raised center aligned segment break-word">
<p><i class="grey music icon"></i><b>Audio Only</b></p>
<audio controls>
{% for format in info.audio_formats %}
<source src="{{format.url}}">
{%endfor%}
No audio available.
</audio>
</div>
<div class="ui label">
<i class="thumbs up green icon"></i> {{video.likeCount}}
</div>
<div class="ui raised segment break-word">
<p>{{info.description}}</p>
</div>
</div>
<div class="ui label">
<i class="thumbs down red icon"></i> {{video.dislikeCount}}
</div>
</div>
{%if videocomments%}
<div class="ui comments">
<h3 class="ui dividing header">Comments</h3>
{% for comment in videocomments %}
{% include '_video_comment.html' %}
{% endfor %}
</div>
{%endif%}
{% if info.live %}
<script src="{{ url_for('static',filename='videojs-http-streaming.min.js')}}"></script>
<script>
var player = videojs('live');
player.play();
</script>
{% endif %}
{%endif%}
<!-- SETUP QUALITY SELECTOR -->
<script>
videojs("video-1", {}, function() {
var player = this;
player.controlBar.addChild('QualitySelector');
});
</script>
<!-- SETUP CONTROL HOTKEYS -->
<script src="{{ url_for('static',filename='videojs.hotkeys.min.js') }}"></script>
<script>
// initialize the plugin
videojs('video-1').ready(function() {
this.hotkeys({
volumeStep: 0.1,
seekStep: 5,
enableMute: true,
enableFullscreen: true,
enableNumbers: false,
enableVolumeScroll: true,
enableHoverScroll: true,
// Mimic VLC seek behavior, and default to 5.
seekStep: function(e) {
if (e.ctrlKey && e.altKey) {
return 5*60;
} else if (e.ctrlKey) {
return 60;
} else if (e.altKey) {
return 10;
} else {
return 5;
}
},
// Enhance existing simple hotkey with a complex hotkey
fullscreenKey: function(e) {
// fullscreen with the F key or Ctrl+Enter
return ((e.which === 70) || (e.ctrlKey && e.which === 13));
},
// Custom Keys
customKeys: {
// Add new simple hotkey
simpleKey: {
key: function(e) {
// Toggle something with S Key
return (e.which === 83);
},
handler: function(player, options, e) {
// Example
if (player.paused()) {
player.play();
} else {
player.pause();
}
}
},
// Add new complex hotkey
complexKey: {
key: function(e) {
// Toggle something with CTRL + D Key
return (e.ctrlKey && e.which === 68);
},
handler: function(player, options, event) {
// Example
if (options.enableMute) {
player.muted(!player.muted());
}
}
},
// Override number keys example from https://github.com/ctd1500/videojs-hotkeys/pull/36
numbersKey: {
key: function(event) {
// Override number keys
return ((event.which > 47 && event.which < 59) || (event.which > 95 && event.which < 106));
},
handler: function(player, options, event) {
// Do not handle if enableModifiersForNumbers set to false and keys are Ctrl, Cmd or Alt
if (options.enableModifiersForNumbers || !(event.metaKey || event.ctrlKey || event.altKey)) {
var sub = 48;
if (event.which > 95) {
sub = 96;
}
var number = event.which - sub;
player.currentTime(player.duration() * number * 0.1);
}
}
},
emptyHotkey: {
// Empty
},
withoutKey: {
handler: function(player, options, event) {
console.log('withoutKey handler');
}
},
withoutHandler: {
key: function(e) {
return true;
}
},
malformedKey: {
key: function() {
console.log('I have a malformed customKey. The Key function must return a boolean.');
},
handler: function(player, options, event) {
//Empty
}
}
}
});
});
</script>
<div style="margin-top: 2em;" class="ui one column center aligned grid">
<div style="margin-bottom: 2em;" class="ui comments">
<h3 class="ui dividing header">Description</h3>
{{video.description}}
</div>
</div>
{% endblock %}

View File

@ -1,23 +0,0 @@
{% extends "base.html" %}
{% block content %}
<div style="padding: 1.3em;" class="ui one column centered grid">
<a href="{{ url_for('ytfollowing') }}"><div class="ui small red statistic">
<div class="value">
{{ followCount }}
</div>
<div class="label">
Following
</div>
</div></a>
</div>
{% if videos %}
<div class="ui centered cards">
{% for video in videos %}
{% include '_video_item.html' %}
{% endfor %}
</div>
{% else %}
{% include '_empty_feed.html' %}
{% endif %}
{% endblock %}

View File

@ -1,35 +0,0 @@
{% extends "base.html" %}
{% block content %}
<div style="padding: 1.3em;" class="ui one column centered grid">
<a href="{{ url_for('ytfollowing') }}"><div class="ui red statistic">
<div class="value">
{{ channelCount }}
</div>
<div class="label">
Following
</div>
</div></a>
</div>
<div class="ui text container">
<div class="ui relaxed divided list">
{% for channel in channelList %}
<div class="item">
<div class="right floated content">
<p>
<form action="{{ url_for('ytunfollow', channelId=channel.channelId) }}" method="post">
{{ form.hidden_tag() }}
{{ form.submit(value='Unfollow') }}
</form>
</p>
</div>
<div class="content">
<a href="{{ url_for('channel',id=channel.channelId)}}" class="header">{{channel.channelName}}</a>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}

View File

@ -1,97 +1,77 @@
{% extends "base.html" %}
{% block content %}
<div class="ui center aligned text container">
<form action="{{url_for('ytsearch', _method='GET')}}">
<div class="ui search">
<input class="prompt" name="q" type="text" placeholder="Search..." autofocus>
<select name="s" id="sort">
<option value="0">Relevance</option>
<option value="3">Views</option>
<option value="2">Date</option>
<option value="1">Rating</option>
</select>
</div>
<div class="ui one column centered grid">
<form class="ui form" action="" method="post" novalidate>
{{ form.hidden_tag() }}
<p>
{{ form.channelId.label }}<br>
{{ form.channelId(size=32) }}<br>
{% for error in form.channelId.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>{{ form.submit() }}</p>
</form>
</div>
<div class="ui text container">
<div class="ui one column middle aligned grid">
<div class="ui message">
<div class="header">
Tip: Videos are shown below channels.
</div>
<p>Just scroll down!</p>
</div>
</div>
{% if results %}
{% if results.channels %}
<h3 class="ui dividing header">Users</h3>
{% endif %}
<div class="ui relaxed divided list">
{% for res in results.channels %}
<div class="item">
<div class="image">
{% if config.isInstance %}
<img src="{{res.thumbnail}}" alt="Avatar">
{% else %}
<img alt="Avatar" src="{{ url_for('img', url=res.thumbnail) }}">
{% endif %}
</div>
<div class="content">
<a class = "header" href="{{ url_for('channel', id=res.channelId)}}">{{res.username}}</a>
<div class="meta">
<span>{{res.description}}</span>
</div>
<div class="description">
<p></p>
</div>
<div class="extra">
<div class="ui label">
<i class="user icon"></i> {{res.suscribers}}
</div>
<div class="ui label">
<i class="video icon"></i> {{res.videos}}
</div>
{% if restricted or current_user.is_authenticated %}
<div class="right floated content">
{% if not current_user.is_following_yt(res.channelId) %}
<form action="{{ url_for('ytfollow', channelId=res.channelId) }}" method="post">
{{ btform.hidden_tag() }}
{{ btform.submit(value='Follow') }}
</form>
{% else %}
<form action="{{ url_for('ytunfollow', channelId=res.channelId) }}" method="post">
{{ btform.hidden_tag() }}
{{ btform.submit(value='Unfollow') }}
</form>
{% endif %}
</div>
{% endif %}
</div>
</div>
<div class="ui one column centered grid">
<div class="ui middle aligned divided list">
<h3 class="ui dividing header">Users</h3>
{% for res in results %}
<div class="item">
<div class="right floated content">
{% if not current_user.is_following_yt(res.channelId) %}
<p>
<form action="{{ url_for('ytfollow', channelId=res.channelId) }}" method="post">
{{ btform.hidden_tag() }}
{{ btform.submit(value='Follow') }}
</form>
</p>
{% else %}
<p>
<form action="{{ url_for('ytunfollow', channelId=res.channelId) }}" method="post">
{{ btform.hidden_tag() }}
{{ btform.submit(value='Unfollow') }}
</form>
</p>
{% endif %}
</div>
<img class="ui avatar image" src="{{ res.thumbnail }}">
<div class="content">
{{res.username}}
<div class="ui label">
<i class="user icon"></i> {{res.subCount}}
</div>
</div>
</div>
{% endfor %}
</div>
<div class="ui middle aligned divided list">
<h3 class="ui dividing header">Videos</h3>
{% if videos %}
<div class="ui centered cards">
{% for video in videos %}
{% include '_video_item.html' %}
{% endfor %}
</div>
{% else %}
{% include '_empty_feed.html' %}
{% endif %}
<div class="ui middle aligned divided list">
{% if results.videos %}
<h3 class="ui dividing header">Videos</h3>
<div class="ui centered cards">
{% for video in results.videos %}
{% include '_video_item.html' %}
{% endfor %}
</div>
{% endif %}
</div>
{%if ppage%}
<div class="ui text container center aligned">
<a href="{{ppage}}"><button class="ui labeled icon button">
<i class="left arrow icon"></i>
Prev
</button></a>
<a href="{{npage}}"><button class="ui right labeled icon button">
<i class="right arrow icon"></i>
Next
</button></a>
</div>
</div>
{%endif%}
</div>
{% endif %}
</div>
{% endblock %}

45
app/tests.py Normal file
View File

@ -0,0 +1,45 @@
from datetime import datetime, timedelta
import unittest
from app import app, db
from app.models import User, Post
class UserModelCase(unittest.TestCase):
def setUp(self):
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
def test_password_hashing(self):
u = User(username='susan')
u.set_password('cat')
self.assertFalse(u.check_password('dog'))
self.assertTrue(u.check_password('cat'))
def test_follow(self):
u1 = User(username='john', email='john@example.com')
u2 = User(username='Snowden', realUser=False)
db.session.add(u1)
db.session.add(u2)
db.session.commit()
self.assertEqual(u1.followed.all(), [])
self.assertEqual(u1.followers.all(), [])
u1.follow(u2)
db.session.commit()
self.assertTrue(u1.is_following(u2))
self.assertEqual(u1.followed.count(), 1)
self.assertEqual(u1.followed.first().username, 'Snowden')
self.assertEqual(u2.followers.count(), 1)
self.assertEqual(u2.followers.first().username, 'john')
u1.unfollow(u2)
db.session.commit()
self.assertFalse(u1.is_following(u2))
self.assertEqual(u1.followed.count(), 0)
self.assertEqual(u2.followers.count(), 0)
if __name__ == '__main__':
unittest.main(verbosity=2)

View File

@ -1,8 +1,6 @@
import os
from dotenv import load_dotenv
basedir = os.path.abspath(os.path.dirname(__file__))
load_dotenv(os.path.join(basedir, '.env'))
class Config(object):
SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'

View File

@ -1,52 +0,0 @@
version: "3.8"
services:
mariadb:
image: mariadb:10.5
environment:
MYSQL_ROOT_PASSWORD: changeme
MYSQL_DATABASE: yotter
MYSQL_USER: yotter
MYSQL_PASSWORD: changeme
restart: unless-stopped
volumes:
- mysql:/var/lib/mysql
healthcheck:
test: ["CMD", "mysqladmin", "ping", "--silent"]
nginx:
image: ytorg/nginx:latest
restart: unless-stopped
environment:
HOSTNAME: 'changeme.example.com'
HTTP_PORT: 8080
YOTTER_ADDRESS: 'http://yotter:5000'
YTPROXY_ADDRESS: 'http://unix:/var/run/ytproxy/http-proxy.sock'
ports:
- "127.0.0.1:8080:8080"
volumes:
- "/var/run/ytproxy:/app/socket/"
ytproxy:
image: 1337kavin/ytproxy:latest
restart: unless-stopped
volumes:
- "/var/run/ytproxy:/app/socket/"
network_mode: host
yotter:
image: ytorg/yotter:latest
restart: unless-stopped
ports:
- "127.0.0.1:5000:5000"
environment:
DATABASE_URL: mysql+pymysql://yotter:changeme@mariadb:3306/yotter
depends_on:
- mariadb
- ytproxy
volumes:
- migrations:/usr/src/app/migrations
- ./yotter-config.json:/usr/src/app/yotter-config.json
healthcheck:
test: ["CMD", "wget" ,"--no-verbose", "--tries=1", "--spider", "http://localhost:5000"]
interval: 1m
timeout: 3s
volumes:
mysql:
migrations:

View File

@ -1,12 +0,0 @@
FROM nginx:mainline-alpine
WORKDIR /var/www
COPY ./app/static ./static
COPY ./nginx.conf.tmpl /nginx.conf.tmpl
ENV HOSTNAME= \
HTTP_PORT=80 \
YOTTER_ADDRESS=http://127.0.0.1:5000 \
YTPROXY_ADDRESS=http://unix:/var/run/ytproxy/http-proxy.sock
CMD ["/bin/sh", "-c", "envsubst '${HOSTNAME} ${HTTP_PORT} ${YOTTER_ADDRESS} ${YTPROXY_ADDRESS}' < /nginx.conf.tmpl > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'"]

View File

@ -1,10 +0,0 @@
.circleci
.git
.github
.gitignore
cache
Dockerfile
docker-compose.yml
LICENSE
*.md
dockerhash.txt

View File

@ -1,30 +0,0 @@
server {
listen ${HTTP_PORT};
server_name ${HOSTNAME};
access_log off;
location / {
proxy_pass ${YOTTER_ADDRESS};
proxy_set_header Host $host;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
location /static/ {
root /var/www;
sendfile on;
aio threads=default;
}
location ~ (^/videoplayback$|/videoplayback/|/vi/|/a/|/ytc|/vi_webp/|/sb/) {
proxy_pass ${YTPROXY_ADDRESS};
add_header Access-Control-Allow-Origin *;
sendfile on;
tcp_nopush on;
aio_write on;
aio threads=default;
directio 512;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}

View File

@ -1,107 +0,0 @@
- [user.py](#userpy)
- [feed.py](#feedpy)
- [Tweets format examples](#tweets-format-examples)
## user.py
### get_user_info(username)
Returns the info of a particular Twitter user without tweets. If the user does not exist, it returns `False`.
##### Return example:
`user.get_user_info("Snowden")`
```
{
'profileFullName': 'Edward Snowden',
'profileUsername': '@Snowden',
'profileBio': 'I used to work for the government. Now I work for the public. President at @FreedomofPress.',
'tweets': '5,009',
'following': '1',
'followers': '4.41M',
'likes': '473',
'profilePic': 'https://nitter.net/pic/profile_images%2F648888480974508032%2F66_cUYfj.jpg'
}
```
### get_tweets(user, page=1)
Returns a list with the tweets on the user feed from the specified page (default is 1).
Example usage: `user.get_tweets("Snowden")`
### get_feed_tweets(html)
This function is used by `get_tweets`. This should not be used as it is a utility function. If you want to know more, you can explore the code.
## feed.py
### get_feed(usernames, daysMaxOld=10, includeRT=True)
This function returns a chronologically ordered feed given a list of usernames (i.e ['Snowden', 'DanielMicay', 'FluffyPony']). Optional parameters are:
* `daysMaxOld`: sets the maximum number of days that the feed posts that will be returned can be.
* `includeRT`: If `False` retweets will be excluded from the feed.
## Tweets format examples:
**Normal tweet**:
```
{
'op': '@Snowden',
'twitterName': 'Edward Snowden',
'timeStamp': '2020-11-03 23:11:40',
'date': 'Nov 3',
'content': Markup('Vote. There is still time.'),
'username': '@Snowden',
'isRT': False,
'profilePic': 'https://nitter.net/pic/profile_images%2F648888480974508032%2F66_cUYfj_normal.jpg',
'url': 'https://nitter.net/Snowden/status/1323764814817218560#m'
}
```
**Retweet**:
```
{
'op': '@StellaMoris1',
'twitterName': 'Stella Moris',
'timeStamp': '2020-11-02 10:21:09',
'date': 'Nov 2',
'content': Markup("Spoke to Julian. A friend of his killed himself in the early hours of this morning. His body is still in the cell on Julian's wing. Julian is devastated.\n\nManoel Santos was gay. He'd lived in UK for 20 years. The Home Office served him with a deportation notice to Brazil.(Thread)"),
'username': ' Edward Snowden retweeted',
'isRT': True,
'profilePic': 'https://nitter.net/pic/profile_images%2F1303198488184975360%2FiH4BdNIT_normal.jpg',
'url': 'https://nitter.net/StellaMoris1/status/1323208519315849217#m'
}
```
**Tweet / Retweet with images**:
```
{
'op': '@Reuters',
'twitterName': 'Reuters',
'timeStamp': '2020-11-02 10:35:07',
'date': 'Nov 2',
'content': Markup('U.S. whistleblower Edward Snowden seeks Russian passport for sake of future son <a href="http://reut.rs/3mNZQuf">reut.rs/3mNZQuf</a>'),
'username': ' Edward Snowden retweeted',
'isRT': True,
'profilePic': 'https://nitter.net/pic/profile_images%2F1194751949821939712%2F3VBu4_Sa_normal.jpg',
'url': 'https://nitter.net/Reuters/status/1323212031978295298#m',
'attachedImages': ['https://nitter.net/pic/media%2FElz-VKLWkAAvTf8.jpg%3Fname%3Dorig']
}
```
**Tweet quoting antoher user**
```
{
'op': '@lsjourneys',
'twitterName': 'Lsjourney',
'timeStamp': '2020-10-28 21:17:09',
'date': 'Oct 28',
'content': Markup('citizenfive 👶'),
'username': ' Edward Snowden retweeted',
'isRT': True,
'profilePic': 'https://nitter.net/pic/profile_images%2F647551437875101696%2FBA2I4vuf_normal.jpg',
'url': 'https://nitter.net/lsjourneys/status/1321561665117310979#m',
'isReply': True,
'replyingTweetContent': Markup('<div class="quote-text">A long time in the making: our greatest collaboration is coming soon.</div>'),
'replyAttachedImages': ['https://nitter.net/pic/media%2FElcdC-BXgAwtT79.jpg%3Fname%3Dorig'],
'replyingUser': '@lsjourneys'
}
```
> Video is not fully supported yet. A parameter `'attachedVideo': True` is added when a video is present on the tweet.

View File

@ -1,50 +0,0 @@
from requests_futures.sessions import FuturesSession
from multiprocessing import Process
from werkzeug.datastructures import Headers
from concurrent.futures import as_completed
from numerize import numerize
from bs4 import BeautifulSoup
from operator import itemgetter, attrgetter
from re import findall
from nitter import user
import time, datetime
import requests
import bleach
import urllib
import json
import re
config = json.load(open('yotter-config.json'))
def get_feed(usernames, daysMaxOld=10, includeRT=True):
'''
Returns feed tweets given a set of usernames
'''
feedTweets = []
with FuturesSession() as session:
futures = [session.get(f'{config["nitterInstance"]}{u}') for u in usernames]
for future in as_completed(futures):
res = future.result().content.decode('utf-8')
html = BeautifulSoup(res, "html.parser")
feedPosts = user.get_feed_tweets(html)
feedTweets.append(feedPosts)
userFeed = []
for feed in feedTweets:
if not includeRT:
for tweet in feed:
if tweet['isRT']:
continue
else:
userFeed.append(tweet)
else:
userFeed+=feed
try:
for uf in userFeed:
if uf == 'emptyFeed':
userFeed.remove(uf)
userFeed.sort(key=lambda item:item['timeStamp'], reverse=True)
except:
print("Error sorting feed - nitter/feed.py")
return userFeed
return userFeed

View File

@ -1,175 +0,0 @@
from flask import Markup
from requests_futures.sessions import FuturesSession
from werkzeug.datastructures import Headers
from concurrent.futures import as_completed
from numerize import numerize
from bs4 import BeautifulSoup
from re import findall
import time, datetime
import requests
import bleach
import urllib
import json
import re
##########################
#### Config variables ####
##########################
config = json.load(open('yotter-config.json'))
config['nitterInstance']
def get_user_info(username):
response = urllib.request.urlopen(f'{config["nitterInstance"]}{username}').read()
#rssFeed = feedparser.parse(response.content)
html = BeautifulSoup(str(response), "lxml")
if html.body.find('div', attrs={'class':'error-panel'}):
return False
else:
html = html.body.find('div', attrs={'class':'profile-card'})
if html.find('a', attrs={'class':'profile-card-fullname'}):
fullName = html.find('a', attrs={'class':'profile-card-fullname'}).getText().encode('latin1').decode('unicode_escape').encode('latin1').decode('utf8')
else:
fullName = None
if html.find('div', attrs={'class':'profile-bio'}):
profileBio = html.find('div', attrs={'class':'profile-bio'}).getText().encode('latin1').decode('unicode_escape').encode('latin1').decode('utf8')
else:
profileBio = None
user = {
"profileFullName":fullName,
"profileUsername":html.find('a', attrs={'class':'profile-card-username'}).string.encode('latin_1').decode('unicode_escape').encode('latin_1').decode('utf8'),
"profileBio":profileBio,
"tweets":html.find_all('span', attrs={'class':'profile-stat-num'})[0].string,
"following":html.find_all('span', attrs={'class':'profile-stat-num'})[1].string,
"followers":numerize.numerize(int(html.find_all('span', attrs={'class':'profile-stat-num'})[2].string.replace(",",""))),
"likes":html.find_all('span', attrs={'class':'profile-stat-num'})[3].string,
"profilePic":config['nitterInstance'] + html.find('a', attrs={'class':'profile-card-avatar'})['href'][1:],
}
return user
def get_tweets(user, page=1):
feed = urllib.request.urlopen(f'{config["nitterInstance"]}{user}').read()
#Gather feedPosts
res = feed.decode('utf-8')
html = BeautifulSoup(res, "html.parser")
feedPosts = get_feed_tweets(html)
if page == 2:
nextPage = html.find('div', attrs={'class':'show-more'}).find('a')['href']
url = f'{config["nitterInstance"]}{user}{nextPage}'
print(url)
feed = urllib.request.urlopen(url).read()
res = feed.decode('utf-8')
html = BeautifulSoup(res, "html.parser")
feedPosts = get_feed_tweets(html)
return feedPosts
def yotterify(text):
URLS = ['https://youtube.com']
text = str(text)
for url in URLS:
text.replace(url, "")
return text
def get_feed_tweets(html):
feedPosts = []
if 'No items found' in str(html.body):
return 'Empty feed'
if "This account's tweets are protected." in str(html.body):
return 'Protected feed'
userFeed = html.find_all('div', attrs={'class':'timeline-item'})
if userFeed != []:
for post in userFeed[:-1]:
if 'show-more' in str(post):
continue
date_time_str = post.find('span', attrs={'class':'tweet-date'}).find('a')['title'].replace(",","")
if post.find('div', attrs={'class':'pinned'}):
if post.find('div', attrs={'class':'pinned'}).find('span', attrs={'icon-pin'}):
continue
tweet = {}
tweet['op'] = post.find('a', attrs={'class':'username'}).text
tweet['twitterName'] = post.find('a', attrs={'class':'fullname'}).text
tweet['timeStamp'] = str(datetime.datetime.strptime(date_time_str, '%d/%m/%Y %H:%M:%S'))
tweet['date'] = post.find('span', attrs={'class':'tweet-date'}).find('a').text
tweet['content'] = Markup(yotterify(post.find('div', attrs={'class':'tweet-content'}).decode_contents().replace("\n", "<br>")))
if post.find('div', attrs={'class':'retweet-header'}):
tweet['username'] = post.find('div', attrs={'class':'retweet-header'}).find('div', attrs={'class':'icon-container'}).text
tweet['isRT'] = True
else:
tweet['username'] = tweet['op']
tweet['isRT'] = False
tweet['profilePic'] = config['nitterInstance']+post.find('a', attrs={'class':'tweet-avatar'}).find('img')['src'][1:]
tweet['url'] = config['nitterInstance'] + post.find('a', attrs={'class':'tweet-link'})['href'][1:]
# Is quoting another tweet
if post.find('div', attrs={'class':'quote'}):
tweet['isReply'] = True
quote = post.find('div', attrs={'class':'quote'})
if 'unavailable' in str(quote):
tweet['unavailableReply'] = True
else:
tweet['unavailableReply'] = False
if not tweet['unavailableReply']:
if quote.find('div', attrs={'class':'quote-text'}):
try:
tweet['replyingTweetContent'] = Markup(quote.find('div', attrs={'class':'quote-text'}).replace("\n", "<br>"))
except:
tweet['replyingTweetContent'] = Markup(quote.find('div', attrs={'class':'quote-text'}))
if quote.find('a', attrs={'class':'still-image'}):
tweet['replyAttachedImages'] = []
images = quote.find_all('a', attrs={'class':'still-image'})
for img in images:
img = BeautifulSoup(str(img), "lxml")
url = config['nitterInstance'] + img.find('a')['href'][1:]
tweet['replyAttachedImages'].append(url)
tweet['replyingUser']=quote.find('a', attrs={'class':'username'}).text
post.find('div', attrs={'class':'quote'}).decompose()
else:
tweet['isReply'] = False
# Has attatchments
if post.find('div', attrs={'class':'attachments'}):
# Images
if post.find('div', attrs={'class':'attachments'}).find('a', attrs={'class':'still-image'}):
tweet['attachedImages'] = []
images = post.find('div', attrs={'class':'attachments'}).find_all('a', attrs={'class':'still-image'})
for img in images:
img = BeautifulSoup(str(img), 'lxml')
url = config['nitterInstance'] + img.find('a')['href'][1:]
tweet['attachedImages'].append(url)
else:
tweet['attachedImages'] = False
# Videos
if post.find('div', attrs={'attachments'}).find('div', attrs={'gallery-video'}):
tweet['attachedVideo'] = True
else:
tweet['attachedVideo'] = False
else:
tweet['attachedVideo'] = False
tweet['attachedImages'] = False
if post.find('div', attrs={'class':'tweet-stats'}):
stats = post.find('div', attrs={'class':'tweet-stats'}).find_all('span', attrs={'class':'tweet-stat'})
for stat in stats:
if 'comment' in str(stat):
tweet['comments'] = stat.find('div',attrs={'class':'icon-container'}).text
elif 'retweet' in str(stat):
tweet['retweets'] = stat.find('div',attrs={'class':'icon-container'}).text
elif 'heart' in str(stat):
tweet['likes'] = stat.find('div',attrs={'class':'icon-container'}).text
else:
tweet['quotes'] = stat.find('div',attrs={'class':'icon-container'}).text
feedPosts.append(tweet)
else:
return {"emptyFeed": True}
return feedPosts

View File

@ -1,46 +0,0 @@
FROM pypy:3-slim-buster AS base
# Image to Build Dependencies
FROM base AS builder
WORKDIR /usr/src/app
COPY ./requirements.txt /usr/src/app
# Build Dependencies
RUN apt-get update \
&& apt-get install -yq build-essential libssl-dev libffi-dev libxml2-dev libxslt-dev zlib1g-dev curl \
&& rm -rf /var/lib/apt/lists/* /etc/apt/sources.list.d/*
# install rust toolchain
RUN curl https://sh.rustup.rs -sSf | \
sh -s -- --default-toolchain stable -y
ENV PATH=/root/.cargo/bin:$PATH
# Python Dependencies
RUN pip install --no-warn-script-location --ignore-installed --no-cache-dir --prefix=/install wheel cryptography gunicorn pymysql
RUN pip install --no-warn-script-location --ignore-installed --no-cache-dir --prefix=/install -r requirements.txt
# Runtime Environment Image
FROM base
WORKDIR /usr/src/app
COPY --from=builder /install/bin /usr/local/bin
COPY --from=builder /install/site-packages /opt/pypy/site-packages
RUN apt-get update && apt-get install -y \
libxml2 libxslt1.1 \
&& rm -rf /var/lib/apt/lists/* /etc/apt/sources.list.d/*
COPY . .
RUN flask db init
CMD flask db stamp head \
&& flask db migrate \
&& flask db upgrade \
&& gunicorn -b 0.0.0.0:5000 -k gevent -w 4 yotter:app
EXPOSE 5000

View File

@ -1,44 +1,48 @@
alembic==1.4.3
beautifulsoup4==4.9.3
bleach==3.3.0
cachetools==4.2.0
certifi==2020.12.5
alembic==1.4.2
async-timeout==3.0.1
attrs==19.3.0
beautifulsoup4==4.9.1
bleach==3.1.5
bs4==0.0.1
certifi==2020.6.20
chardet==3.0.4
click==7.1.2
feedparser==6.0.2
defusedxml==0.6.0
dnspython==1.16.0
email-validator==1.1.1
feedparser==5.2.1
Flask==1.1.2
Flask-Caching==1.9.0
Flask-Login==0.5.0
Flask-Migrate==2.5.3
Flask-SQLAlchemy==2.4.4
Flask-SQLAlchemy==2.4.3
Flask-WTF==0.14.3
gevent==20.9.0
greenlet==0.4.17
future==0.18.2
gevent==20.6.2
greenlet==0.4.16
idna==2.10
itsdangerous==1.1.0
Jinja2==2.11.3
lxml>=4.6.3
Jinja2==2.11.2
llvmlite==0.33.0
lxml==4.5.2
Mako==1.1.3
MarkupSafe==1.1.1
numerize==0.12
packaging==20.8
multidict==4.7.6
numpy==1.19.0
packaging==20.4
PyMySQL==0.9.3
pyparsing==2.4.7
PySocks==1.7.1
python-dateutil==2.8.1
python-dotenv==0.15.0
python-dotenv==0.14.0
python-editor==1.0.4
requests==2.25.1
requests==2.24.0
requests-futures==1.0.0
sgmllib3k==1.0.0
six==1.15.0
socks==0
soupsieve==2.0.1
SQLAlchemy==1.3.22
urllib3==1.26.5
SQLAlchemy==1.3.18
urllib3==1.25.9
webencodings==0.5.1
Werkzeug==1.0.1
WTForms==2.3.3
youtube-dlc==2020.11.11.post3
youtube-search-fork==1.2.5
zope.event==4.5.0
zope.interface==5.2.0
WTForms==2.3.1
yarl==1.4.2
zope.event==4.4
zope.interface==5.1.0

View File

@ -1,15 +0,0 @@
{
"serverName": "yotter.xyz",
"nitterInstance": "https://nitter.mastodont.cat/",
"maxInstanceUsers": 200,
"serverLocation": "Germany",
"restrictPublicUsage":true,
"isInstance":true,
"maintenance_mode":false,
"show_admin_message":false,
"admin_message_title":"Message from the admin",
"admin_message":"Message from the admin text",
"admin_user":"admin_username",
"max_old_user_days": 60,
"donate_url": ""
}

View File

@ -1,290 +0,0 @@
import base64
import json
import math
import re
import traceback
import urllib
import cachetools.func
import flask
import gevent
import youtube.proto as proto
from youtube import util, yt_data_extract
headers_desktop = (
('Accept', '*/*'),
('Accept-Language', 'en-US,en;q=0.5'),
('X-YouTube-Client-Name', '1'),
('X-YouTube-Client-Version', '2.20180830'),
) + util.desktop_ua
headers_mobile = (
('Accept', '*/*'),
('Accept-Language', 'en-US,en;q=0.5'),
('X-YouTube-Client-Name', '2'),
('X-YouTube-Client-Version', '2.20180830'),
) + util.mobile_ua
real_cookie = (('Cookie', 'VISITOR_INFO1_LIVE=8XihrAcN1l4'),)
generic_cookie = (('Cookie', 'VISITOR_INFO1_LIVE=ST1Ti53r4fU'),)
# SORT:
# videos:
# Popular - 1
# Oldest - 2
# Newest - 3
# playlists:
# Oldest - 2
# Newest - 3
# Last video added - 4
# view:
# grid: 0 or 1
# list: 2
def channel_ctoken_v3(channel_id, page, sort, tab, view=1):
# page > 1 doesn't work when sorting by oldest
offset = 30*(int(page) - 1)
page_token = proto.string(61, proto.unpadded_b64encode(
proto.string(1, proto.unpadded_b64encode(proto.uint(1,offset)))
))
tab = proto.string(2, tab )
sort = proto.uint(3, int(sort))
shelf_view = proto.uint(4, 0)
view = proto.uint(6, int(view))
continuation_info = proto.string(3,
proto.percent_b64encode(tab + sort + shelf_view + view + page_token)
)
channel_id = proto.string(2, channel_id )
pointless_nest = proto.string(80226972, channel_id + continuation_info)
return base64.urlsafe_b64encode(pointless_nest).decode('ascii')
def channel_ctoken_v2(channel_id, page, sort, tab, view=1):
# see https://github.com/iv-org/invidious/issues/1319#issuecomment-671732646
# page > 1 doesn't work when sorting by oldest
offset = 30*(int(page) - 1)
schema_number = {
3: 6307666885028338688,
2: 17254859483345278706,
1: 16570086088270825023,
}[int(sort)]
page_token = proto.string(61, proto.unpadded_b64encode(proto.string(1,
proto.uint(1, schema_number) + proto.string(2,
proto.string(1, proto.unpadded_b64encode(proto.uint(1,offset)))
)
)))
tab = proto.string(2, tab )
sort = proto.uint(3, int(sort))
#page = proto.string(15, str(page) )
shelf_view = proto.uint(4, 0)
view = proto.uint(6, int(view))
continuation_info = proto.string(3,
proto.percent_b64encode(tab + sort + shelf_view + view + page_token)
)
channel_id = proto.string(2, channel_id )
pointless_nest = proto.string(80226972, channel_id + continuation_info)
return base64.urlsafe_b64encode(pointless_nest).decode('ascii')
def channel_ctoken_v1(channel_id, page, sort, tab, view=1):
tab = proto.string(2, tab )
sort = proto.uint(3, int(sort))
page = proto.string(15, str(page) )
# example with shelves in videos tab: https://www.youtube.com/channel/UCNL1ZadSjHpjm4q9j2sVtOA/videos
shelf_view = proto.uint(4, 0)
view = proto.uint(6, int(view))
continuation_info = proto.string(3, proto.percent_b64encode(tab + view + sort + shelf_view + page + proto.uint(23, 0)) )
channel_id = proto.string(2, channel_id )
pointless_nest = proto.string(80226972, channel_id + continuation_info)
return base64.urlsafe_b64encode(pointless_nest).decode('ascii')
def get_channel_tab(channel_id, page="1", sort=3, tab='videos', view=1,
ctoken=None, print_status=True):
message = 'Got channel tab' if print_status else None
if not ctoken:
ctoken = channel_ctoken_v3(channel_id, page, sort, tab, view)
ctoken = ctoken.replace('=', '%3D')
# Not sure what the purpose of the key is or whether it will change
# For now it seems to be constant for the API endpoint, not dependent
# on the browsing session or channel
key = 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'
url = 'https://www.youtube.com/youtubei/v1/browse?key=' + key
data = {
'context': {
'client': {
'hl': 'en',
'gl': 'US',
'clientName': 'WEB',
'clientVersion': '2.20180830',
},
},
'continuation': ctoken,
}
content_type_header = (('Content-Type', 'application/json'),)
content = util.fetch_url(
url, headers_desktop + content_type_header,
data=json.dumps(data), debug_name='channel_tab', report_text=message)
info = yt_data_extract.extract_channel_info(json.loads(content), tab)
if info['error'] is not None:
return False
post_process_channel_info(info)
return info
# cache entries expire after 30 minutes
@cachetools.func.ttl_cache(maxsize=128, ttl=30*60)
def get_number_of_videos_channel(channel_id):
if channel_id is None:
return 1000
# Uploads playlist
playlist_id = 'UU' + channel_id[2:]
url = 'https://m.youtube.com/playlist?list=' + playlist_id + '&pbj=1'
try:
response = util.fetch_url(url, headers_mobile,
debug_name='number_of_videos', report_text='Got number of videos')
except urllib.error.HTTPError as e:
traceback.print_exc()
print("Couldn't retrieve number of videos")
return 1000
response = response.decode('utf-8')
# match = re.search(r'"numVideosText":\s*{\s*"runs":\s*\[{"text":\s*"([\d,]*) videos"', response)
match = re.search(r'"numVideosText".*?([,\d]+)', response)
if match:
return int(match.group(1).replace(',',''))
else:
return 0
channel_id_re = re.compile(r'videos\.xml\?channel_id=([a-zA-Z0-9_-]{24})"')
@cachetools.func.lru_cache(maxsize=128)
def get_channel_id(base_url):
# method that gives the smallest possible response at ~4 kb
# needs to be as fast as possible
base_url = base_url.replace('https://www', 'https://m') # avoid redirect
response = util.fetch_url(base_url + '/about?pbj=1', headers_mobile,
debug_name='get_channel_id', report_text='Got channel id').decode('utf-8')
match = channel_id_re.search(response)
if match:
return match.group(1)
return None
def get_number_of_videos_general(base_url):
return get_number_of_videos_channel(get_channel_id(base_url))
def get_channel_search_json(channel_id, query, page):
offset = proto.unpadded_b64encode(proto.uint(3, (page-1)*30))
params = proto.string(2, 'search') + proto.string(15, offset)
params = proto.percent_b64encode(params)
ctoken = proto.string(2, channel_id) + proto.string(3, params) + proto.string(11, query)
ctoken = base64.urlsafe_b64encode(proto.nested(80226972, ctoken)).decode('ascii')
key = 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8'
url = 'https://www.youtube.com/youtubei/v1/browse?key=' + key
data = {
'context': {
'client': {
'hl': 'en',
'gl': 'US',
'clientName': 'WEB',
'clientVersion': '2.20180830',
},
},
'continuation': ctoken,
}
content_type_header = (('Content-Type', 'application/json'),)
polymer_json = util.fetch_url(
url, headers_desktop + content_type_header,
data=json.dumps(data), debug_name='channel_search')
return polymer_json
def post_process_channel_info(info):
info['avatar'] = util.prefix_url(info['avatar'])
info['channel_url'] = util.prefix_url(info['channel_url'])
for item in info['items']:
util.prefix_urls(item)
util.add_extra_html_info(item)
playlist_sort_codes = {'2': "da", '3': "dd", '4': "lad"}
# youtube.com/[channel_id]/[tab]
# youtube.com/user/[username]/[tab]
# youtube.com/c/[custom]/[tab]
# youtube.com/[custom]/[tab]
def get_channel_page_general_url(base_url, tab, request, channel_id=None):
page_number = int(request.args.get('page', 1))
sort = request.args.get('sort', '3')
view = request.args.get('view', '1')
query = request.args.get('query', '')
if tab == 'videos' and channel_id:
tasks = (
gevent.spawn(get_number_of_videos_channel, channel_id),
gevent.spawn(get_channel_tab, channel_id, page_number, sort, 'videos', view)
)
gevent.joinall(tasks)
util.check_gevent_exceptions(*tasks)
number_of_videos, polymer_json = tasks[0].value, tasks[1].value
elif tab == 'videos':
tasks = (
gevent.spawn(get_number_of_videos_general, base_url),
gevent.spawn(util.fetch_url, base_url + '/videos?pbj=1&view=0', headers_desktop, debug_name='gen_channel_videos')
)
gevent.joinall(tasks)
util.check_gevent_exceptions(*tasks)
number_of_videos, polymer_json = tasks[0].value, tasks[1].value
elif tab == 'about':
polymer_json = util.fetch_url(base_url + '/about?pbj=1', headers_desktop, debug_name='gen_channel_about')
elif tab == 'playlists':
polymer_json = util.fetch_url(base_url+ '/playlists?pbj=1&view=1&sort=' + playlist_sort_codes[sort], headers_desktop, debug_name='gen_channel_playlists')
elif tab == 'search' and channel_id:
polymer_json = get_channel_search_json(channel_id, query, page_number)
elif tab == 'search':
url = base_url + '/search?pbj=1&query=' + urllib.parse.quote(query, safe='')
polymer_json = util.fetch_url(url, headers_desktop, debug_name='gen_channel_search')
else:
flask.abort(404, 'Unknown channel tab: ' + tab)
info = yt_data_extract.extract_channel_info(json.loads(polymer_json), tab)
if info['error'] is not None:
return flask.render_template('error.html', error_message = info['error'])
post_process_channel_info(info)
if tab == 'videos':
info['number_of_videos'] = number_of_videos
info['number_of_pages'] = math.ceil(number_of_videos/30)
info['header_playlist_names'] = local_playlist.get_playlist_names()
if tab in ('videos', 'playlists'):
info['current_sort'] = sort
elif tab == 'search':
info['search_box_value'] = query
info['header_playlist_names'] = local_playlist.get_playlist_names()
info['page_number'] = page_number
info['subscribed'] = subscriptions.is_subscribed(info['channel_id'])
return flask.render_template('channel.html',
parameters_dictionary = request.args,
**info
)

View File

@ -1,213 +0,0 @@
from youtube import proto
from flask import Markup as mk
import requests
import base64
import json
import re
# From: https://github.com/user234683/youtube-local/blob/master/youtube/channel.py
# SORT:
# videos:
# Popular - 1
# Oldest - 2
# Newest - 3
# playlists:
# Oldest - 2
# Newest - 3
# Last video added - 4
# view:
# grid: 0 or 1
# list: 2
headers = {
'Host': 'www.youtube.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)',
'Accept': '*/*',
'Accept-Language': 'en-US,en;q=0.5',
'X-YouTube-Client-Name': '1',
'X-YouTube-Client-Version': '2.20180418',
}
real_cookie = (('Cookie', 'VISITOR_INFO1_LIVE=8XihrAcN1l4'),)
generic_cookie = (('Cookie', 'VISITOR_INFO1_LIVE=ST1Ti53r4fU'),)
def channel_ctoken_desktop(channel_id, page, sort, tab, view=1):
# see https://github.com/iv-org/invidious/issues/1319#issuecomment-671732646
# page > 1 doesn't work when sorting by oldest
offset = 30*(int(page) - 1)
schema_number = {
3: 6307666885028338688,
2: 17254859483345278706,
1: 16570086088270825023,
}[int(sort)]
page_token = proto.string(61, proto.unpadded_b64encode(proto.string(1,
proto.uint(1, schema_number) + proto.string(2,
proto.string(1, proto.unpadded_b64encode(proto.uint(1,offset)))
)
)))
tab = proto.string(2, tab )
sort = proto.uint(3, int(sort))
#page = proto.string(15, str(page) )
shelf_view = proto.uint(4, 0)
view = proto.uint(6, int(view))
continuation_info = proto.string(3,
proto.percent_b64encode(tab + sort + shelf_view + view + page_token)
)
channel_id = proto.string(2, channel_id )
pointless_nest = proto.string(80226972, channel_id + continuation_info)
return base64.urlsafe_b64encode(pointless_nest).decode('ascii')
def channel_ctoken_mobile(channel_id, page, sort, tab, view=1):
tab = proto.string(2, tab )
sort = proto.uint(3, int(sort))
page = proto.string(15, str(page) )
# example with shelves in videos tab: https://www.youtube.com/channel/UCNL1ZadSjHpjm4q9j2sVtOA/videos
shelf_view = proto.uint(4, 0)
view = proto.uint(6, int(view))
continuation_info = proto.string( 3, proto.percent_b64encode(tab + view + sort + shelf_view + page) )
channel_id = proto.string(2, channel_id )
pointless_nest = proto.string(80226972, channel_id + continuation_info)
return base64.urlsafe_b64encode(pointless_nest).decode('ascii')
def id_or_username(string):
cidRegex = "^UC.{22}$"
if re.match(cidRegex, string):
return "channel"
else:
return "user"
def get_channel_videos_tab(content):
tabs = content['contents']['twoColumnBrowseResultsRenderer']['tabs']
for tab in tabs:
if tab['title'] != "Videos":
continue
else:
return tab
def get_video_items_from_tab(tab):
items = []
for item in tab:
try:
if item['gridVideoRenderer']:
items.append(item)
else:
continue
except KeyError:
continue
return items
def get_info_grid_video_item(item, channel=None):
item = item['gridVideoRenderer']
thumbnailOverlays = item['thumbnailOverlays']
published = ""
views = ""
isLive = False
isUpcoming = False
try:
if 'UPCOMING' in str(thumbnailOverlays):
start_time = item['upcomingEventData']['startTime']
isUpcoming = True
views = "-"
published = "Scheduled"
except KeyError:
isUpcoming = False
try:
if 'LIVE' in str(thumbnailOverlays):
isLive = True
try:
views = item['viewCountText']['simpleText']
except:
views = "Live"
try:
duration = item['lengthText']['simpleText']
except:
duration = "-"
if published != "Scheduled":
try:
published = item['publishedTimeText']['simpleText']
except KeyError:
published = "None"
except KeyError:
isUpcoming = False
isLive = False
if not isUpcoming and not isLive:
views = item['viewCountText']['simpleText']
published = item['publishedTimeText']['simpleText']
try:
duration = item['lengthText']['simpleText']
except:
duration = "?"
video = {
'videoTitle':item['title']['runs'][0]['text'],
'description':"",
'views':views,
'timeStamp':published,
'duration':duration,
'channelName':channel['username'],
'authorUrl':f"/channel/{channel['channelId']}",
'channelId':channel['channelId'],
'id':item['videoId'],
'videoUrl':f"/watch?v={item['videoId']}",
'isLive':isLive,
'isUpcoming':isUpcoming,
'videoThumb':item['thumbnail']['thumbnails'][0]['url'],
}
return video
def get_author_info_from_channel(content):
hmd = content['metadata']['channelMetadataRenderer']
cmd = content['header']['c4TabbedHeaderRenderer']
description = mk(hmd['description'])
channel = {
"channelId": cmd['channelId'],
"username": cmd['title'],
"thumbnail": f"https:{cmd['avatar']['thumbnails'][0]['url'].replace('/', '~')}",
"description":description,
"suscribers": cmd['subscriberCountText']['runs'][0]['text'].split(" ")[0],
"banner": cmd['banner']['thumbnails'][0]['url'],
}
return channel
def get_channel_info(channelId, videos=True, page=1, sort=3):
if id_or_username(channelId) == "channel":
videos = []
ciUrl = f"https://www.youtube.com/channel/{channelId}"
mainUrl = f"https://www.youtube.com/browse_ajax?ctoken={channel_ctoken_desktop(channelId, page, sort, 'videos')}"
content = json.loads(requests.get(mainUrl, headers=headers).text)
req = requests.get(ciUrl, headers=headers).text
start = (
req.index('window["ytInitialData"]')
+ len('window["ytInitialData"]')
+ 3
)
end = req.index("};", start) + 1
jsonIni = req[start:end]
data = json.loads(jsonIni)
#videosTab = get_channel_videos_tab(content)
authorInfo = get_author_info_from_channel(data)
if videos:
gridVideoItemList = get_video_items_from_tab(content[1]['response']['continuationContents']['gridContinuation']['items'])
for video in gridVideoItemList:
vid = get_info_grid_video_item(video, authorInfo)
videos.append(vid)
print({"channel":authorInfo, "videos":videos})
return {"channel":authorInfo, "videos":videos}
else:
return {"channel":authorInfo}
else:
baseUrl = f"https://www.youtube.com/user/{channelId}"

View File

@ -1,145 +0,0 @@
import base64
import json
from youtube import proto, util, yt_data_extract
from youtube.util import concat_or_none
# Here's what I know about the secret key (starting with ASJN_i)
# *The secret key definitely contains the following information (or perhaps the information is stored at youtube's servers):
# -Video id
# -Offset
# -Sort
# *If the video id or sort in the ctoken contradicts the ASJN, the response is an error. The offset encoded outside the ASJN is ignored entirely.
# *The ASJN is base64 encoded data, indicated by the fact that the character after "ASJN_i" is one of ("0", "1", "2", "3")
# *The encoded data is not valid protobuf
# *The encoded data (after the 5 or so bytes that are always the same) is indistinguishable from random data according to a battery of randomness tests
# *The ASJN in the ctoken provided by a response changes in regular intervals of about a second or two.
# *Old ASJN's continue to work, and start at the same comment even if new comments have been posted since
# *The ASJN has no relation with any of the data in the response it came from
def make_comment_ctoken(video_id, sort=0, offset=0, lc='', secret_key=''):
video_id = proto.as_bytes(video_id)
secret_key = proto.as_bytes(secret_key)
page_info = proto.string(4,video_id) + proto.uint(6, sort)
offset_information = proto.nested(4, page_info) + proto.uint(5, offset)
if secret_key:
offset_information = proto.string(1, secret_key) + offset_information
page_params = proto.string(2, video_id)
if lc:
page_params += proto.string(6, proto.percent_b64encode(proto.string(15, lc)))
result = proto.nested(2, page_params) + proto.uint(3,6) + proto.nested(6, offset_information)
return base64.urlsafe_b64encode(result).decode('ascii')
def comment_replies_ctoken(video_id, comment_id, max_results=500):
params = proto.string(2, comment_id) + proto.uint(9, max_results)
params = proto.nested(3, params)
result = proto.nested(2, proto.string(2, video_id)) + proto.uint(3,6) + proto.nested(6, params)
return base64.urlsafe_b64encode(result).decode('ascii')
mobile_headers = {
'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1',
'Accept': '*/*',
'Accept-Language': 'en-US,en;q=0.5',
'X-YouTube-Client-Name': '2',
'X-YouTube-Client-Version': '2.20180823',
}
def request_comments(ctoken, replies=False):
if replies: # let's make it use different urls for no reason despite all the data being encoded
base_url = "https://m.youtube.com/watch_comment?action_get_comment_replies=1&ctoken="
else:
base_url = "https://m.youtube.com/watch_comment?action_get_comments=1&ctoken="
url = base_url + ctoken.replace("=", "%3D") + "&pbj=1"
for i in range(0,8): # don't retry more than 8 times
content = util.fetch_url(url, headers=mobile_headers, report_text="Retrieved comments", debug_name='request_comments')
if content[0:4] == b")]}'": # random closing characters included at beginning of response for some reason
content = content[4:]
elif content[0:10] == b'\n<!DOCTYPE': # occasionally returns html instead of json for no reason
content = b''
print("got <!DOCTYPE>, retrying")
continue
break
polymer_json = json.loads(util.uppercase_escape(content.decode('utf-8')))
return polymer_json
def single_comment_ctoken(video_id, comment_id):
page_params = proto.string(2, video_id) + proto.string(6, proto.percent_b64encode(proto.string(15, comment_id)))
result = proto.nested(2, page_params) + proto.uint(3,6)
return base64.urlsafe_b64encode(result).decode('ascii')
def post_process_comments_info(comments_info):
for comment in comments_info['comments']:
comment['author_url'] = concat_or_none(
util.URL_ORIGIN, comment['author_url'])
comment['author_avatar'] = concat_or_none(
'/', comment['author_avatar'])
comment['permalink'] = concat_or_none(util.URL_ORIGIN, '/watch?v=',
comments_info['video_id'], '&lc=', comment['id'])
reply_count = comment['reply_count']
if reply_count == 0:
comment['replies_url'] = concat_or_none(util.URL_ORIGIN,
'/post_comment?parent_id=', comment['id'],
'&video_id=', comments_info['video_id'])
else:
comment['replies_url'] = concat_or_none(util.URL_ORIGIN,
'/comments?parent_id=', comment['id'],
'&video_id=', comments_info['video_id'])
if reply_count == 0:
comment['view_replies_text'] = 'Reply'
elif reply_count == 1:
comment['view_replies_text'] = '1 reply'
else:
comment['view_replies_text'] = str(reply_count) + ' replies'
if comment['like_count'] == 1:
comment['likes_text'] = '1 like'
else:
comment['likes_text'] = str(comment['like_count']) + ' likes'
if comments_info['ctoken']:
comments_info['more_comments_url'] = concat_or_none(util.URL_ORIGIN,
'/comments?ctoken=', comments_info['ctoken'])
comments_info['page_number'] = page_number = str(int(comments_info['offset']/20) + 1)
if not comments_info['is_replies']:
comments_info['sort_text'] = 'top' if comments_info['sort'] == 0 else 'newest'
comments_info['video_url'] = concat_or_none(util.URL_ORIGIN,
'/watch?v=', comments_info['video_id'])
comments_info['video_thumbnail'] = concat_or_none('/i.ytimg.com/vi/',
comments_info['video_id'], '/mqdefault.jpg')
def video_comments(video_id, sort=0, offset=0, lc='', secret_key=''):
comments_info = yt_data_extract.extract_comments_info(request_comments(make_comment_ctoken(video_id, sort, offset, lc, secret_key)))
post_process_comments_info(comments_info)
post_comment_url = util.URL_ORIGIN + "/post_comment?video_id=" + video_id
other_sort_url = util.URL_ORIGIN + '/comments?ctoken=' + make_comment_ctoken(video_id, sort=1 - sort, lc=lc)
other_sort_text = 'Sort by ' + ('newest' if sort == 0 else 'top')
comments_info['comment_links'] = [('Post comment', post_comment_url), (other_sort_text, other_sort_url)]
return comments_info
return {}

View File

@ -1,11 +0,0 @@
<SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
<ShortName>Youtube local</ShortName>
<Description>no CIA shit in the background</Description>
<InputEncoding>UTF-8</InputEncoding>
<Image width="16" height="16">data:image/x-icon;base64,AAABAAEAEBAAAAEACAAlAgAAFgAAAIlQTkcNChoKAAAADUlIRFIAAAAQAAAAEAgGAAAAH/P/YQAAAexJREFUOI2lkzFPmlEUhp/73fshtCUCRtvQkJoKMrDQJvoHnBzUhc3EH0DUQf+As6tujo4M6mTiIDp0kGiMTRojTRNSW6o12iD4YYXv3g7Qr4O0ScM7npz7vOe+J0fk83lDF7K6eQygwkdHhI+P0bYNxmBXq5RmZui5vGQgn0f7fKi7O4oLC1gPD48BP9JpnpRKJFZXcQMB3m1u4vr9NHp76d/bo39/n4/z84ROThBa4/r91OJxMKb9BSn5mskAIOt1eq6uEFpjVyrEcjk+T0+TXlzkbTZLuFDAur9/nIFRipuREQCe7+zgBgK8mZvj/fIylVTKa/6UzXKbSnnuHkA0GnwbH/cA0a0takND3IyOEiwWAXBiMYTWjzLwtvB9bAyAwMUF8ZUVPiwtYTWbHqA6PIxoNv8OMLbN3eBga9TZWYQxaKX+AJJJhOv+AyAlT0slAG6TSX5n8+zszJugkzxA4PzcK9YSCQCk42DXaq1aGwqgfT5ebG9jpMQyUjKwu8vrtbWWqxC83NjAd31NsO2uleJnX58HCJ6eEjk8BGNQAA+RCOXJScpTU2AMwnUxlkXk4ACA+2iUSKGArNeRjkMsl6M8MYHQGtHpmIxSvFpfRzoORinQGqvZBCEwQoAxfMlkaIRCnQH/o66v8Re19MavaDNLfgAAAABJRU5ErkJggg==</Image>
<Url type="text/html" method="GET" template="http://localhost:$port_number/youtube.com/search">
<Param name="query" value="{searchTerms}"/>
</Url>
<SearchForm>http://localhost:$port_number/youtube.com/search</SearchForm>
</SearchPlugin>

View File

@ -1,123 +0,0 @@
from youtube import util, yt_data_extract, proto, local_playlist
from youtube import yt_app
import base64
import urllib
import json
import string
import gevent
import math
from flask import request
import flask
def playlist_ctoken(playlist_id, offset):
offset = proto.uint(1, offset)
# this is just obfuscation as far as I can tell. It doesn't even follow protobuf
offset = b'PT:' + proto.unpadded_b64encode(offset)
offset = proto.string(15, offset)
continuation_info = proto.string( 3, proto.percent_b64encode(offset) )
playlist_id = proto.string(2, 'VL' + playlist_id )
pointless_nest = proto.string(80226972, playlist_id + continuation_info)
return base64.urlsafe_b64encode(pointless_nest).decode('ascii')
# initial request types:
# polymer_json: https://m.youtube.com/playlist?list=PLv3TTBr1W_9tppikBxAE_G6qjWdBljBHJ&pbj=1&lact=0
# ajax json: https://m.youtube.com/playlist?list=PLv3TTBr1W_9tppikBxAE_G6qjWdBljBHJ&pbj=1&lact=0 with header X-YouTube-Client-Version: 1.20180418
# continuation request types:
# polymer_json: https://m.youtube.com/playlist?&ctoken=[...]&pbj=1
# ajax json: https://m.youtube.com/playlist?action_continuation=1&ajax=1&ctoken=[...]
headers_1 = (
('Accept', '*/*'),
('Accept-Language', 'en-US,en;q=0.5'),
('X-YouTube-Client-Name', '2'),
('X-YouTube-Client-Version', '2.20180614'),
)
def playlist_first_page(playlist_id, report_text = "Retrieved playlist"):
url = 'https://m.youtube.com/playlist?list=' + playlist_id + '&pbj=1'
content = util.fetch_url(url, util.mobile_ua + headers_1, report_text=report_text, debug_name='playlist_first_page')
content = json.loads(util.uppercase_escape(content.decode('utf-8')))
return content
#https://m.youtube.com/playlist?itct=CBMQybcCIhMIptj9xJaJ2wIV2JKcCh3Idwu-&ctoken=4qmFsgI2EiRWTFBMT3kwajlBdmxWWlB0bzZJa2pLZnB1MFNjeC0tN1BHVEMaDmVnWlFWRHBEUWxFJTNE&pbj=1
def get_videos(playlist_id, page):
url = "https://m.youtube.com/playlist?ctoken=" + playlist_ctoken(playlist_id, (int(page)-1)*20) + "&pbj=1"
headers = {
'User-Agent': ' Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1',
'Accept': '*/*',
'Accept-Language': 'en-US,en;q=0.5',
'X-YouTube-Client-Name': '2',
'X-YouTube-Client-Version': '2.20180508',
}
content = util.fetch_url(url, headers, report_text="Retrieved playlist", debug_name='playlist_videos')
info = json.loads(util.uppercase_escape(content.decode('utf-8')))
return info
@yt_app.route('/playlist')
def get_playlist_page():
if 'list' not in request.args:
abort(400)
playlist_id = request.args.get('list')
page = request.args.get('page', '1')
if page == '1':
first_page_json = playlist_first_page(playlist_id)
this_page_json = first_page_json
else:
tasks = (
gevent.spawn(playlist_first_page, playlist_id, report_text="Retrieved playlist info" ),
gevent.spawn(get_videos, playlist_id, page)
)
gevent.joinall(tasks)
util.check_gevent_exceptions(*tasks)
first_page_json, this_page_json = tasks[0].value, tasks[1].value
info = yt_data_extract.extract_playlist_info(this_page_json)
if info['error']:
return flask.render_template('error.html', error_message = info['error'])
if page != '1':
info['metadata'] = yt_data_extract.extract_playlist_metadata(first_page_json)
util.prefix_urls(info['metadata'])
for item in info.get('items', ()):
util.prefix_urls(item)
util.add_extra_html_info(item)
if 'id' in item:
item['thumbnail'] = '/https://i.ytimg.com/vi/' + item['id'] + '/default.jpg'
item['url'] += '&list=' + playlist_id
if item['index']:
item['url'] += '&index=' + str(item['index'])
video_count = yt_data_extract.deep_get(info, 'metadata', 'video_count')
if video_count is None:
video_count = 40
return flask.render_template('playlist.html',
header_playlist_names = local_playlist.get_playlist_names(),
video_list = info.get('items', []),
num_pages = math.ceil(video_count/20),
parameters_dictionary = request.args,
**info['metadata']
).encode('utf-8')

View File

@ -1,129 +0,0 @@
from math import ceil
import base64
import io
def byte(n):
return bytes((n,))
def varint_encode(offset):
'''In this encoding system, for each 8-bit byte, the first bit is 1 if there are more bytes, and 0 is this is the last one.
The next 7 bits are data. These 7-bit sections represent the data in Little endian order. For example, suppose the data is
aaaaaaabbbbbbbccccccc (each of these sections is 7 bits). It will be encoded as:
1ccccccc 1bbbbbbb 0aaaaaaa
This encoding is used in youtube parameters to encode offsets and to encode the length for length-prefixed data.
See https://developers.google.com/protocol-buffers/docs/encoding#varints for more info.'''
needed_bytes = ceil(offset.bit_length()/7) or 1 # (0).bit_length() returns 0, but we need 1 in that case.
encoded_bytes = bytearray(needed_bytes)
for i in range(0, needed_bytes - 1):
encoded_bytes[i] = (offset & 127) | 128 # 7 least significant bits
offset = offset >> 7
encoded_bytes[-1] = offset & 127 # leave first bit as zero for last byte
return bytes(encoded_bytes)
def varint_decode(encoded):
decoded = 0
for i, byte in enumerate(encoded):
decoded |= (byte & 127) << 7*i
if not (byte & 128):
break
return decoded
def string(field_number, data):
data = as_bytes(data)
return _proto_field(2, field_number, varint_encode(len(data)) + data)
nested = string
def uint(field_number, value):
return _proto_field(0, field_number, varint_encode(value))
def _proto_field(wire_type, field_number, data):
''' See https://developers.google.com/protocol-buffers/docs/encoding#structure '''
return varint_encode( (field_number << 3) | wire_type) + data
def percent_b64encode(data):
return base64.urlsafe_b64encode(data).replace(b'=', b'%3D')
def unpadded_b64encode(data):
return base64.urlsafe_b64encode(data).replace(b'=', b'')
def as_bytes(value):
if isinstance(value, str):
return value.encode('utf-8')
return value
def read_varint(data):
result = 0
i = 0
while True:
try:
byte = data.read(1)[0]
except IndexError:
if i == 0:
raise EOFError()
raise Exception('Unterminated varint starting at ' + str(data.tell() - i))
result |= (byte & 127) << 7*i
if not byte & 128:
break
i += 1
return result
def read_group(data, end_sequence):
start = data.tell()
index = data.original.find(end_sequence, start)
if index == -1:
raise Exception('Unterminated group')
data.seek(index + len(end_sequence))
return data.original[start:index]
def read_protobuf(data):
data_original = data
data = io.BytesIO(data)
data.original = data_original
while True:
try:
tag = read_varint(data)
except EOFError:
break
wire_type = tag & 7
field_number = tag >> 3
if wire_type == 0:
value = read_varint(data)
elif wire_type == 1:
value = data.read(8)
elif wire_type == 2:
length = read_varint(data)
value = data.read(length)
elif wire_type == 3:
end_bytes = encode_varint((field_number << 3) | 4)
value = read_group(data, end_bytes)
elif wire_type == 5:
value = data.read(4)
else:
raise Exception("Unknown wire type: " + str(wire_type) + ", Tag: " + bytes_to_hex(succinct_encode(tag)) + ", at position " + str(data.tell()))
yield (wire_type, field_number, value)
def parse(data):
return {field_number: value for _, field_number, value in read_protobuf(data)}
def b64_to_bytes(data):
if isinstance(data, bytes):
data = data.decode('ascii')
data = data.replace("%3D", "=")
return base64.urlsafe_b64decode(data + "="*((4 - len(data)%4)%4) )

View File

@ -1,167 +0,0 @@
from youtube import proto
from youtube import utils
from flask import Markup
import urllib.parse
import requests
import base64
import json
def page_number_to_sp_parameter(page, autocorrect, sort, filters):
offset = (int(page) - 1)*20 # 20 results per page
autocorrect = proto.nested(8, proto.uint(1, 1 - int(autocorrect) ))
filters_enc = proto.nested(2, proto.uint(1, filters['time']) + proto.uint(2, filters['type']) + proto.uint(3, filters['duration']))
result = proto.uint(1, sort) + filters_enc + autocorrect + proto.uint(9, offset) + proto.string(61, b'')
return base64.urlsafe_b64encode(result).decode('ascii')
def search_by_terms(search_terms, page, autocorrect, sort, filters):
url = "https://www.youtube.com/results?search_query=" + urllib.parse.quote_plus(search_terms)
headers = {
'Host': 'www.youtube.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)',
'Accept': '*/*',
'Accept-Language': 'en-US,en;q=0.5',
'X-YouTube-Client-Name': '1',
'X-YouTube-Client-Version': '2.20180418',
}
url += "&pbj=1&sp=" + page_number_to_sp_parameter(page, autocorrect, sort, filters).replace("=", "%3D")
content = requests.get(url, headers=headers).text
info = json.loads(content)
videos = get_videos_from_search(info)
channels = get_channels_from_search(info)
results = {
"videos": videos,
"channels": channels
}
return results
def get_channels_from_search(search):
results = []
search = search[1]['response']
primaryContents = search['contents']['twoColumnSearchResultsRenderer']['primaryContents']
contents = primaryContents['sectionListRenderer']['contents']
for content in contents:
try:
items = content['itemSectionRenderer']['contents']
except:
continue
for item in items:
try:
item['channelRenderer']
channel = get_channel_renderer_item_info(item['channelRenderer'])
results.append(channel)
except KeyError:
continue
return results
def get_channel_renderer_item_info(item):
try:
suscribers = item['subscriberCountText']['simpleText'].split(" ")[0]
except:
suscribers = "?"
try:
description = utils.get_description_snippet_text(item['descriptionSnippet']['runs'])
except KeyError:
description = ""
try:
channel = {
"channelId": item['channelId'],
"username": item['title']['simpleText'],
"thumbnail": "https:{}".format(item['thumbnail']['thumbnails'][0]['url'].replace("/", "~")),
"description": Markup(str(description)),
"suscribers": suscribers,
"videos": item['videoCountText']['runs'][0]['text']
}
except KeyError:
channel = {
"channelId": item['channelId'],
"username": item['title']['simpleText'],
"avatar": item['thumbnail']['thumbnails'][0]['url'],
"suscribers": suscribers
}
return channel
def get_videos_from_search(search):
latest = []
results = []
search = search[1]['response']
primaryContents = search['contents']['twoColumnSearchResultsRenderer']['primaryContents']
contents = primaryContents['sectionListRenderer']['contents']
for content in contents:
try:
items = content['itemSectionRenderer']['contents']
except:
continue
for item in items:
try:
item['videoRenderer']
video = get_video_renderer_item_info(item['videoRenderer'])
results.append(video)
except KeyError:
continue
# Sometimes Youtube will return an empty query. Try again.
return results
def get_video_renderer_item_info(item):
published = ""
views = ""
isLive = False
isUpcoming = False
thumbnailOverlays = item['thumbnailOverlays']
try:
if 'UPCOMING' in str(thumbnailOverlays):
start_time = item['upcomingEventData']['startTime']
isUpcoming = True
views = "-"
published = "Scheduled"
except KeyError:
isUpcoming = False
try:
if 'LIVE' in str(thumbnailOverlays):
isLive = True
try:
views = item['viewCountText']['simpleText']
except:
views = "Live"
try:
duration = item['lengthText']['simpleText']
except:
duration = "-"
if published != "Scheduled":
try:
published = item['publishedTimeText']['simpleText']
except KeyError:
published = "None"
except:
isUpcoming = False
isLive = False
if not isUpcoming and not isLive:
views = item['viewCountText']['simpleText']
published = item['publishedTimeText']['simpleText']
duration = item['lengthText']['simpleText']
video = {
'videoTitle':item['title']['runs'][0]['text'],
'description':Markup(str(utils.get_description_snippet_text(item['descriptionSnippet']['runs']))),
'views':views,
'timeStamp':published,
'duration':duration,
'channelName':item['ownerText']['runs'][0]['text'],
'authorUrl':"/channel/{}".format(item['ownerText']['runs'][0]['navigationEndpoint']['browseEndpoint']['browseId']),
'channelId':item['ownerText']['runs'][0]['navigationEndpoint']['browseEndpoint']['browseId'],
'id':item['videoId'],
'videoUrl':f"/watch?v={item['videoId']}",
'isLive':isLive,
'isUpcoming':isUpcoming,
'videoThumb':item['thumbnail']['thumbnails'][0]['url'],
}
return video

View File

@ -1,396 +0,0 @@
import gzip
from youtube import yt_data_extract
try:
import brotli
have_brotli = True
except ImportError:
have_brotli = False
import urllib.parse
import re
import time
import os
import json
import gevent
import gevent.queue
import gevent.lock
# The trouble with the requests library: It ships its own certificate bundle via certifi
# instead of using the system certificate store, meaning self-signed certificates
# configured by the user will not work. Some draconian networks block TLS unless a corporate
# certificate is installed on the system. Additionally, some users install a self signed cert
# in order to use programs to modify or monitor requests made by programs on the system.
# Finally, certificates expire and need to be updated, or are sometimes revoked. Sometimes
# certificate authorites go rogue and need to be untrusted. Since we are going through Tor exit nodes,
# this becomes all the more important. A rogue CA could issue a fake certificate for accounts.google.com, and a
# malicious exit node could use this to decrypt traffic when logging in and retrieve passwords. Examples:
# https://www.engadget.com/2015/10/29/google-warns-symantec-over-certificates/
# https://nakedsecurity.sophos.com/2013/12/09/serious-security-google-finds-fake-but-trusted-ssl-certificates-for-its-domains-made-in-france/
# In the requests documentation it says:
# "Before version 2.16, Requests bundled a set of root CAs that it trusted, sourced from the Mozilla trust store.
# The certificates were only updated once for each Requests version. When certifi was not installed,
# this led to extremely out-of-date certificate bundles when using significantly older versions of Requests.
# For the sake of security we recommend upgrading certifi frequently!"
# (http://docs.python-requests.org/en/master/user/advanced/#ca-certificates)
# Expecting users to remember to manually update certifi on Linux isn't reasonable in my view.
# On windows, this is even worse since I am distributing all dependencies. This program is not
# updated frequently, and using requests would lead to outdated certificates. Certificates
# should be updated with OS updates, instead of thousands of developers of different programs
# being expected to do this correctly 100% of the time.
# There is hope that this might be fixed eventually:
# https://github.com/kennethreitz/requests/issues/2966
# Until then, I will use a mix of urllib3 and urllib.
import urllib3
import urllib3.contrib.socks
URL_ORIGIN = "/https://www.youtube.com"
connection_pool = urllib3.PoolManager(cert_reqs = 'CERT_REQUIRED')
def get_pool(use_tor):
return connection_pool
class HTTPAsymmetricCookieProcessor(urllib.request.BaseHandler):
'''Separate cookiejars for receiving and sending'''
def __init__(self, cookiejar_send=None, cookiejar_receive=None):
self.cookiejar_send = cookiejar_send
self.cookiejar_receive = cookiejar_receive
def http_request(self, request):
if self.cookiejar_send is not None:
self.cookiejar_send.add_cookie_header(request)
return request
def http_response(self, request, response):
if self.cookiejar_receive is not None:
self.cookiejar_receive.extract_cookies(response, request)
return response
https_request = http_request
https_response = http_response
class FetchError(Exception):
def __init__(self, code, reason='', ip=None):
Exception.__init__(self, 'HTTP error during request: ' + code + ' ' + reason)
self.code = code
self.reason = reason
self.ip = ip
def decode_content(content, encoding_header):
encodings = encoding_header.replace(' ', '').split(',')
for encoding in reversed(encodings):
if encoding == 'identity':
continue
if encoding == 'br':
content = brotli.decompress(content)
elif encoding == 'gzip':
content = gzip.decompress(content)
return content
def fetch_url_response(url, headers=(), timeout=15, data=None,
cookiejar_send=None, cookiejar_receive=None,
use_tor=True, max_redirects=None):
'''
returns response, cleanup_function
When cookiejar_send is set to a CookieJar object,
those cookies will be sent in the request (but cookies in response will not be merged into it)
When cookiejar_receive is set to a CookieJar object,
cookies received in the response will be merged into the object (nothing will be sent from it)
When both are set to the same object, cookies will be sent from the object,
and response cookies will be merged into it.
'''
headers = dict(headers) # Note: Calling dict() on a dict will make a copy
if have_brotli:
headers['Accept-Encoding'] = 'gzip, br'
else:
headers['Accept-Encoding'] = 'gzip'
# prevent python version being leaked by urllib if User-Agent isn't provided
# (urllib will use ex. Python-urllib/3.6 otherwise)
if 'User-Agent' not in headers and 'user-agent' not in headers and 'User-agent' not in headers:
headers['User-Agent'] = 'Python-urllib'
method = "GET"
if data is not None:
method = "POST"
if isinstance(data, str):
data = data.encode('utf-8')
elif not isinstance(data, bytes):
data = urllib.parse.urlencode(data).encode('utf-8')
if cookiejar_send is not None or cookiejar_receive is not None: # Use urllib
req = urllib.request.Request(url, data=data, headers=headers)
cookie_processor = HTTPAsymmetricCookieProcessor(cookiejar_send=cookiejar_send, cookiejar_receive=cookiejar_receive)
opener = urllib.request.build_opener(cookie_processor)
response = opener.open(req, timeout=timeout)
cleanup_func = (lambda r: None)
else: # Use a urllib3 pool. Cookies can't be used since urllib3 doesn't have easy support for them.
# default: Retry.DEFAULT = Retry(3)
# (in connectionpool.py in urllib3)
# According to the documentation for urlopen, a redirect counts as a
# retry. So there are 3 redirects max by default.
if max_redirects:
retries = urllib3.Retry(3+max_redirects, redirect=max_redirects)
else:
retries = urllib3.Retry(3)
pool = get_pool(use_tor)
response = pool.request(method, url, headers=headers, body=data,
timeout=timeout, preload_content=False,
decode_content=False, retries=retries)
cleanup_func = (lambda r: r.release_conn())
return response, cleanup_func
def fetch_url(url, headers=(), timeout=15, report_text=None, data=None,
cookiejar_send=None, cookiejar_receive=None, use_tor=True,
debug_name=None):
start_time = time.time()
response, cleanup_func = fetch_url_response(
url, headers, timeout=timeout, data=data,
cookiejar_send=cookiejar_send, cookiejar_receive=cookiejar_receive,
use_tor=use_tor)
response_time = time.time()
content = response.read()
read_finish = time.time()
cleanup_func(response) # release_connection for urllib3
if (response.status == 429
and content.startswith(b'<!DOCTYPE')
and b'Our systems have detected unusual traffic' in content):
ip = re.search(br'IP address: ((?:[\da-f]*:)+[\da-f]+|(?:\d+\.)+\d+)',
content)
ip = ip.group(1).decode('ascii') if ip else None
raise FetchError('429', reason=response.reason, ip=ip)
elif response.status >= 400:
raise FetchError(str(response.status), reason=response.reason, ip=None)
if report_text:
print(report_text, ' Latency:', round(response_time - start_time,3), ' Read time:', round(read_finish - response_time,3))
content = decode_content(content, response.getheader('Content-Encoding', default='identity'))
return content
def head(url, use_tor=False, report_text=None, max_redirects=10):
pool = get_pool(use_tor)
start_time = time.time()
# default: Retry.DEFAULT = Retry(3)
# (in connectionpool.py in urllib3)
# According to the documentation for urlopen, a redirect counts as a retry
# So there are 3 redirects max by default. Let's change that
# to 10 since googlevideo redirects a lot.
retries = urllib3.Retry(3+max_redirects, redirect=max_redirects,
raise_on_redirect=False)
headers = {'User-Agent': 'Python-urllib'}
response = pool.request('HEAD', url, headers=headers, retries=retries)
if report_text:
print(report_text, ' Latency:', round(time.time() - start_time,3))
return response
mobile_user_agent = 'Mozilla/5.0 (Linux; Android 7.0; Redmi Note 4 Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Mobile Safari/537.36'
mobile_ua = (('User-Agent', mobile_user_agent),)
desktop_user_agent = 'Mozilla/5.0 (Windows NT 6.1; rv:52.0) Gecko/20100101 Firefox/52.0'
desktop_ua = (('User-Agent', desktop_user_agent),)
class RateLimitedQueue(gevent.queue.Queue):
''' Does initial_burst (def. 30) at first, then alternates between waiting waiting_period (def. 5) seconds and doing subsequent_bursts (def. 10) queries. After 5 seconds with nothing left in the queue, resets rate limiting. '''
def __init__(self, initial_burst=30, waiting_period=5, subsequent_bursts=10):
self.initial_burst = initial_burst
self.waiting_period = waiting_period
self.subsequent_bursts = subsequent_bursts
self.count_since_last_wait = 0
self.surpassed_initial = False
self.lock = gevent.lock.BoundedSemaphore(1)
self.currently_empty = False
self.empty_start = 0
gevent.queue.Queue.__init__(self)
def get(self):
self.lock.acquire() # blocks if another greenlet currently has the lock
if self.count_since_last_wait >= self.subsequent_bursts and self.surpassed_initial:
gevent.sleep(self.waiting_period)
self.count_since_last_wait = 0
elif self.count_since_last_wait >= self.initial_burst and not self.surpassed_initial:
self.surpassed_initial = True
gevent.sleep(self.waiting_period)
self.count_since_last_wait = 0
self.count_since_last_wait += 1
if not self.currently_empty and self.empty():
self.currently_empty = True
self.empty_start = time.monotonic()
item = gevent.queue.Queue.get(self) # blocks when nothing left
if self.currently_empty:
if time.monotonic() - self.empty_start >= self.waiting_period:
self.count_since_last_wait = 0
self.surpassed_initial = False
self.currently_empty = False
self.lock.release()
return item
def download_thumbnail(save_directory, video_id):
url = "https://i.ytimg.com/vi/" + video_id + "/mqdefault.jpg"
save_location = os.path.join(save_directory, video_id + ".jpg")
try:
thumbnail = fetch_url(url, report_text="Saved thumbnail: " + video_id)
except urllib.error.HTTPError as e:
print("Failed to download thumbnail for " + video_id + ": " + str(e))
return False
try:
f = open(save_location, 'wb')
except FileNotFoundError:
os.makedirs(save_directory, exist_ok = True)
f = open(save_location, 'wb')
f.write(thumbnail)
f.close()
return True
def download_thumbnails(save_directory, ids):
if not isinstance(ids, (list, tuple)):
ids = list(ids)
# only do 5 at a time
# do the n where n is divisible by 5
i = -1
for i in range(0, int(len(ids)/5) - 1 ):
gevent.joinall([gevent.spawn(download_thumbnail, save_directory, ids[j]) for j in range(i*5, i*5 + 5)])
# do the remainders (< 5)
gevent.joinall([gevent.spawn(download_thumbnail, save_directory, ids[j]) for j in range(i*5 + 5, len(ids))])
def dict_add(*dicts):
for dictionary in dicts[1:]:
dicts[0].update(dictionary)
return dicts[0]
def video_id(url):
url_parts = urllib.parse.urlparse(url)
return urllib.parse.parse_qs(url_parts.query)['v'][0]
# default, sddefault, mqdefault, hqdefault, hq720
def get_thumbnail_url(video_id):
return "/i.ytimg.com/vi/" + video_id + "/mqdefault.jpg"
def seconds_to_timestamp(seconds):
seconds = int(seconds)
hours, seconds = divmod(seconds,3600)
minutes, seconds = divmod(seconds,60)
if hours != 0:
timestamp = str(hours) + ":"
timestamp += str(minutes).zfill(2) # zfill pads with zeros
else:
timestamp = str(minutes)
timestamp += ":" + str(seconds).zfill(2)
return timestamp
def update_query_string(query_string, items):
parameters = urllib.parse.parse_qs(query_string)
parameters.update(items)
return urllib.parse.urlencode(parameters, doseq=True)
def uppercase_escape(s):
return re.sub(
r'\\U([0-9a-fA-F]{8})',
lambda m: chr(int(m.group(1), base=16)), s)
def prefix_url(url):
if url is None:
return None
url = url.lstrip('/') # some urls have // before them, which has a special meaning
return '/' + url
def left_remove(string, substring):
'''removes substring from the start of string, if present'''
if string.startswith(substring):
return string[len(substring):]
return string
def concat_or_none(*strings):
'''Concatenates strings. Returns None if any of the arguments are None'''
result = ''
for string in strings:
if string is None:
return None
result += string
return result
def prefix_urls(item):
try:
item['thumbnail'] = prefix_url(item['thumbnail'])
except KeyError:
pass
try:
item['author_url'] = prefix_url(item['author_url'])
except KeyError:
pass
def add_extra_html_info(item):
if item['type'] == 'video':
item['url'] = (URL_ORIGIN + '/watch?v=' + item['id']) if item.get('id') else None
video_info = {}
for key in ('id', 'title', 'author', 'duration'):
try:
video_info[key] = item[key]
except KeyError:
video_info[key] = ''
item['video_info'] = json.dumps(video_info)
elif item['type'] == 'playlist':
item['url'] = (URL_ORIGIN + '/playlist?list=' + item['id']) if item.get('id') else None
elif item['type'] == 'channel':
item['url'] = (URL_ORIGIN + "/channel/" + item['id']) if item.get('id') else None
def parse_info_prepare_for_html(renderer, additional_info={}):
item = yt_data_extract.extract_item_info(renderer, additional_info)
prefix_urls(item)
add_extra_html_info(item)
return item
def check_gevent_exceptions(*tasks):
for task in tasks:
if task.exception:
raise task.exception

View File

@ -1,61 +0,0 @@
import urllib
from flask import Markup
import bleach
def get_description_snippet_text(ds):
string = ""
for t in ds:
try:
if t['bold']:
text = "<b>"+t['text']+"</b>"
else:
text = t['text']
except:
text = t['text']
string = string + text
return string
def concat_texts(strings):
'''Concatenates strings. Returns None if any of the arguments are None'''
result = ''
for string in strings:
if string['text'] is None:
return None
result += string['text']
return result
def parse_comment(raw_comment):
cmnt = {}
imgHostName = urllib.parse.urlparse(raw_comment['author_avatar'][1:]).netloc
cmnt['author'] = raw_comment['author']
cmnt['thumbnail'] = raw_comment['author_avatar'].replace(f"https://{imgHostName}","")[1:] + "?host=" + imgHostName
print(cmnt['thumbnail'])
cmnt['channel'] = raw_comment['author_url']
cmnt['text'] = Markup(bleach.linkify(concat_texts(raw_comment['text']).replace("\n", "<br>")))
cmnt['date'] = raw_comment['time_published']
try:
cmnt['creatorHeart'] = raw_comment['creatorHeart']['creatorHeartRenderer']['creatorThumbnail']['thumbnails'][0][
'url']
except:
cmnt['creatorHeart'] = False
try:
cmnt['likes'] = raw_comment['like_count']
except:
cmnt['likes'] = 0
try:
cmnt['replies'] = raw_comment['reply_count']
except:
cmnt['replies'] = 0
return cmnt
def post_process_comments_info(comments_info):
comments = []
for comment in comments_info['comments']:
comments.append(parse_comment(comment))
return comments

View File

@ -1,78 +0,0 @@
from youtube_dlc import YoutubeDL
import json
options = {
'ignoreerrors': True,
'quiet': True,
'skip_download': True
}
ydl = YoutubeDL(options)
ydl.add_default_info_extractors()
config = json.load(open('yotter-config.json'))
def get_info(url):
video = {}
video['error'] = False
try:
info = ydl.extract_info(url, download=False)
except:
video['error'] = True
if info == None:
video['error'] = True
if not video['error'] and info is not None:
video['uploader'] = info['uploader']
video['uploader_id'] = info['uploader_id']
video['channel_id'] = info['channel_id']
video['upload_date'] = info['upload_date']
video['title'] = info['title']
video['thumbnails'] = info['thumbnails']
video['description'] = info['description']
video['categories'] = info['categories']
video['subtitles'] = info['subtitles']
video['duration'] = info['duration']
video['view_count'] = info['view_count']
if(info['like_count'] is None):
video['like_count'] = 0
else:
video['like_count'] = int(info['like_count'])
if(info['dislike_count'] is None):
video['dislike_count'] = 0
else:
video['dislike_count'] = int(info['dislike_count'])
video['total_likes'] = video['dislike_count'] + video['like_count']
video['average_rating'] = str(info['average_rating'])[0:4]
video['formats'] = get_video_formats(info['formats'])
video['audio_formats'] = get_video_formats(info['formats'], audio=True)
video['is_live'] = info['is_live']
video['start_time'] = info['start_time']
video['end_time'] = info['end_time']
video['series'] = info['series']
video['subscriber_count'] = info['subscriber_count']
return video
def get_video_formats(formats, audio=False):
best_formats = []
audio_formats = []
for format in formats:
if format['vcodec'] != 'none' and format['acodec'] != 'none':
# Video and Audio
if format['format_note'] == '144p':
continue
else:
best_formats.append(format)
elif format['vcodec'] == 'none' and format['acodec'] != 'none':
# Audio only
audio_formats.append(format)
else:
# Video only
continue
if audio:
return audio_formats
else:
return best_formats

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