From 6c9286857ef8b314962b67f4a16a66e8c35531bc Mon Sep 17 00:00:00 2001 From: Benedikt Peetz Date: Mon, 14 Oct 2024 14:56:29 +0200 Subject: refactor(treewide): Combine the separate crates in one workspace --- Cargo.lock | 350 +++++++++++++--------- Cargo.toml | 61 ++-- crates/bytes/Cargo.toml | 24 +- crates/bytes/src/lib.rs | 1 - crates/libmpv2/Cargo.toml | 7 +- crates/yt_dlp/Cargo.toml | 33 ++- src/app.rs | 41 --- src/cache/mod.rs | 88 ------ src/cli.rs | 318 -------------------- src/comments/comment.rs | 63 ---- src/comments/display.rs | 117 -------- src/comments/mod.rs | 178 ------------ src/config/default.rs | 102 ------- src/config/definitions.rs | 59 ---- src/config/file_system.rs | 112 ------- src/config/mod.rs | 62 ---- src/constants.rs | 11 - src/download/download_options.rs | 121 -------- src/download/mod.rs | 303 ------------------- src/main.rs | 252 ---------------- src/select/cmds.rs | 147 ---------- src/select/mod.rs | 173 ----------- src/select/selection_file/duration.rs | 111 ------- src/select/selection_file/help.str | 12 - src/select/selection_file/help.str.license | 9 - src/select/selection_file/mod.rs | 34 --- src/status/mod.rs | 107 ------- src/storage/mod.rs | 12 - src/storage/subscriptions.rs | 140 --------- src/storage/video_database/downloader.rs | 153 ---------- src/storage/video_database/extractor_hash.rs | 159 ---------- src/storage/video_database/getters.rs | 345 ---------------------- src/storage/video_database/mod.rs | 179 ------------ src/storage/video_database/schema.sql | 57 ---- src/storage/video_database/setters.rs | 270 ----------------- src/subscribe/mod.rs | 184 ------------ src/update/mod.rs | 257 ----------------- src/videos/display/format_video.rs | 166 ----------- src/videos/display/mod.rs | 314 -------------------- src/videos/mod.rs | 66 ----- src/watch/events/mod.rs | 369 ------------------------ src/watch/events/playlist_handler.rs | 94 ------ src/watch/mod.rs | 117 -------- yt/Cargo.toml | 61 ++++ yt/src/app.rs | 41 +++ yt/src/cache/mod.rs | 88 ++++++ yt/src/cli.rs | 318 ++++++++++++++++++++ yt/src/comments/comment.rs | 63 ++++ yt/src/comments/display.rs | 117 ++++++++ yt/src/comments/mod.rs | 178 ++++++++++++ yt/src/config/default.rs | 102 +++++++ yt/src/config/definitions.rs | 59 ++++ yt/src/config/file_system.rs | 112 +++++++ yt/src/config/mod.rs | 62 ++++ yt/src/constants.rs | 11 + yt/src/download/download_options.rs | 121 ++++++++ yt/src/download/mod.rs | 303 +++++++++++++++++++ yt/src/main.rs | 252 ++++++++++++++++ yt/src/select/cmds.rs | 147 ++++++++++ yt/src/select/mod.rs | 173 +++++++++++ yt/src/select/selection_file/duration.rs | 111 +++++++ yt/src/select/selection_file/help.str | 12 + yt/src/select/selection_file/help.str.license | 9 + yt/src/select/selection_file/mod.rs | 34 +++ yt/src/status/mod.rs | 107 +++++++ yt/src/storage/mod.rs | 12 + yt/src/storage/subscriptions.rs | 140 +++++++++ yt/src/storage/video_database/downloader.rs | 153 ++++++++++ yt/src/storage/video_database/extractor_hash.rs | 159 ++++++++++ yt/src/storage/video_database/getters.rs | 345 ++++++++++++++++++++++ yt/src/storage/video_database/mod.rs | 179 ++++++++++++ yt/src/storage/video_database/schema.sql | 57 ++++ yt/src/storage/video_database/setters.rs | 270 +++++++++++++++++ yt/src/subscribe/mod.rs | 184 ++++++++++++ yt/src/update/mod.rs | 257 +++++++++++++++++ yt/src/videos/display/format_video.rs | 166 +++++++++++ yt/src/videos/display/mod.rs | 314 ++++++++++++++++++++ yt/src/videos/mod.rs | 66 +++++ yt/src/watch/events/mod.rs | 369 ++++++++++++++++++++++++ yt/src/watch/events/playlist_handler.rs | 94 ++++++ yt/src/watch/mod.rs | 117 ++++++++ 81 files changed, 5646 insertions(+), 5495 deletions(-) delete mode 100644 src/app.rs delete mode 100644 src/cache/mod.rs delete mode 100644 src/cli.rs delete mode 100644 src/comments/comment.rs delete mode 100644 src/comments/display.rs delete mode 100644 src/comments/mod.rs delete mode 100644 src/config/default.rs delete mode 100644 src/config/definitions.rs delete mode 100644 src/config/file_system.rs delete mode 100644 src/config/mod.rs delete mode 100644 src/constants.rs delete mode 100644 src/download/download_options.rs delete mode 100644 src/download/mod.rs delete mode 100644 src/main.rs delete mode 100644 src/select/cmds.rs delete mode 100644 src/select/mod.rs delete mode 100644 src/select/selection_file/duration.rs delete mode 100644 src/select/selection_file/help.str delete mode 100644 src/select/selection_file/help.str.license delete mode 100644 src/select/selection_file/mod.rs delete mode 100644 src/status/mod.rs delete mode 100644 src/storage/mod.rs delete mode 100644 src/storage/subscriptions.rs delete mode 100644 src/storage/video_database/downloader.rs delete mode 100644 src/storage/video_database/extractor_hash.rs delete mode 100644 src/storage/video_database/getters.rs delete mode 100644 src/storage/video_database/mod.rs delete mode 100644 src/storage/video_database/schema.sql delete mode 100644 src/storage/video_database/setters.rs delete mode 100644 src/subscribe/mod.rs delete mode 100644 src/update/mod.rs delete mode 100644 src/videos/display/format_video.rs delete mode 100644 src/videos/display/mod.rs delete mode 100644 src/videos/mod.rs delete mode 100644 src/watch/events/mod.rs delete mode 100644 src/watch/events/playlist_handler.rs delete mode 100644 src/watch/mod.rs create mode 100644 yt/Cargo.toml create mode 100644 yt/src/app.rs create mode 100644 yt/src/cache/mod.rs create mode 100644 yt/src/cli.rs create mode 100644 yt/src/comments/comment.rs create mode 100644 yt/src/comments/display.rs create mode 100644 yt/src/comments/mod.rs create mode 100644 yt/src/config/default.rs create mode 100644 yt/src/config/definitions.rs create mode 100644 yt/src/config/file_system.rs create mode 100644 yt/src/config/mod.rs create mode 100644 yt/src/constants.rs create mode 100644 yt/src/download/download_options.rs create mode 100644 yt/src/download/mod.rs create mode 100644 yt/src/main.rs create mode 100644 yt/src/select/cmds.rs create mode 100644 yt/src/select/mod.rs create mode 100644 yt/src/select/selection_file/duration.rs create mode 100644 yt/src/select/selection_file/help.str create mode 100644 yt/src/select/selection_file/help.str.license create mode 100644 yt/src/select/selection_file/mod.rs create mode 100644 yt/src/status/mod.rs create mode 100644 yt/src/storage/mod.rs create mode 100644 yt/src/storage/subscriptions.rs create mode 100644 yt/src/storage/video_database/downloader.rs create mode 100644 yt/src/storage/video_database/extractor_hash.rs create mode 100644 yt/src/storage/video_database/getters.rs create mode 100644 yt/src/storage/video_database/mod.rs create mode 100644 yt/src/storage/video_database/schema.sql create mode 100644 yt/src/storage/video_database/setters.rs create mode 100644 yt/src/subscribe/mod.rs create mode 100644 yt/src/update/mod.rs create mode 100644 yt/src/videos/display/format_video.rs create mode 100644 yt/src/videos/display/mod.rs create mode 100644 yt/src/videos/mod.rs create mode 100644 yt/src/watch/events/mod.rs create mode 100644 yt/src/watch/events/playlist_handler.rs create mode 100644 yt/src/watch/mod.rs diff --git a/Cargo.lock b/Cargo.lock index aa719bd..180bf13 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 3 [[package]] name = "addr2line" -version = "0.24.1" +version = "0.24.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5fb1d8e4442bd405fdfd1dacb42792696b0cf9cb15882e5d097b742a676d375" +checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1" dependencies = [ "gimli", ] @@ -110,15 +110,15 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.87" +version = "1.0.89" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10f00e1f6e58a40e807377c75c6a7f97bf9044fab57816f2414e6f5f4499d7b8" +checksum = "86fdf8605db99b54d3cd748a44c6d04df638eb5dafb219b135d0149bd0db01f6" [[package]] name = "arrayref" -version = "0.3.8" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d151e35f61089500b617991b791fc8bfd237ae50cd5950803758a179b41e67a" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" [[package]] name = "arrayvec" @@ -137,9 +137,9 @@ dependencies = [ [[package]] name = "autocfg" -version = "1.3.0" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" +checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" [[package]] name = "backtrace" @@ -174,7 +174,7 @@ version = "0.70.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f" dependencies = [ - "bitflags", + "bitflags 2.6.0", "cexpr", "clang-sys", "itertools", @@ -188,6 +188,12 @@ dependencies = [ "syn", ] +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.6.0" @@ -233,22 +239,22 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.0.0" +version = "1.2.1" dependencies = [ "serde", ] [[package]] name = "bytes" -version = "1.7.1" +version = "1.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8318a53db07bb3f8dca91a600466bdb3f2eaadeedfdbcf02e1accbad9271ba50" +checksum = "428d9aa8fbc0670b7b8d6030a7fadd0f86151cae55e4dbbece15f3780a3dfaf3" [[package]] name = "cc" -version = "1.1.18" +version = "1.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b62ac837cdb5cb22e10a256099b4fc502b1dfe560cb282963a974d7abd80e476" +checksum = "b16803a61b81d9eabb7eae2588776c4c1e584b738ede45fdbb4c972cec1e9945" dependencies = [ "shlex", ] @@ -304,9 +310,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.17" +version = "4.5.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e5a21b8495e732f1b3c364c9949b201ca7bae518c502c80256c96ad79eaf6ac" +checksum = "b97f376d85a664d5837dbae44bf546e6477a679ff6610010f17276f686d867e8" dependencies = [ "clap_builder", "clap_derive", @@ -314,9 +320,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.17" +version = "4.5.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cf2dd12af7a047ad9d6da2b6b249759a22a7abc0f474c1dae1777afa4b21a73" +checksum = "19bc80abd44e4bed93ca373a0704ccbd1b710dc5749406201bb018272808dc54" dependencies = [ "anstream", "anstyle", @@ -326,9 +332,9 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.13" +version = "4.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "501d359d5f3dcaf6ecdeee48833ae73ec6e42723a1e52419c79abf9507eec0a0" +checksum = "4ac6a0c7b1a9e9a5186361f67dfa1b88213572f427fb9ab038efb2bd8c582dab" dependencies = [ "heck", "proc-macro2", @@ -399,6 +405,47 @@ version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5" +[[package]] +name = "crossbeam" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1137cd7e7fc0fb5d3c5a8678be38ec56e819125d8d7907411fe24ccb943faca8" +dependencies = [ + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-epoch", + "crossbeam-queue", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33480d6946193aa8033910124896ca395333cae7e2d1113d1fef6c3272217df2" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613f8cc01fe9cf1a3eb3d7f488fd2fa8388403e97039e2f73692932e291a770d" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-queue" version = "0.3.11" @@ -528,9 +575,9 @@ dependencies = [ [[package]] name = "futures" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "645c6916888f6cb6350d2550b80fb63e734897a8498abe35cfb732b6487804b0" +checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876" dependencies = [ "futures-channel", "futures-core", @@ -543,9 +590,9 @@ dependencies = [ [[package]] name = "futures-channel" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78" +checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" dependencies = [ "futures-core", "futures-sink", @@ -553,15 +600,15 @@ dependencies = [ [[package]] name = "futures-core" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d" +checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" [[package]] name = "futures-executor" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a576fc72ae164fca6b9db127eaa9a9dda0d61316034f33a0a0d4eda41f02b01d" +checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" dependencies = [ "futures-core", "futures-task", @@ -581,15 +628,15 @@ dependencies = [ [[package]] name = "futures-io" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" +checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" [[package]] name = "futures-macro" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" +checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", @@ -598,21 +645,21 @@ dependencies = [ [[package]] name = "futures-sink" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5" +checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7" [[package]] name = "futures-task" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" +checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" [[package]] name = "futures-util" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" +checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" dependencies = [ "futures-channel", "futures-core", @@ -649,9 +696,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.31.0" +version = "0.31.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32085ea23f3234fc7846555e85283ba4de91e21016dc0455a16286d87a292d64" +checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" [[package]] name = "glob" @@ -669,13 +716,19 @@ dependencies = [ "allocator-api2", ] +[[package]] +name = "hashbrown" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e087f84d4f86bf4b218b927129862374b72199ae7d8657835f1e89000eea4fb" + [[package]] name = "hashlink" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" dependencies = [ - "hashbrown", + "hashbrown 0.14.5", ] [[package]] @@ -731,9 +784,9 @@ dependencies = [ [[package]] name = "iana-time-zone" -version = "0.1.60" +version = "0.1.61" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7ffbb5a1b541ea2561f8c41c087286cc091e21e556a4f09a8f6cbf17b69b141" +checksum = "235e081f3925a06703c2d0117ea8b91f042756fd6e7a6e5d901e8ca1a996b220" dependencies = [ "android_system_properties", "core-foundation-sys", @@ -764,12 +817,12 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.5.0" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68b900aa2f7301e21c36462b170ee99994de34dff39a4a6a528e80e7376d07e5" +checksum = "707907fe3c25f5424cce2cb7e1cbcafee6bdbe735ca90ef77c29e84591e5b9da" dependencies = [ "equivalent", - "hashbrown", + "hashbrown 0.15.0", ] [[package]] @@ -812,9 +865,9 @@ checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" [[package]] name = "js-sys" -version = "0.3.70" +version = "0.3.72" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1868808506b929d7b0cfa8f75951347aa71bb21144b7791bae35d9bccfcfe37a" +checksum = "6a88f1bda2bd75b0452a14784937d796722fdebfe50df998aeb3f0b7603019a9" dependencies = [ "wasm-bindgen", ] @@ -830,9 +883,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.158" +version = "0.2.159" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8adc4bb1803a324070e64a98ae98f38934d91957a99cfb3a43dcbc01bc56439" +checksum = "561d97a539a36e26a9a5fad1ea11a3039a67714694aaa379433e580854bc3dc5" [[package]] name = "libloading" @@ -854,8 +907,10 @@ checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058" name = "libmpv2" version = "4.0.0" dependencies = [ + "crossbeam", "libmpv2-sys", "log", + "sdl2", "thiserror", ] @@ -1020,18 +1075,18 @@ dependencies = [ [[package]] name = "object" -version = "0.36.4" +version = "0.36.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "084f1a5821ac4c651660a94a7153d27ac9d8a53736203f58b31945ded098070a" +checksum = "aedf0a2d09c573ed1d8d85b30c119153926a2b36dce0ab28322c09a117a4683e" dependencies = [ "memchr", ] [[package]] name = "once_cell" -version = "1.19.0" +version = "1.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" +checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775" [[package]] name = "owo-colors" @@ -1091,9 +1146,9 @@ checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "pest" -version = "2.7.12" +version = "2.7.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c73c26c01b8c87956cea613c907c9d6ecffd8d18a2a5908e5de0adfaa185cea" +checksum = "879952a81a83930934cbf1786752d6dedc3b1f29e8f8fb2ad1d0a36f377cf442" dependencies = [ "memchr", "thiserror", @@ -1102,9 +1157,9 @@ dependencies = [ [[package]] name = "pest_derive" -version = "2.7.12" +version = "2.7.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "664d22978e2815783adbdd2c588b455b1bd625299ce36b2a99881ac9627e6d8d" +checksum = "d214365f632b123a47fd913301e14c946c61d1c183ee245fa76eb752e59a02dd" dependencies = [ "pest", "pest_generator", @@ -1112,9 +1167,9 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.7.12" +version = "2.7.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2d5487022d5d33f4c30d91c22afa240ce2a644e87fe08caad974d4eab6badbe" +checksum = "eb55586734301717aea2ac313f50b2eb8f60d2fc3dc01d190eefa2e625f60c4e" dependencies = [ "pest", "pest_meta", @@ -1125,9 +1180,9 @@ dependencies = [ [[package]] name = "pest_meta" -version = "2.7.12" +version = "2.7.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0091754bbd0ea592c4deb3a122ce8ecbb0753b738aa82bc055fcc2eccc8d8174" +checksum = "b75da2a70cf4d9cb76833c990ac9cd3923c9a8905a8929789ce347c84564d03d" dependencies = [ "once_cell", "pest", @@ -1169,15 +1224,15 @@ dependencies = [ [[package]] name = "pkg-config" -version = "0.3.30" +version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" +checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2" [[package]] name = "portable-atomic" -version = "1.7.0" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da544ee218f0d287a911e9c99a39a8c9bc8fcad3cb8db5959940044ecfc67265" +checksum = "cc9c68a3f6da06753e9335d63e27f6b9754dd1920d941135b7ea8224f141adb2" [[package]] name = "ppv-lite86" @@ -1200,18 +1255,18 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.86" +version = "1.0.87" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" +checksum = "b3e4daa0dcf6feba26f985457cdf104d4b4256fc5a09547140f3631bb076b19a" dependencies = [ "unicode-ident", ] [[package]] name = "pyo3" -version = "0.22.2" +version = "0.22.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "831e8e819a138c36e212f3af3fd9eeffed6bf1510a805af35b0edee5ffa59433" +checksum = "00e89ce2565d6044ca31a3eb79a334c3a79a841120a98f64eea9f579564cb691" dependencies = [ "cfg-if", "indoc", @@ -1227,9 +1282,9 @@ dependencies = [ [[package]] name = "pyo3-build-config" -version = "0.22.2" +version = "0.22.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e8730e591b14492a8945cdff32f089250b05f5accecf74aeddf9e8272ce1fa8" +checksum = "d8afbaf3abd7325e08f35ffb8deb5892046fcb2608b703db6a583a5ba4cea01e" dependencies = [ "once_cell", "target-lexicon", @@ -1237,9 +1292,9 @@ dependencies = [ [[package]] name = "pyo3-ffi" -version = "0.22.2" +version = "0.22.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e97e919d2df92eb88ca80a037969f44e5e70356559654962cbb3316d00300c6" +checksum = "ec15a5ba277339d04763f4c23d85987a5b08cbb494860be141e6a10a8eb88022" dependencies = [ "libc", "pyo3-build-config", @@ -1247,9 +1302,9 @@ dependencies = [ [[package]] name = "pyo3-macros" -version = "0.22.2" +version = "0.22.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb57983022ad41f9e683a599f2fd13c3664d7063a3ac5714cae4b7bee7d3f206" +checksum = "15e0f01b5364bcfbb686a52fc4181d412b708a68ed20c330db9fc8d2c2bf5a43" dependencies = [ "proc-macro2", "pyo3-macros-backend", @@ -1259,9 +1314,9 @@ dependencies = [ [[package]] name = "pyo3-macros-backend" -version = "0.22.2" +version = "0.22.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec480c0c51ddec81019531705acac51bcdbeae563557c982aa8263bb96880372" +checksum = "a09b550200e1e5ed9176976d0060cbc2ea82dc8515da07885e7b8153a85caacb" dependencies = [ "heck", "proc-macro2", @@ -1311,18 +1366,18 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.5.3" +version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a908a6e00f1fdd0dfd9c0eb08ce85126f6d8bbda50017e74bc4a4b7d4a926a4" +checksum = "9b6dfecf2c74bce2466cabf93f6664d6998a69eb21e39f4207930065b27b771f" dependencies = [ - "bitflags", + "bitflags 2.6.0", ] [[package]] name = "regex" -version = "1.10.6" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4219d74c6b67a3654a9fbebc4b419e22126d13d2f3c4a07ee0cb61ff79a79619" +checksum = "38200e5ee88914975b69f657f0801b6f6dccafd44fd9326302a4aaeecfacb1d8" dependencies = [ "aho-corasick", "memchr", @@ -1332,9 +1387,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.7" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df" +checksum = "368758f23274712b504848e9d5a6f010445cc8b87a7cdb4d7cbee666c1288da3" dependencies = [ "aho-corasick", "memchr", @@ -1343,9 +1398,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a66a03ae7c801facd77a29370b4faec201768915ac14a721ba36f20bc9c209b" +checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" [[package]] name = "rsa" @@ -1381,11 +1436,11 @@ checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" [[package]] name = "rustix" -version = "0.38.36" +version = "0.38.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f55e80d50763938498dd5ebb18647174e0c76dc38c5505294bb224624f30f36" +checksum = "8acb788b847c24f28525660c4d7758620a7210875711f79e7f663cc152726811" dependencies = [ - "bitflags", + "bitflags 2.6.0", "errno", "libc", "linux-raw-sys", @@ -1404,6 +1459,29 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "sdl2" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b498da7d14d1ad6c839729bd4ad6fc11d90a57583605f3b4df2cd709a9cd380" +dependencies = [ + "bitflags 1.3.2", + "lazy_static", + "libc", + "sdl2-sys", +] + +[[package]] +name = "sdl2-sys" +version = "0.37.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "951deab27af08ed9c6068b7b0d05a93c91f0a8eb16b6b816a5e73452a43521d3" +dependencies = [ + "cfg-if", + "libc", + "version-compare", +] + [[package]] name = "serde" version = "1.0.210" @@ -1438,9 +1516,9 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "0.6.7" +version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb5b1b31579f3811bf615c144393417496f152e12ac8b7663bf664f4a815306d" +checksum = "87607cb1398ed59d48732e575a4c28a7a8ebf2454b964fe3f224f2afc07909e1" dependencies = [ "serde", ] @@ -1582,7 +1660,7 @@ checksum = "d4d8060b456358185f7d50c55d9b5066ad956956fddec42ee2e8567134a8936e" dependencies = [ "atoi", "byteorder", - "bytes 1.7.1", + "bytes 1.7.2", "crc", "crossbeam-queue", "either", @@ -1592,7 +1670,7 @@ dependencies = [ "futures-intrusive", "futures-io", "futures-util", - "hashbrown", + "hashbrown 0.14.5", "hashlink", "hex", "indexmap", @@ -1660,9 +1738,9 @@ checksum = "64bb4714269afa44aef2755150a0fc19d756fb580a67db8885608cf02f47d06a" dependencies = [ "atoi", "base64", - "bitflags", + "bitflags 2.6.0", "byteorder", - "bytes 1.7.1", + "bytes 1.7.2", "crc", "digest", "dotenvy", @@ -1702,7 +1780,7 @@ checksum = "6fa91a732d854c5d7726349bb4bb879bb9478993ceb764247660aee25f67c2f8" dependencies = [ "atoi", "base64", - "bitflags", + "bitflags 2.6.0", "byteorder", "crc", "dotenvy", @@ -1793,9 +1871,9 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "syn" -version = "2.0.77" +version = "2.0.79" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f35bcdf61fd8e7be6caf75f429fdca8beb3ed76584befb503b1569faee373ed" +checksum = "89132cd0bf050864e1d38dc3bbc07a0eb8e7530af26344d3d2bbbef83499f590" dependencies = [ "proc-macro2", "quote", @@ -1810,9 +1888,9 @@ checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" [[package]] name = "tempfile" -version = "3.12.0" +version = "3.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04cbcdd0c794ebb0d4cf35e88edd2f7d2c4c3e9a5a6dab322839b321c6a87a64" +checksum = "f0f2c9fc62d0beef6951ccffd757e241266a2c833136efbe35af6cd2567dca5b" dependencies = [ "cfg-if", "fastrand", @@ -1832,18 +1910,18 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.63" +version = "1.0.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0342370b38b6a11b6cc11d6a805569958d54cfa061a29969c3b5ce2ea405724" +checksum = "d50af8abc119fb8bb6dbabcfa89656f46f84aa0ac7688088608076ad2b459a84" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.63" +version = "1.0.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261" +checksum = "08904e7672f5eb876eaaf87e0ce17857500934f4981c4a0ab2b4aa98baac7fc3" dependencies = [ "proc-macro2", "quote", @@ -1882,7 +1960,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2b070231665d27ad9ec9b8df639893f46727666c6767db40317fbe920a5d998" dependencies = [ "backtrace", - "bytes 1.7.1", + "bytes 1.7.2", "libc", "mio", "pin-project-lite", @@ -1937,9 +2015,9 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.22.20" +version = "0.22.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "583c44c02ad26b0c3f3066fe629275e50627026c51ac2e595cca4c230ce1ce1d" +checksum = "4ae48d6208a266e853d946088ed816055e556cc6028c5e8e2b84d9fa5dd7c7f5" dependencies = [ "indexmap", "serde", @@ -1998,15 +2076,15 @@ checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" [[package]] name = "ucd-trie" -version = "0.1.6" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9" +checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" [[package]] name = "unicode-bidi" -version = "0.3.15" +version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75" +checksum = "5ab17db44d7388991a428b2ee655ce0c212e862eff1768a455c58f9aad6e7893" [[package]] name = "unicode-ident" @@ -2016,24 +2094,24 @@ checksum = "e91b56cd4cadaeb79bbf1a5645f6b4f8dc5bde8834ad5894a8db35fda9efa1fe" [[package]] name = "unicode-normalization" -version = "0.1.23" +version = "0.1.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a56d1686db2308d901306f92a263857ef59ea39678a5458e7cb17f01415101f5" +checksum = "5033c97c4262335cded6d6fc3e5c18ab755e1a3dc96376350f3d8e9f009ad956" dependencies = [ "tinyvec", ] [[package]] name = "unicode-properties" -version = "0.1.2" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ea75f83c0137a9b98608359a5f1af8144876eb67bcb1ce837368e906a9f524" +checksum = "e70f2a8b45122e719eb623c01822704c4e0907e7e426a05927e1a1cfff5b75d0" [[package]] name = "unicode-segmentation" -version = "1.11.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4c87d22b6e3f4a18d4d40ef354e97c90fcb14dd91d7dc0aa9d8a1172ebf7202" +checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" [[package]] name = "unicode_categories" @@ -2071,6 +2149,12 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" +[[package]] +name = "version-compare" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "579a42fc0b8e0c63b76519a339be31bed574929511fa53c1a3acae26eb258f29" + [[package]] name = "version_check" version = "0.9.5" @@ -2091,9 +2175,9 @@ checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" [[package]] name = "wasm-bindgen" -version = "0.2.93" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a82edfc16a6c469f5f44dc7b571814045d60404b55a0ee849f9bcfa2e63dd9b5" +checksum = "128d1e363af62632b8eb57219c8fd7877144af57558fb2ef0368d0087bddeb2e" dependencies = [ "cfg-if", "once_cell", @@ -2102,9 +2186,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.93" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9de396da306523044d3302746f1208fa71d7532227f15e347e2d93e4145dd77b" +checksum = "cb6dd4d3ca0ddffd1dd1c9c04f94b868c37ff5fac97c30b97cff2d74fce3a358" dependencies = [ "bumpalo", "log", @@ -2117,9 +2201,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.93" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "585c4c91a46b072c92e908d99cb1dcdf95c5218eeb6f3bf1efa991ee7a68cccf" +checksum = "e79384be7f8f5a9dd5d7167216f022090cf1f9ec128e6e6a482a2cb5c5422c56" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -2127,9 +2211,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.93" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afc340c74d9005395cf9dd098506f7f44e38f2b4a21c6aaacf9a105ea5e1e836" +checksum = "26c6ab57572f7a24a4985830b120de1594465e5d500f24afe89e16b4e833ef68" dependencies = [ "proc-macro2", "quote", @@ -2140,9 +2224,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.93" +version = "0.2.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c62a0a307cb4a311d3a07867860911ca130c3494e8c2719593806c08bc5d0484" +checksum = "65fc09f10666a9f147042251e0dda9c18f166ff7de300607007e96bdebc1068d" [[package]] name = "whoami" @@ -2322,9 +2406,9 @@ checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "winnow" -version = "0.6.18" +version = "0.6.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68a9bda4691f099d435ad181000724da8e5899daa10713c2d432552b9ccd3a6f" +checksum = "36c1fec1a2bb5866f07c25f68c26e565c4c200aebb96d7e55710c19d3e8ac49b" dependencies = [ "memchr", ] @@ -2341,7 +2425,7 @@ version = "1.2.1" dependencies = [ "anyhow", "blake3", - "bytes 1.0.0", + "bytes 1.2.1", "chrono", "chrono-humanize", "clap", @@ -2366,9 +2450,9 @@ dependencies = [ [[package]] name = "yt_dlp" -version = "0.1.0" +version = "1.2.1" dependencies = [ - "bytes 1.0.0", + "bytes 1.2.1", "log", "pyo3", "serde", diff --git a/Cargo.toml b/Cargo.toml index cd39eb2..1fa9668 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,46 +8,34 @@ # You should have received a copy of the License along with this program. # If not, see . -[package] -name = "yt" -version = "1.2.1" +[workspace] +resolver = "2" +members = [ + "crates/bytes", + "crates/yt_dlp", + "yt", +] + +[workspace.package] edition = "2021" +version = "1.2.1" +rust-version = "1.80.0" +authors = ["Benedikt Peetz "] +repository = "https://git.vhack.eu/soispha/clients/yt" +license = "GPL-3.0-or-later" +description = "A fully featured command line YouTube client" -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[workspace.dependencies] +# Own Crates +yt_dlp = { path = "./crates/yt_dlp" } +bytes = { path = "./crates/bytes" } +libmpv2 = { path = "./crates/libmpv2" } -[dependencies] -anyhow = "1.0.87" -blake3 = "1.5.4" -chrono = { version = "0.4.38", features = ["now"] } -chrono-humanize = "0.2.3" -clap = { version = "4.5.17", features = ["derive"] } -futures = "0.3.30" +# Shared log = "0.4.22" -regex = "1.10.6" serde = { version = "1.0.210", features = ["derive"] } serde_json = "1.0.128" -sqlx = { version = "0.8.2", features = ["runtime-tokio", "sqlite"] } -stderrlog = "0.6.0" -tempfile = "3.12.0" -tokio = { version = "1.40.0", features = [ - "rt-multi-thread", - "macros", - "process", - "time", - "io-std", -] } url = { version = "2.5.2", features = ["serde"] } -xdg = "2.5.2" -yt_dlp = { path = "./crates/yt_dlp/" } -libmpv2 = { path = "./crates/libmpv2" } -bytes = { path = "./crates/bytes", features = ["serde"] } -trinitry = { version = "0.2.2" } -toml = "0.8.19" -nucleo-matcher = "0.3.1" -owo-colors = "4.1.0" - -[[bin]] -name = "yt" [profile.profiling] inherits = "release" @@ -59,7 +47,7 @@ codegen-units = 1 panic = "abort" split-debuginfo = "off" -[lints.rust] +[workspace.lints.rust] # rustc lint groups https://doc.rust-lang.org/rustc/lints/groups.html warnings = "warn" future_incompatible = { level = "warn", priority = -1 } @@ -90,7 +78,7 @@ unused_lifetimes = "warn" unused_qualifications = "warn" variant_size_differences = "warn" -[lints.rustdoc] +[workspace.lints.rustdoc] # rustdoc lints https://doc.rust-lang.org/rustdoc/lints.html broken_intra_doc_links = "warn" private_intra_doc_links = "warn" @@ -100,7 +88,7 @@ invalid_codeblock_attributes = "warn" invalid_rust_codeblocks = "warn" bare_urls = "warn" -[lints.clippy] +[workspace.lints.clippy] # clippy allowed by default dbg_macro = "warn" @@ -112,4 +100,3 @@ style = { level = "warn", priority = -1 } complexity = { level = "warn", priority = -1 } perf = { level = "warn", priority = -1 } pedantic = { level = "warn", priority = -1 } - diff --git a/crates/bytes/Cargo.toml b/crates/bytes/Cargo.toml index 0dc9833..4439aa8 100644 --- a/crates/bytes/Cargo.toml +++ b/crates/bytes/Cargo.toml @@ -10,14 +10,24 @@ [package] name = "bytes" -version = "1.0.0" -edition = "2021" -license = "GPL-3.0-or-later" description = "Simple byte formatting utilities" +keywords = [] +categories = [] +version.workspace = true +edition.workspace = true +authors.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true +publish = false [dependencies] -serde = { version = "1.0.210", optional = true } +serde.workspace = true -[features] -default = ["serde"] -serde = ["dep:serde"] +[dev-dependencies] + +[lints] +workspace = true + +[package.metadata.docs.rs] +all-features = true diff --git a/crates/bytes/src/lib.rs b/crates/bytes/src/lib.rs index 113e8d5..78d3c4e 100644 --- a/crates/bytes/src/lib.rs +++ b/crates/bytes/src/lib.rs @@ -26,7 +26,6 @@ const GB: u64 = 1000 * MB; const TB: u64 = 1000 * GB; pub mod error; -#[cfg(feature = "serde")] pub mod serde; #[derive(Clone, Copy)] diff --git a/crates/libmpv2/Cargo.toml b/crates/libmpv2/Cargo.toml index d92a012..8d45872 100644 --- a/crates/libmpv2/Cargo.toml +++ b/crates/libmpv2/Cargo.toml @@ -8,9 +8,6 @@ # You should have received a copy of the License along with this program. # If not, see . -[workspace] -members = ["libmpv2-sys"] - [package] name = "libmpv2" version = "4.0.0" @@ -23,8 +20,8 @@ keywords = ["media", "playback", "mpv", "libmpv"] [dependencies] libmpv2-sys = { path = "libmpv2-sys", version = "4.0.0" } -log = "0.4.22" -thiserror = "1.0.63" +thiserror = "1.0.64" +log = { version = "0.4.22" } [dev-dependencies] crossbeam = "0.8" diff --git a/crates/yt_dlp/Cargo.toml b/crates/yt_dlp/Cargo.toml index 6cedf5b..0f1d248 100644 --- a/crates/yt_dlp/Cargo.toml +++ b/crates/yt_dlp/Cargo.toml @@ -11,15 +11,28 @@ [package] name = "yt_dlp" description = "A wrapper around the python yt_dlp library" -version = "0.1.0" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +keywords = [] +categories = [] +version.workspace = true +edition.workspace = true +authors.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true +publish = false [dependencies] -log = "0.4.22" -pyo3 = { version = "0.22.2", features = ["auto-initialize", "gil-refs"] } -serde = { version = "1.0.210", features = ["derive"] } -serde_json = "1.0.128" -url = { version = "2.5.2", features = ["serde"] } -bytes = { path = "../bytes" } +pyo3 = { version = "0.22.4", features = ["auto-initialize", "gil-refs"] } +bytes.workspace = true +log.workspace = true +serde.workspace = true +serde_json.workspace = true +url.workspace = true + +[dev-dependencies] + +[lints] +workspace = true + +[package.metadata.docs.rs] +all-features = true diff --git a/src/app.rs b/src/app.rs deleted file mode 100644 index b7d136e..0000000 --- a/src/app.rs +++ /dev/null @@ -1,41 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -use anyhow::{Context, Result}; -use sqlx::{query, sqlite::SqliteConnectOptions, SqlitePool}; - -use crate::config::Config; - -pub struct App { - pub database: SqlitePool, - pub config: Config, -} - -impl App { - pub async fn new(config: Config) -> Result { - let options = SqliteConnectOptions::new() - .filename(&config.paths.database_path) - .optimize_on_close(true, None) - .create_if_missing(true); - - let pool = SqlitePool::connect_with(options) - .await - .context("Failed to connect to database!")?; - - query(include_str!("storage/video_database/schema.sql")) - .execute(&pool) - .await?; - - Ok(App { - database: pool, - config, - }) - } -} diff --git a/src/cache/mod.rs b/src/cache/mod.rs deleted file mode 100644 index a3e08c9..0000000 --- a/src/cache/mod.rs +++ /dev/null @@ -1,88 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -use anyhow::{Context, Result}; -use log::info; -use tokio::fs; - -use crate::{ - app::App, - storage::video_database::{ - downloader::set_video_cache_path, getters::get_videos, setters::set_state_change, Video, - VideoStatus, - }, -}; - -async fn invalidate_video(app: &App, video: &Video, hard: bool) -> Result<()> { - info!("Invalidating cache of video: '{}'", video.title); - - if hard { - if let Some(path) = &video.cache_path { - info!("Removing cached video at: '{}'", path.display()); - fs::remove_file(path).await.with_context(|| { - format!( - "Failed to delete video ('{}') cache path: '{}'.", - video.title, - path.display() - ) - })?; - } - } - - set_video_cache_path(app, &video.extractor_hash, None).await?; - - Ok(()) -} - -pub async fn invalidate(app: &App, hard: bool) -> Result<()> { - let all_cached_things = get_videos(app, &[VideoStatus::Cached], None).await?; - - info!("Got videos to invalidate: '{}'", all_cached_things.len()); - - for video in all_cached_things { - invalidate_video(app, &video, hard).await? - } - - Ok(()) -} - -pub async fn maintain(app: &App, all: bool) -> Result<()> { - let domain = if all { - vec![ - VideoStatus::Pick, - // - VideoStatus::Watch, - VideoStatus::Cached, - VideoStatus::Watched, - // - VideoStatus::Drop, - VideoStatus::Dropped, - ] - } else { - vec![VideoStatus::Watch, VideoStatus::Cached] - }; - - let cached_videos = get_videos(app, domain.as_slice(), None).await?; - - for vid in cached_videos { - if let Some(path) = vid.cache_path.as_ref() { - info!("Checking if path ('{}') exists", path.display()); - if !path.exists() { - invalidate_video(app, &vid, false).await?; - } - } - if vid.status_change { - info!("Video '{}' has it's changing bit set. This is probably the result of an unexpectet exit. Clearing it", vid.title); - set_state_change(app, &vid.extractor_hash, false).await?; - } - } - - Ok(()) -} diff --git a/src/cli.rs b/src/cli.rs deleted file mode 100644 index d19586e..0000000 --- a/src/cli.rs +++ /dev/null @@ -1,318 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -use std::path::PathBuf; - -use anyhow::Context; -use bytes::Bytes; -use chrono::NaiveDate; -use clap::{ArgAction, Args, Parser, Subcommand}; -use url::Url; - -use crate::{ - select::selection_file::duration::Duration, - storage::video_database::extractor_hash::LazyExtractorHash, -}; - -#[derive(Parser, Debug)] -#[clap(author, version, about, long_about = None)] -/// An command line interface to select, download and watch videos -pub struct CliArgs { - #[command(subcommand)] - /// The subcommand to execute [default: select] - pub command: Option, - - /// Increase message verbosity - #[arg(long="verbose", short = 'v', action = ArgAction::Count)] - pub verbosity: u8, - - /// Set the path to the videos.db. This overrides the default and the config file. - #[arg(long, short)] - pub db_path: Option, - - /// Set the path to the config.toml. - /// This overrides the default. - #[arg(long, short)] - pub config_path: Option, - - /// Silence all output - #[arg(long, short = 'q')] - pub quiet: bool, -} - -#[derive(Subcommand, Debug)] -pub enum Command { - /// Download and cache URLs - Download { - /// Forcefully re-download all cached videos (i.e. delete the cache path, then download). - #[arg(short, long)] - force: bool, - - /// The maximum size the download dir should have. Beware that the value must be given in - /// bytes. - #[arg(short, long, value_parser = byte_parser)] - max_cache_size: Option, - }, - - /// Select, download and watch in one command. - Sedowa {}, - /// Download and watch in one command. - Dowa {}, - - /// Work with single videos - Videos { - #[command(subcommand)] - cmd: VideosCommand, - }, - - /// Watch the already cached (and selected) videos - Watch {}, - - /// Show, which videos have been selected to be watched (and their cache status) - Status {}, - - /// Show, the configuration options in effect - Config {}, - - /// Perform various tests - Check { - #[command(subcommand)] - command: CheckCommand, - }, - - /// Display the comments of the currently playing video - Comments {}, - /// Display the description of the currently playing video - Description {}, - - /// Manipulate the video cache in the database - #[command(visible_alias = "db")] - Database { - #[command(subcommand)] - command: CacheCommand, - }, - - /// Change the state of videos in the database (the default) - Select { - #[command(subcommand)] - cmd: Option, - }, - - /// Update the video database - Update { - #[arg(short, long)] - /// The number of videos to updating - max_backlog: Option, - - #[arg(short, long)] - /// The subscriptions to update (can be given multiple times) - subscriptions: Vec, - }, - - /// Manipulate subscription - #[command(visible_alias = "subs")] - Subscriptions { - #[command(subcommand)] - cmd: SubscriptionCommand, - }, -} - -fn byte_parser(input: &str) -> Result { - Ok(input - .parse::() - .with_context(|| format!("Failed to parse '{}' as bytes!", input))? - .as_u64()) -} - -impl Default for Command { - fn default() -> Self { - Self::Select { - cmd: Some(SelectCommand::default()), - } - } -} - -#[derive(Subcommand, Clone, Debug)] -pub enum VideosCommand { - /// List the videos in the database - #[command(visible_alias = "ls")] - List { - /// An optional search query to limit the results - #[arg(action = ArgAction::Append)] - search_query: Option, - - /// The number of videos to show - #[arg(short, long)] - limit: Option, - }, - - /// Get detailed information about a video - Info { - /// The short hash of the video - hash: LazyExtractorHash, - }, -} - -#[derive(Subcommand, Clone, Debug)] -pub enum SubscriptionCommand { - /// Subscribe to an URL - Add { - #[arg(short, long)] - /// The human readable name of the subscription - name: Option, - - /// The URL to listen to - url: Url, - }, - - /// Unsubscribe from an URL - Remove { - /// The human readable name of the subscription - name: String, - }, - - /// Import a bunch of URLs as subscriptions. - Import { - /// The file containing the URLs. Will use Stdin otherwise. - file: Option, - - /// Remove any previous subscriptions - #[arg(short, long)] - force: bool, - }, - /// Write all subscriptions in an format understood by `import` - Export {}, - - /// List all subscriptions - List {}, -} - -#[derive(Clone, Debug, Args)] -#[command(infer_subcommands = true)] -/// Mark the video given by the hash to be watched -pub struct SharedSelectionCommandArgs { - /// The ordering priority (higher means more at the top) - #[arg(short, long)] - pub priority: Option, - - /// The subtitles to download (e.g. 'en,de,sv') - #[arg(short = 'l', long)] - pub subtitle_langs: Option, - - /// The speed to set mpv to - #[arg(short, long)] - pub speed: Option, - - /// The short extractor hash - pub hash: LazyExtractorHash, - - pub title: String, - - pub date: NaiveDate, - - pub publisher: String, - - pub duration: Duration, - - pub url: Url, -} - -#[derive(Subcommand, Clone, Debug)] -// NOTE: Keep this in sync with the [`constants::HELP_STR`] constant. <2024-08-20> -pub enum SelectCommand { - /// Open a `git rebase` like file to select the videos to watch (the default) - File { - /// Include done (watched, dropped) videos - #[arg(long, short)] - done: bool, - - /// Use the last selection file (useful if you've spend time on it and want to get it again) - #[arg(long, short, conflicts_with = "done")] - use_last_selection: bool, - }, - - /// Add a video to the database - #[command(visible_alias = "a")] - Add { urls: Vec }, - - /// Mark the video given by the hash to be watched - #[command(visible_alias = "w")] - Watch { - #[command(flatten)] - shared: SharedSelectionCommandArgs, - }, - - /// Mark the video given by the hash to be dropped - #[command(visible_alias = "d")] - Drop { - #[command(flatten)] - shared: SharedSelectionCommandArgs, - }, - - /// Mark the video given by the hash as already watched - #[command(visible_alias = "wd")] - Watched { - #[command(flatten)] - shared: SharedSelectionCommandArgs, - }, - - /// Open the video URL in Firefox's `timesinks.youtube` profile - #[command(visible_alias = "u")] - Url { - #[command(flatten)] - shared: SharedSelectionCommandArgs, - }, - - /// Reset the videos status to 'Pick' - #[command(visible_alias = "p")] - Pick { - #[command(flatten)] - shared: SharedSelectionCommandArgs, - }, -} -impl Default for SelectCommand { - fn default() -> Self { - Self::File { - done: false, - use_last_selection: false, - } - } -} - -#[derive(Subcommand, Clone, Debug)] -pub enum CheckCommand { - /// Check if the given info.json is deserializable - InfoJson { path: PathBuf }, - - /// Check if the given update info.json is deserializable - UpdateInfoJson { path: PathBuf }, -} - -#[derive(Subcommand, Clone, Copy, Debug)] -pub enum CacheCommand { - /// Invalidate all cache entries - Invalidate { - /// Also delete the cache path - #[arg(short, long)] - hard: bool, - }, - - /// Perform basic maintenance operations on the database. - /// This helps recovering from invalid db states after a crash (or force exit via CTRL+C). - /// - /// 1. Check every path for validity (removing all invalid cache entries) - /// 2. Reset all `status_change` bits of videos to false. - #[command(verbatim_doc_comment)] - Maintain { - /// Check every video (otherwise only the videos to be watched are checked) - #[arg(short, long)] - all: bool, - }, -} diff --git a/src/comments/comment.rs b/src/comments/comment.rs deleted file mode 100644 index 752c510..0000000 --- a/src/comments/comment.rs +++ /dev/null @@ -1,63 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -use yt_dlp::wrapper::info_json::Comment; - -#[derive(Debug, Clone)] -pub struct CommentExt { - pub value: Comment, - pub replies: Vec, -} - -#[derive(Debug, Default)] -pub struct Comments { - pub(super) vec: Vec, -} - -impl Comments { - pub fn new() -> Self { - Self::default() - } - pub fn push(&mut self, value: CommentExt) { - self.vec.push(value); - } - pub fn get_mut(&mut self, key: &str) -> Option<&mut CommentExt> { - self.vec.iter_mut().filter(|c| c.value.id.id == key).last() - } - pub fn insert(&mut self, key: &str, value: CommentExt) { - let parent = self - .vec - .iter_mut() - .filter(|c| c.value.id.id == key) - .last() - .expect("One of these should exist"); - parent.push_reply(value); - } -} -impl CommentExt { - pub fn push_reply(&mut self, value: CommentExt) { - self.replies.push(value) - } - pub fn get_mut_reply(&mut self, key: &str) -> Option<&mut CommentExt> { - self.replies - .iter_mut() - .filter(|c| c.value.id.id == key) - .last() - } -} - -impl From for CommentExt { - fn from(value: Comment) -> Self { - Self { - replies: vec![], - value, - } - } -} diff --git a/src/comments/display.rs b/src/comments/display.rs deleted file mode 100644 index 7000063..0000000 --- a/src/comments/display.rs +++ /dev/null @@ -1,117 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -use std::fmt::Write; - -use chrono::{Local, TimeZone}; -use chrono_humanize::{Accuracy, HumanTime, Tense}; - -use crate::comments::comment::CommentExt; - -use super::comment::Comments; - -impl Comments { - pub fn render(&self, color: bool) -> String { - self.render_help(color).expect("This should never fail.") - } - - fn render_help(&self, color: bool) -> Result { - let mut f = String::new(); - - macro_rules! c { - ($color_str:expr, $write:ident, $color:expr) => { - if $color { - $write.write_str(concat!("\x1b[", $color_str, "m"))? - } - }; - } - - fn format( - comment: &CommentExt, - f: &mut String, - ident_count: u32, - color: bool, - ) -> std::fmt::Result { - let ident = &(0..ident_count).map(|_| " ").collect::(); - let value = &comment.value; - - f.write_str(ident)?; - - if value.author_is_uploader { - c!("91;1", f, color); - } else { - c!("35", f, color); - } - - f.write_str(&value.author)?; - c!("0", f, color); - if value.edited || value.is_favorited { - f.write_str("[")?; - if value.edited { - f.write_str("")?; - } - if value.edited && value.is_favorited { - f.write_str(" ")?; - } - if value.is_favorited { - f.write_str("")?; - } - f.write_str("]")?; - } - - c!("36;1", f, color); - write!( - f, - " {}", - HumanTime::from( - Local - .timestamp_opt(value.timestamp, 0) - .single() - .expect("This should be valid") - ) - .to_text_en(Accuracy::Rough, Tense::Past) - )?; - c!("0", f, color); - - // c!("31;1", f); - // f.write_fmt(format_args!(" [{}]", comment.value.like_count))?; - // c!("0", f); - - f.write_str(":\n")?; - f.write_str(ident)?; - - f.write_str(&value.text.replace('\n', &format!("\n{}", ident)))?; - f.write_str("\n")?; - - if !comment.replies.is_empty() { - let mut children = comment.replies.clone(); - children.sort_by(|a, b| a.value.timestamp.cmp(&b.value.timestamp)); - - for child in children { - format(&child, f, ident_count + 4, color)?; - } - } else { - f.write_str("\n")?; - } - - Ok(()) - } - - if !&self.vec.is_empty() { - let mut children = self.vec.clone(); - children.sort_by(|a, b| b.value.like_count.cmp(&a.value.like_count)); - - for child in children { - format(&child, &mut f, 0, color)? - } - } - Ok(f) - } -} diff --git a/src/comments/mod.rs b/src/comments/mod.rs deleted file mode 100644 index 5fbc3fb..0000000 --- a/src/comments/mod.rs +++ /dev/null @@ -1,178 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -use std::{ - io::Write, - mem, - process::{Command, Stdio}, -}; - -use anyhow::{bail, Context, Result}; -use comment::{CommentExt, Comments}; -use regex::Regex; -use yt_dlp::wrapper::info_json::{Comment, InfoJson, Parent}; - -use crate::{ - app::App, - storage::video_database::{ - getters::{get_currently_playing_video, get_video_info_json}, - Video, - }, -}; - -mod comment; -mod display; - -pub async fn get_comments(app: &App) -> Result { - let currently_playing_video: Video = - if let Some(video) = get_currently_playing_video(app).await? { - video - } else { - bail!("Could not find a currently playing video!"); - }; - - let mut info_json: InfoJson = get_video_info_json(¤tly_playing_video) - .await? - .expect("A currently *playing* must be cached. And thus the info.json should be available"); - - let base_comments = mem::take(&mut info_json.comments).expect("A video should have comments"); - drop(info_json); - - let mut comments = Comments::new(); - base_comments.into_iter().for_each(|c| { - if let Parent::Id(id) = &c.parent { - comments.insert(&(id.clone()), CommentExt::from(c)); - } else { - comments.push(CommentExt::from(c)); - } - }); - - comments.vec.iter_mut().for_each(|comment| { - let replies = mem::take(&mut comment.replies); - let mut output_replies: Vec = vec![]; - - let re = Regex::new(r"\u{200b}?(@[^\t\s]+)\u{200b}?").unwrap(); - for reply in replies { - if let Some(replyee_match) = re.captures(&reply.value.text){ - let full_match = replyee_match.get(0).expect("This always exists"); - let text = reply. - value. - text[0..full_match.start()] - .to_owned() - + - &reply - .value - .text[full_match.end()..]; - let text: &str = text.trim().trim_matches('\u{200b}'); - - let replyee = replyee_match.get(1).expect("This should exist").as_str(); - - - if let Some(parent) = output_replies - .iter_mut() - // .rev() - .flat_map(|com| &mut com.replies) - .flat_map(|com| &mut com.replies) - .flat_map(|com| &mut com.replies) - .filter(|com| com.value.author == replyee) - .last() - { - parent.replies.push(CommentExt::from(Comment { - text: text.to_owned(), - ..reply.value - })) - } else if let Some(parent) = output_replies - .iter_mut() - // .rev() - .flat_map(|com| &mut com.replies) - .flat_map(|com| &mut com.replies) - .filter(|com| com.value.author == replyee) - .last() - { - parent.replies.push(CommentExt::from(Comment { - text: text.to_owned(), - ..reply.value - })) - } else if let Some(parent) = output_replies - .iter_mut() - // .rev() - .flat_map(|com| &mut com.replies) - .filter(|com| com.value.author == replyee) - .last() - { - parent.replies.push(CommentExt::from(Comment { - text: text.to_owned(), - ..reply.value - })) - } else if let Some(parent) = output_replies.iter_mut() - // .rev() - .filter(|com| com.value.author == replyee) - .last() - { - parent.replies.push(CommentExt::from(Comment { - text: text.to_owned(), - ..reply.value - })) - } else { - eprintln!( - "Failed to find a parent for ('{}') both directly and via replies! The reply text was:\n'{}'\n", - replyee, - reply.value.text - ); - output_replies.push(reply); - } - } else { - output_replies.push(reply); - } - } - comment.replies = output_replies; - }); - - Ok(comments) -} - -pub async fn comments(app: &App) -> Result<()> { - let comments = get_comments(app).await?; - - let mut less = Command::new("less") - .args(["--raw-control-chars"]) - .stdin(Stdio::piped()) - .stderr(Stdio::inherit()) - .spawn() - .context("Failed to run less")?; - - let mut child = Command::new("fmt") - .args(["--uniform-spacing", "--split-only", "--width=90"]) - .stdin(Stdio::piped()) - .stderr(Stdio::inherit()) - .stdout(less.stdin.take().expect("Should be open")) - .spawn() - .context("Failed to run fmt")?; - - let mut stdin = child.stdin.take().context("Failed to open stdin")?; - std::thread::spawn(move || { - stdin - .write_all(comments.render(true).as_bytes()) - .expect("Should be able to write to stdin of fmt"); - }); - - let _ = less.wait().context("Failed to await less")?; - - Ok(()) -} - -#[cfg(test)] -mod test { - #[test] - fn test_string_replacement() { - let s = "A \n\nB\n\nC".to_owned(); - assert_eq!("A \n \n B\n \n C", s.replace('\n', "\n ")) - } -} diff --git a/src/config/default.rs b/src/config/default.rs deleted file mode 100644 index 59063f5..0000000 --- a/src/config/default.rs +++ /dev/null @@ -1,102 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -use std::path::PathBuf; - -use anyhow::{Context, Result}; - -fn get_runtime_path(name: &'static str) -> Result { - let xdg_dirs = xdg::BaseDirectories::with_prefix(PREFIX)?; - xdg_dirs - .place_runtime_file(name) - .with_context(|| format!("Failed to place runtime file: '{}'", name)) -} -fn get_data_path(name: &'static str) -> Result { - let xdg_dirs = xdg::BaseDirectories::with_prefix(PREFIX)?; - xdg_dirs - .place_data_file(name) - .with_context(|| format!("Failed to place data file: '{}'", name)) -} -fn get_config_path(name: &'static str) -> Result { - let xdg_dirs = xdg::BaseDirectories::with_prefix(PREFIX)?; - xdg_dirs - .place_config_file(name) - .with_context(|| format!("Failed to place config file: '{}'", name)) -} - -pub(super) fn create_path(path: PathBuf) -> Result { - if !path.exists() { - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent) - .with_context(|| format!("Failed to create the '{}' directory", path.display()))? - } - } - - Ok(path) -} - -pub const PREFIX: &str = "yt"; - -pub mod select { - pub fn playback_speed() -> f64 { - 2.7 - } - pub fn subtitle_langs() -> &'static str { - "" - } -} - -pub mod watch { - pub fn local_comments_length() -> usize { - 1000 - } -} - -pub mod update { - pub fn max_backlog() -> u32 { - 20 - } -} - -pub mod paths { - use std::{env::temp_dir, path::PathBuf}; - - use anyhow::Result; - - use super::{create_path, get_config_path, get_data_path, get_runtime_path, PREFIX}; - - // We download to the temp dir to avoid taxing the disk - pub fn download_dir() -> Result { - let temp_dir = temp_dir(); - - create_path(temp_dir.join(PREFIX)) - } - pub fn mpv_config_path() -> Result { - get_config_path("mpv.conf") - } - pub fn mpv_input_path() -> Result { - get_config_path("mpv.input.conf") - } - pub fn database_path() -> Result { - get_data_path("videos.sqlite") - } - pub fn config_path() -> Result { - get_config_path("config.toml") - } - pub fn last_selection_path() -> Result { - get_runtime_path("selected.yts") - } -} - -pub mod download { - pub fn max_cache_size() -> &'static str { - "3 GiB" - } -} diff --git a/src/config/definitions.rs b/src/config/definitions.rs deleted file mode 100644 index d37e6da..0000000 --- a/src/config/definitions.rs +++ /dev/null @@ -1,59 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -use std::path::PathBuf; - -use serde::Deserialize; - -#[derive(Debug, Deserialize, PartialEq)] -#[serde(deny_unknown_fields)] -pub struct ConfigFile { - pub select: Option, - pub watch: Option, - pub paths: Option, - pub download: Option, - pub update: Option, -} - -#[derive(Debug, Deserialize, PartialEq, Clone, Copy)] -#[serde(deny_unknown_fields)] -pub struct UpdateConfig { - pub max_backlog: Option, -} - -#[derive(Debug, Deserialize, PartialEq, Clone)] -#[serde(deny_unknown_fields)] -pub struct DownloadConfig { - /// This will then be converted to an u64 - pub max_cache_size: Option, -} - -#[derive(Debug, Deserialize, PartialEq, Clone)] -#[serde(deny_unknown_fields)] -pub struct SelectConfig { - pub playback_speed: Option, - pub subtitle_langs: Option, -} - -#[derive(Debug, Deserialize, PartialEq, Clone, Copy)] -#[serde(deny_unknown_fields)] -pub struct WatchConfig { - pub local_comments_length: Option, -} - -#[derive(Debug, Deserialize, PartialEq, Clone)] -#[serde(deny_unknown_fields)] -pub struct PathsConfig { - pub download_dir: Option, - pub mpv_config_path: Option, - pub mpv_input_path: Option, - pub database_path: Option, - pub last_selection_path: Option, -} diff --git a/src/config/file_system.rs b/src/config/file_system.rs deleted file mode 100644 index 5751583..0000000 --- a/src/config/file_system.rs +++ /dev/null @@ -1,112 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -use crate::config::{DownloadConfig, PathsConfig, SelectConfig, WatchConfig}; - -use super::{ - default::{create_path, download, paths, select, update, watch}, - Config, UpdateConfig, -}; - -use std::{fs::read_to_string, path::PathBuf}; - -use anyhow::{Context, Result}; -use bytes::Bytes; - -macro_rules! get { - ($default:path, $config:expr, $key_one:ident, $($keys:ident),*) => { - { - let maybe_value = get!{@option $config, $key_one, $($keys),*}; - if let Some(value) = maybe_value { - value - } else { - $default().to_owned() - } - } - }; - - (@option $config:expr, $key_one:ident, $($keys:ident),*) => { - if let Some(key) = $config.$key_one.clone() { - get!{@option key, $($keys),*} - } else { - None - } - }; - (@option $config:expr, $key_one:ident) => { - $config.$key_one - }; - - (@path_if_none $config:expr, $option_default:expr, $default:path, $key_one:ident, $($keys:ident),*) => { - { - let maybe_download_dir: Option = - get! {@option $config, $key_one, $($keys),*}; - - let down_dir = if let Some(dir) = maybe_download_dir { - PathBuf::from(dir) - } else { - if let Some(path) = $option_default { - path - } else { - $default() - .with_context(|| format!("Failed to get default path for: '{}.{}'", stringify!($key_one), stringify!($($keys),*)))? - } - }; - create_path(down_dir)? - } - }; - (@path $config:expr, $default:path, $key_one:ident, $($keys:ident),*) => { - get! {@path_if_none $config, None, $default, $key_one, $($keys),*} - }; -} - -impl Config { - pub fn from_config_file( - db_path: Option, - config_path: Option, - ) -> Result { - let config_file_path = config_path - .map(Ok) - .unwrap_or_else(|| -> Result<_> { paths::config_path() })?; - - let config: super::definitions::ConfigFile = - toml::from_str(&read_to_string(config_file_path).unwrap_or("".to_owned())) - .context("Failed to parse the config file as toml")?; - - Ok(Self { - select: SelectConfig { - playback_speed: get! {select::playback_speed, config, select, playback_speed}, - subtitle_langs: get! {select::subtitle_langs, config, select, subtitle_langs}, - }, - watch: WatchConfig { - local_comments_length: get! {watch::local_comments_length, config, watch, local_comments_length}, - }, - update: UpdateConfig { - max_backlog: get! {update::max_backlog, config, update, max_backlog}, - }, - paths: PathsConfig { - download_dir: get! {@path config, paths::download_dir, paths, download_dir}, - mpv_config_path: get! {@path config, paths::mpv_config_path, paths, mpv_config_path}, - mpv_input_path: get! {@path config, paths::mpv_input_path, paths, mpv_input_path}, - database_path: get! {@path_if_none config, db_path, paths::database_path, paths, database_path}, - last_selection_path: get! {@path config, paths::last_selection_path, paths, last_selection_path}, - }, - download: DownloadConfig { - max_cache_size: { - let bytes_str: String = - get! {download::max_cache_size, config, download, max_cache_size}; - let number: Bytes = bytes_str - .parse() - .context("Failed to parse max_cache_size")?; - number - }, - }, - }) - } -} diff --git a/src/config/mod.rs b/src/config/mod.rs deleted file mode 100644 index ea40055..0000000 --- a/src/config/mod.rs +++ /dev/null @@ -1,62 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -use std::path::PathBuf; - -use bytes::Bytes; -use serde::Serialize; - -mod default; -mod definitions; -pub mod file_system; - -#[derive(Serialize)] -pub struct Config { - pub select: SelectConfig, - pub watch: WatchConfig, - pub paths: PathsConfig, - pub download: DownloadConfig, - pub update: UpdateConfig, -} -#[derive(Serialize)] -pub struct UpdateConfig { - pub max_backlog: u32, -} -#[derive(Serialize)] -pub struct DownloadConfig { - pub max_cache_size: Bytes, -} -#[derive(Serialize)] -pub struct SelectConfig { - pub playback_speed: f64, - pub subtitle_langs: String, -} -#[derive(Serialize)] -pub struct WatchConfig { - pub local_comments_length: usize, -} -#[derive(Serialize)] -pub struct PathsConfig { - pub download_dir: PathBuf, - pub mpv_config_path: PathBuf, - pub mpv_input_path: PathBuf, - pub database_path: PathBuf, - pub last_selection_path: PathBuf, -} - -// pub fn status_path() -> anyhow::Result { -// const STATUS_PATH: &str = "running.info.json"; -// get_runtime_path(STATUS_PATH) -// } - -// pub fn subscriptions() -> anyhow::Result { -// const SUBSCRIPTIONS: &str = "subscriptions.json"; -// get_data_path(SUBSCRIPTIONS) -// } diff --git a/src/constants.rs b/src/constants.rs deleted file mode 100644 index 54cae89..0000000 --- a/src/constants.rs +++ /dev/null @@ -1,11 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -pub const HELP_STR: &str = include_str!("./select/selection_file/help.str"); diff --git a/src/download/download_options.rs b/src/download/download_options.rs deleted file mode 100644 index e93170a..0000000 --- a/src/download/download_options.rs +++ /dev/null @@ -1,121 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -use serde_json::{json, Value}; - -use crate::{app::App, storage::video_database::YtDlpOptions}; - -// { -// "ratelimit": conf.ratelimit if conf.ratelimit > 0 else None, -// "retries": conf.retries, -// "merge_output_format": conf.merge_output_format, -// "restrictfilenames": conf.restrict_filenames, -// "ignoreerrors": False, -// "postprocessors": [{"key": "FFmpegMetadata"}], -// "logger": _ytdl_logger -// } - -pub fn download_opts( - app: &App, - additional_opts: YtDlpOptions, -) -> serde_json::Map { - match json!({ - "extract_flat": false, - "extractor_args": { - "youtube": { - "comment_sort": [ - "top" - ], - "max_comments": [ - "150", - "all", - "100" - ] - } - }, - "ffmpeg_location": env!("FFMPEG_LOCATION"), - "format": "bestvideo[height<=?1080]+bestaudio/best", - "fragment_retries": 10, - "getcomments": true, - "ignoreerrors": false, - "retries": 10, - - "writeinfojson": true, - "writeannotations": true, - "writesubtitles": true, - "writeautomaticsub": true, - - "outtmpl": { - "default": app.config.paths.download_dir.join("%(channel)s/%(title)s.%(ext)s"), - "chapter": "%(title)s - %(section_number)03d %(section_title)s [%(id)s].%(ext)s" - }, - "compat_opts": {}, - "forceprint": {}, - "print_to_file": {}, - "windowsfilenames": false, - "restrictfilenames": false, - "trim_file_names": false, - "postprocessors": [ - { - "api": "https://sponsor.ajay.app", - "categories": [ - "interaction", - "intro", - "music_offtopic", - "sponsor", - "outro", - "poi_highlight", - "preview", - "selfpromo", - "filler", - "chapter" - ], - "key": "SponsorBlock", - "when": "after_filter" - }, - { - "force_keyframes": false, - "key": "ModifyChapters", - "remove_chapters_patterns": [], - "remove_ranges": [], - "remove_sponsor_segments": [ - "sponsor" - ], - "sponsorblock_chapter_title": "[SponsorBlock]: %(category_names)l" - }, - { - "add_chapters": true, - "add_infojson": null, - "add_metadata": false, - "key": "FFmpegMetadata" - }, - { - "key": "FFmpegConcat", - "only_multi_video": true, - "when": "playlist" - } - ] - }) { - serde_json::Value::Object(mut obj) => { - obj.insert( - "subtitleslangs".to_owned(), - serde_json::Value::Array( - additional_opts - .subtitle_langs - .split(',') - .map(|val| Value::String(val.to_owned())) - .collect::>(), - ), - ); - obj - } - _ => unreachable!("This is an object"), - } -} diff --git a/src/download/mod.rs b/src/download/mod.rs deleted file mode 100644 index 56910f9..0000000 --- a/src/download/mod.rs +++ /dev/null @@ -1,303 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -use std::{collections::HashMap, str::FromStr, sync::Arc, time::Duration}; - -use crate::{ - app::App, - download::download_options::download_opts, - storage::video_database::{ - downloader::{get_next_uncached_video, set_video_cache_path}, - extractor_hash::ExtractorHash, - getters::get_video_yt_dlp_opts, - Video, YtDlpOptions, - }, -}; - -use anyhow::{bail, Context, Result}; -use bytes::Bytes; -use futures::{future::BoxFuture, FutureExt}; -use log::{debug, error, info, warn}; -use tokio::{fs, task::JoinHandle, time}; - -pub mod download_options; - -#[derive(Debug)] -pub struct CurrentDownload { - task_handle: JoinHandle>, - extractor_hash: ExtractorHash, -} - -impl CurrentDownload { - fn new_from_video(app: Arc, video: Video) -> Self { - let extractor_hash = video.extractor_hash.clone(); - - let task_handle = tokio::spawn(async move { - Downloader::actually_cache_video(&app, &video) - .await - .with_context(|| format!("Failed to cache video: '{}'", video.title))?; - Ok(()) - }); - - Self { - task_handle, - extractor_hash, - } - } -} - -enum CacheSizeCheck { - /// The video can be downloaded - Fits, - - /// The video and the current cache size together would exceed the size - TooLarge, - - /// The video would not even fit into the empty cache - ExceedsMaxCacheSize, -} - -pub struct Downloader { - current_download: Option, - video_size_cache: HashMap, - printed_warning: bool, - cached_cache_allocation: Option, -} - -impl Default for Downloader { - fn default() -> Self { - Self::new() - } -} - -impl Downloader { - pub fn new() -> Self { - Self { - current_download: None, - video_size_cache: HashMap::new(), - printed_warning: false, - cached_cache_allocation: None, - } - } - - /// Check if enough cache is available. Will wait for 10s if it's not. - async fn is_enough_cache_available( - &mut self, - app: &App, - max_cache_size: u64, - next_video: &Video, - ) -> Result { - if let Some(cdownload) = &self.current_download { - if cdownload.extractor_hash == next_video.extractor_hash { - // If the video is already being downloaded it will always fit. Otherwise the - // download would not have been started. - return Ok(CacheSizeCheck::Fits); - } - } - let cache_allocation = Self::get_current_cache_allocation(app).await?; - let video_size = self.get_approx_video_size(app, next_video).await?; - - if video_size >= max_cache_size { - error!( - "The video '{}' ({}) exceeds the maximum cache size ({})! \ - Please set a bigger maximum (`--max-cache-size`) or skip it.", - next_video.title, - Bytes::new(video_size), - Bytes::new(max_cache_size) - ); - - return Ok(CacheSizeCheck::ExceedsMaxCacheSize); - } - - if cache_allocation + video_size >= max_cache_size { - if !self.printed_warning { - warn!( - "Can't download video: '{}' ({}) as it's too large for the cache ({} of {} allocated). \ - Waiting for cache size reduction..", - next_video.title, Bytes::new(video_size), Bytes::new(cache_allocation), Bytes::new(max_cache_size) - ); - self.printed_warning = true; - self.cached_cache_allocation = Some(cache_allocation); - } - if let Some(cca) = self.cached_cache_allocation { - if cca != cache_allocation { - warn!( - "Current cache size has changed, it's now: '{}'", - Bytes::new(cache_allocation) - ); - self.cached_cache_allocation = Some(cache_allocation); - } - } else { - info!( - "Current cache size allocation: '{}'", - Bytes::new(cache_allocation) - ); - self.cached_cache_allocation = Some(cache_allocation); - } - - // Wait and hope, that a large video is deleted from the cache. - time::sleep(Duration::from_secs(10)).await; - Ok(CacheSizeCheck::TooLarge) - } else { - self.printed_warning = false; - Ok(CacheSizeCheck::Fits) - } - } - - /// The entry point to the Downloader. - /// This Downloader will periodically check if the database has changed, and then also - /// change which videos it downloads. - /// This will run, until the database doesn't contain any watchable videos - pub async fn consume(&mut self, app: Arc, max_cache_size: u64) -> Result<()> { - while let Some(next_video) = get_next_uncached_video(&app).await? { - match self - .is_enough_cache_available(&app, max_cache_size, &next_video) - .await? - { - CacheSizeCheck::Fits => (), - CacheSizeCheck::TooLarge => continue, - CacheSizeCheck::ExceedsMaxCacheSize => bail!("Giving up."), - }; - - if self.current_download.is_some() { - let current_download = self.current_download.take().expect("Is Some"); - - if current_download.task_handle.is_finished() { - current_download.task_handle.await??; - continue; - } - - if next_video.extractor_hash != current_download.extractor_hash { - info!( - "Noticed, that the next video is not the video being downloaded, replacing it ('{}' vs. '{}')!", - next_video.extractor_hash.into_short_hash(&app).await?, current_download.extractor_hash.into_short_hash(&app).await? - ); - - // Replace the currently downloading video - current_download.task_handle.abort(); - - let new_current_download = - CurrentDownload::new_from_video(Arc::clone(&app), next_video); - - self.current_download = Some(new_current_download); - } else { - // Reset the taken value - self.current_download = Some(current_download); - } - } else { - info!( - "No video is being downloaded right now, setting it to '{}'", - next_video.title - ); - let new_current_download = - CurrentDownload::new_from_video(Arc::clone(&app), next_video); - self.current_download = Some(new_current_download); - } - - time::sleep(Duration::new(1, 0)).await; - } - - info!("Finished downloading!"); - Ok(()) - } - - pub async fn get_current_cache_allocation(app: &App) -> Result { - fn dir_size(mut dir: fs::ReadDir) -> BoxFuture<'static, Result> { - async move { - let mut acc = 0; - while let Some(entry) = dir.next_entry().await? { - let size = match entry.metadata().await? { - data if data.is_dir() => { - let path = entry.path(); - let read_dir = fs::read_dir(path).await?; - - dir_size(read_dir).await? - } - data => data.len(), - }; - acc += size; - } - Ok(acc) - } - .boxed() - } - - dir_size(fs::read_dir(&app.config.paths.download_dir).await?).await - } - - async fn get_approx_video_size(&mut self, app: &App, video: &Video) -> Result { - if let Some(value) = self.video_size_cache.get(&video.extractor_hash) { - Ok(*value) - } else { - // the subtitle file size should be negligible - let add_opts = YtDlpOptions { - subtitle_langs: "".to_owned(), - }; - let opts = &download_opts(app, add_opts); - - let result = yt_dlp::extract_info(opts, &video.url, false, true) - .await - .with_context(|| { - format!("Failed to extract video information: '{}'", video.title) - })?; - - let size = if let Some(val) = result.filesize { - val - } else if let Some(val) = result.filesize_approx { - val - } else if result.duration.is_some() && result.tbr.is_some() { - let duration = result.duration.expect("Is some").ceil() as u64; - - // TODO: yt_dlp gets this from the format - let tbr = result.tbr.expect("Is Some").ceil() as u64; - - duration * tbr * (1000 / 8) - } else { - let hardcoded_default = Bytes::from_str("250 MiB").expect("This is hardcoded"); - error!( - "Failed to find a filesize for video: '{}' (Using hardcoded value of {})", - video.title, hardcoded_default - ); - hardcoded_default.as_u64() - }; - - assert_eq!( - self.video_size_cache - .insert(video.extractor_hash.clone(), size), - None - ); - - Ok(size) - } - } - - async fn actually_cache_video(app: &App, video: &Video) -> Result<()> { - debug!("Download started: {}", &video.title); - - let addional_opts = get_video_yt_dlp_opts(app, &video.extractor_hash).await?; - - let result = yt_dlp::download(&[video.url.clone()], &download_opts(app, addional_opts)) - .await - .with_context(|| format!("Failed to download video: '{}'", video.title))?; - - assert_eq!(result.len(), 1); - let result = &result[0]; - - set_video_cache_path(app, &video.extractor_hash, Some(result)).await?; - - info!( - "Video '{}' was downlaoded to path: {}", - video.title, - result.display() - ); - - Ok(()) - } -} diff --git a/src/main.rs b/src/main.rs deleted file mode 100644 index 37283a1..0000000 --- a/src/main.rs +++ /dev/null @@ -1,252 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -use std::{collections::HashMap, fs, sync::Arc}; - -use anyhow::{bail, Context, Result}; -use app::App; -use bytes::Bytes; -use cache::invalidate; -use clap::Parser; -use cli::{CacheCommand, CheckCommand, SelectCommand, SubscriptionCommand, VideosCommand}; -use config::Config; -use log::info; -use select::cmds::handle_select_cmd; -use storage::video_database::getters::get_video_by_hash; -use tokio::{ - fs::File, - io::{stdin, BufReader}, - task::JoinHandle, -}; -use url::Url; -use videos::display::format_video::FormatVideo; -use yt_dlp::wrapper::info_json::InfoJson; - -use crate::{cli::Command, storage::subscriptions::get_subscriptions}; - -pub mod app; -pub mod cli; - -pub mod cache; -pub mod comments; -pub mod config; -pub mod constants; -pub mod download; -pub mod select; -pub mod status; -pub mod storage; -pub mod subscribe; -pub mod update; -pub mod videos; -pub mod watch; - -#[tokio::main] -async fn main() -> Result<()> { - let args = cli::CliArgs::parse(); - - // The default verbosity is 1 (Warn) - let verbosity: u8 = args.verbosity + 1; - - stderrlog::new() - .module(module_path!()) - .modules(&["yt_dlp".to_owned(), "libmpv2".to_owned()]) - .quiet(args.quiet) - .show_module_names(false) - .color(stderrlog::ColorChoice::Auto) - .verbosity(verbosity as usize) - .timestamp(stderrlog::Timestamp::Off) - .init() - .expect("Let's just hope that this does not panic"); - - info!("Using verbosity level: '{} ({})'", verbosity, { - match verbosity { - 0 => "Error", - 1 => "Warn", - 2 => "Info", - 3 => "Debug", - 4.. => "Trace", - } - }); - - let app = { - let config = Config::from_config_file(args.db_path, args.config_path)?; - App::new(config).await? - }; - - match args.command.unwrap_or(Command::default()) { - Command::Download { - force, - max_cache_size, - } => { - let max_cache_size = - max_cache_size.unwrap_or(app.config.download.max_cache_size.as_u64()); - info!("Max cache size: '{}'", Bytes::new(max_cache_size)); - - if force { - invalidate(&app, true).await?; - } - - download::Downloader::new() - .consume(Arc::new(app), max_cache_size) - .await?; - } - Command::Select { cmd } => { - let cmd = cmd.unwrap_or(SelectCommand::default()); - - match cmd { - SelectCommand::File { - done, - use_last_selection, - } => select::select(&app, done, use_last_selection).await?, - _ => handle_select_cmd(&app, cmd, None).await?, - } - } - Command::Sedowa {} => { - select::select(&app, false, false).await?; - - let arc_app = Arc::new(app); - dowa(arc_app).await?; - } - Command::Dowa {} => { - let arc_app = Arc::new(app); - dowa(arc_app).await?; - } - Command::Videos { cmd } => match cmd { - VideosCommand::List { - search_query, - limit, - } => { - videos::query(&app, limit, search_query) - .await - .context("Failed to query videos")?; - } - VideosCommand::Info { hash } => { - let video = get_video_by_hash(&app, &hash.realize(&app).await?).await?; - - print!( - "{}", - (&video - .to_formatted_video(&app) - .await - .context("Failed to format video")? - .colorize()) - .to_info_display() - ); - } - }, - Command::Update { - max_backlog, - subscriptions, - } => { - let all_subs = get_subscriptions(&app).await?; - - for sub in &subscriptions { - if !all_subs.0.contains_key(sub) { - bail!( - "Your specified subscription to update '{}' is not a subscription!", - sub - ) - } - } - - let max_backlog = max_backlog.unwrap_or(app.config.update.max_backlog); - - update::update(&app, max_backlog, subscriptions, verbosity).await?; - } - Command::Subscriptions { cmd } => match cmd { - SubscriptionCommand::Add { name, url } => { - subscribe::subscribe(&app, name, url) - .await - .context("Failed to add a subscription")?; - } - SubscriptionCommand::Remove { name } => { - subscribe::unsubscribe(&app, name) - .await - .context("Failed to remove a subscription")?; - } - SubscriptionCommand::List {} => { - let all_subs = get_subscriptions(&app).await?; - - for (key, val) in all_subs.0 { - println!("{}: '{}'", key, val.url); - } - } - SubscriptionCommand::Export {} => { - let all_subs = get_subscriptions(&app).await?; - for val in all_subs.0.values() { - println!("{}", val.url); - } - } - SubscriptionCommand::Import { file, force } => { - if let Some(file) = file { - let f = File::open(file).await?; - - subscribe::import(&app, BufReader::new(f), force).await? - } else { - subscribe::import(&app, BufReader::new(stdin()), force).await? - }; - } - }, - - Command::Watch {} => watch::watch(&app).await?, - - Command::Status {} => status::show(&app).await?, - Command::Config {} => status::config(&app)?, - - Command::Database { command } => match command { - CacheCommand::Invalidate { hard } => cache::invalidate(&app, hard).await?, - CacheCommand::Maintain { all } => cache::maintain(&app, all).await?, - }, - - Command::Check { command } => match command { - CheckCommand::InfoJson { path } => { - let string = fs::read_to_string(&path) - .with_context(|| format!("Failed to read '{}' to string!", path.display()))?; - - let _: InfoJson = - serde_json::from_str(&string).context("Failed to deserialize value")?; - } - CheckCommand::UpdateInfoJson { path } => { - let string = fs::read_to_string(&path) - .with_context(|| format!("Failed to read '{}' to string!", path.display()))?; - - let _: HashMap = - serde_json::from_str(&string).context("Failed to deserialize value")?; - } - }, - Command::Comments {} => { - comments::comments(&app).await?; - } - Command::Description {} => { - todo!() - // description::description(&app).await?; - } - } - - Ok(()) -} - -async fn dowa(arc_app: Arc) -> Result<()> { - let max_cache_size = arc_app.config.download.max_cache_size; - info!("Max cache size: '{}'", max_cache_size); - - let arc_app_clone = Arc::clone(&arc_app); - let download: JoinHandle> = tokio::spawn(async move { - download::Downloader::new() - .consume(arc_app_clone, max_cache_size.as_u64()) - .await?; - - Ok(()) - }); - - watch::watch(&arc_app).await?; - download.await??; - Ok(()) -} diff --git a/src/select/cmds.rs b/src/select/cmds.rs deleted file mode 100644 index 6e71607..0000000 --- a/src/select/cmds.rs +++ /dev/null @@ -1,147 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -use crate::{ - app::App, - cli::{SelectCommand, SharedSelectionCommandArgs}, - download::download_options::download_opts, - storage::video_database::{ - self, - getters::get_video_by_hash, - setters::{add_video, set_video_options, set_video_status}, - VideoOptions, VideoStatus, - }, - update::video_entry_to_video, - videos::display::format_video::FormatVideo, -}; - -use anyhow::{bail, Context, Result}; -use futures::future::join_all; -use yt_dlp::wrapper::info_json::InfoType; - -pub async fn handle_select_cmd( - app: &App, - cmd: SelectCommand, - line_number: Option, -) -> Result<()> { - match cmd { - SelectCommand::Pick { shared } => { - handle_status_change(app, shared, line_number, VideoStatus::Pick).await?; - } - SelectCommand::Drop { shared } => { - handle_status_change(app, shared, line_number, VideoStatus::Drop).await?; - } - SelectCommand::Watched { shared } => { - handle_status_change(app, shared, line_number, VideoStatus::Watched).await?; - } - SelectCommand::Add { urls } => { - for url in urls { - let opts = download_opts( - &app, - video_database::YtDlpOptions { - subtitle_langs: "".to_owned(), - }, - ); - let entry = yt_dlp::extract_info(&opts, &url, false, true) - .await - .with_context(|| format!("Failed to fetch entry for url: '{}'", url))?; - - async fn add_entry( - app: &App, - entry: yt_dlp::wrapper::info_json::InfoJson, - ) -> Result<()> { - let video = video_entry_to_video(entry, None)?; - println!( - "{}", - (&video.to_formatted_video(app).await?.colorize()).to_line_display() - ); - add_video(app, video).await?; - - Ok(()) - } - - match entry._type { - Some(InfoType::Video) => { - add_entry(&app, entry).await?; - } - Some(InfoType::Playlist) => { - if let Some(mut entries) = entry.entries { - if !entries.is_empty() { - // Pre-warm the cache - add_entry(app, entries.remove(0)).await?; - - let futures: Vec<_> = entries - .into_iter() - .map(|entry| add_entry(&app, entry)) - .collect(); - - join_all(futures).await.into_iter().collect::>()?; - } - } else { - bail!("Your playlist does not seem to have any entries!") - } - } - other => bail!( - "Your URL should point to a video or a playlist, but points to a '{:#?}'", - other - ), - } - } - } - SelectCommand::Watch { shared } => { - let hash = shared.hash.clone().realize(app).await?; - - let video = get_video_by_hash(app, &hash).await?; - if video.cache_path.is_some() { - handle_status_change(app, shared, line_number, VideoStatus::Cached).await?; - } else { - handle_status_change(app, shared, line_number, VideoStatus::Watch).await?; - } - } - - SelectCommand::Url { shared } => { - let mut firefox = std::process::Command::new("firefox"); - firefox.args(["-P", "timesinks.youtube"]); - firefox.arg(shared.url.as_str()); - let _handle = firefox.spawn().context("Failed to run firefox")?; - } - SelectCommand::File { .. } => unreachable!("This should have been filtered out"), - } - Ok(()) -} - -async fn handle_status_change( - app: &App, - shared: SharedSelectionCommandArgs, - line_number: Option, - new_status: VideoStatus, -) -> Result<()> { - let hash = shared.hash.realize(app).await?; - let video_options = VideoOptions::new( - shared - .subtitle_langs - .unwrap_or(app.config.select.subtitle_langs.clone()), - shared.speed.unwrap_or(app.config.select.playback_speed), - ); - let priority = compute_priority(line_number, shared.priority); - - set_video_status(app, &hash, new_status, priority).await?; - set_video_options(app, &hash, &video_options).await?; - - Ok(()) -} - -fn compute_priority(line_number: Option, priority: Option) -> Option { - if let Some(pri) = priority { - Some(pri) - } else { - line_number - } -} diff --git a/src/select/mod.rs b/src/select/mod.rs deleted file mode 100644 index ca7a203..0000000 --- a/src/select/mod.rs +++ /dev/null @@ -1,173 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -use std::{ - env::{self}, - fs, - io::{BufRead, Write}, - io::{BufReader, BufWriter}, -}; - -use crate::{ - app::App, - cli::CliArgs, - constants::HELP_STR, - storage::video_database::{getters::get_videos, VideoStatus}, - videos::display::format_video::FormatVideo, -}; - -use anyhow::{bail, Context, Result}; -use clap::Parser; -use cmds::handle_select_cmd; -use futures::future::join_all; -use selection_file::process_line; -use tempfile::Builder; -use tokio::process::Command; - -pub mod cmds; -pub mod selection_file; - -pub async fn select(app: &App, done: bool, use_last_selection: bool) -> Result<()> { - let temp_file = Builder::new() - .prefix("yt_video_select-") - .suffix(".yts") - .rand_bytes(6) - .tempfile() - .context("Failed to get tempfile")?; - - if use_last_selection { - fs::copy(&app.config.paths.last_selection_path, &temp_file)?; - } else { - let matching_videos = if done { - get_videos(app, VideoStatus::ALL, None).await? - } else { - get_videos( - app, - &[ - VideoStatus::Pick, - // - VideoStatus::Watch, - VideoStatus::Cached, - ], - None, - ) - .await? - }; - - // Warmup the cache for the display rendering of the videos. - // Otherwise the futures would all try to warm it up at the same time. - if let Some(vid) = matching_videos.first() { - let _ = vid.to_formatted_video(app).await?; - } - - let mut edit_file = BufWriter::new(&temp_file); - - join_all( - matching_videos - .into_iter() - .map(|vid| async { vid.to_formatted_video_owned(app).await }) - .collect::>(), - ) - .await - .into_iter() - .try_for_each(|line| -> Result<()> { - let formatted_line = (&line?).to_select_file_display(); - - edit_file - .write_all(formatted_line.as_bytes()) - .expect("This write should not fail"); - - Ok(()) - })?; - - edit_file.write_all(HELP_STR.as_bytes())?; - edit_file.flush().context("Failed to flush edit file")?; - }; - - { - let editor = env::var("EDITOR").unwrap_or("nvim".to_owned()); - - let mut nvim = Command::new(editor); - nvim.arg(temp_file.path()); - let status = nvim.status().await.context("Falied to run nvim")?; - if !status.success() { - bail!("nvim exited with error status: {}", status) - } - } - - let read_file = temp_file.reopen()?; - fs::copy(temp_file.path(), &app.config.paths.last_selection_path) - .context("Failed to persist selection file")?; - - let reader = BufReader::new(&read_file); - - let mut line_number = 0; - for line in reader.lines() { - let line = line.context("Failed to read a line")?; - - if let Some(line) = process_line(&line)? { - line_number -= 1; - - // debug!( - // "Parsed command: `{}`", - // line.iter() - // .map(|val| format!("\"{}\"", val)) - // .collect::>() - // .join(" ") - // ); - - let arg_line = ["yt", "select"] - .into_iter() - .chain(line.iter().map(|val| val.as_str())); - - let args = CliArgs::parse_from(arg_line); - - let cmd = if let crate::cli::Command::Select { cmd } = - args.command.expect("This will be some") - { - cmd - } else { - unreachable!("This is checked in the `filter_line` function") - }; - - handle_select_cmd( - app, - cmd.expect("This value should always be some here"), - Some(line_number), - ) - .await? - } - } - - Ok(()) -} - -// // FIXME: There should be no reason why we need to re-run yt, just to get the help string. But I've -// // yet to find a way to do it with out the extra exec <2024-08-20> -// async fn get_help() -> Result { -// let binary_name = current_exe()?; -// let cmd = Command::new(binary_name) -// .args(&["select", "--help"]) -// .output() -// .await?; -// -// assert_eq!(cmd.status.code(), Some(0)); -// -// let output = String::from_utf8(cmd.stdout).expect("Our help output was not utf8?"); -// -// let out = output -// .lines() -// .map(|line| format!("# {}\n", line)) -// .collect::(); -// -// debug!("Returning help: '{}'", &out); -// -// Ok(out) -// } diff --git a/src/select/selection_file/duration.rs b/src/select/selection_file/duration.rs deleted file mode 100644 index a38981c..0000000 --- a/src/select/selection_file/duration.rs +++ /dev/null @@ -1,111 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -use std::str::FromStr; - -use anyhow::{Context, Result}; - -#[derive(Copy, Clone, Debug)] -pub struct Duration { - time: u32, -} - -impl FromStr for Duration { - type Err = anyhow::Error; - - fn from_str(s: &str) -> Result { - fn parse_num(str: &str, suffix: char) -> Result { - str.strip_suffix(suffix) - .with_context(|| { - format!("Failed to strip suffix '{}' of number: '{}'", suffix, str) - })? - .parse::() - .with_context(|| format!("Failed to parse '{}'", suffix)) - } - - if s == "[No Duration]" { - return Ok(Self { time: 0 }); - } - - let buf: Vec<_> = s.split(' ').collect(); - - let hours; - let minutes; - let seconds; - - assert_eq!(buf.len(), 2, "Other lengths should not happen"); - - if buf[0].ends_with('h') { - hours = parse_num(buf[0], 'h')?; - minutes = parse_num(buf[1], 'm')?; - seconds = 0; - } else if buf[0].ends_with('m') { - hours = 0; - minutes = parse_num(buf[0], 'm')?; - seconds = parse_num(buf[1], 's')?; - } else { - unreachable!( - "The first part always ends with 'h' or 'm', but was: {:#?}", - buf - ) - } - - Ok(Self { - time: (hours * 60 * 60) + (minutes * 60) + seconds, - }) - } -} - -impl From> for Duration { - fn from(value: Option) -> Self { - Self { - time: value.unwrap_or(0.0).ceil() as u32, - } - } -} - -impl std::fmt::Display for Duration { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { - const SECOND: u32 = 1; - const MINUTE: u32 = 60 * SECOND; - const HOUR: u32 = 60 * MINUTE; - - let base_hour = self.time - (self.time % HOUR); - let base_min = (self.time % HOUR) - ((self.time % HOUR) % MINUTE); - let base_sec = (self.time % HOUR) % MINUTE; - - let h = base_hour / HOUR; - let m = base_min / MINUTE; - let s = base_sec / SECOND; - - if self.time == 0 { - write!(f, "[No Duration]") - } else if h > 0 { - write!(f, "{h}h {m}m") - } else { - write!(f, "{m}m {s}s") - } - } -} -#[cfg(test)] -mod test { - use super::Duration; - - #[test] - fn test_display_duration_1h() { - let dur = Duration { time: 60 * 60 }; - assert_eq!("1h 0m".to_owned(), dur.to_string()); - } - #[test] - fn test_display_duration_30min() { - let dur = Duration { time: 60 * 30 }; - assert_eq!("30m 0s".to_owned(), dur.to_string()); - } -} diff --git a/src/select/selection_file/help.str b/src/select/selection_file/help.str deleted file mode 100644 index eb76ce5..0000000 --- a/src/select/selection_file/help.str +++ /dev/null @@ -1,12 +0,0 @@ -# Commands: -# w, watch [-p,-s,-l] Mark the video given by the hash to be watched -# wd, watched [-p,-s,-l] Mark the video given by the hash as already watched -# d, drop [-p,-s,-l] Mark the video given by the hash to be dropped -# u, url [-p,-s,-l] Open the video URL in Firefox's `timesinks.youtube` profile -# p, pick [-p,-s,-l] Reset the videos status to 'Pick' -# a, add URL Add a video, defined by the URL -# -# See `yt select --help` for more help. -# -# These lines can be re-ordered; they are executed from top to bottom. -# vim: filetype=yts conceallevel=2 concealcursor=nc colorcolumn= diff --git a/src/select/selection_file/help.str.license b/src/select/selection_file/help.str.license deleted file mode 100644 index d4d410f..0000000 --- a/src/select/selection_file/help.str.license +++ /dev/null @@ -1,9 +0,0 @@ -yt - A fully featured command line YouTube client - -Copyright (C) 2024 Benedikt Peetz -SPDX-License-Identifier: GPL-3.0-or-later - -This file is part of Yt. - -You should have received a copy of the License along with this program. -If not, see . diff --git a/src/select/selection_file/mod.rs b/src/select/selection_file/mod.rs deleted file mode 100644 index 45809fa..0000000 --- a/src/select/selection_file/mod.rs +++ /dev/null @@ -1,34 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -//! The data structures needed to express the file, which the user edits - -use anyhow::{Context, Result}; -use trinitry::Trinitry; - -pub mod duration; - -pub fn process_line(line: &str) -> Result>> { - // Filter out comments and empty lines - if line.starts_with('#') || line.trim().is_empty() { - Ok(None) - } else { - // pick 2195db "CouchRecherche? Gunnar und Han von STRG_F sind #mitfunkzuhause" "2020-04-01" "STRG_F - Live" "[1h 5m]" "https://www.youtube.com/watch?v=C8UXOaoMrXY" - - let tri = - Trinitry::new(line).with_context(|| format!("Failed to parse line '{}'", line))?; - - let mut vec = Vec::with_capacity(tri.arguments().len() + 1); - vec.push(tri.command().to_owned()); - vec.extend(tri.arguments().to_vec()); - - Ok(Some(vec)) - } -} diff --git a/src/status/mod.rs b/src/status/mod.rs deleted file mode 100644 index 7ffe8d7..0000000 --- a/src/status/mod.rs +++ /dev/null @@ -1,107 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -use anyhow::{Context, Result}; -use bytes::Bytes; - -use crate::{ - app::App, - download::Downloader, - storage::{ - subscriptions::get_subscriptions, - video_database::{getters::get_videos, VideoStatus}, - }, -}; - -macro_rules! get { - ($videos:expr, $status:ident) => { - $videos - .iter() - .filter(|vid| vid.status == VideoStatus::$status) - .count() - }; - (@changing $videos:expr, $status:ident) => { - $videos - .iter() - .filter(|vid| vid.status == VideoStatus::$status && vid.status_change) - .count() - }; -} - -pub async fn show(app: &App) -> Result<()> { - let all_videos = get_videos( - app, - &[ - VideoStatus::Pick, - // - VideoStatus::Watch, - VideoStatus::Cached, - VideoStatus::Watched, - // - VideoStatus::Drop, - VideoStatus::Dropped, - ], - None, - ) - .await?; - - // lengths - let picked_videos_len = get!(all_videos, Pick); - - let watch_videos_len = get!(all_videos, Watch); - let cached_videos_len = get!(all_videos, Cached); - let watched_videos_len = get!(all_videos, Watched); - - let drop_videos_len = get!(all_videos, Drop); - let dropped_videos_len = get!(all_videos, Dropped); - - // changing - let picked_videos_changing = get!(@changing all_videos, Pick); - - let watch_videos_changing = get!(@changing all_videos, Watch); - let cached_videos_changing = get!(@changing all_videos, Cached); - let watched_videos_changing = get!(@changing all_videos, Watched); - - let drop_videos_changing = get!(@changing all_videos, Drop); - let dropped_videos_changing = get!(@changing all_videos, Dropped); - - let subscriptions = get_subscriptions(app).await?; - let subscriptions_len = subscriptions.0.len(); - - let cache_usage_raw = Downloader::get_current_cache_allocation(app) - .await - .context("Failed to get current cache allocation")?; - let cache_usage = Bytes::new(cache_usage_raw); - println!( - "\ -Picked Videos: {picked_videos_len} ({picked_videos_changing} changing) - -Watch Videos: {watch_videos_len} ({watch_videos_changing} changing) -Cached Videos: {cached_videos_len} ({cached_videos_changing} changing) -Watched Videos: {watched_videos_len} ({watched_videos_changing} changing) - -Drop Videos: {drop_videos_len} ({drop_videos_changing} changing) -Dropped Videos: {dropped_videos_len} ({dropped_videos_changing} changing) - - - Subscriptions: {subscriptions_len} - Cache usage: {cache_usage}" - ); - - Ok(()) -} - -pub fn config(app: &App) -> Result<()> { - let config_str = toml::to_string(&app.config)?; - - print!("{}", config_str); - - Ok(()) -} diff --git a/src/storage/mod.rs b/src/storage/mod.rs deleted file mode 100644 index 6a12d8b..0000000 --- a/src/storage/mod.rs +++ /dev/null @@ -1,12 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -pub mod subscriptions; -pub mod video_database; diff --git a/src/storage/subscriptions.rs b/src/storage/subscriptions.rs deleted file mode 100644 index 22edd08..0000000 --- a/src/storage/subscriptions.rs +++ /dev/null @@ -1,140 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -//! Handle subscriptions - -use std::collections::HashMap; - -use anyhow::Result; -use log::debug; -use serde_json::{json, Value}; -use sqlx::query; -use url::Url; -use yt_dlp::wrapper::info_json::InfoType; - -use crate::app::App; - -#[derive(Clone, Debug)] -pub struct Subscription { - /// The human readable name of this subscription - pub name: String, - - /// The URL this subscription subscribes to - pub url: Url, -} - -impl Subscription { - pub fn new(name: String, url: Url) -> Self { - Self { name, url } - } -} - -/// Check whether an URL could be used as a subscription URL -pub async fn check_url(url: &Url) -> Result { - let yt_opts = match json!( { - "playliststart": 1, - "playlistend": 10, - "noplaylist": false, - "extract_flat": "in_playlist", - }) { - Value::Object(map) => map, - _ => unreachable!("This is hardcoded"), - }; - - let info = yt_dlp::extract_info(&yt_opts, url, false, false).await?; - - debug!("{:#?}", info); - - Ok(info._type == Some(InfoType::Playlist)) -} - -#[derive(Default)] -pub struct Subscriptions(pub(crate) HashMap); - -pub async fn remove_all_subscriptions(app: &App) -> Result<()> { - query!( - " - DELETE FROM subscriptions; - ", - ) - .execute(&app.database) - .await?; - - Ok(()) -} - -/// Get a list of subscriptions -pub async fn get_subscriptions(app: &App) -> Result { - let raw_subs = query!( - " - SELECT * - FROM subscriptions; - " - ) - .fetch_all(&app.database) - .await?; - - let subscriptions: HashMap = raw_subs - .into_iter() - .map(|sub| { - ( - sub.name.clone(), - Subscription::new( - sub.name, - Url::parse(&sub.url).expect("This should be valid"), - ), - ) - }) - .collect(); - - Ok(Subscriptions(subscriptions)) -} - -pub async fn add_subscription(app: &App, sub: &Subscription) -> Result<()> { - let url = sub.url.to_string(); - - query!( - " - INSERT INTO subscriptions ( - name, - url - ) VALUES (?, ?); - ", - sub.name, - url - ) - .execute(&app.database) - .await?; - - println!("Subscribed to '{}' at '{}'", sub.name, sub.url); - Ok(()) -} - -pub async fn remove_subscription(app: &App, sub: &Subscription) -> Result<()> { - let output = query!( - " - DELETE FROM subscriptions - WHERE name = ? - ", - sub.name, - ) - .execute(&app.database) - .await?; - - assert_eq!( - output.rows_affected(), - 1, - "The remove subscriptino query did effect more (or less) than one row. This is a bug." - ); - - println!("Unsubscribed from '{}' at '{}'", sub.name, sub.url); - - Ok(()) -} diff --git a/src/storage/video_database/downloader.rs b/src/storage/video_database/downloader.rs deleted file mode 100644 index ccd4ca9..0000000 --- a/src/storage/video_database/downloader.rs +++ /dev/null @@ -1,153 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -use std::path::{Path, PathBuf}; - -use anyhow::Result; -use log::debug; -use sqlx::query; -use url::Url; - -use crate::{app::App, storage::video_database::VideoStatus}; - -use super::{ExtractorHash, Video}; - -/// Returns to next video which should be downloaded. This respects the priority assigned by select. -/// It does not return videos, which are already cached. -pub async fn get_next_uncached_video(app: &App) -> Result> { - let status = VideoStatus::Watch.as_db_integer(); - - // NOTE: The ORDER BY statement should be the same as the one in [`getters::get_videos`].<2024-08-22> - let result = query!( - r#" - SELECT * - FROM videos - WHERE status = ? AND cache_path IS NULL - ORDER BY priority DESC, publish_date DESC - LIMIT 1; - "#, - status - ) - .fetch_one(&app.database) - .await; - - if let Err(sqlx::Error::RowNotFound) = result { - Ok(None) - } else { - let base = result?; - - let thumbnail_url = base - .thumbnail_url - .as_ref() - .map(|url| Url::parse(url).expect("Parsing this as url should always work")); - - let status_change = if base.status_change == 1 { - true - } else { - assert_eq!(base.status_change, 0, "Can only be 1 or 0"); - false - }; - - let video = Video { - cache_path: base.cache_path.as_ref().map(PathBuf::from), - description: base.description.clone(), - duration: base.duration, - extractor_hash: ExtractorHash::from_hash( - base.extractor_hash - .parse() - .expect("The hash in the db should be valid"), - ), - last_status_change: base.last_status_change, - parent_subscription_name: base.parent_subscription_name.clone(), - priority: base.priority, - publish_date: base.publish_date, - status: VideoStatus::from_db_integer(base.status), - status_change, - thumbnail_url, - title: base.title.clone(), - url: Url::parse(&base.url).expect("Parsing this as url should always work"), - }; - - Ok(Some(video)) - } -} - -/// Update the cached path of a video. Will be set to NULL if the path is None -/// This will also set the status to `Cached` when path is Some, otherwise it set's the status to -/// `Watch`. -pub async fn set_video_cache_path( - app: &App, - video: &ExtractorHash, - path: Option<&Path>, -) -> Result<()> { - if let Some(path) = path { - debug!( - "Setting cache path from '{}' to '{}'", - video.into_short_hash(app).await?, - path.display() - ); - - let path_str = path.display().to_string(); - let extractor_hash = video.hash().to_string(); - let status = VideoStatus::Cached.as_db_integer(); - - query!( - r#" - UPDATE videos - SET cache_path = ?, status = ? - WHERE extractor_hash = ?; - "#, - path_str, - status, - extractor_hash - ) - .execute(&app.database) - .await?; - - Ok(()) - } else { - debug!( - "Setting cache path from '{}' to NULL", - video.into_short_hash(app).await?, - ); - - let extractor_hash = video.hash().to_string(); - let status = VideoStatus::Watch.as_db_integer(); - - query!( - r#" - UPDATE videos - SET cache_path = NULL, status = ? - WHERE extractor_hash = ?; - "#, - status, - extractor_hash - ) - .execute(&app.database) - .await?; - - Ok(()) - } -} - -/// Returns the number of cached videos -pub async fn get_allocated_cache(app: &App) -> Result { - let count = query!( - r#" - SELECT COUNT(cache_path) as count - FROM videos - WHERE cache_path IS NOT NULL; -"#, - ) - .fetch_one(&app.database) - .await?; - - Ok(count.count as u32) -} diff --git a/src/storage/video_database/extractor_hash.rs b/src/storage/video_database/extractor_hash.rs deleted file mode 100644 index c956919..0000000 --- a/src/storage/video_database/extractor_hash.rs +++ /dev/null @@ -1,159 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -use std::{collections::HashMap, fmt::Display, str::FromStr}; - -use anyhow::{bail, Context, Result}; -use blake3::Hash; -use log::debug; -use tokio::sync::OnceCell; - -use crate::{app::App, storage::video_database::getters::get_all_hashes}; - -static EXTRACTOR_HASH_LENGTH: OnceCell = OnceCell::const_new(); - -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct ExtractorHash { - hash: Hash, -} - -impl Display for ExtractorHash { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.hash.fmt(f) - } -} - -#[derive(Debug, Clone)] -pub struct ShortHash(String); - -impl Display for ShortHash { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - self.0.fmt(f) - } -} - -#[derive(Debug, Clone)] -pub struct LazyExtractorHash { - value: ShortHash, -} - -impl FromStr for LazyExtractorHash { - type Err = anyhow::Error; - - fn from_str(s: &str) -> std::result::Result { - // perform some cheap validation - if s.len() > 64 { - bail!("A hash can only contain 64 bytes!"); - } - - Ok(Self { - value: ShortHash(s.to_owned()), - }) - } -} - -impl LazyExtractorHash { - /// Turn the [`LazyExtractorHash`] into the [`ExtractorHash`] - pub async fn realize(self, app: &App) -> Result { - ExtractorHash::from_short_hash(app, &self.value).await - } -} - -impl ExtractorHash { - pub fn from_hash(hash: Hash) -> Self { - Self { hash } - } - pub async fn from_short_hash(app: &App, s: &ShortHash) -> Result { - Ok(Self { - hash: Self::short_hash_to_full_hash(app, s).await?, - }) - } - - pub fn hash(&self) -> &Hash { - &self.hash - } - - pub async fn into_short_hash(&self, app: &App) -> Result { - let needed_chars = if let Some(needed_chars) = EXTRACTOR_HASH_LENGTH.get() { - *needed_chars - } else { - let needed_chars = self - .get_needed_char_len(app) - .await - .context("Failed to calculate needed char length")?; - EXTRACTOR_HASH_LENGTH - .set(needed_chars) - .expect("This should work at this stage"); - - needed_chars - }; - - Ok(ShortHash( - self.hash() - .to_hex() - .chars() - .take(needed_chars) - .collect::(), - )) - } - - async fn short_hash_to_full_hash(app: &App, s: &ShortHash) -> Result { - let all_hashes = get_all_hashes(app) - .await - .context("Failed to fetch all extractor -hashesh from database")?; - - let needed_chars = s.0.len(); - - for hash in all_hashes { - if hash.to_hex()[..needed_chars] == s.0 { - return Ok(hash); - } - } - - bail!("Your shortend hash, does not match a real hash (this is probably a bug)!"); - } - - async fn get_needed_char_len(&self, app: &App) -> Result { - debug!("Calculating the needed hash char length"); - let all_hashes = get_all_hashes(app) - .await - .context("Failed to fetch all extractor -hashesh from database")?; - - let all_char_vec_hashes = all_hashes - .into_iter() - .map(|hash| hash.to_hex().chars().collect::>()) - .collect::>>(); - - // This value should be updated later, if not rust will panic in the assertion. - let mut needed_chars: usize = 1000; - 'outer: for i in 1..64 { - let i_chars: Vec = all_char_vec_hashes - .iter() - .map(|vec| vec.iter().take(i).collect::()) - .collect(); - - let mut uniqnes_hashmap: HashMap = HashMap::new(); - for ch in i_chars { - if let Some(()) = uniqnes_hashmap.insert(ch, ()) { - // The key was already in the hash map, thus we have a duplicated char and need - // at least one char more - continue 'outer; - } - } - - needed_chars = i; - break 'outer; - } - - assert!(needed_chars <= 64, "Hashes are only 64 bytes long"); - - Ok(needed_chars) - } -} diff --git a/src/storage/video_database/getters.rs b/src/storage/video_database/getters.rs deleted file mode 100644 index 29dd014..0000000 --- a/src/storage/video_database/getters.rs +++ /dev/null @@ -1,345 +0,0 @@ -// yt - A fully featured command line YouTube client -// -// Copyright (C) 2024 Benedikt Peetz -// SPDX-License-Identifier: GPL-3.0-or-later -// -// This file is part of Yt. -// -// You should have received a copy of the License along with this program. -// If not, see . - -//! These functions interact with the storage db in a read-only way. They are added on-demaned (as -//! you could theoretically just could do everything with the `get_videos` function), as -//! performance or convince requires. -use std::{fs::File, path::PathBuf}; - -use anyhow::{bail, Context, Result}; -use blake3::Hash; -use log::debug; -use sqlx::{query, QueryBuilder, Row, Sqlite}; -use url::Url; -use yt_dlp::wrapper::info_json::InfoJson; - -use crate::{ - app::App, - storage::{ - subscriptions::Subscription, - video_database::{extractor_hash::ExtractorHash, Video}, - }, -}; - -use super::{MpvOptions, VideoOptions, VideoStatus, YtDlpOptions}; - -macro_rules! video_from_record { - ($record:expr) => { - let thumbnail_url = if let Some(url) = &$record.thumbnail_url { - Some(Url::parse(&url).expect("Parsing this as url should always work")) - } else { - None - }; - - Ok(Video { - cache_path: $record.cache_path.as_ref().map(|val| PathBuf::from(val)), - description: $record.description.clone(), - duration: $record.duration, - extractor_hash: ExtractorHash::from_hash( - $record - .extractor_hash - .parse() - .expect("The db hash should be a valid blake3 hash"), - ), - last_status_change: $record.last_status_change, - parent_subscription_name: $record.parent_subscription_name.clone(), - publish_date: $record.publish_date, - status: VideoStatus::from_db_integer($record.status), - thumbnail_url, - title: $record.title.clone(), - url: Url::parse(&$record.url).expect("Parsing this as url should always work"), - priority: $record.priority, - status_change: if $record.status_change == 1 { - true - } else { - assert_eq!($record.status_change, 0); - false - }, - }) - }; -} - -/// Get the lines to display at the selection file -/// [`changing` = true]: Means that we include *only* videos, that have the `status_changing` flag set -/// [`changing` = None]: Means that we include *both* videos, that have the `status_changing` flag set and not set -pub async fn get_videos( - app: &App, - allowed_states: &[VideoStatus], - changing: Option, -) -> Result> { - let mut qb: QueryBuilder = QueryBuilder::new( - "\ - SELECT * - FROM videos - WHERE status IN ", - ); - - qb.push("("); - allowed_states - .iter() - .enumerate() - .for_each(|(index, state)| { - qb.push("'"); - qb.push(state.as_db_integer()); - qb.push("'"); - - if index != allowed_states.len() - 1 { - qb.push(","); - } - }); - qb.push(")"); - - if let Some(val) = changing { - if val { - qb.push(" AND status_change = 1"); - } else { - qb.push(" AND status_change = 0"); - } - } - - qb.push("\n ORDER BY priority DESC, publish_date DESC;"); - - debug!("Will run: \"{}\"", qb.sql()); - - let videos = qb.build().fetch_all(&app.database).await.with_context(|| { - format!( - "Failed to query videos with states: '{}'", - allowed_states.iter().fold(String::new(), |mut acc, state| { - acc.push(' '); - acc.push_str(state.as_str()); - acc - }), - ) - })?; - - let real_videos: Vec