Skip to content

Commit

Permalink
refactor: [#296] extract duplicate code. File: dir, Node: Top, This i…
Browse files Browse the repository at this point in the history
…s the top of the INFO tree.

This is the Info main menu (aka directory node).
A few useful Info commands:

  'q' quits;
  'H' lists all Info commands;
  'h' starts the Info tutorial;
  'mTexinfo RET' visits the Texinfo manual, etc.

* Menu:

Archiving
* Xorrecord: (xorrecord).       Emulates CD/DVD/BD program cdrecord
* Xorriso: (xorriso).           Burns ISO 9660 on CD, DVD, BD.
* Xorrisofs: (xorrisofs).       Emulates ISO 9660 program mkisofs

Basics
* Common options: (coreutils)Common options.
* Coreutils: (coreutils).       Core GNU (file, text, shell) utilities.
* Date input formats: (coreutils)Date input formats.
* Ed: (ed).                     The GNU line editor
* File permissions: (coreutils)File permissions.
                                Access modes.
* Finding files: (find).        Operating on files matching certain criteria.
* Time: (time).                 time

C++ libraries
* autosprintf: (autosprintf).   Support for printf format strings in C++.

Compression
* Gzip: (gzip).                 General (de)compression of files (lzw).

Development
* SSIP: (ssip).                 Speech Synthesis Interface Protocol.
* Speech Dispatcher: (speech-dispatcher).
                                Speech Dispatcher.
* bzip2 and libbzip2, version 1.0.8: (manual).
                                A program and library for data compression
* libffi: (libffi).             Portable foreign function interface library.

Editors
* nano: (nano).                 Small and friendly text editor.

GNU Gettext Utilities
* autopoint: (gettext)autopoint Invocation.
                                Copy gettext infrastructure.
* envsubst: (gettext)envsubst Invocation.
                                Expand environment variables.
* gettextize: (gettext)gettextize Invocation.
                                Prepare a package for gettext.
* gettext: (gettext).           GNU gettext utilities.
* ISO3166: (gettext)Country Codes.
                                ISO 3166 country codes.
* ISO639: (gettext)Language Codes.
                                ISO 639 language codes.
* msgattrib: (gettext)msgattrib Invocation.
                                Select part of a PO file.
* msgcat: (gettext)msgcat Invocation.
                                Combine several PO files.
* msgcmp: (gettext)msgcmp Invocation.
                                Compare a PO file and template.
* msgcomm: (gettext)msgcomm Invocation.
                                Match two PO files.
* msgconv: (gettext)msgconv Invocation.
                                Convert PO file to encoding.
* msgen: (gettext)msgen Invocation.
                                Create an English PO file.
* msgexec: (gettext)msgexec Invocation.
                                Process a PO file.
* msgfilter: (gettext)msgfilter Invocation.
                                Pipe a PO file through a filter.
* msgfmt: (gettext)msgfmt Invocation.
                                Make MO files out of PO files.
* msggrep: (gettext)msggrep Invocation.
                                Select part of a PO file.
* msginit: (gettext)msginit Invocation.
                                Create a fresh PO file.
* msgmerge: (gettext)msgmerge Invocation.
                                Update a PO file from template.
* msgunfmt: (gettext)msgunfmt Invocation.
                                Uncompile MO file into PO file.
* msguniq: (gettext)msguniq Invocation.
                                Unify duplicates for PO file.
* ngettext: (gettext)ngettext Invocation.
                                Translate a message with plural.
* xgettext: (gettext)xgettext Invocation.
                                Extract strings into a PO file.

GNU organization
* Maintaining Findutils: (find-maint).
                                Maintaining GNU findutils

GNU Utilities
* dirmngr-client: (gnupg).      X.509 CRL and OCSP client.
* dirmngr: (gnupg).             X.509 CRL and OCSP server.
* gpg-agent: (gnupg).           The secret key daemon.
* gpg2: (gnupg).                OpenPGP encryption and signing tool.
* gpgsm: (gnupg).               S/MIME encryption and signing tool.

Individual utilities
* aclocal-invocation: (automake-1.16)aclocal Invocation.
                                                Generating aclocal.m4.
* arch: (coreutils)arch invocation.             Print machine hardware name.
* automake-invocation: (automake-1.16)automake Invocation.
                                                Generating Makefile.in.
* b2sum: (coreutils)b2sum invocation.           Print or check BLAKE2 digests.
* base32: (coreutils)base32 invocation.         Base32 encode/decode data.
* base64: (coreutils)base64 invocation.         Base64 encode/decode data.
* basename: (coreutils)basename invocation.     Strip directory and suffix.
* basenc: (coreutils)basenc invocation.         Encoding/decoding of data.
* cat: (coreutils)cat invocation.               Concatenate and write files.
* chcon: (coreutils)chcon invocation.           Change SELinux CTX of files.
* chgrp: (coreutils)chgrp invocation.           Change file groups.
* chmod: (coreutils)chmod invocation.           Change access permissions.
* chown: (coreutils)chown invocation.           Change file owners and groups.
* chroot: (coreutils)chroot invocation.         Specify the root directory.
* cksum: (coreutils)cksum invocation.           Print POSIX CRC checksum.
* cmp: (diffutils)Invoking cmp.                 Compare 2 files byte by byte.
* comm: (coreutils)comm invocation.             Compare sorted files by line.
* cp: (coreutils)cp invocation.                 Copy files.
* csplit: (coreutils)csplit invocation.         Split by context.
* cut: (coreutils)cut invocation.               Print selected parts of lines.
* date: (coreutils)date invocation.             Print/set system date and time.
* dd: (coreutils)dd invocation.                 Copy and convert a file.
* df: (coreutils)df invocation.                 Report file system usage.
* diff: (diffutils)Invoking diff.               Compare 2 files line by line.
* diff3: (diffutils)Invoking diff3.             Compare 3 files line by line.
* dir: (coreutils)dir invocation.               List directories briefly.
* dircolors: (coreutils)dircolors invocation.   Color setup for ls.
* dirname: (coreutils)dirname invocation.       Strip last file name component.
* du: (coreutils)du invocation.                 Report file usage.
* echo: (coreutils)echo invocation.             Print a line of text.
* env: (coreutils)env invocation.               Modify the environment.
* expand: (coreutils)expand invocation.         Convert tabs to spaces.
* expr: (coreutils)expr invocation.             Evaluate expressions.
* factor: (coreutils)factor invocation.         Print prime factors
* false: (coreutils)false invocation.           Do nothing, unsuccessfully.
* find: (find)Invoking find.                    Finding and acting on files.
* fmt: (coreutils)fmt invocation.               Reformat paragraph text.
* fold: (coreutils)fold invocation.             Wrap long input lines.
* groups: (coreutils)groups invocation.         Print group names a user is in.
* gunzip: (gzip)Overview.                       Decompression.
* gzexe: (gzip)Overview.                        Compress executables.
* head: (coreutils)head invocation.             Output the first part of files.
* hostid: (coreutils)hostid invocation.         Print numeric host identifier.
* hostname: (coreutils)hostname invocation.     Print or set system name.
* id: (coreutils)id invocation.                 Print user identity.
* install: (coreutils)install invocation.       Copy files and set attributes.
* join: (coreutils)join invocation.             Join lines on a common field.
* kill: (coreutils)kill invocation.             Send a signal to processes.
* link: (coreutils)link invocation.             Make hard links between files.
* ln: (coreutils)ln invocation.                 Make links between files.
* locate: (find)Invoking locate.                Finding files in a database.
* logname: (coreutils)logname invocation.       Print current login name.
* ls: (coreutils)ls invocation.                 List directory contents.
* md5sum: (coreutils)md5sum invocation.         Print or check MD5 digests.
* mkdir: (coreutils)mkdir invocation.           Create directories.
* mkfifo: (coreutils)mkfifo invocation.         Create FIFOs (named pipes).
* mknod: (coreutils)mknod invocation.           Create special files.
* mktemp: (coreutils)mktemp invocation.         Create temporary files.
* mv: (coreutils)mv invocation.                 Rename files.
* nice: (coreutils)nice invocation.             Modify niceness.
* nl: (coreutils)nl invocation.                 Number lines and write files.
* nohup: (coreutils)nohup invocation.           Immunize to hangups.
* nproc: (coreutils)nproc invocation.           Print the number of processors.
* numfmt: (coreutils)numfmt invocation.         Reformat numbers.
* od: (coreutils)od invocation.                 Dump files in octal, etc.
* paste: (coreutils)paste invocation.           Merge lines of files.
* patch: (diffutils)Invoking patch.             Apply a patch to a file.
* pathchk: (coreutils)pathchk invocation.       Check file name portability.
* pr: (coreutils)pr invocation.                 Paginate or columnate files.
* printenv: (coreutils)printenv invocation.     Print environment variables.
* printf: (coreutils)printf invocation.         Format and print data.
* ptx: (coreutils)ptx invocation.               Produce permuted indexes.
* pwd: (coreutils)pwd invocation.               Print working directory.
* readlink: (coreutils)readlink invocation.     Print referent of a symlink.
* realpath: (coreutils)realpath invocation.     Print resolved file names.
* rm: (coreutils)rm invocation.                 Remove files.
* rmdir: (coreutils)rmdir invocation.           Remove empty directories.
* runcon: (coreutils)runcon invocation.         Run in specified SELinux CTX.
* sdiff: (diffutils)Invoking sdiff.             Merge 2 files side-by-side.
* seq: (coreutils)seq invocation.               Print numeric sequences
* sha1sum: (coreutils)sha1sum invocation.       Print or check SHA-1 digests.
* sha2: (coreutils)sha2 utilities.              Print or check SHA-2 digests.
* shred: (coreutils)shred invocation.           Remove files more securely.
* shuf: (coreutils)shuf invocation.             Shuffling text files.
* sleep: (coreutils)sleep invocation.           Delay for a specified time.
* sort: (coreutils)sort invocation.             Sort text files.
* split: (coreutils)split invocation.           Split into pieces.
* stat: (coreutils)stat invocation.             Report file(system) status.
* stdbuf: (coreutils)stdbuf invocation.         Modify stdio buffering.
* stty: (coreutils)stty invocation.             Print/change terminal settings.
* sum: (coreutils)sum invocation.               Print traditional checksum.
* sync: (coreutils)sync invocation.             Sync files to stable storage.
* tac: (coreutils)tac invocation.               Reverse files.
* tail: (coreutils)tail invocation.             Output the last part of files.
* tee: (coreutils)tee invocation.               Redirect to multiple files.
* test: (coreutils)test invocation.             File/string tests.
* timeout: (coreutils)timeout invocation.       Run with time limit.
* touch: (coreutils)touch invocation.           Change file timestamps.
* tr: (coreutils)tr invocation.                 Translate characters.
* true: (coreutils)true invocation.             Do nothing, successfully.
* truncate: (coreutils)truncate invocation.     Shrink/extend size of a file.
* tsort: (coreutils)tsort invocation.           Topological sort.
* tty: (coreutils)tty invocation.               Print terminal name.
* uname: (coreutils)uname invocation.           Print system information.
* unexpand: (coreutils)unexpand invocation.     Convert spaces to tabs.
* uniq: (coreutils)uniq invocation.             Uniquify files.
* unlink: (coreutils)unlink invocation.         Removal via unlink(2).
* updatedb: (find)Invoking updatedb.            Building the locate database.
* uptime: (coreutils)uptime invocation.         Print uptime and load.
* users: (coreutils)users invocation.           Print current user names.
* vdir: (coreutils)vdir invocation.             List directories verbosely.
* wc: (coreutils)wc invocation.                 Line, word, and byte counts.
* who: (coreutils)who invocation.               Print who is logged in.
* whoami: (coreutils)whoami invocation.         Print effective user ID.
* xargs: (find)Invoking xargs.                  Operating on many files.
* yes: (coreutils)yes invocation.               Print a string indefinitely.
* zcat: (gzip)Overview.                         Decompression to stdout.
* zdiff: (gzip)Overview.                        Compare compressed files.
* zforce: (gzip)Overview.                       Force .gz extension on files.
* zgrep: (gzip)Overview.                        Search compressed files.
* zmore: (gzip)Overview.                        Decompression output by pages.

Kernel
* grub-dev: (grub-dev).         The GRand Unified Bootloader Dev
* grub-install: (grub)Invoking grub-install.
                                Install GRUB on your drive
* grub-mkconfig: (grub)Invoking grub-mkconfig.
                                Generate GRUB configuration
* grub-mkpasswd-pbkdf2: (grub)Invoking grub-mkpasswd-pbkdf2.
* grub-mkrelpath: (grub)Invoking grub-mkrelpath.
* grub-mkrescue: (grub)Invoking grub-mkrescue.
                                Make a GRUB rescue image
* grub-mount: (grub)Invoking grub-mount.
                                Mount a file system using GRUB
* grub-probe: (grub)Invoking grub-probe.
                                Probe device information
* grub-script-check: (grub)Invoking grub-script-check.
* GRUB: (grub).                 The GRand Unified Bootloader

Libraries
* RLuserman: (rluserman).       The GNU readline library User's Manual.

Math
* bc: (bc).                     An arbitrary precision calculator language.

Miscellaneous
* dc: (dc).                     Arbitrary precision RPN "Desktop Calculator".

Network applications
* Wget: (wget).                 Non-interactive network downloader.

Software development
* Automake: (automake-1.16).    Making GNU standards-compliant Makefiles.
* Automake-history: (automake-history).
                                History of Automake development.

Sound
* SSIP: (ssip).                 Speech Synthesis Interface Protocol.
* Say for Speech Dispatcher: (spd-say).
                                Say.
* Speech Dispatcher: (speech-dispatcher).
                                Speech Dispatcher.

Texinfo documentation system
* info stand-alone: (info-stnd).
                                Read Info documents without Emacs.

Text creation and manipulation
* Diffutils: (diffutils).       Comparing and merging files.
* M4: (m4).                     A powerful macro processor.
* grep: (grep).                 Print lines that match patterns.
* sed: (sed).                   Stream EDitor.   dict constructor
  • Loading branch information
josecelano committed Sep 19, 2023
1 parent f0ad6a4 commit fc95453
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 103 deletions.
4 changes: 2 additions & 2 deletions src/databases/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ pub trait Database: Sync + Send {

let torrent_announce_urls = self.get_torrent_announce_urls_from_id(torrent_info.torrent_id).await?;

Ok(Torrent::from_database(torrent_info, torrent_files, torrent_announce_urls))
Ok(Torrent::from_database(&torrent_info, &torrent_files, torrent_announce_urls))
}

/// Get `Torrent` from `torrent_id`.
Expand All @@ -220,7 +220,7 @@ pub trait Database: Sync + Send {

let torrent_announce_urls = self.get_torrent_announce_urls_from_id(torrent_id).await?;

Ok(Torrent::from_database(torrent_info, torrent_files, torrent_announce_urls))
Ok(Torrent::from_database(&torrent_info, &torrent_files, torrent_announce_urls))
}

/// It returns the list of all infohashes producing the same canonical
Expand Down
127 changes: 78 additions & 49 deletions src/models/torrent_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,57 +98,18 @@ impl Torrent {
/// hex string.
#[must_use]
pub fn from_database(
db_torrent: DbTorrent,
torrent_files: Vec<TorrentFile>,
db_torrent: &DbTorrent,
torrent_files: &Vec<TorrentFile>,
torrent_announce_urls: Vec<Vec<String>>,
) -> Self {
let mut info_dict = TorrentInfoDictionary {
name: db_torrent.name,
pieces: None,
piece_length: db_torrent.piece_length,
md5sum: None,
length: None,
files: None,
private: db_torrent.private,
path: None,
root_hash: None,
source: None,
};

// a torrent file has a root hash or a pieces key, but not both.
if db_torrent.root_hash > 0 {
info_dict.root_hash = Some(db_torrent.pieces);
} else {
let buffer = into_bytes(&db_torrent.pieces).expect("variable `torrent_info.pieces` is not a valid hex string");
info_dict.pieces = Some(ByteBuf::from(buffer));
}

// either set the single file or the multiple files information
if torrent_files.len() == 1 {
let torrent_file = torrent_files
.first()
.expect("vector `torrent_files` should have at least one element");

info_dict.md5sum = torrent_file.md5sum.clone();

info_dict.length = Some(torrent_file.length);

let path = if torrent_file
.path
.first()
.as_ref()
.expect("the vector for the `path` should have at least one element")
.is_empty()
{
None
} else {
Some(torrent_file.path.clone())
};

info_dict.path = path;
} else {
info_dict.files = Some(torrent_files);
}
let info_dict = TorrentInfoDictionary::with(
&db_torrent.name,
db_torrent.piece_length,
db_torrent.private,
db_torrent.root_hash,
&db_torrent.pieces,
torrent_files,
);

Self {
info: info_dict,
Expand Down Expand Up @@ -246,6 +207,74 @@ impl Torrent {
}

impl TorrentInfoDictionary {
/// Constructor.
///
/// # Panics
///
/// This function will panic if:
///
/// - The `pieces` field is not a valid hex string.
/// - For single files torrents the `TorrentFile` path is empty.
#[must_use]
pub fn with(
name: &str,
piece_length: i64,
private: Option<u8>,
root_hash: i64,
pieces: &str,
files: &Vec<TorrentFile>,
) -> Self {
let mut info_dict = Self {
name: name.to_string(),
pieces: None,
piece_length,
md5sum: None,
length: None,
files: None,
private,
path: None,
root_hash: None,
source: None,
};

// a torrent file has a root hash or a pieces key, but not both.
if root_hash > 0 {
info_dict.root_hash = Some(pieces.to_owned());
} else {
let buffer = into_bytes(pieces).expect("variable `torrent_info.pieces` is not a valid hex string");
info_dict.pieces = Some(ByteBuf::from(buffer));
}

// either set the single file or the multiple files information
if files.len() == 1 {
let torrent_file = files
.first()
.expect("vector `torrent_files` should have at least one element");

info_dict.md5sum = torrent_file.md5sum.clone();

info_dict.length = Some(torrent_file.length);

let path = if torrent_file
.path
.first()
.as_ref()
.expect("the vector for the `path` should have at least one element")
.is_empty()
{
None
} else {
Some(torrent_file.path.clone())
};

info_dict.path = path;
} else {
info_dict.files = Some(files.clone());
}

info_dict
}

/// torrent file can only hold a pieces key or a root hash key:
/// [BEP 39](http://www.bittorrent.org/beps/bep_0030.html)
#[must_use]
Expand Down
60 changes: 8 additions & 52 deletions src/services/torrent_file.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
//! This module contains the services related to torrent file management.
use serde_bytes::ByteBuf;
use uuid::Uuid;

use crate::models::torrent_file::{Torrent, TorrentFile, TorrentInfoDictionary};
use crate::services::hasher::sha1;
use crate::utils::hex::into_bytes;

/// It contains the information required to create a new torrent file.
///
Expand All @@ -31,56 +29,14 @@ impl CreateTorrentRequest {
/// This function will panic if the `pieces` field is not a valid hex string.
#[must_use]
pub fn build_info_dictionary(&self) -> TorrentInfoDictionary {
let mut info_dict = TorrentInfoDictionary {
name: self.name.to_string(),
pieces: None,
piece_length: self.piece_length,
md5sum: None,
length: None,
files: None,
private: self.private,
path: None,
root_hash: None,
source: None,
};

// a torrent file has a root hash or a pieces key, but not both.
if self.root_hash > 0 {
info_dict.root_hash = Some(self.pieces.clone());
} else {
let buffer = into_bytes(&self.pieces).expect("variable `torrent_info.pieces` is not a valid hex string");
info_dict.pieces = Some(ByteBuf::from(buffer));
}

// either set the single file or the multiple files information
if self.files.len() == 1 {
let torrent_file = self
.files
.first()
.expect("vector `torrent_files` should have at least one element");

info_dict.md5sum = torrent_file.md5sum.clone();

info_dict.length = Some(torrent_file.length);

let path = if torrent_file
.path
.first()
.as_ref()
.expect("the vector for the `path` should have at least one element")
.is_empty()
{
None
} else {
Some(torrent_file.path.clone())
};

info_dict.path = path;
} else {
info_dict.files = Some(self.files.clone());
}

info_dict
TorrentInfoDictionary::with(
&self.name,
self.piece_length,
self.private,
self.root_hash,
&self.pieces,
&self.files,
)
}
}

Expand Down

0 comments on commit fc95453

Please sign in to comment.