torrust-index-backend 2.0.0-alpha.3

The backend (API) for the Torrust Index project.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
//! Torrent service.
use std::sync::Arc;

use serde_derive::Deserialize;

use super::category::DbCategoryRepository;
use super::user::DbUserRepository;
use crate::config::Configuration;
use crate::databases::database::{Category, Database, Error, Sorting};
use crate::errors::ServiceError;
use crate::models::category::CategoryId;
use crate::models::info_hash::InfoHash;
use crate::models::response::{DeletedTorrentResponse, TorrentResponse, TorrentsResponse};
use crate::models::torrent::{AddTorrentRequest, TorrentId, TorrentListing};
use crate::models::torrent_file::{DbTorrentInfo, Torrent, TorrentFile};
use crate::models::torrent_tag::{TagId, TorrentTag};
use crate::models::user::UserId;
use crate::tracker::statistics_importer::StatisticsImporter;
use crate::{tracker, AsCSV};

pub struct Index {
    configuration: Arc<Configuration>,
    tracker_statistics_importer: Arc<StatisticsImporter>,
    tracker_service: Arc<tracker::service::Service>,
    user_repository: Arc<DbUserRepository>,
    category_repository: Arc<DbCategoryRepository>,
    torrent_repository: Arc<DbTorrentRepository>,
    torrent_info_repository: Arc<DbTorrentInfoRepository>,
    torrent_file_repository: Arc<DbTorrentFileRepository>,
    torrent_announce_url_repository: Arc<DbTorrentAnnounceUrlRepository>,
    torrent_tag_repository: Arc<DbTorrentTagRepository>,
    torrent_listing_generator: Arc<DbTorrentListingGenerator>,
}

/// User request to generate a torrent listing.
#[derive(Debug, Deserialize)]
pub struct ListingRequest {
    pub page_size: Option<u8>,
    pub page: Option<u32>,
    pub sort: Option<Sorting>,
    /// Expects comma separated string, eg: "?categories=movie,other,app"
    pub categories: Option<String>,
    /// Expects comma separated string, eg: "?tags=Linux,Ubuntu"
    pub tags: Option<String>,
    pub search: Option<String>,
}

/// Internal specification for torrent listings.
#[derive(Debug, Deserialize)]
pub struct ListingSpecification {
    pub search: Option<String>,
    pub categories: Option<Vec<String>>,
    pub tags: Option<Vec<String>>,
    pub sort: Sorting,
    pub offset: u64,
    pub page_size: u8,
}

impl Index {
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    pub fn new(
        configuration: Arc<Configuration>,
        tracker_statistics_importer: Arc<StatisticsImporter>,
        tracker_service: Arc<tracker::service::Service>,
        user_repository: Arc<DbUserRepository>,
        category_repository: Arc<DbCategoryRepository>,
        torrent_repository: Arc<DbTorrentRepository>,
        torrent_info_repository: Arc<DbTorrentInfoRepository>,
        torrent_file_repository: Arc<DbTorrentFileRepository>,
        torrent_announce_url_repository: Arc<DbTorrentAnnounceUrlRepository>,
        torrent_tag_repository: Arc<DbTorrentTagRepository>,
        torrent_listing_repository: Arc<DbTorrentListingGenerator>,
    ) -> Self {
        Self {
            configuration,
            tracker_statistics_importer,
            tracker_service,
            user_repository,
            category_repository,
            torrent_repository,
            torrent_info_repository,
            torrent_file_repository,
            torrent_announce_url_repository,
            torrent_tag_repository,
            torrent_listing_generator: torrent_listing_repository,
        }
    }

    /// Adds a torrent to the index.
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    ///
    /// * Unable to get the user from the database.
    /// * Unable to get torrent request from payload.
    /// * Unable to get the category from the database.
    /// * Unable to insert the torrent into the database.
    /// * Unable to add the torrent to the whitelist.
    pub async fn add_torrent(&self, mut torrent_request: AddTorrentRequest, user_id: UserId) -> Result<TorrentId, ServiceError> {
        let _user = self.user_repository.get_compact(&user_id).await?;

        torrent_request.torrent.set_announce_urls(&self.configuration).await;

        let category = self
            .category_repository
            .get_by_name(&torrent_request.metadata.category)
            .await
            .map_err(|_| ServiceError::InvalidCategory)?;

        let torrent_id = self.torrent_repository.add(&torrent_request, user_id, category).await?;

        let _ = self
            .tracker_statistics_importer
            .import_torrent_statistics(torrent_id, &torrent_request.torrent.info_hash())
            .await;

        // We always whitelist the torrent on the tracker because even if the tracker mode is `public`
        // it could be changed to `private` later on.
        if let Err(e) = self
            .tracker_service
            .whitelist_info_hash(torrent_request.torrent.info_hash())
            .await
        {
            // If the torrent can't be whitelisted somehow, remove the torrent from database
            let _ = self.torrent_repository.delete(&torrent_id).await;
            return Err(e);
        }

        self.torrent_tag_repository
            .link_torrent_to_tags(&torrent_id, &torrent_request.metadata.tags)
            .await?;

        Ok(torrent_id)
    }

    /// Gets a torrent from the Index.
    ///
    /// # Errors
    ///
    /// This function will return an error if unable to get the torrent from the
    /// database.
    pub async fn get_torrent(&self, info_hash: &InfoHash, opt_user_id: Option<UserId>) -> Result<Torrent, ServiceError> {
        let mut torrent = self.torrent_repository.get_by_info_hash(info_hash).await?;

        let tracker_url = self.get_tracker_url().await;

        // Add personal tracker url or default tracker url
        match opt_user_id {
            Some(user_id) => {
                let personal_announce_url = self
                    .tracker_service
                    .get_personal_announce_url(user_id)
                    .await
                    .unwrap_or(tracker_url);
                torrent.announce = Some(personal_announce_url.clone());
                if let Some(list) = &mut torrent.announce_list {
                    let vec = vec![personal_announce_url];
                    list.insert(0, vec);
                }
            }
            None => {
                torrent.announce = Some(tracker_url);
            }
        }

        Ok(torrent)
    }

    /// Delete a Torrent from the Index
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    ///
    /// * Unable to get the user who is deleting the torrent (logged-in user).
    /// * The user does not have permission to delete the torrent.
    /// * Unable to get the torrent listing from it's ID.
    /// * Unable to delete the torrent from the database.
    pub async fn delete_torrent(&self, info_hash: &InfoHash, user_id: &UserId) -> Result<DeletedTorrentResponse, ServiceError> {
        let user = self.user_repository.get_compact(user_id).await?;

        // Only administrator can delete torrents.
        // todo: move this to an authorization service.
        if !user.administrator {
            return Err(ServiceError::Unauthorized);
        }

        let torrent_listing = self.torrent_listing_generator.one_torrent_by_info_hash(info_hash).await?;

        self.torrent_repository.delete(&torrent_listing.torrent_id).await?;

        // Remove info-hash from tracker whitelist
        let _ = self
            .tracker_service
            .remove_info_hash_from_whitelist(info_hash.to_string())
            .await;

        Ok(DeletedTorrentResponse {
            torrent_id: torrent_listing.torrent_id,
            info_hash: torrent_listing.info_hash,
        })
    }

    /// Get torrent info from the Index
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// * Unable to get torrent ID.
    /// * Unable to get torrent listing from id.
    /// * Unable to get torrent category from id.
    /// * Unable to get torrent files from id.
    /// * Unable to get torrent info from id.
    /// * Unable to get torrent announce url(s) from id.
    pub async fn get_torrent_info(
        &self,
        info_hash: &InfoHash,
        opt_user_id: Option<UserId>,
    ) -> Result<TorrentResponse, ServiceError> {
        let torrent_listing = self.torrent_listing_generator.one_torrent_by_info_hash(info_hash).await?;

        let torrent_id = torrent_listing.torrent_id;

        let category = match torrent_listing.category_id {
            Some(category_id) => Some(self.category_repository.get_by_id(&category_id).await?),
            None => None,
        };

        let mut torrent_response = TorrentResponse::from_listing(torrent_listing, category);

        // Add files

        torrent_response.files = self.torrent_file_repository.get_by_torrent_id(&torrent_id).await?;

        if torrent_response.files.len() == 1 {
            let torrent_info = self.torrent_info_repository.get_by_info_hash(info_hash).await?;

            torrent_response
                .files
                .iter_mut()
                .for_each(|v| v.path = vec![torrent_info.name.to_string()]);
        }

        // Add trackers

        torrent_response.trackers = self.torrent_announce_url_repository.get_by_torrent_id(&torrent_id).await?;

        let tracker_url = self.get_tracker_url().await;

        // add tracker url
        match opt_user_id {
            Some(user_id) => {
                // if no user owned tracker key can be found, use default tracker url
                let personal_announce_url = self
                    .tracker_service
                    .get_personal_announce_url(user_id)
                    .await
                    .unwrap_or(tracker_url);
                // add personal tracker url to front of vec
                torrent_response.trackers.insert(0, personal_announce_url);
            }
            None => {
                torrent_response.trackers.insert(0, tracker_url);
            }
        }

        // Add magnet link

        // todo: extract a struct or function to build the magnet links
        let mut magnet = format!(
            "magnet:?xt=urn:btih:{}&dn={}",
            torrent_response.info_hash,
            urlencoding::encode(&torrent_response.title)
        );

        // Add trackers from torrent file to magnet link
        for tracker in &torrent_response.trackers {
            magnet.push_str(&format!("&tr={}", urlencoding::encode(tracker)));
        }

        torrent_response.magnet_link = magnet;

        // Get realtime seeders and leechers
        if let Ok(torrent_info) = self
            .tracker_statistics_importer
            .import_torrent_statistics(torrent_response.torrent_id, &torrent_response.info_hash)
            .await
        {
            torrent_response.seeders = torrent_info.seeders;
            torrent_response.leechers = torrent_info.leechers;
        }

        torrent_response.tags = self.torrent_tag_repository.get_tags_for_torrent(&torrent_id).await?;

        Ok(torrent_response)
    }

    /// It returns a list of torrents matching the search criteria.
    ///
    /// # Errors
    ///
    /// Returns a `ServiceError::DatabaseError` if the database query fails.
    pub async fn generate_torrent_info_listing(&self, request: &ListingRequest) -> Result<TorrentsResponse, ServiceError> {
        let torrent_listing_specification = self.listing_specification_from_user_request(request).await;

        let torrents_response = self
            .torrent_listing_generator
            .generate_listing(&torrent_listing_specification)
            .await?;

        Ok(torrents_response)
    }

    /// It converts the user listing request into an internal listing
    /// specification.
    async fn listing_specification_from_user_request(&self, request: &ListingRequest) -> ListingSpecification {
        let settings = self.configuration.settings.read().await;
        let default_torrent_page_size = settings.api.default_torrent_page_size;
        let max_torrent_page_size = settings.api.max_torrent_page_size;
        drop(settings);

        let sort = request.sort.unwrap_or(Sorting::UploadedDesc);
        let page = request.page.unwrap_or(0);
        let page_size = request.page_size.unwrap_or(default_torrent_page_size);

        // Guard that page size does not exceed the maximum
        let max_torrent_page_size = max_torrent_page_size;
        let page_size = if page_size > max_torrent_page_size {
            max_torrent_page_size
        } else {
            page_size
        };

        let offset = u64::from(page * u32::from(page_size));

        let categories = request.categories.as_csv::<String>().unwrap_or(None);

        let tags = request.tags.as_csv::<String>().unwrap_or(None);

        ListingSpecification {
            search: request.search.clone(),
            categories,
            tags,
            sort,
            offset,
            page_size,
        }
    }

    /// Update the torrent info on the Index.
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    ///
    /// * Unable to get the user.
    /// * Unable to get listing from id.
    /// * Unable to update the torrent tile or description.
    /// * User does not have the permissions to update the torrent.
    pub async fn update_torrent_info(
        &self,
        info_hash: &InfoHash,
        title: &Option<String>,
        description: &Option<String>,
        category_id: &Option<CategoryId>,
        tags: &Option<Vec<TagId>>,
        user_id: &UserId,
    ) -> Result<TorrentResponse, ServiceError> {
        let updater = self.user_repository.get_compact(user_id).await?;

        let torrent_listing = self.torrent_listing_generator.one_torrent_by_info_hash(info_hash).await?;

        // Check if user is owner or administrator
        // todo: move this to an authorization service.
        if !(torrent_listing.uploader == updater.username || updater.administrator) {
            return Err(ServiceError::Unauthorized);
        }

        self.torrent_info_repository
            .update(&torrent_listing.torrent_id, title, description, category_id, tags)
            .await?;

        let torrent_listing = self
            .torrent_listing_generator
            .one_torrent_by_torrent_id(&torrent_listing.torrent_id)
            .await?;

        let category = match torrent_listing.category_id {
            Some(category_id) => Some(self.category_repository.get_by_id(&category_id).await?),
            None => None,
        };

        let torrent_response = TorrentResponse::from_listing(torrent_listing, category);

        Ok(torrent_response)
    }

    async fn get_tracker_url(&self) -> String {
        let settings = self.configuration.settings.read().await;
        settings.tracker.url.clone()
    }
}

pub struct DbTorrentRepository {
    database: Arc<Box<dyn Database>>,
}

impl DbTorrentRepository {
    #[must_use]
    pub fn new(database: Arc<Box<dyn Database>>) -> Self {
        Self { database }
    }

    /// It finds the torrent by info-hash.
    ///
    /// # Errors
    ///
    /// This function will return an error there is a database error.
    pub async fn get_by_info_hash(&self, info_hash: &InfoHash) -> Result<Torrent, Error> {
        self.database.get_torrent_from_info_hash(info_hash).await
    }

    /// Inserts the entire torrent in the database.
    ///
    /// # Errors
    ///
    /// This function will return an error there is a database error.
    pub async fn add(
        &self,
        torrent_request: &AddTorrentRequest,
        user_id: UserId,
        category: Category,
    ) -> Result<TorrentId, Error> {
        self.database
            .insert_torrent_and_get_id(
                &torrent_request.torrent,
                user_id,
                category.category_id,
                &torrent_request.metadata.title,
                &torrent_request.metadata.description,
            )
            .await
    }

    /// Deletes the entire torrent in the database.
    ///
    /// # Errors
    ///
    /// This function will return an error there is a database error.
    pub async fn delete(&self, torrent_id: &TorrentId) -> Result<(), Error> {
        self.database.delete_torrent(*torrent_id).await
    }
}

pub struct DbTorrentInfoRepository {
    database: Arc<Box<dyn Database>>,
}

impl DbTorrentInfoRepository {
    #[must_use]
    pub fn new(database: Arc<Box<dyn Database>>) -> Self {
        Self { database }
    }

    /// It finds the torrent info by info-hash.
    ///
    /// # Errors
    ///
    /// This function will return an error there is a database error.
    pub async fn get_by_info_hash(&self, info_hash: &InfoHash) -> Result<DbTorrentInfo, Error> {
        self.database.get_torrent_info_from_info_hash(info_hash).await
    }

    /// It updates the torrent title or/and description by torrent ID.
    ///
    /// # Errors
    ///
    /// This function will return an error there is a database error.
    pub async fn update(
        &self,
        torrent_id: &TorrentId,
        opt_title: &Option<String>,
        opt_description: &Option<String>,
        opt_category_id: &Option<CategoryId>,
        opt_tags: &Option<Vec<TagId>>,
    ) -> Result<(), Error> {
        if let Some(title) = &opt_title {
            self.database.update_torrent_title(*torrent_id, title).await?;
        }

        if let Some(description) = &opt_description {
            self.database.update_torrent_description(*torrent_id, description).await?;
        }

        if let Some(category_id) = &opt_category_id {
            self.database.update_torrent_category(*torrent_id, *category_id).await?;
        }

        if let Some(tags) = opt_tags {
            let mut current_tags: Vec<TagId> = self
                .database
                .get_tags_for_torrent_id(*torrent_id)
                .await?
                .iter()
                .map(|tag| tag.tag_id)
                .collect();

            let mut new_tags = tags.clone();

            current_tags.sort_unstable();
            new_tags.sort_unstable();

            if new_tags != current_tags {
                self.database.delete_all_torrent_tag_links(*torrent_id).await?;
                self.database.add_torrent_tag_links(*torrent_id, tags).await?;
            }
        }

        Ok(())
    }
}

pub struct DbTorrentFileRepository {
    database: Arc<Box<dyn Database>>,
}

impl DbTorrentFileRepository {
    #[must_use]
    pub fn new(database: Arc<Box<dyn Database>>) -> Self {
        Self { database }
    }

    /// It finds the torrent files by torrent id
    ///
    /// # Errors
    ///
    /// It returns an error if there is a database error.
    pub async fn get_by_torrent_id(&self, torrent_id: &TorrentId) -> Result<Vec<TorrentFile>, Error> {
        self.database.get_torrent_files_from_id(*torrent_id).await
    }
}

pub struct DbTorrentAnnounceUrlRepository {
    database: Arc<Box<dyn Database>>,
}

impl DbTorrentAnnounceUrlRepository {
    #[must_use]
    pub fn new(database: Arc<Box<dyn Database>>) -> Self {
        Self { database }
    }

    /// It finds the announce URLs by torrent id
    ///
    /// # Errors
    ///
    /// It returns an error if there is a database error.
    pub async fn get_by_torrent_id(&self, torrent_id: &TorrentId) -> Result<Vec<String>, Error> {
        self.database
            .get_torrent_announce_urls_from_id(*torrent_id)
            .await
            .map(|v| v.into_iter().flatten().collect())
    }
}

pub struct DbTorrentTagRepository {
    database: Arc<Box<dyn Database>>,
}

impl DbTorrentTagRepository {
    #[must_use]
    pub fn new(database: Arc<Box<dyn Database>>) -> Self {
        Self { database }
    }

    /// It adds a new torrent tag link.
    ///
    /// # Errors
    ///
    /// It returns an error if there is a database error.
    pub async fn link_torrent_to_tag(&self, torrent_id: &TorrentId, tag_id: &TagId) -> Result<(), Error> {
        self.database.add_torrent_tag_link(*torrent_id, *tag_id).await
    }

    /// It adds multiple torrent tag links at once.
    ///
    /// # Errors
    ///
    /// It returns an error if there is a database error.
    pub async fn link_torrent_to_tags(&self, torrent_id: &TorrentId, tag_ids: &[TagId]) -> Result<(), Error> {
        self.database.add_torrent_tag_links(*torrent_id, tag_ids).await
    }

    /// It returns all the tags linked to a certain torrent ID.
    ///
    /// # Errors
    ///
    /// It returns an error if there is a database error.
    pub async fn get_tags_for_torrent(&self, torrent_id: &TorrentId) -> Result<Vec<TorrentTag>, Error> {
        self.database.get_tags_for_torrent_id(*torrent_id).await
    }

    /// It removes a torrent tag link.
    ///
    /// # Errors
    ///
    /// It returns an error if there is a database error.
    pub async fn unlink_torrent_from_tag(&self, torrent_id: &TorrentId, tag_id: &TagId) -> Result<(), Error> {
        self.database.delete_torrent_tag_link(*torrent_id, *tag_id).await
    }

    /// It removes all tags for a certain torrent.
    ///
    /// # Errors
    ///
    /// It returns an error if there is a database error.
    pub async fn unlink_all_tags_for_torrent(&self, torrent_id: &TorrentId) -> Result<(), Error> {
        self.database.delete_all_torrent_tag_links(*torrent_id).await
    }
}

pub struct DbTorrentListingGenerator {
    database: Arc<Box<dyn Database>>,
}

impl DbTorrentListingGenerator {
    #[must_use]
    pub fn new(database: Arc<Box<dyn Database>>) -> Self {
        Self { database }
    }

    /// It finds the torrent listing by info-hash
    ///
    /// # Errors
    ///
    /// It returns an error if there is a database error.
    pub async fn one_torrent_by_info_hash(&self, info_hash: &InfoHash) -> Result<TorrentListing, Error> {
        self.database.get_torrent_listing_from_info_hash(info_hash).await
    }

    /// It finds the torrent listing by torrent ID.
    ///
    /// # Errors
    ///
    /// It returns an error if there is a database error.
    pub async fn one_torrent_by_torrent_id(&self, torrent_id: &TorrentId) -> Result<TorrentListing, Error> {
        self.database.get_torrent_listing_from_id(*torrent_id).await
    }

    /// It finds the torrent listing by torrent ID.
    ///
    /// # Errors
    ///
    /// It returns an error if there is a database error.
    pub async fn generate_listing(&self, specification: &ListingSpecification) -> Result<TorrentsResponse, Error> {
        self.database
            .get_torrents_search_sorted_paginated(
                &specification.search,
                &specification.categories,
                &specification.tags,
                &specification.sort,
                specification.offset,
                specification.page_size,
            )
            .await
    }
}