forked from artixweb/artixweb_packages
Compare commits
1 Commits
repos-upda
...
developmen
Author | SHA1 | Date | |
---|---|---|---|
![]() |
7b5b4a1982 |
@@ -1,117 +0,0 @@
|
||||
name: Docker Image CI
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
branches: [ master ]
|
||||
push:
|
||||
branches: [ master ]
|
||||
tags:
|
||||
- 'v*'
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
|
||||
|
||||
jobs:
|
||||
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 90
|
||||
strategy:
|
||||
fail-fast: true
|
||||
env:
|
||||
REGISTRY: gitea.artixlinux.org
|
||||
DH_REGISTRY: docker.io
|
||||
REPO_ORG: ${{ gitea.repository_owner }}
|
||||
DH_ORG: artixlinux
|
||||
IMAGE_NAME: artixweb_packages
|
||||
DH_IMAGE_NAME: artixweb-packages
|
||||
ABSOLUTE_IMAGE: ${{ env.REGISTRY }}/${{ env.REPO_ORG }}/${{ env.IMAGE_NAME }}
|
||||
ABSOLUTE_DH_IMAGE: ${{ env.DH_REGISTRY }}/${{ env.DH_ORG }}/${{ env.DH_IMAGE_NAME }}
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: https://github.com/actions/checkout@v4
|
||||
- name: Set up docker
|
||||
run: curl -fsSL https://get.docker.com | sh
|
||||
- name: Set up QEMU
|
||||
uses: https://github.com/docker/setup-qemu-action@v2
|
||||
- name: Set up Docker Buildx
|
||||
id: buildx
|
||||
uses: https://github.com/docker/setup-buildx-action@v2
|
||||
with:
|
||||
install: true
|
||||
|
||||
- name: Log in to the Container registry
|
||||
uses: https://github.com/docker/login-action@v2
|
||||
if: startsWith(gitea.ref, 'refs/tags/v')
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: corysanin
|
||||
password: ${{ secrets.PAT }}
|
||||
|
||||
- name: Log in to the Docker Hub
|
||||
uses: https://github.com/docker/login-action@v2
|
||||
if: startsWith(gitea.ref, 'refs/tags/v')
|
||||
with:
|
||||
registry: ${{ env.DH_REGISTRY }}
|
||||
username: ${{ secrets.DOCKERHUB_USER }}
|
||||
password: ${{ secrets.DOCKERHUB }}
|
||||
|
||||
- name: Define metadata variables
|
||||
if: startsWith(gitea.ref, 'refs/tags/v')
|
||||
run: |
|
||||
sed -i "s/LABEL Version=.*/ARG version=${{ gitea.ref_name }}/" Dockerfile
|
||||
cat Dockerfile
|
||||
|
||||
- name: Extract metadata for release Docker image
|
||||
if: startsWith(gitea.ref, 'refs/tags/v')
|
||||
id: meta
|
||||
uses: https://github.com/docker/metadata-action@v5
|
||||
with:
|
||||
images: |
|
||||
${{ env.ABSOLUTE_DH_IMAGE }}
|
||||
# ${{ env.ABSOLUTE_IMAGE }}
|
||||
##unexpected status from PUT request: 413 Request Entity Too Large
|
||||
tags: |
|
||||
type=raw,value=latest
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=semver,pattern={{major}}
|
||||
|
||||
- name: Extract metadata for develop Docker image
|
||||
if: "!startsWith(gitea.ref, 'refs/tags/v')"
|
||||
id: meta-develop
|
||||
uses: https://github.com/docker/metadata-action@v5
|
||||
with:
|
||||
images: |
|
||||
${{ env.ABSOLUTE_IMAGE }}
|
||||
tags: |
|
||||
type=ref,enable=true,priority=600,prefix=,suffix=,event=branch
|
||||
type=ref,enable=true,priority=600,prefix=pr-,suffix=,event=pr
|
||||
|
||||
- name: Build and push release Docker image
|
||||
if: startsWith(gitea.ref, 'refs/tags/v')
|
||||
uses: https://github.com/docker/build-push-action@v4
|
||||
with:
|
||||
file: Dockerfile.ci
|
||||
target: deploy
|
||||
pull: true
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
platforms: linux/amd64
|
||||
|
||||
- name: Build develop Docker image
|
||||
if: "!startsWith(gitea.ref, 'refs/tags/v')"
|
||||
uses: https://github.com/docker/build-push-action@v4
|
||||
with:
|
||||
file: Dockerfile.ci
|
||||
target: deploy
|
||||
pull: true
|
||||
push: false
|
||||
tags: ${{ steps.meta-develop.outputs.tags }}
|
||||
labels: ${{ steps.meta-develop.outputs.labels }}
|
||||
platforms: linux/amd64
|
2
.gitignore
vendored
2
.gitignore
vendored
@@ -1,6 +1,6 @@
|
||||
# Cargo stuff
|
||||
target/
|
||||
*/Cargo.lock
|
||||
*Cargo.lock
|
||||
|
||||
# editor stuff
|
||||
.vscode/
|
||||
|
2627
Cargo.lock
generated
2627
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,58 +0,0 @@
|
||||
# This file is part of Artix Web Packages. See LICENSE file for details
|
||||
# Copyright 2022 - Artix Linux
|
||||
FROM artixlinux/artixlinux:base as build
|
||||
|
||||
# update pacman
|
||||
# install clang and pkg-config
|
||||
# install rustup and put $HOME/.cargo/bin in the $PATH
|
||||
# install stable and nightly toolchains
|
||||
# install rustfmt-preview and clippy-preview in the nightly toolchain
|
||||
RUN set -x \
|
||||
&& pacman -Syu --noconfirm \
|
||||
&& pacman -S --noconfirm clang pkgconf \
|
||||
&& pacman -Scc --noconfirm \
|
||||
&& curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y \
|
||||
&& export PATH="$HOME/.cargo/bin:$PATH" \
|
||||
&& rustup toolchain add stable nightly \
|
||||
&& rustup component add --toolchain nightly rustfmt-preview clippy-preview
|
||||
|
||||
# Update PATH in the container
|
||||
ENV PATH="/root/.cargo/bin:${PATH}"
|
||||
ENV RUSTUP_TOOLCHAIN=stable
|
||||
|
||||
RUN pacman -Sy --noconfirm postgresql-libs
|
||||
|
||||
WORKDIR /build
|
||||
|
||||
COPY . ./
|
||||
|
||||
RUN cargo build --release
|
||||
RUN set -x \
|
||||
&& install -vd /usr/share/artixweb_packages/assets \
|
||||
&& cp -rv crates/artixweb-packages/assets/* /usr/share/artixweb_packages/assets/ \
|
||||
&& install -vd /usr/share/artixweb_packages/templates \
|
||||
&& cp -v crates/artixweb-packages/templates/* /usr/share/artixweb_packages/templates/ \
|
||||
&& install -vDm 755 target/release/artixweb_packages -t "/usr/share/artixweb_packages"
|
||||
|
||||
FROM artixlinux/artixlinux:base AS deploy
|
||||
|
||||
LABEL Maintainer="damnwidget@artixlinux.org"
|
||||
LABEL Name="Artix Web Packages Container"
|
||||
LABEL Version="Develop"
|
||||
|
||||
EXPOSE 1936/tcp
|
||||
|
||||
RUN pacman -Sy --noconfirm postgresql-libs \
|
||||
&& set -x \
|
||||
&& pacman -Syu --noconfirm \
|
||||
&& pacman -Scc --noconfirm \
|
||||
&& printf "\n[lib32]\nInclude = /etc/pacman.d/mirrorlist" >> /etc/pacman.conf \
|
||||
&& printf "\n[system-gremlins]\nInclude = /etc/pacman.d/mirrorlist" >> /etc/pacman.conf \
|
||||
&& printf "\n[world-gremlins]\nInclude = /etc/pacman.d/mirrorlist" >> /etc/pacman.conf \
|
||||
&& printf "\n[galaxy-gremlins]\nInclude = /etc/pacman.d/mirrorlist" >> /etc/pacman.conf \
|
||||
&& printf "\n[lib32-gremlins]\nInclude = /etc/pacman.d/mirrorlist" >> /etc/pacman.conf \
|
||||
&& pacman -Sy --noconfirm
|
||||
|
||||
WORKDIR /usr/share/artixweb_packages
|
||||
COPY --from=0 /usr/share/artixweb_packages ./
|
||||
CMD ["./artixweb_packages"]
|
@@ -2,7 +2,7 @@
|
||||
# Copyright 2022 - Artix Linux
|
||||
FROM artixlinux/artixweb-packages-ci:latest AS build
|
||||
|
||||
LABEL Maintainer="damnwidget@artixlinux.org"
|
||||
LABEL Maintainer="nikolar@artixlinux.org"
|
||||
LABEL Name="Artix Web Packages Container"
|
||||
LABEL Version="0.1.0"
|
||||
|
||||
|
@@ -1,21 +1,24 @@
|
||||
[package]
|
||||
name = "artix-gitea"
|
||||
authors = ["Oscar Campos <damnwidget@artixlinux.org>"]
|
||||
description = "Search for packages in Artix Linux repositories"
|
||||
authors = [
|
||||
"Oscar Campos <damnwidget@artixlinux.org>",
|
||||
"Nikola Radojević <nikolar@artixlinux.org>"
|
||||
]
|
||||
exclude = [".gitignore", ".cargo/config"]
|
||||
repository = "gitea.artixlinux.org/artix/artixweb_packaes"
|
||||
homepage = "https://packages.artixlinux.org"
|
||||
keywords = ["artix", "packages", "gitea"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
edition = "2021"
|
||||
version = "0.1.2"
|
||||
version = "0.1.0"
|
||||
|
||||
[lib]
|
||||
name = "artix_gitea"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "4.0.1"
|
||||
serde = { version = "1.0.136", features = ["derive"] }
|
||||
awc = { version = "3.0.0", features = ["rustls"] }
|
||||
chrono = { version = "0.4.19", features = ["serde"] }
|
||||
actix-web = "4.3.1"
|
||||
serde = { version = "1.0.163", features = ["derive"] }
|
||||
awc = { version = "3.1.1", features = ["rustls"] }
|
||||
chrono = { version = "0.4.24", features = ["serde"] }
|
||||
|
@@ -1,14 +1,17 @@
|
||||
[package]
|
||||
name = "artix-pkglib"
|
||||
authors = ["Oscar Campos <damnwidget@artixlinux.org>"]
|
||||
description = "Manipulate Artix Linux packages and databases"
|
||||
authors = [
|
||||
"Oscar Campos <damnwidget@artixlinux.org>",
|
||||
"Nikola Radojević <nikolar@artixlinux.org>"
|
||||
]
|
||||
exclude = [".gitignore", ".cargo/config"]
|
||||
repository = "gitea.artixlinux.org/artix/artixweb_packages"
|
||||
homepage = "https://packages.artixlinux.org"
|
||||
keywords = ["artix", "packages"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
edition = "2021"
|
||||
version = "0.1.2"
|
||||
version = "0.1.0"
|
||||
|
||||
[lib]
|
||||
name = "artix_pkglib"
|
||||
@@ -16,7 +19,7 @@ path = "src/lib.rs"
|
||||
|
||||
|
||||
[dependencies]
|
||||
alpm = "3.0.4"
|
||||
alpm-utils = "3.0.2"
|
||||
pacmanconf = "2.1.0"
|
||||
thiserror = "1.0.58"
|
||||
alpm = "2.2.2"
|
||||
alpm-utils = "2.0.0"
|
||||
pacmanconf = "2.0.0"
|
||||
thiserror = "1.0.40"
|
||||
|
@@ -11,14 +11,14 @@ use alpm::{Alpm, Db, Package};
|
||||
|
||||
/// Data structure used to returns information about an specific packages search
|
||||
pub struct PackagesResultData<'a> {
|
||||
packages: Vec<&'a Package>,
|
||||
packages: Vec<Package<'a>>,
|
||||
total: usize,
|
||||
}
|
||||
|
||||
impl<'a> PackagesResultData<'a> {
|
||||
/// Retrieve the packages of this result if any
|
||||
#[must_use]
|
||||
pub fn packages(&self) -> &Vec<&Package> {
|
||||
pub fn packages(&self) -> &Vec<Package<'a>> {
|
||||
&self.packages
|
||||
}
|
||||
|
||||
@@ -32,19 +32,22 @@ impl<'a> PackagesResultData<'a> {
|
||||
/// Returns back all the packages contained in the given database
|
||||
/// If the database is invalid it returns None
|
||||
#[must_use]
|
||||
pub fn get_packages<'a>(db: &'a Db, limit: usize, offset: usize) -> Vec<&'a Package> {
|
||||
pub fn get_packages(db: Db<'_>, limit: usize, offset: usize) -> Vec<Package<'_>> {
|
||||
let mut ret = Vec::new();
|
||||
if db.is_valid().is_ok() {
|
||||
let pkgs = db.pkgs();
|
||||
if pkgs.is_empty() {
|
||||
return ret;
|
||||
}
|
||||
ret.extend(pkgs);
|
||||
|
||||
// if offset is set, truncate the vector at the given offset
|
||||
if offset != 0 && offset < ret.len() {
|
||||
ret = ret.split_off(offset);
|
||||
// if offset is set, split the vector at the given offset
|
||||
if offset != 0 {
|
||||
ret = ret.split_at(offset).1.to_vec();
|
||||
}
|
||||
|
||||
// if limit is set, truncate the vector at it
|
||||
if limit != 0 && limit < ret.len() {
|
||||
if limit != 0 {
|
||||
ret.truncate(limit);
|
||||
}
|
||||
}
|
||||
@@ -82,7 +85,7 @@ pub fn get_all_packages<'a>(
|
||||
|
||||
if ret.is_empty() {
|
||||
return PackagesResultData {
|
||||
packages: Vec::new(),
|
||||
packages: ret,
|
||||
total: 0,
|
||||
};
|
||||
}
|
||||
@@ -123,14 +126,14 @@ mod test {
|
||||
let alpm = Alpm::new("/", &db_location).unwrap();
|
||||
let db = alpm.register_syncdb("world", SigLevel::NONE).unwrap();
|
||||
|
||||
let pkgs = get_packages(*db, 0, 0);
|
||||
let pkgs = get_packages(db, 0, 0);
|
||||
assert!(!pkgs.is_empty());
|
||||
|
||||
let pkgs = get_packages(*db, 2, 0);
|
||||
let pkgs = get_packages(db, 2, 0);
|
||||
assert_eq!(pkgs.len(), 2);
|
||||
|
||||
let pkgs = get_packages(*db, 0, 0);
|
||||
let pkgs2 = get_packages(*db, 0, 10);
|
||||
let pkgs = get_packages(db, 0, 0);
|
||||
let pkgs2 = get_packages(db, 0, 10);
|
||||
assert_eq!(pkgs2[0].name(), pkgs[10].name());
|
||||
}
|
||||
|
||||
|
@@ -5,7 +5,7 @@
|
||||
Copyright (c) 2022 - Oscar Campos <damnwidget@artixlinux.org>
|
||||
*/
|
||||
|
||||
use alpm::{Alpm, AlpmList, Dep, Package, Pkg, Ver};
|
||||
use alpm::{Alpm, AlpmList, Dep, Package, Ver};
|
||||
|
||||
use crate::error::Error;
|
||||
|
||||
@@ -17,7 +17,7 @@ use crate::error::Error;
|
||||
pub fn get_package_dependencies<'a>(
|
||||
alpm: &'a Alpm,
|
||||
package_name: &'a str,
|
||||
) -> Result<AlpmList<'a, &'a Dep>, Error<'a>> {
|
||||
) -> Result<AlpmList<'a, Dep<'a>>, Error<'a>> {
|
||||
for db in alpm.syncdbs() {
|
||||
let db_pkgs = db.search([package_name].iter());
|
||||
if let Ok(pkgs) = db_pkgs {
|
||||
@@ -40,7 +40,7 @@ pub fn get_package_dependencies<'a>(
|
||||
pub fn get_package_optional_dependencies<'a>(
|
||||
alpm: &'a Alpm,
|
||||
package_name: &'a str,
|
||||
) -> Result<AlpmList<'a, &'a Dep>, Error<'a>> {
|
||||
) -> Result<AlpmList<'a, Dep<'a>>, Error<'a>> {
|
||||
for db in alpm.syncdbs() {
|
||||
let db_pkgs = db.search([package_name].iter());
|
||||
if let Ok(pkgs) = db_pkgs {
|
||||
@@ -84,7 +84,7 @@ pub fn get_package_version<'a>(
|
||||
///
|
||||
/// If the package can not be found a [`Error::PackageNotFound`] error is returned
|
||||
#[allow(clippy::module_name_repetitions)]
|
||||
pub fn get_package<'a>(alpm: &'a Alpm, package_name: &'a str) -> Result<&'a Pkg, Error<'a>> {
|
||||
pub fn get_package<'a>(alpm: &'a Alpm, package_name: &'a str) -> Result<Package<'a>, Error<'a>> {
|
||||
for db in alpm.syncdbs() {
|
||||
let db_pkgs = db.search([package_name].iter());
|
||||
if let Ok(pkgs) = db_pkgs {
|
||||
@@ -110,15 +110,15 @@ pub fn retrieve_providers<'a>(
|
||||
arch: &str,
|
||||
alpm: &'a Alpm,
|
||||
requirement: &'a str,
|
||||
) -> Vec<&'a Package> {
|
||||
let mut pkgs: Vec<&'a Package> = Vec::new();
|
||||
) -> Vec<Package<'a>> {
|
||||
let mut pkgs = Vec::new();
|
||||
for db in alpm.syncdbs() {
|
||||
if arch.to_lowercase() != "any" && db.name() == "lib32" {
|
||||
continue;
|
||||
}
|
||||
|
||||
for pkg in db.pkgs() {
|
||||
let mut a: Vec<&'a Dep> = Vec::new();
|
||||
let mut a: Vec<Dep<'_>> = Vec::new();
|
||||
a.extend(pkg.provides().iter().filter(|d| d.name() == requirement));
|
||||
if !a.is_empty() {
|
||||
pkgs.push(pkg);
|
||||
|
@@ -1,13 +1,16 @@
|
||||
[package]
|
||||
name = "artixweb_packages"
|
||||
authors = ["Oscar Campos <damnwidget@artixlinux.org>"]
|
||||
description = "Artix Linux Packages Information Website"
|
||||
authors = [
|
||||
"Oscar Campos <damnwidget@artixlinux.org>",
|
||||
"Nikola Radojević <nikolar@artixlinux.org>"
|
||||
]
|
||||
exclude = [".gitignore", ".cargo/config"]
|
||||
repository = "gitea.artixlinux.org/artix/artixweb_packages"
|
||||
keywords = ["artix", "packages"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
edition = "2021"
|
||||
version = "0.1.2"
|
||||
version = "0.1.0"
|
||||
|
||||
[[bin]]
|
||||
name = "artixweb_packages"
|
||||
@@ -15,32 +18,33 @@ test = false
|
||||
bench = false
|
||||
|
||||
[dependencies]
|
||||
artix-gitea = { path = "../artix-gitea", version = "=0.1.2" }
|
||||
artix-pkglib = { path = "../artix-pkglib", version = "=0.1.2" }
|
||||
artix-gitea = { path = "../artix-gitea", version = "=0.1.0" }
|
||||
artix-pkglib = { path = "../artix-pkglib", version = "=0.1.0" }
|
||||
|
||||
actix-files = "0.6.0"
|
||||
actix-identity = "0.4"
|
||||
argon2 = "0.4.0"
|
||||
askama = "0.11.1"
|
||||
actix-files = "0.6.2"
|
||||
actix-identity = "0.4.0"
|
||||
argon2 = "0.5.0"
|
||||
askama = "0.12.0"
|
||||
derive_more = "0.99.17"
|
||||
env_logger = "0.9.0"
|
||||
env_logger = "0.10.0"
|
||||
lazy_static = "1.4.0"
|
||||
lettre = "0.10.0-rc.4"
|
||||
log = "0.4.14"
|
||||
r2d2 = "0.8"
|
||||
time = "0.3"
|
||||
lettre = "0.10.4"
|
||||
log = "0.4.17"
|
||||
r2d2 = "0.8.10"
|
||||
time = "0.3.21"
|
||||
|
||||
actix-session = { version = "0.6.0", features = ["cookie-session"] }
|
||||
actix-web = { version = "4.0.1", features = ["rustls"] }
|
||||
clap = { version = "3.1.5", features = ["cargo", "suggestions", "env"] }
|
||||
chrono = { version = "0.4.19", features = ["serde"] }
|
||||
diesel = { version = "1.4.8", features = [
|
||||
actix-session = { version = "0.7.2", features = ["cookie-session"] }
|
||||
actix-web = { version = "4.3.1", features = ["rustls"] }
|
||||
clap = { version = "4.3.0", features = ["cargo", "suggestions", "env"] }
|
||||
chrono = { version = "0.4.24", features = ["serde"] }
|
||||
diesel = { version = "2.0.4", features = [
|
||||
"postgres",
|
||||
"uuidv07",
|
||||
"sqlite",
|
||||
"uuid",
|
||||
"r2d2",
|
||||
"chrono",
|
||||
] }
|
||||
rand_core = { version = "0.6", features = ["std"] }
|
||||
rand_core = { version = "0.6.4", features = ["std"] }
|
||||
serde = { version = "^1.0", features = ["derive"] }
|
||||
serde_json = { version = "1.0.79" }
|
||||
uuid = { version = "0.8", features = ["serde", "v4"] }
|
||||
serde_json = { version = "1.0.96" }
|
||||
uuid = { version = "1.3.1", features = ["serde", "v4"] }
|
||||
|
@@ -3,30 +3,41 @@
|
||||
|
||||
Copyright (c) 2022 - Artix Linux
|
||||
Copyright (c) 2022 - Oscar Campos <damnwidget@artixlinux.org>
|
||||
Copyright (c) 2023 - Nikola Radojević <nikolar@artixlinux.org>
|
||||
*/
|
||||
|
||||
use std::{env, fs::File, io::Read, path::Path};
|
||||
|
||||
use argon2::{password_hash::SaltString, Argon2, PasswordHash, PasswordHasher, PasswordVerifier};
|
||||
use argon2::{
|
||||
password_hash::SaltString, Argon2, PasswordHash, PasswordHasher,
|
||||
PasswordVerifier,
|
||||
};
|
||||
use artix_pkglib::prelude::{Alpm, SigLevel};
|
||||
use rand_core::OsRng;
|
||||
|
||||
use super::lib::errors::ServiceError;
|
||||
use super::utils::errors::ServiceError;
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
/// Global constant application settings
|
||||
pub static ref SETTINGS: AppSettings = AppSettings {
|
||||
app_name: env::var("APP_NAME").unwrap_or_else(|_| String::from("ArtixWeb Packages")),
|
||||
gitea_url: env::var("GITEA_URL").unwrap_or_else(|_| String::from(artix_gitea::prelude::GITEA_URL)),
|
||||
gitea_api_url: env::var("GITEA_API_URL").unwrap_or_else(|_| String::from(artix_gitea::prelude::GITEA_API_URL)),
|
||||
gitea_token: env::var("GITEA_TOKEN").unwrap_or_else(|_| String::new()),
|
||||
databases_path: env::var("DATABASES_PATH").unwrap_or_else(|_| String::from("/var/lib/pacman")),
|
||||
api_token: env::var("API_TOKEN").unwrap_or_else(|_| generate_random_token()),
|
||||
app_name: env::var("APP_NAME")
|
||||
.unwrap_or_else(|_| String::from("ArtixWeb Packages")),
|
||||
gitea_url: env::var("GITEA_URL")
|
||||
.unwrap_or_else(|_| String::from(artix_gitea::prelude::GITEA_URL)),
|
||||
gitea_api_url: env::var("GITEA_API_URL")
|
||||
.unwrap_or_else(|_| String::from(artix_gitea::prelude::GITEA_API_URL)),
|
||||
gitea_token: env::var("GITEA_TOKEN")
|
||||
.unwrap_or_else(|_| String::new()),
|
||||
databases_path: env::var("DATABASES_PATH")
|
||||
.unwrap_or_else(|_| String::from("/var/lib/pacman")),
|
||||
api_token: env::var("API_TOKEN")
|
||||
.unwrap_or_else(|_| generate_random_token()),
|
||||
};
|
||||
}
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
pub static ref SECRET_KEY: String = std::env::var("SECRET_KEY").unwrap_or_else(|_| generate_random_token());
|
||||
pub static ref SECRET_KEY: String = std::env::var("SECRET_KEY")
|
||||
.unwrap_or_else(|_| generate_random_token());
|
||||
}
|
||||
|
||||
/// Data structure containing the site configuration
|
||||
@@ -73,16 +84,8 @@ fn generate_random_token() -> String {
|
||||
token
|
||||
}
|
||||
|
||||
const DATABASESS: [&str; 8] = [
|
||||
"system",
|
||||
"world",
|
||||
"galaxy",
|
||||
"lib32",
|
||||
"system-gremlins",
|
||||
"world-gremlins",
|
||||
"galaxy-gremlins",
|
||||
"lib32-gremlins"
|
||||
];
|
||||
const DATABASESS: [&str; 5] =
|
||||
["system", "world", "galaxy", "universe", "lib32"];
|
||||
const MIN_PASSWORD_LENGTH: usize = 8;
|
||||
|
||||
/// Syncs the configured databases
|
||||
|
@@ -3,21 +3,24 @@
|
||||
|
||||
Copyright (c) 2022 - Artix Linux
|
||||
Copyright (c) 2022 - Oscar Campos <damnwidget@artixlinux.org>
|
||||
Copyright (c) 2022 - Nikola Radojević <nikolar@artixlinux.org>
|
||||
*/
|
||||
|
||||
use std::future::{ready, Ready};
|
||||
|
||||
use actix_identity::Identity;
|
||||
use actix_session::Session;
|
||||
use actix_web::{dev::Payload, http, web, Error, FromRequest, HttpRequest, HttpResponse};
|
||||
use actix_web::{
|
||||
dev::Payload, http, web, Error, FromRequest, HttpRequest, HttpResponse,
|
||||
};
|
||||
use askama::Template;
|
||||
use diesel::prelude::*;
|
||||
use diesel::PgConnection;
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::config::verify;
|
||||
use crate::lib::errors::ServiceError;
|
||||
use crate::models::{Pool, SlimUser, User};
|
||||
use crate::utils::errors::ServiceError;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct Data {
|
||||
@@ -76,7 +79,8 @@ pub async fn login(
|
||||
session: Session,
|
||||
pool: web::Data<Pool>,
|
||||
) -> Result<HttpResponse, actix_web::Error> {
|
||||
let user = web::block(move || query(&auth_data.into_inner(), &pool)).await??;
|
||||
let user =
|
||||
web::block(move || query(&auth_data.into_inner(), &pool)).await??;
|
||||
let user_string = serde_json::to_string(&user).unwrap();
|
||||
id.remember(user_string);
|
||||
session.insert("user_email", user.email)?;
|
||||
@@ -94,9 +98,12 @@ pub async fn logout(id: Identity, session: Session) -> HttpResponse {
|
||||
.finish()
|
||||
}
|
||||
|
||||
fn query(auth_data: &Data, pool: &web::Data<Pool>) -> Result<SlimUser, ServiceError> {
|
||||
fn query(
|
||||
auth_data: &Data,
|
||||
pool: &web::Data<Pool>,
|
||||
) -> Result<SlimUser, ServiceError> {
|
||||
use crate::schema::users::dsl::{email, users};
|
||||
let conn: &PgConnection = &pool.get().unwrap();
|
||||
let conn: &mut PgConnection = &mut pool.get().unwrap();
|
||||
let mut items = users
|
||||
.filter(email.eq(&auth_data.email))
|
||||
.load::<User>(conn)?;
|
||||
|
@@ -3,6 +3,7 @@
|
||||
|
||||
Copyright (c) 2022 - Artix Linux
|
||||
Copyright (c) 2022 - Oscar Campos <damnwidget@artixlinux.org>
|
||||
Copyright (c) 2022 - Nikola Radojević <nikolar@artixlinux.org>
|
||||
*/
|
||||
|
||||
#![allow(clippy::unused_async, clippy::module_name_repetitions)]
|
||||
@@ -38,11 +39,12 @@ pub async fn package_details(
|
||||
pool: web::Data<Pool>,
|
||||
) -> Result<HttpResponse> {
|
||||
let start_time = std::time::Instant::now();
|
||||
let user_email = if let Some(email) = session.get::<String>("user_email").unwrap() {
|
||||
email
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let user_email =
|
||||
if let Some(email) = session.get::<String>("user_email").unwrap() {
|
||||
email
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
let s = if let Ok(details) = get_packages_details_inner(&data, pool).await {
|
||||
PackageDetailsTemplate {
|
||||
@@ -89,10 +91,12 @@ mod filters {
|
||||
|
||||
#[allow(clippy::trivially_copy_pass_by_ref)]
|
||||
pub fn show_date(timestamp: &i64) -> ::askama::Result<NaiveDateTime> {
|
||||
Ok(NaiveDateTime::from_timestamp(*timestamp, 0))
|
||||
Ok(NaiveDateTime::from_timestamp_opt(*timestamp, 0).unwrap())
|
||||
}
|
||||
|
||||
pub(crate) fn provides_or_replaces(deps: &[Dependency]) -> ::askama::Result<String> {
|
||||
pub(crate) fn provides_or_replaces(
|
||||
deps: &[Dependency],
|
||||
) -> ::askama::Result<String> {
|
||||
let mut elements = Vec::new();
|
||||
elements.extend(
|
||||
deps.iter()
|
||||
|
@@ -23,7 +23,6 @@ use super::packages::{get_packages_inner, Response};
|
||||
#[template(path = "base_index.html")]
|
||||
struct BaseTemplate {
|
||||
packages: Vec<Response>,
|
||||
repos: Vec<String>,
|
||||
limit: usize,
|
||||
query: String,
|
||||
user_email: String,
|
||||
@@ -34,7 +33,6 @@ struct BaseTemplate {
|
||||
#[template(path = "packages_nav.html")]
|
||||
struct PackagesNavigation {
|
||||
packages: Vec<Response>,
|
||||
repos: Vec<String>,
|
||||
total: usize,
|
||||
offset: usize,
|
||||
limit: usize,
|
||||
@@ -64,16 +62,7 @@ pub async fn index(
|
||||
String::new()
|
||||
};
|
||||
|
||||
let valid_repos = vec![
|
||||
"system",
|
||||
"world",
|
||||
"galaxy",
|
||||
"lib32",
|
||||
"system-gremlins",
|
||||
"world-gremlins",
|
||||
"galaxy-gremlins",
|
||||
"lib32-gremlins"
|
||||
];
|
||||
let valid_repos = vec!["world", "galaxy", "system", "universe", "lib32"];
|
||||
for parameter in query.0 {
|
||||
let key: &str = ¶meter.0;
|
||||
match key {
|
||||
@@ -127,7 +116,6 @@ pub async fn index(
|
||||
PackagesNavigation {
|
||||
user_email,
|
||||
packages: result.0,
|
||||
repos,
|
||||
total: result.1,
|
||||
query: query_url.join("&"),
|
||||
total_pages: if limit > 0 {
|
||||
@@ -152,8 +140,8 @@ pub async fn index(
|
||||
|
||||
#[allow(clippy::unnecessary_wraps)]
|
||||
mod filters {
|
||||
pub fn selected_repo(repos: &Vec<String>, repo: &str) -> ::askama::Result<bool> {
|
||||
Ok(repos.iter().any(|r| r == repo))
|
||||
pub fn selected_repo(query: &str, repo: &str) -> ::askama::Result<bool> {
|
||||
Ok(query.to_lowercase().contains(&repo.to_lowercase()))
|
||||
}
|
||||
|
||||
pub fn details_url(pkg_name: &str) -> ::askama::Result<String> {
|
||||
|
@@ -3,18 +3,23 @@
|
||||
|
||||
Copyright (c) 2022 - Artix Linux
|
||||
Copyright (c) 2022 - Oscar Campos <damnwidget@artixlinux.org>
|
||||
Copyright (c) 2022 - Nikola Radojević <nikolar@artixlinux.org>
|
||||
*/
|
||||
|
||||
use actix_web::{web, HttpResponse};
|
||||
use askama::Template;
|
||||
use diesel::{prelude::*, PgConnection};
|
||||
use lettre::{transport::smtp::authentication::Credentials, Message, SmtpTransport, Transport};
|
||||
use lettre::{
|
||||
transport::smtp::authentication::Credentials, Message, SmtpTransport,
|
||||
Transport,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::utils;
|
||||
use crate::{
|
||||
config::{SmtpOptions, SETTINGS},
|
||||
lib::templates::EmailTemplate,
|
||||
models::{Invitation, Pool},
|
||||
utils::templates::EmailTemplate,
|
||||
};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
@@ -31,7 +36,11 @@ pub async fn post(
|
||||
if let Some(token) = req.headers().get("x-admin-token") {
|
||||
if token == &SETTINGS.api_token {
|
||||
web::block(move || {
|
||||
create_invitation(invitation_data.into_inner().email, &pool, &smtp_cfg)
|
||||
create_invitation(
|
||||
invitation_data.into_inner().email,
|
||||
&pool,
|
||||
&smtp_cfg,
|
||||
)
|
||||
})
|
||||
.await??;
|
||||
Ok(HttpResponse::Ok().finish())
|
||||
@@ -47,7 +56,7 @@ fn create_invitation(
|
||||
eml: String,
|
||||
pool: &web::Data<Pool>,
|
||||
smtp_cfg: &web::Data<SmtpOptions>,
|
||||
) -> Result<(), crate::lib::errors::ServiceError> {
|
||||
) -> Result<(), utils::errors::ServiceError> {
|
||||
let invitation = query(eml, pool)?;
|
||||
if let Err(err) = send_invitation(&invitation, smtp_cfg) {
|
||||
dbg!(err);
|
||||
@@ -59,7 +68,7 @@ fn create_invitation(
|
||||
fn send_invitation(
|
||||
invitation: &Invitation,
|
||||
smtp_cfg: &web::Data<SmtpOptions>,
|
||||
) -> Result<(), crate::lib::errors::ServiceError> {
|
||||
) -> Result<(), utils::errors::ServiceError> {
|
||||
let email = Message::builder()
|
||||
.from(
|
||||
"ArtixWeb Packages <artixweb@artixlinux.org>"
|
||||
@@ -71,8 +80,11 @@ fn send_invitation(
|
||||
.body(EmailTemplate { invitation }.render().unwrap())
|
||||
.unwrap();
|
||||
|
||||
let smtp_credentials = Credentials::new(smtp_cfg.user.clone(), smtp_cfg.password.clone());
|
||||
let mailer = if let Ok(transport) = SmtpTransport::starttls_relay(&smtp_cfg.relay.clone()) {
|
||||
let smtp_credentials =
|
||||
Credentials::new(smtp_cfg.user.clone(), smtp_cfg.password.clone());
|
||||
let mailer = if let Ok(transport) =
|
||||
SmtpTransport::starttls_relay(&smtp_cfg.relay.clone())
|
||||
{
|
||||
transport.credentials(smtp_credentials).build()
|
||||
} else {
|
||||
// open a local connection on port 25
|
||||
@@ -84,7 +96,7 @@ fn send_invitation(
|
||||
Ok(_) => Ok(()),
|
||||
Err(e) => {
|
||||
log::error!("{}", e);
|
||||
Err(crate::lib::errors::ServiceError::InternalServerError)
|
||||
Err(utils::errors::ServiceError::InternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -93,11 +105,11 @@ fn send_invitation(
|
||||
fn query(
|
||||
eml: String,
|
||||
pool: &web::Data<Pool>,
|
||||
) -> Result<Invitation, crate::lib::errors::ServiceError> {
|
||||
) -> Result<Invitation, utils::errors::ServiceError> {
|
||||
use crate::schema::invitations::dsl::invitations;
|
||||
|
||||
let new_invitation: Invitation = eml.into();
|
||||
let conn: &PgConnection = &pool.get().unwrap();
|
||||
let conn: &mut PgConnection = &mut pool.get().unwrap();
|
||||
|
||||
let inserted_invitation = diesel::insert_into(invitations)
|
||||
.values(&new_invitation)
|
||||
|
@@ -3,6 +3,7 @@
|
||||
|
||||
Copyright (c) 2022 - Artix Linux
|
||||
Copyright (c) 2022 - Oscar Campos <damnwidget@artixlinux.org>
|
||||
Copyright (c) 2022 - Nikola Radojević <nikolar@artixlinux.org>
|
||||
*/
|
||||
|
||||
//! Packages route handlers definitions
|
||||
@@ -20,20 +21,24 @@ use askama::Template;
|
||||
use chrono::prelude::NaiveDateTime;
|
||||
use diesel::prelude::*;
|
||||
use diesel::PgConnection;
|
||||
use lettre::{transport::smtp::authentication::Credentials, Message, SmtpTransport, Transport};
|
||||
use lettre::{
|
||||
transport::smtp::authentication::Credentials, Message, SmtpTransport,
|
||||
Transport,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::config::SmtpOptions;
|
||||
use crate::models::PackageWithFlagView;
|
||||
use crate::models::{Package as PackageMeta, PrivatePackage};
|
||||
use crate::utils;
|
||||
use crate::{
|
||||
config::{sync_databases, SETTINGS},
|
||||
lib::{
|
||||
models::{PackageFlag, Pool},
|
||||
utils::{
|
||||
database::packages,
|
||||
errors::{ArtixWebPackageError, ServiceError},
|
||||
templates::PackageFlagEmail,
|
||||
},
|
||||
models::{PackageFlag, Pool},
|
||||
};
|
||||
|
||||
use super::auth::LoggedUser;
|
||||
@@ -169,7 +174,11 @@ pub async fn flag_package(
|
||||
let user_name = logged_user.email.clone();
|
||||
let package_doublet = format!("{}-{}", data.0, data.1);
|
||||
web::block(move || {
|
||||
flag_package_query(&format!("{}-{}", data.0, data.1), &logged_user.email, &pool)
|
||||
flag_package_query(
|
||||
&format!("{}-{}", data.0, data.1),
|
||||
&logged_user.email,
|
||||
&pool,
|
||||
)
|
||||
})
|
||||
.await??;
|
||||
|
||||
@@ -195,8 +204,11 @@ pub async fn flag_package(
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let smtp_credentials = Credentials::new(smtp_cfg.user.clone(), smtp_cfg.password.clone());
|
||||
let mailer = if let Ok(transport) = SmtpTransport::starttls_relay(&smtp_cfg.relay.clone()) {
|
||||
let smtp_credentials =
|
||||
Credentials::new(smtp_cfg.user.clone(), smtp_cfg.password.clone());
|
||||
let mailer = if let Ok(transport) =
|
||||
SmtpTransport::starttls_relay(&smtp_cfg.relay.clone())
|
||||
{
|
||||
transport.credentials(smtp_credentials).build()
|
||||
} else {
|
||||
// open a local connection on port 25
|
||||
@@ -208,7 +220,7 @@ pub async fn flag_package(
|
||||
Ok(_) => Ok(HttpResponse::Ok().finish()),
|
||||
Err(e) => {
|
||||
log::error!("{}", e);
|
||||
Err(crate::lib::errors::ServiceError::BadRequest(
|
||||
Err(utils::errors::ServiceError::BadRequest(
|
||||
format!("could not send email: {:?}", e),
|
||||
Some(start_time),
|
||||
)
|
||||
@@ -236,7 +248,9 @@ pub async fn flag_package_delete(
|
||||
}
|
||||
}
|
||||
|
||||
if let Ok(result) = web::block(move || flag_package_delete_query(&package_doublet, &pool)).await
|
||||
if let Ok(result) =
|
||||
web::block(move || flag_package_delete_query(&package_doublet, &pool))
|
||||
.await
|
||||
{
|
||||
match result {
|
||||
Ok(_) => HttpResponse::Ok().finish(),
|
||||
@@ -251,11 +265,12 @@ pub async fn flag_package_delete(
|
||||
fn flag_package_delete_query(
|
||||
package_doublet: &str,
|
||||
pool: &web::Data<Pool>,
|
||||
) -> Result<(), crate::lib::errors::ServiceError> {
|
||||
) -> Result<(), utils::errors::ServiceError> {
|
||||
use crate::schema::package_flags::dsl::{package_flags, package_name};
|
||||
|
||||
let conn: &PgConnection = &pool.get().unwrap();
|
||||
diesel::delete(package_flags.filter(package_name.eq(package_doublet))).execute(conn)?;
|
||||
let conn: &mut PgConnection = &mut pool.get().unwrap();
|
||||
diesel::delete(package_flags.filter(package_name.eq(package_doublet)))
|
||||
.execute(conn)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -264,11 +279,11 @@ fn flag_package_query(
|
||||
package_doublet: &str,
|
||||
email: &str,
|
||||
pool: &web::Data<Pool>,
|
||||
) -> Result<(), crate::lib::errors::ServiceError> {
|
||||
) -> Result<(), utils::errors::ServiceError> {
|
||||
use crate::schema::package_flags::dsl::package_flags;
|
||||
|
||||
let pf = PackageFlag::from_details(email, package_doublet);
|
||||
let conn: &PgConnection = &pool.get().unwrap();
|
||||
let conn: &mut PgConnection = &mut pool.get().unwrap();
|
||||
diesel::insert_into(package_flags)
|
||||
.values(&pf)
|
||||
.execute(conn)?;
|
||||
@@ -310,7 +325,10 @@ pub async fn flags_package_ui(
|
||||
// the user has already flag this package_name (plus version)
|
||||
return Ok(HttpResponse::Ok().content_type("text/html").body(
|
||||
PackageAlreadyFlaggedTemplate {
|
||||
error_message: format!("You have already flag package {}", package_doublet),
|
||||
error_message: format!(
|
||||
"You have already flag package {}",
|
||||
package_doublet
|
||||
),
|
||||
user_email: logged_user.email,
|
||||
generation_time: start_time.elapsed().as_millis(),
|
||||
}
|
||||
@@ -367,10 +385,12 @@ fn get_package_flags_query(
|
||||
email: &str,
|
||||
pool: &web::Data<Pool>,
|
||||
start_time: std::time::Instant,
|
||||
) -> Result<bool, crate::lib::errors::ServiceError> {
|
||||
use crate::schema::package_flags::dsl::{package_flags, package_name, user_email};
|
||||
) -> Result<bool, utils::errors::ServiceError> {
|
||||
use crate::schema::package_flags::dsl::{
|
||||
package_flags, package_name, user_email,
|
||||
};
|
||||
|
||||
let conn: &PgConnection = &pool.get().unwrap();
|
||||
let conn: &mut PgConnection = &mut pool.get().unwrap();
|
||||
package_flags
|
||||
.filter(package_name.eq_all(pkg_id))
|
||||
.filter(user_email.eq_all(email))
|
||||
@@ -398,7 +418,9 @@ fn get_package_flags_query(
|
||||
pub async fn get_packages<'a>(
|
||||
data: web::Path<(String, usize, usize)>,
|
||||
) -> Result<HttpResponse, ArtixWebPackageError> {
|
||||
if let Ok(result) = get_packages_inner(&data.0, data.1, data.2, None, None).await {
|
||||
if let Ok(result) =
|
||||
get_packages_inner(&data.0, data.1, data.2, None, None).await
|
||||
{
|
||||
return Ok(HttpResponse::Ok()
|
||||
.content_type("application/json; charset=utf-8")
|
||||
.insert_header(("X-Packages-Number", result.0.len()))
|
||||
@@ -513,8 +535,10 @@ pub(crate) async fn get_packages_details_inner(
|
||||
|
||||
let pkg_name_version = format!("{}-{}", pkg.name(), pkg.version());
|
||||
let p_pool = pool.clone();
|
||||
if let Ok(Ok(metadata)) =
|
||||
web::block(move || get_package_metadata(&pkg_name_version, &pool)).await
|
||||
if let Ok(Ok(metadata)) = web::block(move || {
|
||||
get_package_metadata(&pkg_name_version, &pool)
|
||||
})
|
||||
.await
|
||||
{
|
||||
result.last_updated = metadata.last_update.timestamp();
|
||||
result.gitea_url = metadata.gitea_url;
|
||||
@@ -531,9 +555,12 @@ pub(crate) async fn get_packages_details_inner(
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
// retrieve a valid organization name for gitea packages
|
||||
let org_name = get_org_name(&pkg);
|
||||
|
||||
// look for this package in gitea
|
||||
if let Some(gitea_repo) = Repository::retrieve_repository(
|
||||
&String::from("packages"),
|
||||
&org_name,
|
||||
package_name,
|
||||
Some(&SETTINGS.gitea_api_url),
|
||||
)
|
||||
@@ -547,7 +574,11 @@ pub(crate) async fn get_packages_details_inner(
|
||||
let metadata = PackageMeta {
|
||||
package_name: format!("{}-{}", pkg.name(), pkg.version()),
|
||||
gitea_url: result.gitea_url.clone(),
|
||||
last_update: chrono::NaiveDateTime::from_timestamp(result.last_updated, 0),
|
||||
last_update: chrono::NaiveDateTime::from_timestamp_opt(
|
||||
result.last_updated,
|
||||
0,
|
||||
)
|
||||
.unwrap(),
|
||||
};
|
||||
if web::block(move || add_package_metadata(&metadata, &p_pool))
|
||||
.await
|
||||
@@ -570,8 +601,10 @@ pub(crate) async fn get_packages_details_inner(
|
||||
fn add_package_metadata(metadata: &PackageMeta, pool: &web::Data<Pool>) {
|
||||
use crate::schema::packages::dsl::packages;
|
||||
|
||||
let conn: &PgConnection = &pool.get().unwrap();
|
||||
if let Err(err) = diesel::insert_into(packages).values(metadata).execute(conn) {
|
||||
let conn: &mut PgConnection = &mut pool.get().unwrap();
|
||||
if let Err(err) =
|
||||
diesel::insert_into(packages).values(metadata).execute(conn)
|
||||
{
|
||||
dbg!(err.to_string());
|
||||
}
|
||||
}
|
||||
@@ -580,31 +613,34 @@ fn add_package_metadata(metadata: &PackageMeta, pool: &web::Data<Pool>) {
|
||||
fn get_package_metadata<'a>(
|
||||
pkg_doublet: &'a str,
|
||||
pool: &'a web::Data<Pool>,
|
||||
) -> Result<PrivatePackage, crate::lib::errors::ServiceError> {
|
||||
) -> Result<PrivatePackage, utils::errors::ServiceError> {
|
||||
use crate::schema::{package_flags, packages};
|
||||
|
||||
let start_time = std::time::Instant::now();
|
||||
let conn: &PgConnection = &pool.get().unwrap();
|
||||
let metadata: Vec<(PackageMeta, Option<chrono::NaiveDateTime>, Option<String>)> =
|
||||
packages::table
|
||||
.find(pkg_doublet)
|
||||
.left_join(
|
||||
package_flags::table.on(package_flags::package_name
|
||||
.eq(packages::package_name)
|
||||
.and(package_flags::flag_on.ge(packages::last_update))),
|
||||
let conn: &mut PgConnection = &mut pool.get().unwrap();
|
||||
let metadata: Vec<(
|
||||
PackageMeta,
|
||||
Option<chrono::NaiveDateTime>,
|
||||
Option<String>,
|
||||
)> = packages::table
|
||||
.find(pkg_doublet)
|
||||
.left_join(
|
||||
package_flags::table.on(package_flags::package_name
|
||||
.eq(packages::package_name)
|
||||
.and(package_flags::flag_on.ge(packages::last_update))),
|
||||
)
|
||||
.select((
|
||||
packages::all_columns,
|
||||
package_flags::flag_on.nullable(),
|
||||
package_flags::user_email.nullable(),
|
||||
))
|
||||
.load(conn)
|
||||
.map_err(|_db_error| {
|
||||
ServiceError::BadRequest(
|
||||
format!("Could not find package {}", pkg_doublet),
|
||||
Some(start_time),
|
||||
)
|
||||
.select((
|
||||
packages::all_columns,
|
||||
package_flags::flag_on.nullable(),
|
||||
package_flags::user_email.nullable(),
|
||||
))
|
||||
.load(conn)
|
||||
.map_err(|_db_error| {
|
||||
ServiceError::BadRequest(
|
||||
format!("Could not find package {}", pkg_doublet),
|
||||
Some(start_time),
|
||||
)
|
||||
})?;
|
||||
})?;
|
||||
|
||||
if let Some(user_metadata) = metadata.first() {
|
||||
let flaggers = metadata.iter().map(|meta| meta.2.clone()).collect();
|
||||
@@ -618,6 +654,33 @@ fn get_package_metadata<'a>(
|
||||
}
|
||||
}
|
||||
|
||||
// retrieves a valid (hopefully) organization name from a package name or base
|
||||
fn get_org_name(pkg: &Package<'_>) -> String {
|
||||
let mut pkg_name = pkg.name();
|
||||
let mut org_name = if let Some(base) = pkg.base() {
|
||||
pkg_name = base;
|
||||
format!(
|
||||
"packages{}",
|
||||
base.to_uppercase().chars().next().unwrap_or('_')
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"packages{}",
|
||||
pkg_name.to_uppercase().chars().next().unwrap_or('_')
|
||||
)
|
||||
};
|
||||
|
||||
if pkg_name.starts_with("python-") {
|
||||
org_name = String::from("packagesPython");
|
||||
} else if pkg.name().starts_with("perl-") {
|
||||
org_name = String::from("packagesPerl");
|
||||
} else if pkg.name().starts_with("ruby-") {
|
||||
org_name = String::from("packagesRuby");
|
||||
}
|
||||
|
||||
org_name
|
||||
}
|
||||
|
||||
pub(crate) async fn get_packages_inner(
|
||||
repo_names: &str,
|
||||
limit: usize,
|
||||
@@ -649,7 +712,9 @@ pub(crate) async fn get_packages_inner(
|
||||
let pkgs = pkgs.unwrap();
|
||||
|
||||
let flagged_packages = if let Some(pool) = pool {
|
||||
if let Ok(flagged_packages) = get_flagged_packages(start_time, pool).await {
|
||||
if let Ok(flagged_packages) =
|
||||
get_flagged_packages(start_time, pool).await
|
||||
{
|
||||
flagged_packages
|
||||
} else {
|
||||
Vec::new()
|
||||
@@ -677,7 +742,11 @@ pub(crate) async fn get_packages_inner(
|
||||
},
|
||||
package_name: pkg.name().to_string(),
|
||||
version: pkg.version().as_str().to_string(),
|
||||
last_update: NaiveDateTime::from_timestamp(pkg.build_date(), 0),
|
||||
last_update: NaiveDateTime::from_timestamp_opt(
|
||||
pkg.build_date(),
|
||||
0,
|
||||
)
|
||||
.unwrap(),
|
||||
description: String::from(pkg.desc().unwrap_or_default()),
|
||||
flag_on,
|
||||
flagged,
|
||||
@@ -697,24 +766,28 @@ pub(crate) async fn get_packages_inner(
|
||||
async fn get_flagged_packages(
|
||||
start_time: std::time::Instant,
|
||||
pool: &web::Data<Pool>,
|
||||
) -> Result<Vec<PackageWithFlagView>, crate::lib::errors::ServiceError> {
|
||||
) -> Result<Vec<PackageWithFlagView>, utils::errors::ServiceError> {
|
||||
use crate::schema::package_flags::dsl::{
|
||||
flag_on, package_flags, package_name as package_flag_name,
|
||||
};
|
||||
use crate::schema::packages::dsl::{last_update, package_name, packages};
|
||||
|
||||
let conn: &PgConnection = &pool.get().unwrap();
|
||||
let packages_data: Vec<(PackageMeta, Option<chrono::NaiveDateTime>)> = packages
|
||||
.inner_join(
|
||||
package_flags.on(flag_on
|
||||
.ge(last_update)
|
||||
.and(package_name.eq(package_flag_name))),
|
||||
)
|
||||
.select((packages::all_columns(), flag_on.nullable()))
|
||||
.load(conn)
|
||||
.map_err(|_db_error| {
|
||||
ServiceError::BadRequest(String::from("Could not find packages"), Some(start_time))
|
||||
})?;
|
||||
let conn: &mut PgConnection = &mut pool.get().unwrap();
|
||||
let packages_data: Vec<(PackageMeta, Option<chrono::NaiveDateTime>)> =
|
||||
packages
|
||||
.inner_join(
|
||||
package_flags.on(flag_on
|
||||
.ge(last_update)
|
||||
.and(package_name.eq(package_flag_name))),
|
||||
)
|
||||
.select((packages::all_columns(), flag_on.nullable()))
|
||||
.load(conn)
|
||||
.map_err(|_db_error| {
|
||||
ServiceError::BadRequest(
|
||||
String::from("Could not find packages"),
|
||||
Some(start_time),
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(packages_data
|
||||
.iter()
|
||||
@@ -734,7 +807,8 @@ async fn retrieve_maintainers(gitea_repo: &Repository) -> Vec<String> {
|
||||
for line in lines {
|
||||
let lower = line.to_lowercase();
|
||||
if lower.contains("maintainer") || lower.contains("contributor") {
|
||||
let data: Vec<String> = line.split(':').map(|m| m.trim().to_string()).collect();
|
||||
let data: Vec<String> =
|
||||
line.split(':').map(|m| m.trim().to_string()).collect();
|
||||
if data.len() > 1 {
|
||||
maintainers.push(data[1].clone());
|
||||
}
|
||||
@@ -752,7 +826,7 @@ async fn retrieve_maintainers(gitea_repo: &Repository) -> Vec<String> {
|
||||
fn get_depends_from_package<'a>(
|
||||
alpm: &'a Alpm,
|
||||
arch: &str,
|
||||
deps: AlpmList<'_, &Dep>,
|
||||
deps: AlpmList<'_, Dep<'_>>,
|
||||
kind: &DependencyKind,
|
||||
) -> Vec<Dependency> {
|
||||
match kind {
|
||||
@@ -778,7 +852,7 @@ fn get_depends_from_package<'a>(
|
||||
|
||||
// constructs a Dependency instance with the given data and returns it back
|
||||
#[allow(clippy::needless_pass_by_value)]
|
||||
fn construct_dependency(arch: &str, alpm: &Alpm, dep: &Dep) -> Dependency {
|
||||
fn construct_dependency(arch: &str, alpm: &Alpm, dep: Dep<'_>) -> Dependency {
|
||||
let kind = if dep
|
||||
.name()
|
||||
.rsplit('.')
|
||||
@@ -791,25 +865,33 @@ fn construct_dependency(arch: &str, alpm: &Alpm, dep: &Dep) -> Dependency {
|
||||
DependencyKind::Depend
|
||||
};
|
||||
|
||||
common_dependency_data(arch, alpm, dep, kind)
|
||||
common_dependency_data(arch, alpm, &dep, kind)
|
||||
}
|
||||
|
||||
// constructs a (make) Dependency instance with the given data and return it back
|
||||
#[allow(clippy::needless_pass_by_value)]
|
||||
fn construct_make_dependency(arch: &str, alpm: &Alpm, dep: &Dep) -> Dependency {
|
||||
common_dependency_data(arch, alpm, dep, DependencyKind::Make)
|
||||
fn construct_make_dependency(
|
||||
arch: &str,
|
||||
alpm: &Alpm,
|
||||
dep: Dep<'_>,
|
||||
) -> Dependency {
|
||||
common_dependency_data(arch, alpm, &dep, DependencyKind::Make)
|
||||
}
|
||||
|
||||
// constructs a (opt) Dependency instance with the given data and return it back
|
||||
#[allow(clippy::needless_pass_by_value)]
|
||||
fn construct_opt_dependency(arch: &str, alpm: &Alpm, dep: &Dep) -> Dependency {
|
||||
common_dependency_data(arch, alpm, dep, DependencyKind::Opt)
|
||||
fn construct_opt_dependency(
|
||||
arch: &str,
|
||||
alpm: &Alpm,
|
||||
dep: Dep<'_>,
|
||||
) -> Dependency {
|
||||
common_dependency_data(arch, alpm, &dep, DependencyKind::Opt)
|
||||
}
|
||||
|
||||
fn common_dependency_data<'a>(
|
||||
arch: &str,
|
||||
alpm: &'a Alpm,
|
||||
dep: &Dep,
|
||||
dep: &Dep<'_>,
|
||||
kind: DependencyKind,
|
||||
) -> Dependency {
|
||||
let ver = if let Some(ver) = dep.version() {
|
||||
|
@@ -3,6 +3,7 @@
|
||||
|
||||
Copyright (c) 2022 - Artix Linux
|
||||
Copyright (c) 2022 - Oscar Campos <damnwidget@artixlinux.org>
|
||||
Copyright (c) 2022 - Nikola Radojević <nikolar@artixlinux.org>
|
||||
*/
|
||||
|
||||
use actix_session::Session;
|
||||
@@ -13,8 +14,9 @@ use diesel::PgConnection;
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::config::{check_password_strength, hash_password};
|
||||
use crate::lib::errors::ServiceError;
|
||||
use crate::models::{Invitation, Pool, SlimUser, User};
|
||||
use crate::utils;
|
||||
use crate::utils::errors::ServiceError;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct UserData {
|
||||
@@ -93,17 +95,20 @@ pub async fn invitation(
|
||||
fn check_invitation(
|
||||
invitation_id: &str,
|
||||
pool: &web::Data<Pool>,
|
||||
) -> Result<bool, crate::lib::errors::ServiceError> {
|
||||
) -> Result<bool, utils::errors::ServiceError> {
|
||||
use crate::schema::invitations::dsl::{id, invitations};
|
||||
|
||||
let invitation_id = uuid::Uuid::parse_str(invitation_id)?;
|
||||
let conn: &PgConnection = &pool.get().unwrap();
|
||||
let conn: &mut PgConnection = &mut pool.get().unwrap();
|
||||
|
||||
let inv = invitations
|
||||
.filter(id.eq(invitation_id))
|
||||
.load::<Invitation>(conn)
|
||||
.map_err(|_db_error| {
|
||||
ServiceError::BadRequest("Invalid or expired Invitation".into(), None)
|
||||
ServiceError::BadRequest(
|
||||
"Invalid or expired Invitation".into(),
|
||||
None,
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(!inv.is_empty())
|
||||
@@ -141,7 +146,8 @@ pub async fn new_user(
|
||||
}
|
||||
|
||||
// create user from the input data in the form
|
||||
web::block(move || query(&invitation_id.into_inner(), &password, &pool)).await??;
|
||||
web::block(move || query(&invitation_id.into_inner(), &password, &pool))
|
||||
.await??;
|
||||
Ok(HttpResponse::SeeOther()
|
||||
.append_header((http::header::LOCATION, "/login"))
|
||||
.finish())
|
||||
@@ -151,13 +157,13 @@ fn query(
|
||||
invitation_id: &str,
|
||||
password: &str,
|
||||
pool: &web::Data<Pool>,
|
||||
) -> Result<SlimUser, crate::lib::errors::ServiceError> {
|
||||
) -> Result<SlimUser, utils::errors::ServiceError> {
|
||||
use crate::schema::invitations::dsl::{id, invitations};
|
||||
use crate::schema::users::dsl::users;
|
||||
|
||||
let start_time = std::time::Instant::now();
|
||||
let invitation_id = uuid::Uuid::parse_str(invitation_id)?;
|
||||
let conn: &PgConnection = &pool.get().unwrap();
|
||||
let conn: &mut PgConnection = &mut pool.get().unwrap();
|
||||
invitations
|
||||
.filter(id.eq(invitation_id))
|
||||
.load::<Invitation>(conn)
|
||||
@@ -175,8 +181,9 @@ fn query(
|
||||
let password = hash_password(password)?;
|
||||
|
||||
let user = User::from_details(invitation.email, password);
|
||||
let inserted_user: User =
|
||||
diesel::insert_into(users).values(&user).get_result(conn)?;
|
||||
let inserted_user: User = diesel::insert_into(users)
|
||||
.values(&user)
|
||||
.get_result(conn)?;
|
||||
|
||||
return Ok(inserted_user.into());
|
||||
}
|
||||
|
@@ -3,6 +3,7 @@
|
||||
|
||||
Copyright (c) 2022 - Artix Linux
|
||||
Copyright (c) 2022 - Oscar Campos <damnwidget@artixlinux.org>
|
||||
Copyright (c) 2023 - Nikola Radojević <nikolar@artixlinux.org>
|
||||
*/
|
||||
|
||||
//! This crate provides an HTTP API to work with Artix Packages
|
||||
@@ -20,10 +21,10 @@ extern crate diesel;
|
||||
|
||||
mod config;
|
||||
mod handlers;
|
||||
mod lib;
|
||||
mod models;
|
||||
mod routes;
|
||||
mod schema;
|
||||
mod utils;
|
||||
|
||||
use actix_identity::{CookieIdentityPolicy, IdentityService};
|
||||
use actix_session::{storage::CookieSessionStore, SessionMiddleware};
|
||||
@@ -38,6 +39,12 @@ use diesel::r2d2::ConnectionManager;
|
||||
use log::{debug, warn};
|
||||
use time::Duration;
|
||||
|
||||
const DEFAULT_BIND_ADDR: &'static str = "127.0.0.1";
|
||||
const DEFAULT_PORT_STR: &'static str = "1936";
|
||||
const DEFAULT_PORT: u16 = 1936;
|
||||
const DEFAULT_DB_URL: &'static str = "localhost";
|
||||
const DEFAULT_DOMAIN: &'static str = "localhost";
|
||||
|
||||
#[actix_web::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
// parse config
|
||||
@@ -45,20 +52,24 @@ async fn main() -> std::io::Result<()> {
|
||||
.arg(
|
||||
arg!(-b --bind <BIND_ADDRESS>)
|
||||
.required(false)
|
||||
.default_value("127.0.0.1")
|
||||
.default_value(DEFAULT_BIND_ADDR)
|
||||
.env("BIND_ADDRESS"),
|
||||
)
|
||||
.arg(arg!(-p --port <PORT>).required(false).default_value("1936"))
|
||||
.arg(
|
||||
arg!(-p --port <PORT>)
|
||||
.required(false)
|
||||
.default_value(DEFAULT_PORT_STR),
|
||||
)
|
||||
.arg(
|
||||
arg!(-u --databaseurl <DATABASE_URL>)
|
||||
.required(false)
|
||||
.default_value("localhost")
|
||||
.default_value(DEFAULT_DB_URL)
|
||||
.env("DATABASE_URL"),
|
||||
)
|
||||
.arg(
|
||||
arg!(-d --domain <DOMAIN>)
|
||||
.required(false)
|
||||
.default_value("localhost"),
|
||||
.default_value(DEFAULT_DOMAIN),
|
||||
)
|
||||
.arg(
|
||||
arg!(-k --key <SESSION_KEY>)
|
||||
@@ -79,38 +90,41 @@ async fn main() -> std::io::Result<()> {
|
||||
.arg(arg!(-v - -verbose ... ))
|
||||
.get_matches();
|
||||
|
||||
// count how many appearances of verbose we got and assign a value for env_logger
|
||||
let debug_level = match matches.occurrences_of("verbose") {
|
||||
// count how many appearances of verbose we got and assign a value
|
||||
// for env_logger
|
||||
let debug_level = match matches.get_count("verbose") {
|
||||
0 => "warn",
|
||||
1 => "info",
|
||||
_ => "debug",
|
||||
};
|
||||
|
||||
// configure logger
|
||||
env_logger::init_from_env(env_logger::Env::default().default_filter_or(debug_level));
|
||||
env_logger::init_from_env(
|
||||
env_logger::Env::default().default_filter_or(debug_level),
|
||||
);
|
||||
debug!("environment logger level set to 'debug'");
|
||||
|
||||
let host_addr = matches.value_of("bind").unwrap_or_default();
|
||||
let port = matches.value_of("port").unwrap_or_default();
|
||||
let host_addr = matches.get_one::<String>("bind").unwrap();
|
||||
let port = matches.get_one::<String>("port").unwrap();
|
||||
let host_port = if let Ok(n) = port.parse::<u16>() {
|
||||
n
|
||||
} else {
|
||||
warn!("could not parse {} host_port, defaulting to 1936", port);
|
||||
1936
|
||||
DEFAULT_PORT
|
||||
};
|
||||
|
||||
let database_url = matches.value_of("databaseurl").unwrap_or_default();
|
||||
let domain = matches.value_of("domain").unwrap_or_default();
|
||||
let master_key = matches.value_of("key").unwrap();
|
||||
let database_url = matches.get_one::<String>("databaseurl").unwrap();
|
||||
let domain = matches.get_one::<String>("domain").unwrap();
|
||||
let master_key = matches.get_one::<String>("key").unwrap();
|
||||
|
||||
let smtp_config = config::SmtpOptions {
|
||||
user: String::from(matches.value_of("smtp_user").unwrap_or_default()),
|
||||
password: String::from(matches.value_of("smtp_pwd").unwrap_or_default()),
|
||||
relay: String::from(matches.value_of("smtp_relay").unwrap_or_default()),
|
||||
user: String::from(matches.get_one::<String>("smtp_user").unwrap()),
|
||||
password: String::from(matches.get_one::<String>("smtp_pwd").unwrap()),
|
||||
relay: String::from(matches.get_one::<String>("smtp_relay").unwrap()),
|
||||
};
|
||||
|
||||
// start http server
|
||||
debug!("starting Artix web server on {}:{}", host_addr, host_port);
|
||||
debug!("Starting Artix web server on {}:{}", host_addr, host_port);
|
||||
start_web_server(
|
||||
host_addr,
|
||||
host_port,
|
||||
|
@@ -3,6 +3,7 @@
|
||||
|
||||
Copyright (c) 2022 - Artix Linux
|
||||
Copyright (c) 2022 - Oscar Campos <damnwidget@artixlinux.org>
|
||||
Copyright (c) 2022 - Nikola Radojević <nikolar@artixlinux.org>
|
||||
*/
|
||||
|
||||
use diesel::{r2d2::ConnectionManager, PgConnection};
|
||||
@@ -15,7 +16,7 @@ use super::schema::{invitations, package_flags, packages, users};
|
||||
pub type Pool = r2d2::Pool<ConnectionManager<PgConnection>>;
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Queryable, Insertable)]
|
||||
#[table_name = "packages"]
|
||||
#[diesel(table_name = packages)]
|
||||
pub struct Package {
|
||||
pub package_name: String,
|
||||
pub gitea_url: String,
|
||||
@@ -23,7 +24,10 @@ pub struct Package {
|
||||
}
|
||||
|
||||
impl Package {
|
||||
pub fn from_details<S: Into<String>, T: Into<String>>(name: S, url: T) -> Self {
|
||||
pub fn from_details<S: Into<String>, T: Into<String>>(
|
||||
name: S,
|
||||
url: T,
|
||||
) -> Self {
|
||||
Package {
|
||||
package_name: name.into(),
|
||||
gitea_url: url.into(),
|
||||
@@ -79,7 +83,7 @@ impl PackageWithFlagView {
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Queryable, Insertable)]
|
||||
#[table_name = "users"]
|
||||
#[diesel(table_name = users)]
|
||||
pub struct User {
|
||||
pub email: String,
|
||||
pub hash: String,
|
||||
@@ -88,7 +92,10 @@ pub struct User {
|
||||
}
|
||||
|
||||
impl User {
|
||||
pub fn from_details<S: Into<String>, T: Into<String>>(email: S, pwd: T) -> Self {
|
||||
pub fn from_details<S: Into<String>, T: Into<String>>(
|
||||
email: S,
|
||||
pwd: T,
|
||||
) -> Self {
|
||||
User {
|
||||
email: email.into(),
|
||||
hash: pwd.into(),
|
||||
@@ -99,7 +106,7 @@ impl User {
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Queryable, Insertable)]
|
||||
#[table_name = "invitations"]
|
||||
#[diesel(table_name = invitations)]
|
||||
pub(crate) struct Invitation {
|
||||
pub id: Uuid,
|
||||
pub email: String,
|
||||
@@ -115,13 +122,14 @@ where
|
||||
Invitation {
|
||||
id: uuid::Uuid::new_v4(),
|
||||
email: email.into(),
|
||||
expires_at: chrono::Local::now().naive_local() + chrono::Duration::hours(24),
|
||||
expires_at: chrono::Local::now().naive_local()
|
||||
+ chrono::Duration::hours(24),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Queryable, Insertable)]
|
||||
#[table_name = "package_flags"]
|
||||
#[diesel(table_name = package_flags)]
|
||||
pub struct PackageFlag {
|
||||
pub user_email: String,
|
||||
pub package_name: String,
|
||||
@@ -129,7 +137,10 @@ pub struct PackageFlag {
|
||||
}
|
||||
|
||||
impl PackageFlag {
|
||||
pub fn from_details<S: Into<String>, T: Into<String>>(user_email: S, package_name: T) -> Self {
|
||||
pub fn from_details<S: Into<String>, T: Into<String>>(
|
||||
user_email: S,
|
||||
package_name: T,
|
||||
) -> Self {
|
||||
PackageFlag {
|
||||
user_email: user_email.into(),
|
||||
package_name: package_name.into(),
|
||||
|
@@ -3,6 +3,7 @@
|
||||
|
||||
Copyright (c) 2022 - Artix Linux
|
||||
Copyright (c) 2022 - Oscar Campos <damnwidget@artixlinux.org>
|
||||
Copyright (c) 2022 - Nikola Radojević <nikolar@artixlinux.org>
|
||||
*/
|
||||
|
||||
use actix_files::Files;
|
||||
@@ -14,7 +15,10 @@ use crate::handlers::{auth, details, index, invitation, packages, register};
|
||||
pub fn config_app(cfg: &mut web::ServiceConfig) {
|
||||
cfg.service(
|
||||
web::scope("")
|
||||
.service(web::resource("/api/invitation").route(web::post().to(invitation::post)))
|
||||
.service(
|
||||
web::resource("/api/invitation")
|
||||
.route(web::post().to(invitation::post)),
|
||||
)
|
||||
.service(
|
||||
web::scope("/api/packages")
|
||||
.service(
|
||||
@@ -22,7 +26,9 @@ pub fn config_app(cfg: &mut web::ServiceConfig) {
|
||||
.route(web::get().to(packages::get_packages)),
|
||||
)
|
||||
.service(web::scope("/{package_name}").service(
|
||||
web::resource("").route(web::get().to(packages::get_package_details)),
|
||||
web::resource("").route(
|
||||
web::get().to(packages::get_package_details),
|
||||
),
|
||||
))
|
||||
.default_service(
|
||||
web::route()
|
||||
@@ -46,7 +52,9 @@ pub fn config_app(cfg: &mut web::ServiceConfig) {
|
||||
.route(web::delete().to(auth::logout))
|
||||
.route(web::get().to(auth::ui)),
|
||||
)
|
||||
.service(web::resource("/logout").route(web::post().to(auth::logout)))
|
||||
.service(
|
||||
web::resource("/logout").route(web::post().to(auth::logout)),
|
||||
)
|
||||
.service(
|
||||
web::resource("/flag_package/{package_name}/{package_version}")
|
||||
.route(web::post().to(packages::flag_package))
|
||||
|
@@ -3,11 +3,12 @@
|
||||
|
||||
Copyright (c) 2022 - Artix Linux
|
||||
Copyright (c) 2022 - Oscar Campos <damnwidget@artixlinux.org>
|
||||
Copyright (c) 2022 - Nikola Radojević <nikolar@artixlinux.org>
|
||||
*/
|
||||
|
||||
use artix_pkglib::prelude::{get_all_packages, Alpm, PackagesResultData};
|
||||
|
||||
use crate::lib::errors::ArtixWebPackageError;
|
||||
use crate::utils::errors::ArtixWebPackageError;
|
||||
|
||||
/// Retrieve all the packages in all the databases in the system
|
||||
/// If `limit` is used then the results are limited to its value
|
@@ -3,6 +3,7 @@
|
||||
|
||||
Copyright (c) 2022 - Artix Linux
|
||||
Copyright (c) 2022 - Oscar Campos <damnwidget@artixlinux.org>
|
||||
Copyright (c) 2022 - Nikola Radojević <nikolar@artixlinux.org>
|
||||
*/
|
||||
|
||||
use actix_web::{
|
||||
@@ -70,9 +71,11 @@ struct UnauthorizedTemplate {
|
||||
impl error::ResponseError for ServiceError {
|
||||
fn error_response(&self) -> HttpResponse {
|
||||
match self {
|
||||
ServiceError::InternalServerError => HttpResponse::InternalServerError()
|
||||
.reason("Internal Server Error, Please try later")
|
||||
.body("Internal Server Error, Please try later"),
|
||||
ServiceError::InternalServerError => {
|
||||
HttpResponse::InternalServerError()
|
||||
.reason("Internal Server Error, Please try later")
|
||||
.body("Internal Server Error, Please try later")
|
||||
}
|
||||
ServiceError::BadRequest(ref message, start_time) => {
|
||||
let t = if let Some(start_time) = start_time {
|
||||
start_time.elapsed().as_millis()
|
||||
@@ -90,15 +93,19 @@ impl error::ResponseError for ServiceError {
|
||||
.unwrap(),
|
||||
)
|
||||
}
|
||||
ServiceError::Unauthorized => HttpResponse::Unauthorized().reason("Unauthorized").body(
|
||||
UnauthorizedTemplate {
|
||||
user_email: String::new(),
|
||||
error_message: String::from("You are not authorized to access this resource"),
|
||||
generation_time: 0,
|
||||
}
|
||||
.render()
|
||||
.unwrap(),
|
||||
),
|
||||
ServiceError::Unauthorized => {
|
||||
HttpResponse::Unauthorized().reason("Unauthorized").body(
|
||||
UnauthorizedTemplate {
|
||||
user_email: String::new(),
|
||||
error_message: String::from(
|
||||
"You are not authorized to access this resource",
|
||||
),
|
||||
generation_time: 0,
|
||||
}
|
||||
.render()
|
||||
.unwrap(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -114,9 +121,15 @@ impl From<DBError> for ServiceError {
|
||||
match error {
|
||||
DBError::DatabaseError(kind, info) => {
|
||||
if let DatabaseErrorKind::UniqueViolation = kind {
|
||||
let mut message = info.details().unwrap_or_else(|| info.message()).to_string();
|
||||
let mut message = info
|
||||
.details()
|
||||
.unwrap_or_else(|| info.message())
|
||||
.to_string();
|
||||
if message.contains("Key (email)=") {
|
||||
message = format!("Can not register user, already exists: {}", message);
|
||||
message = format!(
|
||||
"Can not register user, already exists: {}",
|
||||
message
|
||||
);
|
||||
}
|
||||
return ServiceError::BadRequest(message, None);
|
||||
}
|
@@ -3,6 +3,7 @@
|
||||
|
||||
Copyright (c) 2022 - Artix Linux
|
||||
Copyright (c) 2022 - Oscar Campos <damnwidget@artixlinux.org>
|
||||
Copyright (c) 2022 - Nikola Radojević <nikolar@artixlinux.org>
|
||||
*/
|
||||
|
||||
//! `ArtixWeb` Packages Library.
|
@@ -3,6 +3,7 @@
|
||||
|
||||
Copyright (c) 2022 - Artix Linux
|
||||
Copyright (c) 2022 - Oscar Campos <damnwidget@artixlinux.org>
|
||||
Copyright (c) 2022 - Nikola Radojević <nikolar@artixlinux.org>
|
||||
*/
|
||||
|
||||
use askama::Template;
|
@@ -10,14 +10,11 @@
|
||||
<div>
|
||||
<label for="repo_name" title="Repositories to include in the search">Repositories</label>
|
||||
<select id="repo_name" name="repo" multiple="">
|
||||
<option value="system" {% if repos|selected_repo("system") %} selected {% endif %}>System</option>
|
||||
<option value="world" {% if repos|selected_repo("world") %} selected {% endif %}>World</option>
|
||||
<option value="galaxy" {% if repos|selected_repo("galaxy") %} selected {% endif %}>Galaxy</option>
|
||||
<option value="lib32" {% if repos|selected_repo("lib32") %} selected {% endif %}>Lib32</option>
|
||||
<option value="system-gremlins" {% if repos|selected_repo("system-gremlins") %} selected {% endif %}>System-Gremlins</option>
|
||||
<option value="world-gremlins" {% if repos|selected_repo("world-gremlins") %} selected {% endif %}>World-Gremlins</option>
|
||||
<option value="galaxy-gremlins" {% if repos|selected_repo("galaxy-gremlins") %} selected {% endif %}>Galaxy-Gremlins</option>
|
||||
<option value="lib32-gremlins" {% if repos|selected_repo("lib32-gremlins") %} selected {% endif %}>Lib32-Gremlins</option>
|
||||
<option value="World" {% if query|selected_repo("World") %} selected {% endif %}>World</option>
|
||||
<option value="Galaxy" {% if query|selected_repo("Galaxy") %} selected {% endif %}>Galaxy</option>
|
||||
<option value="System" {% if query|selected_repo("System") %} selected {% endif %}>System</option>
|
||||
<option value="Universe" {% if query|selected_repo("Universe") %} selected {% endif %}>Universe</option>
|
||||
<option value="Lib32" {% if query|selected_repo("Lib32") %} selected {% endif %}>Lib32</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
|
1
rustfmt.toml
Normal file
1
rustfmt.toml
Normal file
@@ -0,0 +1 @@
|
||||
max_width = 80
|
Reference in New Issue
Block a user