Compare commits
42 commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
dd5353d244 | ||
![]() |
6a68241a7c | ||
![]() |
401061b7b7 | ||
![]() |
fc88b70e5e | ||
![]() |
24bfd7e5e7 | ||
![]() |
13a8983437 | ||
![]() |
8906b66cb3 | ||
![]() |
4afd963c64 | ||
![]() |
8b1d6e8a49 | ||
![]() |
5733197fdd | ||
![]() |
3a6b76374e | ||
![]() |
d632fea6a7 | ||
![]() |
660c7e600a | ||
![]() |
dee73dfa33 | ||
![]() |
7099e7ab33 | ||
![]() |
010aad4727 | ||
![]() |
192a2faa00 | ||
![]() |
5844ba629d | ||
![]() |
be3a4013db | ||
![]() |
a19f46ad18 | ||
![]() |
e60b913452 | ||
![]() |
9ba47f458f | ||
![]() |
8ea797f880 | ||
![]() |
b263234dc2 | ||
![]() |
a125b8a43e | ||
![]() |
03a87fcd23 | ||
![]() |
7b90d95a95 | ||
![]() |
634e6b6354 | ||
![]() |
a0db2144a5 | ||
![]() |
238ef73ed4 | ||
![]() |
5f37e8e8ee | ||
![]() |
2dd12756df | ||
![]() |
e2c84879d6 | ||
![]() |
977d5cfce0 | ||
![]() |
3c0cb2ecec | ||
![]() |
607b3bda4a | ||
![]() |
4a9f405947 | ||
![]() |
a9d5993b20 | ||
![]() |
dafa1ab1d5 | ||
![]() |
f5e7c6eabf | ||
![]() |
1284de8c13 | ||
![]() |
94dc7b567c |
|
@ -1,14 +0,0 @@
|
|||
{
|
||||
"name": "Rust",
|
||||
"image": "mcr.microsoft.com/devcontainers/rust:0-1-bullseye",
|
||||
"features": {
|
||||
"ghcr.io/devcontainers/features/docker-in-docker:2": {}
|
||||
},
|
||||
"portsAttributes": {
|
||||
"8080": {
|
||||
"label": "libreddit",
|
||||
"onAutoForward": "notify"
|
||||
}
|
||||
},
|
||||
"postCreateCommand": "cargo build"
|
||||
}
|
1
.gitattributes
vendored
|
@ -1 +0,0 @@
|
|||
Dockerfile.* linguist-language=Dockerfile
|
2
.github/FUNDING.yml
vendored
|
@ -1,2 +0,0 @@
|
|||
liberapay: spike
|
||||
custom: ['https://www.buymeacoffee.com/spikecodes']
|
4
.github/ISSUE_TEMPLATE/feature_parity.md
vendored
|
@ -1,6 +1,6 @@
|
|||
---
|
||||
name: ✨ Feature parity
|
||||
about: Suggest implementing a feature into Libreddit that is found in Reddit.com
|
||||
about: Suggest implementing a feature into Ferrit that is found in Reddit.com
|
||||
title: '✨ Feature parity: '
|
||||
labels: feature parity
|
||||
assignees: ''
|
||||
|
@ -12,7 +12,7 @@ assignees: ''
|
|||
A clear and concise description of what the feature is.
|
||||
-->
|
||||
|
||||
## Describe how this could be implemented into Libreddit
|
||||
## Describe how this could be implemented into Ferrit
|
||||
<!--
|
||||
A clear and concise description of what you want to happen.
|
||||
-->
|
||||
|
|
2
.github/ISSUE_TEMPLATE/feature_request.md
vendored
|
@ -1,6 +1,6 @@
|
|||
---
|
||||
name: 💡 Feature request
|
||||
about: Suggest a feature for Libreddit that is not found in Reddit
|
||||
about: Suggest a feature for Ferrit that is not found in Reddit
|
||||
title: '💡 Feature request: '
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
|
|
58
.github/workflows/main-docker.yml
vendored
|
@ -1,58 +0,0 @@
|
|||
name: Docker Build
|
||||
|
||||
on:
|
||||
push:
|
||||
paths-ignore:
|
||||
- "**.md"
|
||||
branches:
|
||||
- 'main'
|
||||
- 'master'
|
||||
|
||||
jobs:
|
||||
build-docker:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
config:
|
||||
- { platform: 'linux/amd64', tag: 'latest', dockerfile: 'Dockerfile' }
|
||||
- { platform: 'linux/arm64', tag: 'latest-arm', dockerfile: 'Dockerfile.arm' }
|
||||
- { platform: 'linux/arm/v7', tag: 'latest-armv7', dockerfile: 'Dockerfile.armv7' }
|
||||
steps:
|
||||
- name: Checkout sources
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v2
|
||||
with:
|
||||
platforms: all
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
id: buildx
|
||||
uses: docker/setup-buildx-action@v2
|
||||
with:
|
||||
version: latest
|
||||
|
||||
- name: Login to DockerHub
|
||||
uses: docker/login-action@v2
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Docker Hub Description
|
||||
uses: peter-evans/dockerhub-description@v3
|
||||
if: matrix.config.platform == 'linux/amd64'
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
repository: libreddit/libreddit
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v4
|
||||
with:
|
||||
context: .
|
||||
file: ./${{ matrix.config.dockerfile }}
|
||||
platforms: ${{ matrix.config.platform }}
|
||||
push: true
|
||||
tags: libreddit/libreddit:${{ matrix.config.tag }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
78
.github/workflows/main-rust.yml
vendored
|
@ -1,78 +0,0 @@
|
|||
name: Rust Build & Publish
|
||||
|
||||
on:
|
||||
push:
|
||||
paths-ignore:
|
||||
- "**.md"
|
||||
|
||||
branches:
|
||||
- 'main'
|
||||
- 'master'
|
||||
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout sources
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Cache Packages
|
||||
uses: Swatinem/rust-cache@v2
|
||||
|
||||
- name: Install stable toolchain
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
toolchain: stable
|
||||
|
||||
# Building actions
|
||||
- name: Build
|
||||
run: RUSTFLAGS='-C target-feature=+crt-static' cargo build --release --target x86_64-unknown-linux-gnu
|
||||
|
||||
- name: Calculate SHA512 checksum
|
||||
run: sha512sum target/x86_64-unknown-linux-gnu/release/libreddit > libreddit.sha512
|
||||
|
||||
- name: Calculate SHA256 checksum
|
||||
run: sha256sum target/x86_64-unknown-linux-gnu/release/libreddit > libreddit.sha256
|
||||
|
||||
- uses: actions/upload-artifact@v3
|
||||
name: Upload a Build Artifact
|
||||
with:
|
||||
name: libreddit
|
||||
path: |
|
||||
target/x86_64-unknown-linux-gnu/release/libreddit
|
||||
libreddit.sha512
|
||||
libreddit.sha256
|
||||
|
||||
- name: Versions
|
||||
id: version
|
||||
run: echo "VERSION=$(cargo metadata --format-version 1 --no-deps | jq .packages[0].version -r | sed 's/^/v/')" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# Publishing actions
|
||||
|
||||
- name: Publish to crates.io
|
||||
if: github.event_name == 'release'
|
||||
run: cargo publish --no-verify --token ${{ secrets.CARGO_REGISTRY_TOKEN }}
|
||||
|
||||
- name: Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
if: github.base_ref != 'master' && github.event_name == 'release'
|
||||
with:
|
||||
tag_name: ${{ steps.version.outputs.VERSION }}
|
||||
name: ${{ steps.version.outputs.VERSION }} - ${{ github.event.head_commit.message }}
|
||||
draft: true
|
||||
files: |
|
||||
target/x86_64-unknown-linux-gnu/release/libreddit
|
||||
libreddit.sha512
|
||||
libreddit.sha256
|
||||
body: |
|
||||
- ${{ github.event.head_commit.message }} ${{ github.sha }}
|
||||
generate_release_notes: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
62
.github/workflows/pull-request.yml
vendored
|
@ -1,62 +0,0 @@
|
|||
name: Pull Request
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- 'main'
|
||||
- 'master'
|
||||
|
||||
pull_request:
|
||||
branches:
|
||||
- 'main'
|
||||
- 'master'
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: cargo test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout sources
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Install stable toolchain
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
toolchain: stable
|
||||
|
||||
- name: Run cargo test
|
||||
run: cargo test
|
||||
|
||||
format:
|
||||
name: cargo fmt --all -- --check
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout sources
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Install stable toolchain with rustfmt component
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
toolchain: stable
|
||||
components: rustfmt
|
||||
|
||||
- name: Run cargo fmt
|
||||
run: cargo fmt --all -- --check
|
||||
|
||||
clippy:
|
||||
name: cargo clippy -- -D warnings
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout sources
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Install stable toolchain with clippy component
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
toolchain: stable
|
||||
components: clippy
|
||||
|
||||
- name: Run cargo clippy
|
||||
run: cargo clippy -- -D warnings
|
30
.github/workflows/rust.yml
vendored
Normal file
|
@ -0,0 +1,30 @@
|
|||
name: Rust
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "master" ]
|
||||
pull_request:
|
||||
branches: [ "master" ]
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Run formatting check
|
||||
run: cargo fmt --check
|
||||
|
||||
- name: Run cargo clippy check
|
||||
run: cargo clippy
|
||||
|
||||
- name: Build
|
||||
run: cargo build --verbose
|
||||
|
||||
- name: Run tests
|
||||
run: cargo test --verbose
|
5
.gitignore
vendored
|
@ -1,4 +1 @@
|
|||
/target
|
||||
|
||||
# Idea Files
|
||||
.idea/
|
||||
/target
|
2
.replit
|
@ -1,2 +1,2 @@
|
|||
run = "while :; do set -ex; nix-env -iA nixpkgs.unzip; curl -o./libreddit.zip -fsSL -- https://nightly.link/libreddit/libreddit/workflows/main-rust/master/libreddit.zip; unzip -n libreddit.zip; mv target/x86_64-unknown-linux-gnu/release/libreddit .; chmod +x libreddit; set +e; ./libreddit -H 63115200; sleep 1; done"
|
||||
run = "while :; do set -ex; curl -o./ferrit -fsSL -- https://github.com/ferritreader/ferrit/releases/latest/download/ferrit.x86_64-unknown-linux-gnu ; chmod +x ferrit; set +e; ./ferrit -H 63115200; sleep 1; done"
|
||||
language = "bash"
|
||||
|
|
25
CREDITS
|
@ -3,12 +3,10 @@
|
|||
accountForIssues <52367365+accountForIssues@users.noreply.github.com>
|
||||
Adrian Lebioda <adrianlebioda@gmail.com>
|
||||
alefvanoon <53198048+alefvanoon@users.noreply.github.com>
|
||||
Alexandre Iooss <erdnaxe@crans.org>
|
||||
alyaeanyx <alexandra.hollmeier@mailbox.org>
|
||||
AndreVuillemot160 <84594011+AndreVuillemot160@users.noreply.github.com>
|
||||
Andrew Kaufman <57281817+andrew-kaufman@users.noreply.github.com>
|
||||
Artemis <51862164+artemislena@users.noreply.github.com>
|
||||
arthomnix <35371030+arthomnix@users.noreply.github.com>
|
||||
Arya K <73596856+gi-yt@users.noreply.github.com>
|
||||
Austin Huang <im@austinhuang.me>
|
||||
Basti <pred2k@users.noreply.github.com>
|
||||
|
@ -17,25 +15,18 @@ BobIsMyManager <ahoumatt@yahoo.com>
|
|||
curlpipe <11898833+curlpipe@users.noreply.github.com>
|
||||
dacousb <53299044+dacousb@users.noreply.github.com>
|
||||
Daniel Valentine <Daniel-Valentine@users.noreply.github.com>
|
||||
Daniel Valentine <daniel@vielle.ws>
|
||||
dbrennand <52419383+dbrennand@users.noreply.github.com>
|
||||
dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
|
||||
Diego Magdaleno <38844659+DiegoMagdaleno@users.noreply.github.com>
|
||||
domve <domve@posteo.net>
|
||||
Dyras <jevwmguf@duck.com>
|
||||
Edward <101938856+EdwardLangdon@users.noreply.github.com>
|
||||
elliot <75391956+ellieeet123@users.noreply.github.com>
|
||||
erdnaxe <erdnaxe@users.noreply.github.com>
|
||||
Esmail EL BoB <github.defilable@simplelogin.co>
|
||||
FireMasterK <20838718+FireMasterK@users.noreply.github.com>
|
||||
George Roubos <cowkingdom@hotmail.com>
|
||||
git-bruh <e817509a-8ee9-4332-b0ad-3a6bdf9ab63f@aleeas.com>
|
||||
gmnsii <95436780+gmnsii@users.noreply.github.com>
|
||||
guaddy <67671414+guaddy@users.noreply.github.com>
|
||||
Harsh Mishra <erbeusgriffincasper@gmail.com>
|
||||
igna <igna@intent.cool>
|
||||
imabritishcow <bcow@protonmail.com>
|
||||
Johannes Schleifenbaum <johannes@js-webcoding.de>
|
||||
Josiah <70736638+fres7h@users.noreply.github.com>
|
||||
JPyke3 <pyke.jacob1@gmail.com>
|
||||
Kavin <20838718+FireMasterK@users.noreply.github.com>
|
||||
|
@ -43,14 +34,10 @@ Kazi <kzshantonu@users.noreply.github.com>
|
|||
Kieran <42723993+EnderDev@users.noreply.github.com>
|
||||
Kieran <kieran@dothq.co>
|
||||
Kyle Roth <kylrth@gmail.com>
|
||||
laazyCmd <laazy.pr00gramming@protonmail.com>
|
||||
Laurențiu Nicola <lnicola@users.noreply.github.com>
|
||||
Lena <102762572+MarshDeer@users.noreply.github.com>
|
||||
Macic <46872282+Macic-Dev@users.noreply.github.com>
|
||||
Mario A <10923513+Midblyte@users.noreply.github.com>
|
||||
Matt <69441971+sigaloid@users.noreply.github.com>
|
||||
Matthew Crossman <matt@crossman.page>
|
||||
Matthew E <matt@matthew.science>
|
||||
Matthew Esposito <matt@matthew.science>
|
||||
Mennaruuk <52135169+Mennaruuk@users.noreply.github.com>
|
||||
mikupls <93015331+mikupls@users.noreply.github.com>
|
||||
Nainar <nainar.mb@gmail.com>
|
||||
|
@ -58,13 +45,8 @@ Nathan Moos <moosingin3space@gmail.com>
|
|||
Nicholas Christopher <nchristopher@tuta.io>
|
||||
Nick Lowery <ClockVapor@users.noreply.github.com>
|
||||
Nico <github@dr460nf1r3.org>
|
||||
NKIPSC <15067635+NKIPSC@users.noreply.github.com>
|
||||
o69mar <119129086+o69mar@users.noreply.github.com>
|
||||
obeho <71698631+obeho@users.noreply.github.com>
|
||||
obscurity <z@x4.pm>
|
||||
Om G <34579088+OxyMagnesium@users.noreply.github.com>
|
||||
pin <90570748+0323pin@users.noreply.github.com>
|
||||
potatoesAreGod <118043038+potatoesAreGod@users.noreply.github.com>
|
||||
RiversideRocks <59586759+RiversideRocks@users.noreply.github.com>
|
||||
robin <8597693+robrobinbin@users.noreply.github.com>
|
||||
Robin <8597693+robrobinbin@users.noreply.github.com>
|
||||
|
@ -72,13 +54,11 @@ robrobinbin <>
|
|||
robrobinbin <8597693+robrobinbin@users.noreply.github.com>
|
||||
robrobinbin <robindepril@gmail.com>
|
||||
Ruben Elshof <15641671+rubenelshof@users.noreply.github.com>
|
||||
Rupert Angermeier <rangermeier@users.noreply.github.com>
|
||||
Scoder12 <34356756+Scoder12@users.noreply.github.com>
|
||||
Slayer <51095261+GhostSlayer@users.noreply.github.com>
|
||||
Soheb <somoso@users.noreply.github.com>
|
||||
somini <somini@users.noreply.github.com>
|
||||
somoso <github@soheb.anonaddy.com>
|
||||
Spenser Black <spenserblack01@gmail.com>
|
||||
Spike <19519553+spikecodes@users.noreply.github.com>
|
||||
spikecodes <19519553+spikecodes@users.noreply.github.com>
|
||||
sybenx <syb@duck.com>
|
||||
|
@ -86,11 +66,8 @@ TheCultLeader666 <65368815+TheCultLeader666@users.noreply.github.com>
|
|||
TheFrenchGhosty <47571719+TheFrenchGhosty@users.noreply.github.com>
|
||||
The TwilightBlood <hwengerstickel@protonmail.com>
|
||||
tirz <36501933+tirz@users.noreply.github.com>
|
||||
Tokarak <63452145+Tokarak@users.noreply.github.com>
|
||||
Tsvetomir Bonev <invakid404@riseup.net>
|
||||
Vladislav Nepogodin <nepogodin.vlad@gmail.com>
|
||||
Walkx <walkxnl@gmail.com>
|
||||
Wichai <1482605+Chengings@users.noreply.github.com>
|
||||
wsy2220 <wsy@dogben.com>
|
||||
xatier <xatierlike@gmail.com>
|
||||
Zach <72994911+zachjmurphy@users.noreply.github.com>
|
||||
|
|
952
Cargo.lock
generated
50
Cargo.toml
|
@ -1,41 +1,35 @@
|
|||
[package]
|
||||
name = "libreddit"
|
||||
name = "ferrit"
|
||||
description = " Alternative private front-end to Reddit"
|
||||
license = "AGPL-3.0"
|
||||
repository = "https://github.com/spikecodes/libreddit"
|
||||
version = "0.30.1"
|
||||
authors = ["spikecodes <19519553+spikecodes@users.noreply.github.com>"]
|
||||
repository = "https://github.com/ferritreader/ferrit"
|
||||
version = "0.1.1"
|
||||
authors = ["Daniel Valentine <Daniel-Valentine@users.noreply.github.com>", "spikecodes <19519553+spikecodes@users.noreply.github.com>"]
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
askama = { version = "0.12.0", default-features = false }
|
||||
cached = "0.43.0"
|
||||
clap = { version = "4.1.1", default-features = false, features = ["std", "env"] }
|
||||
regex = "1.7.1"
|
||||
serde = { version = "1.0.152", features = ["derive"] }
|
||||
cookie = "0.17.0"
|
||||
askama = { version = "0.11.1", default-features = false }
|
||||
async-recursion = "1.0.0"
|
||||
cached = "0.40.0"
|
||||
clap = { version = "3.1.18", default-features = false, features = ["std"] }
|
||||
regex = "1.5.6"
|
||||
serde = { version = "1.0.137", features = ["derive"] }
|
||||
cookie = "0.16.0"
|
||||
futures-lite = "1.12.0"
|
||||
hyper = { version = "0.14.23", features = ["full"] }
|
||||
hyper-rustls = "0.24.0"
|
||||
percent-encoding = "2.2.0"
|
||||
hyper = { version = "0.14.19", features = ["full"] }
|
||||
hyper-rustls = "0.23.0"
|
||||
percent-encoding = "2.1.0"
|
||||
route-recognizer = "0.3.1"
|
||||
serde_json = "1.0.91"
|
||||
tokio = { version = "1.24.2", features = ["full"] }
|
||||
time = { version = "0.3.17", features = ["local-offset"] }
|
||||
url = "2.3.1"
|
||||
rust-embed = { version = "6.4.2", features = ["include-exclude"] }
|
||||
serde_json = "1.0.81"
|
||||
tokio = { version = "1.18.2", features = ["full"] }
|
||||
time = "0.3.9"
|
||||
url = "2.2.2"
|
||||
rust-embed = "6.4.0"
|
||||
libflate = "1.2.0"
|
||||
brotli = { version = "3.3.4", features = ["std"] }
|
||||
toml = "0.7.4"
|
||||
once_cell = "1.17.0"
|
||||
serde_yaml = "0.9.16"
|
||||
build_html = "2.2.0"
|
||||
toml = "0.5.9"
|
||||
once_cell = "1.16.0"
|
||||
|
||||
[dev-dependencies]
|
||||
lipsum = "0.9.0"
|
||||
lipsum = "0.8.2"
|
||||
sealed_test = "1.0.0"
|
||||
|
||||
[profile.release]
|
||||
codegen-units = 1
|
||||
lto = true
|
||||
strip = "symbols"
|
||||
|
|
12
Dockerfile
|
@ -5,7 +5,7 @@ FROM rust:alpine AS builder
|
|||
|
||||
RUN apk add --no-cache musl-dev
|
||||
|
||||
WORKDIR /libreddit
|
||||
WORKDIR /ferrit
|
||||
|
||||
COPY . .
|
||||
|
||||
|
@ -21,16 +21,16 @@ COPY --from=builder /usr/share/ca-certificates /usr/share/ca-certificates
|
|||
COPY --from=builder /etc/ssl/certs /etc/ssl/certs
|
||||
|
||||
# Copy our build
|
||||
COPY --from=builder /libreddit/target/x86_64-unknown-linux-musl/release/libreddit /usr/local/bin/libreddit
|
||||
COPY --from=builder /ferrit/target/x86_64-unknown-linux-musl/release/ferrit /usr/local/bin/ferrit
|
||||
|
||||
# Use an unprivileged user.
|
||||
RUN adduser --home /nonexistent --no-create-home --disabled-password libreddit
|
||||
USER libreddit
|
||||
RUN adduser --home /nonexistent --no-create-home --disabled-password ferrit
|
||||
USER ferrit
|
||||
|
||||
# Tell Docker to expose port 8080
|
||||
EXPOSE 8080
|
||||
|
||||
# Run a healthcheck every minute to make sure Libreddit is functional
|
||||
# Run a healthcheck every minute to make sure ferrit is functional
|
||||
HEALTHCHECK --interval=1m --timeout=3s CMD wget --spider --q http://localhost:8080/settings || exit 1
|
||||
|
||||
CMD ["libreddit"]
|
||||
CMD ["ferrit"]
|
||||
|
|
|
@ -3,22 +3,13 @@
|
|||
####################################################################################################
|
||||
FROM rust:alpine AS builder
|
||||
|
||||
RUN apk add --no-cache g++ git
|
||||
RUN apk add --no-cache g++
|
||||
|
||||
WORKDIR /usr/src/libreddit
|
||||
|
||||
# cache dependencies in their own layer
|
||||
COPY Cargo.lock Cargo.toml .
|
||||
RUN mkdir src && echo "fn main() {}" > src/main.rs && cargo install --config net.git-fetch-with-cli=true --path . && rm -rf ./src
|
||||
WORKDIR /usr/src/ferrit
|
||||
|
||||
COPY . .
|
||||
|
||||
# net.git-fetch-with-cli is specified in order to prevent a potential OOM kill
|
||||
# in low memory environments. See:
|
||||
# https://users.rust-lang.org/t/cargo-uses-too-much-memory-being-run-in-qemu/76531
|
||||
# This is tracked under issue #641. This also requires us to install git in the
|
||||
# builder.
|
||||
RUN cargo install --config net.git-fetch-with-cli=true --path .
|
||||
RUN cargo install --path .
|
||||
|
||||
####################################################################################################
|
||||
## Final image
|
||||
|
@ -30,16 +21,16 @@ COPY --from=builder /usr/share/ca-certificates /usr/share/ca-certificates
|
|||
COPY --from=builder /etc/ssl/certs /etc/ssl/certs
|
||||
|
||||
# Copy our build
|
||||
COPY --from=builder /usr/local/cargo/bin/libreddit /usr/local/bin/libreddit
|
||||
COPY --from=builder /usr/local/cargo/bin/ferrit /usr/local/bin/ferrit
|
||||
|
||||
# Use an unprivileged user.
|
||||
RUN adduser --home /nonexistent --no-create-home --disabled-password libreddit
|
||||
USER libreddit
|
||||
RUN adduser --home /nonexistent --no-create-home --disabled-password ferrit
|
||||
USER ferrit
|
||||
|
||||
# Tell Docker to expose port 8080
|
||||
EXPOSE 8080
|
||||
|
||||
# Run a healthcheck every minute to make sure Libreddit is functional
|
||||
# Run a healthcheck every minute to make sure ferrit is functional
|
||||
HEALTHCHECK --interval=1m --timeout=3s CMD wget --spider --q http://localhost:8080/settings || exit 1
|
||||
|
||||
CMD ["libreddit"]
|
||||
CMD ["ferrit"]
|
||||
|
|
|
@ -12,7 +12,7 @@ RUN apt-get update && apt-get -y install gcc-arm-linux-gnueabihf \
|
|||
|
||||
RUN rustup target add armv7-unknown-linux-musleabihf
|
||||
|
||||
WORKDIR /libreddit
|
||||
WORKDIR /ferrit
|
||||
|
||||
COPY . .
|
||||
|
||||
|
@ -28,16 +28,16 @@ COPY --from=builder /usr/share/ca-certificates /usr/share/ca-certificates
|
|||
COPY --from=builder /etc/ssl/certs /etc/ssl/certs
|
||||
|
||||
# Copy our build
|
||||
COPY --from=builder /libreddit/target/armv7-unknown-linux-musleabihf/release/libreddit /usr/local/bin/libreddit
|
||||
COPY --from=builder /ferrit/target/armv7-unknown-linux-musleabihf/release/ferrit /usr/local/bin/ferrit
|
||||
|
||||
# Use an unprivileged user.
|
||||
RUN adduser --home /nonexistent --no-create-home --disabled-password libreddit
|
||||
USER libreddit
|
||||
RUN adduser --home /nonexistent --no-create-home --disabled-password ferrit
|
||||
USER ferrit
|
||||
|
||||
# Tell Docker to expose port 8080
|
||||
EXPOSE 8080
|
||||
|
||||
# Run a healthcheck every minute to make sure Libreddit is functional
|
||||
# Run a healthcheck every minute to make sure ferrit is functional
|
||||
HEALTHCHECK --interval=1m --timeout=3s CMD wget --spider --q http://localhost:8080/settings || exit 1
|
||||
|
||||
CMD ["libreddit"]
|
||||
CMD ["ferrit"]
|
||||
|
|
298
README.md
|
@ -1,295 +1,31 @@
|
|||
# Libreddit
|
||||
# Ferrit
|
||||
|
||||
> An alternative private front-end to Reddit
|
||||
**Ferrit** is a front-end for Reddit, written in [Rust](https://www.rust-lang.org/). It is a fork of the [Libreddit project](https://github.com/spikecodes/libreddit) started by [spikecodes](https://spike.codes).
|
||||
|
||||
# ⚠️ Why do I get TOO MANY REQUESTS errors? ⚠️
|
||||
## As of July 12th, 2023, Libreddit is currently not operational as Reddit's API changes, that were designed to kill third-party apps and content scrapers who don't pay [large fees](https://www.theverge.com/2023/5/31/23743993/reddit-apollo-client-api-cost), went into effect. [Read the full announcement here.](https://github.com/libreddit/libreddit/issues/840)
|
||||
## One of the project maintainers is working towards keeping this project alive to some extent: https://github.com/libreddit/libreddit/issues/836
|
||||
## Why Ferrit?
|
||||
|
||||

|
||||
Ferrit is a fast, light, private, and secure way to browse Reddit. View the hottest takes on **/r/unpopularopinion** without having to enable Javascript or unwillingly submit any information to Reddit's servers. For more information, see the following pages on our [wiki](https://github.com/ferritreader/ferrit/wiki):
|
||||
|
||||
---
|
||||
* [FAQ/What are the advantages to using Ferrit over Reddit?](https://github.com/ferritreader/ferrit/wiki/FAQ#what-are-the-advantages-to-using-ferrit-over-reddit): what Ferrit does and why it is preferable to visiting Reddit directly
|
||||
* [FAQ/What are the disadvantages to using Ferrit over Reddit?](https://github.com/ferritreader/ferrit/wiki/FAQ#what-are-the-disadvantages-to-using-ferrit-over-reddit): what Ferrit is _not_
|
||||
* [Privacy/Reddit](https://github.com/ferritreader/ferrit/wiki/Privacy#reddit): an acounting of the data Reddit may and will collect from its visitors
|
||||
|
||||
**10-second pitch:** Libreddit is a portmanteau of "libre" (meaning freedom) and "Reddit". It is a private front-end like [Invidious](https://github.com/iv-org/invidious) but for Reddit. Browse the coldest takes of [r/unpopularopinion](https://libreddit.spike.codes/r/unpopularopinion) without being [tracked](#reddit).
|
||||
The [whole FAQ](https://github.com/ferritreader/ferrit/wiki/FAQ) may address other questions you may have about Ferrit.
|
||||
|
||||
- 🚀 Fast: written in Rust for blazing-fast speeds and memory safety
|
||||
- ☁️ Light: no JavaScript, no ads, no tracking, no bloat
|
||||
- 🕵 Private: all requests are proxied through the server, including media
|
||||
- 🔒 Secure: strong [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) prevents browser requests to Reddit
|
||||
## Instances
|
||||
|
||||
---
|
||||
Visit the [_Instances_ wiki page](https://github.com/ferritreader/ferrit/wiki/Instances) for a list of running Ferrit instances.
|
||||
|
||||
I appreciate any donations! Your support allows me to continue developing Libreddit.
|
||||
## Getting and Installing Ferrit
|
||||
|
||||
<a href="https://www.buymeacoffee.com/spikecodes" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 40px" ></a>
|
||||
<a href="https://liberapay.com/spike/donate"><img alt="Donate using Liberapay" src="https://liberapay.com/assets/widgets/donate.svg" style="height: 40px"></a>
|
||||
Visit [Building, Installation, and Deployment](https://github.com/ferritreader/ferrit/wiki/Building,-Installation,-and-Deployment) on the wiki for detailed instructions on how to obtain and set up Ferrit.
|
||||
|
||||
## Discuss
|
||||
|
||||
**Bitcoin:** `bc1qwyxjnafpu3gypcpgs025cw9wa7ryudtecmwa6y`
|
||||
You can talk with the Ferrit maintainers and other uses in the official forums. See the [_Discuss_ wiki page](https://github.com/ferritreader/ferrit/wiki/Discuss) for more information.
|
||||
|
||||
**Monero:** `45FJrEuFPtG2o7QZz2Nps77TbHD4sPqxViwbdyV9A6ktfHiWs47UngG5zXPcLoDXAc8taeuBgeNjfeprwgeXYXhN3C9tVSR`
|
||||
## Credits
|
||||
|
||||
---
|
||||
See the CREDITS file in the repository root for a list of contributors up to and including the commit of the latest release. This file is updated with each release and on occasion in between releases.
|
||||
|
||||
# Instances
|
||||
|
||||
🔗 **Want to automatically redirect Reddit links to Libreddit? Use [LibRedirect](https://github.com/libredirect/libredirect) or [Privacy Redirect](https://github.com/SimonBrazell/privacy-redirect)!**
|
||||
|
||||
[Follow this link](https://github.com/libreddit/libreddit-instances/blob/master/instances.md) for an up-to-date table of instances in Markdown format. This list is also available as [a machine-readable JSON](https://github.com/libreddit/libreddit-instances/blob/master/instances.json).
|
||||
|
||||
Both files are part of the [libreddit-instances](https://github.com/libreddit/libreddit-instances) repository. To contribute your [self-hosted instance](#deployment) to the list, see the [libreddit-instances README](https://github.com/libreddit/libreddit-instances/blob/master/README.md).
|
||||
|
||||
---
|
||||
|
||||
# About
|
||||
|
||||
Find Libreddit on 💬 [Matrix](https://matrix.to/#/#libreddit:kde.org), 🐋 [Docker](https://hub.docker.com/r/libreddit/libreddit), :octocat: [GitHub](https://github.com/libreddit/libreddit), and 🦊 [GitLab](https://gitlab.com/libreddit/libreddit).
|
||||
|
||||
## Built with
|
||||
|
||||
- [Rust](https://www.rust-lang.org/) - Programming language
|
||||
- [Hyper](https://github.com/hyperium/hyper) - HTTP server and client
|
||||
- [Askama](https://github.com/djc/askama) - Templating engine
|
||||
- [Rustls](https://github.com/ctz/rustls) - TLS library
|
||||
|
||||
## Info
|
||||
Libreddit hopes to provide an easier way to browse Reddit, without the ads, trackers, and bloat. Libreddit was inspired by other alternative front-ends to popular services such as [Invidious](https://github.com/iv-org/invidious) for YouTube, [Nitter](https://github.com/zedeus/nitter) for Twitter, and [Bibliogram](https://sr.ht/~cadence/bibliogram/) for Instagram.
|
||||
|
||||
Libreddit currently implements most of Reddit's (signed-out) functionalities but still lacks [a few features](https://github.com/libreddit/libreddit/issues).
|
||||
|
||||
## How does it compare to Teddit?
|
||||
|
||||
Teddit is another awesome open source project designed to provide an alternative frontend to Reddit. There is no connection between the two, and you're welcome to use whichever one you favor. Competition fosters innovation and Teddit's release has motivated me to build Libreddit into an even more polished product.
|
||||
|
||||
If you are looking to compare, the biggest differences I have noticed are:
|
||||
- Libreddit is themed around Reddit's redesign whereas Teddit appears to stick much closer to Reddit's old design. This may suit some users better as design is always subjective.
|
||||
- Libreddit is written in [Rust](https://www.rust-lang.org) for speed and memory safety. It uses [Hyper](https://hyper.rs), a speedy and lightweight HTTP server/client implementation.
|
||||
|
||||
---
|
||||
|
||||
# Comparison
|
||||
|
||||
This section outlines how Libreddit compares to Reddit.
|
||||
|
||||
## Speed
|
||||
|
||||
Lasted tested Nov 11, 2022.
|
||||
|
||||
Results from Google PageSpeed Insights ([Libreddit Report](https://pagespeed.web.dev/report?url=https%3A%2F%2Flibreddit.spike.codes%2F), [Reddit Report](https://pagespeed.web.dev/report?url=https://www.reddit.com)).
|
||||
|
||||
| | Libreddit | Reddit |
|
||||
|------------------------|-------------|-----------|
|
||||
| Requests | 60 | 83 |
|
||||
| Speed Index | 2.0s | 10.4s |
|
||||
| Time to Interactive | **2.8s** | **12.4s** |
|
||||
|
||||
## Privacy
|
||||
|
||||
### Reddit
|
||||
|
||||
**Logging:** According to Reddit's [privacy policy](https://www.redditinc.com/policies/privacy-policy), they "may [automatically] log information" including:
|
||||
- IP address
|
||||
- User-agent string
|
||||
- Browser type
|
||||
- Operating system
|
||||
- Referral URLs
|
||||
- Device information (e.g., device IDs)
|
||||
- Device settings
|
||||
- Pages visited
|
||||
- Links clicked
|
||||
- The requested URL
|
||||
- Search terms
|
||||
|
||||
**Location:** The same privacy policy goes on to describe that location data may be collected through the use of:
|
||||
- GPS (consensual)
|
||||
- Bluetooth (consensual)
|
||||
- Content associated with a location (consensual)
|
||||
- Your IP Address
|
||||
|
||||
**Cookies:** Reddit's [cookie notice](https://www.redditinc.com/policies/cookies) documents the array of cookies used by Reddit including/regarding:
|
||||
- Authentication
|
||||
- Functionality
|
||||
- Analytics and Performance
|
||||
- Advertising
|
||||
- Third-Party Cookies
|
||||
- Third-Party Site
|
||||
|
||||
### Libreddit
|
||||
|
||||
For transparency, I hope to describe all the ways Libreddit handles user privacy.
|
||||
|
||||
#### Server
|
||||
|
||||
* **Logging:** In production (when running the binary, hosting with docker, or using the official instances), Libreddit logs nothing. When debugging (running from source without `--release`), Libreddit logs post IDs fetched to aid with troubleshooting.
|
||||
|
||||
* **Cookies:** Libreddit uses optional cookies to store any configured settings in [the settings menu](https://libreddit.spike.codes/settings). These are not cross-site cookies and the cookies hold no personal data.
|
||||
|
||||
#### Official instance (libreddit.spike.codes)
|
||||
|
||||
The official instance is hosted at https://libreddit.spike.codes.
|
||||
|
||||
* **Server:** The official instance runs a production binary, and thus logs nothing.
|
||||
|
||||
* **DNS:** The domain for the official instance uses Cloudflare as the DNS resolver. However, this site is not proxied through Cloudflare, and thus Cloudflare doesn't have access to user traffic.
|
||||
|
||||
* **Hosting:** The official instance is hosted on [Replit](https://replit.com/), which monitors usage to prevent abuse. I can understand if this invalidates certain users' threat models, and therefore, self-hosting, using unofficial instances, and browsing through Tor are welcomed.
|
||||
|
||||
---
|
||||
|
||||
# Installation
|
||||
|
||||
## 1) Cargo
|
||||
|
||||
Make sure Rust stable is installed along with `cargo`, Rust's package manager.
|
||||
|
||||
```
|
||||
cargo install libreddit
|
||||
```
|
||||
|
||||
## 2) Docker
|
||||
|
||||
Deploy the [Docker image](https://hub.docker.com/r/libreddit/libreddit) of Libreddit:
|
||||
```
|
||||
docker pull libreddit/libreddit
|
||||
docker run -d --name libreddit -p 8080:8080 libreddit/libreddit
|
||||
```
|
||||
|
||||
Deploy using a different port (in this case, port 80):
|
||||
```
|
||||
docker pull libreddit/libreddit
|
||||
docker run -d --name libreddit -p 80:8080 libreddit/libreddit
|
||||
```
|
||||
|
||||
To deploy on `arm64` platforms, simply replace `libreddit/libreddit` in the commands above with `libreddit/libreddit:arm`.
|
||||
|
||||
To deploy on `armv7` platforms, simply replace `libreddit/libreddit` in the commands above with `libreddit/libreddit:armv7`.
|
||||
|
||||
## 3) AUR
|
||||
|
||||
For ArchLinux users, Libreddit is available from the AUR as [`libreddit-git`](https://aur.archlinux.org/packages/libreddit-git).
|
||||
|
||||
```
|
||||
yay -S libreddit-git
|
||||
```
|
||||
## 4) NetBSD/pkgsrc
|
||||
|
||||
For NetBSD users, Libreddit is available from the official repositories.
|
||||
|
||||
```
|
||||
pkgin install libreddit
|
||||
```
|
||||
|
||||
Or, if you prefer to build from source
|
||||
|
||||
```
|
||||
cd /usr/pkgsrc/libreddit
|
||||
make install
|
||||
```
|
||||
|
||||
## 5) GitHub Releases
|
||||
|
||||
If you're on Linux and none of these methods work for you, you can grab a Linux binary from [the newest release](https://github.com/libreddit/libreddit/releases/latest).
|
||||
|
||||
## 6) Replit/Heroku/Glitch
|
||||
|
||||
> **Warning**
|
||||
> These are free hosting options, but they are *not* private and will monitor server usage to prevent abuse. If you need a free and easy setup, this method may work best for you.
|
||||
|
||||
<a href="https://repl.it/github/libreddit/libreddit"><img src="https://repl.it/badge/github/libreddit/libreddit" alt="Run on Repl.it" height="32" /></a>
|
||||
[](https://heroku.com/deploy?template=https://github.com/libreddit/libreddit)
|
||||
[](https://glitch.com/edit/#!/remix/libreddit)
|
||||
|
||||
---
|
||||
|
||||
# Deployment
|
||||
|
||||
Once installed, deploy Libreddit to `0.0.0.0:8080` by running:
|
||||
|
||||
```
|
||||
libreddit
|
||||
```
|
||||
|
||||
## Instance settings
|
||||
|
||||
Assign a default value for each instance-specific setting by passing environment variables to Libreddit in the format `LIBREDDIT_{X}`. Replace `{X}` with the setting name (see list below) in capital letters.
|
||||
|
||||
| Name | Possible values | Default value | Description |
|
||||
|---------------------------|-----------------|------------------|-----------------------------------------------------------------------------------------------------------|
|
||||
| `SFW_ONLY` | `["on", "off"]` | `off` | Enables SFW-only mode for the instance, i.e. all NSFW content is filtered. |
|
||||
| `BANNER` | String | (empty) | Allows the server to set a banner to be displayed. Currently this is displayed on the instance info page. |
|
||||
| `ROBOTS_DISABLE_INDEXING` | `["on", "off"]` | `off` | Disables indexing of the instance by search engines. |
|
||||
| `PUSHSHIFT_FRONTEND` | String | `www.unddit.com` | Allows the server to set the Pushshift frontend to be used with "removed" links. |
|
||||
|
||||
## Default User Settings
|
||||
|
||||
Assign a default value for each user-modifiable setting by passing environment variables to Libreddit in the format `LIBREDDIT_DEFAULT_{Y}`. Replace `{Y}` with the setting name (see list below) in capital letters.
|
||||
|
||||
| Name | Possible values | Default value |
|
||||
|-------------------------------------|------------------------------------------------------------------------------------------------------------------------------------|---------------|
|
||||
| `THEME` | `["system", "light", "dark", "black", "dracula", "nord", "laserwave", "violet", "gold", "rosebox", "gruvboxdark", "gruvboxlight"]` | `system` |
|
||||
| `FRONT_PAGE` | `["default", "popular", "all"]` | `default` |
|
||||
| `LAYOUT` | `["card", "clean", "compact"]` | `card` |
|
||||
| `WIDE` | `["on", "off"]` | `off` |
|
||||
| `POST_SORT` | `["hot", "new", "top", "rising", "controversial"]` | `hot` |
|
||||
| `COMMENT_SORT` | `["confidence", "top", "new", "controversial", "old"]` | `confidence` |
|
||||
| `SHOW_NSFW` | `["on", "off"]` | `off` |
|
||||
| `BLUR_NSFW` | `["on", "off"]` | `off` |
|
||||
| `USE_HLS` | `["on", "off"]` | `off` |
|
||||
| `HIDE_HLS_NOTIFICATION` | `["on", "off"]` | `off` |
|
||||
| `AUTOPLAY_VIDEOS` | `["on", "off"]` | `off` |
|
||||
| `SUBSCRIPTIONS` | `+`-delimited list of subreddits (`sub1+sub2+sub3+...`) | _(none)_ |
|
||||
| `HIDE_AWARDS` | `["on", "off"]` | `off` |
|
||||
| `DISABLE_VISIT_REDDIT_CONFIRMATION` | `["on", "off"]` | `off` |
|
||||
|
||||
You can also configure Libreddit with a configuration file. An example `libreddit.toml` can be found below:
|
||||
|
||||
```toml
|
||||
LIBREDDIT_DEFAULT_WIDE = "on"
|
||||
LIBREDDIT_DEFAULT_USE_HLS = "on"
|
||||
```
|
||||
|
||||
### Examples
|
||||
|
||||
```bash
|
||||
LIBREDDIT_DEFAULT_SHOW_NSFW=on libreddit
|
||||
```
|
||||
|
||||
```bash
|
||||
LIBREDDIT_DEFAULT_WIDE=on LIBREDDIT_DEFAULT_THEME=dark libreddit -r
|
||||
```
|
||||
|
||||
## Proxying using NGINX
|
||||
|
||||
> **Note**
|
||||
> If you're [proxying Libreddit through an NGINX Reverse Proxy](https://github.com/libreddit/libreddit/issues/122#issuecomment-782226853), add
|
||||
> ```nginx
|
||||
> proxy_http_version 1.1;
|
||||
> ```
|
||||
> to your NGINX configuration file above your `proxy_pass` line.
|
||||
|
||||
## systemd
|
||||
|
||||
You can use the systemd service available in `contrib/libreddit.service`
|
||||
(install it on `/etc/systemd/system/libreddit.service`).
|
||||
|
||||
That service can be optionally configured in terms of environment variables by
|
||||
creating a file in `/etc/libreddit.conf`. Use the `contrib/libreddit.conf` as a
|
||||
template. You can also add the `LIBREDDIT_DEFAULT__{X}` settings explained
|
||||
above.
|
||||
|
||||
When "Proxying using NGINX" where the proxy is on the same machine, you should
|
||||
guarantee nginx waits for this service to start. Edit
|
||||
`/etc/systemd/system/libreddit.service.d/reverse-proxy.conf`:
|
||||
|
||||
```conf
|
||||
[Unit]
|
||||
Before=nginx.service
|
||||
```
|
||||
|
||||
## Building
|
||||
|
||||
```
|
||||
git clone https://github.com/libreddit/libreddit
|
||||
cd libreddit
|
||||
cargo run
|
||||
```
|
||||
We offer special thanks to **spikecodes** for his foundational work on the Libreddit project.
|
||||
|
|
43
app.json
|
@ -1,5 +1,5 @@
|
|||
{
|
||||
"name": "Libreddit",
|
||||
"name": "Ferrit",
|
||||
"description": "Private front-end for Reddit",
|
||||
"buildpacks": [
|
||||
{
|
||||
|
@ -11,55 +11,34 @@
|
|||
],
|
||||
"stack": "container",
|
||||
"env": {
|
||||
"LIBREDDIT_DEFAULT_THEME": {
|
||||
"FERRIT_DEFAULT_THEME": {
|
||||
"required": false
|
||||
},
|
||||
"LIBREDDIT_DEFAULT_FRONT_PAGE": {
|
||||
"FERRIT_DEFAULT_FRONT_PAGE": {
|
||||
"required": false
|
||||
},
|
||||
"LIBREDDIT_DEFAULT_LAYOUT": {
|
||||
"FERRIT_DEFAULT_LAYOUT": {
|
||||
"required": false
|
||||
},
|
||||
"LIBREDDIT_DEFAULT_WIDE": {
|
||||
"FERRIT_DEFAULT_WIDE": {
|
||||
"required": false
|
||||
},
|
||||
"LIBREDDIT_DEFAULT_COMMENT_SORT": {
|
||||
"FERRIT_DEFAULT_COMMENT_SORT": {
|
||||
"required": false
|
||||
},
|
||||
"LIBREDDIT_DEFAULT_POST_SORT": {
|
||||
"FERRIT_DEFAULT_POST_SORT": {
|
||||
"required": false
|
||||
},
|
||||
"LIBREDDIT_DEFAULT_SHOW_NSFW": {
|
||||
"FERRIT_DEFAULT_SHOW_NSFW": {
|
||||
"required": false
|
||||
},
|
||||
"LIBREDDIT_DEFAULT_BLUR_NSFW": {
|
||||
"FERRIT_DEFAULT_BLUR_NSFW": {
|
||||
"required": false
|
||||
},
|
||||
"LIBREDDIT_USE_HLS": {
|
||||
"FERRIT_USE_HLS": {
|
||||
"required": false
|
||||
},
|
||||
"LIBREDDIT_HIDE_HLS_NOTIFICATION": {
|
||||
"required": false
|
||||
},
|
||||
"LIBREDDIT_SFW_ONLY": {
|
||||
"required": false
|
||||
},
|
||||
"LIBREDDIT_DEFAULT_HIDE_AWARDS": {
|
||||
"required": false
|
||||
},
|
||||
"LIBREDDIT_BANNER": {
|
||||
"required": false
|
||||
},
|
||||
"LIBREDDIT_ROBOTS_DISABLE_INDEXING": {
|
||||
"required": false
|
||||
},
|
||||
"LIBREDDIT_DEFAULT_SUBSCRIPTIONS": {
|
||||
"required": false
|
||||
},
|
||||
"LIBREDDIT_DEFAULT_DISABLE_VISIT_REDDIT_CONFIRMATION": {
|
||||
"required": false
|
||||
},
|
||||
"LIBREDDIT_PUSHSHIFT_FRONTEND": {
|
||||
"FERRIT_HIDE_HLS_NOTIFICATION": {
|
||||
"required": false
|
||||
}
|
||||
}
|
||||
|
|
24
build.rs
|
@ -1,24 +0,0 @@
|
|||
use std::process::{Command, ExitStatus, Output};
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::os::windows::process::ExitStatusExt;
|
||||
|
||||
fn main() {
|
||||
let output = String::from_utf8(
|
||||
Command::new("git")
|
||||
.args(["rev-parse", "HEAD"])
|
||||
.output()
|
||||
.unwrap_or(Output {
|
||||
stdout: vec![],
|
||||
stderr: vec![],
|
||||
status: ExitStatus::from_raw(0),
|
||||
})
|
||||
.stdout,
|
||||
)
|
||||
.unwrap_or_default();
|
||||
let git_hash = if output == String::default() { "dev".into() } else { output };
|
||||
println!("cargo:rustc-env=GIT_HASH={git_hash}");
|
||||
}
|
2
contrib/ferrit.conf
Normal file
|
@ -0,0 +1,2 @@
|
|||
ADDRESS=0.0.0.0
|
||||
PORT=12345
|
|
@ -1,15 +1,15 @@
|
|||
[Unit]
|
||||
Description=libreddit daemon
|
||||
Description=Ferrit daemon
|
||||
After=network.service
|
||||
|
||||
[Service]
|
||||
DynamicUser=yes
|
||||
# Default Values
|
||||
#Environment=ADDRESS=0.0.0.0
|
||||
#Environment=PORT=8080
|
||||
Environment=ADDRESS=0.0.0.0
|
||||
Environment=PORT=8080
|
||||
# Optional Override
|
||||
EnvironmentFile=-/etc/libreddit.conf
|
||||
ExecStart=/usr/bin/libreddit -a ${ADDRESS} -p ${PORT}
|
||||
EnvironmentFile=-/etc/ferrit.conf
|
||||
ExecStart=/usr/bin/ferrit -a ${ADDRESS} -p ${PORT}
|
||||
|
||||
# Hardening
|
||||
DeviceAllow=
|
|
@ -1,16 +0,0 @@
|
|||
ADDRESS=0.0.0.0
|
||||
PORT=12345
|
||||
#LIBREDDIT_DEFAULT_THEME=default
|
||||
#LIBREDDIT_DEFAULT_FRONT_PAGE=default
|
||||
#LIBREDDIT_DEFAULT_LAYOUT=card
|
||||
#LIBREDDIT_DEFAULT_WIDE=off
|
||||
#LIBREDDIT_DEFAULT_POST_SORT=hot
|
||||
#LIBREDDIT_DEFAULT_COMMENT_SORT=confidence
|
||||
#LIBREDDIT_DEFAULT_SHOW_NSFW=off
|
||||
#LIBREDDIT_DEFAULT_BLUR_NSFW=off
|
||||
#LIBREDDIT_DEFAULT_USE_HLS=off
|
||||
#LIBREDDIT_DEFAULT_HIDE_HLS_NOTIFICATION=off
|
||||
#LIBREDDIT_DEFAULT_AUTOPLAY_VIDEOS=off
|
||||
#LIBREDDIT_DEFAULT_SUBSCRIPTIONS=off (sub1+sub2+sub3)
|
||||
#LIBREDDIT_DEFAULT_HIDE_AWARDS=off
|
||||
#LIBREDDIT_DEFAULT_DISABLE_VISIT_REDDIT_CONFIRMATION=off
|
|
@ -4,21 +4,10 @@ services:
|
|||
web:
|
||||
build: .
|
||||
restart: always
|
||||
container_name: "libreddit"
|
||||
container_name: "ferrit"
|
||||
ports:
|
||||
- 8080:8080
|
||||
user: nobody
|
||||
read_only: true
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop:
|
||||
- ALL
|
||||
networks:
|
||||
- libreddit
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--spider", "-q", "--tries=1", "http://localhost:8080/settings"]
|
||||
interval: 5m
|
||||
timeout: 3s
|
||||
|
||||
networks:
|
||||
libreddit:
|
||||
|
|
|
@ -1,7 +1,10 @@
|
|||
#!/usr/bin/env bash
|
||||
|
||||
# This scripts generates the CREDITS file in the repository root, which
|
||||
# contains a list of all contributors ot the Libreddit project.
|
||||
# This scripts generates the CREDITS file in the repository root.
|
||||
#
|
||||
# The generated file contains a list of all contributors to the Ferrit project,
|
||||
# including those who contributed to the original Libreddit project
|
||||
# (https://github.com/spikecodes/libreddit).
|
||||
#
|
||||
# We use git-log to surface the names and emails of all authors and committers,
|
||||
# and grep will filter any automated commits due to GitHub.
|
||||
|
|
101
src/client.rs
|
@ -1,10 +1,7 @@
|
|||
use cached::proc_macro::cached;
|
||||
use futures_lite::{future::Boxed, FutureExt};
|
||||
use hyper::client::HttpConnector;
|
||||
use hyper::{body, body::Buf, client, header, Body, Client, Method, Request, Response, Uri};
|
||||
use hyper_rustls::HttpsConnector;
|
||||
use hyper::{body, body::Buf, client, header, Body, Method, Request, Response, Uri};
|
||||
use libflate::gzip;
|
||||
use once_cell::sync::Lazy;
|
||||
use percent_encoding::{percent_encode, CONTROLS};
|
||||
use serde_json::Value;
|
||||
use std::{io, result::Result};
|
||||
|
@ -14,48 +11,25 @@ use crate::server::RequestExt;
|
|||
|
||||
const REDDIT_URL_BASE: &str = "https://www.reddit.com";
|
||||
|
||||
static CLIENT: Lazy<Client<HttpsConnector<HttpConnector>>> = Lazy::new(|| {
|
||||
let https = hyper_rustls::HttpsConnectorBuilder::new().with_native_roots().https_only().enable_http1().build();
|
||||
client::Client::builder().build(https)
|
||||
});
|
||||
|
||||
/// Gets the canonical path for a resource on Reddit. This is accomplished by
|
||||
/// making a `HEAD` request to Reddit at the path given in `path`.
|
||||
///
|
||||
/// This function returns `Ok(Some(path))`, where `path`'s value is identical
|
||||
/// to that of the value of the argument `path`, if Reddit responds to our
|
||||
/// `HEAD` request with a 2xx-family HTTP code. It will also return an
|
||||
/// `Ok(Some(String))` if Reddit responds to our `HEAD` request with a
|
||||
/// `Location` header in the response, and the HTTP code is in the 3xx-family;
|
||||
/// the `String` will contain the path as reported in `Location`. The return
|
||||
/// value is `Ok(None)` if Reddit responded with a 3xx, but did not provide a
|
||||
/// `Location` header. An `Err(String)` is returned if Reddit responds with a
|
||||
/// 429, or if we were unable to decode the value in the `Location` header.
|
||||
/// Gets the canonical path for a resource on Reddit. On success, a
|
||||
/// `Some(Option<String>)` will be returned. If Reddit responds with
|
||||
/// anything other than an HTTP 3xx, a `None` will be returned. Any
|
||||
/// other error results in an `Err(String)`.
|
||||
#[cached(size = 1024, time = 600, result = true)]
|
||||
pub async fn canonical_path(path: String) -> Result<Option<String>, String> {
|
||||
let res = reddit_head(path.clone(), true).await?;
|
||||
let res = reddit_head(path, true).await?;
|
||||
|
||||
if res.status() == 429 {
|
||||
return Err("Too many requests.".to_string());
|
||||
};
|
||||
|
||||
// If Reddit responds with a 2xx, then the path is already canonical.
|
||||
if res.status().to_string().starts_with('2') {
|
||||
return Ok(Some(path));
|
||||
match res.headers().get(header::LOCATION) {
|
||||
None => Ok(None),
|
||||
Some(hdr) => match hdr.to_str() {
|
||||
Ok(val) => Ok(Some(val.to_string().trim_start_matches(REDDIT_URL_BASE).to_string())),
|
||||
Err(e) => Err(e.to_string()),
|
||||
},
|
||||
}
|
||||
|
||||
// If Reddit responds with anything other than 3xx (except for the 2xx as
|
||||
// above), return a None.
|
||||
if !res.status().to_string().starts_with('3') {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
Ok(
|
||||
res
|
||||
.headers()
|
||||
.get(header::LOCATION)
|
||||
.map(|val| percent_encode(val.as_bytes(), CONTROLS).to_string().trim_start_matches(REDDIT_URL_BASE).to_string()),
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn proxy(req: Request<Body>, format: &str) -> Result<Response<Body>, String> {
|
||||
|
@ -74,8 +48,11 @@ async fn stream(url: &str, req: &Request<Body>) -> Result<Response<Body>, String
|
|||
// First parameter is target URL (mandatory).
|
||||
let uri = url.parse::<Uri>().map_err(|_| "Couldn't parse URL".to_string())?;
|
||||
|
||||
// Prepare the HTTPS connector.
|
||||
let https = hyper_rustls::HttpsConnectorBuilder::new().with_native_roots().https_only().enable_http1().build();
|
||||
|
||||
// Build the hyper client from the HTTPS connector.
|
||||
let client: client::Client<_, hyper::Body> = CLIENT.clone();
|
||||
let client: client::Client<_, Body> = client::Client::builder().build(https);
|
||||
|
||||
let mut builder = Request::get(uri);
|
||||
|
||||
|
@ -104,8 +81,6 @@ async fn stream(url: &str, req: &Request<Body>) -> Result<Response<Body>, String
|
|||
rm("x-cdn-server-region");
|
||||
rm("x-reddit-cdn");
|
||||
rm("x-reddit-video-features");
|
||||
rm("Nel");
|
||||
rm("Report-To");
|
||||
|
||||
res
|
||||
})
|
||||
|
@ -130,28 +105,24 @@ fn request(method: &'static Method, path: String, redirect: bool, quarantine: bo
|
|||
// Build Reddit URL from path.
|
||||
let url = format!("{}{}", REDDIT_URL_BASE, path);
|
||||
|
||||
// Construct the hyper client from the HTTPS connector.
|
||||
let client: client::Client<_, hyper::Body> = CLIENT.clone();
|
||||
// Prepare the HTTPS connector.
|
||||
let https = hyper_rustls::HttpsConnectorBuilder::new().with_native_roots().https_or_http().enable_http1().build();
|
||||
|
||||
// Build request to Reddit. When making a GET, request gzip compression.
|
||||
// (Reddit doesn't do brotli yet.)
|
||||
// Construct the hyper client from the HTTPS connector.
|
||||
let client: client::Client<_, Body> = client::Client::builder().build(https);
|
||||
|
||||
// Build request to Reddit. When making a GET, request gzip compression
|
||||
// (Reddit doesn't do brotli yet)
|
||||
let builder = Request::builder()
|
||||
.method(method)
|
||||
.uri(&url)
|
||||
.header("User-Agent", format!("web:libreddit:{}", env!("CARGO_PKG_VERSION")))
|
||||
.header("User-Agent", format!("web:ferrit:{}", env!("CARGO_PKG_VERSION")))
|
||||
.header("Host", "www.reddit.com")
|
||||
.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
|
||||
.header("Accept-Encoding", if method == Method::GET { "gzip" } else { "identity" })
|
||||
.header("Accept-Language", "en-US,en;q=0.5")
|
||||
.header("Connection", "keep-alive")
|
||||
.header(
|
||||
"Cookie",
|
||||
if quarantine {
|
||||
"_options=%7B%22pref_quarantine_optin%22%3A%20true%2C%20%22pref_gated_sr_optin%22%3A%20true%7D"
|
||||
} else {
|
||||
""
|
||||
},
|
||||
)
|
||||
.header("Cookie", if quarantine { "_options=%7B%22pref_quarantine_optin%22%3A%20true%7D" } else { "" })
|
||||
.body(Body::empty());
|
||||
|
||||
async move {
|
||||
|
@ -169,21 +140,10 @@ fn request(method: &'static Method, path: String, redirect: bool, quarantine: bo
|
|||
method,
|
||||
response
|
||||
.headers()
|
||||
.get(header::LOCATION)
|
||||
.get("Location")
|
||||
.map(|val| {
|
||||
// We need to make adjustments to the URI
|
||||
// we get back from Reddit. Namely, we
|
||||
// must:
|
||||
//
|
||||
// 1. Remove the authority (e.g.
|
||||
// https://www.reddit.com) that may be
|
||||
// present, so that we recurse on the
|
||||
// path (and query parameters) as
|
||||
// required.
|
||||
//
|
||||
// 2. Percent-encode the path.
|
||||
let new_path = percent_encode(val.as_bytes(), CONTROLS).to_string().trim_start_matches(REDDIT_URL_BASE).to_string();
|
||||
format!("{}{}raw_json=1", new_path, if new_path.contains('?') { "&" } else { "?" })
|
||||
let new_url = percent_encode(val.as_bytes(), CONTROLS).to_string();
|
||||
format!("{}{}raw_json=1", new_url, if new_url.contains('?') { "&" } else { "?" })
|
||||
})
|
||||
.unwrap_or_default()
|
||||
.to_string(),
|
||||
|
@ -227,8 +187,9 @@ fn request(method: &'static Method, path: String, redirect: bool, quarantine: bo
|
|||
};
|
||||
|
||||
decompressed = Vec::<u8>::new();
|
||||
if let Err(e) = io::copy(&mut decoder, &mut decompressed) {
|
||||
return Err(e.to_string());
|
||||
match io::copy(&mut decoder, &mut decompressed) {
|
||||
Ok(_) => {}
|
||||
Err(e) => return Err(e.to_string()),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
193
src/config.rs
|
@ -1,75 +1,49 @@
|
|||
use once_cell::sync::Lazy;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{env::var, fs::read_to_string};
|
||||
use std::env::var;
|
||||
|
||||
// Waiting for https://github.com/rust-lang/rust/issues/74465 to land, so we
|
||||
// can reduce reliance on once_cell.
|
||||
//
|
||||
// This is the local static that is initialized at runtime (technically at
|
||||
// first request) and contains the instance settings.
|
||||
pub(crate) static CONFIG: Lazy<Config> = Lazy::new(Config::load);
|
||||
|
||||
// This serves as the frontend for the Pushshift API - on removed comments, this URL will
|
||||
// be the base of a link, to display removed content (on another site).
|
||||
pub(crate) const DEFAULT_PUSHSHIFT_FRONTEND: &str = "www.unddit.com";
|
||||
static CONFIG: Lazy<Config> = Lazy::new(Config::load);
|
||||
|
||||
/// Stores the configuration parsed from the environment variables and the
|
||||
/// config file. `Config::Default()` contains None for each setting.
|
||||
/// When adding more config settings, add it to `Config::load`,
|
||||
/// `get_setting_from_config`, both below, as well as
|
||||
/// instance_info::InstanceInfo.to_string(), README.md and app.json.
|
||||
#[derive(Default, Serialize, Deserialize, Clone, Debug)]
|
||||
#[derive(Default, serde::Deserialize)]
|
||||
pub struct Config {
|
||||
#[serde(rename = "LIBREDDIT_SFW_ONLY")]
|
||||
pub(crate) sfw_only: Option<String>,
|
||||
#[serde(rename = "FERRIT_SFW_ONLY")]
|
||||
sfw_only: Option<String>,
|
||||
|
||||
#[serde(rename = "LIBREDDIT_DEFAULT_THEME")]
|
||||
pub(crate) default_theme: Option<String>,
|
||||
#[serde(rename = "FERRIT_DEFAULT_THEME")]
|
||||
default_theme: Option<String>,
|
||||
|
||||
#[serde(rename = "LIBREDDIT_DEFAULT_FRONT_PAGE")]
|
||||
pub(crate) default_front_page: Option<String>,
|
||||
#[serde(rename = "FERRIT_DEFAULT_FRONT_PAGE")]
|
||||
default_front_page: Option<String>,
|
||||
|
||||
#[serde(rename = "LIBREDDIT_DEFAULT_LAYOUT")]
|
||||
pub(crate) default_layout: Option<String>,
|
||||
#[serde(rename = "FERRIT_DEFAULT_LAYOUT")]
|
||||
default_layout: Option<String>,
|
||||
|
||||
#[serde(rename = "LIBREDDIT_DEFAULT_WIDE")]
|
||||
pub(crate) default_wide: Option<String>,
|
||||
#[serde(rename = "FERRIT_DEFAULT_WIDE")]
|
||||
default_wide: Option<String>,
|
||||
|
||||
#[serde(rename = "LIBREDDIT_DEFAULT_COMMENT_SORT")]
|
||||
pub(crate) default_comment_sort: Option<String>,
|
||||
#[serde(rename = "FERRIT_DEFAULT_COMMENT_SORT")]
|
||||
default_comment_sort: Option<String>,
|
||||
|
||||
#[serde(rename = "LIBREDDIT_DEFAULT_POST_SORT")]
|
||||
pub(crate) default_post_sort: Option<String>,
|
||||
#[serde(rename = "FERRIT_DEFAULT_POST_SORT")]
|
||||
default_post_sort: Option<String>,
|
||||
|
||||
#[serde(rename = "LIBREDDIT_DEFAULT_SHOW_NSFW")]
|
||||
pub(crate) default_show_nsfw: Option<String>,
|
||||
#[serde(rename = "FERRIT_DEFAULT_SHOW_NSFW")]
|
||||
default_show_nsfw: Option<String>,
|
||||
|
||||
#[serde(rename = "LIBREDDIT_DEFAULT_BLUR_NSFW")]
|
||||
pub(crate) default_blur_nsfw: Option<String>,
|
||||
#[serde(rename = "FERRIT_DEFAULT_BLUR_NSFW")]
|
||||
default_blur_nsfw: Option<String>,
|
||||
|
||||
#[serde(rename = "LIBREDDIT_DEFAULT_USE_HLS")]
|
||||
pub(crate) default_use_hls: Option<String>,
|
||||
#[serde(rename = "FERRIT_DEFAULT_USE_HLS")]
|
||||
default_use_hls: Option<String>,
|
||||
|
||||
#[serde(rename = "LIBREDDIT_DEFAULT_HIDE_HLS_NOTIFICATION")]
|
||||
pub(crate) default_hide_hls_notification: Option<String>,
|
||||
|
||||
#[serde(rename = "LIBREDDIT_DEFAULT_HIDE_AWARDS")]
|
||||
pub(crate) default_hide_awards: Option<String>,
|
||||
|
||||
#[serde(rename = "LIBREDDIT_DEFAULT_SUBSCRIPTIONS")]
|
||||
pub(crate) default_subscriptions: Option<String>,
|
||||
|
||||
#[serde(rename = "LIBREDDIT_DEFAULT_DISABLE_VISIT_REDDIT_CONFIRMATION")]
|
||||
pub(crate) default_disable_visit_reddit_confirmation: Option<String>,
|
||||
|
||||
#[serde(rename = "LIBREDDIT_BANNER")]
|
||||
pub(crate) banner: Option<String>,
|
||||
|
||||
#[serde(rename = "LIBREDDIT_ROBOTS_DISABLE_INDEXING")]
|
||||
pub(crate) robots_disable_indexing: Option<String>,
|
||||
|
||||
#[serde(rename = "LIBREDDIT_PUSHSHIFT_FRONTEND")]
|
||||
pub(crate) pushshift: Option<String>,
|
||||
#[serde(rename = "FERRIT_DEFAULT_HIDE_HLS_NOTIFICATION")]
|
||||
default_hide_hls_notification: Option<String>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
|
@ -77,55 +51,48 @@ impl Config {
|
|||
/// In the case that there are no environment variables set and there is no
|
||||
/// config file, this function returns a Config that contains all None values.
|
||||
pub fn load() -> Self {
|
||||
// Read from libreddit.toml config file. If for any reason, it fails, the
|
||||
// Read from ferrit.toml config file. If for any reason, it fails, the
|
||||
// default `Config` is used (all None values)
|
||||
let config: Config = toml::from_str(&read_to_string("libreddit.toml").unwrap_or_default()).unwrap_or_default();
|
||||
let config: Config = toml::from_str(&std::fs::read_to_string("ferrit.toml").unwrap_or_default()).unwrap_or_default();
|
||||
// This function defines the order of preference - first check for
|
||||
// environment variables with "LIBREDDIT", then check the config, then if
|
||||
// environment variables with "FERRIT", then check for environment variables
|
||||
// with "LIBREDDIT" for reverse compatibility, then check the config, then if
|
||||
// both are `None`, return a `None` via the `map_or_else` function
|
||||
let parse = |key: &str| -> Option<String> { var(key).ok().map_or_else(|| get_setting_from_config(key, &config), Some) };
|
||||
|
||||
let parse = |key: &str| -> Option<String> {
|
||||
var(key)
|
||||
.ok()
|
||||
.map_or_else(|| var(key.replace("FERRIT", "LIBREDDIT")).ok(), Some)
|
||||
.map_or_else(|| get_setting_from_config(key, &config), Some)
|
||||
};
|
||||
Self {
|
||||
sfw_only: parse("LIBREDDIT_SFW_ONLY"),
|
||||
default_theme: parse("LIBREDDIT_DEFAULT_THEME"),
|
||||
default_front_page: parse("LIBREDDIT_DEFAULT_FRONT_PAGE"),
|
||||
default_layout: parse("LIBREDDIT_DEFAULT_LAYOUT"),
|
||||
default_post_sort: parse("LIBREDDIT_DEFAULT_POST_SORT"),
|
||||
default_wide: parse("LIBREDDIT_DEFAULT_WIDE"),
|
||||
default_comment_sort: parse("LIBREDDIT_DEFAULT_COMMENT_SORT"),
|
||||
default_show_nsfw: parse("LIBREDDIT_DEFAULT_SHOW_NSFW"),
|
||||
default_blur_nsfw: parse("LIBREDDIT_DEFAULT_BLUR_NSFW"),
|
||||
default_use_hls: parse("LIBREDDIT_DEFAULT_USE_HLS"),
|
||||
default_hide_hls_notification: parse("LIBREDDIT_DEFAULT_HIDE_HLS"),
|
||||
default_hide_awards: parse("LIBREDDIT_DEFAULT_HIDE_AWARDS"),
|
||||
default_subscriptions: parse("LIBREDDIT_DEFAULT_SUBSCRIPTIONS"),
|
||||
default_disable_visit_reddit_confirmation: parse("LIBREDDIT_DEFAULT_DISABLE_VISIT_REDDIT_CONFIRMATION"),
|
||||
banner: parse("LIBREDDIT_BANNER"),
|
||||
robots_disable_indexing: parse("LIBREDDIT_ROBOTS_DISABLE_INDEXING"),
|
||||
pushshift: parse("LIBREDDIT_PUSHSHIFT_FRONTEND"),
|
||||
sfw_only: parse("FERRIT_SFW_ONLY"),
|
||||
default_theme: parse("FERRIT_DEFAULT_THEME"),
|
||||
default_front_page: parse("FERRIT_DEFAULT_FRONT_PAGE"),
|
||||
default_layout: parse("FERRIT_DEFAULT_LAYOUT"),
|
||||
default_post_sort: parse("FERRIT_DEFAULT_POST_SORT"),
|
||||
default_wide: parse("FERRIT_DEFAULT_WIDE"),
|
||||
default_comment_sort: parse("FERRIT_DEFAULT_COMMENT_SORT"),
|
||||
default_show_nsfw: parse("FERRIT_DEFAULT_SHOW_NSFW"),
|
||||
default_blur_nsfw: parse("FERRIT_DEFAULT_BLUR_NSFW"),
|
||||
default_use_hls: parse("FERRIT_DEFAULT_USE_HLS"),
|
||||
default_hide_hls_notification: parse("FERRIT_DEFAULT_HIDE_HLS"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_setting_from_config(name: &str, config: &Config) -> Option<String> {
|
||||
match name {
|
||||
"LIBREDDIT_SFW_ONLY" => config.sfw_only.clone(),
|
||||
"LIBREDDIT_DEFAULT_THEME" => config.default_theme.clone(),
|
||||
"LIBREDDIT_DEFAULT_FRONT_PAGE" => config.default_front_page.clone(),
|
||||
"LIBREDDIT_DEFAULT_LAYOUT" => config.default_layout.clone(),
|
||||
"LIBREDDIT_DEFAULT_COMMENT_SORT" => config.default_comment_sort.clone(),
|
||||
"LIBREDDIT_DEFAULT_POST_SORT" => config.default_post_sort.clone(),
|
||||
"LIBREDDIT_DEFAULT_SHOW_NSFW" => config.default_show_nsfw.clone(),
|
||||
"LIBREDDIT_DEFAULT_BLUR_NSFW" => config.default_blur_nsfw.clone(),
|
||||
"LIBREDDIT_DEFAULT_USE_HLS" => config.default_use_hls.clone(),
|
||||
"LIBREDDIT_DEFAULT_HIDE_HLS_NOTIFICATION" => config.default_hide_hls_notification.clone(),
|
||||
"LIBREDDIT_DEFAULT_WIDE" => config.default_wide.clone(),
|
||||
"LIBREDDIT_DEFAULT_HIDE_AWARDS" => config.default_hide_awards.clone(),
|
||||
"LIBREDDIT_DEFAULT_SUBSCRIPTIONS" => config.default_subscriptions.clone(),
|
||||
"LIBREDDIT_DEFAULT_DISABLE_VISIT_REDDIT_CONFIRMATION" => config.default_disable_visit_reddit_confirmation.clone(),
|
||||
"LIBREDDIT_BANNER" => config.banner.clone(),
|
||||
"LIBREDDIT_ROBOTS_DISABLE_INDEXING" => config.robots_disable_indexing.clone(),
|
||||
"LIBREDDIT_PUSHSHIFT_FRONTEND" => config.pushshift.clone(),
|
||||
"FERRIT_SFW_ONLY" => config.sfw_only.clone(),
|
||||
"FERRIT_DEFAULT_THEME" => config.default_theme.clone(),
|
||||
"FERRIT_DEFAULT_FRONT_PAGE" => config.default_front_page.clone(),
|
||||
"FERRIT_DEFAULT_LAYOUT" => config.default_layout.clone(),
|
||||
"FERRIT_DEFAULT_COMMENT_SORT" => config.default_comment_sort.clone(),
|
||||
"FERRIT_DEFAULT_POST_SORT" => config.default_post_sort.clone(),
|
||||
"FERRIT_DEFAULT_SHOW_NSFW" => config.default_show_nsfw.clone(),
|
||||
"FERRIT_DEFAULT_BLUR_NSFW" => config.default_blur_nsfw.clone(),
|
||||
"FERRIT_DEFAULT_USE_HLS" => config.default_use_hls.clone(),
|
||||
"FERRIT_DEFAULT_HIDE_HLS_NOTIFICATION" => config.default_hide_hls_notification.clone(),
|
||||
"FERRIT_DEFAULT_WIDE" => config.default_wide.clone(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
@ -136,46 +103,40 @@ pub(crate) fn get_setting(name: &str) -> Option<String> {
|
|||
}
|
||||
|
||||
#[cfg(test)]
|
||||
use {sealed_test::prelude::*, std::fs::write};
|
||||
use sealed_test::prelude::*;
|
||||
|
||||
#[test]
|
||||
fn test_deserialize() {
|
||||
// Must handle empty input
|
||||
let result = toml::from_str::<Config>("");
|
||||
assert!(result.is_ok(), "Error: {}", result.unwrap_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[sealed_test(env = [("LIBREDDIT_SFW_ONLY", "on")])]
|
||||
#[sealed_test(env = [("FERRIT_SFW_ONLY", "1")])]
|
||||
fn test_env_var() {
|
||||
assert!(crate::utils::sfw_only())
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[sealed_test]
|
||||
fn test_config() {
|
||||
let config_to_write = r#"LIBREDDIT_DEFAULT_COMMENT_SORT = "best""#;
|
||||
write("libreddit.toml", config_to_write).unwrap();
|
||||
assert_eq!(get_setting("LIBREDDIT_DEFAULT_COMMENT_SORT"), Some("best".into()));
|
||||
#[sealed_test(env = [("FERRIT_DEFAULT_COMMENT_SORT", "top"), ("LIBREDDIT_DEFAULT_COMMENT_SORT", "best")])]
|
||||
fn test_env_precedence() {
|
||||
assert_eq!(crate::config::get_setting("FERRIT_DEFAULT_COMMENT_SORT"), Some("top".into()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[sealed_test(env = [("LIBREDDIT_DEFAULT_COMMENT_SORT", "top")])]
|
||||
#[sealed_test]
|
||||
fn test_config() {
|
||||
let config_to_write = r#"FERRIT_DEFAULT_COMMENT_SORT = "best""#;
|
||||
std::fs::write("ferrit.toml", config_to_write).unwrap();
|
||||
assert_eq!(crate::config::get_setting("FERRIT_DEFAULT_COMMENT_SORT"), Some("best".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[sealed_test(env = [("FERRIT_DEFAULT_COMMENT_SORT", "top")])]
|
||||
fn test_env_config_precedence() {
|
||||
let config_to_write = r#"LIBREDDIT_DEFAULT_COMMENT_SORT = "best""#;
|
||||
write("libreddit.toml", config_to_write).unwrap();
|
||||
assert_eq!(get_setting("LIBREDDIT_DEFAULT_COMMENT_SORT"), Some("top".into()))
|
||||
let config_to_write = r#"FERRIT_DEFAULT_COMMENT_SORT = "best""#;
|
||||
std::fs::write("ferrit.toml", config_to_write).unwrap();
|
||||
assert_eq!(crate::config::get_setting("FERRIT_DEFAULT_COMMENT_SORT"), Some("top".into()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[sealed_test(env = [("LIBREDDIT_DEFAULT_COMMENT_SORT", "top")])]
|
||||
fn test_alt_env_config_precedence() {
|
||||
let config_to_write = r#"LIBREDDIT_DEFAULT_COMMENT_SORT = "best""#;
|
||||
write("libreddit.toml", config_to_write).unwrap();
|
||||
assert_eq!(get_setting("LIBREDDIT_DEFAULT_COMMENT_SORT"), Some("top".into()))
|
||||
}
|
||||
#[test]
|
||||
#[sealed_test(env = [("LIBREDDIT_DEFAULT_SUBSCRIPTIONS", "news+bestof")])]
|
||||
fn test_default_subscriptions() {
|
||||
assert_eq!(get_setting("LIBREDDIT_DEFAULT_SUBSCRIPTIONS"), Some("news+bestof".into()));
|
||||
let config_to_write = r#"FERRIT_DEFAULT_COMMENT_SORT = "best""#;
|
||||
std::fs::write("Ferrit.toml", config_to_write).unwrap();
|
||||
assert_eq!(crate::config::get_setting("FERRIT_DEFAULT_COMMENT_SORT"), Some("top".into()))
|
||||
}
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
use crate::client::json;
|
||||
use crate::server::RequestExt;
|
||||
use crate::subreddit::{can_access_quarantine, quarantine};
|
||||
use crate::utils::{error, filter_posts, get_filters, nsfw_landing, parse_post, template, Post, Preferences};
|
||||
use crate::utils::{error, filter_posts, get_filters, nsfw_landing, parse_post, setting, template, Post, Preferences};
|
||||
|
||||
use askama::Template;
|
||||
use hyper::{Body, Request, Response};
|
||||
|
@ -67,12 +67,11 @@ pub async fn item(req: Request<Body>) -> Result<Response<Body>, String> {
|
|||
Ok(response) => {
|
||||
let post = parse_post(&response[0]["data"]["children"][0]).await;
|
||||
|
||||
let req_url = req.uri().to_string();
|
||||
// Return landing page if this post if this Reddit deems this post
|
||||
// NSFW, but we have also disabled the display of NSFW content
|
||||
// or if the instance is SFW-only
|
||||
if post.nsfw && crate::utils::should_be_nsfw_gated(&req, &req_url) {
|
||||
return Ok(nsfw_landing(req, req_url).await.unwrap_or_default());
|
||||
// or if the instance is SFW-only.
|
||||
if post.nsfw && (setting(&req, "show_nsfw") != "on" || crate::utils::sfw_only()) {
|
||||
return Ok(nsfw_landing(req).await.unwrap_or_default());
|
||||
}
|
||||
|
||||
let filters = get_filters(&req);
|
||||
|
@ -196,13 +195,14 @@ pub async fn item(req: Request<Body>) -> Result<Response<Body>, String> {
|
|||
after = response[1]["data"]["after"].as_str().unwrap_or_default().to_string();
|
||||
}
|
||||
}
|
||||
let url = req.uri().to_string();
|
||||
|
||||
template(DuplicatesTemplate {
|
||||
params: DuplicatesParams { before, after, sort },
|
||||
post,
|
||||
duplicates,
|
||||
prefs: Preferences::new(&req),
|
||||
url: req_url,
|
||||
prefs: Preferences::new(req),
|
||||
url,
|
||||
num_posts_filtered,
|
||||
all_posts_filtered,
|
||||
})
|
||||
|
@ -210,9 +210,9 @@ pub async fn item(req: Request<Body>) -> Result<Response<Body>, String> {
|
|||
|
||||
// Process error.
|
||||
Err(msg) => {
|
||||
if msg == "quarantined" || msg == "gated" {
|
||||
if msg == "quarantined" {
|
||||
let sub = req.param("sub").unwrap_or_default();
|
||||
quarantine(req, sub, msg)
|
||||
quarantine(req, sub)
|
||||
} else {
|
||||
error(req, msg).await
|
||||
}
|
||||
|
|
|
@ -1,212 +0,0 @@
|
|||
use crate::{
|
||||
config::{Config, CONFIG},
|
||||
server::RequestExt,
|
||||
utils::{ErrorTemplate, Preferences},
|
||||
};
|
||||
use askama::Template;
|
||||
use build_html::{Container, Html, HtmlContainer, Table};
|
||||
use hyper::{http::Error, Body, Request, Response};
|
||||
use once_cell::sync::Lazy;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
// This is the local static that is intialized at runtime (technically at
|
||||
// the first request to the info endpoint) and contains the data
|
||||
// retrieved from the info endpoint.
|
||||
pub(crate) static INSTANCE_INFO: Lazy<InstanceInfo> = Lazy::new(InstanceInfo::new);
|
||||
|
||||
/// Handles instance info endpoint
|
||||
pub async fn instance_info(req: Request<Body>) -> Result<Response<Body>, String> {
|
||||
// This will retrieve the extension given, or create a new string - which will
|
||||
// simply become the last option, an HTML page.
|
||||
let extension = req.param("extension").unwrap_or(String::new());
|
||||
let response = match extension.as_str() {
|
||||
"yaml" | "yml" => info_yaml(),
|
||||
"txt" => info_txt(),
|
||||
"json" => info_json(),
|
||||
"html" | "" => info_html(req),
|
||||
_ => {
|
||||
let error = ErrorTemplate {
|
||||
msg: "Error: Invalid info extension".into(),
|
||||
prefs: Preferences::new(&req),
|
||||
url: req.uri().to_string(),
|
||||
}
|
||||
.render()
|
||||
.unwrap();
|
||||
Response::builder().status(404).header("content-type", "text/html; charset=utf-8").body(error.into())
|
||||
}
|
||||
};
|
||||
response.map_err(|err| format!("{err}"))
|
||||
}
|
||||
|
||||
fn info_json() -> Result<Response<Body>, Error> {
|
||||
if let Ok(body) = serde_json::to_string(&*INSTANCE_INFO) {
|
||||
Response::builder().status(200).header("content-type", "application/json").body(body.into())
|
||||
} else {
|
||||
Response::builder()
|
||||
.status(500)
|
||||
.header("content-type", "text/plain")
|
||||
.body(Body::from("Error serializing JSON"))
|
||||
}
|
||||
}
|
||||
|
||||
fn info_yaml() -> Result<Response<Body>, Error> {
|
||||
if let Ok(body) = serde_yaml::to_string(&*INSTANCE_INFO) {
|
||||
// We can use `application/yaml` as media type, though there is no guarantee
|
||||
// that browsers will honor it. But we'll do it anyway. See:
|
||||
// https://github.com/ietf-wg-httpapi/mediatypes/blob/main/draft-ietf-httpapi-yaml-mediatypes.md#media-type-applicationyaml-application-yaml
|
||||
Response::builder().status(200).header("content-type", "application/yaml").body(body.into())
|
||||
} else {
|
||||
Response::builder()
|
||||
.status(500)
|
||||
.header("content-type", "text/plain")
|
||||
.body(Body::from("Error serializing YAML."))
|
||||
}
|
||||
}
|
||||
|
||||
fn info_txt() -> Result<Response<Body>, Error> {
|
||||
Response::builder()
|
||||
.status(200)
|
||||
.header("content-type", "text/plain")
|
||||
.body(Body::from(INSTANCE_INFO.to_string(StringType::Raw)))
|
||||
}
|
||||
fn info_html(req: Request<Body>) -> Result<Response<Body>, Error> {
|
||||
let message = MessageTemplate {
|
||||
title: String::from("Instance information"),
|
||||
body: INSTANCE_INFO.to_string(StringType::Html),
|
||||
prefs: Preferences::new(&req),
|
||||
url: req.uri().to_string(),
|
||||
}
|
||||
.render()
|
||||
.unwrap();
|
||||
Response::builder().status(200).header("content-type", "text/html; charset=utf8").body(Body::from(message))
|
||||
}
|
||||
#[derive(Serialize, Deserialize, Default)]
|
||||
pub(crate) struct InstanceInfo {
|
||||
crate_version: String,
|
||||
git_commit: String,
|
||||
deploy_date: String,
|
||||
compile_mode: String,
|
||||
deploy_unix_ts: i64,
|
||||
config: Config,
|
||||
}
|
||||
|
||||
impl InstanceInfo {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
crate_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
git_commit: env!("GIT_HASH").to_string(),
|
||||
deploy_date: OffsetDateTime::now_local().unwrap_or_else(|_| OffsetDateTime::now_utc()).to_string(),
|
||||
#[cfg(debug_assertions)]
|
||||
compile_mode: "Debug".into(),
|
||||
#[cfg(not(debug_assertions))]
|
||||
compile_mode: "Release".into(),
|
||||
deploy_unix_ts: OffsetDateTime::now_local().unwrap_or_else(|_| OffsetDateTime::now_utc()).unix_timestamp(),
|
||||
config: CONFIG.clone(),
|
||||
}
|
||||
}
|
||||
fn to_table(&self) -> String {
|
||||
let mut container = Container::default();
|
||||
let convert = |o: &Option<String>| -> String { o.clone().unwrap_or("<span class=\"unset\"><i>Unset</i></span>".to_owned()) };
|
||||
if let Some(banner) = &self.config.banner {
|
||||
container.add_header(3, "Instance banner");
|
||||
container.add_raw("<br />");
|
||||
container.add_paragraph(banner);
|
||||
container.add_raw("<br />");
|
||||
}
|
||||
container.add_table(
|
||||
Table::from([
|
||||
["Crate version", &self.crate_version],
|
||||
["Git commit", &self.git_commit],
|
||||
["Deploy date", &self.deploy_date],
|
||||
["Deploy timestamp", &self.deploy_unix_ts.to_string()],
|
||||
["Compile mode", &self.compile_mode],
|
||||
["SFW only", &convert(&self.config.sfw_only)],
|
||||
["Pushshift frontend", &convert(&self.config.pushshift)],
|
||||
//TODO: fallback to crate::config::DEFAULT_PUSHSHIFT_FRONTEND
|
||||
])
|
||||
.with_header_row(["Settings"]),
|
||||
);
|
||||
container.add_raw("<br />");
|
||||
container.add_table(
|
||||
Table::from([
|
||||
["Hide awards", &convert(&self.config.default_hide_awards)],
|
||||
["Theme", &convert(&self.config.default_theme)],
|
||||
["Front page", &convert(&self.config.default_front_page)],
|
||||
["Layout", &convert(&self.config.default_layout)],
|
||||
["Wide", &convert(&self.config.default_wide)],
|
||||
["Comment sort", &convert(&self.config.default_comment_sort)],
|
||||
["Post sort", &convert(&self.config.default_post_sort)],
|
||||
["Show NSFW", &convert(&self.config.default_show_nsfw)],
|
||||
["Blur NSFW", &convert(&self.config.default_blur_nsfw)],
|
||||
["Use HLS", &convert(&self.config.default_use_hls)],
|
||||
["Hide HLS notification", &convert(&self.config.default_hide_hls_notification)],
|
||||
["Subscriptions", &convert(&self.config.default_subscriptions)],
|
||||
])
|
||||
.with_header_row(["Default preferences"]),
|
||||
);
|
||||
container.to_html_string().replace("<th>", "<th colspan=\"2\">")
|
||||
}
|
||||
fn to_string(&self, string_type: StringType) -> String {
|
||||
match string_type {
|
||||
StringType::Raw => {
|
||||
format!(
|
||||
"Crate version: {}\n
|
||||
Git commit: {}\n
|
||||
Deploy date: {}\n
|
||||
Deploy timestamp: {}\n
|
||||
Compile mode: {}\n
|
||||
SFW only: {:?}\n
|
||||
Pushshift frontend: {:?}\n
|
||||
Config:\n
|
||||
Banner: {:?}\n
|
||||
Hide awards: {:?}\n
|
||||
Default theme: {:?}\n
|
||||
Default front page: {:?}\n
|
||||
Default layout: {:?}\n
|
||||
Default wide: {:?}\n
|
||||
Default comment sort: {:?}\n
|
||||
Default post sort: {:?}\n
|
||||
Default show NSFW: {:?}\n
|
||||
Default blur NSFW: {:?}\n
|
||||
Default use HLS: {:?}\n
|
||||
Default hide HLS notification: {:?}\n
|
||||
Default subscriptions: {:?}\n",
|
||||
self.crate_version,
|
||||
self.git_commit,
|
||||
self.deploy_date,
|
||||
self.deploy_unix_ts,
|
||||
self.compile_mode,
|
||||
self.config.sfw_only,
|
||||
self.config.pushshift,
|
||||
self.config.banner,
|
||||
self.config.default_hide_awards,
|
||||
self.config.default_theme,
|
||||
self.config.default_front_page,
|
||||
self.config.default_layout,
|
||||
self.config.default_wide,
|
||||
self.config.default_comment_sort,
|
||||
self.config.default_post_sort,
|
||||
self.config.default_show_nsfw,
|
||||
self.config.default_blur_nsfw,
|
||||
self.config.default_use_hls,
|
||||
self.config.default_hide_hls_notification,
|
||||
self.config.default_subscriptions,
|
||||
)
|
||||
}
|
||||
StringType::Html => self.to_table(),
|
||||
}
|
||||
}
|
||||
}
|
||||
enum StringType {
|
||||
Raw,
|
||||
Html,
|
||||
}
|
||||
#[derive(Template)]
|
||||
#[template(path = "message.html")]
|
||||
struct MessageTemplate {
|
||||
title: String,
|
||||
body: String,
|
||||
prefs: Preferences,
|
||||
url: String,
|
||||
}
|
61
src/main.rs
|
@ -5,7 +5,6 @@
|
|||
// Reference local files
|
||||
mod config;
|
||||
mod duplicates;
|
||||
mod instance_info;
|
||||
mod post;
|
||||
mod search;
|
||||
mod settings;
|
||||
|
@ -14,14 +13,13 @@ mod user;
|
|||
mod utils;
|
||||
|
||||
// Import Crates
|
||||
use clap::{Arg, ArgAction, Command};
|
||||
use clap::{Arg, Command};
|
||||
|
||||
use futures_lite::FutureExt;
|
||||
use hyper::{header::HeaderValue, Body, Request, Response};
|
||||
|
||||
mod client;
|
||||
use client::{canonical_path, proxy};
|
||||
use once_cell::sync::Lazy;
|
||||
use server::RequestExt;
|
||||
use utils::{error, redirect, ThemeAssets};
|
||||
|
||||
|
@ -108,7 +106,7 @@ async fn style() -> Result<Response<Body>, String> {
|
|||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let matches = Command::new("Libreddit")
|
||||
let matches = Command::new("Ferrit")
|
||||
.version(env!("CARGO_PKG_VERSION"))
|
||||
.about("Private front-end for Reddit written in Rust ")
|
||||
.arg(
|
||||
|
@ -116,7 +114,7 @@ async fn main() {
|
|||
.short('r')
|
||||
.long("redirect-https")
|
||||
.help("Redirect all HTTP requests to HTTPS (no longer functional)")
|
||||
.num_args(0),
|
||||
.takes_value(false),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("address")
|
||||
|
@ -125,18 +123,16 @@ async fn main() {
|
|||
.value_name("ADDRESS")
|
||||
.help("Sets address to listen on")
|
||||
.default_value("0.0.0.0")
|
||||
.num_args(1),
|
||||
.takes_value(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("port")
|
||||
.short('p')
|
||||
.long("port")
|
||||
.value_name("PORT")
|
||||
.env("PORT")
|
||||
.help("Port to listen on")
|
||||
.default_value("8080")
|
||||
.action(ArgAction::Set)
|
||||
.num_args(1),
|
||||
.takes_value(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("hsts")
|
||||
|
@ -145,28 +141,21 @@ async fn main() {
|
|||
.value_name("EXPIRE_TIME")
|
||||
.help("HSTS header to tell browsers that this site should only be accessed over HTTPS")
|
||||
.default_value("604800")
|
||||
.num_args(1),
|
||||
.takes_value(true),
|
||||
)
|
||||
.get_matches();
|
||||
|
||||
let address = matches.get_one::<String>("address").unwrap();
|
||||
let port = matches.get_one::<String>("port").unwrap();
|
||||
let hsts = matches.get_one("hsts").map(|m: &String| m.as_str());
|
||||
let address = matches.value_of("address").unwrap_or("0.0.0.0");
|
||||
let port = std::env::var("PORT").unwrap_or_else(|_| matches.value_of("port").unwrap_or("8080").to_string());
|
||||
let hsts = matches.value_of("hsts");
|
||||
|
||||
let listener = [address, ":", port].concat();
|
||||
let listener = [address, ":", &port].concat();
|
||||
|
||||
println!("Starting Libreddit...");
|
||||
println!("Starting Ferrit...");
|
||||
|
||||
// Begin constructing a server
|
||||
let mut app = server::Server::new();
|
||||
|
||||
// Force evaluation of statics. In instance_info case, we need to evaluate
|
||||
// the timestamp so deploy date is accurate - in config case, we need to
|
||||
// evaluate the configuration to avoid paying penalty at first request.
|
||||
|
||||
Lazy::force(&config::CONFIG);
|
||||
Lazy::force(&instance_info::INSTANCE_INFO);
|
||||
|
||||
// Define default headers (added to all responses)
|
||||
app.default_headers = headers! {
|
||||
"Referrer-Policy" => "no-referrer",
|
||||
|
@ -186,21 +175,9 @@ async fn main() {
|
|||
app
|
||||
.at("/manifest.json")
|
||||
.get(|_| resource(include_str!("../static/manifest.json"), "application/json", false).boxed());
|
||||
app.at("/robots.txt").get(|_| {
|
||||
resource(
|
||||
if match config::get_setting("LIBREDDIT_ROBOTS_DISABLE_INDEXING") {
|
||||
Some(val) => val == "on",
|
||||
None => false,
|
||||
} {
|
||||
"User-agent: *\nDisallow: /"
|
||||
} else {
|
||||
"User-agent: *\nDisallow: /u/\nDisallow: /user/"
|
||||
},
|
||||
"text/plain",
|
||||
true,
|
||||
)
|
||||
.boxed()
|
||||
});
|
||||
app
|
||||
.at("/robots.txt")
|
||||
.get(|_| resource("User-agent: *\nDisallow: /u/\nDisallow: /user/", "text/plain", true).boxed());
|
||||
app.at("/favicon.ico").get(|_| favicon().boxed());
|
||||
app.at("/logo.png").get(|_| pwa_logo().boxed());
|
||||
app.at("/Inter.var.woff2").get(|_| font().boxed());
|
||||
|
@ -213,7 +190,7 @@ async fn main() {
|
|||
.at("/hls.min.js")
|
||||
.get(|_| resource(include_str!("../static/hls.min.js"), "text/javascript", false).boxed());
|
||||
|
||||
// Proxy media through Libreddit
|
||||
// Proxy media through Ferrit
|
||||
app.at("/vid/:id/:size").get(|r| proxy(r, "https://v.redd.it/{id}/DASH_{size}").boxed());
|
||||
app.at("/hls/:id/*path").get(|r| proxy(r, "https://v.redd.it/{id}/{path}").boxed());
|
||||
app.at("/img/*path").get(|r| proxy(r, "https://i.redd.it/{path}").boxed());
|
||||
|
@ -306,10 +283,6 @@ async fn main() {
|
|||
// Handle about pages
|
||||
app.at("/about").get(|req| error(req, "About pages aren't added yet".to_string()).boxed());
|
||||
|
||||
// Instance info page
|
||||
app.at("/info").get(|r| instance_info::instance_info(r).boxed());
|
||||
app.at("/info.:extension").get(|r| instance_info::instance_info(r).boxed());
|
||||
|
||||
app.at("/:id").get(|req: Request<Body>| {
|
||||
Box::pin(async move {
|
||||
match req.param("id").as_deref() {
|
||||
|
@ -317,7 +290,7 @@ async fn main() {
|
|||
Some("best" | "hot" | "new" | "top" | "rising" | "controversial") => subreddit::community(req).await,
|
||||
|
||||
// Short link for post
|
||||
Some(id) if (5..8).contains(&id.len()) => match canonical_path(format!("/{}", id)).await {
|
||||
Some(id) if (5..7).contains(&id.len()) => match canonical_path(format!("/{}", id)).await {
|
||||
Ok(path_opt) => match path_opt {
|
||||
Some(path) => Ok(redirect(path)),
|
||||
None => error(req, "Post ID is invalid. It may point to a post on a community that has been banned.").await,
|
||||
|
@ -334,7 +307,7 @@ async fn main() {
|
|||
// Default service in case no routes match
|
||||
app.at("/*").get(|req| error(req, "Nothing here".to_string()).boxed());
|
||||
|
||||
println!("Running Libreddit v{} on {}!", env!("CARGO_PKG_VERSION"), listener);
|
||||
println!("Running Ferrit v{} on {}!", env!("CARGO_PKG_VERSION"), listener);
|
||||
|
||||
let server = app.listen(listener);
|
||||
|
||||
|
|
240
src/post.rs
|
@ -1,6 +1,5 @@
|
|||
// CRATES
|
||||
use crate::client::json;
|
||||
use crate::config::get_setting;
|
||||
use crate::server::RequestExt;
|
||||
use crate::subreddit::{can_access_quarantine, quarantine};
|
||||
use crate::utils::{
|
||||
|
@ -9,8 +8,6 @@ use crate::utils::{
|
|||
use hyper::{Body, Request, Response};
|
||||
|
||||
use askama::Template;
|
||||
use once_cell::sync::Lazy;
|
||||
use regex::Regex;
|
||||
use std::collections::HashSet;
|
||||
|
||||
// STRUCTS
|
||||
|
@ -23,18 +20,13 @@ struct PostTemplate {
|
|||
prefs: Preferences,
|
||||
single_thread: bool,
|
||||
url: String,
|
||||
url_without_query: String,
|
||||
comment_query: String,
|
||||
}
|
||||
|
||||
static COMMENT_SEARCH_CAPTURE: Lazy<Regex> = Lazy::new(|| Regex::new(r#"\?q=(.*)&type=comment"#).unwrap());
|
||||
|
||||
pub async fn item(req: Request<Body>) -> Result<Response<Body>, String> {
|
||||
// Build Reddit API path
|
||||
let mut path: String = format!("{}.json?{}&raw_json=1", req.uri().path(), req.uri().query().unwrap_or_default());
|
||||
let sub = req.param("sub").unwrap_or_default();
|
||||
let quarantined = can_access_quarantine(&req, &sub);
|
||||
let url = req.uri().to_string();
|
||||
|
||||
// Set sort to sort query parameter
|
||||
let sort = param(&path, "sort").unwrap_or_else(|| {
|
||||
|
@ -64,41 +56,31 @@ pub async fn item(req: Request<Body>) -> Result<Response<Body>, String> {
|
|||
// Parse the JSON into Post and Comment structs
|
||||
let post = parse_post(&response[0]["data"]["children"][0]).await;
|
||||
|
||||
let req_url = req.uri().to_string();
|
||||
// Return landing page if this post if this Reddit deems this post
|
||||
// NSFW, but we have also disabled the display of NSFW content
|
||||
// or if the instance is SFW-only.
|
||||
if post.nsfw && crate::utils::should_be_nsfw_gated(&req, &req_url) {
|
||||
return Ok(nsfw_landing(req, req_url).await.unwrap_or_default());
|
||||
if post.nsfw && (setting(&req, "show_nsfw") != "on" || crate::utils::sfw_only()) {
|
||||
return Ok(nsfw_landing(req).await.unwrap_or_default());
|
||||
}
|
||||
|
||||
let query = match COMMENT_SEARCH_CAPTURE.captures(&url) {
|
||||
Some(captures) => captures.get(1).unwrap().as_str().replace("%20", " ").replace('+', " "),
|
||||
None => String::new(),
|
||||
};
|
||||
|
||||
let comments = match query.as_str() {
|
||||
"" => parse_comments(&response[1], &post.permalink, &post.author.name, highlighted_comment, &get_filters(&req), &req),
|
||||
_ => query_comments(&response[1], &post.permalink, &post.author.name, highlighted_comment, &get_filters(&req), &query, &req),
|
||||
};
|
||||
let comments = parse_comments(&response[1], &post.permalink, &post.author.name, highlighted_comment, &get_filters(&req));
|
||||
let url = req.uri().to_string();
|
||||
|
||||
// Use the Post and Comment structs to generate a website to show users
|
||||
template(PostTemplate {
|
||||
comments,
|
||||
post,
|
||||
url_without_query: url.clone().trim_end_matches(&format!("?q={query}&type=comment")).to_string(),
|
||||
sort,
|
||||
prefs: Preferences::new(&req),
|
||||
prefs: Preferences::new(req),
|
||||
single_thread,
|
||||
url: req_url,
|
||||
comment_query: query,
|
||||
url,
|
||||
})
|
||||
}
|
||||
// If the Reddit API returns an error, exit and send error page to user
|
||||
Err(msg) => {
|
||||
if msg == "quarantined" || msg == "gated" {
|
||||
if msg == "quarantined" {
|
||||
let sub = req.param("sub").unwrap_or_default();
|
||||
quarantine(req, sub, msg)
|
||||
quarantine(req, sub)
|
||||
} else {
|
||||
error(req, msg).await
|
||||
}
|
||||
|
@ -107,8 +89,7 @@ pub async fn item(req: Request<Body>) -> Result<Response<Body>, String> {
|
|||
}
|
||||
|
||||
// COMMENTS
|
||||
|
||||
fn parse_comments(json: &serde_json::Value, post_link: &str, post_author: &str, highlighted_comment: &str, filters: &HashSet<String>, req: &Request<Body>) -> Vec<Comment> {
|
||||
fn parse_comments(json: &serde_json::Value, post_link: &str, post_author: &str, highlighted_comment: &str, filters: &HashSet<String>) -> Vec<Comment> {
|
||||
// Parse the comment JSON into a Vector of Comments
|
||||
let comments = json["data"]["children"].as_array().map_or(Vec::new(), std::borrow::ToOwned::to_owned);
|
||||
|
||||
|
@ -116,138 +97,87 @@ fn parse_comments(json: &serde_json::Value, post_link: &str, post_author: &str,
|
|||
comments
|
||||
.into_iter()
|
||||
.map(|comment| {
|
||||
let kind = comment["kind"].as_str().unwrap_or_default().to_string();
|
||||
let data = &comment["data"];
|
||||
|
||||
let unix_time = data["created_utc"].as_f64().unwrap_or_default();
|
||||
let (rel_time, created) = time(unix_time);
|
||||
|
||||
let edited = data["edited"].as_f64().map_or((String::new(), String::new()), time);
|
||||
|
||||
let score = data["score"].as_i64().unwrap_or(0);
|
||||
|
||||
// If this comment contains replies, handle those too
|
||||
let replies: Vec<Comment> = if data["replies"].is_object() {
|
||||
parse_comments(&data["replies"], post_link, post_author, highlighted_comment, filters, req)
|
||||
parse_comments(&data["replies"], post_link, post_author, highlighted_comment, filters)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
build_comment(&comment, data, replies, post_link, post_author, highlighted_comment, filters, req)
|
||||
|
||||
let awards: Awards = Awards::parse(&data["all_awardings"]);
|
||||
|
||||
let parent_kind_and_id = val(&comment, "parent_id");
|
||||
let parent_info = parent_kind_and_id.split('_').collect::<Vec<&str>>();
|
||||
|
||||
let id = val(&comment, "id");
|
||||
let highlighted = id == highlighted_comment;
|
||||
|
||||
let body = if (val(&comment, "author") == "[deleted]" && val(&comment, "body") == "[removed]") || val(&comment, "body") == "[deleted]" {
|
||||
format!(
|
||||
"<div class=\"md\"><p>[removed] — <a href=\"https://www.unddit.com{}{}\">view removed comment</a></p></div>",
|
||||
post_link, id
|
||||
)
|
||||
} else {
|
||||
rewrite_urls(&val(&comment, "body_html"))
|
||||
};
|
||||
|
||||
let author = Author {
|
||||
name: val(&comment, "author"),
|
||||
flair: Flair {
|
||||
flair_parts: FlairPart::parse(
|
||||
data["author_flair_type"].as_str().unwrap_or_default(),
|
||||
data["author_flair_richtext"].as_array(),
|
||||
data["author_flair_text"].as_str(),
|
||||
),
|
||||
text: val(&comment, "link_flair_text"),
|
||||
background_color: val(&comment, "author_flair_background_color"),
|
||||
foreground_color: val(&comment, "author_flair_text_color"),
|
||||
},
|
||||
distinguished: val(&comment, "distinguished"),
|
||||
};
|
||||
let is_filtered = filters.contains(&["u_", author.name.as_str()].concat());
|
||||
|
||||
// Many subreddits have a default comment posted about the sub's rules etc.
|
||||
// Many Ferrit users do not wish to see this kind of comment by default.
|
||||
// Reddit does not tell us which users are "bots", so a good heuristic is to
|
||||
// collapse stickied moderator comments.
|
||||
let is_moderator_comment = data["distinguished"].as_str().unwrap_or_default() == "moderator";
|
||||
let is_stickied = data["stickied"].as_bool().unwrap_or_default();
|
||||
let collapsed = (is_moderator_comment && is_stickied) || is_filtered;
|
||||
|
||||
Comment {
|
||||
id,
|
||||
kind,
|
||||
parent_id: parent_info[1].to_string(),
|
||||
parent_kind: parent_info[0].to_string(),
|
||||
post_link: post_link.to_string(),
|
||||
post_author: post_author.to_string(),
|
||||
body,
|
||||
author,
|
||||
score: if data["score_hidden"].as_bool().unwrap_or_default() {
|
||||
("\u{2022}".to_string(), "Hidden".to_string())
|
||||
} else {
|
||||
format_num(score)
|
||||
},
|
||||
rel_time,
|
||||
created,
|
||||
edited,
|
||||
replies,
|
||||
highlighted,
|
||||
awards,
|
||||
collapsed,
|
||||
is_filtered,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn query_comments(
|
||||
json: &serde_json::Value,
|
||||
post_link: &str,
|
||||
post_author: &str,
|
||||
highlighted_comment: &str,
|
||||
filters: &HashSet<String>,
|
||||
query: &str,
|
||||
req: &Request<Body>,
|
||||
) -> Vec<Comment> {
|
||||
let comments = json["data"]["children"].as_array().map_or(Vec::new(), std::borrow::ToOwned::to_owned);
|
||||
let mut results = Vec::new();
|
||||
|
||||
comments.into_iter().for_each(|comment| {
|
||||
let data = &comment["data"];
|
||||
|
||||
// If this comment contains replies, handle those too
|
||||
if data["replies"].is_object() {
|
||||
results.append(&mut query_comments(&data["replies"], post_link, post_author, highlighted_comment, filters, query, req))
|
||||
}
|
||||
|
||||
let c = build_comment(&comment, data, Vec::new(), post_link, post_author, highlighted_comment, filters, req);
|
||||
if c.body.to_lowercase().contains(&query.to_lowercase()) {
|
||||
results.push(c);
|
||||
}
|
||||
});
|
||||
|
||||
results
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn build_comment(
|
||||
comment: &serde_json::Value,
|
||||
data: &serde_json::Value,
|
||||
replies: Vec<Comment>,
|
||||
post_link: &str,
|
||||
post_author: &str,
|
||||
highlighted_comment: &str,
|
||||
filters: &HashSet<String>,
|
||||
req: &Request<Body>,
|
||||
) -> Comment {
|
||||
let id = val(comment, "id");
|
||||
|
||||
let body = if (val(comment, "author") == "[deleted]" && val(comment, "body") == "[removed]") || val(comment, "body") == "[ Removed by Reddit ]" {
|
||||
format!(
|
||||
"<div class=\"md\"><p>[removed] — <a href=\"https://{}{}{}\">view removed comment</a></p></div>",
|
||||
get_setting("LIBREDDIT_PUSHSHIFT_FRONTEND").unwrap_or(String::from(crate::config::DEFAULT_PUSHSHIFT_FRONTEND)),
|
||||
post_link,
|
||||
id
|
||||
)
|
||||
} else {
|
||||
rewrite_urls(&val(comment, "body_html"))
|
||||
};
|
||||
let kind = comment["kind"].as_str().unwrap_or_default().to_string();
|
||||
|
||||
let unix_time = data["created_utc"].as_f64().unwrap_or_default();
|
||||
let (rel_time, created) = time(unix_time);
|
||||
|
||||
let edited = data["edited"].as_f64().map_or((String::new(), String::new()), time);
|
||||
|
||||
let score = data["score"].as_i64().unwrap_or(0);
|
||||
|
||||
// The JSON API only provides comments up to some threshold.
|
||||
// Further comments have to be loaded by subsequent requests.
|
||||
// The "kind" value will be "more" and the "count"
|
||||
// shows how many more (sub-)comments exist in the respective nesting level.
|
||||
// Note that in certain (seemingly random) cases, the count is simply wrong.
|
||||
let more_count = data["count"].as_i64().unwrap_or_default();
|
||||
|
||||
let awards: Awards = Awards::parse(&data["all_awardings"]);
|
||||
|
||||
let parent_kind_and_id = val(comment, "parent_id");
|
||||
let parent_info = parent_kind_and_id.split('_').collect::<Vec<&str>>();
|
||||
|
||||
let highlighted = id == highlighted_comment;
|
||||
|
||||
let author = Author {
|
||||
name: val(comment, "author"),
|
||||
flair: Flair {
|
||||
flair_parts: FlairPart::parse(
|
||||
data["author_flair_type"].as_str().unwrap_or_default(),
|
||||
data["author_flair_richtext"].as_array(),
|
||||
data["author_flair_text"].as_str(),
|
||||
),
|
||||
text: val(comment, "link_flair_text"),
|
||||
background_color: val(comment, "author_flair_background_color"),
|
||||
foreground_color: val(comment, "author_flair_text_color"),
|
||||
},
|
||||
distinguished: val(comment, "distinguished"),
|
||||
};
|
||||
let is_filtered = filters.contains(&["u_", author.name.as_str()].concat());
|
||||
|
||||
// Many subreddits have a default comment posted about the sub's rules etc.
|
||||
// Many libreddit users do not wish to see this kind of comment by default.
|
||||
// Reddit does not tell us which users are "bots", so a good heuristic is to
|
||||
// collapse stickied moderator comments.
|
||||
let is_moderator_comment = data["distinguished"].as_str().unwrap_or_default() == "moderator";
|
||||
let is_stickied = data["stickied"].as_bool().unwrap_or_default();
|
||||
let collapsed = (is_moderator_comment && is_stickied) || is_filtered;
|
||||
|
||||
Comment {
|
||||
id,
|
||||
kind,
|
||||
parent_id: parent_info[1].to_string(),
|
||||
parent_kind: parent_info[0].to_string(),
|
||||
post_link: post_link.to_string(),
|
||||
post_author: post_author.to_string(),
|
||||
body,
|
||||
author,
|
||||
score: if data["score_hidden"].as_bool().unwrap_or_default() {
|
||||
("\u{2022}".to_string(), "Hidden".to_string())
|
||||
} else {
|
||||
format_num(score)
|
||||
},
|
||||
rel_time,
|
||||
created,
|
||||
edited,
|
||||
replies,
|
||||
highlighted,
|
||||
awards,
|
||||
collapsed,
|
||||
is_filtered,
|
||||
more_count,
|
||||
prefs: Preferences::new(req),
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,8 +7,6 @@ use crate::{
|
|||
};
|
||||
use askama::Template;
|
||||
use hyper::{Body, Request, Response};
|
||||
use once_cell::sync::Lazy;
|
||||
use regex::Regex;
|
||||
|
||||
// STRUCTS
|
||||
struct SearchParams {
|
||||
|
@ -46,12 +44,8 @@ struct SearchTemplate {
|
|||
all_posts_filtered: bool,
|
||||
/// Whether all posts were hidden because they are NSFW (and user has disabled show NSFW)
|
||||
all_posts_hidden_nsfw: bool,
|
||||
no_posts: bool,
|
||||
}
|
||||
|
||||
// Regex matched against search queries to determine if they are reddit urls.
|
||||
static REDDIT_URL_MATCH: Lazy<Regex> = Lazy::new(|| Regex::new(r"^https?://([^\./]+\.)*reddit.com/").unwrap());
|
||||
|
||||
// SERVICES
|
||||
pub async fn find(req: Request<Body>) -> Result<Response<Body>, String> {
|
||||
// This ensures that during a search, no NSFW posts are fetched at all
|
||||
|
@ -61,8 +55,7 @@ pub async fn find(req: Request<Body>) -> Result<Response<Body>, String> {
|
|||
""
|
||||
};
|
||||
let path = format!("{}.json?{}{}&raw_json=1", req.uri().path(), req.uri().query().unwrap_or_default(), nsfw_results);
|
||||
let mut query = param(&path, "q").unwrap_or_default();
|
||||
query = REDDIT_URL_MATCH.replace(&query, "").to_string();
|
||||
let query = param(&path, "q").unwrap_or_default();
|
||||
|
||||
if query.is_empty() {
|
||||
return Ok(redirect("/".to_string()));
|
||||
|
@ -110,19 +103,17 @@ pub async fn find(req: Request<Body>) -> Result<Response<Body>, String> {
|
|||
restrict_sr: param(&path, "restrict_sr").unwrap_or_default(),
|
||||
typed,
|
||||
},
|
||||
prefs: Preferences::new(&req),
|
||||
prefs: Preferences::new(req),
|
||||
url,
|
||||
is_filtered: true,
|
||||
all_posts_filtered: false,
|
||||
all_posts_hidden_nsfw: false,
|
||||
no_posts: false,
|
||||
})
|
||||
} else {
|
||||
match Post::fetch(&path, quarantined).await {
|
||||
Ok((mut posts, after)) => {
|
||||
let (_, all_posts_filtered) = filter_posts(&mut posts, &filters);
|
||||
let no_posts = posts.is_empty();
|
||||
let all_posts_hidden_nsfw = !no_posts && (posts.iter().all(|p| p.flags.nsfw) && setting(&req, "show_nsfw") != "on");
|
||||
let all_posts_hidden_nsfw = posts.iter().all(|p| p.flags.nsfw) && setting(&req, "show_nsfw") != "on";
|
||||
template(SearchTemplate {
|
||||
posts,
|
||||
subreddits,
|
||||
|
@ -136,18 +127,17 @@ pub async fn find(req: Request<Body>) -> Result<Response<Body>, String> {
|
|||
restrict_sr: param(&path, "restrict_sr").unwrap_or_default(),
|
||||
typed,
|
||||
},
|
||||
prefs: Preferences::new(&req),
|
||||
prefs: Preferences::new(req),
|
||||
url,
|
||||
is_filtered: false,
|
||||
all_posts_filtered,
|
||||
all_posts_hidden_nsfw,
|
||||
no_posts,
|
||||
})
|
||||
}
|
||||
Err(msg) => {
|
||||
if msg == "quarantined" || msg == "gated" {
|
||||
if msg == "quarantined" {
|
||||
let sub = req.param("sub").unwrap_or_default();
|
||||
quarantine(req, sub, msg)
|
||||
quarantine(req, sub)
|
||||
} else {
|
||||
error(req, msg).await
|
||||
}
|
||||
|
|
237
src/server.rs
|
@ -1,11 +1,10 @@
|
|||
use brotli::enc::{BrotliCompress, BrotliEncoderParams};
|
||||
use cached::proc_macro::cached;
|
||||
use cookie::Cookie;
|
||||
use core::f64;
|
||||
use futures_lite::{future::Boxed, Future, FutureExt};
|
||||
use hyper::{
|
||||
body,
|
||||
body::HttpBody,
|
||||
body::{Buf, HttpBody},
|
||||
header,
|
||||
service::{make_service_fn, service_fn},
|
||||
HeaderMap,
|
||||
|
@ -28,7 +27,7 @@ use crate::dbg_msg;
|
|||
type BoxResponse = Pin<Box<dyn Future<Output = Result<Response<Body>, String>> + Send>>;
|
||||
|
||||
/// Compressors for the response Body, in ascending order of preference.
|
||||
#[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
#[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||||
enum CompressionType {
|
||||
Passthrough,
|
||||
Gzip,
|
||||
|
@ -43,9 +42,6 @@ enum CompressionType {
|
|||
const DEFAULT_COMPRESSOR: CompressionType = CompressionType::Gzip;
|
||||
|
||||
impl CompressionType {
|
||||
/// Returns a `CompressionType` given a content coding
|
||||
/// in [RFC 7231](https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.4)
|
||||
/// format.
|
||||
fn parse(s: &str) -> Option<CompressionType> {
|
||||
let c = match s {
|
||||
// Compressors we support.
|
||||
|
@ -67,11 +63,14 @@ impl CompressionType {
|
|||
|
||||
impl ToString for CompressionType {
|
||||
fn to_string(&self) -> String {
|
||||
match self {
|
||||
CompressionType::Gzip => "gzip".to_string(),
|
||||
CompressionType::Brotli => "br".to_string(),
|
||||
_ => String::new(),
|
||||
}
|
||||
let s: &str = match *self {
|
||||
CompressionType::Gzip => "gzip",
|
||||
CompressionType::Brotli => "br",
|
||||
|
||||
_ => "",
|
||||
};
|
||||
|
||||
s.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -194,7 +193,7 @@ impl Route<'_> {
|
|||
|
||||
impl Server {
|
||||
pub fn new() -> Self {
|
||||
Server {
|
||||
Self {
|
||||
default_headers: HeaderMap::new(),
|
||||
router: Router::new(),
|
||||
}
|
||||
|
@ -243,7 +242,7 @@ impl Server {
|
|||
match func.await {
|
||||
Ok(mut res) => {
|
||||
res.headers_mut().extend(def_headers);
|
||||
let _ = compress_response(&req_headers, &mut res).await;
|
||||
let _ = compress_response(req_headers, &mut res).await;
|
||||
|
||||
Ok(res)
|
||||
}
|
||||
|
@ -253,7 +252,7 @@ impl Server {
|
|||
.boxed()
|
||||
}
|
||||
// If there was a routing error
|
||||
Err(e) => new_boilerplate(def_headers, req_headers, 404, e.into()).boxed(),
|
||||
Err(e) => async move { new_boilerplate(def_headers, req_headers, 404, e.into()).await }.boxed(),
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
@ -282,7 +281,7 @@ async fn new_boilerplate(
|
|||
) -> Result<Response<Body>, String> {
|
||||
match Response::builder().status(status).body(body) {
|
||||
Ok(mut res) => {
|
||||
let _ = compress_response(&req_headers, &mut res).await;
|
||||
let _ = compress_response(req_headers, &mut res).await;
|
||||
|
||||
res.headers_mut().extend(default_headers.clone());
|
||||
Ok(res)
|
||||
|
@ -306,8 +305,7 @@ async fn new_boilerplate(
|
|||
/// Accept-Encoding: gzip, compress, br
|
||||
/// Accept-Encoding: br;q=1.0, gzip;q=0.8, *;q=0.1
|
||||
/// ```
|
||||
#[cached]
|
||||
fn determine_compressor(accept_encoding: String) -> Option<CompressionType> {
|
||||
fn determine_compressor(accept_encoding: &str) -> Option<CompressionType> {
|
||||
if accept_encoding.is_empty() {
|
||||
return None;
|
||||
};
|
||||
|
@ -347,7 +345,7 @@ fn determine_compressor(accept_encoding: String) -> Option<CompressionType> {
|
|||
|
||||
impl PartialOrd for CompressorCandidate {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
// Guard against NAN, both on our end and on the other.
|
||||
// Guard against NaN, both on our end and on the other.
|
||||
if self.q.is_nan() || other.q.is_nan() {
|
||||
return None;
|
||||
};
|
||||
|
@ -379,7 +377,7 @@ fn determine_compressor(accept_encoding: String) -> Option<CompressionType> {
|
|||
|
||||
// This loop reads the requested compressors and keeps track of whichever
|
||||
// one has the highest priority per our heuristic.
|
||||
for val in accept_encoding.split(',') {
|
||||
for val in accept_encoding.to_string().split(',') {
|
||||
let mut q: f64 = 1.0;
|
||||
|
||||
// The compressor and q-value (if the latter is defined)
|
||||
|
@ -474,7 +472,7 @@ fn determine_compressor(accept_encoding: String) -> Option<CompressionType> {
|
|||
///
|
||||
/// This function logs errors to stderr, but only in debug mode. No information
|
||||
/// is logged in release builds.
|
||||
async fn compress_response(req_headers: &HeaderMap<header::HeaderValue>, res: &mut Response<Body>) -> Result<(), String> {
|
||||
async fn compress_response(req_headers: HeaderMap<header::HeaderValue>, res: &mut Response<Body>) -> Result<(), String> {
|
||||
// Check if the data is eligible for compression.
|
||||
if let Some(hdr) = res.headers().get(header::CONTENT_TYPE) {
|
||||
match from_utf8(hdr.as_bytes()) {
|
||||
|
@ -504,22 +502,30 @@ async fn compress_response(req_headers: &HeaderMap<header::HeaderValue>, res: &m
|
|||
return Ok(());
|
||||
};
|
||||
|
||||
// Quick and dirty closure for extracting a header from the request and
|
||||
// returning it as a &str.
|
||||
let get_req_header = |k: header::HeaderName| -> Option<&str> {
|
||||
match req_headers.get(k) {
|
||||
Some(hdr) => match from_utf8(hdr.as_bytes()) {
|
||||
Ok(val) => Some(val),
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
Err(e) => {
|
||||
dbg_msg!(e);
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(not(debug_assertions))]
|
||||
Err(_) => None,
|
||||
},
|
||||
None => None,
|
||||
}
|
||||
};
|
||||
|
||||
// Check to see which compressor is requested, and if we can use it.
|
||||
let accept_encoding: String = match req_headers.get(header::ACCEPT_ENCODING) {
|
||||
let accept_encoding: &str = match get_req_header(header::ACCEPT_ENCODING) {
|
||||
Some(val) => val,
|
||||
None => return Ok(()), // Client requested no compression.
|
||||
|
||||
Some(hdr) => match String::from_utf8(hdr.as_bytes().into()) {
|
||||
Ok(val) => val,
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
Err(e) => {
|
||||
dbg_msg!(e);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
#[cfg(not(debug_assertions))]
|
||||
Err(_) => return Ok(()),
|
||||
},
|
||||
};
|
||||
|
||||
let compressor: CompressionType = match determine_compressor(accept_encoding) {
|
||||
|
@ -527,95 +533,72 @@ async fn compress_response(req_headers: &HeaderMap<header::HeaderValue>, res: &m
|
|||
None => return Ok(()),
|
||||
};
|
||||
|
||||
// Get the body from the response.
|
||||
let body_bytes: Vec<u8> = match body::to_bytes(res.body_mut()).await {
|
||||
Ok(b) => b.to_vec(),
|
||||
Err(e) => {
|
||||
dbg_msg!(e);
|
||||
return Err(e.to_string());
|
||||
}
|
||||
};
|
||||
// Perform the compression.
|
||||
let compressed: Vec<u8>;
|
||||
{
|
||||
// Get the body from the response.
|
||||
let mut aggregated_body = match body::aggregate(res.body_mut()).await {
|
||||
Ok(b) => b.reader(),
|
||||
Err(e) => {
|
||||
dbg_msg!(e);
|
||||
return Err(e.to_string());
|
||||
}
|
||||
};
|
||||
|
||||
// Compress!
|
||||
match compress_body(compressor, body_bytes) {
|
||||
Ok(compressed) => {
|
||||
// We get here iff the compression was successful. Replace the body
|
||||
// with the compressed payload, and add the appropriate
|
||||
// Content-Encoding header in the response.
|
||||
res.headers_mut().insert(header::CONTENT_ENCODING, compressor.to_string().parse().unwrap());
|
||||
*(res.body_mut()) = Body::from(compressed);
|
||||
}
|
||||
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Compresses a `Vec<u8>` given a [`CompressionType`].
|
||||
///
|
||||
/// This is a helper function for [`compress_response`] and should not be
|
||||
/// called directly.
|
||||
|
||||
// I've chosen a TTL of 600 (== 10 minutes) since compression is
|
||||
// computationally expensive and we don't want to be doing it often. This is
|
||||
// larger than client::json's TTL, but that's okay, because if client::json
|
||||
// returns a new serde_json::Value, body_bytes changes, so this function will
|
||||
// execute again.
|
||||
#[cached(size = 100, time = 600, result = true)]
|
||||
fn compress_body(compressor: CompressionType, body_bytes: Vec<u8>) -> Result<Vec<u8>, String> {
|
||||
// io::Cursor implements io::Read, required for our encoders.
|
||||
let mut reader = io::Cursor::new(body_bytes);
|
||||
|
||||
let compressed: Vec<u8> = match compressor {
|
||||
CompressionType::Gzip => {
|
||||
let mut gz: gzip::Encoder<Vec<u8>> = match gzip::Encoder::new(Vec::new()) {
|
||||
Ok(gz) => gz,
|
||||
Err(e) => {
|
||||
dbg_msg!(e);
|
||||
return Err(e.to_string());
|
||||
}
|
||||
};
|
||||
|
||||
match io::copy(&mut reader, &mut gz) {
|
||||
Ok(_) => match gz.finish().into_result() {
|
||||
Ok(compressed) => compressed,
|
||||
// Compress!
|
||||
compressed = match compressor {
|
||||
CompressionType::Gzip => {
|
||||
let mut gz: gzip::Encoder<Vec<u8>> = match gzip::Encoder::new(Vec::new()) {
|
||||
Ok(gz) => gz,
|
||||
Err(e) => {
|
||||
dbg_msg!(e);
|
||||
return Err(e.to_string());
|
||||
}
|
||||
};
|
||||
|
||||
match io::copy(&mut aggregated_body, &mut gz) {
|
||||
Ok(_) => match gz.finish().into_result() {
|
||||
Ok(compressed) => compressed,
|
||||
Err(e) => {
|
||||
dbg_msg!(e);
|
||||
return Err(e.to_string());
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
dbg_msg!(e);
|
||||
return Err(e.to_string());
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
dbg_msg!(e);
|
||||
return Err(e.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CompressionType::Brotli => {
|
||||
// We may want to make the compression parameters configurable
|
||||
// in the future. For now, the defaults are sufficient.
|
||||
let brotli_params = BrotliEncoderParams::default();
|
||||
CompressionType::Brotli => {
|
||||
// We may want to make the compression parameters configurable
|
||||
// in the future. For now, the defaults are sufficient.
|
||||
let brotli_params = BrotliEncoderParams::default();
|
||||
|
||||
let mut compressed = Vec::<u8>::new();
|
||||
match BrotliCompress(&mut reader, &mut compressed, &brotli_params) {
|
||||
Ok(_) => compressed,
|
||||
Err(e) => {
|
||||
dbg_msg!(e);
|
||||
return Err(e.to_string());
|
||||
let mut compressed = Vec::<u8>::new();
|
||||
match BrotliCompress(&mut aggregated_body, &mut compressed, &brotli_params) {
|
||||
Ok(_) => compressed,
|
||||
Err(e) => {
|
||||
dbg_msg!(e);
|
||||
return Err(e.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// This arm is for any requested compressor for which we don't yet
|
||||
// have an implementation.
|
||||
_ => {
|
||||
let msg = "unsupported compressor".to_string();
|
||||
return Err(msg);
|
||||
}
|
||||
};
|
||||
// This arm is for any requested compressor for which we don't yet
|
||||
// have an implementation.
|
||||
_ => return Ok(()),
|
||||
};
|
||||
}
|
||||
|
||||
Ok(compressed)
|
||||
// We get here iff the compression was successful. Replace the body with
|
||||
// the compressed payload, and add the appropriate Content-Encoding header
|
||||
// in the response.
|
||||
res.headers_mut().insert(header::CONTENT_ENCODING, compressor.to_string().parse().unwrap());
|
||||
*(res.body_mut()) = Body::from(compressed);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
@ -629,18 +612,18 @@ mod tests {
|
|||
#[test]
|
||||
fn test_determine_compressor() {
|
||||
// Single compressor given.
|
||||
assert_eq!(determine_compressor("unsupported".to_string()), None);
|
||||
assert_eq!(determine_compressor("gzip".to_string()), Some(CompressionType::Gzip));
|
||||
assert_eq!(determine_compressor("*".to_string()), Some(DEFAULT_COMPRESSOR));
|
||||
assert_eq!(determine_compressor("unsupported"), None);
|
||||
assert_eq!(determine_compressor("gzip"), Some(CompressionType::Gzip));
|
||||
assert_eq!(determine_compressor("*"), Some(DEFAULT_COMPRESSOR));
|
||||
|
||||
// Multiple compressors.
|
||||
assert_eq!(determine_compressor("gzip, br".to_string()), Some(CompressionType::Brotli));
|
||||
assert_eq!(determine_compressor("gzip;q=0.8, br;q=0.3".to_string()), Some(CompressionType::Gzip));
|
||||
assert_eq!(determine_compressor("br, gzip".to_string()), Some(CompressionType::Brotli));
|
||||
assert_eq!(determine_compressor("br;q=0.3, gzip;q=0.4".to_string()), Some(CompressionType::Gzip));
|
||||
assert_eq!(determine_compressor("gzip, br"), Some(CompressionType::Brotli));
|
||||
assert_eq!(determine_compressor("gzip;q=0.8, br;q=0.3"), Some(CompressionType::Gzip));
|
||||
assert_eq!(determine_compressor("br, gzip"), Some(CompressionType::Brotli));
|
||||
assert_eq!(determine_compressor("br;q=0.3, gzip;q=0.4"), Some(CompressionType::Gzip));
|
||||
|
||||
// Invalid q-values.
|
||||
assert_eq!(determine_compressor("gzip;q=NAN".to_string()), None);
|
||||
assert_eq!(determine_compressor("gzip;q=NAN"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
@ -657,7 +640,7 @@ mod tests {
|
|||
};
|
||||
}
|
||||
|
||||
for accept_encoding in [
|
||||
for accept_encoding in vec![
|
||||
"*",
|
||||
ae_gen!(CompressionType::Gzip),
|
||||
ae_gen!(CompressionType::Brotli, CompressionType::Gzip),
|
||||
|
@ -665,9 +648,9 @@ mod tests {
|
|||
] {
|
||||
// Determine what the expected encoding should be based on both the
|
||||
// specific encodings we accept.
|
||||
let expected_encoding: CompressionType = match determine_compressor(accept_encoding.to_string()) {
|
||||
let expected_encoding: CompressionType = match determine_compressor(accept_encoding) {
|
||||
Some(s) => s,
|
||||
None => panic!("determine_compressor(accept_encoding.to_string()) => None"),
|
||||
None => panic!("determine_compressor(accept_encoding) => None"),
|
||||
};
|
||||
|
||||
// Build headers with our Accept-Encoding.
|
||||
|
@ -684,8 +667,8 @@ mod tests {
|
|||
.unwrap();
|
||||
|
||||
// Perform the compression.
|
||||
if let Err(e) = block_on(compress_response(&req_headers, &mut res)) {
|
||||
panic!("compress_response(&req_headers, &mut res) => Err(\"{}\")", e);
|
||||
if let Err(e) = block_on(compress_response(req_headers, &mut res)) {
|
||||
panic!("compress_response(req_headers, &mut res) => Err(\"{}\")", e);
|
||||
};
|
||||
|
||||
// If the content was compressed, we expect the Content-Encoding
|
||||
|
@ -718,8 +701,7 @@ mod tests {
|
|||
// This provides an io::Read for the underlying body.
|
||||
let mut body_cursor: io::Cursor<Vec<u8>> = io::Cursor::new(body_vec);
|
||||
|
||||
// Match the appropriate decompresor for the given
|
||||
// expected_encoding.
|
||||
// Match the appropriate decompresor for the given expected_encoding.
|
||||
let mut decoder: Box<dyn io::Read> = match expected_encoding {
|
||||
CompressionType::Gzip => match gzip::Decoder::new(&mut body_cursor) {
|
||||
Ok(dgz) => Box::new(dgz),
|
||||
|
@ -732,8 +714,9 @@ mod tests {
|
|||
};
|
||||
|
||||
let mut decompressed = Vec::<u8>::new();
|
||||
if let Err(e) = io::copy(&mut decoder, &mut decompressed) {
|
||||
panic!("{}", e);
|
||||
match io::copy(&mut decoder, &mut decompressed) {
|
||||
Ok(_) => {}
|
||||
Err(e) => panic!("{}", e),
|
||||
};
|
||||
|
||||
assert!(decompressed.eq(&expected_lorem_ipsum));
|
||||
|
|
|
@ -19,7 +19,7 @@ struct SettingsTemplate {
|
|||
|
||||
// CONSTANTS
|
||||
|
||||
const PREFS: [&str; 13] = [
|
||||
const PREFS: [&str; 11] = [
|
||||
"theme",
|
||||
"front_page",
|
||||
"layout",
|
||||
|
@ -31,8 +31,6 @@ const PREFS: [&str; 13] = [
|
|||
"use_hls",
|
||||
"hide_hls_notification",
|
||||
"autoplay_videos",
|
||||
"hide_awards",
|
||||
"disable_visit_reddit_confirmation",
|
||||
];
|
||||
|
||||
// FUNCTIONS
|
||||
|
@ -41,7 +39,7 @@ const PREFS: [&str; 13] = [
|
|||
pub async fn get(req: Request<Body>) -> Result<Response<Body>, String> {
|
||||
let url = req.uri().to_string();
|
||||
template(SettingsTemplate {
|
||||
prefs: Preferences::new(&req),
|
||||
prefs: Preferences::new(req),
|
||||
url,
|
||||
})
|
||||
}
|
||||
|
|
|
@ -26,7 +26,6 @@ struct SubredditTemplate {
|
|||
all_posts_filtered: bool,
|
||||
/// Whether all posts were hidden because they are NSFW (and user has disabled show NSFW)
|
||||
all_posts_hidden_nsfw: bool,
|
||||
no_posts: bool,
|
||||
}
|
||||
|
||||
#[derive(Template)]
|
||||
|
@ -97,11 +96,10 @@ pub async fn community(req: Request<Body>) -> Result<Response<Body>, String> {
|
|||
}
|
||||
};
|
||||
|
||||
let req_url = req.uri().to_string();
|
||||
// Return landing page if this post if this is NSFW community but the user
|
||||
// has disabled the display of NSFW content or if the instance is SFW-only.
|
||||
if sub.nsfw && crate::utils::should_be_nsfw_gated(&req, &req_url) {
|
||||
return Ok(nsfw_landing(req, req_url).await.unwrap_or_default());
|
||||
if sub.nsfw && (setting(&req, "show_nsfw") != "on" || crate::utils::sfw_only()) {
|
||||
return Ok(nsfw_landing(req).await.unwrap_or_default());
|
||||
}
|
||||
|
||||
let path = format!("/r/{}/{}.json?{}&raw_json=1", sub_name.clone(), sort, req.uri().query().unwrap_or_default());
|
||||
|
@ -116,36 +114,33 @@ pub async fn community(req: Request<Body>) -> Result<Response<Body>, String> {
|
|||
posts: Vec::new(),
|
||||
sort: (sort, param(&path, "t").unwrap_or_default()),
|
||||
ends: (param(&path, "after").unwrap_or_default(), "".to_string()),
|
||||
prefs: Preferences::new(&req),
|
||||
prefs: Preferences::new(req),
|
||||
url,
|
||||
redirect_url,
|
||||
is_filtered: true,
|
||||
all_posts_filtered: false,
|
||||
all_posts_hidden_nsfw: false,
|
||||
no_posts: false,
|
||||
})
|
||||
} else {
|
||||
match Post::fetch(&path, quarantined).await {
|
||||
Ok((mut posts, after)) => {
|
||||
let (_, all_posts_filtered) = filter_posts(&mut posts, &filters);
|
||||
let no_posts = posts.is_empty();
|
||||
let all_posts_hidden_nsfw = !no_posts && (posts.iter().all(|p| p.flags.nsfw) && setting(&req, "show_nsfw") != "on");
|
||||
let all_posts_hidden_nsfw = posts.iter().all(|p| p.flags.nsfw) && setting(&req, "show_nsfw") != "on";
|
||||
template(SubredditTemplate {
|
||||
sub,
|
||||
posts,
|
||||
sort: (sort, param(&path, "t").unwrap_or_default()),
|
||||
ends: (param(&path, "after").unwrap_or_default(), after),
|
||||
prefs: Preferences::new(&req),
|
||||
prefs: Preferences::new(req),
|
||||
url,
|
||||
redirect_url,
|
||||
is_filtered: false,
|
||||
all_posts_filtered,
|
||||
all_posts_hidden_nsfw,
|
||||
no_posts,
|
||||
})
|
||||
}
|
||||
Err(msg) => match msg.as_str() {
|
||||
"quarantined" | "gated" => quarantine(req, sub_name, msg),
|
||||
"quarantined" => quarantine(req, sub_name),
|
||||
"private" => error(req, format!("r/{} is a private community", sub_name)).await,
|
||||
"banned" => error(req, format!("r/{} has been banned from Reddit", sub_name)).await,
|
||||
_ => error(req, msg).await,
|
||||
|
@ -154,13 +149,13 @@ pub async fn community(req: Request<Body>) -> Result<Response<Body>, String> {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn quarantine(req: Request<Body>, sub: String, restriction: String) -> Result<Response<Body>, String> {
|
||||
pub fn quarantine(req: Request<Body>, sub: String) -> Result<Response<Body>, String> {
|
||||
let wall = WallTemplate {
|
||||
title: format!("r/{} is {}", sub, restriction),
|
||||
title: format!("r/{} is quarantined", sub),
|
||||
msg: "Please click the button below to continue to this subreddit.".to_string(),
|
||||
url: req.uri().to_string(),
|
||||
sub,
|
||||
prefs: Preferences::new(&req),
|
||||
prefs: Preferences::new(req),
|
||||
};
|
||||
|
||||
Ok(
|
||||
|
@ -207,7 +202,7 @@ pub async fn subscriptions_filters(req: Request<Body>) -> Result<Response<Body>,
|
|||
|
||||
let query = req.uri().query().unwrap_or_default().to_string();
|
||||
|
||||
let preferences = Preferences::new(&req);
|
||||
let preferences = Preferences::new(req);
|
||||
let mut sub_list = preferences.subscriptions;
|
||||
let mut filters = preferences.filters;
|
||||
|
||||
|
@ -268,11 +263,7 @@ pub async fn subscriptions_filters(req: Request<Body>) -> Result<Response<Body>,
|
|||
|
||||
// Redirect back to subreddit
|
||||
// check for redirect parameter if unsubscribing/unfiltering from outside sidebar
|
||||
let path = if let Some(redirect_path) = param(&format!("?{}", query), "redirect") {
|
||||
format!("/{}", redirect_path)
|
||||
} else {
|
||||
format!("/r/{}", sub)
|
||||
};
|
||||
let path = param(&format!("?{}", query), "redirect").map_or_else(|| format!("/r/{}", sub), |redirect_path| format!("/{}", redirect_path));
|
||||
|
||||
let mut response = redirect(path);
|
||||
|
||||
|
@ -320,12 +311,12 @@ pub async fn wiki(req: Request<Body>) -> Result<Response<Body>, String> {
|
|||
sub,
|
||||
wiki: rewrite_urls(response["data"]["content_html"].as_str().unwrap_or("<h3>Wiki not found</h3>")),
|
||||
page,
|
||||
prefs: Preferences::new(&req),
|
||||
prefs: Preferences::new(req),
|
||||
url,
|
||||
}),
|
||||
Err(msg) => {
|
||||
if msg == "quarantined" || msg == "gated" {
|
||||
quarantine(req, sub, msg)
|
||||
if msg == "quarantined" {
|
||||
quarantine(req, sub)
|
||||
} else {
|
||||
error(req, msg).await
|
||||
}
|
||||
|
@ -358,12 +349,12 @@ pub async fn sidebar(req: Request<Body>) -> Result<Response<Body>, String> {
|
|||
// ),
|
||||
sub,
|
||||
page: "Sidebar".to_string(),
|
||||
prefs: Preferences::new(&req),
|
||||
prefs: Preferences::new(req),
|
||||
url,
|
||||
}),
|
||||
Err(msg) => {
|
||||
if msg == "quarantined" || msg == "gated" {
|
||||
quarantine(req, sub, msg)
|
||||
if msg == "quarantined" {
|
||||
quarantine(req, sub)
|
||||
} else {
|
||||
error(req, msg).await
|
||||
}
|
||||
|
|
17
src/user.rs
|
@ -26,7 +26,6 @@ struct UserTemplate {
|
|||
all_posts_filtered: bool,
|
||||
/// Whether all posts were hidden because they are NSFW (and user has disabled show NSFW)
|
||||
all_posts_hidden_nsfw: bool,
|
||||
no_posts: bool,
|
||||
}
|
||||
|
||||
// FUNCTIONS
|
||||
|
@ -43,19 +42,18 @@ pub async fn profile(req: Request<Body>) -> Result<Response<Body>, String> {
|
|||
let url = String::from(req.uri().path_and_query().map_or("", |val| val.as_str()));
|
||||
let redirect_url = url[1..].replace('?', "%3F").replace('&', "%26");
|
||||
|
||||
// Retrieve other variables from Libreddit request
|
||||
// Retrieve other variables from Ferrit request
|
||||
let sort = param(&path, "sort").unwrap_or_default();
|
||||
let username = req.param("name").unwrap_or_default();
|
||||
|
||||
// Retrieve info from user about page.
|
||||
let user = user(&username).await.unwrap_or_default();
|
||||
|
||||
let req_url = req.uri().to_string();
|
||||
// Return landing page if this post if this Reddit deems this user NSFW,
|
||||
// but we have also disabled the display of NSFW content or if the instance
|
||||
// is SFW-only.
|
||||
if user.nsfw && crate::utils::should_be_nsfw_gated(&req, &req_url) {
|
||||
return Ok(nsfw_landing(req, req_url).await.unwrap_or_default());
|
||||
if user.nsfw && (setting(&req, "show_nsfw") != "on" || crate::utils::sfw_only()) {
|
||||
return Ok(nsfw_landing(req).await.unwrap_or_default());
|
||||
}
|
||||
|
||||
let filters = get_filters(&req);
|
||||
|
@ -66,34 +64,31 @@ pub async fn profile(req: Request<Body>) -> Result<Response<Body>, String> {
|
|||
sort: (sort, param(&path, "t").unwrap_or_default()),
|
||||
ends: (param(&path, "after").unwrap_or_default(), "".to_string()),
|
||||
listing,
|
||||
prefs: Preferences::new(&req),
|
||||
prefs: Preferences::new(req),
|
||||
url,
|
||||
redirect_url,
|
||||
is_filtered: true,
|
||||
all_posts_filtered: false,
|
||||
all_posts_hidden_nsfw: false,
|
||||
no_posts: false,
|
||||
})
|
||||
} else {
|
||||
// Request user posts/comments from Reddit
|
||||
match Post::fetch(&path, false).await {
|
||||
Ok((mut posts, after)) => {
|
||||
let (_, all_posts_filtered) = filter_posts(&mut posts, &filters);
|
||||
let no_posts = posts.is_empty();
|
||||
let all_posts_hidden_nsfw = !no_posts && (posts.iter().all(|p| p.flags.nsfw) && setting(&req, "show_nsfw") != "on");
|
||||
let all_posts_hidden_nsfw = posts.iter().all(|p| p.flags.nsfw) && setting(&req, "show_nsfw") != "on";
|
||||
template(UserTemplate {
|
||||
user,
|
||||
posts,
|
||||
sort: (sort, param(&path, "t").unwrap_or_default()),
|
||||
ends: (param(&path, "after").unwrap_or_default(), after),
|
||||
listing,
|
||||
prefs: Preferences::new(&req),
|
||||
prefs: Preferences::new(req),
|
||||
url,
|
||||
redirect_url,
|
||||
is_filtered: false,
|
||||
all_posts_filtered,
|
||||
all_posts_hidden_nsfw,
|
||||
no_posts,
|
||||
})
|
||||
}
|
||||
// If there is an error show error page
|
||||
|
|
298
src/utils.rs
|
@ -1,4 +1,3 @@
|
|||
use crate::config::get_setting;
|
||||
//
|
||||
// CRATES
|
||||
//
|
||||
|
@ -6,7 +5,6 @@ use crate::{client::json, server::RequestExt};
|
|||
use askama::Template;
|
||||
use cookie::Cookie;
|
||||
use hyper::{Body, Request, Response};
|
||||
use once_cell::sync::Lazy;
|
||||
use regex::Regex;
|
||||
use rust_embed::RustEmbed;
|
||||
use serde_json::Value;
|
||||
|
@ -98,61 +96,6 @@ pub struct Author {
|
|||
pub distinguished: String,
|
||||
}
|
||||
|
||||
pub struct Poll {
|
||||
pub poll_options: Vec<PollOption>,
|
||||
pub voting_end_timestamp: (String, String),
|
||||
pub total_vote_count: u64,
|
||||
}
|
||||
|
||||
impl Poll {
|
||||
pub fn parse(poll_data: &Value) -> Option<Self> {
|
||||
poll_data.as_object()?;
|
||||
|
||||
let total_vote_count = poll_data["total_vote_count"].as_u64()?;
|
||||
// voting_end_timestamp is in the format of milliseconds
|
||||
let voting_end_timestamp = time(poll_data["voting_end_timestamp"].as_f64()? / 1000.0);
|
||||
let poll_options = PollOption::parse(&poll_data["options"])?;
|
||||
|
||||
Some(Self {
|
||||
poll_options,
|
||||
total_vote_count,
|
||||
voting_end_timestamp,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn most_votes(&self) -> u64 {
|
||||
self.poll_options.iter().filter_map(|o| o.vote_count).max().unwrap_or(0)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PollOption {
|
||||
pub id: u64,
|
||||
pub text: String,
|
||||
pub vote_count: Option<u64>,
|
||||
}
|
||||
|
||||
impl PollOption {
|
||||
pub fn parse(options: &Value) -> Option<Vec<Self>> {
|
||||
Some(
|
||||
options
|
||||
.as_array()?
|
||||
.iter()
|
||||
.filter_map(|option| {
|
||||
// For each poll option
|
||||
|
||||
// we can't just use as_u64() because "id": String("...") and serde would parse it as None
|
||||
let id = option["id"].as_str()?.parse::<u64>().ok()?;
|
||||
let text = option["text"].as_str()?.to_owned();
|
||||
let vote_count = option["vote_count"].as_u64();
|
||||
|
||||
// Construct PollOption items
|
||||
Some(Self { id, text, vote_count })
|
||||
})
|
||||
.collect::<Vec<Self>>(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Post flags with nsfw and stickied
|
||||
pub struct Flags {
|
||||
pub nsfw: bool,
|
||||
|
@ -261,17 +204,10 @@ impl GalleryMedia {
|
|||
// For each image in gallery
|
||||
let media_id = item["media_id"].as_str().unwrap_or_default();
|
||||
let image = &metadata[media_id]["s"];
|
||||
let image_type = &metadata[media_id]["m"];
|
||||
|
||||
let url = if image_type == "image/gif" {
|
||||
image["gif"].as_str().unwrap_or_default()
|
||||
} else {
|
||||
image["u"].as_str().unwrap_or_default()
|
||||
};
|
||||
|
||||
// Construct gallery items
|
||||
Self {
|
||||
url: format_url(url),
|
||||
url: format_url(image["u"].as_str().unwrap_or_default()),
|
||||
width: image["x"].as_i64().unwrap_or_default(),
|
||||
height: image["y"].as_i64().unwrap_or_default(),
|
||||
caption: item["caption"].as_str().unwrap_or_default().to_string(),
|
||||
|
@ -290,7 +226,6 @@ pub struct Post {
|
|||
pub body: String,
|
||||
pub author: Author,
|
||||
pub permalink: String,
|
||||
pub poll: Option<Poll>,
|
||||
pub score: (String, String),
|
||||
pub upvote_ratio: i64,
|
||||
pub post_type: String,
|
||||
|
@ -397,10 +332,9 @@ impl Post {
|
|||
},
|
||||
flags: Flags {
|
||||
nsfw: data["over_18"].as_bool().unwrap_or_default(),
|
||||
stickied: data["stickied"].as_bool().unwrap_or_default() || data["pinned"].as_bool().unwrap_or_default(),
|
||||
stickied: data["stickied"].as_bool().unwrap_or_default(),
|
||||
},
|
||||
permalink: val(post, "permalink"),
|
||||
poll: Poll::parse(&data["poll_data"]),
|
||||
rel_time,
|
||||
created,
|
||||
num_duplicates: post["data"]["num_duplicates"].as_u64().unwrap_or(0),
|
||||
|
@ -436,8 +370,6 @@ pub struct Comment {
|
|||
pub awards: Awards,
|
||||
pub collapsed: bool,
|
||||
pub is_filtered: bool,
|
||||
pub more_count: i64,
|
||||
pub prefs: Preferences,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
|
@ -572,12 +504,10 @@ pub struct Preferences {
|
|||
pub hide_hls_notification: String,
|
||||
pub use_hls: String,
|
||||
pub autoplay_videos: String,
|
||||
pub disable_visit_reddit_confirmation: String,
|
||||
pub comment_sort: String,
|
||||
pub post_sort: String,
|
||||
pub subscriptions: Vec<String>,
|
||||
pub filters: Vec<String>,
|
||||
pub hide_awards: String,
|
||||
}
|
||||
|
||||
#[derive(RustEmbed)]
|
||||
|
@ -587,31 +517,29 @@ pub struct ThemeAssets;
|
|||
|
||||
impl Preferences {
|
||||
// Build preferences from cookies
|
||||
pub fn new(req: &Request<Body>) -> Self {
|
||||
pub fn new(req: Request<Body>) -> Self {
|
||||
// Read available theme names from embedded css files.
|
||||
// Always make the default "system" theme available.
|
||||
let mut themes = vec!["system".to_string()];
|
||||
for file in ThemeAssets::iter() {
|
||||
let chunks: Vec<&str> = file.as_ref().split(".css").collect();
|
||||
themes.push(chunks[0].to_owned())
|
||||
themes.push(chunks[0].to_owned());
|
||||
}
|
||||
Self {
|
||||
available_themes: themes,
|
||||
theme: setting(req, "theme"),
|
||||
front_page: setting(req, "front_page"),
|
||||
layout: setting(req, "layout"),
|
||||
wide: setting(req, "wide"),
|
||||
show_nsfw: setting(req, "show_nsfw"),
|
||||
blur_nsfw: setting(req, "blur_nsfw"),
|
||||
use_hls: setting(req, "use_hls"),
|
||||
hide_hls_notification: setting(req, "hide_hls_notification"),
|
||||
autoplay_videos: setting(req, "autoplay_videos"),
|
||||
disable_visit_reddit_confirmation: setting(req, "disable_visit_reddit_confirmation"),
|
||||
comment_sort: setting(req, "comment_sort"),
|
||||
post_sort: setting(req, "post_sort"),
|
||||
subscriptions: setting(req, "subscriptions").split('+').map(String::from).filter(|s| !s.is_empty()).collect(),
|
||||
filters: setting(req, "filters").split('+').map(String::from).filter(|s| !s.is_empty()).collect(),
|
||||
hide_awards: setting(req, "hide_awards"),
|
||||
theme: setting(&req, "theme"),
|
||||
front_page: setting(&req, "front_page"),
|
||||
layout: setting(&req, "layout"),
|
||||
wide: setting(&req, "wide"),
|
||||
show_nsfw: setting(&req, "show_nsfw"),
|
||||
blur_nsfw: setting(&req, "blur_nsfw"),
|
||||
use_hls: setting(&req, "use_hls"),
|
||||
hide_hls_notification: setting(&req, "hide_hls_notification"),
|
||||
autoplay_videos: setting(&req, "autoplay_videos"),
|
||||
comment_sort: setting(&req, "comment_sort"),
|
||||
post_sort: setting(&req, "post_sort"),
|
||||
subscriptions: setting(&req, "subscriptions").split('+').map(String::from).filter(|s| !s.is_empty()).collect(),
|
||||
filters: setting(&req, "filters").split('+').map(String::from).filter(|s| !s.is_empty()).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -659,12 +587,9 @@ pub async fn parse_post(post: &serde_json::Value) -> Post {
|
|||
|
||||
let permalink = val(post, "permalink");
|
||||
|
||||
let poll = Poll::parse(&post["data"]["poll_data"]);
|
||||
|
||||
let body = if val(post, "removed_by_category") == "moderator" {
|
||||
format!(
|
||||
"<div class=\"md\"><p>[removed] — <a href=\"https://{}{}\">view removed post</a></p></div>",
|
||||
get_setting("LIBREDDIT_PUSHSHIFT_FRONTEND").unwrap_or(String::from(crate::config::DEFAULT_PUSHSHIFT_FRONTEND)),
|
||||
"<div class=\"md\"><p>[removed] — <a href=\"https://www.unddit.com{}\">view removed post</a></p></div>",
|
||||
permalink
|
||||
)
|
||||
} else {
|
||||
|
@ -692,7 +617,6 @@ pub async fn parse_post(post: &serde_json::Value) -> Post {
|
|||
distinguished: val(post, "distinguished"),
|
||||
},
|
||||
permalink,
|
||||
poll,
|
||||
score: format_num(score),
|
||||
upvote_ratio: ratio as i64,
|
||||
post_type,
|
||||
|
@ -702,7 +626,7 @@ pub async fn parse_post(post: &serde_json::Value) -> Post {
|
|||
alt_url: String::new(),
|
||||
width: post["data"]["thumbnail_width"].as_i64().unwrap_or_default(),
|
||||
height: post["data"]["thumbnail_height"].as_i64().unwrap_or_default(),
|
||||
poster: String::new(),
|
||||
poster: "".to_string(),
|
||||
},
|
||||
flair: Flair {
|
||||
flair_parts: FlairPart::parse(
|
||||
|
@ -719,8 +643,8 @@ pub async fn parse_post(post: &serde_json::Value) -> Post {
|
|||
},
|
||||
},
|
||||
flags: Flags {
|
||||
nsfw: post["data"]["over_18"].as_bool().unwrap_or_default(),
|
||||
stickied: post["data"]["stickied"].as_bool().unwrap_or_default() || post["data"]["pinned"].as_bool().unwrap_or(false),
|
||||
nsfw: post["data"]["over_18"].as_bool().unwrap_or(false),
|
||||
stickied: post["data"]["stickied"].as_bool().unwrap_or(false),
|
||||
},
|
||||
domain: val(post, "domain"),
|
||||
rel_time,
|
||||
|
@ -757,7 +681,7 @@ pub fn setting(req: &Request<Body>, name: &str) -> String {
|
|||
.cookie(name)
|
||||
.unwrap_or_else(|| {
|
||||
// If there is no cookie for this setting, try receiving a default from the config
|
||||
if let Some(default) = crate::config::get_setting(&format!("LIBREDDIT_DEFAULT_{}", name.to_uppercase())) {
|
||||
if let Some(default) = crate::config::get_setting(&format!("FERRIT_DEFAULT_{}", name.to_uppercase())) {
|
||||
Cookie::new(name, default)
|
||||
} else {
|
||||
Cookie::named(name)
|
||||
|
@ -780,21 +704,6 @@ pub async fn catch_random(sub: &str, additional: &str) -> Result<Response<Body>,
|
|||
}
|
||||
}
|
||||
|
||||
static REGEX_URL_WWW: Lazy<Regex> = Lazy::new(|| Regex::new(r"https://www\.reddit\.com/(.*)").unwrap());
|
||||
static REGEX_URL_OLD: Lazy<Regex> = Lazy::new(|| Regex::new(r"https://old\.reddit\.com/(.*)").unwrap());
|
||||
static REGEX_URL_NP: Lazy<Regex> = Lazy::new(|| Regex::new(r"https://np\.reddit\.com/(.*)").unwrap());
|
||||
static REGEX_URL_PLAIN: Lazy<Regex> = Lazy::new(|| Regex::new(r"https://reddit\.com/(.*)").unwrap());
|
||||
static REGEX_URL_VIDEOS: Lazy<Regex> = Lazy::new(|| Regex::new(r"https://v\.redd\.it/(.*)/DASH_([0-9]{2,4}(\.mp4|$|\?source=fallback))").unwrap());
|
||||
static REGEX_URL_VIDEOS_HLS: Lazy<Regex> = Lazy::new(|| Regex::new(r"https://v\.redd\.it/(.+)/(HLSPlaylist\.m3u8.*)$").unwrap());
|
||||
static REGEX_URL_IMAGES: Lazy<Regex> = Lazy::new(|| Regex::new(r"https://i\.redd\.it/(.*)").unwrap());
|
||||
static REGEX_URL_THUMBS_A: Lazy<Regex> = Lazy::new(|| Regex::new(r"https://a\.thumbs\.redditmedia\.com/(.*)").unwrap());
|
||||
static REGEX_URL_THUMBS_B: Lazy<Regex> = Lazy::new(|| Regex::new(r"https://b\.thumbs\.redditmedia\.com/(.*)").unwrap());
|
||||
static REGEX_URL_EMOJI: Lazy<Regex> = Lazy::new(|| Regex::new(r"https://emoji\.redditmedia\.com/(.*)/(.*)").unwrap());
|
||||
static REGEX_URL_PREVIEW: Lazy<Regex> = Lazy::new(|| Regex::new(r"https://preview\.redd\.it/(.*)").unwrap());
|
||||
static REGEX_URL_EXTERNAL_PREVIEW: Lazy<Regex> = Lazy::new(|| Regex::new(r"https://external\-preview\.redd\.it/(.*)").unwrap());
|
||||
static REGEX_URL_STYLES: Lazy<Regex> = Lazy::new(|| Regex::new(r"https://styles\.redditmedia\.com/(.*)").unwrap());
|
||||
static REGEX_URL_STATIC_MEDIA: Lazy<Regex> = Lazy::new(|| Regex::new(r"https://www\.redditstatic\.com/(.*)").unwrap());
|
||||
|
||||
// Direct urls to proxy if proxy is enabled
|
||||
pub fn format_url(url: &str) -> String {
|
||||
if url.is_empty() || url == "self" || url == "default" || url == "nsfw" || url == "spoiler" {
|
||||
|
@ -803,11 +712,13 @@ pub fn format_url(url: &str) -> String {
|
|||
Url::parse(url).map_or(url.to_string(), |parsed| {
|
||||
let domain = parsed.domain().unwrap_or_default();
|
||||
|
||||
let capture = |regex: &Regex, format: &str, segments: i16| {
|
||||
regex.captures(url).map_or(String::new(), |caps| match segments {
|
||||
1 => [format, &caps[1]].join(""),
|
||||
2 => [format, &caps[1], "/", &caps[2]].join(""),
|
||||
_ => String::new(),
|
||||
let capture = |regex: &str, format: &str, segments: i16| {
|
||||
Regex::new(regex).map_or(String::new(), |re| {
|
||||
re.captures(url).map_or(String::new(), |caps| match segments {
|
||||
1 => [format, &caps[1]].join(""),
|
||||
2 => [format, &caps[1], "/", &caps[2]].join(""),
|
||||
_ => String::new(),
|
||||
})
|
||||
})
|
||||
};
|
||||
|
||||
|
@ -833,46 +744,44 @@ pub fn format_url(url: &str) -> String {
|
|||
}
|
||||
|
||||
match domain {
|
||||
"www.reddit.com" => capture(®EX_URL_WWW, "/", 1),
|
||||
"old.reddit.com" => capture(®EX_URL_OLD, "/", 1),
|
||||
"np.reddit.com" => capture(®EX_URL_NP, "/", 1),
|
||||
"reddit.com" => capture(®EX_URL_PLAIN, "/", 1),
|
||||
"v.redd.it" => chain!(capture(®EX_URL_VIDEOS, "/vid/", 2), capture(®EX_URL_VIDEOS_HLS, "/hls/", 2)),
|
||||
"i.redd.it" => capture(®EX_URL_IMAGES, "/img/", 1),
|
||||
"a.thumbs.redditmedia.com" => capture(®EX_URL_THUMBS_A, "/thumb/a/", 1),
|
||||
"b.thumbs.redditmedia.com" => capture(®EX_URL_THUMBS_B, "/thumb/b/", 1),
|
||||
"emoji.redditmedia.com" => capture(®EX_URL_EMOJI, "/emoji/", 2),
|
||||
"preview.redd.it" => capture(®EX_URL_PREVIEW, "/preview/pre/", 1),
|
||||
"external-preview.redd.it" => capture(®EX_URL_EXTERNAL_PREVIEW, "/preview/external-pre/", 1),
|
||||
"styles.redditmedia.com" => capture(®EX_URL_STYLES, "/style/", 1),
|
||||
"www.redditstatic.com" => capture(®EX_URL_STATIC_MEDIA, "/static/", 1),
|
||||
"www.reddit.com" => capture(r"https://www\.reddit\.com/(.*)", "/", 1),
|
||||
"old.reddit.com" => capture(r"https://old\.reddit\.com/(.*)", "/", 1),
|
||||
"np.reddit.com" => capture(r"https://np\.reddit\.com/(.*)", "/", 1),
|
||||
"reddit.com" => capture(r"https://reddit\.com/(.*)", "/", 1),
|
||||
"v.redd.it" => chain!(
|
||||
capture(r"https://v\.redd\.it/(.*)/DASH_([0-9]{2,4}(\.mp4|$|\?source=fallback))", "/vid/", 2),
|
||||
capture(r"https://v\.redd\.it/(.+)/(HLSPlaylist\.m3u8.*)$", "/hls/", 2)
|
||||
),
|
||||
"i.redd.it" => capture(r"https://i\.redd\.it/(.*)", "/img/", 1),
|
||||
"a.thumbs.redditmedia.com" => capture(r"https://a\.thumbs\.redditmedia\.com/(.*)", "/thumb/a/", 1),
|
||||
"b.thumbs.redditmedia.com" => capture(r"https://b\.thumbs\.redditmedia\.com/(.*)", "/thumb/b/", 1),
|
||||
"emoji.redditmedia.com" => capture(r"https://emoji\.redditmedia\.com/(.*)/(.*)", "/emoji/", 2),
|
||||
"preview.redd.it" => capture(r"https://preview\.redd\.it/(.*)", "/preview/pre/", 1),
|
||||
"external-preview.redd.it" => capture(r"https://external\-preview\.redd\.it/(.*)", "/preview/external-pre/", 1),
|
||||
"styles.redditmedia.com" => capture(r"https://styles\.redditmedia\.com/(.*)", "/style/", 1),
|
||||
"www.redditstatic.com" => capture(r"https://www\.redditstatic\.com/(.*)", "/static/", 1),
|
||||
_ => url.to_string(),
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
static REDDIT_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r#"href="(https|http|)://(www\.|old\.|np\.|amp\.|)(reddit\.com|redd\.it)/"#).unwrap());
|
||||
static REDDIT_PREVIEW_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"https://external-preview\.redd\.it(.*)[^?]").unwrap());
|
||||
|
||||
// Rewrite Reddit links to Libreddit in body of text
|
||||
// Rewrite Reddit links to Ferrit in body of text
|
||||
pub fn rewrite_urls(input_text: &str) -> String {
|
||||
let text1 =
|
||||
// Rewrite Reddit links to Libreddit
|
||||
REDDIT_REGEX.replace_all(input_text, r#"href="/"#)
|
||||
.to_string()
|
||||
// Remove (html-encoded) "\" from URLs.
|
||||
.replace("%5C", "")
|
||||
.replace('\\', "");
|
||||
let text1 = Regex::new(r#"href="(https|http|)://(www\.|old\.|np\.|amp\.|)(reddit\.com|redd\.it)/"#)
|
||||
.map_or(String::new(), |re| re.replace_all(input_text, r#"href="/"#).to_string())
|
||||
// Remove (html-encoded) "\" from URLs.
|
||||
.replace("%5C", "")
|
||||
.replace('\\', "");
|
||||
|
||||
// Rewrite external media previews to Libreddit
|
||||
if REDDIT_PREVIEW_REGEX.is_match(&text1) {
|
||||
REDDIT_PREVIEW_REGEX
|
||||
.replace_all(&text1, format_url(REDDIT_PREVIEW_REGEX.find(&text1).map(|x| x.as_str()).unwrap_or_default()))
|
||||
.to_string()
|
||||
} else {
|
||||
text1
|
||||
}
|
||||
// Rewrite external media previews to Ferrit
|
||||
Regex::new(r"https://external-preview\.redd\.it(.*)[^?]").map_or(String::new(), |re| {
|
||||
if re.is_match(&text1) {
|
||||
re.replace_all(&text1, format_url(re.find(&text1).map(|x| x.as_str()).unwrap_or_default())).to_string()
|
||||
} else {
|
||||
text1
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Format vote count to a string that will be displayed.
|
||||
|
@ -893,31 +802,20 @@ pub fn format_num(num: i64) -> (String, String) {
|
|||
// Parse a relative and absolute time from a UNIX timestamp
|
||||
pub fn time(created: f64) -> (String, String) {
|
||||
let time = OffsetDateTime::from_unix_timestamp(created.round() as i64).unwrap_or(OffsetDateTime::UNIX_EPOCH);
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let min = time.min(now);
|
||||
let max = time.max(now);
|
||||
let time_delta = max - min;
|
||||
let time_delta = OffsetDateTime::now_utc() - time;
|
||||
|
||||
// If the time difference is more than a month, show full date
|
||||
let mut rel_time = if time_delta > Duration::days(30) {
|
||||
let rel_time = if time_delta > Duration::days(30) {
|
||||
time.format(format_description!("[month repr:short] [day] '[year repr:last_two]")).unwrap_or_default()
|
||||
// Otherwise, show relative date/time
|
||||
} else if time_delta.whole_days() > 0 {
|
||||
format!("{}d", time_delta.whole_days())
|
||||
format!("{}d ago", time_delta.whole_days())
|
||||
} else if time_delta.whole_hours() > 0 {
|
||||
format!("{}h", time_delta.whole_hours())
|
||||
format!("{}h ago", time_delta.whole_hours())
|
||||
} else {
|
||||
format!("{}m", time_delta.whole_minutes())
|
||||
format!("{}m ago", time_delta.whole_minutes())
|
||||
};
|
||||
|
||||
if time_delta <= Duration::days(30) {
|
||||
if now < time {
|
||||
rel_time += " left";
|
||||
} else {
|
||||
rel_time += " ago";
|
||||
}
|
||||
}
|
||||
|
||||
(
|
||||
rel_time,
|
||||
time
|
||||
|
@ -959,7 +857,7 @@ pub async fn error(req: Request<Body>, msg: impl ToString) -> Result<Response<Bo
|
|||
let url = req.uri().to_string();
|
||||
let body = ErrorTemplate {
|
||||
msg: msg.to_string(),
|
||||
prefs: Preferences::new(&req),
|
||||
prefs: Preferences::new(req),
|
||||
url,
|
||||
}
|
||||
.render()
|
||||
|
@ -968,35 +866,17 @@ pub async fn error(req: Request<Body>, msg: impl ToString) -> Result<Response<Bo
|
|||
Ok(Response::builder().status(404).header("content-type", "text/html").body(body.into()).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Returns true if the config/env variable `LIBREDDIT_SFW_ONLY` carries the
|
||||
/// value `on`.
|
||||
///
|
||||
/// If this variable is set as such, the instance will operate in SFW-only
|
||||
/// mode; all NSFW content will be filtered. Attempts to access NSFW
|
||||
/// subreddits or posts or userpages for users Reddit has deemed NSFW will
|
||||
/// be denied.
|
||||
/// Retrieve the `FERRIT_SFW_ONLY` setting value from the config, based on
|
||||
/// environment variables and the config file.
|
||||
pub fn sfw_only() -> bool {
|
||||
match crate::config::get_setting("LIBREDDIT_SFW_ONLY") {
|
||||
Some(val) => val == "on",
|
||||
None => false,
|
||||
}
|
||||
crate::config::get_setting("FERRIT_SFW_ONLY").is_some()
|
||||
}
|
||||
|
||||
// Determines if a request shoud redirect to a nsfw landing gate.
|
||||
pub fn should_be_nsfw_gated(req: &Request<Body>, req_url: &str) -> bool {
|
||||
let sfw_instance = sfw_only();
|
||||
let gate_nsfw = (setting(req, "show_nsfw") != "on") || sfw_instance;
|
||||
|
||||
// Nsfw landing gate should not be bypassed on a sfw only instance,
|
||||
let bypass_gate = !sfw_instance && req_url.contains("&bypass_nsfw_landing");
|
||||
|
||||
gate_nsfw && !bypass_gate
|
||||
}
|
||||
|
||||
/// Renders the landing page for NSFW content when the user has not enabled
|
||||
/// Render the landing page for NSFW content when the user has not enabled
|
||||
/// "show NSFW posts" in settings.
|
||||
pub async fn nsfw_landing(req: Request<Body>, req_url: String) -> Result<Response<Body>, String> {
|
||||
pub async fn nsfw_landing(req: Request<Body>) -> Result<Response<Body>, String> {
|
||||
let res_type: ResourceType;
|
||||
let url = req.uri().to_string();
|
||||
|
||||
// Determine from the request URL if the resource is a subreddit, a user
|
||||
// page, or a post.
|
||||
|
@ -1014,8 +894,8 @@ pub async fn nsfw_landing(req: Request<Body>, req_url: String) -> Result<Respons
|
|||
let body = NSFWLandingTemplate {
|
||||
res,
|
||||
res_type,
|
||||
prefs: Preferences::new(&req),
|
||||
url: req_url,
|
||||
prefs: Preferences::new(req),
|
||||
url,
|
||||
}
|
||||
.render()
|
||||
.unwrap_or_default();
|
||||
|
@ -1025,7 +905,8 @@ pub async fn nsfw_landing(req: Request<Body>, req_url: String) -> Result<Respons
|
|||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{format_num, format_url, rewrite_urls};
|
||||
use super::format_num;
|
||||
use super::rewrite_urls;
|
||||
|
||||
#[test]
|
||||
fn format_num_works() {
|
||||
|
@ -1045,33 +926,4 @@ mod tests {
|
|||
r#"<a href="https://www.reddit.com/r/linux_gaming/comments/x/just_a_test/">https://www.reddit.com/r/linux_gaming/comments/x/just_a_test/</a>"#
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_format_url() {
|
||||
assert_eq!(format_url("https://a.thumbs.redditmedia.com/XYZ.jpg"), "/thumb/a/XYZ.jpg");
|
||||
assert_eq!(format_url("https://emoji.redditmedia.com/a/b"), "/emoji/a/b");
|
||||
|
||||
assert_eq!(
|
||||
format_url("https://external-preview.redd.it/foo.jpg?auto=webp&s=bar"),
|
||||
"/preview/external-pre/foo.jpg?auto=webp&s=bar"
|
||||
);
|
||||
|
||||
assert_eq!(format_url("https://i.redd.it/foobar.jpg"), "/img/foobar.jpg");
|
||||
assert_eq!(
|
||||
format_url("https://preview.redd.it/qwerty.jpg?auto=webp&s=asdf"),
|
||||
"/preview/pre/qwerty.jpg?auto=webp&s=asdf"
|
||||
);
|
||||
assert_eq!(format_url("https://v.redd.it/foo/DASH_360.mp4?source=fallback"), "/vid/foo/360.mp4");
|
||||
assert_eq!(
|
||||
format_url("https://v.redd.it/foo/HLSPlaylist.m3u8?a=bar&v=1&f=sd"),
|
||||
"/hls/foo/HLSPlaylist.m3u8?a=bar&v=1&f=sd"
|
||||
);
|
||||
assert_eq!(format_url("https://www.redditstatic.com/gold/awards/icon/icon.png"), "/static/gold/awards/icon/icon.png");
|
||||
|
||||
assert_eq!(format_url(""), "");
|
||||
assert_eq!(format_url("self"), "");
|
||||
assert_eq!(format_url("default"), "");
|
||||
assert_eq!(format_url("nsfw"), "");
|
||||
assert_eq!(format_url("spoiler"), "");
|
||||
}
|
||||
}
|
||||
|
|
Before Width: | Height: | Size: 8 KiB After Width: | Height: | Size: 5 KiB |
Before Width: | Height: | Size: 4.2 KiB After Width: | Height: | Size: 306 KiB |
Before Width: | Height: | Size: 969 B After Width: | Height: | Size: 1.1 KiB |
4
static/hls.min.js
vendored
BIN
static/logo.png
Before Width: | Height: | Size: 7.9 KiB After Width: | Height: | Size: 24 KiB |
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "Libreddit",
|
||||
"short_name": "Libreddit",
|
||||
"name": "Ferrit",
|
||||
"short_name": "Ferrit",
|
||||
"display": "standalone",
|
||||
"background_color": "#1f1f1f",
|
||||
"description": "An alternative private front-end to Reddit",
|
||||
|
@ -20,4 +20,4 @@
|
|||
"sizes": "32x32"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
342
static/style.css
|
@ -4,30 +4,6 @@
|
|||
:root {
|
||||
--nsfw: #ff5c5d;
|
||||
--admin: #ea0027;
|
||||
|
||||
/* Reddit redirect warning constants */
|
||||
--popup-red: #ea0027;
|
||||
--popup-black: #111;
|
||||
--popup-text: #fff;
|
||||
--popup-background-1: #0f0f0f;
|
||||
--popup-background-2: #220f0f;
|
||||
--popup-reddit-url: var(--popup-red);
|
||||
|
||||
--popup-background: repeating-linear-gradient(
|
||||
-45deg,
|
||||
var(--popup-background-1),
|
||||
var(--popup-background-1) 50px,
|
||||
var(--popup-background-2) 50px,
|
||||
var(--popup-background-2) 100px
|
||||
);
|
||||
|
||||
--popup-toreddit-background: var(--popup-black);
|
||||
--popup-toreddit-text: var(--popup-red);
|
||||
--popup-goback-background: var(--popup-red);
|
||||
--popup-goback-text: #222;
|
||||
--popup-border: 1px solid var(--popup-red);
|
||||
|
||||
--footer-height: 30px;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
|
@ -50,10 +26,6 @@
|
|||
--highlighted: #333;
|
||||
--visited: #aaa;
|
||||
--shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
|
||||
--popup: #b80a27;
|
||||
|
||||
/* Hint color theme to browser for scrollbar */
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
/* Browser-defined light theme */
|
||||
|
@ -70,9 +42,6 @@
|
|||
--highlighted: white;
|
||||
--visited: #555;
|
||||
--shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
||||
|
||||
/* Hint color theme to browser for scrollbar */
|
||||
color-scheme: light;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -101,9 +70,6 @@ body {
|
|||
background: var(--background);
|
||||
font-size: 15px;
|
||||
padding-top: 60px;
|
||||
padding-bottom: var(--footer-height);
|
||||
min-height: calc(100vh - 60px);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
nav {
|
||||
|
@ -128,7 +94,7 @@ nav {
|
|||
}
|
||||
|
||||
nav * { color: var(--text); }
|
||||
nav #reddit, #code > span { color: var(--accent); }
|
||||
nav #ferrit_logo_p2, #code > span { color: var(--accent); }
|
||||
nav #code > svg { stroke: var(--accent); }
|
||||
|
||||
nav #logo {
|
||||
|
@ -147,7 +113,13 @@ nav #links svg {
|
|||
display: none;
|
||||
}
|
||||
|
||||
nav #libreddit {
|
||||
nav #version {
|
||||
opacity: 50%;
|
||||
vertical-align: -2px;
|
||||
margin-right: 10px;
|
||||
}
|
||||
|
||||
nav #ferrit_logo {
|
||||
vertical-align: -2px;
|
||||
}
|
||||
|
||||
|
@ -156,109 +128,10 @@ nav #libreddit {
|
|||
margin-left: 10px;
|
||||
}
|
||||
|
||||
.popup {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
overflow: clip;
|
||||
opacity: 0;
|
||||
position: fixed;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
bottom: 0;
|
||||
right: 0;
|
||||
visibility: hidden;
|
||||
transition: all 0.1s ease-in-out;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
/* fallback for firefox esr */
|
||||
.popup {
|
||||
background-color: #000000fd;
|
||||
}
|
||||
|
||||
/* all other browsers */
|
||||
@supports ((-webkit-backdrop-filter: none) or (backdrop-filter: none)) {
|
||||
.popup {
|
||||
-webkit-backdrop-filter: blur(.25rem) brightness(15%);
|
||||
backdrop-filter: blur(.25rem) brightness(15%);
|
||||
}
|
||||
}
|
||||
|
||||
.popup-inner {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
text-align: center;
|
||||
max-width: 600px;
|
||||
max-height: 500px;
|
||||
width: fit-content;
|
||||
height: fit-content;
|
||||
padding: 1rem;
|
||||
background: var(--popup-background);
|
||||
border: var(--popup-border);
|
||||
border-radius: 5px;
|
||||
transition: all 0.1s ease-in-out;
|
||||
}
|
||||
|
||||
.popup-inner svg {
|
||||
display: unset !important;
|
||||
width: 35%;
|
||||
stroke: none;
|
||||
margin: 1rem;
|
||||
}
|
||||
|
||||
.popup-inner h1 {
|
||||
color: var(--popup-text);
|
||||
margin: 1.5rem 1.5rem 1rem;
|
||||
}
|
||||
|
||||
.popup-inner p {
|
||||
color: var(--popup-text);
|
||||
}
|
||||
|
||||
.popup-inner a {
|
||||
border-radius: 5px;
|
||||
padding: 2%;
|
||||
width: 80%;
|
||||
margin: 0.5rem;
|
||||
cursor: pointer;
|
||||
transition: all 0.1s ease-in-out;
|
||||
}
|
||||
|
||||
#goback {
|
||||
background: var(--popup-goback-background);
|
||||
color: var(--popup-goback-text);
|
||||
}
|
||||
|
||||
#goback:not(.selected):hover {
|
||||
#reddit_link {
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
#toreddit {
|
||||
background: var(--popup-toreddit-background);
|
||||
color: var(--popup-toreddit-text);
|
||||
border: 1px solid var(--popup-red);
|
||||
}
|
||||
|
||||
#toreddit:not(.selected):hover {
|
||||
background: var(--popup-toreddit-text);
|
||||
color: var(--popup-toreddit-background);
|
||||
}
|
||||
|
||||
.popup:target {
|
||||
visibility: visible;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
#reddit_url {
|
||||
width: 80%;
|
||||
color: var(--popup-reddit-url);
|
||||
font-weight: 600;
|
||||
line-break: anywhere;
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
#code {
|
||||
margin-left: 10px;
|
||||
}
|
||||
|
@ -269,7 +142,6 @@ main {
|
|||
max-width: 1000px;
|
||||
padding: 10px 20px;
|
||||
margin: 0 auto;
|
||||
padding-bottom: 4em;
|
||||
}
|
||||
|
||||
.wide main {
|
||||
|
@ -282,54 +154,25 @@ main {
|
|||
}
|
||||
|
||||
#column_one {
|
||||
width: 100%;
|
||||
max-width: 750px;
|
||||
border-radius: 5px;
|
||||
overflow: inherit;
|
||||
}
|
||||
|
||||
/* Body footer. */
|
||||
body > footer {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
background: var(--post);
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
}
|
||||
|
||||
.footer-button {
|
||||
align-items: center;
|
||||
border-radius: .25rem;
|
||||
box-sizing: border-box;
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
display: inline-flex;
|
||||
padding-left: 1em;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
/* / Body footer. */
|
||||
|
||||
/* Footer in content block. */
|
||||
main > * > footer {
|
||||
footer {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
main > * > footer > a {
|
||||
footer > a {
|
||||
margin-right: 5px;
|
||||
}
|
||||
|
||||
/* / Footer in content block. */
|
||||
|
||||
button {
|
||||
background: none;
|
||||
border: none;
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
hr {
|
||||
|
@ -380,17 +223,13 @@ aside {
|
|||
border-radius: 5px;
|
||||
overflow: hidden;
|
||||
}
|
||||
#subreddit, #sidebar { min-width: 350px; }
|
||||
|
||||
#user *, #subreddit * { text-align: center; }
|
||||
|
||||
#user, #sub_meta, #sidebar_contents { padding: 20px; }
|
||||
|
||||
#sidebar, #sidebar_contents { margin-top: 10px; }
|
||||
#sidebar_label, #subreddit_label {
|
||||
padding: 10px;
|
||||
text-align: left;
|
||||
}
|
||||
#sidebar_label { padding: 10px; }
|
||||
|
||||
#user_icon, #sub_icon {
|
||||
width: 100px;
|
||||
|
@ -402,6 +241,7 @@ aside {
|
|||
}
|
||||
|
||||
#user_title, #sub_title {
|
||||
margin: 0 20px;
|
||||
font-size: 20px;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
@ -545,7 +385,6 @@ select, #search, #sort_options, #listing_options, #inside, #searchbox > *, #sort
|
|||
select {
|
||||
background: var(--outside);
|
||||
transition: 0.2s background;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
select, #search {
|
||||
|
@ -558,10 +397,6 @@ select, #search {
|
|||
border-radius: 5px 0px 0px 5px;
|
||||
}
|
||||
|
||||
.commentQuery {
|
||||
background: var(--post);
|
||||
}
|
||||
|
||||
#searchbox {
|
||||
grid-area: searchbox;
|
||||
display: flex;
|
||||
|
@ -639,31 +474,22 @@ button.submit:hover > svg { stroke: var(--accent); }
|
|||
background: transparent;
|
||||
}
|
||||
|
||||
#commentQueryForms {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
#allCommentsLink {
|
||||
color: var(--green);
|
||||
}
|
||||
|
||||
#sort, #search_sort {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
#sort_options, #listing_options, main > * > footer > a {
|
||||
#sort_options, #listing_options, footer > a {
|
||||
border-radius: 5px;
|
||||
align-items: center;
|
||||
box-shadow: var(--shadow);
|
||||
background: var(--outside);
|
||||
display: flex;
|
||||
overflow-y: hidden;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
#sort_options > a, #listing_options > a, main > * > footer > a {
|
||||
#sort_options > a, #listing_options > a, footer > a {
|
||||
color: var(--text);
|
||||
padding: 10px 20px;
|
||||
text-align: center;
|
||||
|
@ -771,7 +597,6 @@ a.search_subreddit:hover {
|
|||
"post_score post_title post_thumbnail" 1fr
|
||||
"post_score post_media post_thumbnail" auto
|
||||
"post_score post_body post_thumbnail" auto
|
||||
"post_score post_poll post_thumbnail" auto
|
||||
"post_score post_notification post_thumbnail" auto
|
||||
"post_score post_footer post_thumbnail" auto
|
||||
/ minmax(40px, auto) minmax(0, 1fr) fit-content(min(20%, 152px));
|
||||
|
@ -972,44 +797,6 @@ a.search_subreddit:hover {
|
|||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.post_poll {
|
||||
grid-area: post_poll;
|
||||
padding: 5px 15px 5px 12px;
|
||||
}
|
||||
|
||||
.poll_option {
|
||||
position: relative;
|
||||
margin-right: 15px;
|
||||
margin-top: 14px;
|
||||
z-index: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.poll_chart {
|
||||
padding: 14px 0;
|
||||
background-color: var(--accent);
|
||||
opacity: 0.2;
|
||||
border-radius: 5px;
|
||||
z-index: -1;
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
.poll_option span {
|
||||
margin-left: 8px;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.poll_option span:nth-of-type(1) {
|
||||
min-width: 10%;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.most_voted {
|
||||
opacity: 0.45;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* Used only for text post preview */
|
||||
.post_preview {
|
||||
-webkit-mask-image: linear-gradient(180deg,#000 60%,transparent);;
|
||||
|
@ -1032,17 +819,6 @@ a.search_subreddit:hover {
|
|||
font-weight: bold;
|
||||
}
|
||||
|
||||
#comment_count {
|
||||
font-weight: 500;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
#comment_count > #sorted_by {
|
||||
font-weight: normal;
|
||||
opacity: 0.7;
|
||||
margin-right: 7px;
|
||||
}
|
||||
|
||||
#post_links {
|
||||
display: flex;
|
||||
list-style: none;
|
||||
|
@ -1060,7 +836,7 @@ a.search_subreddit:hover {
|
|||
|
||||
@media screen and (min-width: 480px) {
|
||||
#post_links > li.mobile_item {
|
||||
display: none;
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1337,16 +1113,22 @@ summary.comment_data {
|
|||
}
|
||||
|
||||
.prefs {
|
||||
padding: 10px 20px 20px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
padding: 20px;
|
||||
background: var(--post);
|
||||
border-radius: 5px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.prefs fieldset {
|
||||
border: 0;
|
||||
padding: 10px 0;
|
||||
margin: 0 0 5px;
|
||||
.prefs > div {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
height: 35px;
|
||||
align-items: center;
|
||||
margin-top: 7px;
|
||||
}
|
||||
|
||||
.prefs legend {
|
||||
|
@ -1354,25 +1136,11 @@ summary.comment_data {
|
|||
border-bottom: 1px solid var(--highlighted);
|
||||
font-size: 18px;
|
||||
padding-bottom: 10px;
|
||||
margin-bottom: 7px;
|
||||
width: 100%;
|
||||
float: left; /* places the legend inside the (invisible) border, instead of vertically centered on top border*/
|
||||
}
|
||||
|
||||
.prefs-group {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
height: 35px;
|
||||
align-items: center;
|
||||
margin-top: 7px;
|
||||
}
|
||||
|
||||
.prefs-group > *:not(:last-child) {
|
||||
margin-right: 1ch;
|
||||
}
|
||||
|
||||
.prefs-group > *:last-child {
|
||||
margin-left: auto;
|
||||
.prefs legend:not(:first-child) {
|
||||
padding-top: 10px;
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
.prefs select {
|
||||
|
@ -1390,8 +1158,7 @@ aside.prefs {
|
|||
background: var(--highlighted);
|
||||
padding: 10px 15px;
|
||||
border-radius: 5px;
|
||||
margin-top: 5px;
|
||||
width: 100%
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
input[type="submit"] {
|
||||
|
@ -1421,10 +1188,6 @@ input[type="submit"] {
|
|||
width: 250px;
|
||||
background: var(--highlighted) !important;
|
||||
}
|
||||
/* Info page */
|
||||
.unset {
|
||||
color: lightslategrey;
|
||||
}
|
||||
|
||||
/* Markdown */
|
||||
|
||||
|
@ -1454,21 +1217,16 @@ input[type="submit"] {
|
|||
color: var(--accent);
|
||||
}
|
||||
|
||||
.md .md-spoiler-text, .md-spoiler-text a {
|
||||
.md .md-spoiler-text {
|
||||
background: var(--highlighted);
|
||||
color: transparent;
|
||||
}
|
||||
|
||||
.md-spoiler-text:hover {
|
||||
.md .md-spoiler-text:hover {
|
||||
background: var(--foreground);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.md-spoiler-text:hover a {
|
||||
background: var(--foreground);
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.md li { margin: 10px 0; }
|
||||
.toc_child { list-style: none; }
|
||||
|
||||
|
@ -1536,7 +1294,7 @@ td, th {
|
|||
|
||||
.listing_warn a {
|
||||
color: var(--accent);
|
||||
}
|
||||
};
|
||||
|
||||
/* NSFW Landing Page */
|
||||
|
||||
|
@ -1566,10 +1324,7 @@ td, th {
|
|||
/* Mobile */
|
||||
|
||||
@media screen and (max-width: 800px) {
|
||||
body {
|
||||
padding-top: 120px;
|
||||
padding-bottom: var(--footer-height);
|
||||
}
|
||||
body { padding-top: 120px }
|
||||
|
||||
main {
|
||||
flex-direction: column-reverse;
|
||||
|
@ -1608,21 +1363,17 @@ td, th {
|
|||
#user, #sidebar { margin: 20px 0; }
|
||||
#logo, #links { margin-bottom: 5px; }
|
||||
#searchbox { width: calc(100vw - 35px); }
|
||||
|
||||
}
|
||||
|
||||
@media screen and (max-width: 480px) {
|
||||
body {
|
||||
padding-top: 100px;
|
||||
padding-bottom: var(--footer-height);
|
||||
}
|
||||
body { padding-top: 100px; }
|
||||
#version { display: none; }
|
||||
|
||||
.post {
|
||||
grid-template: "post_header post_header post_thumbnail" auto
|
||||
"post_title post_title post_thumbnail" 1fr
|
||||
"post_media post_media post_thumbnail" auto
|
||||
"post_body post_body post_thumbnail" auto
|
||||
"post_poll post_poll post_thumbnail" auto
|
||||
"post_notification post_notification post_thumbnail" auto
|
||||
"post_score post_footer post_thumbnail" auto
|
||||
/ auto 1fr fit-content(min(20%, 152px));
|
||||
|
@ -1632,10 +1383,6 @@ td, th {
|
|||
margin: 5px 0px 20px 15px;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.post_poll {
|
||||
padding: 5px 15px 10px 12px;
|
||||
}
|
||||
|
||||
.compact .post_score { padding: 0; }
|
||||
|
||||
|
@ -1679,17 +1426,4 @@ td, th {
|
|||
#post_links > li.desktop_item { display: none }
|
||||
#post_links > li.mobile_item { display: auto }
|
||||
.post_footer > p > span#upvoted { display: none }
|
||||
|
||||
.popup {
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.popup-inner {
|
||||
max-width: 80%;
|
||||
}
|
||||
|
||||
#commentQueryForms {
|
||||
display: initial;
|
||||
justify-content: initial;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,13 +0,0 @@
|
|||
/* Gruvbox-Dark theme setting */
|
||||
.gruvboxdark {
|
||||
--accent: #8ec07c;
|
||||
--green: #b8bb26;
|
||||
--text: #ebdbb2;
|
||||
--foreground: #3c3836;
|
||||
--background: #282828;
|
||||
--outside: #3c3836;
|
||||
--post: #3c3836;
|
||||
--panel-border: 1px solid #504945;
|
||||
--highlighted: #282828;
|
||||
--shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
|
||||
}
|
|
@ -1,18 +0,0 @@
|
|||
/* Gruvbox-Light theme setting */
|
||||
.gruvboxlight {
|
||||
--accent: #427b58;
|
||||
--green: #79740e;
|
||||
--text: #3c3836;
|
||||
--foreground: #ebdbb2;
|
||||
--background: #fbf1c7;
|
||||
--outside: #ebdbb2;
|
||||
--post: #ebdbb2;
|
||||
--panel-border: 1px solid #d5c4a1;
|
||||
--highlighted: #fbf1c7;
|
||||
--shadow: 0 1px 3px rgba(0, 0, 0, 0.25);
|
||||
}
|
||||
|
||||
html:has(> .gruvboxlight) {
|
||||
/* Hint color theme to browser for scrollbar */
|
||||
color-scheme: light;
|
||||
}
|
|
@ -11,9 +11,4 @@
|
|||
--highlighted: white;
|
||||
--visited: #555;
|
||||
--shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
html:has(> .light) {
|
||||
/* Hint color theme to browser for scrollbar */
|
||||
color-scheme: light;
|
||||
}
|
|
@ -1,17 +1,15 @@
|
|||
{% import "utils.html" as utils %}
|
||||
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
{% block head %}
|
||||
<title>{% block title %}Libreddit{% endblock %}</title>
|
||||
<title>{% block title %}Ferrit{% endblock %}</title>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
|
||||
<meta name="description" content="View on Libreddit, an alternative private front-end to Reddit.">
|
||||
<meta name="description" content="View on Ferrit, an alternative private front-end to Reddit.">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<!-- General PWA -->
|
||||
<meta name="theme-color" content="#1F1F1F">
|
||||
<!-- iOS Application -->
|
||||
<meta name="apple-mobile-web-app-title" content="Libreddit">
|
||||
<meta name="apple-mobile-web-app-title" content="Ferrit">
|
||||
<meta name="apple-mobile-web-app-capable" content="yes">
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="default">
|
||||
<!-- Android -->
|
||||
|
@ -21,7 +19,7 @@
|
|||
<!-- PWA Manifest -->
|
||||
<link rel="manifest" type="application/json" href="/manifest.json">
|
||||
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
|
||||
<link rel="stylesheet" type="text/css" href="/style.css?v={{ env!("CARGO_PKG_VERSION") }}">
|
||||
<link rel="stylesheet" type="text/css" href="/style.css">
|
||||
{% endblock %}
|
||||
</head>
|
||||
<body class="
|
||||
|
@ -31,21 +29,22 @@
|
|||
<!-- NAVIGATION BAR -->
|
||||
<nav>
|
||||
<div id="logo">
|
||||
<a id="libreddit" href="/"><span id="lib">lib</span><span id="reddit">reddit.</span></a>
|
||||
<a id="ferrit_logo" href="/"><span id="ferrit_logo_p1">ferr</span><span id="ferrit_logo_p2">it.</span></a>
|
||||
<span id="version">v{{ env!("CARGO_PKG_VERSION") }}{% if crate::utils::sfw_only() %} <span title="This instance is SFW-only.">💼</span>{% endif %}</span>
|
||||
{% block subscriptions %}{% endblock %}
|
||||
</div>
|
||||
{% block search %}{% endblock %}
|
||||
<div id="links">
|
||||
<a id="reddit_link" {% if prefs.disable_visit_reddit_confirmation != "on" %}href="#popup"{% else %}href="https://www.reddit.com{{ url }}" rel="nofollow"{% endif %}>
|
||||
<a id="reddit_link" href="https://www.reddit.com{{ url }}" rel="nofollow">
|
||||
<span>reddit</span>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M22 2L12 22"/>
|
||||
<path d="M2 6.70587C3.33333 8.07884 3.33333 11.5971 3.33333 11.5971M3.33333 19.647V11.5971M3.33333 11.5971C3.33333 11.5971 5.125 7.47817 8 7.47817C10.875 7.47817 12 8.85114 12 8.85114"/>
|
||||
<title>reddit</title>
|
||||
<g transform="matrix(0.1219078,0,0,0.1219078,-2.7657832,-0.46047565)" style="fill:currentColor;fill-opacity:1;stroke:none;stroke-width:2">
|
||||
<path d="m 97.96875,84.774794 q -10.5,-1.78125 -19.875,-1.78125 -15.09375,0 -24.375,11.34375 -9.28125,11.343746 -9.28125,28.874996 v 47.625 h -16.875 v -65.71875 q 0,-7.124996 -1.3125,-16.781246 -1.21875,-9.65625 -3.5625,-18.9375 h 16.03125 q 3.75,12.9375 4.5,23.4375 h 0.46875 q 4.6875,-10.5 9.1875,-15.375 4.5,-4.96875 10.6875,-7.40625 6.1875,-2.53125 15.09375,-2.53125 9.75,0 19.3125,1.59375 z" />
|
||||
<path d="M 125.90625,172.71229 202.875,31.712294 h 16.6875 L 142.96875,172.71229 Z" />
|
||||
</g>
|
||||
</svg>
|
||||
</a>
|
||||
{% if prefs.disable_visit_reddit_confirmation != "on" %}
|
||||
{% call utils::visit_reddit_confirmation(url) %}
|
||||
{% endif %}
|
||||
<a id="settings_link" href="/settings">
|
||||
<span>settings</span>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
|
@ -53,6 +52,13 @@
|
|||
<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>
|
||||
</svg>
|
||||
</a>
|
||||
<a id="code" href="https://github.com/ferritreader/ferrit">
|
||||
<span>code</span>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<title>code</title>
|
||||
<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>
|
||||
</svg>
|
||||
</a>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
|
@ -63,18 +69,5 @@
|
|||
{% endblock %}
|
||||
</main>
|
||||
{% endblock %}
|
||||
|
||||
<!-- FOOTER -->
|
||||
{% block footer %}
|
||||
<footer>
|
||||
<p id="version">v{{ env!("CARGO_PKG_VERSION") }}</p>
|
||||
<div class="footer-button">
|
||||
<a href="/info" title="View instance information">ⓘ View instance info</a>
|
||||
</div>
|
||||
<div class="footer-button">
|
||||
<a href="https://github.com/libreddit/libreddit" title="View code on GitHub"><> Code</a>
|
||||
</div>
|
||||
</footer>
|
||||
{% endblock %}
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
{% import "utils.html" as utils %}
|
||||
|
||||
{% if kind == "more" && parent_kind == "t1" %}
|
||||
<a class="deeper_replies" href="{{ post_link }}{{ parent_id }}">→ More replies ({{ more_count }})</a>
|
||||
<a class="deeper_replies" href="{{ post_link }}{{ parent_id }}">→ More replies</a>
|
||||
{% else if kind == "t1" %}
|
||||
<div id="{{ id }}" class="comment">
|
||||
<div class="comment_left">
|
||||
|
@ -20,7 +20,7 @@
|
|||
{% endif %}
|
||||
<a href="{{ post_link }}{{ id }}/?context=3" class="created" title="{{ created }}">{{ rel_time }}</a>
|
||||
{% if edited.0 != "".to_string() %}<span class="edited" title="{{ edited.1 }}">edited {{ edited.0 }}</span>{% endif %}
|
||||
{% if !awards.is_empty() && prefs.hide_awards != "on" %}
|
||||
{% if !awards.is_empty() %}
|
||||
<span class="dot">•</span>
|
||||
{% for award in awards.clone() %}
|
||||
<span class="award" title="{{ award.name }}">
|
||||
|
@ -35,7 +35,7 @@
|
|||
<div class="comment_body {% if highlighted %}highlighted{% endif %}">{{ body|safe }}</div>
|
||||
{% endif %}
|
||||
<blockquote class="replies">{% for c in replies -%}{{ c.render().unwrap()|safe }}{%- endfor %}
|
||||
</bockquote>
|
||||
</blockquote>
|
||||
</details>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
|
|
@ -65,7 +65,7 @@
|
|||
<a class="post_author {{ post.author.distinguished }}" href="/u/{{ post.author.name }}">u/{{ post.author.name }}</a>
|
||||
<span class="dot">•</span>
|
||||
<span class="created" title="{{ post.created }}">{{ post.rel_time }}</span>
|
||||
{% if !post.awards.is_empty() && prefs.hide_awards != "on" %}
|
||||
{% if !post.awards.is_empty() %}
|
||||
{% for award in post.awards.clone() %}
|
||||
<span class="award" title="{{ award.name }}">
|
||||
<img alt="{{ award.name }}" src="{{ award.icon_url }}" width="16" height="16"/>
|
||||
|
@ -104,4 +104,4 @@
|
|||
</footer>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% endblock %}
|
|
@ -1,10 +0,0 @@
|
|||
{% extends "base.html" %}
|
||||
{% block title %}{{ title }}{% endblock %}
|
||||
{% block sortstyle %}{% endblock %}
|
||||
{% block content %}
|
||||
<div id="message">
|
||||
<h1>{{ title }}</h1>
|
||||
<br>
|
||||
{{ body|safe }}
|
||||
</div>
|
||||
{% endblock %}
|
|
@ -3,28 +3,18 @@
|
|||
{% block sortstyle %}{% endblock %}
|
||||
{% block content %}
|
||||
<div id="nsfw_landing">
|
||||
<h1>
|
||||
😱
|
||||
{% if res_type == crate::utils::ResourceType::Subreddit %}
|
||||
r/{{ res }} is a NSFW community!
|
||||
{% else if res_type == crate::utils::ResourceType::User %}
|
||||
u/{{ res }}'s content is NSFW!
|
||||
{% else if res_type == crate::utils::ResourceType::Post %}
|
||||
This post is NSFW!
|
||||
{% endif %}
|
||||
</h1>
|
||||
{% if res_type == crate::utils::ResourceType::Subreddit %}
|
||||
<h1>😱 r/{{ res }} is a NSFW community!</h1>
|
||||
{% else if res_type == crate::utils::ResourceType::User %}
|
||||
<h1>😱 u/{{ res }}'s content is NSFW!</h1>
|
||||
{% else if res_type == crate::utils::ResourceType::Post %}
|
||||
<h1>😱 This post is NSFW!</h1>
|
||||
{% endif %}
|
||||
<br />
|
||||
|
||||
<p>
|
||||
{% if crate::utils::sfw_only() %}
|
||||
This instance of Libreddit is SFW-only.</p>
|
||||
{% else %}
|
||||
Enable "Show NSFW posts" in <a href="/settings">settings</a> to view this {% if res_type == crate::utils::ResourceType::Subreddit %}subreddit{% else if res_type == crate::utils::ResourceType::User %}user's posts or comments{% else if res_type == crate::utils::ResourceType::Post %}post{% endif %}. <br>
|
||||
{% if res_type == crate::utils::ResourceType::Post %} You can also temporarily bypass this gate and view the post by clicking on this <a href="{{url}}&bypass_nsfw_landing">link</a>.{% endif %}
|
||||
{% endif %}
|
||||
</p>
|
||||
{% if crate::utils::sfw_only() %}
|
||||
<p>This instance of Ferrit is SFW-only.</p>
|
||||
{% else %}
|
||||
<p>Enable "Show NSFW posts" in <a href="/settings">settings</a> to view this {% if res_type == crate::utils::ResourceType::Subreddit %}subreddit{% else if res_type == crate::utils::ResourceType::User %}user's posts or comments{% else if res_type == crate::utils::ResourceType::Post %}post{% endif %}.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block footer %}
|
||||
{% endblock %}
|
||||
|
||||
|
|
|
@ -13,25 +13,16 @@
|
|||
<!-- Meta Tags -->
|
||||
<meta name="author" content="u/{{ post.author.name }}">
|
||||
<meta name="title" content="{{ post.title }} - r/{{ post.community }}">
|
||||
<meta property="og:title" content="{{ post.title }} - r/{{ post.community }}">
|
||||
<meta property="og:description" content="View on Libreddit, an alternative private front-end to Reddit.">
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:url" content="{{ post.permalink }}">
|
||||
<meta property="twitter:url" content="{{ post.permalink }}">
|
||||
<meta property="twitter:title" content="{{ post.title }} - r/{{ post.community }}">
|
||||
<meta property="twitter:description" content="View on Libreddit, an alternative private front-end to Reddit.">
|
||||
{% if post.post_type == "image" %}
|
||||
<meta property="og:type" content="image">
|
||||
<meta property="og:title" content="{{ post.title }} - r/{{ post.community }}">
|
||||
<meta property="og:description" content="View on Ferrit, an alternative private front-end to Reddit.">
|
||||
<meta property="og:image" content="{{ post.thumbnail.url }}">
|
||||
<meta property="twitter:card" content="summary_large_image">
|
||||
<meta property="twitter:url" content="{{ post.permalink }}">
|
||||
<meta property="twitter:title" content="{{ post.title }} - r/{{ post.community }}">
|
||||
<meta property="twitter:description" content="View on Ferrit, an alternative private front-end to Reddit.">
|
||||
<meta property="twitter:image" content="{{ post.thumbnail.url }}">
|
||||
{% else if post.post_type == "video" || post.post_type == "gif" %}
|
||||
<meta property="twitter:card" content="video">
|
||||
<meta property="og:type" content="video">
|
||||
<meta property="og:video" content="{{ post.media.url }}">
|
||||
<meta property="og:video:type" content="video/mp4">
|
||||
{% else %}
|
||||
<meta property="og:type" content="website">
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
|
||||
{% block subscriptions %}
|
||||
|
@ -43,32 +34,17 @@
|
|||
{% call utils::post(post) %}
|
||||
|
||||
<!-- SORT FORM -->
|
||||
<div id="commentQueryForms">
|
||||
<form id="sort">
|
||||
<p id="comment_count">{{post.comments.0}} {% if post.comments.0 == "1" %}comment{% else %}comments{% endif %} <span id="sorted_by">sorted by </span></p>
|
||||
<select name="sort" title="Sort comments by" id="commentSortSelect">
|
||||
<select name="sort" title="Sort comments by">
|
||||
{% call utils::options(sort, ["confidence", "top", "new", "controversial", "old"], "confidence") %}
|
||||
</select>
|
||||
<button id="sort_submit" class="submit">
|
||||
<svg width="15" viewBox="0 0 110 100" fill="none" stroke-width="10" stroke-linecap="round">
|
||||
<path d="M20 50 H100" />
|
||||
<path d="M75 15 L100 50 L75 85" />
|
||||
→
|
||||
</svg>
|
||||
</button>
|
||||
</form>
|
||||
<!-- SEARCH FORM -->
|
||||
<form id="sort">
|
||||
<input id="search" class="commentQuery" type="search" name="q" value="{{ comment_query }}" placeholder="Search comments">
|
||||
<input type="hidden" name="type" value="comment">
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{% if comment_query != "" %}
|
||||
Comments containing "{{ comment_query }}" | <a id="allCommentsLink" href="{{ url_without_query }}">All comments</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</select><button id="sort_submit" class="submit">
|
||||
<svg width="15" viewBox="0 0 110 100" fill="none" stroke-width="10" stroke-linecap="round">
|
||||
<path d="M20 50 H100" />
|
||||
<path d="M75 15 L100 50 L75 85" />
|
||||
→
|
||||
</svg>
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<!-- COMMENTS -->
|
||||
{% for c in comments -%}
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
{% extends "base.html" %}
|
||||
{% import "utils.html" as utils %}
|
||||
|
||||
{% block title %}Libreddit: search results - {{ params.q }}{% endblock %}
|
||||
{% block title %}Ferrit: search results - {{ params.q }}{% endblock %}
|
||||
|
||||
{% block subscriptions %}
|
||||
{% call utils::sub_list("") %}
|
||||
|
@ -10,7 +10,7 @@
|
|||
{% block content %}
|
||||
<div id="column_one">
|
||||
<form id="search_sort">
|
||||
<input id="search" type="text" name="q" placeholder="Search" value="{{ params.q|safe }}" title="Search libreddit">
|
||||
<input id="search" type="text" name="q" placeholder="Search" value="{{ params.q }}" title="Search Ferrit">
|
||||
{% if sub != "" %}
|
||||
<div id="inside">
|
||||
<input type="checkbox" name="restrict_sr" id="restrict_sr" {% if params.restrict_sr != "" %}checked{% endif %}>
|
||||
|
@ -29,7 +29,7 @@
|
|||
→
|
||||
</svg>
|
||||
</button>
|
||||
</form>
|
||||
</form>
|
||||
|
||||
{% if !is_filtered %}
|
||||
{% if subreddits.len() > 0 || params.typed == "sr_user" %}
|
||||
|
@ -61,10 +61,6 @@
|
|||
<span class="listing_warn">All posts are hidden because they are NSFW. Enable "Show NSFW posts" in settings to view.</span>
|
||||
{% endif %}
|
||||
|
||||
{% if no_posts %}
|
||||
<center>No posts were found.</center>
|
||||
{% endif %}
|
||||
|
||||
{% if all_posts_filtered %}
|
||||
<span class="listing_warn">(All content on this page has been filtered)</span>
|
||||
{% else if is_filtered %}
|
||||
|
@ -99,13 +95,13 @@
|
|||
{% if params.typed != "sr_user" %}
|
||||
<footer>
|
||||
{% if params.before != "" %}
|
||||
<a href="?q={{ params.q|safe }}&restrict_sr={{ params.restrict_sr }}
|
||||
<a href="?q={{ params.q }}&restrict_sr={{ params.restrict_sr }}
|
||||
&sort={{ params.sort }}&t={{ params.t }}
|
||||
&before={{ params.before }}" accesskey="P">PREV</a>
|
||||
{% endif %}
|
||||
|
||||
{% if params.after != "" %}
|
||||
<a href="?q={{ params.q|safe }}&restrict_sr={{ params.restrict_sr }}
|
||||
<a href="?q={{ params.q }}&restrict_sr={{ params.restrict_sr }}
|
||||
&sort={{ params.sort }}&t={{ params.t }}
|
||||
&after={{ params.after }}" accesskey="N">NEXT</a>
|
||||
{% endif %}
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
{% extends "base.html" %}
|
||||
{% import "utils.html" as utils %}
|
||||
|
||||
{% block title %}Libreddit Settings{% endblock %}
|
||||
{% block title %}Ferrit Settings{% endblock %}
|
||||
|
||||
{% block search %}
|
||||
{% call utils::search("".to_owned(), "", "") %}
|
||||
|
@ -11,91 +11,76 @@
|
|||
<div id="settings">
|
||||
<form action="/settings" method="POST">
|
||||
<div class="prefs">
|
||||
<fieldset>
|
||||
<legend>Appearance</legend>
|
||||
<div class="prefs-group">
|
||||
<label for="theme">Theme:</label>
|
||||
<select name="theme" id="theme">
|
||||
{% call utils::options(prefs.theme, prefs.available_themes, "system") %}
|
||||
</select>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>Interface</legend>
|
||||
<div class="prefs-group">
|
||||
<label for="front_page">Front page:</label>
|
||||
<select name="front_page" id="front_page">
|
||||
{% call utils::options(prefs.front_page, ["default", "popular", "all"], "default") %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="prefs-group">
|
||||
<label for="layout">Layout:</label>
|
||||
<select name="layout" id="layout">
|
||||
{% call utils::options(prefs.layout, ["card", "clean", "compact"], "card") %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="prefs-group">
|
||||
<label for="wide">Wide UI:</label>
|
||||
<input type="hidden" value="off" name="wide">
|
||||
<input type="checkbox" name="wide" id="wide" {% if prefs.wide == "on" %}checked{% endif %}>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>Content</legend>
|
||||
<div class="prefs-group">
|
||||
<label for="post_sort" title="Applies only to subreddit feeds">Default subreddit post sort:</label>
|
||||
<select name="post_sort">
|
||||
{% call utils::options(prefs.post_sort, ["hot", "new", "top", "rising", "controversial"], "hot") %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="prefs-group">
|
||||
<label for="comment_sort">Default comment sort:</label>
|
||||
<select name="comment_sort" id="comment_sort">
|
||||
{% call utils::options(prefs.comment_sort, ["confidence", "top", "new", "controversial", "old"], "confidence") %}
|
||||
</select>
|
||||
</div>
|
||||
{% if !crate::utils::sfw_only() %}
|
||||
<div class="prefs-group">
|
||||
<label for="show_nsfw">Show NSFW posts:</label>
|
||||
<input type="hidden" value="off" name="show_nsfw">
|
||||
<input type="checkbox" name="show_nsfw" id="show_nsfw" {% if prefs.show_nsfw == "on" %}checked{% endif %}>
|
||||
</div>
|
||||
<div class="prefs-group">
|
||||
<label for="blur_nsfw">Blur NSFW previews:</label>
|
||||
<input type="hidden" value="off" name="blur_nsfw">
|
||||
<input type="checkbox" name="blur_nsfw" id="blur_nsfw" {% if prefs.blur_nsfw == "on" %}checked{% endif %}>
|
||||
</div>
|
||||
{% endif %}
|
||||
<div class="prefs-group">
|
||||
<label for="autoplay_videos">Autoplay videos</label>
|
||||
<input type="hidden" value="off" name="autoplay_videos">
|
||||
<input type="checkbox" name="autoplay_videos" id="autoplay_videos" {% if prefs.autoplay_videos == "on" %}checked{% endif %}>
|
||||
</div>
|
||||
<div class="prefs-group">
|
||||
<label for="use_hls">Use HLS for videos</label>
|
||||
<legend>Appearance</legend>
|
||||
<div id="theme">
|
||||
<label for="theme">Theme:</label>
|
||||
<select name="theme">
|
||||
{% call utils::options(prefs.theme, prefs.available_themes, "system") %}
|
||||
</select>
|
||||
</div>
|
||||
<legend>Interface</legend>
|
||||
<div id="front_page">
|
||||
<label for="front_page">Front page:</label>
|
||||
<select name="front_page">
|
||||
{% call utils::options(prefs.front_page, ["default", "popular", "all"], "default") %}
|
||||
</select>
|
||||
</div>
|
||||
<div id="layout">
|
||||
<label for="layout">Layout:</label>
|
||||
<select name="layout">
|
||||
{% call utils::options(prefs.layout, ["card", "clean", "compact"], "card") %}
|
||||
</select>
|
||||
</div>
|
||||
<div id="wide">
|
||||
<label for="wide">Wide UI:</label>
|
||||
<input type="hidden" value="off" name="wide">
|
||||
<input type="checkbox" name="wide" {% if prefs.wide == "on" %}checked{% endif %}>
|
||||
</div>
|
||||
<legend>Content</legend>
|
||||
<div id="post_sort">
|
||||
<label for="post_sort" title="Applies only to subreddit feeds">Default subreddit post sort:</label>
|
||||
<select name="post_sort">
|
||||
{% call utils::options(prefs.post_sort, ["hot", "new", "top", "rising", "controversial"], "hot") %}
|
||||
</select>
|
||||
</div>
|
||||
<div id="comment_sort">
|
||||
<label for="comment_sort">Default comment sort:</label>
|
||||
<select name="comment_sort">
|
||||
{% call utils::options(prefs.comment_sort, ["confidence", "top", "new", "controversial", "old"], "confidence") %}
|
||||
</select>
|
||||
</div>
|
||||
{% if !crate::utils::sfw_only() %}
|
||||
<div id="show_nsfw">
|
||||
<label for="show_nsfw">Show NSFW posts:</label>
|
||||
<input type="hidden" value="off" name="show_nsfw">
|
||||
<input type="checkbox" name="show_nsfw" {% if prefs.show_nsfw == "on" %}checked{% endif %}>
|
||||
</div>
|
||||
<div id="blur_nsfw">
|
||||
<label for="blur_nsfw">Blur NSFW previews:</label>
|
||||
<input type="hidden" value="off" name="blur_nsfw">
|
||||
<input type="checkbox" name="blur_nsfw" {% if prefs.blur_nsfw == "on" %}checked{% endif %}>
|
||||
</div>
|
||||
{% endif %}
|
||||
<div id="autoplay_videos">
|
||||
<label for="autoplay_videos">Autoplay videos</label>
|
||||
<input type="hidden" value="off" name="autoplay_videos">
|
||||
<input type="checkbox" name="autoplay_videos" {% if prefs.autoplay_videos == "on" %}checked{% endif %}>
|
||||
</div>
|
||||
<div id="use_hls">
|
||||
<label for="use_hls">Use HLS for videos
|
||||
<details id="feeds">
|
||||
<summary>Why?</summary>
|
||||
<div id="feed_list" class="helper">Reddit videos require JavaScript (via HLS.js) to be enabled to be played with audio. Therefore, this toggle lets you either use Libreddit JS-free or utilize this feature.</div>
|
||||
<div id="feed_list" class="helper">Reddit videos require JavaScript (via HLS.js) to be enabled to be played with audio. Therefore, this toggle lets you either use Ferrit JS-free or utilize this feature.</div>
|
||||
</details>
|
||||
<input type="hidden" value="off" name="use_hls">
|
||||
<input type="checkbox" name="use_hls" id="use_hls" {% if prefs.use_hls == "on" %}checked{% endif %}>
|
||||
</div>
|
||||
<div class="prefs-group">
|
||||
<label for="hide_hls_notification">Hide notification about possible HLS usage</label>
|
||||
<input type="hidden" value="off" name="hide_hls_notification">
|
||||
<input type="checkbox" name="hide_hls_notification" id="hide_hls_notification" {% if prefs.hide_hls_notification == "on" %}checked{% endif %}>
|
||||
</div>
|
||||
<div class="prefs-group">
|
||||
<label for="hide_awards">Hide awards</label>
|
||||
<input type="hidden" value="off" name="hide_awards">
|
||||
<input type="checkbox" name="hide_awards" id="hide_awards" {% if prefs.hide_awards == "on" %}checked{% endif %}>
|
||||
</div>
|
||||
<div class="prefs-group">
|
||||
<label for="disable_visit_reddit_confirmation">Do not confirm before visiting content on Reddit</label>
|
||||
<input type="hidden" value="off" name="disable_visit_reddit_confirmation">
|
||||
<input type="checkbox" name="disable_visit_reddit_confirmation" {% if prefs.disable_visit_reddit_confirmation == "on" %}checked{% endif %}>
|
||||
</div>
|
||||
</fieldset>
|
||||
</label>
|
||||
<input type="hidden" value="off" name="use_hls">
|
||||
<input type="checkbox" name="use_hls" {% if prefs.use_hls == "on" %}checked{% endif %}>
|
||||
</div>
|
||||
<div id="hide_hls_notification">
|
||||
<label for="hide_hls_notification">Hide notification about possible HLS usage</label>
|
||||
<input type="hidden" value="off" name="hide_hls_notification">
|
||||
<input type="checkbox" name="hide_hls_notification" {% if prefs.hide_hls_notification == "on" %}checked{% endif %}>
|
||||
</div>
|
||||
<input id="save" type="submit" value="Save">
|
||||
</div>
|
||||
</form>
|
||||
|
@ -132,7 +117,11 @@
|
|||
|
||||
<div id="settings_note">
|
||||
<p><b>Note:</b> settings and subscriptions are saved in browser cookies. Clearing your cookies will reset them.</p><br>
|
||||
<p>You can restore your current settings and subscriptions after clearing your cookies using <a href="/settings/restore/?theme={{ prefs.theme }}&front_page={{ prefs.front_page }}&layout={{ prefs.layout }}&wide={{ prefs.wide }}&post_sort={{ prefs.post_sort }}&comment_sort={{ prefs.comment_sort }}&show_nsfw={{ prefs.show_nsfw }}&blur_nsfw={{ prefs.blur_nsfw }}&use_hls={{ prefs.use_hls }}&hide_hls_notification={{ prefs.hide_hls_notification }}&hide_awards={{ prefs.hide_awards }}&disable_visit_reddit_confirmation={{ prefs.disable_visit_reddit_confirmation }}&subscriptions={{ prefs.subscriptions.join("%2B") }}&autoplay_videos={{ prefs.autoplay_videos }}&filters={{ prefs.filters.join("%2B") }}">this link</a>.</p>
|
||||
<p>You can restore your current settings and subscriptions after clearing your cookies using <a href="/settings/restore/?theme={{ prefs.theme }}&front_page={{ prefs.front_page }}&layout={{ prefs.layout }}&wide={{ prefs.wide }}&post_sort={{ prefs.post_sort }}&comment_sort={{ prefs.comment_sort }}&show_nsfw={{ prefs.show_nsfw }}&blur_nsfw={{ prefs.blur_nsfw }}&use_hls={{ prefs.use_hls }}&hide_hls_notification={{ prefs.hide_hls_notification }}&subscriptions={{ prefs.subscriptions.join("%2B") }}&filters={{ prefs.filters.join("%2B") }}">this link</a>.</p>
|
||||
<br />
|
||||
{% if crate::utils::sfw_only() %}
|
||||
<p>This instance is SFW-only. It will block all NSFW content.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
|
@ -4,7 +4,7 @@
|
|||
{% block title %}
|
||||
{% if sub.title != "" %}{{ sub.title }}
|
||||
{% else if sub.name != "" %}{{ sub.name }}
|
||||
{% else %}Libreddit{% endif %}
|
||||
{% else %}Ferrit{% endif %}
|
||||
{% endblock %}
|
||||
|
||||
{% block search %}
|
||||
|
@ -50,10 +50,6 @@
|
|||
<center>All posts are hidden because they are NSFW. Enable "Show NSFW posts" in settings to view.</center>
|
||||
{% endif %}
|
||||
|
||||
{% if no_posts %}
|
||||
<center>No posts were found.</center>
|
||||
{% endif %}
|
||||
|
||||
{% if all_posts_filtered %}
|
||||
<center>(All content on this page has been filtered)</center>
|
||||
{% else %}
|
||||
|
@ -88,8 +84,7 @@
|
|||
<center>(Content from r/{{ sub.name }} has been filtered)</center>
|
||||
{% endif %}
|
||||
{% if !sub.name.is_empty() && sub.name != "all" && sub.name != "popular" && !sub.name.contains("+") %}
|
||||
<details class="panel" id="subreddit" open>
|
||||
<summary id="subreddit_label">Subreddit</summary>
|
||||
<div class="panel" id="subreddit">
|
||||
{% if sub.wiki %}
|
||||
<div id="top">
|
||||
<div>Posts</div>
|
||||
|
@ -132,7 +127,7 @@
|
|||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
</div>
|
||||
<details class="panel" id="sidebar">
|
||||
<summary id="sidebar_label">Sidebar</summary>
|
||||
<div id="sidebar_contents">
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
{% call utils::search("".to_owned(), "", "") %}
|
||||
{% endblock %}
|
||||
|
||||
{% block title %}{{ user.name.replace("u/", "") }} (u/{{ user.name }}) - Libreddit{% endblock %}
|
||||
{% block title %}{{ user.name.replace("u/", "") }} (u/{{ user.name }}) - Ferrit{% endblock %}
|
||||
|
||||
{% block subscriptions %}
|
||||
{% call utils::sub_list("") %}
|
||||
|
@ -36,10 +36,6 @@
|
|||
<center>All posts are hidden because they are NSFW. Enable "Show NSFW posts" in settings to view.</center>
|
||||
{% endif %}
|
||||
|
||||
{% if no_posts %}
|
||||
<center>No posts were found.</center>
|
||||
{% endif %}
|
||||
|
||||
{% if all_posts_filtered %}
|
||||
<center>(All content on this page has been filtered)</center>
|
||||
{% else %}
|
||||
|
|
|
@ -16,7 +16,7 @@
|
|||
|
||||
{% macro search(root, search) -%}
|
||||
<form action="{% if root != "/r/" && !root.is_empty() %}{{ root }}{% endif %}/search" id="searchbox">
|
||||
<input id="search" type="text" name="q" placeholder="Search" title="Search libreddit" value="{{ search }}">
|
||||
<input id="search" type="text" name="q" placeholder="Search" title="Search Ferrit" value="{{ search }}">
|
||||
{% if root != "/r/" && !root.is_empty() %}
|
||||
<div id="inside">
|
||||
<input type="checkbox" name="restrict_sr" id="restrict_sr" checked>
|
||||
|
@ -73,7 +73,7 @@
|
|||
{% endif %}
|
||||
<span class="dot">•</span>
|
||||
<span class="created" title="{{ post.created }}">{{ post.rel_time }}</span>
|
||||
{% if !post.awards.is_empty() && prefs.hide_awards != "on" %}
|
||||
{% if !post.awards.is_empty() %}
|
||||
<span class="dot">•</span>
|
||||
<span class="awards">
|
||||
{% for award in post.awards.clone() %}
|
||||
|
@ -115,7 +115,7 @@
|
|||
{% if prefs.use_hls == "on" && !post.media.alt_url.is_empty() %}
|
||||
<script src="/hls.min.js"></script>
|
||||
<div class="post_media_content">
|
||||
<video class="post_media_video short {% if prefs.autoplay_videos == "on" %}hls_autoplay{% endif %}" {% if post.media.width > 0 && post.media.height > 0 %}width="{{ post.media.width }}" height="{{ post.media.height }}"{% endif %} poster="{{ post.media.poster }}" preload="none" controls>
|
||||
<video class="post_media_video short {% if prefs.autoplay_videos == "on" %}hls_autoplay{% endif %}" width="{{ post.media.width }}" height="{{ post.media.height }}" poster="{{ post.media.poster }}" preload="none" controls>
|
||||
<source src="{{ post.media.alt_url }}" type="application/vnd.apple.mpegurl" />
|
||||
<source src="{{ post.media.url }}" type="video/mp4" />
|
||||
</video>
|
||||
|
@ -148,9 +148,6 @@
|
|||
<!-- POST BODY -->
|
||||
<div class="post_body">{{ post.body|safe }}</div>
|
||||
<div class="post_score" title="{{ post.score.1 }}">{{ post.score.0 }}<span class="label"> Upvotes</span></div>
|
||||
|
||||
{% call poll(post) %}
|
||||
|
||||
<div class="post_footer">
|
||||
<ul id="post_links">
|
||||
<li class="desktop_item"><a href="{{ post.permalink }}">permalink</a></li>
|
||||
|
@ -159,32 +156,14 @@
|
|||
<li class="desktop_item"><a href="/r/{{ post.community }}/duplicates/{{ post.id }}">duplicates</a></li>
|
||||
<li class="mobile_item"><a href="/r/{{ post.community }}/duplicates/{{ post.id }}">dupes</a></li>
|
||||
{% endif %}
|
||||
{% call external_reddit_link(post.permalink) %}
|
||||
<li class="desktop_item"><a href="https://reddit.com{{ post.permalink }}" rel="nofollow">reddit</a></li>
|
||||
<li class="mobile_item"><a href="https://reddit.com{{ post.permalink }}" rel="nofollow">reddit</a></li>
|
||||
</ul>
|
||||
<p>{{ post.upvote_ratio }}%<span id="upvoted"> Upvoted</span></p>
|
||||
</div>
|
||||
</div>
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro external_reddit_link(permalink) %}
|
||||
{% for dev_type in ["desktop", "mobile"] %}
|
||||
<li class="{{ dev_type }}_item">
|
||||
<a
|
||||
{% if prefs.disable_visit_reddit_confirmation != "on" %}
|
||||
href="#popup"
|
||||
{% else %}
|
||||
href="https://reddit.com{{ permalink }}"
|
||||
rel="nofollow"
|
||||
{% endif %}
|
||||
>reddit</a>
|
||||
|
||||
{% if prefs.disable_visit_reddit_confirmation != "on" %}
|
||||
{% call visit_reddit_confirmation(permalink) %}
|
||||
{% endif %}
|
||||
</li>
|
||||
{% endfor %}
|
||||
{% endmacro %}
|
||||
|
||||
{% macro post_in_list(post) -%}
|
||||
<div class="post {% if post.flags.stickied %}stickied{% endif %}" id="{{ post.id }}">
|
||||
<p class="post_header">
|
||||
|
@ -199,7 +178,7 @@
|
|||
<a class="post_author {{ post.author.distinguished }}" href="/u/{{ post.author.name }}">u/{{ post.author.name }}</a>
|
||||
<span class="dot">•</span>
|
||||
<span class="created" title="{{ post.created }}">{{ post.rel_time }}</span>
|
||||
{% if !post.awards.is_empty() && prefs.hide_awards != "on" %}
|
||||
{% if !post.awards.is_empty() %}
|
||||
{% for award in post.awards.clone() %}
|
||||
<span class="award" title="{{ award.name }}">
|
||||
<img alt="{{ award.name }}" src="{{ award.icon_url }}" width="16" height="16"/>
|
||||
|
@ -234,19 +213,19 @@
|
|||
</div>
|
||||
{% else if (prefs.layout.is_empty() || prefs.layout == "card") && post.post_type == "gif" %}
|
||||
<div class="post_media_content">
|
||||
<video class="post_media_video short {%if post.flags.nsfw && prefs.blur_nsfw=="on" %}post_nsfw_blur{% endif %}" src="{{ post.media.url }}" {% if post.media.width > 0 && post.media.height > 0 %}width="{{ post.media.width }}" height="{{ post.media.height }}"{% endif %} poster="{{ post.media.poster }}" preload="none" controls loop {% if prefs.autoplay_videos == "on" %}autoplay{% endif %}><a href={{ post.media.url }}>Video</a></video>
|
||||
<video class="post_media_video short {%if post.flags.nsfw && prefs.blur_nsfw=="on" %}post_nsfw_blur{% endif %}" src="{{ post.media.url }}" width="{{ post.media.width }}" height="{{ post.media.height }}" poster="{{ post.media.poster }}" preload="none" controls loop {% if prefs.autoplay_videos == "on" %}autoplay{% endif %}><a href={{ post.media.url }}>Video</a></video>
|
||||
</div>
|
||||
{% else if (prefs.layout.is_empty() || prefs.layout == "card") && post.post_type == "video" %}
|
||||
{% if prefs.use_hls == "on" && !post.media.alt_url.is_empty() %}
|
||||
<div class="post_media_content">
|
||||
<video class="post_media_video short {%if post.flags.nsfw && prefs.blur_nsfw=="on" %}post_nsfw_blur{% endif %} {% if prefs.autoplay_videos == "on" %}hls_autoplay{% endif %}" {% if post.media.width > 0 && post.media.height > 0 %}width="{{ post.media.width }}" height="{{ post.media.height }}"{% endif %} poster="{{ post.media.poster }}" controls preload="none">
|
||||
<video class="post_media_video short {%if post.flags.nsfw && prefs.blur_nsfw=="on" %}post_nsfw_blur{% endif %} {% if prefs.autoplay_videos == "on" %}hls_autoplay{% endif %}" width="{{ post.media.width }}" height="{{ post.media.height }}" poster="{{ post.media.poster }}" controls preload="none">
|
||||
<source src="{{ post.media.alt_url }}" type="application/vnd.apple.mpegurl" />
|
||||
<source src="{{ post.media.url }}" type="video/mp4" />
|
||||
</video>
|
||||
</div>
|
||||
{% else %}
|
||||
<div class="post_media_content">
|
||||
<video class="post_media_video short {%if post.flags.nsfw && prefs.blur_nsfw=="on" %}post_nsfw_blur{% endif %}" src="{{ post.media.url }}" {% if post.media.width > 0 && post.media.height > 0 %}width="{{ post.media.width }}" height="{{ post.media.height }}"{% endif %} poster="{{ post.media.poster }}" preload="none" controls {% if prefs.autoplay_videos == "on" %}autoplay{% endif %}><a href={{ post.media.url }}>Video</a></video>
|
||||
<video class="post_media_video short {%if post.flags.nsfw && prefs.blur_nsfw=="on" %}post_nsfw_blur{% endif %}" src="{{ post.media.url }}" width="{{ post.media.width }}" height="{{ post.media.height }}" poster="{{ post.media.poster }}" preload="none" controls {% if prefs.autoplay_videos == "on" %}autoplay{% endif %}><a href={{ post.media.url }}>Video</a></video>
|
||||
</div>
|
||||
{% call render_hls_notification(format!("{}%23{}", &self.url[1..].replace("&", "%26").replace("+", "%2B"), post.id)) %}
|
||||
{% endif %}
|
||||
|
@ -275,64 +254,8 @@
|
|||
<div class="post_body post_preview">
|
||||
{{ post.body|safe }}
|
||||
</div>
|
||||
|
||||
{% call poll(post) %}
|
||||
|
||||
<div class="post_footer">
|
||||
<a href="{{ post.permalink }}" class="post_comments" title="{{ post.comments.1 }} {% if post.comments.1 == "1" %}comment{% else %}comments{% endif %}">{{ post.comments.0 }} {% if post.comments.1 == "1" %}comment{% else %}comments{% endif %}</a>
|
||||
<a href="{{ post.permalink }}" class="post_comments" title="{{ post.comments.1 }} comments">{{ post.comments.0 }} comments</a>
|
||||
</div>
|
||||
</div>
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro visit_reddit_confirmation(url) -%}
|
||||
<div class="popup" id="popup">
|
||||
<div class="popup-inner">
|
||||
<h1>You are about to leave Libreddit</h1>
|
||||
<p>Do you want to continue?</p>
|
||||
<p id="reddit_url">https://www.reddit.com{{ url }}</p>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 639.24 563">
|
||||
<defs>
|
||||
<style>.cls-1{fill:#000000;}.cls-2{fill:#f8aa00;}</style>
|
||||
</defs>
|
||||
<path class="cls-2" d="M322.03,0c1.95,2.5,4.88,.9,7.33,1.65,10.5,3.21,17.65,10.39,22.83,19.35,93.64,162.06,186.98,324.29,280.25,486.56,15.73,20.19,2.49,51.27-22.92,54.37-1.21,.19-2.72-.54-3.49,1.08H239.03c-70.33-2.43-141.6,.79-212.08-1.74-17.49-4.92-23.16-15.88-26.91-32.26l-.04-1.97C88.74,354.76,194.49,188.2,289.92,18.43c6.2-10.66,15.03-16.94,27.61-17.36,.95-.03,2.05,.18,2.51-1.07h2Zm-2.43,545c94.95-.02,189.9,.04,284.85-.02,11.84-.73,20.75-13.19,16.68-23.55C523.83,355.97,430.74,187.62,332.05,23.07c-7.93-9.02-22.2-6.58-27.23,3.22C230.28,156.11,155.21,285.64,80.41,415.31c-19.88,34.41-39.31,69.07-59.78,103.14-2.43,4.05-4.24,8.8-1.68,14.18,3.92,8.24,9.59,12.37,18.82,12.37,93.95,0,187.9,0,281.85,0Z"/>
|
||||
<path class="cls-1" d="M319.61,545c-93.95,0-187.9,0-281.85,0-9.22,0-14.89-4.13-18.82-12.37-2.56-5.38-.75-10.13,1.68-14.18,20.47-34.07,39.9-68.73,59.78-103.14C155.21,285.64,230.28,156.11,304.82,26.29c5.03-9.8,19.3-12.24,27.23-3.22,98.7,164.55,191.79,332.9,289.1,498.35,4.06,10.36-4.85,22.82-16.68,23.55-94.94,.06-189.9,0-284.85,.02Zm.44-462.31C238.88,223.22,158.17,362.95,77.28,503h485.54c-80.94-140.13-161.61-279.79-242.77-420.31Z"/>
|
||||
<path class="cls-2" d="M320.05,82.69c81.16,140.52,161.83,280.18,242.77,420.31H77.28C158.17,362.95,238.88,223.22,320.05,82.69Zm36.05,118.99c-.14-46.75-68.32-52.32-74.66-4.76,.73,51.49,9.2,102.97,12.63,154.49,1.18,13.14,10.53,21.81,23.32,22.76,13.12,.97,23.89-9.13,24.96-21.58,4.44-49.99,9.4-101.22,13.76-150.91Zm-36.56,271.4c48.8,.76,49.24-74.7-.31-75.47-53.45,3-46.02,78.12,.31,75.47Z"/>
|
||||
<path class="cls-1" d="M356.1,201.67c-4.36,49.69-9.31,100.91-13.76,150.91-1.07,12.45-11.84,22.56-24.96,21.58-12.79-.95-22.14-9.63-23.31-22.76-3.43-51.52-11.9-103-12.63-154.49,6.33-47.53,74.51-42.03,74.66,4.76Z"/>
|
||||
<path class="cls-1" d="M319.54,473.08c-46.34,2.64-53.75-72.47-.31-75.47,49.56,.78,49.1,76.24,.31,75.47Z"/>
|
||||
</svg>
|
||||
<a id="goback" href="#">No, go back!</a>
|
||||
<a id="toreddit" href="https://www.reddit.com{{ url }}" rel="nofollow">Yes, take me to Reddit</a>
|
||||
</div>
|
||||
</div>
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro poll(post) -%}
|
||||
{% match post.poll %}
|
||||
{% when Some with (poll) %}
|
||||
{% let widest = poll.most_votes() %}
|
||||
<div class="post_poll">
|
||||
<span>{{ poll.total_vote_count }} votes,</span>
|
||||
<span title="{{ poll.voting_end_timestamp.1 }}">{{ poll.voting_end_timestamp.0 }}</span>
|
||||
{% for option in poll.poll_options %}
|
||||
<div class="poll_option">
|
||||
{# Posts without vote_count (all open polls) will show up without votes.
|
||||
This is an issue with Reddit API, it doesn't work on Old Reddit either. #}
|
||||
{% match option.vote_count %}
|
||||
{% when Some with (vote_count) %}
|
||||
{% if vote_count.eq(widest) || widest == 0 %}
|
||||
<div class="poll_chart most_voted"></div>
|
||||
{% else %}
|
||||
<div class="poll_chart" style="width: {{ (vote_count * 100) / widest }}%"></div>
|
||||
{% endif %}
|
||||
<span>{{ vote_count }}</span>
|
||||
{% when None %}
|
||||
<div class="poll_chart most_voted"></div>
|
||||
<span></span>
|
||||
{% endmatch %}
|
||||
<span>{{ option.text }}</span>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% when None %}
|
||||
{% endmatch %}
|
||||
{%- endmacro %}
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
|
||||
{% block title %}
|
||||
{% if sub != "" %}{{ page }} - {{ sub }}
|
||||
{% else %}Libreddit{% endif %}
|
||||
{% else %}Ferrit{% endif %}
|
||||
{% endblock %}
|
||||
|
||||
{% block search %}
|
||||
|
|