-
Notifications
You must be signed in to change notification settings - Fork 1
Magnet upload + resolution #44
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
angrynode
wants to merge
2
commits into
axum
Choose a base branch
from
magnet-form3
base: axum
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,185 @@ | ||
| use chrono::Utc; | ||
| use hightorrent_api::hightorrent::{MagnetLink, MagnetLinkError, TorrentFile, TorrentID}; | ||
| use sea_orm::entity::prelude::*; | ||
| use sea_orm::*; | ||
| use snafu::prelude::*; | ||
|
|
||
| use crate::database::operation::*; | ||
| use crate::extractors::user::User; | ||
| use crate::routes::magnet::MagnetForm; | ||
| use crate::state::AppState; | ||
| use crate::state::logger::LoggerError; | ||
|
|
||
| /// A category to store associated files. | ||
| /// | ||
| /// Each category has a name and an associated path on disk, where | ||
| /// symlinks to the content will be created. | ||
| #[sea_orm::model] | ||
| #[derive(Clone, Debug, PartialEq, DeriveEntityModel)] | ||
| #[sea_orm(table_name = "magnet")] | ||
| pub struct Model { | ||
| #[sea_orm(primary_key)] | ||
| pub id: i32, | ||
| pub torrent_id: TorrentID, | ||
| pub link: MagnetLink, | ||
| pub name: String, | ||
| pub resolved: Option<TorrentFile>, | ||
| } | ||
|
|
||
| #[async_trait::async_trait] | ||
| impl ActiveModelBehavior for ActiveModel {} | ||
|
|
||
| #[derive(Debug, Snafu)] | ||
| #[snafu(visibility(pub))] | ||
| pub enum MagnetError { | ||
| #[snafu(display("The magnet is invalid"))] | ||
| InvalidMagnet { source: MagnetLinkError }, | ||
| #[snafu(display("Database error"))] | ||
| DB { source: sea_orm::DbErr }, | ||
| #[snafu(display("The magnet (ID: {id}) does not exist"))] | ||
| NotFound { id: i32 }, | ||
| #[snafu(display("The magnet (TorrentID: {id}) does not exist"))] | ||
| NotFoundTorrentID { id: TorrentID }, | ||
| #[snafu(display("Failed to save the operation log"))] | ||
| Logger { source: LoggerError }, | ||
| } | ||
|
|
||
| #[derive(Clone, Debug)] | ||
| pub struct MagnetOperator { | ||
| pub state: AppState, | ||
| pub user: Option<User>, | ||
| } | ||
|
|
||
| impl MagnetOperator { | ||
| /// List magnets | ||
| /// | ||
| /// Should not fail, unless SQLite was corrupted for some reason. | ||
| pub async fn list(&self) -> Result<Vec<Model>, MagnetError> { | ||
| Entity::find() | ||
| .all(&self.state.database) | ||
| .await | ||
| .context(DBSnafu) | ||
| } | ||
|
|
||
| /// Count magnets | ||
| /// | ||
| /// Should not fail, unless SQLite was corrupted for some reason. | ||
| pub async fn count(&self) -> Result<usize, MagnetError> { | ||
| // TODO: there may be a faster sea_orm operation for this | ||
| Ok(self.list().await?.len()) | ||
| } | ||
|
|
||
| pub async fn get(&self, id: i32) -> Result<Model, MagnetError> { | ||
| let db = &self.state.database; | ||
|
|
||
| Entity::find_by_id(id) | ||
| .one(db) | ||
| .await | ||
| .context(DBSnafu)? | ||
| .ok_or(MagnetError::NotFound { id }) | ||
| } | ||
|
|
||
| pub async fn get_by_torrent_id(&self, id: &TorrentID) -> Result<Model, MagnetError> { | ||
| let db = &self.state.database; | ||
|
|
||
| Entity::find() | ||
| .filter(Column::TorrentId.eq(id.clone())) | ||
| .one(db) | ||
| .await | ||
| .context(DBSnafu)? | ||
| .ok_or(MagnetError::NotFoundTorrentID { id: id.clone() }) | ||
| } | ||
|
|
||
| /// Delete an uploaded magnet | ||
| pub async fn delete(&self, id: i32) -> Result<String, MagnetError> { | ||
| let db = &self.state.database; | ||
|
|
||
| let uploaded_magnet = Entity::find_by_id(id) | ||
| .one(db) | ||
| .await | ||
| .context(DBSnafu)? | ||
| .ok_or(MagnetError::NotFound { id })?; | ||
|
|
||
| let clone: Model = uploaded_magnet.clone(); | ||
| uploaded_magnet.delete(db).await.context(DBSnafu)?; | ||
|
|
||
| let operation_log = OperationLog { | ||
| user: self.user.clone(), | ||
| date: Utc::now(), | ||
| table: Table::Magnet, | ||
| operation: OperationType::Delete, | ||
| operation_id: OperationId { | ||
| object_id: clone.id, | ||
| name: clone.name.to_owned(), | ||
| }, | ||
| operation_form: None, | ||
| }; | ||
|
|
||
| self.state | ||
| .logger | ||
| .write(operation_log) | ||
| .await | ||
| .context(LoggerSnafu)?; | ||
|
|
||
| Ok(clone.name) | ||
| } | ||
|
|
||
| /// Create a new uploaded magnet | ||
| /// | ||
| /// Fails if: | ||
| /// | ||
| /// - the magnet is invalid | ||
| pub async fn create(&self, f: &MagnetForm) -> Result<Model, MagnetError> { | ||
| let magnet = MagnetLink::new(&f.magnet).context(InvalidMagnetSnafu)?; | ||
|
|
||
| // Check duplicates | ||
| let list = self.list().await?; | ||
|
|
||
| if list.iter().any(|x| x.torrent_id == magnet.id()) { | ||
| // The magnet is already known | ||
| return self.get_by_torrent_id(&magnet.id()).await; | ||
| } | ||
|
|
||
| let model = ActiveModel { | ||
| torrent_id: Set(magnet.id()), | ||
| link: Set(magnet.clone()), | ||
| name: Set(magnet.name().to_string()), | ||
| // TODO: check if we already have the torrent in which case it's already resolved! | ||
| resolved: Set(None), | ||
| ..Default::default() | ||
| } | ||
| .save(&self.state.database) | ||
| .await | ||
| .context(DBSnafu)?; | ||
|
|
||
| // Now that the magnet has been summoned into the DB, | ||
| // we should let the resolver know about it. | ||
| self.state | ||
| .resolver | ||
| .send(magnet.clone()) | ||
| .expect("resolver sender channel has been closed"); | ||
|
|
||
| // Should not fail | ||
| let model = model.try_into_model().unwrap(); | ||
|
|
||
| let operation_log = OperationLog { | ||
| user: self.user.clone(), | ||
| date: Utc::now(), | ||
| table: Table::Magnet, | ||
| operation: OperationType::Create, | ||
| operation_id: OperationId { | ||
| object_id: model.id.to_owned(), | ||
| name: model.name.to_string(), | ||
| }, | ||
| operation_form: Some(Operation::Magnet(f.clone())), | ||
| }; | ||
|
|
||
| self.state | ||
| .logger | ||
| .write(operation_log) | ||
| .await | ||
| .context(LoggerSnafu)?; | ||
|
|
||
| Ok(model) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| // sea_orm example: https://github.com/SeaQL/sea-orm/blob/master/examples/axum_example/ | ||
| pub mod category; | ||
| pub mod content_folder; | ||
| pub mod magnet; | ||
| pub mod operation; | ||
| pub mod operator; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| use sea_orm_migration::{prelude::*, schema::*}; | ||
|
|
||
| use crate::migration::m20251110_01_create_table_category::Category; | ||
| use crate::migration::m20251113_203047_add_content_folder::ContentFolder; | ||
|
|
||
| #[derive(DeriveMigrationName)] | ||
| pub struct Migration; | ||
|
|
||
| #[async_trait::async_trait] | ||
| impl MigrationTrait for Migration { | ||
| async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { | ||
| manager | ||
| .create_table( | ||
| Table::create() | ||
| .table(Magnet::Table) | ||
| .if_not_exists() | ||
| .col(pk_auto(Magnet::Id)) | ||
| .col(string(Magnet::TorrentID).unique_key()) | ||
| .col(string(Magnet::Name)) | ||
| .col(string(Magnet::Link)) | ||
| .col(var_binary(Magnet::Resolved, 0).null()) | ||
| .col(ColumnDef::new(Magnet::ContentFolderId).integer()) | ||
| .foreign_key( | ||
| ForeignKey::create() | ||
| .name("fk-magnet-content_folder_id") | ||
| .from(Magnet::Table, Magnet::ContentFolderId) | ||
| .to(ContentFolder::Table, ContentFolder::Id), | ||
| ) | ||
| .col(ColumnDef::new(Magnet::CategoryId).integer()) | ||
| .foreign_key( | ||
| ForeignKey::create() | ||
| .name("fk-magnet-category_id") | ||
| .from(Magnet::Table, Magnet::CategoryId) | ||
| .to(Category::Table, Category::Id), | ||
| ) | ||
| .to_owned(), | ||
| ) | ||
| .await | ||
| } | ||
|
|
||
| async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { | ||
| manager | ||
| .drop_table(Table::drop().table(Magnet::Table).to_owned()) | ||
| .await | ||
| } | ||
| } | ||
|
|
||
| #[derive(DeriveIden)] | ||
| enum Magnet { | ||
| Table, | ||
| Id, | ||
| TorrentID, | ||
| Name, | ||
| Link, | ||
| Resolved, | ||
| ContentFolderId, | ||
| CategoryId, | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We should keep the content/category here.