Compare commits

..

139 commits

Author SHA1 Message Date
sledgehammer999
0188e11dd7
Bump to 5.0.3 2024-12-16 01:51:32 +02:00
sledgehammer999
1dc348539b
Update Changelog 2024-12-16 01:49:38 +02:00
sledgehammer999
241a0e91bf
Sync translations from Transifex and run lupdate 2024-12-16 01:49:09 +02:00
Vladimir Golovnev
68f7295500
Avoid race condition when update tracker entries
PR #21995.
2024-12-15 17:50:19 +03:00
Vladimir Golovnev
53adb7bfa8
Backport changes to v5.0.x branch
PR #21898.
2024-12-09 07:04:06 +03:00
Giacomo411
6128f6eecc
NSIS: Update Italian translation
PR #21920.
2024-12-08 12:18:07 +02:00
sledgehammer999
d156a44f8d
WebUI: Fix reloading page after login
Manual backport of PR  #21832
Original author: Evgenii Ryshkov
See commit: 1e851b3637
2024-12-08 12:15:15 +02:00
Thomas Piccirello
c3c7f28bad
WebUI: Fix removing tracker URL with '|' character
Closes #19074.
PR #21346.
2024-12-07 23:47:49 +02:00
Chocobo1
9ac14cdf9f
Don't follow symlink when creating torrents on Windows
Now on Windows, it won't follow/include .lnk files when creating torrents.
Note that libtorrent will throw errors if we force adding .lnk files.

Non-Windows OS will still follow symlinks.

Closes #13286.
PR #21944.
2024-12-07 21:19:46 +03:00
Vladimir Golovnev
b899ea8c40
Use cached current time when parse RSS feed
PR #21959.
2024-12-07 11:12:31 +03:00
Vladimir Golovnev
0d7c367332
Avoid redundant requests of announce entries from libtorrent
PR #21949.
2024-12-06 20:00:27 +03:00
wavygecko
22826499d5
Don't add duplicate episodes to previously matched
PR #21917.
2024-11-28 15:12:17 +03:00
Vladimir Golovnev
dbfd830b56
Avoid repeatedly creating the same QDateTime values
PR #21904.
2024-11-26 15:11:07 +03:00
Vladimir Golovnev
ad3348b95f
Fix incorrect SQL column definition
PR #21874.
2024-11-23 11:25:40 +03:00
Bartu Özen
44b08fcb74
WebAPI: Fix incorrect key in torrent creator
PR #21879.
2024-11-23 11:22:04 +03:00
Vladimir Golovnev
71b752baf3
Discard obsolete "state update" events after torrent is reloaded
PR #21873.
Closes #21827.
2024-11-23 11:21:17 +03:00
sledgehammer999
15b6091261
Bump to 5.0.2 2024-11-17 23:25:16 +02:00
sledgehammer999
abe457389d
Update Changelog 2024-11-17 23:22:51 +02:00
sledgehammer999
abce4cd1bc
Sync translations from Transifex and run lupdate 2024-11-17 23:22:09 +02:00
3gf8jv4dv
2bfb336905
NSIS: Update Traditional Chinese translation
PR #21694.

---------

Co-authored-by: Chocobo1 <Chocobo1@users.noreply.github.com>
2024-11-17 22:45:24 +02:00
3gf8jv4dv
2dee65fa52
NSIS: Update Simplified Chinese translation
PR #21693.

---------

Co-authored-by: Chocobo1 <Chocobo1@users.noreply.github.com>
2024-11-17 22:45:23 +02:00
Ikko Eltociear Ashimine
423b3ed9bf
NSIS: update luxembourgish
PR #21456.
2024-11-17 22:45:18 +02:00
Vladimir Golovnev
3454f064f0
Backport changes in v5.0.x branch
PR #21698.
2024-11-17 10:50:54 +03:00
Chocobo1
ac9ca4f452
Don't apply Mark-of-the-Web on existing files
`TorrentImpl::isDownloading()` was excessively broad which included unexpected events for the
case here. So use the underlying state directly.

Closes #21788.
PR #21836.
2024-11-16 16:04:51 +03:00
Chocobo1
09899a7d0d
Avoid reapplying Mark-of-the-Web when it already exists
Also use scope guards to handle resources.

Related #21788.
PR #21806.
2024-11-14 10:14:52 +03:00
Hanabishi
9ab3c573dc
WebUI: fix color scheme for iframes
A backport of #21750 as a follow up to #21748.

Original PR #21750.
PR #21810.
2024-11-11 19:03:40 +08:00
Vladimir Golovnev
993eb25323
Preserve initial torrent progress while checking resume data
PR #21784.
2024-11-10 12:51:17 +03:00
sledgehammer999
1e27e6504e
Merge pull request #21748 from sledgehammer999/backport_webui_color_switcher
WebUI: Add color scheme switcher (v5_0_x)

Bacport of #21613
2024-11-09 12:15:47 +02:00
Vladimir Golovnev
330dce6aa2
Correctly handle "torrent finished" events
PR #21786.
Closes #21699.
2024-11-08 11:47:37 +03:00
Vladimir Golovnev
39b965af48
Check real palette darkness to detect "dark theme"
`QStyleHints::colorScheme()` returns chosen color scheme even if current style doesn't support it and uses different palette.

PR #21771.
2024-11-08 11:47:26 +03:00
Vladimir Golovnev
5e105b0348
Optimize checking for outdated tracker endpoints
PR #21768.
2024-11-07 09:42:53 +03:00
Vladimir Golovnev
f2b2a2b034
Optimize converting TCP endpoints to strings
There may be quite a few endpoint names (one for each available network card), and they usually remain unchanged throughout the session, while previously producing such names was performed every time they were accessed. Now they are retrieved from the cache.

PR #21770.
2024-11-07 09:42:43 +03:00
Vladimir Golovnev
10499dffe9
Optimize conversion of time points from libtorrent to Qt clocks
Obtain current date time of Qt and libtorrent clocks only once
for processing entire current libtorrent alerts bunch.

PR #21764.
2024-11-05 16:46:28 +03:00
Vladimir Golovnev
eea01b94a3
Reset tracker entries when pause the session
PR #21738.
2024-11-04 16:28:04 +03:00
Vladimir Golovnev
374951f6f2
Handle Qt style names in a case insensitive way
PR #21720.
Closes #21716.
2024-11-03 10:06:30 +03:00
sledgehammer999
6d6f9bc619
Reorder code to match UI 2024-11-02 17:52:13 +02:00
sledgehammer999
84ee620fdc
Webui: Add color scheme switcher
Closes #21600
2024-11-02 17:32:55 +02:00
Vladimir Golovnev
6079b25419
Fix .torrent file could not be deleted when torrent is canceled
PR #21735.
Closes #21723.
2024-11-02 16:42:11 +03:00
Vladimir Golovnev
fe24bc825b
Remove trackers from previous category when moved to new one
PR #21717.
Closes #21637.
2024-11-02 16:42:07 +03:00
sledgehammer999
94136262a8
Bump to 5.0.1 2024-10-28 18:12:20 +02:00
sledgehammer999
f52947e27e
Update Changelog 2024-10-28 18:09:38 +02:00
sledgehammer999
315e88aee9
Sync translations from Transifex and run lupdate 2024-10-28 18:08:55 +02:00
Vladimir Golovnev
565c6d843a
Correctly delete the moved search tab
PR #21687.
Closes #21675.
2024-10-28 09:45:23 +03:00
Vladimir Golovnev
9104351c89
Backport changes to v5.0.x branch
PR #21679.
2024-10-24 12:55:50 +03:00
sledgehammer999
e58b0a65d2
Merge pull request #21663 from sledgehammer999/backport_dont_ignore_ssl_errors
Don't ignore SSL errors
2024-10-24 11:02:31 +03:00
Chocobo1
878d829904
Fix button state for SSL certificate check
A copy paste error was introduced in PR #20338.

PR #21659.
2024-10-23 08:56:55 +03:00
sledgehammer999
063f77bc6c
Allow to use Qt's default QStyle
Relevant prior PR #21553

PR #21605.
2024-10-21 20:05:54 +03:00
sledgehammer999
2a4077414f
Reorder code to match UI 2024-10-21 19:53:28 +03:00
sledgehammer999
2a44253802
Don't ignore SSL errors 2024-10-21 19:45:32 +03:00
Chocobo1
4712eba0dc
Don't change combobox index after selection
Also keep the list sorted.

PR #21599.
2024-10-21 15:49:18 +03:00
Hanabishi
983b7814aa
Add "Simple pread/pwrite" disk IO type
PR #21300.
2024-10-21 15:47:28 +03:00
Vladimir Golovnev
e082a21751
Improve color scheme change detection
* Fix pieces bars won't correctly detect color scheme change with Qt 6.8.
* Update RSS article content view on color scheme changed.

PR #21625.
Closes #21327.
2024-10-21 09:51:37 +03:00
dyseg
7dd1d1bac8
Free resources allocated by web session once it is destructed
PR #21618.
Closes #20873.
2024-10-21 09:48:24 +03:00
Chocobo1
49f57b1049
WebUI: fix 'rename files' dialog cannot be opened more than once
Added an IIFE around the whole script to suppress variable redeclaration errors.

Closes #21614.
Original PR #21620.
PR #21621.
2024-10-20 16:07:13 +08:00
Vladimir Golovnev
fbf68a0649
Correctly apply filename filter when !qB extension is enabled
PR #21628.
Closes #21624.
2024-10-19 13:39:12 +03:00
xavier2k6
39229dc06a
Sync flag icons with upstream
* Release: 7.2.3
* Contains bug fixes & additional flags

PR #21220.
2024-10-14 11:54:52 +03:00
Vladimir Golovnev
bb314e1555
Correctly handle "torrent finished after move" event
PR #21596.
Closes #21576.
2024-10-14 11:52:56 +03:00
Vladimir Golovnev
a3a8b15828
Always notify user about duplicate torrent
PR #21480.
Closes #21475.
2024-10-14 11:52:47 +03:00
Vladimir Golovnev
b579afe1aa
Allow to choose Qt style
PR #21553.
2024-10-11 16:09:59 +03:00
stalkerok
93096dba56
Disable the ability to create torrents with a piece size of 256MiB
Disabling will reduce the number of users experiencing this issue.
https://github.com/qbittorrent/qBittorrent/issues/21011

PR #21295.
2024-10-10 15:40:05 +03:00
Vladimir Golovnev
6379c33964
Disable "Move to trash" option by default
PR #21528.
2024-10-10 14:16:37 +03:00
Chocobo1
84372de675
Import correct libraries
Fixes "plugin not supported" errors with python 3.8.

PR #21539.
2024-10-10 16:29:51 +08:00
skomerko
403b7c7c35
WebUI: Use proper text color to highlight items in all filter lists
Previously, text color of selected filter items was not applied correctly in all situations, making them difficult to read.
This improves existing styles so that text is always correctly distinguished from the background.

This fixes issue from second post in https://github.com/qbittorrent/qBittorrent/issues/21426

PR #21507.
2024-10-07 22:13:50 +08:00
skomerko
b2fab43865
WebUI: Don't load Tabs & dynamicTable stylesheets in Properties panel
This removes duplicate stylesheet imports that caused the transfer list to be completely collapsed in Chrome-based browsers.

Closes #21426.
PR #21506.
2024-10-07 22:03:54 +08:00
Vladimir Golovnev
387821267f
Don't try to apply Mark-of-the-Web to nonexistent files
Trying to apply it to a nonexistent file is unacceptable, as it may unexpectedly create such a file.

PR #21488.
Closes #21440.
2024-10-05 12:28:09 +03:00
Vladimir Golovnev
dd7ef8e934
WebUI: Fix incorrect row ID
Incorrect row ID prevented the "Torrent content removing mode" option from being displayed on some platforms.

PR #21481.
2024-10-04 14:11:45 +03:00
sledgehammer999
cce295faeb
Bump to 5.0.0 2024-09-29 20:53:45 +03:00
sledgehammer999
db5479ea01
Update Changelog 2024-09-29 20:49:43 +03:00
sledgehammer999
e1216c4c9a
Sync translations from Transifex and run lupdate 2024-09-29 20:36:58 +03:00
sledgehammer999
f4a0868426
Make Program Updater choose the same build for download
We're probably stuck offering the duo of RC_1_2 and RC_2_0 for some
time in the future. So hardcode the choices and make the Program Updater
choose the variant the user currently uses.
2024-09-29 20:28:10 +03:00
sledgehammer999
59a5fcf7d0
Sync translations from Transifex and run lupdate 2024-09-13 11:10:38 +03:00
Vladimir Golovnev
f9a2b02a8d
Backport changes to v5.0.x branch
PR #21241.
2024-09-12 08:42:52 +03:00
skomerko
04f6a565f3
WebUI: Provide 'Merge trackers to existing torrent' option
PR #21302.
2024-09-11 19:18:17 +03:00
Vladimir Golovnev
3e96048ee4
Apply "merge trackers" logic regardless of way the torrent is added
PR #21299.
2024-09-07 09:13:19 +04:00
Prince Gupta
d4ccf3001c
Fix highlighted piece color
PR #20971.
2024-09-02 16:17:57 +03:00
skomerko
64506f16bd
WebUI: Provide 'Use Category paths in Manual Mode' option
PR #21223.
2024-08-26 13:10:05 +03:00
sledgehammer999
24a7a835af
Create new resources for this branch for Transifex 2024-08-26 01:11:05 +03:00
sledgehammer999
93b9bf9552
Sync translations from Transifex and run lupdate 2024-08-26 01:05:21 +03:00
Vladimir Golovnev
f4125601de
Refresh search results colors once color scheme is changed
* Refresh search results colors once color scheme is changed
* Improve color of visited search result items

PR #21189.
Closes #21187.
2024-08-21 15:12:07 +03:00
sledgehammer999
2d67729617
Bump to v5.0.0rc1 2024-08-18 23:21:21 +03:00
sledgehammer999
878ebbed41
Update Changelog 2024-08-18 23:17:25 +03:00
Vladimir Golovnev
c61c3d7cd8
Backport changes to v5.0.x branch
PR #21164.
2024-08-16 07:17:21 +03:00
skomerko
978fbbdc0d
WebUI: Always create generic filter items
PR #21188.
2024-08-15 20:37:19 +03:00
stalkerok
63689cf763
Add a flag about the connection peers are using NAT hole punching
PR #21052.
2024-08-15 20:33:45 +03:00
thalieht
cebc72d3cf
WebUI: Add missing columns in transfer list
* Incomplete Save Path
* Info Hash v1
* Info Hash v2

PR #21158.
2024-08-15 20:32:40 +03:00
Vladimir Golovnev
a67bd271c6
Refresh pieces bar colors once color scheme is changed
PR #21183.
Closes #21155.
2024-08-13 09:37:47 +03:00
skomerko
a8cffbb205
WebUI: Clear trackerList on full update
Like other similar data structures, trackerList also need to be cleared in the event of a full sync update.

PR #21148.
2024-08-11 14:20:45 +03:00
Vladimir Golovnev
7dfb0110d4
Fix Incomplete Save Path cannot be changed for torrents without metadata
PR #21152.
Closes #21140.
2024-08-08 08:22:54 +03:00
Vladimir Golovnev
3ad8fcbdd2
Hide zero status filters when torrents removed
PR #21150.
Closes #21146.
2024-08-08 08:22:51 +03:00
Vladimir Golovnev
195eae5f3d
Backport changes to v5.0.x branch
PR #20996.
2024-08-02 21:22:49 +03:00
Hanabishi
920ae26f7b
WebUI: Fix Torrent Management Mode selector
PR #21053.
2024-07-15 17:40:17 +03:00
David Newhall
09ed0d6b66
WebAPI: Add root_path to torrent/info result
PR #21066.
Closes #21057.
2024-07-15 08:52:52 +03:00
Vladimir Golovnev
4f0cc8aa11
Fix incorrect sorting by "private" column
PR #21041.
2024-07-15 08:52:42 +03:00
ManiMatter
4d490c84e7
Add ability to display torrent "privateness" in UI
PR #20951.

---------

Co-authored-by: Chocobo1 <Chocobo1@users.noreply.github.com>
Co-authored-by: Vladimir Golovnev <glassez@yandex.ru>
Co-authored-by: thalieht <thalieht@users.noreply.github.com>
2024-07-15 08:52:23 +03:00
Vladimir Golovnev
96607ce874
Prevent incorrect size from being used for creating array
PR #21050.
2024-07-12 08:51:08 +03:00
Vladimir Golovnev
418edc7471
Apply bulk changes to correct content widget items
PR #21006.
Closes #21001.
2024-07-08 16:51:33 +03:00
Vladimir Golovnev
bd01b7c4df
WebUI: Correctly apply changed "save path" of RSS rules
PR #21030.
Closes #20141.
2024-07-08 10:18:02 +03:00
Vladimir Golovnev
b0ac763048
Show scroll bar in Torrent Tags dialog
PR #21026.
Closes #21022.
2024-07-07 16:10:07 +03:00
Vladimir Golovnev
127d2d6f0b
Fix handling of tags containing '&' character
PR #21024.
Closes #20773.
2024-07-07 16:10:05 +03:00
Vladimir Golovnev
4149609e78
Allow to move content files to Trash instead of deleting them
PR #20252.
2024-07-07 16:09:48 +03:00
Vladimir Golovnev
78c549f83e
Use custom storage when reloading torrent
PR #20998.
2024-07-07 16:07:22 +03:00
Thomas Piccirello
a3a53e2e0e
WebUI: Fix preference name conflict
PR #20990.
2024-07-07 16:06:55 +03:00
Vladimir Golovnev
5aaa43e01d
Restore ability to use server-side translation by custom WebUI
PR #20968.
2024-06-29 21:59:22 +03:00
Chocobo1
86745d7b07
GHA CI: use static versions of AppImage builder
It does not affect the produced artifacts. The only difference is the
tool itself won't depend on some specific OS image or library version.

PR #20983.
2024-06-25 21:13:20 +03:00
Thomas Piccirello
210650a5ee
Use enabled search plugins by default in WebUI
PR #20969.
Closes #20558.
2024-06-25 21:13:20 +03:00
Chocobo1
fe93b6d0d8
Use proper casting
Previously `m_shutdownTimeout * 1000` was calculated in `int` and now it
is `qint64`.

PR #20982.
2024-06-25 21:13:19 +03:00
Chocobo1
e8b585acd8
Allow numeric types
The canonical type for `size_string` is `str`. However numeric types are also accepted in order
to accommodate poorly written plugins.

PR #20976.
2024-06-25 21:13:19 +03:00
vikas_c
cea20141a9
Show download progress for folders with zero byte size as 100 instead of 0
Fixes the download progress calculation for folders with zero size.
Previously, the progress would be Zero. Now, folders with zero size
show 100% progress.

PR #20567.
2024-06-25 21:13:19 +03:00
Chocobo1
0f5a27ed50
Improve connection handling
1. Previously unhandled connections will stay in pending state. It won't
be closed until timeout happened. This may lead to wasting system
resources. Now the (over-limit) connection is actively rejected.

2. When out-of-memory occurs here, reject the new connection instead of
throwing exception and crash.

3. Also clean up some unused bits.

PR #20961.
2024-06-25 21:13:18 +03:00
Vladimir Golovnev
c2cf898ccd
Allow to use regular expression to filter torrent content
PR #20944.
Closes #19934.
2024-06-25 21:13:18 +03:00
Chocobo1
5e5aa8a563
Add type annotations
A few code are revised because the type checker (mypy) doesn't allow
changing types on a variable.

PR #20935.
2024-06-25 21:13:18 +03:00
ManiMatter
12a4c3fda2
WebAPI: Add "private" filter for 'info' endpoint
PR #20833.

---------

Co-authored-by: Vladimir Golovnev <glassez@yandex.ru>
Co-authored-by: Chocobo1 <Chocobo1@users.noreply.github.com>
2024-06-25 21:13:17 +03:00
Vladimir Golovnev
5f50b701d2
Don't use custom "file icon provider" on Windows
PR #20936.
Closes #20908.
2024-06-25 21:13:17 +03:00
Chocobo1
9f20d9c3aa
Revise Protocol column
Add "BT" (BitTorrent) to avoid confusion about which protocol it is referring to.
Also its value doesn't need to be translated.

PR #20897.
2024-06-25 21:13:17 +03:00
Vladimir Golovnev
05e3130baa
Apply share limits when torrent downloading is finished
PR #20917.
Closes #20874.
2024-06-25 21:13:17 +03:00
Vladimir Golovnev
683492648f
Apply filename filter to subfolder names as well
PR #20902.
Closes #14480.
2024-06-25 21:13:17 +03:00
Chocobo1
2f2e158877
WebUI: unify comment format 2024-06-25 21:13:16 +03:00
BurningMop
e60e96cb0e
Add optional headers to search request
PR #20923.
2024-06-25 21:13:16 +03:00
Chocobo1
5f31208bf1
Add required manifest field
https://learn.microsoft.com/en-us/windows/win32/sbscs/application-manifests#assemblyidentity

PR #20907.
2024-06-25 21:13:16 +03:00
Chocobo1
fa58e58e70
WebUI: unify curly bracket usage 2024-06-25 21:13:16 +03:00
dependabot[bot]
671943a9a6
GHA CI: Bump Github Actions versions
PR #20913.

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Chocobo1 <Chocobo1@users.noreply.github.com>
2024-06-25 21:13:16 +03:00
Chocobo1
8bad80bcdd
Avoid redundant lookup
PR #20890.
2024-06-25 21:13:15 +03:00
thalieht
c44e300507
Increase default height of 'Share ratio limit' dialog in WebUI
PR #20866.
2024-06-25 21:13:15 +03:00
Chocobo1
318a677e8f
Avoid creating redundant temporary file list
PR #20863.
2024-06-25 21:13:15 +03:00
Chocobo1
0246df790a
Use Qt built-in methods 2024-06-25 21:13:15 +03:00
Chocobo1
782fbc1425
Use simpler conversion
The cookie value can only contain ASCII characters.
2024-06-25 21:13:15 +03:00
Chocobo1
7deccd5592
WebUI: add missing break 2024-06-25 21:13:14 +03:00
Chocobo1
4a36fe7278
WebUI: don't auto infer radix parameter 2024-06-25 21:13:14 +03:00
Chocobo1
1c5af96ad8
WebUI: simplify code 2024-06-25 21:13:14 +03:00
Chocobo1
3bb47a5410
WebUI: iterate over own properties only 2024-06-25 21:13:14 +03:00
Chocobo1
d7abeb4bf0
WebUI: use assignment operator shorthand 2024-06-25 21:13:14 +03:00
Chocobo1
a19d623ead
WebUI: prefer arrow function in callbacks 2024-06-25 21:13:13 +03:00
Chocobo1
1ef21bc2b7
WebUI: enforce usage of const whenever possible 2024-06-25 21:13:13 +03:00
Chocobo1
4687b4e8e4
WebUI: enforce string quotes coding style 2024-06-25 19:33:20 +03:00
Thomas Piccirello
d2e5163861
WebUI: Restore previously used tab on load
This PR restores the users previously used tab (Transfer, Search, RSS, etc.) when the WebUI is reloaded.

PR #20705.
2024-06-25 19:30:10 +03:00
sledgehammer999
8a15ea8026
Merge pull request #20963 from sledgehammer999/revert_webui_i18n
Revert i18next
2024-06-25 03:02:24 +03:00
sledgehammer999
2b99554813
Update WebUI translation files 2024-06-17 02:07:15 +03:00
sledgehammer999
e6638f9c19
Revert "Use client side translation for public login page"
This reverts commit ac91c1348b.
2024-06-16 23:31:19 +03:00
sledgehammer999
ec6eac2ba1
Revert "Avoid leaking user locale preference to the web"
This reverts commit 66c34ddb6e.
2024-06-16 23:14:21 +03:00
569 changed files with 129505 additions and 190238 deletions

2
.github/FUNDING.yml vendored
View file

@ -1 +1 @@
custom: "https://www.qbittorrent.org/donate" custom: "https://www.qbittorrent.org/donate.php"

View file

@ -14,10 +14,12 @@ body:
#### Prerequisites before submitting an issue! #### Prerequisites before submitting an issue!
- Read the issue reporting section in the **[contributing guidelines](https://github.com/qbittorrent/qBittorrent/blob/master/CONTRIBUTING.md)**, to know how to submit a good bug report with the required information. - Read the issue reporting section in the **[contributing guidelines](https://github.com/qbittorrent/qBittorrent/blob/master/CONTRIBUTING.md)**, to know how to submit a good bug report with the required information.
- Verify that the issue is not fixed and is reproducible in the **[latest official qBittorrent version](https://www.qbittorrent.org/download.php).** - Verify that the issue is not fixed and is reproducible in the **[latest official qBittorrent version](https://www.qbittorrent.org/download.php).**
- (Optional, but recommended) Verify that the issue is not fixed and is reproducible in the latest CI (**[macOS](https://github.com/qbittorrent/qBittorrent/actions/workflows/ci_macos.yaml?query=branch%3Amaster+event%3Apush)** / **[Ubuntu](https://github.com/qbittorrent/qBittorrent/actions/workflows/ci_ubuntu.yaml?query=branch%3Amaster+event%3Apush)** / **[Windows](https://github.com/qbittorrent/qBittorrent/actions/workflows/ci_windows.yaml?query=branch%3Amaster+event%3Apush)**) builds. - (Optional, but recommended) Verify that the issue is not fixed and is reproducible in the latest CI (currently only on **[Windows](https://github.com/qbittorrent/qBittorrent/actions/workflows/ci_windows.yaml?query=branch%3Amaster+event%3Apush)**) builds.
- Perform a **[search of the issue tracker (including closed ones)](https://github.com/qbittorrent/qBittorrent/issues?q=is%3Aissue+is%3Aopen+-label%3A%22Feature+request%22)** to avoid posting a duplicate. - Check the **[frequent/common issues list](https://github.com/qbittorrent/qBittorrent/projects/2)** and perform a **[search of the issue tracker (including closed ones)](https://github.com/qbittorrent/qBittorrent/issues)** to avoid posting a duplicate.
- Make sure this is not a support request or question, both of which are better suited for either the **[discussions section](https://github.com/qbittorrent/qBittorrent/discussions)**, **[forum](https://qbforums.shiki.hu/)**, or **[subreddit](https://www.reddit.com/r/qBittorrent/)**. - Make sure this is not a support request or question, both of which are better suited for either the **[discussions section](https://github.com/qbittorrent/qBittorrent/discussions)**, **[forum](https://qbforums.shiki.hu/)**, or **[subreddit](https://www.reddit.com/r/qBittorrent/)**.
- Verify that the **[wiki](https://github.com/qbittorrent/qBittorrent/wiki)** did not contain a suitable solution either. - Verify that the **[wiki](https://github.com/qbittorrent/qBittorrent/wiki)** did not contain a suitable solution either.
- If relevant to issue/when asked, the qBittorrent preferences file, qBittorrent.log & watched_folders.json (if using "Watched Folders" feature) must be provided.
See **[Where does qBittorrent save its settings?](https://github.com/qbittorrent/qBittorrent/wiki/Frequently-Asked-Questions#Where_does_qBittorrent_save_its_settings)**
- type: textarea - type: textarea
attributes: attributes:
@ -26,10 +28,10 @@ body:
Qt and libtorrent-rasterbar versions are required when: 1. You are using linux. 2. You are not using an official build downloaded from our website. Qt and libtorrent-rasterbar versions are required when: 1. You are using linux. 2. You are not using an official build downloaded from our website.
Example of preferred formatting: Example of preferred formatting:
qBittorrent: 4.6.6 x64 qBittorrent: 4.3.7 x64
Operating system: Windows 10 Pro x64 (22H2) 10.0.19045 Operating system: Windows 10 Pro 21H1/2009 x64
Qt: 6.4.3 Qt: 5.15.2
libtorrent-rasterbar: 1.2.19 libtorrent-rasterbar: 1.2.14
placeholder: | placeholder: |
qBittorrent: qBittorrent:
Operating system: Operating system:
@ -71,4 +73,4 @@ body:
See **[Where does qBittorrent save its settings?](https://github.com/qbittorrent/qBittorrent/wiki/Frequently-Asked-Questions#Where_does_qBittorrent_save_its_settings)** See **[Where does qBittorrent save its settings?](https://github.com/qbittorrent/qBittorrent/wiki/Frequently-Asked-Questions#Where_does_qBittorrent_save_its_settings)**
#### Note: It's the user's responsibility to redact any sensitive information #### Note: It's the user's responsibility to redact any sensitive information
validations: validations:
required: true required: false

View file

@ -12,15 +12,11 @@ jobs:
ci: ci:
name: Check name: Check
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
security-events: write
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v4 uses: actions/checkout@v4
with:
persist-credentials: false
- name: Setup python - name: Install tools
uses: actions/setup-python@v5 uses: actions/setup-python@v5
with: with:
python-version: "*" python-version: "*"
@ -36,7 +32,7 @@ jobs:
curl \ curl \
-L \ -L \
-o "${{ runner.temp }}/pandoc.tar.gz" \ -o "${{ runner.temp }}/pandoc.tar.gz" \
"https://github.com/jgm/pandoc/releases/download/3.7.0.2/pandoc-3.7.0.2-linux-amd64.tar.gz" "https://github.com/jgm/pandoc/releases/download/3.1.7/pandoc-3.1.7-linux-amd64.tar.gz"
tar -xf "${{ runner.temp }}/pandoc.tar.gz" -C "${{ github.workspace }}/.." tar -xf "${{ runner.temp }}/pandoc.tar.gz" -C "${{ github.workspace }}/.."
mv "${{ github.workspace }}/.."/pandoc-* "${{ env.pandoc_path }}" mv "${{ github.workspace }}/.."/pandoc-* "${{ env.pandoc_path }}"
# run pandoc # run pandoc
@ -46,26 +42,3 @@ jobs:
done done
# check diff, ignore "Automatically generated by ..." part # check diff, ignore "Automatically generated by ..." part
git diff -I '\.\\".*' --exit-code git diff -I '\.\\".*' --exit-code
- name: Check GitHub Actions workflow
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
pip install zizmor
IGNORE_RULEID='(.ruleId != "zizmor/template-injection")
and (.ruleId != "zizmor/unpinned-uses")'
IGNORE_ID='(.id != "zizmor/template-injection")
and (.id != "zizmor/unpinned-uses")'
zizmor \
--format sarif \
--persona auditor \
./ \
| jq "(.runs[].results |= map(select($IGNORE_RULEID)))
| (.runs[].tool.driver.rules |= map(select($IGNORE_ID)))" \
> "${{ runner.temp }}/zizmor_results.sarif"
- name: Upload zizmor results
uses: github/codeql-action/upload-sarif@v3
with:
category: zizmor
sarif_file: "${{ runner.temp }}/zizmor_results.sarif"

View file

@ -2,7 +2,8 @@ name: CI - macOS
on: [pull_request, push] on: [pull_request, push]
permissions: {} permissions:
actions: write
concurrency: concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
@ -12,15 +13,13 @@ jobs:
ci: ci:
name: Build name: Build
runs-on: macos-latest runs-on: macos-latest
permissions:
actions: write
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
libt_version: ["2.0.11", "1.2.20"] libt_version: ["2.0.10", "1.2.19"]
qbt_gui: ["GUI=ON", "GUI=OFF"] qbt_gui: ["GUI=ON", "GUI=OFF"]
qt_version: ["6.9.1"] qt_version: ["6.7.0"]
env: env:
boost_path: "${{ github.workspace }}/../boost" boost_path: "${{ github.workspace }}/../boost"
@ -29,8 +28,6 @@ jobs:
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v4 uses: actions/checkout@v4
with:
persist-credentials: false
- name: Install dependencies - name: Install dependencies
uses: Wandalen/wretry.action@v3 uses: Wandalen/wretry.action@v3
@ -52,15 +49,15 @@ jobs:
store_cache: ${{ github.ref == 'refs/heads/master' }} store_cache: ${{ github.ref == 'refs/heads/master' }}
update_packager_index: false update_packager_index: false
ccache_options: | ccache_options: |
max_size=1G max_size=2G
- name: Install boost - name: Install boost
env: env:
BOOST_MAJOR_VERSION: "1" BOOST_MAJOR_VERSION: "1"
BOOST_MINOR_VERSION: "86" BOOST_MINOR_VERSION: "85"
BOOST_PATCH_VERSION: "0" BOOST_PATCH_VERSION: "0"
run: | run: |
boost_url="https://archives.boost.io/release/${{ env.BOOST_MAJOR_VERSION }}.${{ env.BOOST_MINOR_VERSION }}.${{ env.BOOST_PATCH_VERSION }}/source/boost_${{ env.BOOST_MAJOR_VERSION }}_${{ env.BOOST_MINOR_VERSION }}_${{ env.BOOST_PATCH_VERSION }}.tar.gz" boost_url="https://boostorg.jfrog.io/artifactory/main/release/${{ env.BOOST_MAJOR_VERSION }}.${{ env.BOOST_MINOR_VERSION }}.${{ env.BOOST_PATCH_VERSION }}/source/boost_${{ env.BOOST_MAJOR_VERSION }}_${{ env.BOOST_MINOR_VERSION }}_${{ env.BOOST_PATCH_VERSION }}.tar.gz"
boost_url2="https://sourceforge.net/projects/boost/files/boost/${{ env.BOOST_MAJOR_VERSION }}.${{ env.BOOST_MINOR_VERSION }}.${{ env.BOOST_PATCH_VERSION }}/boost_${{ env.BOOST_MAJOR_VERSION }}_${{ env.BOOST_MINOR_VERSION }}_${{ env.BOOST_PATCH_VERSION }}.tar.gz" boost_url2="https://sourceforge.net/projects/boost/files/boost/${{ env.BOOST_MAJOR_VERSION }}.${{ env.BOOST_MINOR_VERSION }}.${{ env.BOOST_PATCH_VERSION }}/boost_${{ env.BOOST_MAJOR_VERSION }}_${{ env.BOOST_MINOR_VERSION }}_${{ env.BOOST_PATCH_VERSION }}.tar.gz"
set +e set +e
curl -L -o "${{ runner.temp }}/boost.tar.gz" "$boost_url" curl -L -o "${{ runner.temp }}/boost.tar.gz" "$boost_url"
@ -70,9 +67,6 @@ jobs:
tar -xf "${{ runner.temp }}/boost.tar.gz" -C "${{ github.workspace }}/.."; _exitCode="$?" tar -xf "${{ runner.temp }}/boost.tar.gz" -C "${{ github.workspace }}/.."; _exitCode="$?"
fi fi
mv "${{ github.workspace }}/.."/boost_* "${{ env.boost_path }}" mv "${{ github.workspace }}/.."/boost_* "${{ env.boost_path }}"
cd "${{ env.boost_path }}"
./bootstrap.sh
./b2 stage --stagedir=./ --with-headers
- name: Install Qt - name: Install Qt
uses: jurplel/install-qt-action@v4 uses: jurplel/install-qt-action@v4
@ -96,23 +90,23 @@ jobs:
-G "Ninja" \ -G "Ninja" \
-DBUILD_SHARED_LIBS=OFF \ -DBUILD_SHARED_LIBS=OFF \
-DCMAKE_BUILD_TYPE=RelWithDebInfo \ -DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DCMAKE_CXX_STANDARD=20 \ -DCMAKE_CXX_STANDARD=17 \
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON \ -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
-DBOOST_ROOT="${{ env.boost_path }}/lib/cmake" \ -DBOOST_ROOT="${{ env.boost_path }}" \
-Ddeprecated-functions=OFF -Ddeprecated-functions=OFF
cmake --build build cmake --build build
sudo cmake --install build sudo cmake --install build
- name: Build qBittorrent - name: Build qBittorrent
run: | run: |
CXXFLAGS="$CXXFLAGS -DQT_FORCE_ASSERTS -Werror -Wno-error=deprecated-declarations" \ CXXFLAGS="$CXXFLAGS -Werror -Wno-error=deprecated-declarations" \
LDFLAGS="$LDFLAGS -gz" \ LDFLAGS="$LDFLAGS -gz" \
cmake \ cmake \
-B build \ -B build \
-G "Ninja" \ -G "Ninja" \
-DCMAKE_BUILD_TYPE=RelWithDebInfo \ -DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON \ -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
-DBOOST_ROOT="${{ env.boost_path }}/lib/cmake" \ -DBOOST_ROOT="${{ env.boost_path }}" \
-DTESTING=ON \ -DTESTING=ON \
-DVERBOSE_CONFIGURE=ON \ -DVERBOSE_CONFIGURE=ON \
-D${{ matrix.qbt_gui }} -D${{ matrix.qbt_gui }}

View file

@ -16,8 +16,6 @@ jobs:
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v4 uses: actions/checkout@v4
with:
persist-credentials: false
- name: Setup python (auxiliary scripts) - name: Setup python (auxiliary scripts)
uses: actions/setup-python@v5 uses: actions/setup-python@v5
@ -25,7 +23,7 @@ jobs:
python-version: '3' # use default version python-version: '3' # use default version
- name: Install tools (auxiliary scripts) - name: Install tools (auxiliary scripts)
run: pip install bandit isort pycodestyle pyflakes run: pip install bandit pycodestyle pyflakes
- name: Gather files (auxiliary scripts) - name: Gather files (auxiliary scripts)
run: | run: |
@ -36,7 +34,7 @@ jobs:
- name: Lint code (auxiliary scripts) - name: Lint code (auxiliary scripts)
run: | run: |
pyflakes $PY_FILES pyflakes $PY_FILES
bandit --skip B101,B314,B405 $PY_FILES bandit --skip B314,B405 $PY_FILES
- name: Format code (auxiliary scripts) - name: Format code (auxiliary scripts)
run: | run: |
@ -44,10 +42,6 @@ jobs:
--max-line-length=1000 \ --max-line-length=1000 \
--statistics \ --statistics \
$PY_FILES $PY_FILES
isort \
--check \
--diff \
$PY_FILES
- name: Build code (auxiliary scripts) - name: Build code (auxiliary scripts)
run: | run: |
@ -56,10 +50,10 @@ jobs:
- name: Setup python (search engine) - name: Setup python (search engine)
uses: actions/setup-python@v5 uses: actions/setup-python@v5
with: with:
python-version: '3.9' python-version: '3.7'
- name: Install tools (search engine) - name: Install tools (search engine)
run: pip install bandit isort mypy pycodestyle pyflakes pyright run: pip install bandit mypy pycodestyle pyflakes pyright
- name: Gather files (search engine) - name: Gather files (search engine)
run: | run: |
@ -89,10 +83,6 @@ jobs:
--max-line-length=1000 \ --max-line-length=1000 \
--statistics \ --statistics \
$PY_FILES $PY_FILES
isort \
--check \
--diff \
$PY_FILES
- name: Build code (search engine) - name: Build code (search engine)
run: | run: |

View file

@ -2,7 +2,9 @@ name: CI - Ubuntu
on: [pull_request, push] on: [pull_request, push]
permissions: {} permissions:
actions: write
security-events: write
concurrency: concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
@ -12,27 +14,22 @@ jobs:
ci: ci:
name: Build name: Build
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
actions: write
security-events: write
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
libt_version: ["2.0.11", "1.2.20"] libt_version: ["2.0.10", "1.2.19"]
qbt_gui: ["GUI=ON", "GUI=OFF"] qbt_gui: ["GUI=ON", "GUI=OFF"]
qt_version: ["6.6.3"] qt_version: ["6.5.2"]
env: env:
boost_path: "${{ github.workspace }}/../boost" boost_path: "${{ github.workspace }}/../boost"
harden_flags: "-D_FORTIFY_SOURCE=3 -D_GLIBCXX_ASSERTIONS" harden_flags: "-D_FORTIFY_SOURCE=2 -D_GLIBCXX_ASSERTIONS"
libtorrent_path: "${{ github.workspace }}/../libtorrent" libtorrent_path: "${{ github.workspace }}/../libtorrent"
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v4 uses: actions/checkout@v4
with:
persist-credentials: false
- name: Install dependencies - name: Install dependencies
run: | run: |
@ -47,15 +44,15 @@ jobs:
store_cache: ${{ github.ref == 'refs/heads/master' }} store_cache: ${{ github.ref == 'refs/heads/master' }}
update_packager_index: false update_packager_index: false
ccache_options: | ccache_options: |
max_size=1G max_size=2G
- name: Install boost - name: Install boost
env: env:
BOOST_MAJOR_VERSION: "1" BOOST_MAJOR_VERSION: "1"
BOOST_MINOR_VERSION: "77" BOOST_MINOR_VERSION: "76"
BOOST_PATCH_VERSION: "0" BOOST_PATCH_VERSION: "0"
run: | run: |
boost_url="https://archives.boost.io/release/${{ env.BOOST_MAJOR_VERSION }}.${{ env.BOOST_MINOR_VERSION }}.${{ env.BOOST_PATCH_VERSION }}/source/boost_${{ env.BOOST_MAJOR_VERSION }}_${{ env.BOOST_MINOR_VERSION }}_${{ env.BOOST_PATCH_VERSION }}.tar.gz" boost_url="https://boostorg.jfrog.io/artifactory/main/release/${{ env.BOOST_MAJOR_VERSION }}.${{ env.BOOST_MINOR_VERSION }}.${{ env.BOOST_PATCH_VERSION }}/source/boost_${{ env.BOOST_MAJOR_VERSION }}_${{ env.BOOST_MINOR_VERSION }}_${{ env.BOOST_PATCH_VERSION }}.tar.gz"
boost_url2="https://sourceforge.net/projects/boost/files/boost/${{ env.BOOST_MAJOR_VERSION }}.${{ env.BOOST_MINOR_VERSION }}.${{ env.BOOST_PATCH_VERSION }}/boost_${{ env.BOOST_MAJOR_VERSION }}_${{ env.BOOST_MINOR_VERSION }}_${{ env.BOOST_PATCH_VERSION }}.tar.gz" boost_url2="https://sourceforge.net/projects/boost/files/boost/${{ env.BOOST_MAJOR_VERSION }}.${{ env.BOOST_MINOR_VERSION }}.${{ env.BOOST_PATCH_VERSION }}/boost_${{ env.BOOST_MAJOR_VERSION }}_${{ env.BOOST_MINOR_VERSION }}_${{ env.BOOST_PATCH_VERSION }}.tar.gz"
set +e set +e
curl -L -o "${{ runner.temp }}/boost.tar.gz" "$boost_url" curl -L -o "${{ runner.temp }}/boost.tar.gz" "$boost_url"
@ -65,9 +62,6 @@ jobs:
tar -xf "${{ runner.temp }}/boost.tar.gz" -C "${{ github.workspace }}/.."; _exitCode="$?" tar -xf "${{ runner.temp }}/boost.tar.gz" -C "${{ github.workspace }}/.."; _exitCode="$?"
fi fi
mv "${{ github.workspace }}/.."/boost_* "${{ env.boost_path }}" mv "${{ github.workspace }}/.."/boost_* "${{ env.boost_path }}"
cd "${{ env.boost_path }}"
./bootstrap.sh
./b2 stage --stagedir=./ --with-headers
- name: Install Qt - name: Install Qt
uses: jurplel/install-qt-action@v4 uses: jurplel/install-qt-action@v4
@ -91,9 +85,8 @@ jobs:
-G "Ninja" \ -G "Ninja" \
-DBUILD_SHARED_LIBS=OFF \ -DBUILD_SHARED_LIBS=OFF \
-DCMAKE_BUILD_TYPE=RelWithDebInfo \ -DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DCMAKE_CXX_STANDARD=20 \
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON \ -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
-DBOOST_ROOT="${{ env.boost_path }}/lib/cmake" \ -DBOOST_ROOT="${{ env.boost_path }}" \
-Ddeprecated-functions=OFF -Ddeprecated-functions=OFF
cmake --build build cmake --build build
sudo cmake --install build sudo cmake --install build
@ -108,14 +101,14 @@ jobs:
- name: Build qBittorrent - name: Build qBittorrent
run: | run: |
CXXFLAGS="$CXXFLAGS ${{ env.harden_flags }} -DQT_FORCE_ASSERTS -Werror" \ CXXFLAGS="$CXXFLAGS ${{ env.harden_flags }} -Werror" \
LDFLAGS="$LDFLAGS -gz" \ LDFLAGS="$LDFLAGS -gz" \
cmake \ cmake \
-B build \ -B build \
-G "Ninja" \ -G "Ninja" \
-DCMAKE_BUILD_TYPE=RelWithDebInfo \ -DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON \ -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
-DBOOST_ROOT="${{ env.boost_path }}/lib/cmake" \ -DBOOST_ROOT="${{ env.boost_path }}" \
-DCMAKE_INSTALL_PREFIX="/usr" \ -DCMAKE_INSTALL_PREFIX="/usr" \
-DTESTING=ON \ -DTESTING=ON \
-DVERBOSE_CONFIGURE=ON \ -DVERBOSE_CONFIGURE=ON \
@ -141,15 +134,16 @@ jobs:
- name: Install AppImage - name: Install AppImage
run: | run: |
sudo apt install libfuse2
curl \ curl \
-L \ -L \
-Z \ -Z \
-O https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-x86_64.AppImage \ -O https://github.com/linuxdeploy/linuxdeploy/releases/download/continuous/linuxdeploy-static-x86_64.AppImage \
-O https://github.com/linuxdeploy/linuxdeploy-plugin-qt/releases/download/continuous/linuxdeploy-plugin-qt-x86_64.AppImage \ -O https://github.com/linuxdeploy/linuxdeploy-plugin-qt/releases/download/continuous/linuxdeploy-plugin-qt-static-x86_64.AppImage \
-O https://github.com/linuxdeploy/linuxdeploy-plugin-appimage/releases/download/continuous/linuxdeploy-plugin-appimage-x86_64.AppImage -O https://github.com/linuxdeploy/linuxdeploy-plugin-appimage/releases/download/continuous/linuxdeploy-plugin-appimage-x86_64.AppImage
chmod +x \ chmod +x \
linuxdeploy-x86_64.AppImage \ linuxdeploy-static-x86_64.AppImage \
linuxdeploy-plugin-qt-x86_64.AppImage \ linuxdeploy-plugin-qt-static-x86_64.AppImage \
linuxdeploy-plugin-appimage-x86_64.AppImage linuxdeploy-plugin-appimage-x86_64.AppImage
- name: Prepare files for AppImage - name: Prepare files for AppImage
@ -162,13 +156,12 @@ jobs:
- name: Package AppImage - name: Package AppImage
run: | run: |
rm -f "${{ runner.workspace }}/Qt/${{ matrix.qt_version }}/gcc_64/plugins/sqldrivers/libqsqlmimer.so" ./linuxdeploy-static-x86_64.AppImage --appdir qbittorrent --plugin qt
./linuxdeploy-x86_64.AppImage --appdir qbittorrent --plugin qt
rm qbittorrent/apprun-hooks/* rm qbittorrent/apprun-hooks/*
cp .github/workflows/helper/appimage/export_vars.sh qbittorrent/apprun-hooks/export_vars.sh cp .github/workflows/helper/appimage/export_vars.sh qbittorrent/apprun-hooks/export_vars.sh
NO_APPSTREAM=1 \ NO_APPSTREAM=1 \
OUTPUT=upload/qbittorrent-CI_Ubuntu_x86_64.AppImage \ OUTPUT=upload/qbittorrent-CI_Ubuntu_x86_64.AppImage \
./linuxdeploy-x86_64.AppImage --appdir qbittorrent --output appimage ./linuxdeploy-static-x86_64.AppImage --appdir qbittorrent --output appimage
- name: Upload build artifacts - name: Upload build artifacts
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4

View file

@ -2,7 +2,8 @@ name: CI - WebUI
on: [pull_request, push] on: [pull_request, push]
permissions: {} permissions:
security-events: write
concurrency: concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
@ -12,8 +13,6 @@ jobs:
ci: ci:
name: Check name: Check
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
security-events: write
defaults: defaults:
run: run:
@ -22,8 +21,6 @@ jobs:
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v4 uses: actions/checkout@v4
with:
persist-credentials: false
- name: Setup nodejs - name: Setup nodejs
uses: actions/setup-node@v4 uses: actions/setup-node@v4
@ -31,15 +28,7 @@ jobs:
node-version: 'lts/*' node-version: 'lts/*'
- name: Install tools - name: Install tools
run: | run: npm install
npm install
npm ls
echo "::group::npm ls --all"
npm ls --all
echo "::endgroup::"
- name: Run tests
run: npm test
- name: Lint code - name: Lint code
run: npm run lint run: npm run lint

View file

@ -2,7 +2,8 @@ name: CI - Windows
on: [pull_request, push] on: [pull_request, push]
permissions: {} permissions:
actions: write
concurrency: concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
@ -12,13 +13,11 @@ jobs:
ci: ci:
name: Build name: Build
runs-on: windows-latest runs-on: windows-latest
permissions:
actions: write
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
libt_version: ["2.0.11", "1.2.20"] libt_version: ["2.0.10", "1.2.19"]
env: env:
boost_path: "${{ github.workspace }}/../boost" boost_path: "${{ github.workspace }}/../boost"
@ -28,8 +27,6 @@ jobs:
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v4 uses: actions/checkout@v4
with:
persist-credentials: false
- name: Setup devcmd - name: Setup devcmd
uses: ilammy/msvc-dev-cmd@v1 uses: ilammy/msvc-dev-cmd@v1
@ -67,7 +64,6 @@ jobs:
"set(VCPKG_BUILD_TYPE release)") "set(VCPKG_BUILD_TYPE release)")
# clear buildtrees after each package installation to reduce disk space requirements # clear buildtrees after each package installation to reduce disk space requirements
$packages = ` $packages = `
"boost-build:x64-windows-static-md-release",
"openssl:x64-windows-static-md-release", "openssl:x64-windows-static-md-release",
"zlib:x64-windows-static-md-release" "zlib:x64-windows-static-md-release"
${{ env.vcpkg_path }}/vcpkg.exe upgrade ` ${{ env.vcpkg_path }}/vcpkg.exe upgrade `
@ -82,10 +78,10 @@ jobs:
- name: Install boost - name: Install boost
env: env:
BOOST_MAJOR_VERSION: "1" BOOST_MAJOR_VERSION: "1"
BOOST_MINOR_VERSION: "86" BOOST_MINOR_VERSION: "85"
BOOST_PATCH_VERSION: "0" BOOST_PATCH_VERSION: "0"
run: | run: |
$boost_url="https://archives.boost.io/release/${{ env.BOOST_MAJOR_VERSION }}.${{ env.BOOST_MINOR_VERSION }}.${{ env.BOOST_PATCH_VERSION }}/source/boost_${{ env.BOOST_MAJOR_VERSION }}_${{ env.BOOST_MINOR_VERSION }}_${{ env.BOOST_PATCH_VERSION }}.tar.gz" $boost_url="https://boostorg.jfrog.io/artifactory/main/release/${{ env.BOOST_MAJOR_VERSION }}.${{ env.BOOST_MINOR_VERSION }}.${{ env.BOOST_PATCH_VERSION }}/source/boost_${{ env.BOOST_MAJOR_VERSION }}_${{ env.BOOST_MINOR_VERSION }}_${{ env.BOOST_PATCH_VERSION }}.tar.gz"
$boost_url2="https://sourceforge.net/projects/boost/files/boost/${{ env.BOOST_MAJOR_VERSION }}.${{ env.BOOST_MINOR_VERSION }}.${{ env.BOOST_PATCH_VERSION }}/boost_${{ env.BOOST_MAJOR_VERSION }}_${{ env.BOOST_MINOR_VERSION }}_${{ env.BOOST_PATCH_VERSION }}.tar.gz" $boost_url2="https://sourceforge.net/projects/boost/files/boost/${{ env.BOOST_MAJOR_VERSION }}.${{ env.BOOST_MINOR_VERSION }}.${{ env.BOOST_PATCH_VERSION }}/boost_${{ env.BOOST_MAJOR_VERSION }}_${{ env.BOOST_MINOR_VERSION }}_${{ env.BOOST_PATCH_VERSION }}.tar.gz"
curl -L -o "${{ runner.temp }}/boost.tar.gz" "$boost_url" curl -L -o "${{ runner.temp }}/boost.tar.gz" "$boost_url"
tar -xf "${{ runner.temp }}/boost.tar.gz" -C "${{ github.workspace }}/.." tar -xf "${{ runner.temp }}/boost.tar.gz" -C "${{ github.workspace }}/.."
@ -95,19 +91,11 @@ jobs:
tar -xf "${{ runner.temp }}/boost.tar.gz" -C "${{ github.workspace }}/.." tar -xf "${{ runner.temp }}/boost.tar.gz" -C "${{ github.workspace }}/.."
} }
move "${{ github.workspace }}/../boost_*" "${{ env.boost_path }}" move "${{ github.workspace }}/../boost_*" "${{ env.boost_path }}"
cd "${{ env.boost_path }}"
#.\bootstrap.bat
${{ env.vcpkg_path }}/installed/x64-windows-static-md-release/tools/boost-build/b2.exe `
stage `
toolset=msvc `
--stagedir=.\ `
--with-headers
- name: Install Qt - name: Install Qt
uses: jurplel/install-qt-action@v4 uses: jurplel/install-qt-action@v4
with: with:
version: "6.9.1" version: "6.7.3"
arch: win64_msvc2022_64
archives: qtbase qtsvg qttools archives: qtbase qtsvg qttools
cache: true cache: true
@ -121,16 +109,15 @@ jobs:
${{ env.libtorrent_path }} ${{ env.libtorrent_path }}
cd ${{ env.libtorrent_path }} cd ${{ env.libtorrent_path }}
$env:CXXFLAGS+=" /guard:cf" $env:CXXFLAGS+=" /guard:cf"
$env:LDFLAGS+=" /GUARD:CF" $env:LDFLAGS+=" /guard:cf"
cmake ` cmake `
-B build ` -B build `
-G "Ninja" ` -G "Ninja" `
-DCMAKE_BUILD_TYPE=RelWithDebInfo ` -DCMAKE_BUILD_TYPE=RelWithDebInfo `
-DCMAKE_CXX_STANDARD=20 `
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON ` -DCMAKE_EXPORT_COMPILE_COMMANDS=ON `
-DCMAKE_INSTALL_PREFIX="${{ env.libtorrent_path }}/install" ` -DCMAKE_INSTALL_PREFIX="${{ env.libtorrent_path }}/install" `
-DCMAKE_TOOLCHAIN_FILE="${{ env.vcpkg_path }}/scripts/buildsystems/vcpkg.cmake" ` -DCMAKE_TOOLCHAIN_FILE="${{ env.vcpkg_path }}/scripts/buildsystems/vcpkg.cmake" `
-DBOOST_ROOT="${{ env.boost_path }}/lib/cmake" ` -DBOOST_ROOT="${{ env.boost_path }}" `
-DBUILD_SHARED_LIBS=OFF ` -DBUILD_SHARED_LIBS=OFF `
-Ddeprecated-functions=OFF ` -Ddeprecated-functions=OFF `
-Dstatic_runtime=OFF ` -Dstatic_runtime=OFF `
@ -140,14 +127,14 @@ jobs:
- name: Build qBittorrent - name: Build qBittorrent
run: | run: |
$env:CXXFLAGS+="/DQT_FORCE_ASSERTS /WX" $env:CXXFLAGS+=" /WX"
cmake ` cmake `
-B build ` -B build `
-G "Ninja" ` -G "Ninja" `
-DCMAKE_BUILD_TYPE=RelWithDebInfo ` -DCMAKE_BUILD_TYPE=RelWithDebInfo `
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON ` -DCMAKE_EXPORT_COMPILE_COMMANDS=ON `
-DCMAKE_TOOLCHAIN_FILE="${{ env.vcpkg_path }}/scripts/buildsystems/vcpkg.cmake" ` -DCMAKE_TOOLCHAIN_FILE="${{ env.vcpkg_path }}/scripts/buildsystems/vcpkg.cmake" `
-DBOOST_ROOT="${{ env.boost_path }}/lib/cmake" ` -DBOOST_ROOT="${{ env.boost_path }}" `
-DLibtorrentRasterbar_DIR="${{ env.libtorrent_path }}/install/lib/cmake/LibtorrentRasterbar" ` -DLibtorrentRasterbar_DIR="${{ env.libtorrent_path }}/install/lib/cmake/LibtorrentRasterbar" `
-DMSVC_RUNTIME_DYNAMIC=ON ` -DMSVC_RUNTIME_DYNAMIC=ON `
-DTESTING=ON ` -DTESTING=ON `

View file

@ -14,9 +14,9 @@ jobs:
strategy: strategy:
matrix: matrix:
libt_version: ["2.0.11"] libt_version: ["2.0.10"]
qbt_gui: ["GUI=ON"] qbt_gui: ["GUI=ON"]
qt_version: ["6.9.1"] qt_version: ["6.5.2"]
env: env:
boost_path: "${{ github.workspace }}/../boost" boost_path: "${{ github.workspace }}/../boost"
@ -26,8 +26,6 @@ jobs:
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v4 uses: actions/checkout@v4
with:
persist-credentials: false
- name: Install dependencies - name: Install dependencies
run: | run: |
@ -39,10 +37,10 @@ jobs:
- name: Install boost - name: Install boost
env: env:
BOOST_MAJOR_VERSION: "1" BOOST_MAJOR_VERSION: "1"
BOOST_MINOR_VERSION: "88" BOOST_MINOR_VERSION: "85"
BOOST_PATCH_VERSION: "0" BOOST_PATCH_VERSION: "0"
run: | run: |
boost_url="https://archives.boost.io/release/${{ env.BOOST_MAJOR_VERSION }}.${{ env.BOOST_MINOR_VERSION }}.${{ env.BOOST_PATCH_VERSION }}/source/boost_${{ env.BOOST_MAJOR_VERSION }}_${{ env.BOOST_MINOR_VERSION }}_${{ env.BOOST_PATCH_VERSION }}.tar.gz" boost_url="https://boostorg.jfrog.io/artifactory/main/release/${{ env.BOOST_MAJOR_VERSION }}.${{ env.BOOST_MINOR_VERSION }}.${{ env.BOOST_PATCH_VERSION }}/source/boost_${{ env.BOOST_MAJOR_VERSION }}_${{ env.BOOST_MINOR_VERSION }}_${{ env.BOOST_PATCH_VERSION }}.tar.gz"
boost_url2="https://sourceforge.net/projects/boost/files/boost/${{ env.BOOST_MAJOR_VERSION }}.${{ env.BOOST_MINOR_VERSION }}.${{ env.BOOST_PATCH_VERSION }}/boost_${{ env.BOOST_MAJOR_VERSION }}_${{ env.BOOST_MINOR_VERSION }}_${{ env.BOOST_PATCH_VERSION }}.tar.gz" boost_url2="https://sourceforge.net/projects/boost/files/boost/${{ env.BOOST_MAJOR_VERSION }}.${{ env.BOOST_MINOR_VERSION }}.${{ env.BOOST_PATCH_VERSION }}/boost_${{ env.BOOST_MAJOR_VERSION }}_${{ env.BOOST_MINOR_VERSION }}_${{ env.BOOST_PATCH_VERSION }}.tar.gz"
set +e set +e
curl -L -o "${{ runner.temp }}/boost.tar.gz" "$boost_url" curl -L -o "${{ runner.temp }}/boost.tar.gz" "$boost_url"
@ -52,9 +50,6 @@ jobs:
tar -xf "${{ runner.temp }}/boost.tar.gz" -C "${{ github.workspace }}/.."; _exitCode="$?" tar -xf "${{ runner.temp }}/boost.tar.gz" -C "${{ github.workspace }}/.."; _exitCode="$?"
fi fi
mv "${{ github.workspace }}/.."/boost_* "${{ env.boost_path }}" mv "${{ github.workspace }}/.."/boost_* "${{ env.boost_path }}"
cd "${{ env.boost_path }}"
./bootstrap.sh
./b2 stage --stagedir=./ --with-headers
- name: Install Qt - name: Install Qt
uses: jurplel/install-qt-action@v4 uses: jurplel/install-qt-action@v4
@ -76,8 +71,7 @@ jobs:
-B build \ -B build \
-G "Ninja" \ -G "Ninja" \
-DCMAKE_BUILD_TYPE=RelWithDebInfo \ -DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DCMAKE_CXX_STANDARD=20 \ -DBOOST_ROOT="${{ env.boost_path }}" \
-DBOOST_ROOT="${{ env.boost_path }}/lib/cmake" \
-Ddeprecated-functions=OFF -Ddeprecated-functions=OFF
cmake --build build cmake --build build
sudo cmake --install build sudo cmake --install build
@ -101,7 +95,7 @@ jobs:
-B build \ -B build \
-G "Ninja" \ -G "Ninja" \
-DCMAKE_BUILD_TYPE=RelWithDebInfo \ -DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DBOOST_ROOT="${{ env.boost_path }}/lib/cmake" \ -DBOOST_ROOT="${{ env.boost_path }}" \
-DVERBOSE_CONFIGURE=ON \ -DVERBOSE_CONFIGURE=ON \
-D${{ matrix.qbt_gui }} -D${{ matrix.qbt_gui }}
PATH="${{ env.coverity_path }}/bin:$PATH" \ PATH="${{ env.coverity_path }}/bin:$PATH" \

View file

@ -16,5 +16,3 @@ ths = "ths"
[default.extend-words] [default.extend-words]
BA = "BA" BA = "BA"
helo = "helo" helo = "helo"
Pn = "Pn"
UIU = "UIU"

View file

@ -1,95 +0,0 @@
#!/usr/bin/env python3
# A pre-commit hook for checking items order in grid layouts
# Copyright (C) 2024 Mike Tzou (Chocobo1)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# In addition, as a special exception, the copyright holders give permission to
# link this program with the OpenSSL project's "OpenSSL" library (or with
# modified versions of it that use the same license as the "OpenSSL" library),
# and distribute the linked executables. You must obey the GNU General Public
# License in all respects for all of the code used other than "OpenSSL". If you
# modify file(s), you may extend this exception to your version of the file(s),
# but you are not obligated to do so. If you do not wish to do so, delete this
# exception statement from your version.
import argparse
import re
import sys
import xml.etree.ElementTree as ElementTree
from collections.abc import Callable, Sequence
from typing import Optional
def traversePostOrder(root: ElementTree.Element, visitFunc: Callable[[ElementTree.Element], None]) -> None:
stack = [(root, False)]
while len(stack) > 0:
(element, visit) = stack.pop()
if visit:
visitFunc(element)
else:
stack.append((element, True))
stack.extend((child, False) for child in reversed(element))
def modifyElement(element: ElementTree.Element) -> None:
def getSortKey(e: ElementTree.Element) -> tuple[int, int]:
if e.tag == 'item':
return (int(e.attrib['row']), int(e.attrib['column']))
return (-1, -1) # don't care
if element.tag == 'layout' and element.attrib['class'] == 'QGridLayout' and len(element) > 0:
element[:] = sorted(element, key=getSortKey)
# workaround_2a: ElementTree will unescape `&quot;` and we need to escape it back
if element.tag == 'string' and element.text is not None:
element.text = element.text.replace('"', '&quot;')
def main(argv: Optional[Sequence[str]] = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', help='Filenames to check')
args = parser.parse_args(argv)
for filename in args.filenames:
with open(filename, 'r+') as f:
orig = f.read()
root = ElementTree.fromstring(orig)
traversePostOrder(root, modifyElement)
ElementTree.indent(root, ' ')
# workaround_1: cannot use `xml_declaration=True` since it uses single quotes instead of Qt preferred double quotes
ret = f'<?xml version="1.0" encoding="UTF-8"?>\n{ElementTree.tostring(root, 'unicode')}\n'
# workaround_2b: ElementTree will turn `&quot;` into `&amp;quot;`, so revert it back
ret = ret.replace('&amp;quot;', '&quot;')
# workaround_3: Qt prefers no whitespaces in self-closing tags
ret = re.sub('<(.+) +/>', r'<\1/>', ret)
if ret != orig:
print(f'Tip: run this script to apply the fix: `python {__file__} {filename}`', file=sys.stderr)
f.seek(0)
f.write(ret)
f.truncate()
return 0
if __name__ == '__main__':
sys.exit(main())

View file

@ -26,11 +26,9 @@
# but you are not obligated to do so. If you do not wish to do so, delete this # but you are not obligated to do so. If you do not wish to do so, delete this
# exception statement from your version. # exception statement from your version.
from typing import Optional, Sequence
import argparse import argparse
import re import re
import sys
from collections.abc import Sequence
from typing import Optional
def main(argv: Optional[Sequence[str]] = None) -> int: def main(argv: Optional[Sequence[str]] = None) -> int:
@ -69,4 +67,4 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
if __name__ == '__main__': if __name__ == '__main__':
sys.exit(main()) exit(main())

View file

@ -4,13 +4,12 @@ on:
schedule: schedule:
- cron: '0 0 * * *' - cron: '0 0 * * *'
permissions: {} permissions:
pull-requests: write
jobs: jobs:
stale: stale:
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
pull-requests: write
steps: steps:
- name: Mark and close stale PRs - name: Mark and close stale PRs
uses: actions/stale@v9 uses: actions/stale@v9

4
.gitignore vendored
View file

@ -41,3 +41,7 @@ src/icons/skin/build-icons/icons/*.png
# CMake build directory # CMake build directory
build/ build/
# Web UI tools
node_modules
package-lock.json

View file

@ -1,12 +1,6 @@
repos: repos:
- repo: local - repo: local
hooks: hooks:
- id: check-grid-order
name: Check items order in grid layouts
entry: .github/workflows/helper/pre-commit/check_grid_items_order.py
language: script
files: \.ui$
- id: check-translation-tag - id: check-translation-tag
name: Check newline characters in <translation> tag name: Check newline characters in <translation> tag
entry: .github/workflows/helper/pre-commit/check_translation_tag.py entry: .github/workflows/helper/pre-commit/check_translation_tag.py
@ -19,7 +13,7 @@ repos:
- ts - ts
- repo: https://github.com/pre-commit/pre-commit-hooks.git - repo: https://github.com/pre-commit/pre-commit-hooks.git
rev: v5.0.0 rev: v4.5.0
hooks: hooks:
- id: check-json - id: check-json
name: Check JSON files name: Check JSON files
@ -69,17 +63,19 @@ repos:
- ts - ts
- repo: https://github.com/codespell-project/codespell.git - repo: https://github.com/codespell-project/codespell.git
rev: v2.4.1 rev: v2.2.6
hooks: hooks:
- id: codespell - id: codespell
name: Check spelling (codespell) name: Check spelling (codespell)
args: ["--ignore-words-list", "additionals,categor,curren,fo,indexIn,ist,ket,notin,searchin,sectionin,superseeding,te,ths"] args: ["--ignore-words-list", "additionals,curren,fo,ist,ket,searchin,superseeding,te,ths"]
exclude: | exclude: |
(?x)^( (?x)^(
.*\.desktop | .*\.desktop |
.*\.qrc | .*\.qrc |
build-aux/.* |
Changelog | Changelog |
dist/windows/installer-translations/.* | dist/windows/installer-translations/.* |
m4/.* |
src/base/3rdparty/.* | src/base/3rdparty/.* |
src/searchengine/nova3/socks.py | src/searchengine/nova3/socks.py |
src/webui/www/private/scripts/lib/.* src/webui/www/private/scripts/lib/.*
@ -88,7 +84,7 @@ repos:
- ts - ts
- repo: https://github.com/crate-ci/typos.git - repo: https://github.com/crate-ci/typos.git
rev: v1.32.0 rev: v1.16.18
hooks: hooks:
- id: typos - id: typos
name: Check spelling (typos) name: Check spelling (typos)
@ -99,8 +95,11 @@ repos:
.*\.desktop | .*\.desktop |
.*\.qrc | .*\.qrc |
\.pre-commit-config\.yaml | \.pre-commit-config\.yaml |
build-aux/.* |
Changelog | Changelog |
configure.* |
dist/windows/installer-translations/.* | dist/windows/installer-translations/.* |
m4/.* |
src/base/3rdparty/.* | src/base/3rdparty/.* |
src/searchengine/nova3/socks.py | src/searchengine/nova3/socks.py |
src/webui/www/private/scripts/lib/.* src/webui/www/private/scripts/lib/.*

View file

@ -1,7 +1,7 @@
[main] [main]
host = https://www.transifex.com host = https://www.transifex.com
[o:sledgehammer999:p:qbittorrent:r:qbittorrent_master] [o:sledgehammer999:p:qbittorrent:r:qbittorrent_v50x]
file_filter = src/lang/qbittorrent_<lang>.ts file_filter = src/lang/qbittorrent_<lang>.ts
source_file = src/lang/qbittorrent_en.ts source_file = src/lang/qbittorrent_en.ts
source_lang = en source_lang = en
@ -9,7 +9,7 @@ type = QT
minimum_perc = 23 minimum_perc = 23
lang_map = pt: pt_PT, zh: zh_CN lang_map = pt: pt_PT, zh: zh_CN
[o:sledgehammer999:p:qbittorrent:r:qbittorrent_webui] [o:sledgehammer999:p:qbittorrent:r:qbittorrent_webui_v50x]
file_filter = src/webui/www/translations/webui_<lang>.ts file_filter = src/webui/www/translations/webui_<lang>.ts
source_file = src/webui/www/translations/webui_en.ts source_file = src/webui/www/translations/webui_en.ts
source_lang = en source_lang = en

View file

@ -8,7 +8,7 @@ project(qBittorrent
# version requirements - older versions may work, but you are on your own # version requirements - older versions may work, but you are on your own
set(minBoostVersion 1.76) set(minBoostVersion 1.76)
set(minQt6Version 6.6.0) set(minQt6Version 6.5.0)
set(minOpenSSLVersion 3.0.2) set(minOpenSSLVersion 3.0.2)
set(minLibtorrent1Version 1.2.19) set(minLibtorrent1Version 1.2.19)
set(minLibtorrentVersion 2.0.10) set(minLibtorrentVersion 2.0.10)

View file

@ -2,7 +2,7 @@
Version 2, June 1991 Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc., Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
<https://fsf.org/> 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed. of this license document, but changing it is not allowed.
@ -304,7 +304,8 @@ the "copyright" line and a pointer to where the full notice is found.
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License along You should have received a copy of the GNU General Public License along
with this program; if not, see <https://www.gnu.org/licenses/>. with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail. Also add information on how to contact you by electronic and paper mail.
@ -328,8 +329,8 @@ necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker. `Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Moe Ghoul>, 1 April 1989 <signature of Ty Coon>, 1 April 1989
Moe Ghoul, President of Vice Ty Coon, President of Vice
This General Public License does not permit incorporating your program into This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may proprietary programs. If your program is a subroutine library, you may

View file

@ -1,4 +1,28 @@
Unreleased - sledgehammer999 <sledgehammer999@qbittorrent.org> - v5.1.0 Mon Dec 16th 2024 - sledgehammer999 <sledgehammer999@qbittorrent.org> - v5.0.3
- BUGFIX: Discard obsolete "state update" events after torrent is reloaded (glassez)
- BUGFIX: Fix incorrect SQL column definition (glassez)
- BUGFIX: Avoid redundant requests of announce entries from libtorrent (glassez)
- WEBUI: Fix removing tracker URL with '|' character (Thomas Piccirello)
- WEBUI: Fix reloading page after login (Evgenii Ryshkov)
- WEBAPI: Fix incorrect key in torrent creator (Bartu Özen)
- RSS: Don't add duplicate episodes to previously matched (wavygecko)
- RSS: Use cached current time when parsing RSS feed (glassez)
- WINDOWS: Don't follow symlink when creating torrents on Windows (Chocobo1)
- WINDOWS: NSIS: Update Italian translation (Giacomo411)
Sun Nov 17th 2024 - sledgehammer999 <sledgehammer999@qbittorrent.org> - v5.0.2
- BUGFIX: Remove trackers from previous category when moved to new one (glassez)
- BUGFIX: Fix `.torrent` file could not be deleted when torrent is canceled (glassez)
- BUGFIX: Reset tracker entries when pausing the session (glassez)
- BUGFIX: Check real palette darkness to detect "dark theme" (glassez)
- BUGFIX: Correctly handle "torrent finished" events (glassez)
- BUGFIX: Preserve initial torrent progress while checking resume data (glassez)
- BUGFIX: Avoid reapplying Mark-of-the-Web when it already exists (Chocobo1)
- BUGFIX: Don't apply Mark-of-the-Web on existing files (Chocobo1)
- WEBUI: Add color scheme switcher (sledgehammer999)
- SEARCH: Correctly delete the moved search tab (glassez)
- WINDOWS: Correctly save and restore Qt style setting (glassez)
- WINDOWS: NSIS: update Luxembourgish, Simplified Chinese and Traditional Chinese translations (Ikko Eltociear Ashimine, 3gf8jv4dv)
Mon Oct 28th 2024 - sledgehammer999 <sledgehammer999@qbittorrent.org> - v5.0.1 Mon Oct 28th 2024 - sledgehammer999 <sledgehammer999@qbittorrent.org> - v5.0.1
- FEATURE: Add "Simple pread/pwrite" disk IO type (Hanabishi) - FEATURE: Add "Simple pread/pwrite" disk IO type (Hanabishi)
@ -106,42 +130,6 @@ Sun Sep 29th 2024 - sledgehammer999 <sledgehammer999@qbittorrent.org> - v5.0.0
- OTHER: Minimum supported versions: Qt: 6.5, Boost: 1.76, OpenSSL: 3.0.2 - OTHER: Minimum supported versions: Qt: 6.5, Boost: 1.76, OpenSSL: 3.0.2
- OTHER: Switch to C++20 - OTHER: Switch to C++20
Mon Sep 16th 2024 - sledgehammer999 <sledgehammer999@qbittorrent.org> - v4.6.7
- BUGFIX: The updater will launch the link to the build variant you're currently using (sledgehammer999)
- BUGFIX: Focus on Download button if torrent link retrieved from the clipboard (glassez)
- WEBUI: RSS: The list of feeds wouldn't load for Apply Rule (glassez)
Sun Aug 18th 2024 - sledgehammer999 <sledgehammer999@qbittorrent.org> - v4.6.6
- BUGFIX: Fix handling of tags containing '&' character (glassez)
- BUGFIX: Show scroll bar in Torrent Tags dialog (glassez)
- BUGFIX: Apply bulk changes to correct content widget items (glassez)
- BUGFIX: Hide zero status filters when torrents are removed (glassez)
- BUGFIX: Fix `Incomplete Save Path` cannot be changed for torrents without metadata (glassez)
- WEBUI: Correctly apply changed "save path" of RSS rules (glassez)
- WEBUI: Clear tracker list on full update (skomerko)
- OTHER: Update User-Agent string for internal downloader and search engines (cayenne17)
Sun May 26th 2024 - sledgehammer999 <sledgehammer999@qbittorrent.org> - v4.6.5
- BUGFIX: Prevent app from being closed when disabling system tray icon (glassez)
- BUGFIX: Fix <kbd>Enter</kbd> key behavior in Add new torrent dialog (glassez)
- BUGFIX: Prevent invalid status filter index from being used (glassez)
- BUGFIX: Add extra offset for dialog frame (glassez)
- BUGFIX: Don't overwrite stored layout of main window with incorrect one (glassez)
- BUGFIX: Don't forget to resume "missing files" torrent when rechecking (glassez)
- WEBUI: Restore ability to use server-side translation by custom WebUI (glassez)
- WEBUI: Fix wrong peer number (Chocobo1)
- LINUX: Improve AppStream metadata (Chocobo1)
Sun Mar 24th 2024 - sledgehammer999 <sledgehammer999@qbittorrent.org> - v4.6.4
- BUGFIX: Correctly adjust "Add New torrent" dialog position in all the cases (glassez)
- BUGFIX: Change "metadata received" stop condition behavior (glassez)
- BUGFIX: Add a small delay before processing the key input of search boxes (Chocobo1)
- BUGFIX: Ensure the profile path is pointing to a directory (Chocobo1)
- RSS: Use better icons for RSS articles (glassez)
- WINDOWS: NSIS: Update French, Hungarian translations (MarcDrieu, foxi69)
- LINUX: Fix sorting when ICU isn't used (Chocobo1)
- LINUX: Fix invisible tray icon on Plasma 6 (tehcneko)
Mon Jan 15th 2024 - sledgehammer999 <sledgehammer999@qbittorrent.org> - v4.6.3 Mon Jan 15th 2024 - sledgehammer999 <sledgehammer999@qbittorrent.org> - v4.6.3
- BUGFIX: Correctly update number of filtered items (glassez) - BUGFIX: Correctly update number of filtered items (glassez)
- BUGFIX: Don't forget to store Stop condition value (glassez) - BUGFIX: Don't forget to store Stop condition value (glassez)

View file

@ -11,14 +11,14 @@ qBittorrent - A BitTorrent client in C++ / Qt
- OpenSSL >= 3.0.2 - OpenSSL >= 3.0.2
- Qt 6.6.0 - 6.x - Qt 6.5.0 - 6.x
- zlib >= 1.2.11 - zlib >= 1.2.11
- CMake >= 3.16 - CMake >= 3.16
* Compile-time only * Compile-time only
- Python >= 3.9.0 - Python >= 3.7.0
* Optional, run-time only * Optional, run-time only
* Used by the bundled search engine * Used by the bundled search engine

View file

@ -1,18 +0,0 @@
# Security Policy
qBittorrent takes the security of our software seriously, including all source code repositories managed through our GitHub organisation.
If you believe you have found a security vulnerability in qBittorrent, please report it to us as described below.
## Reporting Security Issues
Please do not report security vulnerabilities through public GitHub issues. Instead, please use GitHubs private vulnerability reporting functionality associated to this repository. Additionally, you may email us with all security-related inquiries and notifications at `security@qbittorrent.org`.
Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
1. Type of issue
2. Step-by-step instructions to reproduce the issue
3. Proof-of-concept or exploit code (if possible)
4. Potential impact of the issue, including how an attacker might exploit the issue
This information will help us triage your report more quickly. Any and all CVEs will be requested and issued through GitHubs private vulnerability reporting functionality, which will be published alongside the disclosure.
This security policy only applies to the most recent stable branch of qBittorrent. Flaws in old versions that are not present in the current stable branch will not be fixed.

View file

@ -1,44 +0,0 @@
# WebAPI Changelog
## 2.11.10
* [#22932](https://github.com/qbittorrent/qBittorrent/pull/22932)
* `torrents/categories` and `sync/maindata` now serialize categories' `downloadPath` to `null`, rather than `undefined`
## 2.11.9
* [#21015](https://github.com/qbittorrent/qBittorrent/pull/21015)
* Add `torrents/fetchMetadata` endpoint for retrieving torrent metadata associated with a URL
* Add `torrents/parseMetadata` endpoint for retrieving torrent metadata associated with a .torrent file
* Add `torrents/saveMetadata` endpoint for saving retrieved torrent metadata to a .torrent file
* `torrents/add` allows adding a torrent with metadata previously retrieved via `torrents/fetchMetadata` or `torrents/parseMetadata`
* `torrents/add` allows specifying a torrent's file priorities
* [#22698](https://github.com/qbittorrent/qBittorrent/pull/22698)
* `torrents/addTrackers` and `torrents/removeTrackers` now accept `hash=all` and adds/removes the tracker to/from *all* torrents
* For compatibility, `torrents/removeTrackers` still accepts `hash=*` internally we transform it into `all`
* Allow passing a pipe (`|`) separated list of hashes in `hash` for `torrents/addTrackers` and `torrents/removeTrackers`
## 2.11.8
* [#21349](https://github.com/qbittorrent/qBittorrent/pull/21349)
* Handle sending `204 No Content` status code when response contains no data
* Some endpoints still return `200 OK` to ensure smooth transition
* [#22750](https://github.com/qbittorrent/qBittorrent/pull/22750)
* `torrents/info` allows an optional parameter `includeFiles` that defaults to `false`
* Each torrent will contain a new key `files` which will list all files similar to the `torrents/files` endpoint
* [#22813](https://github.com/qbittorrent/qBittorrent/pull/22813)
* `app/getDirectoryContent` allows an optional parameter `withMetadata` to send file metadata
* Fields are `name`, `type`, `size`, `creation_date`, `last_access_date`, `last_modification_date`
* See PR for TypeScript types
## 2.11.7
* [#22166](https://github.com/qbittorrent/qBittorrent/pull/22166)
* `sync/maindata` returns 3 new torrent fields: `has_tracker_warning`, `has_tracker_error`, `has_other_announce_error`
## 2.11.6
* [#22460](https://github.com/qbittorrent/qBittorrent/pull/22460)
* `app/setPreferences` allows only one of `max_ratio_enabled`, `max_ratio` to be present
* `app/setPreferences` allows only one of `max_seeding_time_enabled`, `max_seeding_time` to be present
* `app/setPreferences` allows only one of `max_inactive_seeding_time_enabled`, `max_inactive_seeding_time` to be present

View file

@ -47,9 +47,6 @@ find_package(Boost ${minBoostVersion} REQUIRED)
find_package(OpenSSL ${minOpenSSLVersion} REQUIRED) find_package(OpenSSL ${minOpenSSLVersion} REQUIRED)
find_package(ZLIB ${minZlibVersion} REQUIRED) find_package(ZLIB ${minZlibVersion} REQUIRED)
find_package(Qt6 ${minQt6Version} REQUIRED COMPONENTS Core Network Sql Xml LinguistTools) find_package(Qt6 ${minQt6Version} REQUIRED COMPONENTS Core Network Sql Xml LinguistTools)
if (Qt6_FOUND AND (Qt6_VERSION VERSION_GREATER_EQUAL 6.10))
find_package(Qt6 ${minQt6Version} REQUIRED COMPONENTS CorePrivate)
endif()
if (DBUS) if (DBUS)
find_package(Qt6 ${minQt6Version} REQUIRED COMPONENTS DBus) find_package(Qt6 ${minQt6Version} REQUIRED COMPONENTS DBus)
set_package_properties(Qt6DBus PROPERTIES set_package_properties(Qt6DBus PROPERTIES

View file

@ -20,7 +20,7 @@ target_compile_features(qbt_common_cfg INTERFACE
) )
target_compile_definitions(qbt_common_cfg INTERFACE target_compile_definitions(qbt_common_cfg INTERFACE
QT_DISABLE_DEPRECATED_UP_TO=0x060600 QT_DISABLE_DEPRECATED_UP_TO=0x060500
QT_NO_CAST_FROM_ASCII QT_NO_CAST_FROM_ASCII
QT_NO_CAST_TO_ASCII QT_NO_CAST_TO_ASCII
QT_NO_CAST_FROM_BYTEARRAY QT_NO_CAST_FROM_BYTEARRAY
@ -89,7 +89,7 @@ if (MSVC)
/Zc:__cplusplus /Zc:__cplusplus
) )
target_link_options(qbt_common_cfg INTERFACE target_link_options(qbt_common_cfg INTERFACE
/GUARD:CF /guard:cf
$<$<NOT:$<CONFIG:Debug>>:/OPT:REF /OPT:ICF> $<$<NOT:$<CONFIG:Debug>>:/OPT:REF /OPT:ICF>
# suppress linking warning due to /INCREMENTAL and /OPT:ICF being both ON # suppress linking warning due to /INCREMENTAL and /OPT:ICF being both ON
$<$<CONFIG:RelWithDebInfo>:/INCREMENTAL:NO> $<$<CONFIG:RelWithDebInfo>:/INCREMENTAL:NO>

4
dist/mac/Info.plist vendored
View file

@ -55,7 +55,7 @@
<key>CFBundlePackageType</key> <key>CFBundlePackageType</key>
<string>APPL</string> <string>APPL</string>
<key>CFBundleShortVersionString</key> <key>CFBundleShortVersionString</key>
<string>5.2.0</string> <string>5.0.3</string>
<key>CFBundleExecutable</key> <key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string> <string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key> <key>CFBundleIdentifier</key>
@ -67,7 +67,7 @@
<key>NSAppleScriptEnabled</key> <key>NSAppleScriptEnabled</key>
<string>YES</string> <string>YES</string>
<key>NSHumanReadableCopyright</key> <key>NSHumanReadableCopyright</key>
<string>Copyright © 2006-2025 The qBittorrent project</string> <string>Copyright © 2006-2024 The qBittorrent project</string>
<key>UTExportedTypeDeclarations</key> <key>UTExportedTypeDeclarations</key>
<array> <array>
<dict> <dict>

Binary file not shown.

Binary file not shown.

View file

@ -34,12 +34,12 @@ endforeach()
if (GUI) if (GUI)
install(FILES org.qbittorrent.qBittorrent.desktop install(FILES org.qbittorrent.qBittorrent.desktop
DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/applications DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/applications/
COMPONENT data COMPONENT data
) )
install(FILES org.qbittorrent.qBittorrent.metainfo.xml install(FILES org.qbittorrent.qBittorrent.metainfo.xml
DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/metainfo DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/metainfo/
COMPONENT data COMPONENT data
) )
@ -55,9 +55,4 @@ if (GUI)
DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/scalable/status DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/icons/hicolor/scalable/status
COMPONENT data COMPONENT data
) )
else()
install(FILES org.qbittorrent.qBittorrent-nox.metainfo.xml
DESTINATION ${CMAKE_INSTALL_DATAROOTDIR}/metainfo
COMPONENT data
)
endif() endif()

Binary file not shown.

Before

Width:  |  Height:  |  Size: 747 B

After

Width:  |  Height:  |  Size: 750 B

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 747 B

After

Width:  |  Height:  |  Size: 750 B

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

After

Width:  |  Height:  |  Size: 3.7 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

After

Width:  |  Height:  |  Size: 3.7 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.1 KiB

After

Width:  |  Height:  |  Size: 4.1 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.1 KiB

After

Width:  |  Height:  |  Size: 4.1 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.4 KiB

After

Width:  |  Height:  |  Size: 5.4 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.4 KiB

After

Width:  |  Height:  |  Size: 5.4 KiB

Before After
Before After

View file

@ -1,57 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright 2014 sledgehammer999 <sledgehammer999@qbittorrent.org> -->
<component type="console-application">
<id>org.qbittorrent.qBittorrent-nox</id>
<metadata_license>CC0-1.0</metadata_license>
<project_license>GPL-3.0-or-later and OpenSSL</project_license>
<name>qBittorrent-nox</name>
<summary>An open-source Bittorrent client (nox version)</summary>
<description>
<p>
The qBittorrent project aims to provide an open-source software alternative to µTorrent.
Additionally, qBittorrent runs and provides the same features on all major platforms (FreeBSD, Linux, macOS, OS/2, Windows).
qBittorrent is based on the Qt toolkit and libtorrent-rasterbar library.
</p>
<ul>
<li>Polished µTorrent-like User Interface</li>
<li>Well-integrated and extensible Search Engine</li>
<li>RSS feed support with advanced download filters (incl. regex)</li>
<li>Many Bittorrent extensions supported</li>
<li>Remote control through Web user interface, written with AJAX</li>
<li>Sequential downloading (Download in order)</li>
<li>Advanced control over torrents, trackers and peers</li>
<li>Bandwidth scheduler</li>
<li>Torrent creation tool</li>
<li>IP Filtering (eMule &amp; PeerGuardian format compatible)</li>
<li>IPv6 compliant</li>
<li>UPnP / NAT-PMP port forwarding support</li>
<li>Available on all platforms: Windows, Linux, macOS, FreeBSD, OS/2</li>
<li>Available in ~70 languages</li>
</ul>
</description>
<provides>
<binary>qbittorrent-nox</binary>
</provides>
<screenshots>
<screenshot type="default">
<caption>Running headless (nox) version</caption>
<image>https://raw.githubusercontent.com/qbittorrent/qBittorrent-website/43fcf4550f567c38fb879b984922b659e90982cc/src/img/screenshots/linux/5.webp</image>
</screenshot>
</screenshots>
<update_contact>sledgehammer999@qbittorrent.org</update_contact>
<developer id="org.qbittorrent">
<name>The qBittorrent Project</name>
</developer>
<url type="homepage">https://www.qbittorrent.org/</url>
<url type="bugtracker">https://bugs.qbittorrent.org/</url>
<url type="faq">https://wiki.qbittorrent.org/Frequently-Asked-Questions</url>
<url type="help">https://forum.qbittorrent.org/</url>
<url type="donation">https://www.qbittorrent.org/donate</url>
<url type="translate">https://wiki.qbittorrent.org/How-to-translate-qBittorrent</url>
<url type="vcs-browser">https://github.com/qbittorrent/qBittorrent</url>
<url type="contribute">https://github.com/qbittorrent/qBittorrent/blob/master/CONTRIBUTING.md</url>
<content_rating type="oars-1.1"/>
<releases>
<release version="5.2.0~alpha1" date="2025-02-11"/>
</releases>
</component>

View file

@ -105,7 +105,7 @@ GenericName[ka]=BitTorrent კლიენტი
Comment[ka]= BitTorrent- Comment[ka]= BitTorrent-
Name[ka]=qBittorrent Name[ka]=qBittorrent
GenericName[ko]=BitTorrent GenericName[ko]=BitTorrent
Comment[ko]=BitTorrent Comment[ko]=BitTorrent
Name[ko]=qBittorrent Name[ko]=qBittorrent
GenericName[lt]=BitTorrent klientas GenericName[lt]=BitTorrent klientas
Comment[lt]=Atsisiųskite bei dalinkitės failais BitTorrent tinkle Comment[lt]=Atsisiųskite bei dalinkitės failais BitTorrent tinkle

View file

@ -62,6 +62,6 @@
<url type="contribute">https://github.com/qbittorrent/qBittorrent/blob/master/CONTRIBUTING.md</url> <url type="contribute">https://github.com/qbittorrent/qBittorrent/blob/master/CONTRIBUTING.md</url>
<content_rating type="oars-1.1"/> <content_rating type="oars-1.1"/>
<releases> <releases>
<release version="5.2.0~alpha1" date="2025-02-11"/> <release version="5.0.3" date="2024-12-16"/>
</releases> </releases>
</component> </component>

View file

@ -14,7 +14,7 @@
; 4.5.1.3 -> good ; 4.5.1.3 -> good
; 4.5.1.3.2 -> bad ; 4.5.1.3.2 -> bad
; 4.5.0beta -> bad ; 4.5.0beta -> bad
!define /ifndef QBT_VERSION "5.2.0" !define /ifndef QBT_VERSION "5.0.3"
; Option that controls the installer's window name ; Option that controls the installer's window name
; If set, its value will be used like this: ; If set, its value will be used like this:
@ -86,7 +86,7 @@ OutFile "qbittorrent_${QBT_INSTALLER_FILENAME}_setup.exe"
;Installer Version Information ;Installer Version Information
VIAddVersionKey "ProductName" "qBittorrent" VIAddVersionKey "ProductName" "qBittorrent"
VIAddVersionKey "CompanyName" "The qBittorrent project" VIAddVersionKey "CompanyName" "The qBittorrent project"
VIAddVersionKey "LegalCopyright" "Copyright ©2006-2025 The qBittorrent project" VIAddVersionKey "LegalCopyright" "Copyright ©2006-2024 The qBittorrent project"
VIAddVersionKey "FileDescription" "qBittorrent - A Bittorrent Client" VIAddVersionKey "FileDescription" "qBittorrent - A Bittorrent Client"
VIAddVersionKey "FileVersion" "${QBT_VERSION}" VIAddVersionKey "FileVersion" "${QBT_VERSION}"
@ -111,8 +111,7 @@ RequestExecutionLevel user
!define MUI_HEADERIMAGE !define MUI_HEADERIMAGE
!define MUI_COMPONENTSPAGE_NODESC !define MUI_COMPONENTSPAGE_NODESC
;!define MUI_ICON "qbittorrent.ico" ;!define MUI_ICON "qbittorrent.ico"
!define MUI_LICENSEPAGE_BUTTON $(^NextBtn) !define MUI_LICENSEPAGE_CHECKBOX
!define MUI_LICENSEPAGE_TEXT_BOTTOM "$_CLICK"
!define MUI_LANGDLL_ALLLANGUAGES !define MUI_LANGDLL_ALLLANGUAGES
;-------------------------------- ;--------------------------------

View file

@ -7,7 +7,7 @@ LangString inst_desktop ${LANG_PORTUGUESE} "Criar atalho no ambiente de trabalho
;LangString inst_startmenu ${LANG_ENGLISH} "Create Start Menu Shortcut" ;LangString inst_startmenu ${LANG_ENGLISH} "Create Start Menu Shortcut"
LangString inst_startmenu ${LANG_PORTUGUESE} "Criar atalho no menu Iniciar" LangString inst_startmenu ${LANG_PORTUGUESE} "Criar atalho no menu Iniciar"
;LangString inst_startup ${LANG_ENGLISH} "Start qBittorrent on Windows start up" ;LangString inst_startup ${LANG_ENGLISH} "Start qBittorrent on Windows start up"
LangString inst_startup ${LANG_PORTUGUESE} "Iniciar o qBittorrent no arranque do Windows" LangString inst_startup ${LANG_PORTUGUESE} "Iniciar o qBittorrent na inicialização do Windows"
;LangString inst_torrent ${LANG_ENGLISH} "Open .torrent files with qBittorrent" ;LangString inst_torrent ${LANG_ENGLISH} "Open .torrent files with qBittorrent"
LangString inst_torrent ${LANG_PORTUGUESE} "Abrir ficheiros .torrent com o qBittorrent" LangString inst_torrent ${LANG_PORTUGUESE} "Abrir ficheiros .torrent com o qBittorrent"
;LangString inst_magnet ${LANG_ENGLISH} "Open magnet links with qBittorrent" ;LangString inst_magnet ${LANG_ENGLISH} "Open magnet links with qBittorrent"
@ -29,7 +29,7 @@ LangString launch_qbt ${LANG_PORTUGUESE} "Iniciar qBittorrent."
;LangString inst_requires_64bit ${LANG_ENGLISH} "This installer works only in 64-bit Windows versions." ;LangString inst_requires_64bit ${LANG_ENGLISH} "This installer works only in 64-bit Windows versions."
LangString inst_requires_64bit ${LANG_PORTUGUESE} "Este instalador funciona apenas em versões Windows de 64 bits." LangString inst_requires_64bit ${LANG_PORTUGUESE} "Este instalador funciona apenas em versões Windows de 64 bits."
;LangString inst_requires_win10 ${LANG_ENGLISH} "This installer requires at least Windows 10 (1809) / Windows Server 2019." ;LangString inst_requires_win10 ${LANG_ENGLISH} "This installer requires at least Windows 10 (1809) / Windows Server 2019."
LangString inst_requires_win10 ${LANG_PORTUGUESE} "Este instalador requer, pelo menos, o Windows 10 (1809) / Windows Server 2019." LangString inst_requires_win10 ${LANG_PORTUGUESE} "This installer requires at least Windows 10 (1809) / Windows Server 2019."
;LangString inst_uninstall_link_description ${LANG_ENGLISH} "Uninstall qBittorrent" ;LangString inst_uninstall_link_description ${LANG_ENGLISH} "Uninstall qBittorrent"
LangString inst_uninstall_link_description ${LANG_PORTUGUESE} "Desinstalar qBittorrent" LangString inst_uninstall_link_description ${LANG_PORTUGUESE} "Desinstalar qBittorrent"

View file

@ -7,21 +7,21 @@ LangString inst_desktop ${LANG_SWEDISH} "Skapa skrivbordsgenväg"
;LangString inst_startmenu ${LANG_ENGLISH} "Create Start Menu Shortcut" ;LangString inst_startmenu ${LANG_ENGLISH} "Create Start Menu Shortcut"
LangString inst_startmenu ${LANG_SWEDISH} "Skapa startmenygenväg" LangString inst_startmenu ${LANG_SWEDISH} "Skapa startmenygenväg"
;LangString inst_startup ${LANG_ENGLISH} "Start qBittorrent on Windows start up" ;LangString inst_startup ${LANG_ENGLISH} "Start qBittorrent on Windows start up"
LangString inst_startup ${LANG_SWEDISH} "Starta qBittorrent vid Windows-uppstart" LangString inst_startup ${LANG_SWEDISH} "Starta qBittorrent vid Windows start"
;LangString inst_torrent ${LANG_ENGLISH} "Open .torrent files with qBittorrent" ;LangString inst_torrent ${LANG_ENGLISH} "Open .torrent files with qBittorrent"
LangString inst_torrent ${LANG_SWEDISH} "Öppna .torrent-filer med qBittorrent" LangString inst_torrent ${LANG_SWEDISH} "Öppna .torrent-filer med qBittorrent"
;LangString inst_magnet ${LANG_ENGLISH} "Open magnet links with qBittorrent" ;LangString inst_magnet ${LANG_ENGLISH} "Open magnet links with qBittorrent"
LangString inst_magnet ${LANG_SWEDISH} "Öppna magnetlänkar med qBittorrent" LangString inst_magnet ${LANG_SWEDISH} "Öppna magnetlänkar med qBittorrent"
;LangString inst_firewall ${LANG_ENGLISH} "Add Windows Firewall rule" ;LangString inst_firewall ${LANG_ENGLISH} "Add Windows Firewall rule"
LangString inst_firewall ${LANG_SWEDISH} "Lägg till Windows-brandväggsregel" LangString inst_firewall ${LANG_SWEDISH} "Lägg till Windows-brandväggregel"
;LangString inst_pathlimit ${LANG_ENGLISH} "Disable Windows path length limit (260 character MAX_PATH limitation, requires Windows 10 1607 or later)" ;LangString inst_pathlimit ${LANG_ENGLISH} "Disable Windows path length limit (260 character MAX_PATH limitation, requires Windows 10 1607 or later)"
LangString inst_pathlimit ${LANG_SWEDISH} "Inaktivera gränsen för Windows-sökvägslängd (260 tecken MAX_PATH-begränsning, kräver Windows 10 1607 eller senare)" LangString inst_pathlimit ${LANG_SWEDISH} "Inaktivera gränsen för Windows-sökvägslängd (260 tecken MAX_PATH-begränsning, kräver Windows 10 1607 eller senare)"
;LangString inst_firewallinfo ${LANG_ENGLISH} "Adding Windows Firewall rule" ;LangString inst_firewallinfo ${LANG_ENGLISH} "Adding Windows Firewall rule"
LangString inst_firewallinfo ${LANG_SWEDISH} "Lägger till Windows-brandväggsregel" LangString inst_firewallinfo ${LANG_SWEDISH} "Lägger till Windows-brandväggregel"
;LangString inst_warning ${LANG_ENGLISH} "qBittorrent is running. Please close the application before installing." ;LangString inst_warning ${LANG_ENGLISH} "qBittorrent is running. Please close the application before installing."
LangString inst_warning ${LANG_SWEDISH} "qBittorrent körs. Stäng programmet innan du installerar." LangString inst_warning ${LANG_SWEDISH} "qBittorrent körs. Vänligen stäng programmet innan du installerar."
;LangString inst_uninstall_question ${LANG_ENGLISH} "Current version will be uninstalled. User settings and torrents will remain intact." ;LangString inst_uninstall_question ${LANG_ENGLISH} "Current version will be uninstalled. User settings and torrents will remain intact."
LangString inst_uninstall_question ${LANG_SWEDISH} "Aktuell version avinstalleras. Användarinställningar och torrenter kommer att förbli intakta." LangString inst_uninstall_question ${LANG_SWEDISH} "Nuvarande version avinstalleras. Användarinställningar och torrenter kommer att förbli intakta."
;LangString inst_unist ${LANG_ENGLISH} "Uninstalling previous version." ;LangString inst_unist ${LANG_ENGLISH} "Uninstalling previous version."
LangString inst_unist ${LANG_SWEDISH} "Avinstallerar tidigare version." LangString inst_unist ${LANG_SWEDISH} "Avinstallerar tidigare version."
;LangString launch_qbt ${LANG_ENGLISH} "Launch qBittorrent." ;LangString launch_qbt ${LANG_ENGLISH} "Launch qBittorrent."
@ -53,7 +53,7 @@ LangString remove_firewallinfo ${LANG_SWEDISH} "Tar bort Windows-brandväggsrege
;LangString remove_cache ${LANG_ENGLISH} "Remove torrents and cached data" ;LangString remove_cache ${LANG_ENGLISH} "Remove torrents and cached data"
LangString remove_cache ${LANG_SWEDISH} "Ta bort torrenter och cachade data" LangString remove_cache ${LANG_SWEDISH} "Ta bort torrenter och cachade data"
;LangString uninst_warning ${LANG_ENGLISH} "qBittorrent is running. Please close the application before uninstalling." ;LangString uninst_warning ${LANG_ENGLISH} "qBittorrent is running. Please close the application before uninstalling."
LangString uninst_warning ${LANG_SWEDISH} "qBittorrent körs. Stäng programmet innan du avinstallerar." LangString uninst_warning ${LANG_SWEDISH} "qBittorrent körs. Vänligen stäng programmet innan du avinstallerar."
;LangString uninst_tor_warn ${LANG_ENGLISH} "Not removing .torrent association. It is associated with:" ;LangString uninst_tor_warn ${LANG_ENGLISH} "Not removing .torrent association. It is associated with:"
LangString uninst_tor_warn ${LANG_SWEDISH} "Tar inte bort .torrent-association. Den är associerad med:" LangString uninst_tor_warn ${LANG_SWEDISH} "Tar inte bort .torrent-association. Den är associerad med:"
;LangString uninst_mag_warn ${LANG_ENGLISH} "Not removing magnet association. It is associated with:" ;LangString uninst_mag_warn ${LANG_ENGLISH} "Not removing magnet association. It is associated with:"

View file

@ -1,44 +1,41 @@
.\" Automatically generated by Pandoc 3.7.0.2 .\" Automatically generated by Pandoc 3.1.7
.\" .\"
.TH "QBITTORRENT\-NOX" "1" "January 16th 2010" "Command line Bittorrent client written in C++ / Qt" .TH "QBITTORRENT-NOX" "1" "January 16th 2010" "Command line Bittorrent client written in C++ / Qt" ""
.SH NAME .SH NAME
qBittorrent\-nox \- a command line Bittorrent client written in C++ / Qt qBittorrent-nox - a command line Bittorrent client written in C++ / Qt
.SH SYNOPSIS .SH SYNOPSIS
\f[B]qbittorrent\-nox\f[R] \f[B]qbittorrent-nox\f[R]
\f[CR][\-\-d|\-\-daemon] [\-\-webui\-port=x] [TORRENT_FILE | URL]...\f[R] \f[CR][--d|--daemon] [--webui-port=x] [TORRENT_FILE | URL]...\f[R]
.PP .PP
\f[B]qbittorrent\-nox\f[R] \f[CR]\-\-help\f[R] \f[B]qbittorrent-nox\f[R] \f[CR]--help\f[R]
.PP .PP
\f[B]qbittorrent\-nox\f[R] \f[CR]\-\-version\f[R] \f[B]qbittorrent-nox\f[R] \f[CR]--version\f[R]
.SH DESCRIPTION .SH DESCRIPTION
\f[B]qBittorrent\-nox\f[R] is an advanced command\-line Bittorrent \f[B]qBittorrent-nox\f[R] is an advanced command-line Bittorrent client
client written in C++ / Qt using the \f[B]libtorrent\-rasterbar\f[R] written in C++ / Qt using the \f[B]libtorrent-rasterbar\f[R] library by
library by Arvid Norberg. Arvid Norberg.
qBittorrent\-nox aims to be a good alternative to other command line qBittorrent-nox aims to be a good alternative to other command line
bittorrent clients and provides features similar to popular graphical bittorrent clients and provides features similar to popular graphical
clients. clients.
.PP .PP
qBittorrent\-nox is fast, stable, light and it supports unicode. qBittorrent-nox is fast, stable, light and it supports unicode.
It also comes with UPnP port forwarding / NAT\-PMP, encryption (Vuze It also comes with UPnP port forwarding / NAT-PMP, encryption (Vuze
compatible), FAST extension (mainline) and PeX support (utorrent compatible), FAST extension (mainline) and PeX support (utorrent
compatible). compatible).
.PP .PP
qBittorrent\-nox is meant to be controlled via its feature\-rich Web UI qBittorrent-nox is meant to be controlled via its feature-rich Web UI
which is accessible as a default on http://localhost:8080. which is accessible as a default on http://localhost:8080.
The Web UI access is secured and the default account user name is The Web UI access is secured and the default account user name is
\(lqadmin\(rq with \(lqadminadmin\(rq as a password. \[lq]admin\[rq] with \[lq]adminadmin\[rq] as a password.
.SH OPTIONS .SH OPTIONS
\f[B]\f[CB]\-\-help\f[B]\f[R] Prints the command line options. \f[B]\f[CB]--help\f[B]\f[R] Prints the command line options.
.PP .PP
\f[B]\f[CB]\-\-version\f[B]\f[R] Prints qbittorrent program version \f[B]\f[CB]--version\f[B]\f[R] Prints qbittorrent program version
number. number.
.PP .PP
\f[B]\f[CB]\-\-webui\-port=x\f[B]\f[R] Changes Web UI port to x \f[B]\f[CB]--webui-port=x\f[B]\f[R] Changes Web UI port to x (default:
(default: 8080). 8080).
.SH BUGS .SH BUGS
If you find a bug, please report it at https://bugs.qbittorrent.org If you find a bug, please report it at https://bugs.qbittorrent.org
.SH AUTHORS .SH AUTHORS
Christophe Dumez \c Christophe Dumez <chris@qbittorrent.org>.
.MT chris@qbittorrent.org
.ME \c
\&.

View file

@ -1,38 +1,35 @@
.\" Automatically generated by Pandoc 3.7.0.2 .\" Automatically generated by Pandoc 3.1.7
.\" .\"
.TH "QBITTORRENT" "1" "January 16th 2010" "Bittorrent client written in C++ / Qt" .TH "QBITTORRENT" "1" "January 16th 2010" "Bittorrent client written in C++ / Qt" ""
.SH NAME .SH NAME
qBittorrent \- a Bittorrent client written in C++ / Qt qBittorrent - a Bittorrent client written in C++ / Qt
.SH SYNOPSIS .SH SYNOPSIS
\f[B]qbittorrent\f[R] \f[B]qbittorrent\f[R]
\f[CR][\-\-no\-splash] [\-\-webui\-port=x] [TORRENT_FILE | URL]...\f[R] \f[CR][--no-splash] [--webui-port=x] [TORRENT_FILE | URL]...\f[R]
.PP .PP
\f[B]qbittorrent\f[R] \f[CR]\-\-help\f[R] \f[B]qbittorrent\f[R] \f[CR]--help\f[R]
.PP .PP
\f[B]qbittorrent\f[R] \f[CR]\-\-version\f[R] \f[B]qbittorrent\f[R] \f[CR]--version\f[R]
.SH DESCRIPTION .SH DESCRIPTION
\f[B]qBittorrent\f[R] is an advanced Bittorrent client written in C++ / \f[B]qBittorrent\f[R] is an advanced Bittorrent client written in C++ /
Qt, using the \f[B]libtorrent\-rasterbar\f[R] library by Arvid Norberg. Qt, using the \f[B]libtorrent-rasterbar\f[R] library by Arvid Norberg.
qBittorrent is similar to uTorrent. qBittorrent is similar to uTorrent.
qBittorrent is fast, stable, light, it supports unicode and it provides qBittorrent is fast, stable, light, it supports unicode and it provides
a good integrated search engine. a good integrated search engine.
It also comes with UPnP port forwarding / NAT\-PMP, encryption (Vuze It also comes with UPnP port forwarding / NAT-PMP, encryption (Vuze
compatible), FAST extension (mainline) and PeX support (utorrent compatible), FAST extension (mainline) and PeX support (utorrent
compatible). compatible).
.SH OPTIONS .SH OPTIONS
\f[B]\f[CB]\-\-help\f[B]\f[R] Prints the command line options. \f[B]\f[CB]--help\f[B]\f[R] Prints the command line options.
.PP .PP
\f[B]\f[CB]\-\-version\f[B]\f[R] Prints qbittorrent program version \f[B]\f[CB]--version\f[B]\f[R] Prints qbittorrent program version
number. number.
.PP .PP
\f[B]\f[CB]\-\-no\-splash\f[B]\f[R] Disables splash screen on startup. \f[B]\f[CB]--no-splash\f[B]\f[R] Disables splash screen on startup.
.PP .PP
\f[B]\f[CB]\-\-webui\-port=x\f[B]\f[R] Changes Web UI port to x \f[B]\f[CB]--webui-port=x\f[B]\f[R] Changes Web UI port to x (default:
(default: 8080). 8080).
.SH BUGS .SH BUGS
If you find a bug, please report it at https://bugs.qbittorrent.org If you find a bug, please report it at https://bugs.qbittorrent.org
.SH AUTHORS .SH AUTHORS
Christophe Dumez \c Christophe Dumez <chris@qbittorrent.org>.
.MT chris@qbittorrent.org
.ME \c
\&.

View file

@ -1,10 +1,7 @@
.\" Automatically generated by Pandoc 3.7.0.2 .\" Automatically generated by Pandoc 3.1.7
.\" .\"
.TH "QBITTORRENT\-NOX" "1" "16 января 2010" "Клиент сети БитТоррент для командной строки" .TH "QBITTORRENT-NOX" "1" "16 января 2010" "Клиент сети БитТоррент для командной строки" ""
.SH НАЗВАНИЕ .SH НАЗВАНИЕ
qBittorrent\-nox \(em клиент сети БитТоррент для командной строки. qBittorrent-nox \[em] клиент сети БитТоррент для командной строки.
.SH АВТОРЫ .SH АВТОРЫ
Christophe Dumez \c Christophe Dumez <chris@qbittorrent.org>.
.MT chris@qbittorrent.org
.ME \c
\&.

View file

@ -1,10 +1,7 @@
.\" Automatically generated by Pandoc 3.7.0.2 .\" Automatically generated by Pandoc 3.1.7
.\" .\"
.TH "QBITTORRENT" "1" "16 января 2010" "Клиент сети БитТоррент" .TH "QBITTORRENT" "1" "16 января 2010" "Клиент сети БитТоррент" ""
.SH НАЗВАНИЕ .SH НАЗВАНИЕ
qBittorrent \(em клиент сети БитТоррент. qBittorrent \[em] клиент сети БитТоррент.
.SH АВТОРЫ .SH АВТОРЫ
Christophe Dumez \c Christophe Dumez <chris@qbittorrent.org>.
.MT chris@qbittorrent.org
.ME \c
\&.

View file

@ -1,6 +1,6 @@
/* /*
* Bittorrent Client using Qt and libtorrent. * Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2015-2025 Vladimir Golovnev <glassez@yandex.ru> * Copyright (C) 2015-2024 Vladimir Golovnev <glassez@yandex.ru>
* Copyright (C) 2006 Christophe Dumez * Copyright (C) 2006 Christophe Dumez
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
@ -124,28 +124,6 @@ namespace
const int PIXMAP_CACHE_SIZE = 64 * 1024 * 1024; // 64MiB const int PIXMAP_CACHE_SIZE = 64 * 1024 * 1024; // 64MiB
#endif #endif
const QString PARAM_ADDSTOPPED = u"@addStopped"_s;
const QString PARAM_CATEGORY = u"@category"_s;
const QString PARAM_FIRSTLASTPIECEPRIORITY = u"@firstLastPiecePriority"_s;
const QString PARAM_SAVEPATH = u"@savePath"_s;
const QString PARAM_SEQUENTIAL = u"@sequential"_s;
const QString PARAM_SKIPCHECKING = u"@skipChecking"_s;
const QString PARAM_SKIPDIALOG = u"@skipDialog"_s;
QString bindParamValue(const QStringView paramName, const QStringView paramValue)
{
return paramName + u'=' + paramValue;
}
std::pair<QStringView, QStringView> parseParam(const QStringView param)
{
const qsizetype sepIndex = param.indexOf(u'=');
if (sepIndex >= 0)
return {param.first(sepIndex), param.sliced(sepIndex + 1)};
return {param, {}};
}
QString serializeParams(const QBtCommandLineParameters &params) QString serializeParams(const QBtCommandLineParameters &params)
{ {
QStringList result; QStringList result;
@ -160,86 +138,85 @@ namespace
const BitTorrent::AddTorrentParams &addTorrentParams = params.addTorrentParams; const BitTorrent::AddTorrentParams &addTorrentParams = params.addTorrentParams;
if (!addTorrentParams.savePath.isEmpty()) if (!addTorrentParams.savePath.isEmpty())
result.append(bindParamValue(PARAM_SAVEPATH, addTorrentParams.savePath.data())); result.append(u"@savePath=" + addTorrentParams.savePath.data());
if (addTorrentParams.addStopped.has_value()) if (addTorrentParams.addStopped.has_value())
result.append(bindParamValue(PARAM_ADDSTOPPED, (*addTorrentParams.addStopped ? u"1" : u"0"))); result.append(*addTorrentParams.addStopped ? u"@addStopped=1"_s : u"@addStopped=0"_s);
if (addTorrentParams.skipChecking) if (addTorrentParams.skipChecking)
result.append(PARAM_SKIPCHECKING); result.append(u"@skipChecking"_s);
if (!addTorrentParams.category.isEmpty()) if (!addTorrentParams.category.isEmpty())
result.append(bindParamValue(PARAM_CATEGORY, addTorrentParams.category)); result.append(u"@category=" + addTorrentParams.category);
if (addTorrentParams.sequential) if (addTorrentParams.sequential)
result.append(PARAM_SEQUENTIAL); result.append(u"@sequential"_s);
if (addTorrentParams.firstLastPiecePriority) if (addTorrentParams.firstLastPiecePriority)
result.append(PARAM_FIRSTLASTPIECEPRIORITY); result.append(u"@firstLastPiecePriority"_s);
if (params.skipDialog.has_value()) if (params.skipDialog.has_value())
result.append(bindParamValue(PARAM_SKIPDIALOG, (*params.skipDialog ? u"1" : u"0"))); result.append(*params.skipDialog ? u"@skipDialog=1"_s : u"@skipDialog=0"_s);
result += params.torrentSources; result += params.torrentSources;
return result.join(PARAMS_SEPARATOR); return result.join(PARAMS_SEPARATOR);
} }
QBtCommandLineParameters parseParams(const QStringView str) QBtCommandLineParameters parseParams(const QString &str)
{ {
QBtCommandLineParameters parsedParams; QBtCommandLineParameters parsedParams;
BitTorrent::AddTorrentParams &addTorrentParams = parsedParams.addTorrentParams; BitTorrent::AddTorrentParams &addTorrentParams = parsedParams.addTorrentParams;
for (QStringView param : asConst(str.split(PARAMS_SEPARATOR, Qt::SkipEmptyParts))) for (QString param : asConst(str.split(PARAMS_SEPARATOR, Qt::SkipEmptyParts)))
{ {
param = param.trimmed(); param = param.trimmed();
const auto [paramName, paramValue] = parseParam(param);
// Process strings indicating options specified by the user. // Process strings indicating options specified by the user.
if (paramName == PARAM_SAVEPATH) if (param.startsWith(u"@savePath="))
{ {
addTorrentParams.savePath = Path(paramValue.toString()); addTorrentParams.savePath = Path(param.mid(10));
continue; continue;
} }
if (paramName == PARAM_ADDSTOPPED) if (param.startsWith(u"@addStopped="))
{ {
addTorrentParams.addStopped = (paramValue.toInt() != 0); addTorrentParams.addStopped = (QStringView(param).mid(11).toInt() != 0);
continue; continue;
} }
if (paramName == PARAM_SKIPCHECKING) if (param == u"@skipChecking")
{ {
addTorrentParams.skipChecking = true; addTorrentParams.skipChecking = true;
continue; continue;
} }
if (paramName == PARAM_CATEGORY) if (param.startsWith(u"@category="))
{ {
addTorrentParams.category = paramValue.toString(); addTorrentParams.category = param.mid(10);
continue; continue;
} }
if (paramName == PARAM_SEQUENTIAL) if (param == u"@sequential")
{ {
addTorrentParams.sequential = true; addTorrentParams.sequential = true;
continue; continue;
} }
if (paramName == PARAM_FIRSTLASTPIECEPRIORITY) if (param == u"@firstLastPiecePriority")
{ {
addTorrentParams.firstLastPiecePriority = true; addTorrentParams.firstLastPiecePriority = true;
continue; continue;
} }
if (paramName == PARAM_SKIPDIALOG) if (param.startsWith(u"@skipDialog="))
{ {
parsedParams.skipDialog = (paramValue.toInt() != 0); parsedParams.skipDialog = (QStringView(param).mid(12).toInt() != 0);
continue; continue;
} }
parsedParams.torrentSources.append(param.toString()); parsedParams.torrentSources.append(param);
} }
return parsedParams; return parsedParams;
@ -410,7 +387,7 @@ void Application::setMemoryWorkingSetLimit(const int size)
return; return;
m_storeMemoryWorkingSetLimit = size; m_storeMemoryWorkingSetLimit = size;
#if defined(QBT_USES_LIBTORRENT2) && !defined(Q_OS_LINUX) && !defined(Q_OS_MACOS) #if defined(QBT_USES_LIBTORRENT2) && !defined(Q_OS_MACOS)
applyMemoryWorkingSetLimit(); applyMemoryWorkingSetLimit();
#endif #endif
} }
@ -575,9 +552,6 @@ void Application::runExternalProgram(const QString &programTemplate, const BitTo
case u'L': case u'L':
str.replace(i, 2, torrent->category()); str.replace(i, 2, torrent->category());
break; break;
case u'M':
str.replace(i, 2, torrent->comment());
break;
case u'N': case u'N':
str.replace(i, 2, torrent->name()); str.replace(i, 2, torrent->name());
break; break;
@ -605,7 +579,7 @@ void Application::runExternalProgram(const QString &programTemplate, const BitTo
const QString logMsg = tr("Running external program. Torrent: \"%1\". Command: `%2`"); const QString logMsg = tr("Running external program. Torrent: \"%1\". Command: `%2`");
const QString logMsgError = tr("Failed to run external program. Torrent: \"%1\". Command: `%2`"); const QString logMsgError = tr("Failed to run external program. Torrent: \"%1\". Command: `%2`");
// The processing sequence is different for Windows and other OS, this is intentional // The processing sequenece is different for Windows and other OS, this is intentional
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
const QString program = replaceVariables(programTemplate); const QString program = replaceVariables(programTemplate);
const std::wstring programWStr = program.toStdWString(); const std::wstring programWStr = program.toStdWString();
@ -662,13 +636,7 @@ void Application::runExternalProgram(const QString &programTemplate, const BitTo
{ {
// strip redundant quotes // strip redundant quotes
if (arg.startsWith(u'"') && arg.endsWith(u'"')) if (arg.startsWith(u'"') && arg.endsWith(u'"'))
{ arg = arg.mid(1, (arg.size() - 2));
#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
arg.slice(1, (arg.size() - 2));
#else
arg.removeLast().removeFirst();
#endif
}
arg = replaceVariables(arg); arg = replaceVariables(arg);
} }
@ -677,7 +645,6 @@ void Application::runExternalProgram(const QString &programTemplate, const BitTo
QProcess proc; QProcess proc;
proc.setProgram(command); proc.setProgram(command);
proc.setArguments(args); proc.setArguments(args);
proc.setUnixProcessParameters(QProcess::UnixProcessFlag::CloseFileDescriptors);
if (proc.startDetached()) if (proc.startDetached())
{ {
@ -847,7 +814,7 @@ int Application::exec()
printf("%s\n", qUtf8Printable(loadingStr)); printf("%s\n", qUtf8Printable(loadingStr));
#endif #endif
#if defined(QBT_USES_LIBTORRENT2) && !defined(Q_OS_LINUX) && !defined(Q_OS_MACOS) #if defined(QBT_USES_LIBTORRENT2) && !defined(Q_OS_MACOS)
applyMemoryWorkingSetLimit(); applyMemoryWorkingSetLimit();
#endif #endif
@ -930,10 +897,10 @@ int Application::exec()
m_desktopIntegration->showNotification(tr("Torrent added"), tr("'%1' was added.", "e.g: xxx.avi was added.").arg(torrent->name())); m_desktopIntegration->showNotification(tr("Torrent added"), tr("'%1' was added.", "e.g: xxx.avi was added.").arg(torrent->name()));
}); });
connect(m_addTorrentManager, &AddTorrentManager::addTorrentFailed, this connect(m_addTorrentManager, &AddTorrentManager::addTorrentFailed, this
, [this](const QString &source, const BitTorrent::AddTorrentError &reason) , [this](const QString &source, const QString &reason)
{ {
m_desktopIntegration->showNotification(tr("Add torrent failed") m_desktopIntegration->showNotification(tr("Add torrent failed")
, tr("Couldn't add torrent '%1', reason: %2.").arg(source, reason.message)); , tr("Couldn't add torrent '%1', reason: %2.").arg(source, reason));
}); });
disconnect(m_desktopIntegration, &DesktopIntegration::activationRequested, this, &Application::createStartupProgressDialog); disconnect(m_desktopIntegration, &DesktopIntegration::activationRequested, this, &Application::createStartupProgressDialog);
@ -1205,7 +1172,7 @@ void Application::shutdownCleanup([[maybe_unused]] QSessionManager &manager)
} }
#endif #endif
#if defined(QBT_USES_LIBTORRENT2) && !defined(Q_OS_LINUX) && !defined(Q_OS_MACOS) #if defined(QBT_USES_LIBTORRENT2) && !defined(Q_OS_MACOS)
void Application::applyMemoryWorkingSetLimit() const void Application::applyMemoryWorkingSetLimit() const
{ {
const size_t MiB = 1024 * 1024; const size_t MiB = 1024 * 1024;

View file

@ -36,7 +36,6 @@
#include <QDebug> #include <QDebug>
#include <QFileInfo> #include <QFileInfo>
#include <QProcessEnvironment> #include <QProcessEnvironment>
#include <QStringView>
#if defined(Q_OS_WIN) && !defined(DISABLE_GUI) #if defined(Q_OS_WIN) && !defined(DISABLE_GUI)
#include <QMessageBox> #include <QMessageBox>
@ -61,7 +60,7 @@ namespace
class Option class Option
{ {
protected: protected:
explicit constexpr Option(const QStringView name, const QChar shortcut = QChar::Null) explicit constexpr Option(const char *name, char shortcut = 0)
: m_name {name} : m_name {name}
, m_shortcut {shortcut} , m_shortcut {shortcut}
{ {
@ -69,23 +68,23 @@ namespace
QString fullParameter() const QString fullParameter() const
{ {
return u"--" + m_name.toString(); return u"--" + QString::fromLatin1(m_name);
} }
QString shortcutParameter() const QString shortcutParameter() const
{ {
return u"-" + m_shortcut; return u"-" + QChar::fromLatin1(m_shortcut);
} }
bool hasShortcut() const bool hasShortcut() const
{ {
return !m_shortcut.isNull(); return m_shortcut != 0;
} }
QString envVarName() const QString envVarName() const
{ {
return u"QBT_" return u"QBT_"
+ m_name.toString().toUpper().replace(u'-', u'_'); + QString::fromLatin1(m_name).toUpper().replace(u'-', u'_');
} }
public: public:
@ -100,15 +99,15 @@ namespace
} }
private: private:
const QStringView m_name; const char *m_name = nullptr;
const QChar m_shortcut; const char m_shortcut;
}; };
// Boolean option. // Boolean option.
class BoolOption : protected Option class BoolOption : protected Option
{ {
public: public:
explicit constexpr BoolOption(const QStringView name, const QChar shortcut = QChar::Null) explicit constexpr BoolOption(const char *name, char shortcut = 0)
: Option {name, shortcut} : Option {name, shortcut}
{ {
} }
@ -140,8 +139,8 @@ namespace
struct StringOption : protected Option struct StringOption : protected Option
{ {
public: public:
explicit constexpr StringOption(const QStringView name) explicit constexpr StringOption(const char *name)
: Option {name, QChar::Null} : Option {name, 0}
{ {
} }
@ -182,7 +181,7 @@ namespace
class IntOption : protected StringOption class IntOption : protected StringOption
{ {
public: public:
explicit constexpr IntOption(const QStringView name) explicit constexpr IntOption(const char *name)
: StringOption {name} : StringOption {name}
{ {
} }
@ -230,8 +229,8 @@ namespace
class TriStateBoolOption : protected Option class TriStateBoolOption : protected Option
{ {
public: public:
constexpr TriStateBoolOption(const QStringView name, const bool defaultValue) constexpr TriStateBoolOption(const char *name, bool defaultValue)
: Option {name, QChar::Null} : Option {name, 0}
, m_defaultValue(defaultValue) , m_defaultValue(defaultValue)
{ {
} }
@ -300,32 +299,31 @@ namespace
return arg.section(u'=', 0, 0) == option.fullParameter(); return arg.section(u'=', 0, 0) == option.fullParameter();
} }
private: bool m_defaultValue;
bool m_defaultValue = false;
}; };
constexpr const BoolOption SHOW_HELP_OPTION {u"help", u'h'}; constexpr const BoolOption SHOW_HELP_OPTION {"help", 'h'};
#if !defined(Q_OS_WIN) || defined(DISABLE_GUI) #if !defined(Q_OS_WIN) || defined(DISABLE_GUI)
constexpr const BoolOption SHOW_VERSION_OPTION {u"version", u'v'}; constexpr const BoolOption SHOW_VERSION_OPTION {"version", 'v'};
#endif #endif
constexpr const BoolOption CONFIRM_LEGAL_NOTICE {u"confirm-legal-notice"}; constexpr const BoolOption CONFIRM_LEGAL_NOTICE {"confirm-legal-notice"};
#if defined(DISABLE_GUI) && !defined(Q_OS_WIN) #if defined(DISABLE_GUI) && !defined(Q_OS_WIN)
constexpr const BoolOption DAEMON_OPTION {u"daemon", u'd'}; constexpr const BoolOption DAEMON_OPTION {"daemon", 'd'};
#else #else
constexpr const BoolOption NO_SPLASH_OPTION {u"no-splash"}; constexpr const BoolOption NO_SPLASH_OPTION {"no-splash"};
#endif #endif
constexpr const IntOption WEBUI_PORT_OPTION {u"webui-port"}; constexpr const IntOption WEBUI_PORT_OPTION {"webui-port"};
constexpr const IntOption TORRENTING_PORT_OPTION {u"torrenting-port"}; constexpr const IntOption TORRENTING_PORT_OPTION {"torrenting-port"};
constexpr const StringOption PROFILE_OPTION {u"profile"}; constexpr const StringOption PROFILE_OPTION {"profile"};
constexpr const StringOption CONFIGURATION_OPTION {u"configuration"}; constexpr const StringOption CONFIGURATION_OPTION {"configuration"};
constexpr const BoolOption RELATIVE_FASTRESUME {u"relative-fastresume"}; constexpr const BoolOption RELATIVE_FASTRESUME {"relative-fastresume"};
constexpr const StringOption SAVE_PATH_OPTION {u"save-path"}; constexpr const StringOption SAVE_PATH_OPTION {"save-path"};
constexpr const TriStateBoolOption STOPPED_OPTION {u"add-stopped", true}; constexpr const TriStateBoolOption STOPPED_OPTION {"add-stopped", true};
constexpr const BoolOption SKIP_HASH_CHECK_OPTION {u"skip-hash-check"}; constexpr const BoolOption SKIP_HASH_CHECK_OPTION {"skip-hash-check"};
constexpr const StringOption CATEGORY_OPTION {u"category"}; constexpr const StringOption CATEGORY_OPTION {"category"};
constexpr const BoolOption SEQUENTIAL_OPTION {u"sequential"}; constexpr const BoolOption SEQUENTIAL_OPTION {"sequential"};
constexpr const BoolOption FIRST_AND_LAST_OPTION {u"first-and-last"}; constexpr const BoolOption FIRST_AND_LAST_OPTION {"first-and-last"};
constexpr const TriStateBoolOption SKIP_DIALOG_OPTION {u"skip-dialog", true}; constexpr const TriStateBoolOption SKIP_DIALOG_OPTION {"skip-dialog", true};
} }
QBtCommandLineParameters::QBtCommandLineParameters(const QProcessEnvironment &env) QBtCommandLineParameters::QBtCommandLineParameters(const QProcessEnvironment &env)
@ -465,13 +463,13 @@ QBtCommandLineParameters parseCommandLine(const QStringList &args)
return result; return result;
} }
QString wrapText(const QString &text, const int initialIndentation = USAGE_TEXT_COLUMN, const int wrapAtColumn = WRAP_AT_COLUMN) QString wrapText(const QString &text, int initialIndentation = USAGE_TEXT_COLUMN, int wrapAtColumn = WRAP_AT_COLUMN)
{ {
const QStringList words = text.split(u' '); QStringList words = text.split(u' ');
QStringList lines = {words.first()}; QStringList lines = {words.first()};
int currentLineMaxLength = wrapAtColumn - initialIndentation; int currentLineMaxLength = wrapAtColumn - initialIndentation;
for (const QString &word : asConst(words.sliced(1))) for (const QString &word : asConst(words.mid(1)))
{ {
if (lines.last().length() + word.length() + 1 < currentLineMaxLength) if (lines.last().length() + word.length() + 1 < currentLineMaxLength)
{ {
@ -491,12 +489,6 @@ QString makeUsage(const QString &prgName)
{ {
const QString indentation {USAGE_INDENTATION, u' '}; const QString indentation {USAGE_INDENTATION, u' '};
#if defined(Q_OS_WIN)
const QString noSplashCommand = u"set QBT_NO_SPLASH=1 && " + prgName;
#else
const QString noSplashCommand = u"QBT_NO_SPLASH=1 " + prgName;
#endif
const QString text = QCoreApplication::translate("CMD Options", "Usage:") + u'\n' const QString text = QCoreApplication::translate("CMD Options", "Usage:") + u'\n'
+ indentation + prgName + u' ' + QCoreApplication::translate("CMD Options", "[options] [(<filename> | <url>)...]") + u'\n' + indentation + prgName + u' ' + QCoreApplication::translate("CMD Options", "[options] [(<filename> | <url>)...]") + u'\n'
@ -548,7 +540,7 @@ QString makeUsage(const QString &prgName)
"'parameter-name', environment variable name is 'QBT_PARAMETER_NAME' (in upper " "'parameter-name', environment variable name is 'QBT_PARAMETER_NAME' (in upper "
"case, '-' replaced with '_'). To pass flag values, set the variable to '1' or " "case, '-' replaced with '_'). To pass flag values, set the variable to '1' or "
"'TRUE'. For example, to disable the splash screen: "), 0) + u'\n' "'TRUE'. For example, to disable the splash screen: "), 0) + u'\n'
+ noSplashCommand + u'\n' + u"QBT_NO_SPLASH=1 " + prgName + u'\n'
+ wrapText(QCoreApplication::translate("CMD Options", "Command line parameters take precedence over environment variables"), 0) + u'\n'; + wrapText(QCoreApplication::translate("CMD Options", "Command line parameters take precedence over environment variables"), 0) + u'\n';
return text; return text;

View file

@ -32,8 +32,8 @@
#include <QDateTime> #include <QDateTime>
#include <QDir> #include <QDir>
#include <QList>
#include <QTextStream> #include <QTextStream>
#include <QVector>
#include "base/global.h" #include "base/global.h"
#include "base/logger.h" #include "base/logger.h"
@ -175,15 +175,12 @@ void FileLogger::flushLog()
void FileLogger::openLogFile() void FileLogger::openLogFile()
{ {
if (!m_logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)) if (!m_logFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text)
|| !m_logFile.setPermissions(QFile::ReadOwner | QFile::WriteOwner))
{ {
LogMsg(tr("An error occurred while trying to open the log file. Logging to file is disabled. File: \"%1\". Error: \"%2\".") m_logFile.close();
.arg(m_logFile.fileName(), m_logFile.errorString()), Log::CRITICAL); LogMsg(tr("An error occurred while trying to open the log file. Logging to file is disabled."), Log::CRITICAL);
return;
} }
// best effort, don't report error
m_logFile.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
} }
void FileLogger::closeLogFile() void FileLogger::closeLogFile()

View file

@ -74,7 +74,6 @@
#include <windows.h> #include <windows.h>
#endif #endif
#include <QByteArray>
#include <QDataStream> #include <QDataStream>
#include <QFileInfo> #include <QFileInfo>
#include <QLocalServer> #include <QLocalServer>
@ -91,7 +90,7 @@ namespace QtLP_Private
#endif #endif
} }
const QByteArray ACK = QByteArrayLiteral("ack"); const char ACK[] = "ack";
QtLocalPeer::QtLocalPeer(const QString &path, QObject *parent) QtLocalPeer::QtLocalPeer(const QString &path, QObject *parent)
: QObject(parent) : QObject(parent)
@ -170,7 +169,7 @@ bool QtLocalPeer::sendMessage(const QString &message, const int timeout)
{ {
res &= socket.waitForReadyRead(timeout); // wait for ack res &= socket.waitForReadyRead(timeout); // wait for ack
if (res) if (res)
res &= (socket.read(ACK.size()) == ACK); res &= (socket.read(qstrlen(ACK)) == ACK);
} }
return res; return res;
} }
@ -221,7 +220,7 @@ void QtLocalPeer::receiveConnection()
return; return;
} }
QString message(QString::fromUtf8(uMsg)); QString message(QString::fromUtf8(uMsg));
socket->write(ACK); socket->write(ACK, qstrlen(ACK));
socket->waitForBytesWritten(1000); socket->waitForBytesWritten(1000);
socket->waitForDisconnected(1000); // make sure client reads ack socket->waitForDisconnected(1000); // make sure client reads ack
delete socket; delete socket;

View file

@ -71,8 +71,8 @@
#include <QFile> #include <QFile>
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
#include <QList>
#include <QString> #include <QString>
#include <QVector>
#endif #endif
namespace QtLP_Private namespace QtLP_Private
@ -105,7 +105,7 @@ namespace QtLP_Private
Qt::HANDLE m_writeMutex = nullptr; Qt::HANDLE m_writeMutex = nullptr;
Qt::HANDLE m_readMutex = nullptr; Qt::HANDLE m_readMutex = nullptr;
QList<Qt::HANDLE> m_readMutexes; QVector<Qt::HANDLE> m_readMutexes;
QString m_mutexName; QString m_mutexName;
#endif #endif

File diff suppressed because it is too large Load diff

View file

@ -6,9 +6,7 @@ add_library(qbt_base STATIC
applicationcomponent.h applicationcomponent.h
asyncfilestorage.h asyncfilestorage.h
bittorrent/abstractfilestorage.h bittorrent/abstractfilestorage.h
bittorrent/addtorrenterror.h
bittorrent/addtorrentparams.h bittorrent/addtorrentparams.h
bittorrent/announcetimepoint.h
bittorrent/bandwidthscheduler.h bittorrent/bandwidthscheduler.h
bittorrent/bencoderesumedatastorage.h bittorrent/bencoderesumedatastorage.h
bittorrent/cachestatus.h bittorrent/cachestatus.h
@ -55,7 +53,6 @@ add_library(qbt_base STATIC
concepts/stringable.h concepts/stringable.h
digest32.h digest32.h
exceptions.h exceptions.h
freediskspacechecker.h
global.h global.h
http/connection.h http/connection.h
http/httperror.h http/httperror.h
@ -161,7 +158,6 @@ add_library(qbt_base STATIC
bittorrent/trackerentry.cpp bittorrent/trackerentry.cpp
bittorrent/trackerentrystatus.cpp bittorrent/trackerentrystatus.cpp
exceptions.cpp exceptions.cpp
freediskspacechecker.cpp
http/connection.cpp http/connection.cpp
http/httperror.cpp http/httperror.cpp
http/requestparser.cpp http/requestparser.cpp

View file

@ -29,7 +29,6 @@
#include "addtorrentmanager.h" #include "addtorrentmanager.h"
#include "base/bittorrent/addtorrenterror.h"
#include "base/bittorrent/infohash.h" #include "base/bittorrent/infohash.h"
#include "base/bittorrent/session.h" #include "base/bittorrent/session.h"
#include "base/bittorrent/torrentdescriptor.h" #include "base/bittorrent/torrentdescriptor.h"
@ -141,7 +140,7 @@ void AddTorrentManager::onSessionTorrentAdded(BitTorrent::Torrent *torrent)
} }
} }
void AddTorrentManager::onSessionAddTorrentFailed(const BitTorrent::InfoHash &infoHash, const BitTorrent::AddTorrentError &reason) void AddTorrentManager::onSessionAddTorrentFailed(const BitTorrent::InfoHash &infoHash, const QString &reason)
{ {
if (const QString source = m_sourcesByInfoHash.take(infoHash); !source.isEmpty()) if (const QString source = m_sourcesByInfoHash.take(infoHash); !source.isEmpty())
{ {
@ -155,7 +154,7 @@ void AddTorrentManager::onSessionAddTorrentFailed(const BitTorrent::InfoHash &in
void AddTorrentManager::handleAddTorrentFailed(const QString &source, const QString &reason) void AddTorrentManager::handleAddTorrentFailed(const QString &source, const QString &reason)
{ {
LogMsg(tr("Failed to add torrent. Source: \"%1\". Reason: \"%2\"").arg(source, reason), Log::WARNING); LogMsg(tr("Failed to add torrent. Source: \"%1\". Reason: \"%2\"").arg(source, reason), Log::WARNING);
emit addTorrentFailed(source, {BitTorrent::AddTorrentError::Other, reason}); emit addTorrentFailed(source, reason);
} }
void AddTorrentManager::handleDuplicateTorrent(const QString &source void AddTorrentManager::handleDuplicateTorrent(const QString &source
@ -186,9 +185,9 @@ void AddTorrentManager::handleDuplicateTorrent(const QString &source
message = tr("Trackers are merged from new source"); message = tr("Trackers are merged from new source");
} }
LogMsg(tr("Detected an attempt to add a duplicate torrent. Source: %1. Existing torrent: \"%2\". Torrent infohash: %3. Result: %4") LogMsg(tr("Detected an attempt to add a duplicate torrent. Source: %1. Existing torrent: %2. Result: %3")
.arg(source, existingTorrent->name(), existingTorrent->infoHash().toString(), message)); .arg(source, existingTorrent->name(), message));
emit addTorrentFailed(source, {BitTorrent::AddTorrentError::DuplicateTorrent, message}); emit addTorrentFailed(source, message);
} }
void AddTorrentManager::setTorrentFileGuard(const QString &source, std::shared_ptr<TorrentFileGuard> torrentFileGuard) void AddTorrentManager::setTorrentFileGuard(const QString &source, std::shared_ptr<TorrentFileGuard> torrentFileGuard)

View file

@ -44,7 +44,6 @@ namespace BitTorrent
class Session; class Session;
class Torrent; class Torrent;
class TorrentDescriptor; class TorrentDescriptor;
struct AddTorrentError;
} }
namespace Net namespace Net
@ -67,7 +66,7 @@ public:
signals: signals:
void torrentAdded(const QString &source, BitTorrent::Torrent *torrent); void torrentAdded(const QString &source, BitTorrent::Torrent *torrent);
void addTorrentFailed(const QString &source, const BitTorrent::AddTorrentError &reason); void addTorrentFailed(const QString &source, const QString &reason);
protected: protected:
bool addTorrentToSession(const QString &source, const BitTorrent::TorrentDescriptor &torrentDescr bool addTorrentToSession(const QString &source, const BitTorrent::TorrentDescriptor &torrentDescr
@ -80,7 +79,7 @@ protected:
private: private:
void onDownloadFinished(const Net::DownloadResult &result); void onDownloadFinished(const Net::DownloadResult &result);
void onSessionTorrentAdded(BitTorrent::Torrent *torrent); void onSessionTorrentAdded(BitTorrent::Torrent *torrent);
void onSessionAddTorrentFailed(const BitTorrent::InfoHash &infoHash, const BitTorrent::AddTorrentError &reason); void onSessionAddTorrentFailed(const BitTorrent::InfoHash &infoHash, const QString &reason);
bool processTorrent(const QString &source, const BitTorrent::TorrentDescriptor &torrentDescr bool processTorrent(const QString &source, const BitTorrent::TorrentDescriptor &torrentDescr
, const BitTorrent::AddTorrentParams &addTorrentParams); , const BitTorrent::AddTorrentParams &addTorrentParams);

View file

@ -30,7 +30,7 @@
#include <QDir> #include <QDir>
#include <QHash> #include <QHash>
#include <QList> #include <QVector>
#include "base/exceptions.h" #include "base/exceptions.h"
#include "base/path.h" #include "base/path.h"
@ -71,7 +71,7 @@ void BitTorrent::AbstractFileStorage::renameFolder(const Path &oldFolderPath, co
if (newFolderPath.isAbsolute()) if (newFolderPath.isAbsolute())
throw RuntimeError(tr("Absolute path isn't allowed: '%1'.").arg(newFolderPath.toString())); throw RuntimeError(tr("Absolute path isn't allowed: '%1'.").arg(newFolderPath.toString()));
QList<int> renamingFileIndexes; QVector<int> renamingFileIndexes;
renamingFileIndexes.reserve(filesCount()); renamingFileIndexes.reserve(filesCount());
for (int i = 0; i < filesCount(); ++i) for (int i = 0; i < filesCount(); ++i)

View file

@ -1,49 +0,0 @@
/*
* Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2025 Vladimir Golovnev <glassez@yandex.ru>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* In addition, as a special exception, the copyright holders give permission to
* link this program with the OpenSSL project's "OpenSSL" library (or with
* modified versions of it that use the same license as the "OpenSSL" library),
* and distribute the linked executables. You must obey the GNU General Public
* License in all respects for all of the code used other than "OpenSSL". If you
* modify file(s), you may extend this exception to your version of the file(s),
* but you are not obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
#pragma once
#include <QMetaType>
#include <QString>
namespace BitTorrent
{
struct AddTorrentError
{
enum Kind
{
DuplicateTorrent,
Other
};
Kind kind = Other;
QString message;
};
}
Q_DECLARE_METATYPE(BitTorrent::AddTorrentError)

View file

@ -30,9 +30,9 @@
#include <optional> #include <optional>
#include <QList>
#include <QMetaType> #include <QMetaType>
#include <QString> #include <QString>
#include <QVector>
#include "base/path.h" #include "base/path.h"
#include "base/tagset.h" #include "base/tagset.h"
@ -62,7 +62,7 @@ namespace BitTorrent
std::optional<bool> addStopped; std::optional<bool> addStopped;
std::optional<Torrent::StopCondition> stopCondition; std::optional<Torrent::StopCondition> stopCondition;
PathList filePaths; // used if TorrentInfo is set PathList filePaths; // used if TorrentInfo is set
QList<DownloadPriority> filePriorities; // used if TorrentInfo is set QVector<DownloadPriority> filePriorities; // used if TorrentInfo is set
bool skipChecking = false; bool skipChecking = false;
std::optional<BitTorrent::TorrentContentLayout> contentLayout; std::optional<BitTorrent::TorrentContentLayout> contentLayout;
std::optional<bool> useAutoTMM; std::optional<bool> useAutoTMM;

View file

@ -1,36 +0,0 @@
/*
* Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2024 Vladimir Golovnev <glassez@yandex.ru>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* In addition, as a special exception, the copyright holders give permission to
* link this program with the OpenSSL project's "OpenSSL" library (or with
* modified versions of it that use the same license as the "OpenSSL" library),
* and distribute the linked executables. You must obey the GNU General Public
* License in all respects for all of the code used other than "OpenSSL". If you
* modify file(s), you may extend this exception to your version of the file(s),
* but you are not obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
#pragma once
#include <chrono>
namespace BitTorrent
{
using AnnounceTimePoint = std::chrono::high_resolution_clock::time_point;
}

View file

@ -102,7 +102,7 @@ bool BandwidthScheduler::isTimeForAlternative() const
alternative = !alternative; alternative = !alternative;
break; break;
default: default:
Q_UNREACHABLE(); Q_ASSERT(false);
break; break;
} }
} }

View file

@ -64,7 +64,7 @@ namespace BitTorrent
void store(const TorrentID &id, const LoadTorrentParams &resumeData) const; void store(const TorrentID &id, const LoadTorrentParams &resumeData) const;
void remove(const TorrentID &id) const; void remove(const TorrentID &id) const;
void storeQueue(const QList<TorrentID> &queue) const; void storeQueue(const QVector<TorrentID> &queue) const;
private: private:
const Path m_resumeDataDir; const Path m_resumeDataDir;
@ -131,11 +131,10 @@ BitTorrent::BencodeResumeDataStorage::BencodeResumeDataStorage(const Path &path,
m_asyncWorker->moveToThread(m_ioThread.get()); m_asyncWorker->moveToThread(m_ioThread.get());
connect(m_ioThread.get(), &QThread::finished, m_asyncWorker, &QObject::deleteLater); connect(m_ioThread.get(), &QThread::finished, m_asyncWorker, &QObject::deleteLater);
m_ioThread->setObjectName("BencodeResumeDataStorage m_ioThread");
m_ioThread->start(); m_ioThread->start();
} }
QList<BitTorrent::TorrentID> BitTorrent::BencodeResumeDataStorage::registeredTorrents() const QVector<BitTorrent::TorrentID> BitTorrent::BencodeResumeDataStorage::registeredTorrents() const
{ {
return m_registeredTorrents; return m_registeredTorrents;
} }
@ -147,7 +146,7 @@ BitTorrent::LoadResumeDataResult BitTorrent::BencodeResumeDataStorage::load(cons
const Path torrentFilePath = path() / Path(idString + u".torrent"); const Path torrentFilePath = path() / Path(idString + u".torrent");
const qint64 torrentSizeLimit = Preferences::instance()->getTorrentFileSizeLimit(); const qint64 torrentSizeLimit = Preferences::instance()->getTorrentFileSizeLimit();
const auto resumeDataReadResult = Utils::IO::readFile(fastresumePath, -1); const auto resumeDataReadResult = Utils::IO::readFile(fastresumePath, torrentSizeLimit);
if (!resumeDataReadResult) if (!resumeDataReadResult)
return nonstd::make_unexpected(resumeDataReadResult.error().message); return nonstd::make_unexpected(resumeDataReadResult.error().message);
@ -189,13 +188,8 @@ void BitTorrent::BencodeResumeDataStorage::loadQueue(const Path &queueFilename)
return; return;
} }
QHash<TorrentID, qsizetype> registeredTorrentsIndexes;
registeredTorrentsIndexes.reserve(m_registeredTorrents.length());
for (qsizetype i = 0; i < m_registeredTorrents.length(); ++i)
registeredTorrentsIndexes.insert(m_registeredTorrents.at(i), i);
const QRegularExpression hashPattern {u"^([A-Fa-f0-9]{40})$"_s}; const QRegularExpression hashPattern {u"^([A-Fa-f0-9]{40})$"_s};
qsizetype queuePos = 0; int start = 0;
while (true) while (true)
{ {
const auto line = QString::fromLatin1(queueFile.readLine(lineMaxLength).trimmed()); const auto line = QString::fromLatin1(queueFile.readLine(lineMaxLength).trimmed());
@ -206,15 +200,11 @@ void BitTorrent::BencodeResumeDataStorage::loadQueue(const Path &queueFilename)
if (rxMatch.hasMatch()) if (rxMatch.hasMatch())
{ {
const auto torrentID = BitTorrent::TorrentID::fromString(rxMatch.captured(1)); const auto torrentID = BitTorrent::TorrentID::fromString(rxMatch.captured(1));
const qsizetype pos = registeredTorrentsIndexes.value(torrentID, -1); const int pos = m_registeredTorrents.indexOf(torrentID, start);
if (pos != -1) if (pos != -1)
{ {
if (pos != queuePos) std::swap(m_registeredTorrents[start], m_registeredTorrents[pos]);
{ ++start;
m_registeredTorrents.swapItemsAt(pos, queuePos);
registeredTorrentsIndexes.insert(m_registeredTorrents.at(pos), pos);
}
++queuePos;
} }
} }
} }
@ -299,11 +289,10 @@ BitTorrent::LoadResumeDataResult BitTorrent::BencodeResumeDataStorage::loadTorre
lt::add_torrent_params &p = torrentParams.ltAddTorrentParams; lt::add_torrent_params &p = torrentParams.ltAddTorrentParams;
p = lt::read_resume_data(resumeDataRoot, ec); p = lt::read_resume_data(resumeDataRoot, ec);
if (ec)
return nonstd::make_unexpected(tr("Cannot parse resume data: %1").arg(QString::fromStdString(ec.message())));
if (!metadata.isEmpty()) if (!metadata.isEmpty())
{ {
const auto *pref = Preferences::instance();
const lt::bdecode_node torentInfoRoot = lt::bdecode(metadata, ec const lt::bdecode_node torentInfoRoot = lt::bdecode(metadata, ec
, nullptr, pref->getBdecodeDepthLimit(), pref->getBdecodeTokenLimit()); , nullptr, pref->getBdecodeDepthLimit(), pref->getBdecodeTokenLimit());
if (ec) if (ec)
@ -331,8 +320,6 @@ BitTorrent::LoadResumeDataResult BitTorrent::BencodeResumeDataStorage::loadTorre
p.save_path = Profile::instance()->fromPortablePath( p.save_path = Profile::instance()->fromPortablePath(
Path(fromLTString(p.save_path))).toString().toStdString(); Path(fromLTString(p.save_path))).toString().toStdString();
if (p.save_path.empty())
return nonstd::make_unexpected(tr("Corrupted resume data: %1").arg(tr("save_path is invalid")));
torrentParams.stopped = (p.flags & lt::torrent_flags::paused) && !(p.flags & lt::torrent_flags::auto_managed); torrentParams.stopped = (p.flags & lt::torrent_flags::paused) && !(p.flags & lt::torrent_flags::auto_managed);
torrentParams.operatingMode = (p.flags & lt::torrent_flags::paused) || (p.flags & lt::torrent_flags::auto_managed) torrentParams.operatingMode = (p.flags & lt::torrent_flags::paused) || (p.flags & lt::torrent_flags::auto_managed)
@ -351,9 +338,9 @@ BitTorrent::LoadResumeDataResult BitTorrent::BencodeResumeDataStorage::loadTorre
return torrentParams; return torrentParams;
} }
void BitTorrent::BencodeResumeDataStorage::store(const TorrentID &id, LoadTorrentParams resumeData) const void BitTorrent::BencodeResumeDataStorage::store(const TorrentID &id, const LoadTorrentParams &resumeData) const
{ {
QMetaObject::invokeMethod(m_asyncWorker, [this, id, resumeData = std::move(resumeData)] QMetaObject::invokeMethod(m_asyncWorker, [this, id, resumeData]()
{ {
m_asyncWorker->store(id, resumeData); m_asyncWorker->store(id, resumeData);
}); });
@ -367,7 +354,7 @@ void BitTorrent::BencodeResumeDataStorage::remove(const TorrentID &id) const
}); });
} }
void BitTorrent::BencodeResumeDataStorage::storeQueue(const QList<TorrentID> &queue) const void BitTorrent::BencodeResumeDataStorage::storeQueue(const QVector<TorrentID> &queue) const
{ {
QMetaObject::invokeMethod(m_asyncWorker, [this, queue]() QMetaObject::invokeMethod(m_asyncWorker, [this, queue]()
{ {
@ -473,7 +460,7 @@ void BitTorrent::BencodeResumeDataStorage::Worker::remove(const TorrentID &id) c
Utils::Fs::removeFile(m_resumeDataDir / torrentFilename); Utils::Fs::removeFile(m_resumeDataDir / torrentFilename);
} }
void BitTorrent::BencodeResumeDataStorage::Worker::storeQueue(const QList<TorrentID> &queue) const void BitTorrent::BencodeResumeDataStorage::Worker::storeQueue(const QVector<TorrentID> &queue) const
{ {
QByteArray data; QByteArray data;
data.reserve(((BitTorrent::TorrentID::length() * 2) + 1) * queue.size()); data.reserve(((BitTorrent::TorrentID::length() * 2) + 1) * queue.size());

View file

@ -29,7 +29,7 @@
#pragma once #pragma once
#include <QDir> #include <QDir>
#include <QList> #include <QVector>
#include "base/pathfwd.h" #include "base/pathfwd.h"
#include "base/utils/thread.h" #include "base/utils/thread.h"
@ -37,6 +37,7 @@
#include "resumedatastorage.h" #include "resumedatastorage.h"
class QByteArray; class QByteArray;
class QThread;
namespace BitTorrent namespace BitTorrent
{ {
@ -48,18 +49,18 @@ namespace BitTorrent
public: public:
explicit BencodeResumeDataStorage(const Path &path, QObject *parent = nullptr); explicit BencodeResumeDataStorage(const Path &path, QObject *parent = nullptr);
QList<TorrentID> registeredTorrents() const override; QVector<TorrentID> registeredTorrents() const override;
LoadResumeDataResult load(const TorrentID &id) const override; LoadResumeDataResult load(const TorrentID &id) const override;
void store(const TorrentID &id, LoadTorrentParams resumeData) const override; void store(const TorrentID &id, const LoadTorrentParams &resumeData) const override;
void remove(const TorrentID &id) const override; void remove(const TorrentID &id) const override;
void storeQueue(const QList<TorrentID> &queue) const override; void storeQueue(const QVector<TorrentID> &queue) const override;
private: private:
void doLoadAll() const override; void doLoadAll() const override;
void loadQueue(const Path &queueFilename); void loadQueue(const Path &queueFilename);
LoadResumeDataResult loadTorrentResumeData(const QByteArray &data, const QByteArray &metadata) const; LoadResumeDataResult loadTorrentResumeData(const QByteArray &data, const QByteArray &metadata) const;
QList<TorrentID> m_registeredTorrents; QVector<TorrentID> m_registeredTorrents;
Utils::Thread::UniquePtr m_ioThread; Utils::Thread::UniquePtr m_ioThread;
class Worker; class Worker;

View file

@ -52,7 +52,7 @@ BitTorrent::CategoryOptions BitTorrent::CategoryOptions::fromJSON(const QJsonObj
QJsonObject BitTorrent::CategoryOptions::toJSON() const QJsonObject BitTorrent::CategoryOptions::toJSON() const
{ {
QJsonValue downloadPathValue = QJsonValue::Null; QJsonValue downloadPathValue = QJsonValue::Undefined;
if (downloadPath) if (downloadPath)
{ {
if (downloadPath->enabled) if (downloadPath->enabled)

View file

@ -1,6 +1,6 @@
/* /*
* Bittorrent Client using Qt and libtorrent. * Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2021-2025 Vladimir Golovnev <glassez@yandex.ru> * Copyright (C) 2021-2023 Vladimir Golovnev <glassez@yandex.ru>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
@ -41,7 +41,6 @@
#include <QByteArray> #include <QByteArray>
#include <QDebug> #include <QDebug>
#include <QList>
#include <QMutex> #include <QMutex>
#include <QSet> #include <QSet>
#include <QSqlDatabase> #include <QSqlDatabase>
@ -49,6 +48,7 @@
#include <QSqlQuery> #include <QSqlQuery>
#include <QSqlRecord> #include <QSqlRecord>
#include <QThread> #include <QThread>
#include <QVector>
#include <QWaitCondition> #include <QWaitCondition>
#include "base/exceptions.h" #include "base/exceptions.h"
@ -86,7 +86,7 @@ namespace
class StoreJob final : public Job class StoreJob final : public Job
{ {
public: public:
StoreJob(const TorrentID &torrentID, LoadTorrentParams resumeData); StoreJob(const TorrentID &torrentID, const LoadTorrentParams &resumeData);
void perform(QSqlDatabase db) override; void perform(QSqlDatabase db) override;
private: private:
@ -107,11 +107,11 @@ namespace
class StoreQueueJob final : public Job class StoreQueueJob final : public Job
{ {
public: public:
explicit StoreQueueJob(const QList<TorrentID> &queue); explicit StoreQueueJob(const QVector<TorrentID> &queue);
void perform(QSqlDatabase db) override; void perform(QSqlDatabase db) override;
private: private:
const QList<TorrentID> m_queue; const QVector<TorrentID> m_queue;
}; };
struct Column struct Column
@ -120,35 +120,36 @@ namespace
QString placeholder; QString placeholder;
}; };
Column makeColumn(const QString &columnName) Column makeColumn(const char *columnName)
{ {
return {.name = columnName, .placeholder = (u':' + columnName)}; const QString name = QString::fromLatin1(columnName);
return {.name = name, .placeholder = (u':' + name)};
} }
const Column DB_COLUMN_ID = makeColumn(u"id"_s); const Column DB_COLUMN_ID = makeColumn("id");
const Column DB_COLUMN_TORRENT_ID = makeColumn(u"torrent_id"_s); const Column DB_COLUMN_TORRENT_ID = makeColumn("torrent_id");
const Column DB_COLUMN_QUEUE_POSITION = makeColumn(u"queue_position"_s); const Column DB_COLUMN_QUEUE_POSITION = makeColumn("queue_position");
const Column DB_COLUMN_NAME = makeColumn(u"name"_s); const Column DB_COLUMN_NAME = makeColumn("name");
const Column DB_COLUMN_CATEGORY = makeColumn(u"category"_s); const Column DB_COLUMN_CATEGORY = makeColumn("category");
const Column DB_COLUMN_TAGS = makeColumn(u"tags"_s); const Column DB_COLUMN_TAGS = makeColumn("tags");
const Column DB_COLUMN_TARGET_SAVE_PATH = makeColumn(u"target_save_path"_s); const Column DB_COLUMN_TARGET_SAVE_PATH = makeColumn("target_save_path");
const Column DB_COLUMN_DOWNLOAD_PATH = makeColumn(u"download_path"_s); const Column DB_COLUMN_DOWNLOAD_PATH = makeColumn("download_path");
const Column DB_COLUMN_CONTENT_LAYOUT = makeColumn(u"content_layout"_s); const Column DB_COLUMN_CONTENT_LAYOUT = makeColumn("content_layout");
const Column DB_COLUMN_RATIO_LIMIT = makeColumn(u"ratio_limit"_s); const Column DB_COLUMN_RATIO_LIMIT = makeColumn("ratio_limit");
const Column DB_COLUMN_SEEDING_TIME_LIMIT = makeColumn(u"seeding_time_limit"_s); const Column DB_COLUMN_SEEDING_TIME_LIMIT = makeColumn("seeding_time_limit");
const Column DB_COLUMN_INACTIVE_SEEDING_TIME_LIMIT = makeColumn(u"inactive_seeding_time_limit"_s); const Column DB_COLUMN_INACTIVE_SEEDING_TIME_LIMIT = makeColumn("inactive_seeding_time_limit");
const Column DB_COLUMN_SHARE_LIMIT_ACTION = makeColumn(u"share_limit_action"_s); const Column DB_COLUMN_SHARE_LIMIT_ACTION = makeColumn("share_limit_action");
const Column DB_COLUMN_HAS_OUTER_PIECES_PRIORITY = makeColumn(u"has_outer_pieces_priority"_s); const Column DB_COLUMN_HAS_OUTER_PIECES_PRIORITY = makeColumn("has_outer_pieces_priority");
const Column DB_COLUMN_HAS_SEED_STATUS = makeColumn(u"has_seed_status"_s); const Column DB_COLUMN_HAS_SEED_STATUS = makeColumn("has_seed_status");
const Column DB_COLUMN_OPERATING_MODE = makeColumn(u"operating_mode"_s); const Column DB_COLUMN_OPERATING_MODE = makeColumn("operating_mode");
const Column DB_COLUMN_STOPPED = makeColumn(u"stopped"_s); const Column DB_COLUMN_STOPPED = makeColumn("stopped");
const Column DB_COLUMN_STOP_CONDITION = makeColumn(u"stop_condition"_s); const Column DB_COLUMN_STOP_CONDITION = makeColumn("stop_condition");
const Column DB_COLUMN_SSL_CERTIFICATE = makeColumn(u"ssl_certificate"_s); const Column DB_COLUMN_SSL_CERTIFICATE = makeColumn("ssl_certificate");
const Column DB_COLUMN_SSL_PRIVATE_KEY = makeColumn(u"ssl_private_key"_s); const Column DB_COLUMN_SSL_PRIVATE_KEY = makeColumn("ssl_private_key");
const Column DB_COLUMN_SSL_DH_PARAMS = makeColumn(u"ssl_dh_params"_s); const Column DB_COLUMN_SSL_DH_PARAMS = makeColumn("ssl_dh_params");
const Column DB_COLUMN_RESUMEDATA = makeColumn(u"libtorrent_resume_data"_s); const Column DB_COLUMN_RESUMEDATA = makeColumn("libtorrent_resume_data");
const Column DB_COLUMN_METADATA = makeColumn(u"metadata"_s); const Column DB_COLUMN_METADATA = makeColumn("metadata");
const Column DB_COLUMN_VALUE = makeColumn(u"value"_s); const Column DB_COLUMN_VALUE = makeColumn("value");
template <typename LTStr> template <typename LTStr>
QString fromLTString(const LTStr &str) QString fromLTString(const LTStr &str)
@ -167,7 +168,7 @@ namespace
return u"CREATE TABLE %1 (%2)"_s.arg(quoted(tableName), items.join(u',')); return u"CREATE TABLE %1 (%2)"_s.arg(quoted(tableName), items.join(u','));
} }
std::pair<QString, QString> joinColumns(const QList<Column> &columns) std::pair<QString, QString> joinColumns(const QVector<Column> &columns)
{ {
int namesSize = columns.size(); int namesSize = columns.size();
int valuesSize = columns.size(); int valuesSize = columns.size();
@ -192,30 +193,104 @@ namespace
return std::make_pair(names, values); return std::make_pair(names, values);
} }
QString makeInsertStatement(const QString &tableName, const QList<Column> &columns) QString makeInsertStatement(const QString &tableName, const QVector<Column> &columns)
{ {
const auto [names, values] = joinColumns(columns); const auto [names, values] = joinColumns(columns);
return u"INSERT INTO %1 (%2) VALUES (%3)"_s return u"INSERT INTO %1 (%2) VALUES (%3)"_s
.arg(quoted(tableName), names, values); .arg(quoted(tableName), names, values);
} }
QString makeUpdateStatement(const QString &tableName, const QList<Column> &columns) QString makeUpdateStatement(const QString &tableName, const QVector<Column> &columns)
{ {
const auto [names, values] = joinColumns(columns); const auto [names, values] = joinColumns(columns);
return u"UPDATE %1 SET (%2) = (%3)"_s return u"UPDATE %1 SET (%2) = (%3)"_s
.arg(quoted(tableName), names, values); .arg(quoted(tableName), names, values);
} }
QString makeOnConflictUpdateStatement(const Column &constraint, const QList<Column> &columns) QString makeOnConflictUpdateStatement(const Column &constraint, const QVector<Column> &columns)
{ {
const auto [names, values] = joinColumns(columns); const auto [names, values] = joinColumns(columns);
return u" ON CONFLICT (%1) DO UPDATE SET (%2) = (%3)"_s return u" ON CONFLICT (%1) DO UPDATE SET (%2) = (%3)"_s
.arg(quoted(constraint.name), names, values); .arg(quoted(constraint.name), names, values);
} }
QString makeColumnDefinition(const Column &column, const QString &definition) QString makeColumnDefinition(const Column &column, const char *definition)
{ {
return u"%1 %2"_s.arg(quoted(column.name), definition); return u"%1 %2"_s.arg(quoted(column.name), QString::fromLatin1(definition));
}
LoadTorrentParams parseQueryResultRow(const QSqlQuery &query)
{
LoadTorrentParams resumeData;
resumeData.name = query.value(DB_COLUMN_NAME.name).toString();
resumeData.category = query.value(DB_COLUMN_CATEGORY.name).toString();
const QString tagsData = query.value(DB_COLUMN_TAGS.name).toString();
if (!tagsData.isEmpty())
{
const QStringList tagList = tagsData.split(u',');
resumeData.tags.insert(tagList.cbegin(), tagList.cend());
}
resumeData.hasFinishedStatus = query.value(DB_COLUMN_HAS_SEED_STATUS.name).toBool();
resumeData.firstLastPiecePriority = query.value(DB_COLUMN_HAS_OUTER_PIECES_PRIORITY.name).toBool();
resumeData.ratioLimit = query.value(DB_COLUMN_RATIO_LIMIT.name).toInt() / 1000.0;
resumeData.seedingTimeLimit = query.value(DB_COLUMN_SEEDING_TIME_LIMIT.name).toInt();
resumeData.inactiveSeedingTimeLimit = query.value(DB_COLUMN_INACTIVE_SEEDING_TIME_LIMIT.name).toInt();
resumeData.shareLimitAction = Utils::String::toEnum<ShareLimitAction>(
query.value(DB_COLUMN_SHARE_LIMIT_ACTION.name).toString(), ShareLimitAction::Default);
resumeData.contentLayout = Utils::String::toEnum<TorrentContentLayout>(
query.value(DB_COLUMN_CONTENT_LAYOUT.name).toString(), TorrentContentLayout::Original);
resumeData.operatingMode = Utils::String::toEnum<TorrentOperatingMode>(
query.value(DB_COLUMN_OPERATING_MODE.name).toString(), TorrentOperatingMode::AutoManaged);
resumeData.stopped = query.value(DB_COLUMN_STOPPED.name).toBool();
resumeData.stopCondition = Utils::String::toEnum(
query.value(DB_COLUMN_STOP_CONDITION.name).toString(), Torrent::StopCondition::None);
resumeData.sslParameters =
{
.certificate = QSslCertificate(query.value(DB_COLUMN_SSL_CERTIFICATE.name).toByteArray()),
.privateKey = Utils::SSLKey::load(query.value(DB_COLUMN_SSL_PRIVATE_KEY.name).toByteArray()),
.dhParams = query.value(DB_COLUMN_SSL_DH_PARAMS.name).toByteArray()
};
resumeData.savePath = Profile::instance()->fromPortablePath(
Path(query.value(DB_COLUMN_TARGET_SAVE_PATH.name).toString()));
resumeData.useAutoTMM = resumeData.savePath.isEmpty();
if (!resumeData.useAutoTMM)
{
resumeData.downloadPath = Profile::instance()->fromPortablePath(
Path(query.value(DB_COLUMN_DOWNLOAD_PATH.name).toString()));
}
const QByteArray bencodedResumeData = query.value(DB_COLUMN_RESUMEDATA.name).toByteArray();
const auto *pref = Preferences::instance();
const int bdecodeDepthLimit = pref->getBdecodeDepthLimit();
const int bdecodeTokenLimit = pref->getBdecodeTokenLimit();
lt::error_code ec;
const lt::bdecode_node resumeDataRoot = lt::bdecode(bencodedResumeData, ec
, nullptr, bdecodeDepthLimit, bdecodeTokenLimit);
lt::add_torrent_params &p = resumeData.ltAddTorrentParams;
p = lt::read_resume_data(resumeDataRoot, ec);
if (const QByteArray bencodedMetadata = query.value(DB_COLUMN_METADATA.name).toByteArray()
; !bencodedMetadata.isEmpty())
{
const lt::bdecode_node torentInfoRoot = lt::bdecode(bencodedMetadata, ec
, nullptr, bdecodeDepthLimit, bdecodeTokenLimit);
p.ti = std::make_shared<lt::torrent_info>(torentInfoRoot, ec);
}
p.save_path = Profile::instance()->fromPortablePath(Path(fromLTString(p.save_path)))
.toString().toStdString();
if (p.flags & lt::torrent_flags::stop_when_ready)
{
p.flags &= ~lt::torrent_flags::stop_when_ready;
resumeData.stopCondition = Torrent::StopCondition::FilesChecked;
}
return resumeData;
} }
} }
@ -231,9 +306,9 @@ namespace BitTorrent
void run() override; void run() override;
void requestInterruption(); void requestInterruption();
void store(const TorrentID &id, LoadTorrentParams resumeData); void store(const TorrentID &id, const LoadTorrentParams &resumeData);
void remove(const TorrentID &id); void remove(const TorrentID &id);
void storeQueue(const QList<TorrentID> &queue); void storeQueue(const QVector<TorrentID> &queue);
private: private:
void addJob(std::unique_ptr<Job> job); void addJob(std::unique_ptr<Job> job);
@ -250,6 +325,7 @@ namespace BitTorrent
BitTorrent::DBResumeDataStorage::DBResumeDataStorage(const Path &dbPath, QObject *parent) BitTorrent::DBResumeDataStorage::DBResumeDataStorage(const Path &dbPath, QObject *parent)
: ResumeDataStorage(dbPath, parent) : ResumeDataStorage(dbPath, parent)
, m_ioThread {new QThread}
{ {
const bool needCreateDB = !dbPath.exists(); const bool needCreateDB = !dbPath.exists();
@ -280,7 +356,7 @@ BitTorrent::DBResumeDataStorage::~DBResumeDataStorage()
QSqlDatabase::removeDatabase(DB_CONNECTION_NAME); QSqlDatabase::removeDatabase(DB_CONNECTION_NAME);
} }
QList<BitTorrent::TorrentID> BitTorrent::DBResumeDataStorage::registeredTorrents() const QVector<BitTorrent::TorrentID> BitTorrent::DBResumeDataStorage::registeredTorrents() const
{ {
const auto selectTorrentIDStatement = u"SELECT %1 FROM %2 ORDER BY %3;"_s const auto selectTorrentIDStatement = u"SELECT %1 FROM %2 ORDER BY %3;"_s
.arg(quoted(DB_COLUMN_TORRENT_ID.name), quoted(DB_TABLE_TORRENTS), quoted(DB_COLUMN_QUEUE_POSITION.name)); .arg(quoted(DB_COLUMN_TORRENT_ID.name), quoted(DB_TABLE_TORRENTS), quoted(DB_COLUMN_QUEUE_POSITION.name));
@ -291,7 +367,7 @@ QList<BitTorrent::TorrentID> BitTorrent::DBResumeDataStorage::registeredTorrents
if (!query.exec(selectTorrentIDStatement)) if (!query.exec(selectTorrentIDStatement))
throw RuntimeError(query.lastError().text()); throw RuntimeError(query.lastError().text());
QList<TorrentID> registeredTorrents; QVector<TorrentID> registeredTorrents;
registeredTorrents.reserve(query.size()); registeredTorrents.reserve(query.size());
while (query.next()) while (query.next())
registeredTorrents.append(BitTorrent::TorrentID::fromString(query.value(0).toString())); registeredTorrents.append(BitTorrent::TorrentID::fromString(query.value(0).toString()));
@ -327,9 +403,9 @@ BitTorrent::LoadResumeDataResult BitTorrent::DBResumeDataStorage::load(const Tor
return parseQueryResultRow(query); return parseQueryResultRow(query);
} }
void BitTorrent::DBResumeDataStorage::store(const TorrentID &id, LoadTorrentParams resumeData) const void BitTorrent::DBResumeDataStorage::store(const TorrentID &id, const LoadTorrentParams &resumeData) const
{ {
m_asyncWorker->store(id, std::move(resumeData)); m_asyncWorker->store(id, resumeData);
} }
void BitTorrent::DBResumeDataStorage::remove(const BitTorrent::TorrentID &id) const void BitTorrent::DBResumeDataStorage::remove(const BitTorrent::TorrentID &id) const
@ -337,7 +413,7 @@ void BitTorrent::DBResumeDataStorage::remove(const BitTorrent::TorrentID &id) co
m_asyncWorker->remove(id); m_asyncWorker->remove(id);
} }
void BitTorrent::DBResumeDataStorage::storeQueue(const QList<TorrentID> &queue) const void BitTorrent::DBResumeDataStorage::storeQueue(const QVector<TorrentID> &queue) const
{ {
m_asyncWorker->storeQueue(queue); m_asyncWorker->storeQueue(queue);
} }
@ -362,7 +438,7 @@ void BitTorrent::DBResumeDataStorage::doLoadAll() const
if (!query.exec(selectTorrentIDStatement)) if (!query.exec(selectTorrentIDStatement))
throw RuntimeError(query.lastError().text()); throw RuntimeError(query.lastError().text());
QList<TorrentID> registeredTorrents; QVector<TorrentID> registeredTorrents;
registeredTorrents.reserve(query.size()); registeredTorrents.reserve(query.size());
while (query.next()) while (query.next())
registeredTorrents.append(TorrentID::fromString(query.value(0).toString())); registeredTorrents.append(TorrentID::fromString(query.value(0).toString()));
@ -436,9 +512,9 @@ void BitTorrent::DBResumeDataStorage::createDB() const
try try
{ {
const QStringList tableMetaItems = { const QStringList tableMetaItems = {
makeColumnDefinition(DB_COLUMN_ID, u"INTEGER PRIMARY KEY"_s), makeColumnDefinition(DB_COLUMN_ID, "INTEGER PRIMARY KEY"),
makeColumnDefinition(DB_COLUMN_NAME, u"TEXT NOT NULL UNIQUE"_s), makeColumnDefinition(DB_COLUMN_NAME, "TEXT NOT NULL UNIQUE"),
makeColumnDefinition(DB_COLUMN_VALUE, u"BLOB"_s) makeColumnDefinition(DB_COLUMN_VALUE, "BLOB")
}; };
const QString createTableMetaQuery = makeCreateTableStatement(DB_TABLE_META, tableMetaItems); const QString createTableMetaQuery = makeCreateTableStatement(DB_TABLE_META, tableMetaItems);
if (!query.exec(createTableMetaQuery)) if (!query.exec(createTableMetaQuery))
@ -455,29 +531,29 @@ void BitTorrent::DBResumeDataStorage::createDB() const
throw RuntimeError(query.lastError().text()); throw RuntimeError(query.lastError().text());
const QStringList tableTorrentsItems = { const QStringList tableTorrentsItems = {
makeColumnDefinition(DB_COLUMN_ID, u"INTEGER PRIMARY KEY"_s), makeColumnDefinition(DB_COLUMN_ID, "INTEGER PRIMARY KEY"),
makeColumnDefinition(DB_COLUMN_TORRENT_ID, u"BLOB NOT NULL UNIQUE"_s), makeColumnDefinition(DB_COLUMN_TORRENT_ID, "BLOB NOT NULL UNIQUE"),
makeColumnDefinition(DB_COLUMN_QUEUE_POSITION, u"INTEGER NOT NULL DEFAULT -1"_s), makeColumnDefinition(DB_COLUMN_QUEUE_POSITION, "INTEGER NOT NULL DEFAULT -1"),
makeColumnDefinition(DB_COLUMN_NAME, u"TEXT"_s), makeColumnDefinition(DB_COLUMN_NAME, "TEXT"),
makeColumnDefinition(DB_COLUMN_CATEGORY, u"TEXT"_s), makeColumnDefinition(DB_COLUMN_CATEGORY, "TEXT"),
makeColumnDefinition(DB_COLUMN_TAGS, u"TEXT"_s), makeColumnDefinition(DB_COLUMN_TAGS, "TEXT"),
makeColumnDefinition(DB_COLUMN_TARGET_SAVE_PATH, u"TEXT"_s), makeColumnDefinition(DB_COLUMN_TARGET_SAVE_PATH, "TEXT"),
makeColumnDefinition(DB_COLUMN_DOWNLOAD_PATH, u"TEXT"_s), makeColumnDefinition(DB_COLUMN_DOWNLOAD_PATH, "TEXT"),
makeColumnDefinition(DB_COLUMN_CONTENT_LAYOUT, u"TEXT NOT NULL"_s), makeColumnDefinition(DB_COLUMN_CONTENT_LAYOUT, "TEXT NOT NULL"),
makeColumnDefinition(DB_COLUMN_RATIO_LIMIT, u"INTEGER NOT NULL"_s), makeColumnDefinition(DB_COLUMN_RATIO_LIMIT, "INTEGER NOT NULL"),
makeColumnDefinition(DB_COLUMN_SEEDING_TIME_LIMIT, u"INTEGER NOT NULL"_s), makeColumnDefinition(DB_COLUMN_SEEDING_TIME_LIMIT, "INTEGER NOT NULL"),
makeColumnDefinition(DB_COLUMN_INACTIVE_SEEDING_TIME_LIMIT, u"INTEGER NOT NULL"_s), makeColumnDefinition(DB_COLUMN_INACTIVE_SEEDING_TIME_LIMIT, "INTEGER NOT NULL"),
makeColumnDefinition(DB_COLUMN_SHARE_LIMIT_ACTION, u"TEXT NOT NULL DEFAULT `Default`"_s), makeColumnDefinition(DB_COLUMN_SHARE_LIMIT_ACTION, "TEXT NOT NULL DEFAULT `Default`"),
makeColumnDefinition(DB_COLUMN_HAS_OUTER_PIECES_PRIORITY, u"INTEGER NOT NULL"_s), makeColumnDefinition(DB_COLUMN_HAS_OUTER_PIECES_PRIORITY, "INTEGER NOT NULL"),
makeColumnDefinition(DB_COLUMN_HAS_SEED_STATUS, u"INTEGER NOT NULL"_s), makeColumnDefinition(DB_COLUMN_HAS_SEED_STATUS, "INTEGER NOT NULL"),
makeColumnDefinition(DB_COLUMN_OPERATING_MODE, u"TEXT NOT NULL"_s), makeColumnDefinition(DB_COLUMN_OPERATING_MODE, "TEXT NOT NULL"),
makeColumnDefinition(DB_COLUMN_STOPPED, u"INTEGER NOT NULL"_s), makeColumnDefinition(DB_COLUMN_STOPPED, "INTEGER NOT NULL"),
makeColumnDefinition(DB_COLUMN_STOP_CONDITION, u"TEXT NOT NULL DEFAULT `None`"_s), makeColumnDefinition(DB_COLUMN_STOP_CONDITION, "TEXT NOT NULL DEFAULT `None`"),
makeColumnDefinition(DB_COLUMN_SSL_CERTIFICATE, u"TEXT"_s), makeColumnDefinition(DB_COLUMN_SSL_CERTIFICATE, "TEXT"),
makeColumnDefinition(DB_COLUMN_SSL_PRIVATE_KEY, u"TEXT"_s), makeColumnDefinition(DB_COLUMN_SSL_PRIVATE_KEY, "TEXT"),
makeColumnDefinition(DB_COLUMN_SSL_DH_PARAMS, u"TEXT"_s), makeColumnDefinition(DB_COLUMN_SSL_DH_PARAMS, "TEXT"),
makeColumnDefinition(DB_COLUMN_RESUMEDATA, u"BLOB NOT NULL"_s), makeColumnDefinition(DB_COLUMN_RESUMEDATA, "BLOB NOT NULL"),
makeColumnDefinition(DB_COLUMN_METADATA, u"BLOB"_s) makeColumnDefinition(DB_COLUMN_METADATA, "BLOB")
}; };
const QString createTableTorrentsQuery = makeCreateTableStatement(DB_TABLE_TORRENTS, tableTorrentsItems); const QString createTableTorrentsQuery = makeCreateTableStatement(DB_TABLE_TORRENTS, tableTorrentsItems);
if (!query.exec(createTableTorrentsQuery)) if (!query.exec(createTableTorrentsQuery))
@ -515,7 +591,7 @@ void BitTorrent::DBResumeDataStorage::updateDB(const int fromVersion) const
try try
{ {
const auto addColumn = [&query](const QString &table, const Column &column, const QString &definition) const auto addColumn = [&query](const QString &table, const Column &column, const char *definition)
{ {
const auto testQuery = u"SELECT COUNT(%1) FROM %2;"_s.arg(quoted(column.name), quoted(table)); const auto testQuery = u"SELECT COUNT(%1) FROM %2;"_s.arg(quoted(column.name), quoted(table));
if (query.exec(testQuery)) if (query.exec(testQuery))
@ -527,10 +603,10 @@ void BitTorrent::DBResumeDataStorage::updateDB(const int fromVersion) const
}; };
if (fromVersion <= 1) if (fromVersion <= 1)
addColumn(DB_TABLE_TORRENTS, DB_COLUMN_DOWNLOAD_PATH, u"TEXT"_s); addColumn(DB_TABLE_TORRENTS, DB_COLUMN_DOWNLOAD_PATH, "TEXT");
if (fromVersion <= 2) if (fromVersion <= 2)
addColumn(DB_TABLE_TORRENTS, DB_COLUMN_STOP_CONDITION, u"TEXT NOT NULL DEFAULT `None`"_s); addColumn(DB_TABLE_TORRENTS, DB_COLUMN_STOP_CONDITION, "TEXT NOT NULL DEFAULT `None`");
if (fromVersion <= 3) if (fromVersion <= 3)
{ {
@ -542,17 +618,17 @@ void BitTorrent::DBResumeDataStorage::updateDB(const int fromVersion) const
} }
if (fromVersion <= 4) if (fromVersion <= 4)
addColumn(DB_TABLE_TORRENTS, DB_COLUMN_INACTIVE_SEEDING_TIME_LIMIT, u"INTEGER NOT NULL DEFAULT -2"_s); addColumn(DB_TABLE_TORRENTS, DB_COLUMN_INACTIVE_SEEDING_TIME_LIMIT, "INTEGER NOT NULL DEFAULT -2");
if (fromVersion <= 5) if (fromVersion <= 5)
{ {
addColumn(DB_TABLE_TORRENTS, DB_COLUMN_SSL_CERTIFICATE, u"TEXT"_s); addColumn(DB_TABLE_TORRENTS, DB_COLUMN_SSL_CERTIFICATE, "TEXT");
addColumn(DB_TABLE_TORRENTS, DB_COLUMN_SSL_PRIVATE_KEY, u"TEXT"_s); addColumn(DB_TABLE_TORRENTS, DB_COLUMN_SSL_PRIVATE_KEY, "TEXT");
addColumn(DB_TABLE_TORRENTS, DB_COLUMN_SSL_DH_PARAMS, u"TEXT"_s); addColumn(DB_TABLE_TORRENTS, DB_COLUMN_SSL_DH_PARAMS, "TEXT");
} }
if (fromVersion <= 6) if (fromVersion <= 6)
addColumn(DB_TABLE_TORRENTS, DB_COLUMN_SHARE_LIMIT_ACTION, u"TEXT NOT NULL DEFAULT `Default`"_s); addColumn(DB_TABLE_TORRENTS, DB_COLUMN_SHARE_LIMIT_ACTION, "TEXT NOT NULL DEFAULT `Default`");
if (fromVersion == 7) if (fromVersion == 7)
{ {
@ -614,90 +690,6 @@ void BitTorrent::DBResumeDataStorage::enableWALMode() const
throw RuntimeError(tr("WAL mode is probably unsupported due to filesystem limitations.")); throw RuntimeError(tr("WAL mode is probably unsupported due to filesystem limitations."));
} }
LoadResumeDataResult DBResumeDataStorage::parseQueryResultRow(const QSqlQuery &query) const
{
LoadTorrentParams resumeData;
resumeData.name = query.value(DB_COLUMN_NAME.name).toString();
resumeData.category = query.value(DB_COLUMN_CATEGORY.name).toString();
const QString tagsData = query.value(DB_COLUMN_TAGS.name).toString();
if (!tagsData.isEmpty())
{
const QStringList tagList = tagsData.split(u',');
resumeData.tags.insert(tagList.cbegin(), tagList.cend());
}
resumeData.hasFinishedStatus = query.value(DB_COLUMN_HAS_SEED_STATUS.name).toBool();
resumeData.firstLastPiecePriority = query.value(DB_COLUMN_HAS_OUTER_PIECES_PRIORITY.name).toBool();
resumeData.ratioLimit = query.value(DB_COLUMN_RATIO_LIMIT.name).toInt() / 1000.0;
resumeData.seedingTimeLimit = query.value(DB_COLUMN_SEEDING_TIME_LIMIT.name).toInt();
resumeData.inactiveSeedingTimeLimit = query.value(DB_COLUMN_INACTIVE_SEEDING_TIME_LIMIT.name).toInt();
resumeData.shareLimitAction = Utils::String::toEnum<ShareLimitAction>(
query.value(DB_COLUMN_SHARE_LIMIT_ACTION.name).toString(), ShareLimitAction::Default);
resumeData.contentLayout = Utils::String::toEnum<TorrentContentLayout>(
query.value(DB_COLUMN_CONTENT_LAYOUT.name).toString(), TorrentContentLayout::Original);
resumeData.operatingMode = Utils::String::toEnum<TorrentOperatingMode>(
query.value(DB_COLUMN_OPERATING_MODE.name).toString(), TorrentOperatingMode::AutoManaged);
resumeData.stopped = query.value(DB_COLUMN_STOPPED.name).toBool();
resumeData.stopCondition = Utils::String::toEnum(
query.value(DB_COLUMN_STOP_CONDITION.name).toString(), Torrent::StopCondition::None);
resumeData.sslParameters =
{
.certificate = QSslCertificate(query.value(DB_COLUMN_SSL_CERTIFICATE.name).toByteArray()),
.privateKey = Utils::SSLKey::load(query.value(DB_COLUMN_SSL_PRIVATE_KEY.name).toByteArray()),
.dhParams = query.value(DB_COLUMN_SSL_DH_PARAMS.name).toByteArray()
};
resumeData.savePath = Profile::instance()->fromPortablePath(
Path(query.value(DB_COLUMN_TARGET_SAVE_PATH.name).toString()));
resumeData.useAutoTMM = resumeData.savePath.isEmpty();
if (!resumeData.useAutoTMM)
{
resumeData.downloadPath = Profile::instance()->fromPortablePath(
Path(query.value(DB_COLUMN_DOWNLOAD_PATH.name).toString()));
}
const QByteArray bencodedResumeData = query.value(DB_COLUMN_RESUMEDATA.name).toByteArray();
const auto *pref = Preferences::instance();
const int bdecodeDepthLimit = pref->getBdecodeDepthLimit();
const int bdecodeTokenLimit = pref->getBdecodeTokenLimit();
lt::error_code ec;
const lt::bdecode_node resumeDataRoot = lt::bdecode(bencodedResumeData, ec, nullptr, bdecodeDepthLimit, bdecodeTokenLimit);
if (ec)
return nonstd::make_unexpected(tr("Cannot parse resume data: %1").arg(QString::fromStdString(ec.message())));
lt::add_torrent_params &p = resumeData.ltAddTorrentParams;
p = lt::read_resume_data(resumeDataRoot, ec);
if (ec)
return nonstd::make_unexpected(tr("Cannot parse resume data: %1").arg(QString::fromStdString(ec.message())));
if (const QByteArray bencodedMetadata = query.value(DB_COLUMN_METADATA.name).toByteArray()
; !bencodedMetadata.isEmpty())
{
const lt::bdecode_node torentInfoRoot = lt::bdecode(bencodedMetadata, ec
, nullptr, bdecodeDepthLimit, bdecodeTokenLimit);
if (ec)
return nonstd::make_unexpected(tr("Cannot parse torrent info: %1").arg(QString::fromStdString(ec.message())));
p.ti = std::make_shared<lt::torrent_info>(torentInfoRoot, ec);
if (ec)
return nonstd::make_unexpected(tr("Cannot parse torrent info: %1").arg(QString::fromStdString(ec.message())));
}
p.save_path = Profile::instance()->fromPortablePath(Path(fromLTString(p.save_path)))
.toString().toStdString();
if (p.save_path.empty())
return nonstd::make_unexpected(tr("Corrupted resume data: %1").arg(tr("save_path is invalid")));
if (p.flags & lt::torrent_flags::stop_when_ready)
{
p.flags &= ~lt::torrent_flags::stop_when_ready;
resumeData.stopCondition = Torrent::StopCondition::FilesChecked;
}
return resumeData;
}
BitTorrent::DBResumeDataStorage::Worker::Worker(const Path &dbPath, QReadWriteLock &dbLock, QObject *parent) BitTorrent::DBResumeDataStorage::Worker::Worker(const Path &dbPath, QReadWriteLock &dbLock, QObject *parent)
: QThread(parent) : QThread(parent)
, m_path {dbPath} , m_path {dbPath}
@ -769,9 +761,9 @@ void DBResumeDataStorage::Worker::requestInterruption()
m_waitCondition.wakeAll(); m_waitCondition.wakeAll();
} }
void BitTorrent::DBResumeDataStorage::Worker::store(const TorrentID &id, LoadTorrentParams resumeData) void BitTorrent::DBResumeDataStorage::Worker::store(const TorrentID &id, const LoadTorrentParams &resumeData)
{ {
addJob(std::make_unique<StoreJob>(id, std::move(resumeData))); addJob(std::make_unique<StoreJob>(id, resumeData));
} }
void BitTorrent::DBResumeDataStorage::Worker::remove(const TorrentID &id) void BitTorrent::DBResumeDataStorage::Worker::remove(const TorrentID &id)
@ -779,7 +771,7 @@ void BitTorrent::DBResumeDataStorage::Worker::remove(const TorrentID &id)
addJob(std::make_unique<RemoveJob>(id)); addJob(std::make_unique<RemoveJob>(id));
} }
void BitTorrent::DBResumeDataStorage::Worker::storeQueue(const QList<TorrentID> &queue) void BitTorrent::DBResumeDataStorage::Worker::storeQueue(const QVector<TorrentID> &queue)
{ {
addJob(std::make_unique<StoreQueueJob>(queue)); addJob(std::make_unique<StoreQueueJob>(queue));
} }
@ -797,9 +789,9 @@ namespace
{ {
using namespace BitTorrent; using namespace BitTorrent;
StoreJob::StoreJob(const TorrentID &torrentID, LoadTorrentParams resumeData) StoreJob::StoreJob(const TorrentID &torrentID, const LoadTorrentParams &resumeData)
: m_torrentID {torrentID} : m_torrentID {torrentID}
, m_resumeData {std::move(resumeData)} , m_resumeData {resumeData}
{ {
} }
@ -829,7 +821,7 @@ StoreJob::StoreJob(const TorrentID &torrentID, LoadTorrentParams resumeData)
} }
} }
QList<Column> columns { QVector<Column> columns {
DB_COLUMN_TORRENT_ID, DB_COLUMN_TORRENT_ID,
DB_COLUMN_NAME, DB_COLUMN_NAME,
DB_COLUMN_CATEGORY, DB_COLUMN_CATEGORY,
@ -961,7 +953,7 @@ StoreJob::StoreJob(const TorrentID &torrentID, LoadTorrentParams resumeData)
} }
} }
StoreQueueJob::StoreQueueJob(const QList<TorrentID> &queue) StoreQueueJob::StoreQueueJob(const QVector<TorrentID> &queue)
: m_queue {queue} : m_queue {queue}
{ {
} }

View file

@ -1,6 +1,6 @@
/* /*
* Bittorrent Client using Qt and libtorrent. * Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2021-2025 Vladimir Golovnev <glassez@yandex.ru> * Copyright (C) 2021-2022 Vladimir Golovnev <glassez@yandex.ru>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
@ -31,9 +31,10 @@
#include <QReadWriteLock> #include <QReadWriteLock>
#include "base/pathfwd.h" #include "base/pathfwd.h"
#include "base/utils/thread.h"
#include "resumedatastorage.h" #include "resumedatastorage.h"
class QSqlQuery; class QThread;
namespace BitTorrent namespace BitTorrent
{ {
@ -46,12 +47,12 @@ namespace BitTorrent
explicit DBResumeDataStorage(const Path &dbPath, QObject *parent = nullptr); explicit DBResumeDataStorage(const Path &dbPath, QObject *parent = nullptr);
~DBResumeDataStorage() override; ~DBResumeDataStorage() override;
QList<TorrentID> registeredTorrents() const override; QVector<TorrentID> registeredTorrents() const override;
LoadResumeDataResult load(const TorrentID &id) const override; LoadResumeDataResult load(const TorrentID &id) const override;
void store(const TorrentID &id, LoadTorrentParams resumeData) const override; void store(const TorrentID &id, const LoadTorrentParams &resumeData) const override;
void remove(const TorrentID &id) const override; void remove(const TorrentID &id) const override;
void storeQueue(const QList<TorrentID> &queue) const override; void storeQueue(const QVector<TorrentID> &queue) const override;
private: private:
void doLoadAll() const override; void doLoadAll() const override;
@ -59,7 +60,8 @@ namespace BitTorrent
void createDB() const; void createDB() const;
void updateDB(int fromVersion) const; void updateDB(int fromVersion) const;
void enableWALMode() const; void enableWALMode() const;
LoadResumeDataResult parseQueryResultRow(const QSqlQuery &query) const;
Utils::Thread::UniquePtr m_ioThread;
class Worker; class Worker;
Worker *m_asyncWorker = nullptr; Worker *m_asyncWorker = nullptr;

View file

@ -1,6 +1,6 @@
/* /*
* Bittorrent Client using Qt and libtorrent. * Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2020-2025 Vladimir Golovnev <glassez@yandex.ru> * Copyright (C) 2020 Vladimir Golovnev <glassez@yandex.ru>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
@ -27,14 +27,13 @@
*/ */
#include "filesearcher.h" #include "filesearcher.h"
#include <QPromise>
#include "base/bittorrent/common.h" #include "base/bittorrent/common.h"
#include "base/bittorrent/infohash.h"
namespace void FileSearcher::search(const BitTorrent::TorrentID &id, const PathList &originalFileNames
, const Path &savePath, const Path &downloadPath, const bool forceAppendExt)
{ {
bool findInDir(const Path &dirPath, PathList &fileNames, const bool forceAppendExt) const auto findInDir = [](const Path &dirPath, PathList &fileNames, const bool forceAppendExt) -> bool
{ {
bool found = false; bool found = false;
for (Path &fileName : fileNames) for (Path &fileName : fileNames)
@ -59,12 +58,8 @@ namespace
} }
return found; return found;
} };
}
void FileSearcher::search(const PathList &originalFileNames, const Path &savePath
, const Path &downloadPath, const bool forceAppendExt, QPromise<FileSearchResult> &promise)
{
Path usedPath = savePath; Path usedPath = savePath;
PathList adjustedFileNames = originalFileNames; PathList adjustedFileNames = originalFileNames;
const bool found = findInDir(usedPath, adjustedFileNames, (forceAppendExt && downloadPath.isEmpty())); const bool found = findInDir(usedPath, adjustedFileNames, (forceAppendExt && downloadPath.isEmpty()));
@ -74,5 +69,5 @@ void FileSearcher::search(const PathList &originalFileNames, const Path &savePat
findInDir(usedPath, adjustedFileNames, forceAppendExt); findInDir(usedPath, adjustedFileNames, forceAppendExt);
} }
promise.addResult(FileSearchResult {.savePath = usedPath, .fileNames = adjustedFileNames}); emit searchFinished(id, usedPath, adjustedFileNames);
} }

View file

@ -1,6 +1,6 @@
/* /*
* Bittorrent Client using Qt and libtorrent. * Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2020-2025 Vladimir Golovnev <glassez@yandex.ru> * Copyright (C) 2020 Vladimir Golovnev <glassez@yandex.ru>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
@ -32,13 +32,10 @@
#include "base/path.h" #include "base/path.h"
template <typename T> class QPromise; namespace BitTorrent
struct FileSearchResult
{ {
Path savePath; class TorrentID;
PathList fileNames; }
};
class FileSearcher final : public QObject class FileSearcher final : public QObject
{ {
@ -46,8 +43,12 @@ class FileSearcher final : public QObject
Q_DISABLE_COPY_MOVE(FileSearcher) Q_DISABLE_COPY_MOVE(FileSearcher)
public: public:
using QObject::QObject; FileSearcher() = default;
void search(const PathList &originalFileNames, const Path &savePath public slots:
, const Path &downloadPath, bool forceAppendExt, QPromise<FileSearchResult> &promise); void search(const BitTorrent::TorrentID &id, const PathList &originalFileNames
, const Path &savePath, const Path &downloadPath, bool forceAppendExt);
signals:
void searchFinished(const BitTorrent::TorrentID &id, const Path &savePath, const PathList &fileNames);
}; };

View file

@ -133,7 +133,7 @@ int FilterParserThread::parseDATFilterFile()
return ruleCount; return ruleCount;
} }
std::vector<char> buffer(BUFFER_SIZE, 0); // seems a bit faster than QList std::vector<char> buffer(BUFFER_SIZE, 0); // seems a bit faster than QVector
qint64 bytesRead = 0; qint64 bytesRead = 0;
int offset = 0; int offset = 0;
int start = 0; int start = 0;
@ -297,7 +297,7 @@ int FilterParserThread::parseP2PFilterFile()
return ruleCount; return ruleCount;
} }
std::vector<char> buffer(BUFFER_SIZE, 0); // seems a bit faster than QList std::vector<char> buffer(BUFFER_SIZE, 0); // seems a bit faster than QVector
qint64 bytesRead = 0; qint64 bytesRead = 0;
int offset = 0; int offset = 0;
int start = 0; int start = 0;

View file

@ -29,9 +29,6 @@
#include "infohash.h" #include "infohash.h"
#include <QHash> #include <QHash>
#include <QString>
#include "base/global.h"
const int TorrentIDTypeId = qRegisterMetaType<BitTorrent::TorrentID>(); const int TorrentIDTypeId = qRegisterMetaType<BitTorrent::TorrentID>();
@ -89,28 +86,6 @@ BitTorrent::TorrentID BitTorrent::InfoHash::toTorrentID() const
#endif #endif
} }
QString BitTorrent::InfoHash::toString() const
{
// Returns a string that is suitable for logging purpose
QString ret;
ret.reserve(40 + 64 + 2); // v1 hash length + v2 hash length + comma
const SHA1Hash v1Hash = v1();
const bool v1IsValid = v1Hash.isValid();
if (v1IsValid)
ret += v1Hash.toString();
if (const SHA256Hash v2Hash = v2(); v2Hash.isValid())
{
if (v1IsValid)
ret += u", ";
ret += v2Hash.toString();
}
return ret;
}
BitTorrent::InfoHash::operator WrappedType() const BitTorrent::InfoHash::operator WrappedType() const
{ {
return m_nativeHash; return m_nativeHash;

View file

@ -36,8 +36,6 @@
#include "base/digest32.h" #include "base/digest32.h"
class QString;
using SHA1Hash = Digest32<160>; using SHA1Hash = Digest32<160>;
using SHA256Hash = Digest32<256>; using SHA256Hash = Digest32<256>;
@ -81,8 +79,6 @@ namespace BitTorrent
SHA256Hash v2() const; SHA256Hash v2() const;
TorrentID toTorrentID() const; TorrentID toTorrentID() const;
QString toString() const;
operator WrappedType() const; operator WrappedType() const;
private: private:

View file

@ -39,11 +39,7 @@ PeerAddress PeerAddress::parse(const QStringView address)
if (address.startsWith(u'[') && address.contains(u"]:")) if (address.startsWith(u'[') && address.contains(u"]:"))
{ // IPv6 { // IPv6
ipPort = address.split(u"]:"); ipPort = address.split(u"]:");
#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0) ipPort[0] = ipPort[0].mid(1); // chop '['
ipPort[0].slice(1); // chop '['
#else
ipPort[0] = ipPort[0].sliced(1); // chop '['
#endif
} }
else if (address.contains(u':')) else if (address.contains(u':'))
{ // IPv4 { // IPv4

View file

@ -30,12 +30,12 @@
#include <utility> #include <utility>
#include <QList>
#include <QMetaObject> #include <QMetaObject>
#include <QMutexLocker> #include <QMutexLocker>
#include <QThread> #include <QThread>
#include <QVector>
const int TORRENTIDLIST_TYPEID = qRegisterMetaType<QList<BitTorrent::TorrentID>>(); const int TORRENTIDLIST_TYPEID = qRegisterMetaType<QVector<BitTorrent::TorrentID>>();
BitTorrent::ResumeDataStorage::ResumeDataStorage(const Path &path, QObject *parent) BitTorrent::ResumeDataStorage::ResumeDataStorage(const Path &path, QObject *parent)
: QObject(parent) : QObject(parent)
@ -56,7 +56,6 @@ void BitTorrent::ResumeDataStorage::loadAll() const
{ {
doLoadAll(); doLoadAll();
}); });
loadingThread->setObjectName("ResumeDataStorage::loadAll loadingThread");
connect(loadingThread, &QThread::finished, loadingThread, &QObject::deleteLater); connect(loadingThread, &QThread::finished, loadingThread, &QObject::deleteLater);
loadingThread->start(); loadingThread->start();
} }
@ -71,8 +70,8 @@ QList<BitTorrent::LoadedResumeData> BitTorrent::ResumeDataStorage::fetchLoadedRe
return loadedResumeData; return loadedResumeData;
} }
void BitTorrent::ResumeDataStorage::onResumeDataLoaded(const TorrentID &torrentID, LoadResumeDataResult loadResumeDataResult) const void BitTorrent::ResumeDataStorage::onResumeDataLoaded(const TorrentID &torrentID, const LoadResumeDataResult &loadResumeDataResult) const
{ {
const QMutexLocker locker {&m_loadedResumeDataMutex}; const QMutexLocker locker {&m_loadedResumeDataMutex};
m_loadedResumeData.append({.torrentID = torrentID, .result = std::move(loadResumeDataResult)}); m_loadedResumeData.append({torrentID, loadResumeDataResult});
} }

View file

@ -58,21 +58,21 @@ namespace BitTorrent
Path path() const; Path path() const;
virtual QList<TorrentID> registeredTorrents() const = 0; virtual QVector<TorrentID> registeredTorrents() const = 0;
virtual LoadResumeDataResult load(const TorrentID &id) const = 0; virtual LoadResumeDataResult load(const TorrentID &id) const = 0;
virtual void store(const TorrentID &id, LoadTorrentParams resumeData) const = 0; virtual void store(const TorrentID &id, const LoadTorrentParams &resumeData) const = 0;
virtual void remove(const TorrentID &id) const = 0; virtual void remove(const TorrentID &id) const = 0;
virtual void storeQueue(const QList<TorrentID> &queue) const = 0; virtual void storeQueue(const QVector<TorrentID> &queue) const = 0;
void loadAll() const; void loadAll() const;
QList<LoadedResumeData> fetchLoadedResumeData() const; QList<LoadedResumeData> fetchLoadedResumeData() const;
signals: signals:
void loadStarted(const QList<BitTorrent::TorrentID> &torrents); void loadStarted(const QVector<BitTorrent::TorrentID> &torrents);
void loadFinished(); void loadFinished();
protected: protected:
void onResumeDataLoaded(const TorrentID &torrentID, LoadResumeDataResult loadResumeDataResult) const; void onResumeDataLoaded(const TorrentID &torrentID, const LoadResumeDataResult &loadResumeDataResult) const;
private: private:
virtual void doLoadAll() const = 0; virtual void doLoadAll() const = 0;

View file

@ -1,6 +1,6 @@
/* /*
* Bittorrent Client using Qt and libtorrent. * Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2015-2025 Vladimir Golovnev <glassez@yandex.ru> * Copyright (C) 2015-2024 Vladimir Golovnev <glassez@yandex.ru>
* Copyright (C) 2006 Christophe Dumez <chris@qbittorrent.org> * Copyright (C) 2006 Christophe Dumez <chris@qbittorrent.org>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
@ -34,7 +34,6 @@
#include "base/pathfwd.h" #include "base/pathfwd.h"
#include "base/tagset.h" #include "base/tagset.h"
#include "addtorrenterror.h"
#include "addtorrentparams.h" #include "addtorrentparams.h"
#include "categoryoptions.h" #include "categoryoptions.h"
#include "sharelimitaction.h" #include "sharelimitaction.h"
@ -238,12 +237,6 @@ namespace BitTorrent
virtual Path finishedTorrentExportDirectory() const = 0; virtual Path finishedTorrentExportDirectory() const = 0;
virtual void setFinishedTorrentExportDirectory(const Path &path) = 0; virtual void setFinishedTorrentExportDirectory(const Path &path) = 0;
virtual bool isAddTrackersFromURLEnabled() const = 0;
virtual void setAddTrackersFromURLEnabled(bool enabled) = 0;
virtual QString additionalTrackersURL() const = 0;
virtual void setAdditionalTrackersURL(const QString &url) = 0;
virtual QString additionalTrackersFromURL() const = 0;
virtual int globalDownloadSpeedLimit() const = 0; virtual int globalDownloadSpeedLimit() const = 0;
virtual void setGlobalDownloadSpeedLimit(int limit) = 0; virtual void setGlobalDownloadSpeedLimit(int limit) = 0;
virtual int globalUploadSpeedLimit() const = 0; virtual int globalUploadSpeedLimit() const = 0;
@ -265,8 +258,6 @@ namespace BitTorrent
virtual void setPerformanceWarningEnabled(bool enable) = 0; virtual void setPerformanceWarningEnabled(bool enable) = 0;
virtual int saveResumeDataInterval() const = 0; virtual int saveResumeDataInterval() const = 0;
virtual void setSaveResumeDataInterval(int value) = 0; virtual void setSaveResumeDataInterval(int value) = 0;
virtual std::chrono::minutes saveStatisticsInterval() const = 0;
virtual void setSaveStatisticsInterval(std::chrono::minutes value) = 0;
virtual int shutdownTimeout() const = 0; virtual int shutdownTimeout() const = 0;
virtual void setShutdownTimeout(int value) = 0; virtual void setShutdownTimeout(int value) = 0;
virtual int port() const = 0; virtual int port() const = 0;
@ -393,8 +384,6 @@ namespace BitTorrent
virtual void setIncludeOverheadInLimits(bool include) = 0; virtual void setIncludeOverheadInLimits(bool include) = 0;
virtual QString announceIP() const = 0; virtual QString announceIP() const = 0;
virtual void setAnnounceIP(const QString &ip) = 0; virtual void setAnnounceIP(const QString &ip) = 0;
virtual int announcePort() const = 0;
virtual void setAnnouncePort(int port) = 0;
virtual int maxConcurrentHTTPAnnounces() const = 0; virtual int maxConcurrentHTTPAnnounces() const = 0;
virtual void setMaxConcurrentHTTPAnnounces(int value) = 0; virtual void setMaxConcurrentHTTPAnnounces(int value) = 0;
virtual bool isReannounceWhenAddressChangedEnabled() const = 0; virtual bool isReannounceWhenAddressChangedEnabled() const = 0;
@ -422,8 +411,6 @@ namespace BitTorrent
virtual void setUTPRateLimited(bool limited) = 0; virtual void setUTPRateLimited(bool limited) = 0;
virtual MixedModeAlgorithm utpMixedMode() const = 0; virtual MixedModeAlgorithm utpMixedMode() const = 0;
virtual void setUtpMixedMode(MixedModeAlgorithm mode) = 0; virtual void setUtpMixedMode(MixedModeAlgorithm mode) = 0;
virtual int hostnameCacheTTL() const = 0;
virtual void setHostnameCacheTTL(int value) = 0;
virtual bool isIDNSupportEnabled() const = 0; virtual bool isIDNSupportEnabled() const = 0;
virtual void setIDNSupportEnabled(bool enabled) = 0; virtual void setIDNSupportEnabled(bool enabled) = 0;
virtual bool multiConnectionsPerIpEnabled() const = 0; virtual bool multiConnectionsPerIpEnabled() const = 0;
@ -460,7 +447,7 @@ namespace BitTorrent
virtual Torrent *getTorrent(const TorrentID &id) const = 0; virtual Torrent *getTorrent(const TorrentID &id) const = 0;
virtual Torrent *findTorrent(const InfoHash &infoHash) const = 0; virtual Torrent *findTorrent(const InfoHash &infoHash) const = 0;
virtual QList<Torrent *> torrents() const = 0; virtual QVector<Torrent *> torrents() const = 0;
virtual qsizetype torrentsCount() const = 0; virtual qsizetype torrentsCount() const = 0;
virtual const SessionStatus &status() const = 0; virtual const SessionStatus &status() const = 0;
virtual const CacheStatus &cacheStatus() const = 0; virtual const CacheStatus &cacheStatus() const = 0;
@ -474,25 +461,21 @@ namespace BitTorrent
virtual bool downloadMetadata(const TorrentDescriptor &torrentDescr) = 0; virtual bool downloadMetadata(const TorrentDescriptor &torrentDescr) = 0;
virtual bool cancelDownloadMetadata(const TorrentID &id) = 0; virtual bool cancelDownloadMetadata(const TorrentID &id) = 0;
virtual void increaseTorrentsQueuePos(const QList<TorrentID> &ids) = 0; virtual void increaseTorrentsQueuePos(const QVector<TorrentID> &ids) = 0;
virtual void decreaseTorrentsQueuePos(const QList<TorrentID> &ids) = 0; virtual void decreaseTorrentsQueuePos(const QVector<TorrentID> &ids) = 0;
virtual void topTorrentsQueuePos(const QList<TorrentID> &ids) = 0; virtual void topTorrentsQueuePos(const QVector<TorrentID> &ids) = 0;
virtual void bottomTorrentsQueuePos(const QList<TorrentID> &ids) = 0; virtual void bottomTorrentsQueuePos(const QVector<TorrentID> &ids) = 0;
virtual QString lastExternalIPv4Address() const = 0;
virtual QString lastExternalIPv6Address() const = 0;
virtual qint64 freeDiskSpace() const = 0;
signals: signals:
void startupProgressUpdated(int progress); void startupProgressUpdated(int progress);
void addTorrentFailed(const InfoHash &infoHash, const AddTorrentError &reason); void addTorrentFailed(const InfoHash &infoHash, const QString &reason);
void allTorrentsFinished(); void allTorrentsFinished();
void categoryAdded(const QString &categoryName); void categoryAdded(const QString &categoryName);
void categoryRemoved(const QString &categoryName); void categoryRemoved(const QString &categoryName);
void categoryOptionsChanged(const QString &categoryName); void categoryOptionsChanged(const QString &categoryName);
void fullDiskError(Torrent *torrent, const QString &msg); void fullDiskError(Torrent *torrent, const QString &msg);
void IPFilterParsed(bool error, int ruleCount); void IPFilterParsed(bool error, int ruleCount);
void loadTorrentFailed(const QString &error);
void metadataDownloaded(const TorrentInfo &info); void metadataDownloaded(const TorrentInfo &info);
void restored(); void restored();
void paused(); void paused();
@ -512,17 +495,16 @@ namespace BitTorrent
void torrentStarted(Torrent *torrent); void torrentStarted(Torrent *torrent);
void torrentSavePathChanged(Torrent *torrent); void torrentSavePathChanged(Torrent *torrent);
void torrentSavingModeChanged(Torrent *torrent); void torrentSavingModeChanged(Torrent *torrent);
void torrentsLoaded(const QList<Torrent *> &torrents); void torrentsLoaded(const QVector<Torrent *> &torrents);
void torrentsUpdated(const QList<Torrent *> &torrents); void torrentsUpdated(const QVector<Torrent *> &torrents);
void torrentTagAdded(Torrent *torrent, const Tag &tag); void torrentTagAdded(Torrent *torrent, const Tag &tag);
void torrentTagRemoved(Torrent *torrent, const Tag &tag); void torrentTagRemoved(Torrent *torrent, const Tag &tag);
void trackerError(Torrent *torrent, const QString &tracker); void trackerError(Torrent *torrent, const QString &tracker);
void trackersAdded(Torrent *torrent, const QList<TrackerEntry> &trackers); void trackersAdded(Torrent *torrent, const QVector<TrackerEntry> &trackers);
void trackersChanged(Torrent *torrent); void trackersChanged(Torrent *torrent);
void trackersRemoved(Torrent *torrent, const QStringList &trackers); void trackersRemoved(Torrent *torrent, const QStringList &trackers);
void trackerSuccess(Torrent *torrent, const QString &tracker); void trackerSuccess(Torrent *torrent, const QString &tracker);
void trackerWarning(Torrent *torrent, const QString &tracker); void trackerWarning(Torrent *torrent, const QString &tracker);
void trackerEntryStatusesUpdated(Torrent *torrent, const QHash<QString, TrackerEntryStatus> &updatedTrackers); void trackerEntryStatusesUpdated(Torrent *torrent, const QHash<QString, TrackerEntryStatus> &updatedTrackers);
void freeDiskSpaceChecked(qint64 result);
}; };
} }

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,6 @@
/* /*
* Bittorrent Client using Qt and libtorrent. * Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2015-2025 Vladimir Golovnev <glassez@yandex.ru> * Copyright (C) 2015-2024 Vladimir Golovnev <glassez@yandex.ru>
* Copyright (C) 2006 Christophe Dumez <chris@qbittorrent.org> * Copyright (C) 2006 Christophe Dumez <chris@qbittorrent.org>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
@ -29,8 +29,6 @@
#pragma once #pragma once
#include <chrono>
#include <functional>
#include <utility> #include <utility>
#include <vector> #include <vector>
@ -39,14 +37,14 @@
#include <libtorrent/torrent_handle.hpp> #include <libtorrent/torrent_handle.hpp>
#include <QtContainerFwd> #include <QtContainerFwd>
#include <QDateTime>
#include <QElapsedTimer> #include <QElapsedTimer>
#include <QHash> #include <QHash>
#include <QList>
#include <QMap> #include <QMap>
#include <QMutex> #include <QMutex>
#include <QPointer> #include <QPointer>
#include <QSet> #include <QSet>
#include <QThreadPool> #include <QVector>
#include "base/path.h" #include "base/path.h"
#include "base/settingvalue.h" #include "base/settingvalue.h"
@ -57,21 +55,19 @@
#include "session.h" #include "session.h"
#include "sessionstatus.h" #include "sessionstatus.h"
#include "torrentinfo.h" #include "torrentinfo.h"
#include "trackerentrystatus.h"
class QString; class QString;
class QThread;
class QThreadPool;
class QTimer; class QTimer;
class QUrl; class QUrl;
template <typename T> class QFuture;
class BandwidthScheduler; class BandwidthScheduler;
class FileSearcher; class FileSearcher;
class FilterParserThread; class FilterParserThread;
class FreeDiskSpaceChecker;
class NativeSessionExtension; class NativeSessionExtension;
struct FileSearchResult;
namespace BitTorrent namespace BitTorrent
{ {
enum class MoveStorageMode; enum class MoveStorageMode;
@ -239,8 +235,6 @@ namespace BitTorrent
void setPerformanceWarningEnabled(bool enable) override; void setPerformanceWarningEnabled(bool enable) override;
int saveResumeDataInterval() const override; int saveResumeDataInterval() const override;
void setSaveResumeDataInterval(int value) override; void setSaveResumeDataInterval(int value) override;
std::chrono::minutes saveStatisticsInterval() const override;
void setSaveStatisticsInterval(std::chrono::minutes value) override;
int shutdownTimeout() const override; int shutdownTimeout() const override;
void setShutdownTimeout(int value) override; void setShutdownTimeout(int value) override;
int port() const override; int port() const override;
@ -367,8 +361,6 @@ namespace BitTorrent
void setIncludeOverheadInLimits(bool include) override; void setIncludeOverheadInLimits(bool include) override;
QString announceIP() const override; QString announceIP() const override;
void setAnnounceIP(const QString &ip) override; void setAnnounceIP(const QString &ip) override;
int announcePort() const override;
void setAnnouncePort(int port) override;
int maxConcurrentHTTPAnnounces() const override; int maxConcurrentHTTPAnnounces() const override;
void setMaxConcurrentHTTPAnnounces(int value) override; void setMaxConcurrentHTTPAnnounces(int value) override;
bool isReannounceWhenAddressChangedEnabled() const override; bool isReannounceWhenAddressChangedEnabled() const override;
@ -396,8 +388,6 @@ namespace BitTorrent
void setUTPRateLimited(bool limited) override; void setUTPRateLimited(bool limited) override;
MixedModeAlgorithm utpMixedMode() const override; MixedModeAlgorithm utpMixedMode() const override;
void setUtpMixedMode(MixedModeAlgorithm mode) override; void setUtpMixedMode(MixedModeAlgorithm mode) override;
int hostnameCacheTTL() const override;
void setHostnameCacheTTL(int value) override;
bool isIDNSupportEnabled() const override; bool isIDNSupportEnabled() const override;
void setIDNSupportEnabled(bool enabled) override; void setIDNSupportEnabled(bool enabled) override;
bool multiConnectionsPerIpEnabled() const override; bool multiConnectionsPerIpEnabled() const override;
@ -434,7 +424,7 @@ namespace BitTorrent
Torrent *getTorrent(const TorrentID &id) const override; Torrent *getTorrent(const TorrentID &id) const override;
Torrent *findTorrent(const InfoHash &infoHash) const override; Torrent *findTorrent(const InfoHash &infoHash) const override;
QList<Torrent *> torrents() const override; QVector<Torrent *> torrents() const override;
qsizetype torrentsCount() const override; qsizetype torrentsCount() const override;
const SessionStatus &status() const override; const SessionStatus &status() const override;
const CacheStatus &cacheStatus() const override; const CacheStatus &cacheStatus() const override;
@ -448,15 +438,10 @@ namespace BitTorrent
bool downloadMetadata(const TorrentDescriptor &torrentDescr) override; bool downloadMetadata(const TorrentDescriptor &torrentDescr) override;
bool cancelDownloadMetadata(const TorrentID &id) override; bool cancelDownloadMetadata(const TorrentID &id) override;
void increaseTorrentsQueuePos(const QList<TorrentID> &ids) override; void increaseTorrentsQueuePos(const QVector<TorrentID> &ids) override;
void decreaseTorrentsQueuePos(const QList<TorrentID> &ids) override; void decreaseTorrentsQueuePos(const QVector<TorrentID> &ids) override;
void topTorrentsQueuePos(const QList<TorrentID> &ids) override; void topTorrentsQueuePos(const QVector<TorrentID> &ids) override;
void bottomTorrentsQueuePos(const QList<TorrentID> &ids) override; void bottomTorrentsQueuePos(const QVector<TorrentID> &ids) override;
QString lastExternalIPv4Address() const override;
QString lastExternalIPv6Address() const override;
qint64 freeDiskSpace() const override;
// Torrent interface // Torrent interface
void handleTorrentResumeDataRequested(const TorrentImpl *torrent); void handleTorrentResumeDataRequested(const TorrentImpl *torrent);
@ -472,43 +457,34 @@ namespace BitTorrent
void handleTorrentStarted(TorrentImpl *torrent); void handleTorrentStarted(TorrentImpl *torrent);
void handleTorrentChecked(TorrentImpl *torrent); void handleTorrentChecked(TorrentImpl *torrent);
void handleTorrentFinished(TorrentImpl *torrent); void handleTorrentFinished(TorrentImpl *torrent);
void handleTorrentTrackersAdded(TorrentImpl *torrent, const QList<TrackerEntry> &newTrackers); void handleTorrentTrackersAdded(TorrentImpl *torrent, const QVector<TrackerEntry> &newTrackers);
void handleTorrentTrackersRemoved(TorrentImpl *torrent, const QStringList &deletedTrackers); void handleTorrentTrackersRemoved(TorrentImpl *torrent, const QStringList &deletedTrackers);
void handleTorrentTrackersChanged(TorrentImpl *torrent); void handleTorrentTrackersChanged(TorrentImpl *torrent);
void handleTorrentUrlSeedsAdded(TorrentImpl *torrent, const QList<QUrl> &newUrlSeeds); void handleTorrentUrlSeedsAdded(TorrentImpl *torrent, const QVector<QUrl> &newUrlSeeds);
void handleTorrentUrlSeedsRemoved(TorrentImpl *torrent, const QList<QUrl> &urlSeeds); void handleTorrentUrlSeedsRemoved(TorrentImpl *torrent, const QVector<QUrl> &urlSeeds);
void handleTorrentResumeDataReady(TorrentImpl *torrent, LoadTorrentParams data); void handleTorrentResumeDataReady(TorrentImpl *torrent, const LoadTorrentParams &data);
void handleTorrentInfoHashChanged(TorrentImpl *torrent, const InfoHash &prevInfoHash); void handleTorrentInfoHashChanged(TorrentImpl *torrent, const InfoHash &prevInfoHash);
void handleTorrentStorageMovingStateChanged(TorrentImpl *torrent); void handleTorrentStorageMovingStateChanged(TorrentImpl *torrent);
bool addMoveTorrentStorageJob(TorrentImpl *torrent, const Path &newPath, MoveStorageMode mode, MoveStorageContext context); bool addMoveTorrentStorageJob(TorrentImpl *torrent, const Path &newPath, MoveStorageMode mode, MoveStorageContext context);
lt::torrent_handle reloadTorrent(const lt::torrent_handle &currentHandle, lt::add_torrent_params params); void findIncompleteFiles(const TorrentInfo &torrentInfo, const Path &savePath
, const Path &downloadPath, const PathList &filePaths = {}) const;
QFuture<FileSearchResult> findIncompleteFiles(const Path &savePath, const Path &downloadPath, const PathList &filePaths = {}) const;
void enablePortMapping(); void enablePortMapping();
void disablePortMapping(); void disablePortMapping();
void addMappedPorts(const QSet<quint16> &ports); void addMappedPorts(const QSet<quint16> &ports);
void removeMappedPorts(const QSet<quint16> &ports); void removeMappedPorts(const QSet<quint16> &ports);
QDateTime fromLTTimePoint32(const lt::time_point32 &timePoint) const;
template <typename Func> template <typename Func>
void invoke(Func &&func) void invoke(Func &&func)
{ {
QMetaObject::invokeMethod(this, std::forward<Func>(func), Qt::QueuedConnection); QMetaObject::invokeMethod(this, std::forward<Func>(func), Qt::QueuedConnection);
} }
template <typename Func> void invokeAsync(std::function<void ()> func);
void invokeAsync(Func &&func)
{
m_asyncWorker->start(std::forward<Func>(func));
}
bool isAddTrackersFromURLEnabled() const override;
void setAddTrackersFromURLEnabled(bool enabled) override;
QString additionalTrackersURL() const override;
void setAdditionalTrackersURL(const QString &url) override;
QString additionalTrackersFromURL() const override;
signals: signals:
void addTorrentAlertsReceived(qsizetype count); void addTorrentAlertsReceived(qsizetype count);
@ -520,6 +496,7 @@ namespace BitTorrent
void generateResumeData(); void generateResumeData();
void handleIPFilterParsed(int ruleCount); void handleIPFilterParsed(int ruleCount);
void handleIPFilterError(); void handleIPFilterError();
void fileSearchFinished(const TorrentID &id, const Path &savePath, const PathList &fileNames);
void torrentContentRemovingFinished(const QString &torrentName, const QString &errorMessage); void torrentContentRemovingFinished(const QString &torrentName, const QString &errorMessage);
private: private:
@ -578,7 +555,8 @@ namespace BitTorrent
void updateSeedingLimitTimer(); void updateSeedingLimitTimer();
void exportTorrentFile(const Torrent *torrent, const Path &folderPath); void exportTorrentFile(const Torrent *torrent, const Path &folderPath);
void handleAlert(lt::alert *alert); void handleAlert(const lt::alert *alert);
void dispatchTorrentAlert(const lt::torrent_alert *alert);
void handleAddTorrentAlert(const lt::add_torrent_alert *alert); void handleAddTorrentAlert(const lt::add_torrent_alert *alert);
void handleStateUpdateAlert(const lt::state_update_alert *alert); void handleStateUpdateAlert(const lt::state_update_alert *alert);
void handleMetadataReceivedAlert(const lt::metadata_received_alert *alert); void handleMetadataReceivedAlert(const lt::metadata_received_alert *alert);
@ -605,28 +583,15 @@ namespace BitTorrent
void handleTrackerAlert(const lt::tracker_alert *alert); void handleTrackerAlert(const lt::tracker_alert *alert);
#ifdef QBT_USES_LIBTORRENT2 #ifdef QBT_USES_LIBTORRENT2
void handleTorrentConflictAlert(const lt::torrent_conflict_alert *alert); void handleTorrentConflictAlert(const lt::torrent_conflict_alert *alert);
void handleFilePrioAlert(const lt::file_prio_alert *alert);
#endif #endif
void handleFastResumeRejectedAlert(const lt::fastresume_rejected_alert *alert);
void handleFileCompletedAlert(const lt::file_completed_alert *alert);
void handleFileRenamedAlert(const lt::file_renamed_alert *alert);
void handleFileRenameFailedAlert(const lt::file_rename_failed_alert *alert);
void handlePerformanceAlert(const lt::performance_alert *alert) const;
void handleSaveResumeDataAlert(lt::save_resume_data_alert *alert);
void handleSaveResumeDataFailedAlert(const lt::save_resume_data_failed_alert *alert);
void handleTorrentCheckedAlert(const lt::torrent_checked_alert *alert);
void handleTorrentFinishedAlert(const lt::torrent_finished_alert *alert);
TorrentImpl *createTorrent(const lt::torrent_handle &nativeHandle, LoadTorrentParams params); TorrentImpl *createTorrent(const lt::torrent_handle &nativeHandle, const LoadTorrentParams &params);
TorrentImpl *getTorrent(const lt::torrent_handle &nativeHandle) const;
void saveResumeData(); void saveResumeData();
void saveTorrentsQueue(); void saveTorrentsQueue();
void removeTorrentsQueue(); void removeTorrentsQueue();
void populateAdditionalTrackersFromURL(); std::vector<lt::alert *> getPendingAlerts(lt::time_duration time = lt::time_duration::zero()) const;
void fetchPendingAlerts(lt::time_duration time = lt::time_duration::zero());
void moveTorrentStorage(const MoveStorageJob &job) const; void moveTorrentStorage(const MoveStorageJob &job) const;
void handleMoveTorrentStorageJobFinished(const Path &newPath); void handleMoveTorrentStorageJobFinished(const Path &newPath);
@ -644,9 +609,6 @@ namespace BitTorrent
void handleRemovedTorrent(const TorrentID &torrentID, const QString &partfileRemoveError = {}); void handleRemovedTorrent(const TorrentID &torrentID, const QString &partfileRemoveError = {});
void setAdditionalTrackersFromURL(const QString &trackers);
void updateTrackersFromURL();
CachedSettingValue<QString> m_DHTBootstrapNodes; CachedSettingValue<QString> m_DHTBootstrapNodes;
CachedSettingValue<bool> m_isDHTEnabled; CachedSettingValue<bool> m_isDHTEnabled;
CachedSettingValue<bool> m_isLSDEnabled; CachedSettingValue<bool> m_isLSDEnabled;
@ -692,7 +654,6 @@ namespace BitTorrent
CachedSettingValue<bool> m_ignoreLimitsOnLAN; CachedSettingValue<bool> m_ignoreLimitsOnLAN;
CachedSettingValue<bool> m_includeOverheadInLimits; CachedSettingValue<bool> m_includeOverheadInLimits;
CachedSettingValue<QString> m_announceIP; CachedSettingValue<QString> m_announceIP;
CachedSettingValue<int> m_announcePort;
CachedSettingValue<int> m_maxConcurrentHTTPAnnounces; CachedSettingValue<int> m_maxConcurrentHTTPAnnounces;
CachedSettingValue<bool> m_isReannounceWhenAddressChangedEnabled; CachedSettingValue<bool> m_isReannounceWhenAddressChangedEnabled;
CachedSettingValue<int> m_stopTrackerTimeout; CachedSettingValue<int> m_stopTrackerTimeout;
@ -703,7 +664,6 @@ namespace BitTorrent
CachedSettingValue<BTProtocol> m_btProtocol; CachedSettingValue<BTProtocol> m_btProtocol;
CachedSettingValue<bool> m_isUTPRateLimited; CachedSettingValue<bool> m_isUTPRateLimited;
CachedSettingValue<MixedModeAlgorithm> m_utpMixedMode; CachedSettingValue<MixedModeAlgorithm> m_utpMixedMode;
CachedSettingValue<int> m_hostnameCacheTTL;
CachedSettingValue<bool> m_IDNSupportEnabled; CachedSettingValue<bool> m_IDNSupportEnabled;
CachedSettingValue<bool> m_multiConnectionsPerIpEnabled; CachedSettingValue<bool> m_multiConnectionsPerIpEnabled;
CachedSettingValue<bool> m_validateHTTPSTrackerCertificate; CachedSettingValue<bool> m_validateHTTPSTrackerCertificate;
@ -711,8 +671,6 @@ namespace BitTorrent
CachedSettingValue<bool> m_blockPeersOnPrivilegedPorts; CachedSettingValue<bool> m_blockPeersOnPrivilegedPorts;
CachedSettingValue<bool> m_isAddTrackersEnabled; CachedSettingValue<bool> m_isAddTrackersEnabled;
CachedSettingValue<QString> m_additionalTrackers; CachedSettingValue<QString> m_additionalTrackers;
CachedSettingValue<bool> m_isAddTrackersFromURLEnabled;
CachedSettingValue<QString> m_additionalTrackersURL;
CachedSettingValue<qreal> m_globalMaxRatio; CachedSettingValue<qreal> m_globalMaxRatio;
CachedSettingValue<int> m_globalMaxSeedingMinutes; CachedSettingValue<int> m_globalMaxSeedingMinutes;
CachedSettingValue<int> m_globalMaxInactiveSeedingMinutes; CachedSettingValue<int> m_globalMaxInactiveSeedingMinutes;
@ -734,7 +692,6 @@ namespace BitTorrent
CachedSettingValue<bool> m_isBandwidthSchedulerEnabled; CachedSettingValue<bool> m_isBandwidthSchedulerEnabled;
CachedSettingValue<bool> m_isPerformanceWarningEnabled; CachedSettingValue<bool> m_isPerformanceWarningEnabled;
CachedSettingValue<int> m_saveResumeDataInterval; CachedSettingValue<int> m_saveResumeDataInterval;
CachedSettingValue<int> m_saveStatisticsInterval;
CachedSettingValue<int> m_shutdownTimeout; CachedSettingValue<int> m_shutdownTimeout;
CachedSettingValue<int> m_port; CachedSettingValue<int> m_port;
CachedSettingValue<bool> m_sslEnabled; CachedSettingValue<bool> m_sslEnabled;
@ -786,9 +743,6 @@ namespace BitTorrent
bool m_IPFilteringConfigured = false; bool m_IPFilteringConfigured = false;
mutable bool m_listenInterfaceConfigured = false; mutable bool m_listenInterfaceConfigured = false;
QString m_additionalTrackersFromURL;
QTimer *m_updateTrackersFromURLTimer = nullptr;
bool m_isRestored = false; bool m_isRestored = false;
bool m_isPaused = isStartPaused(); bool m_isPaused = isStartPaused();
@ -798,9 +752,8 @@ namespace BitTorrent
const bool m_wasPexEnabled = m_isPeXEnabled; const bool m_wasPexEnabled = m_isPeXEnabled;
int m_numResumeData = 0; int m_numResumeData = 0;
QList<TrackerEntry> m_additionalTrackerEntries; QVector<TrackerEntry> m_additionalTrackerEntries;
QList<TrackerEntry> m_additionalTrackerEntriesFromURL; QVector<QRegularExpression> m_excludedFileNamesRegExpList;
QList<QRegularExpression> m_excludedFileNamesRegExpList;
// Statistics // Statistics
mutable QElapsedTimer m_statisticsLastUpdateTimer; mutable QElapsedTimer m_statisticsLastUpdateTimer;
@ -825,19 +778,16 @@ namespace BitTorrent
FileSearcher *m_fileSearcher = nullptr; FileSearcher *m_fileSearcher = nullptr;
TorrentContentRemover *m_torrentContentRemover = nullptr; TorrentContentRemover *m_torrentContentRemover = nullptr;
using AddTorrentAlertHandler = std::function<void (const lt::add_torrent_alert *alert)>;
QList<AddTorrentAlertHandler> m_addTorrentAlertHandlers;
QHash<TorrentID, lt::torrent_handle> m_downloadedMetadata; QHash<TorrentID, lt::torrent_handle> m_downloadedMetadata;
QHash<TorrentID, TorrentImpl *> m_torrents; QHash<TorrentID, TorrentImpl *> m_torrents;
QHash<TorrentID, TorrentImpl *> m_hybridTorrentsByAltID; QHash<TorrentID, TorrentImpl *> m_hybridTorrentsByAltID;
QHash<TorrentID, LoadTorrentParams> m_loadingTorrents;
QHash<TorrentID, RemovingTorrentData> m_removingTorrents; QHash<TorrentID, RemovingTorrentData> m_removingTorrents;
QHash<TorrentID, TorrentID> m_changedTorrentIDs; QHash<TorrentID, TorrentID> m_changedTorrentIDs;
QMap<QString, CategoryOptions> m_categories; QMap<QString, CategoryOptions> m_categories;
TagSet m_tags; TagSet m_tags;
std::vector<lt::alert *> m_alerts; // make it a class variable so it can preserve its allocated `capacity`
qsizetype m_receivedAddTorrentAlertsCount = 0; qsizetype m_receivedAddTorrentAlertsCount = 0;
QList<Torrent *> m_loadedTorrents; QList<Torrent *> m_loadedTorrents;
@ -858,8 +808,7 @@ namespace BitTorrent
QList<MoveStorageJob> m_moveStorageQueue; QList<MoveStorageJob> m_moveStorageQueue;
QString m_lastExternalIPv4Address; QString m_lastExternalIP;
QString m_lastExternalIPv6Address;
bool m_needUpgradeDownloadPath = false; bool m_needUpgradeDownloadPath = false;
@ -869,13 +818,13 @@ namespace BitTorrent
bool m_isPortMappingEnabled = false; bool m_isPortMappingEnabled = false;
QHash<quint16, std::vector<lt::port_mapping_t>> m_mappedPorts; QHash<quint16, std::vector<lt::port_mapping_t>> m_mappedPorts;
QElapsedTimer m_wakeupCheckTimestamp; QTimer *m_wakeupCheckTimer = nullptr;
QDateTime m_wakeupCheckTimestamp;
QList<TorrentImpl *> m_pendingFinishedTorrents; QList<TorrentImpl *> m_pendingFinishedTorrents;
FreeDiskSpaceChecker *m_freeDiskSpaceChecker = nullptr; QDateTime m_qNow;
QTimer *m_freeDiskSpaceCheckingTimer = nullptr; lt::clock_type::time_point m_ltNow;
qint64 m_freeDiskSpace = -1;
friend void Session::initInstance(); friend void Session::initInstance();
friend void Session::freeInstance(); friend void Session::freeInstance();

View file

@ -29,8 +29,6 @@
#include "torrent.h" #include "torrent.h"
#include <limits>
#include <QHash> #include <QHash>
#include "infohash.h" #include "infohash.h"
@ -53,7 +51,9 @@ namespace BitTorrent
const int Torrent::USE_GLOBAL_INACTIVE_SEEDING_TIME = -2; const int Torrent::USE_GLOBAL_INACTIVE_SEEDING_TIME = -2;
const int Torrent::NO_INACTIVE_SEEDING_TIME_LIMIT = -1; const int Torrent::NO_INACTIVE_SEEDING_TIME_LIMIT = -1;
const qreal Torrent::MAX_RATIO = std::numeric_limits<qreal>::infinity(); const qreal Torrent::MAX_RATIO = 9999;
const int Torrent::MAX_SEEDING_TIME = 525600;
const int Torrent::MAX_INACTIVE_SEEDING_TIME = 525600;
TorrentID Torrent::id() const TorrentID Torrent::id() const
{ {

View file

@ -1,6 +1,6 @@
/* /*
* Bittorrent Client using Qt and libtorrent. * Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2015-2025 Vladimir Golovnev <glassez@yandex.ru> * Copyright (C) 2015-2024 Vladimir Golovnev <glassez@yandex.ru>
* Copyright (C) 2006 Christophe Dumez <chris@qbittorrent.org> * Copyright (C) 2006 Christophe Dumez <chris@qbittorrent.org>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
@ -45,8 +45,6 @@ class QByteArray;
class QDateTime; class QDateTime;
class QUrl; class QUrl;
template <typename T> class QFuture;
namespace BitTorrent namespace BitTorrent
{ {
enum class DownloadPriority; enum class DownloadPriority;
@ -134,6 +132,8 @@ namespace BitTorrent
static const int NO_INACTIVE_SEEDING_TIME_LIMIT; static const int NO_INACTIVE_SEEDING_TIME_LIMIT;
static const qreal MAX_RATIO; static const qreal MAX_RATIO;
static const int MAX_SEEDING_TIME;
static const int MAX_INACTIVE_SEEDING_TIME;
using TorrentContentHandler::TorrentContentHandler; using TorrentContentHandler::TorrentContentHandler;
@ -257,8 +257,8 @@ namespace BitTorrent
virtual bool hasMissingFiles() const = 0; virtual bool hasMissingFiles() const = 0;
virtual bool hasError() const = 0; virtual bool hasError() const = 0;
virtual int queuePosition() const = 0; virtual int queuePosition() const = 0;
virtual QList<TrackerEntryStatus> trackers() const = 0; virtual QVector<TrackerEntryStatus> trackers() const = 0;
virtual QList<QUrl> urlSeeds() const = 0; virtual QVector<QUrl> urlSeeds() const = 0;
virtual QString error() const = 0; virtual QString error() const = 0;
virtual qlonglong totalDownload() const = 0; virtual qlonglong totalDownload() const = 0;
virtual qlonglong totalUpload() const = 0; virtual qlonglong totalUpload() const = 0;
@ -275,7 +275,10 @@ namespace BitTorrent
virtual bool isDHTDisabled() const = 0; virtual bool isDHTDisabled() const = 0;
virtual bool isPEXDisabled() const = 0; virtual bool isPEXDisabled() const = 0;
virtual bool isLSDDisabled() const = 0; virtual bool isLSDDisabled() const = 0;
virtual QVector<PeerInfo> peers() const = 0;
virtual QBitArray pieces() const = 0; virtual QBitArray pieces() const = 0;
virtual QBitArray downloadingPieces() const = 0;
virtual QVector<int> pieceAvailability() const = 0;
virtual qreal distributedCopies() const = 0; virtual qreal distributedCopies() const = 0;
virtual qreal maxRatio() const = 0; virtual qreal maxRatio() const = 0;
virtual int maxSeedingTime() const = 0; virtual int maxSeedingTime() const = 0;
@ -304,11 +307,11 @@ namespace BitTorrent
virtual void setDHTDisabled(bool disable) = 0; virtual void setDHTDisabled(bool disable) = 0;
virtual void setPEXDisabled(bool disable) = 0; virtual void setPEXDisabled(bool disable) = 0;
virtual void setLSDDisabled(bool disable) = 0; virtual void setLSDDisabled(bool disable) = 0;
virtual void addTrackers(QList<TrackerEntry> trackers) = 0; virtual void addTrackers(QVector<TrackerEntry> trackers) = 0;
virtual void removeTrackers(const QStringList &trackers) = 0; virtual void removeTrackers(const QStringList &trackers) = 0;
virtual void replaceTrackers(QList<TrackerEntry> trackers) = 0; virtual void replaceTrackers(QVector<TrackerEntry> trackers) = 0;
virtual void addUrlSeeds(const QList<QUrl> &urlSeeds) = 0; virtual void addUrlSeeds(const QVector<QUrl> &urlSeeds) = 0;
virtual void removeUrlSeeds(const QList<QUrl> &urlSeeds) = 0; virtual void removeUrlSeeds(const QVector<QUrl> &urlSeeds) = 0;
virtual bool connectPeer(const PeerAddress &peerAddress) = 0; virtual bool connectPeer(const PeerAddress &peerAddress) = 0;
virtual void clearPeers() = 0; virtual void clearPeers() = 0;
virtual void setMetadata(const TorrentInfo &torrentInfo) = 0; virtual void setMetadata(const TorrentInfo &torrentInfo) = 0;
@ -322,10 +325,10 @@ namespace BitTorrent
virtual nonstd::expected<QByteArray, QString> exportToBuffer() const = 0; virtual nonstd::expected<QByteArray, QString> exportToBuffer() const = 0;
virtual nonstd::expected<void, QString> exportToFile(const Path &path) const = 0; virtual nonstd::expected<void, QString> exportToFile(const Path &path) const = 0;
virtual QFuture<QList<PeerInfo>> fetchPeerInfo() const = 0; virtual void fetchPeerInfo(std::function<void (QVector<PeerInfo>)> resultHandler) const = 0;
virtual QFuture<QList<QUrl>> fetchURLSeeds() const = 0; virtual void fetchURLSeeds(std::function<void (QVector<QUrl>)> resultHandler) const = 0;
virtual QFuture<QList<int>> fetchPieceAvailability() const = 0; virtual void fetchPieceAvailability(std::function<void (QVector<int>)> resultHandler) const = 0;
virtual QFuture<QBitArray> fetchDownloadingPieces() const = 0; virtual void fetchDownloadingPieces(std::function<void (QBitArray)> resultHandler) const = 0;
TorrentID id() const; TorrentID id() const;
bool isRunning() const; bool isRunning() const;

View file

@ -1,6 +1,6 @@
/* /*
* Bittorrent Client using Qt and libtorrent. * Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2022-2025 Vladimir Golovnev <glassez@yandex.ru> * Copyright (C) 2022-2023 Vladimir Golovnev <glassez@yandex.ru>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
@ -34,8 +34,6 @@
#include "abstractfilestorage.h" #include "abstractfilestorage.h"
#include "downloadpriority.h" #include "downloadpriority.h"
template <typename T> class QFuture;
namespace BitTorrent namespace BitTorrent
{ {
class TorrentContentHandler : public QObject, public AbstractFileStorage class TorrentContentHandler : public QObject, public AbstractFileStorage
@ -46,17 +44,18 @@ namespace BitTorrent
virtual bool hasMetadata() const = 0; virtual bool hasMetadata() const = 0;
virtual Path actualStorageLocation() const = 0; virtual Path actualStorageLocation() const = 0;
virtual Path actualFilePath(int fileIndex) const = 0; virtual Path actualFilePath(int fileIndex) const = 0;
virtual QList<DownloadPriority> filePriorities() const = 0; virtual QVector<DownloadPriority> filePriorities() const = 0;
virtual QList<qreal> filesProgress() const = 0; virtual QVector<qreal> filesProgress() const = 0;
/** /**
* @brief fraction of file pieces that are available at least from one peer * @brief fraction of file pieces that are available at least from one peer
* *
* This is not the same as torrrent availability, it is just a fraction of pieces * This is not the same as torrrent availability, it is just a fraction of pieces
* that can be downloaded right now. It varies between 0 to 1. * that can be downloaded right now. It varies between 0 to 1.
*/ */
virtual QFuture<QList<qreal>> fetchAvailableFileFractions() const = 0; virtual QVector<qreal> availableFileFractions() const = 0;
virtual void fetchAvailableFileFractions(std::function<void (QVector<qreal>)> resultHandler) const = 0;
virtual void prioritizeFiles(const QList<DownloadPriority> &priorities) = 0; virtual void prioritizeFiles(const QVector<DownloadPriority> &priorities) = 0;
virtual void flushCache() const = 0; virtual void flushCache() const = 0;
}; };
} }

View file

@ -62,10 +62,7 @@ BitTorrent::TorrentCreationManager::TorrentCreationManager(IApplication *app, QO
, m_maxTasks {SETTINGS_KEY(u"MaxTasks"_s), 256} , m_maxTasks {SETTINGS_KEY(u"MaxTasks"_s), 256}
, m_numThreads {SETTINGS_KEY(u"NumThreads"_s), 1} , m_numThreads {SETTINGS_KEY(u"NumThreads"_s), 1}
, m_tasks {std::make_unique<TaskSet>()} , m_tasks {std::make_unique<TaskSet>()}
, m_threadPool(this)
{ {
m_threadPool.setObjectName("TorrentCreationManager m_threadPool");
if (m_numThreads > 0) if (m_numThreads > 0)
m_threadPool.setMaxThreadCount(m_numThreads); m_threadPool.setMaxThreadCount(m_numThreads);
} }

View file

@ -124,20 +124,18 @@ void TorrentCreator::run()
// need to sort the file names by natural sort order // need to sort the file names by natural sort order
QStringList dirs = {m_params.sourcePath.data()}; QStringList dirs = {m_params.sourcePath.data()};
QDirIterator dirIter {m_params.sourcePath.data(), (QDir::AllDirs | QDir::NoDotAndDotDot), QDirIterator::Subdirectories}; #ifdef Q_OS_WIN
// libtorrent couldn't handle .lnk files on Windows
// Also, Windows users do not expect torrent creator to traverse into .lnk files so skip over them
const QDir::Filters dirFilters {QDir::AllDirs | QDir::NoDotAndDotDot | QDir::NoSymLinks};
#else
const QDir::Filters dirFilters {QDir::AllDirs | QDir::NoDotAndDotDot};
#endif
QDirIterator dirIter {m_params.sourcePath.data(), dirFilters, QDirIterator::Subdirectories};
while (dirIter.hasNext()) while (dirIter.hasNext())
{ {
const QFileInfo dirInfo = dirIter.nextFileInfo(); const QString filePath = dirIter.next();
dirs.append(filePath);
#ifdef Q_OS_WIN
// .lnk to directory
// Windows users do not expect torrent creator to traverse into .lnk files so skip over them
if (dirInfo.isShortcut())
continue;
#endif
const QString dirPath = dirInfo.filePath();
dirs.append(dirPath);
} }
std::sort(dirs.begin(), dirs.end(), naturalLessThan); std::sort(dirs.begin(), dirs.end(), naturalLessThan);
@ -148,29 +146,19 @@ void TorrentCreator::run()
{ {
QStringList tmpNames; // natural sort files within each dir QStringList tmpNames; // natural sort files within each dir
QDirIterator fileIter {dir, QDir::Files}; #ifdef Q_OS_WIN
const QDir::Filters fileFilters {QDir::Files | QDir::NoSymLinks};
#else
const QDir::Filters fileFilters {QDir::Files};
#endif
QDirIterator fileIter {dir, fileFilters};
while (fileIter.hasNext()) while (fileIter.hasNext())
{ {
const QFileInfo fileInfo = fileIter.nextFileInfo(); const QFileInfo fileInfo = fileIter.nextFileInfo();
const Path filePath {fileInfo.filePath()};
qint64 fileSize = fileInfo.size();
#ifdef Q_OS_WIN const Path relFilePath = parentPath.relativePathOf(Path(fileInfo.filePath()));
// .lnk to file
// libtorrent couldn't handle .lnk files on Windows
if (fileInfo.isShortcut())
continue;
// file symbolic link
// QFileInfo::size() failed to return the target file size
// and we need to redirect it manually
if (fileInfo.isSymbolicLink())
fileSize = QFileInfo(fileInfo.symLinkTarget()).size();
#endif
const Path relFilePath = parentPath.relativePathOf(filePath);
tmpNames.append(relFilePath.toString()); tmpNames.append(relFilePath.toString());
fileSizeMap[tmpNames.last()] = fileSize; fileSizeMap[tmpNames.last()] = fileInfo.size();
} }
std::sort(tmpNames.begin(), tmpNames.end(), naturalLessThan); std::sort(tmpNames.begin(), tmpNames.end(), naturalLessThan);
@ -186,8 +174,8 @@ void TorrentCreator::run()
#ifdef QBT_USES_LIBTORRENT2 #ifdef QBT_USES_LIBTORRENT2
lt::create_torrent newTorrent {fs, m_params.pieceSize, toNativeTorrentFormatFlag(m_params.torrentFormat)}; lt::create_torrent newTorrent {fs, m_params.pieceSize, toNativeTorrentFormatFlag(m_params.torrentFormat)};
#else #else
lt::create_torrent newTorrent {fs, m_params.pieceSize, m_params.paddedFileSizeLimit lt::create_torrent newTorrent(fs, m_params.pieceSize, m_params.paddedFileSizeLimit
, (m_params.isAlignmentOptimized ? lt::create_torrent::optimize_alignment : lt::create_flags_t {})}; , (m_params.isAlignmentOptimized ? lt::create_torrent::optimize_alignment : lt::create_flags_t {}));
#endif #endif
// Add url seeds // Add url seeds

View file

@ -141,22 +141,6 @@ catch (const lt::system_error &err)
return nonstd::make_unexpected(QString::fromLocal8Bit(err.what())); return nonstd::make_unexpected(QString::fromLocal8Bit(err.what()));
} }
nonstd::expected<QByteArray, QString> BitTorrent::TorrentDescriptor::saveToBuffer() const
try
{
const lt::entry torrentEntry = lt::write_torrent_file(m_ltAddTorrentParams);
// usually torrent size should be smaller than 1 MB,
// however there are >100 MB v2/hybrid torrent files out in the wild
QByteArray buffer;
buffer.reserve(1024 * 1024);
lt::bencode(std::back_inserter(buffer), torrentEntry);
return buffer;
}
catch (const lt::system_error &err)
{
return nonstd::make_unexpected(QString::fromLocal8Bit(err.what()));
}
BitTorrent::TorrentDescriptor::TorrentDescriptor(lt::add_torrent_params ltAddTorrentParams) BitTorrent::TorrentDescriptor::TorrentDescriptor(lt::add_torrent_params ltAddTorrentParams)
: m_ltAddTorrentParams {std::move(ltAddTorrentParams)} : m_ltAddTorrentParams {std::move(ltAddTorrentParams)}
{ {
@ -223,9 +207,9 @@ void BitTorrent::TorrentDescriptor::setTorrentInfo(TorrentInfo torrentInfo)
} }
} }
QList<BitTorrent::TrackerEntry> BitTorrent::TorrentDescriptor::trackers() const QVector<BitTorrent::TrackerEntry> BitTorrent::TorrentDescriptor::trackers() const
{ {
QList<TrackerEntry> ret; QVector<TrackerEntry> ret;
ret.reserve(static_cast<decltype(ret)::size_type>(m_ltAddTorrentParams.trackers.size())); ret.reserve(static_cast<decltype(ret)::size_type>(m_ltAddTorrentParams.trackers.size()));
std::size_t i = 0; std::size_t i = 0;
for (const std::string &tracker : m_ltAddTorrentParams.trackers) for (const std::string &tracker : m_ltAddTorrentParams.trackers)
@ -234,9 +218,9 @@ QList<BitTorrent::TrackerEntry> BitTorrent::TorrentDescriptor::trackers() const
return ret; return ret;
} }
QList<QUrl> BitTorrent::TorrentDescriptor::urlSeeds() const QVector<QUrl> BitTorrent::TorrentDescriptor::urlSeeds() const
{ {
QList<QUrl> urlSeeds; QVector<QUrl> urlSeeds;
urlSeeds.reserve(static_cast<decltype(urlSeeds)::size_type>(m_ltAddTorrentParams.url_seeds.size())); urlSeeds.reserve(static_cast<decltype(urlSeeds)::size_type>(m_ltAddTorrentParams.url_seeds.size()));
for (const std::string &nativeURLSeed : m_ltAddTorrentParams.url_seeds) for (const std::string &nativeURLSeed : m_ltAddTorrentParams.url_seeds)

View file

@ -39,6 +39,7 @@
#include "base/3rdparty/expected.hpp" #include "base/3rdparty/expected.hpp"
#include "base/path.h" #include "base/path.h"
#include "torrentdescriptor.h"
#include "torrentinfo.h" #include "torrentinfo.h"
class QByteArray; class QByteArray;
@ -59,8 +60,8 @@ namespace BitTorrent
QDateTime creationDate() const; QDateTime creationDate() const;
QString creator() const; QString creator() const;
QString comment() const; QString comment() const;
QList<TrackerEntry> trackers() const; QVector<TrackerEntry> trackers() const;
QList<QUrl> urlSeeds() const; QVector<QUrl> urlSeeds() const;
const std::optional<TorrentInfo> &info() const; const std::optional<TorrentInfo> &info() const;
void setTorrentInfo(TorrentInfo torrentInfo); void setTorrentInfo(TorrentInfo torrentInfo);
@ -69,7 +70,6 @@ namespace BitTorrent
static nonstd::expected<TorrentDescriptor, QString> loadFromFile(const Path &path) noexcept; static nonstd::expected<TorrentDescriptor, QString> loadFromFile(const Path &path) noexcept;
static nonstd::expected<TorrentDescriptor, QString> parse(const QString &str) noexcept; static nonstd::expected<TorrentDescriptor, QString> parse(const QString &str) noexcept;
nonstd::expected<void, QString> saveToFile(const Path &path) const; nonstd::expected<void, QString> saveToFile(const Path &path) const;
nonstd::expected<QByteArray, QString> saveToBuffer() const;
const lt::add_torrent_params &ltAddTorrentParams() const; const lt::add_torrent_params &ltAddTorrentParams() const;

File diff suppressed because it is too large Load diff

View file

@ -41,11 +41,11 @@
#include <QBitArray> #include <QBitArray>
#include <QDateTime> #include <QDateTime>
#include <QHash> #include <QHash>
#include <QList>
#include <QMap> #include <QMap>
#include <QObject> #include <QObject>
#include <QQueue> #include <QQueue>
#include <QString> #include <QString>
#include <QVector>
#include "base/path.h" #include "base/path.h"
#include "base/tagset.h" #include "base/tagset.h"
@ -94,7 +94,8 @@ namespace BitTorrent
Q_DISABLE_COPY_MOVE(TorrentImpl) Q_DISABLE_COPY_MOVE(TorrentImpl)
public: public:
TorrentImpl(SessionImpl *session, const lt::torrent_handle &nativeHandle, LoadTorrentParams params); TorrentImpl(SessionImpl *session, lt::session *nativeSession
, const lt::torrent_handle &nativeHandle, const LoadTorrentParams &params);
~TorrentImpl() override; ~TorrentImpl() override;
bool isValid() const; bool isValid() const;
@ -161,7 +162,7 @@ namespace BitTorrent
qlonglong fileSize(int index) const override; qlonglong fileSize(int index) const override;
PathList filePaths() const override; PathList filePaths() const override;
PathList actualFilePaths() const override; PathList actualFilePaths() const override;
QList<DownloadPriority> filePriorities() const override; QVector<DownloadPriority> filePriorities() const override;
TorrentInfo info() const override; TorrentInfo info() const override;
bool isFinished() const override; bool isFinished() const override;
@ -183,13 +184,13 @@ namespace BitTorrent
bool hasMissingFiles() const override; bool hasMissingFiles() const override;
bool hasError() const override; bool hasError() const override;
int queuePosition() const override; int queuePosition() const override;
QList<TrackerEntryStatus> trackers() const override; QVector<TrackerEntryStatus> trackers() const override;
QList<QUrl> urlSeeds() const override; QVector<QUrl> urlSeeds() const override;
QString error() const override; QString error() const override;
qlonglong totalDownload() const override; qlonglong totalDownload() const override;
qlonglong totalUpload() const override; qlonglong totalUpload() const override;
qlonglong eta() const override; qlonglong eta() const override;
QList<qreal> filesProgress() const override; QVector<qreal> filesProgress() const override;
int seedsCount() const override; int seedsCount() const override;
int peersCount() const override; int peersCount() const override;
int leechsCount() const override; int leechsCount() const override;
@ -202,7 +203,10 @@ namespace BitTorrent
bool isDHTDisabled() const override; bool isDHTDisabled() const override;
bool isPEXDisabled() const override; bool isPEXDisabled() const override;
bool isLSDDisabled() const override; bool isLSDDisabled() const override;
QVector<PeerInfo> peers() const override;
QBitArray pieces() const override; QBitArray pieces() const override;
QBitArray downloadingPieces() const override;
QVector<int> pieceAvailability() const override;
qreal distributedCopies() const override; qreal distributedCopies() const override;
qreal maxRatio() const override; qreal maxRatio() const override;
int maxSeedingTime() const override; int maxSeedingTime() const override;
@ -216,6 +220,7 @@ namespace BitTorrent
int connectionsCount() const override; int connectionsCount() const override;
int connectionsLimit() const override; int connectionsLimit() const override;
qlonglong nextAnnounce() const override; qlonglong nextAnnounce() const override;
QVector<qreal> availableFileFractions() const override;
void setName(const QString &name) override; void setName(const QString &name) override;
void setSequentialDownload(bool enable) override; void setSequentialDownload(bool enable) override;
@ -226,7 +231,7 @@ namespace BitTorrent
void forceDHTAnnounce() override; void forceDHTAnnounce() override;
void forceRecheck() override; void forceRecheck() override;
void renameFile(int index, const Path &path) override; void renameFile(int index, const Path &path) override;
void prioritizeFiles(const QList<DownloadPriority> &priorities) override; void prioritizeFiles(const QVector<DownloadPriority> &priorities) override;
void setUploadLimit(int limit) override; void setUploadLimit(int limit) override;
void setDownloadLimit(int limit) override; void setDownloadLimit(int limit) override;
void setSuperSeeding(bool enable) override; void setSuperSeeding(bool enable) override;
@ -234,11 +239,11 @@ namespace BitTorrent
void setPEXDisabled(bool disable) override; void setPEXDisabled(bool disable) override;
void setLSDDisabled(bool disable) override; void setLSDDisabled(bool disable) override;
void flushCache() const override; void flushCache() const override;
void addTrackers(QList<TrackerEntry> trackers) override; void addTrackers(QVector<TrackerEntry> trackers) override;
void removeTrackers(const QStringList &trackers) override; void removeTrackers(const QStringList &trackers) override;
void replaceTrackers(QList<TrackerEntry> trackers) override; void replaceTrackers(QVector<TrackerEntry> trackers) override;
void addUrlSeeds(const QList<QUrl> &urlSeeds) override; void addUrlSeeds(const QVector<QUrl> &urlSeeds) override;
void removeUrlSeeds(const QList<QUrl> &urlSeeds) override; void removeUrlSeeds(const QVector<QUrl> &urlSeeds) override;
bool connectPeer(const PeerAddress &peerAddress) override; bool connectPeer(const PeerAddress &peerAddress) override;
void clearPeers() override; void clearPeers() override;
void setMetadata(const TorrentInfo &torrentInfo) override; void setMetadata(const TorrentInfo &torrentInfo) override;
@ -253,29 +258,19 @@ namespace BitTorrent
nonstd::expected<QByteArray, QString> exportToBuffer() const override; nonstd::expected<QByteArray, QString> exportToBuffer() const override;
nonstd::expected<void, QString> exportToFile(const Path &path) const override; nonstd::expected<void, QString> exportToFile(const Path &path) const override;
QFuture<QList<PeerInfo>> fetchPeerInfo() const override; void fetchPeerInfo(std::function<void (QVector<PeerInfo>)> resultHandler) const override;
QFuture<QList<QUrl>> fetchURLSeeds() const override; void fetchURLSeeds(std::function<void (QVector<QUrl>)> resultHandler) const override;
QFuture<QList<int>> fetchPieceAvailability() const override; void fetchPieceAvailability(std::function<void (QVector<int>)> resultHandler) const override;
QFuture<QBitArray> fetchDownloadingPieces() const override; void fetchDownloadingPieces(std::function<void (QBitArray)> resultHandler) const override;
QFuture<QList<qreal>> fetchAvailableFileFractions() const override; void fetchAvailableFileFractions(std::function<void (QVector<qreal>)> resultHandler) const override;
bool needSaveResumeData() const; bool needSaveResumeData() const;
// Session interface // Session interface
lt::torrent_handle nativeHandle() const; lt::torrent_handle nativeHandle() const;
int fileIndexFromNative(lt::file_index_t nativeFileIndex) const; void handleAlert(const lt::alert *a);
void handleStateUpdate(const lt::torrent_status &nativeStatus); void handleStateUpdate(const lt::torrent_status &nativeStatus);
void handleFastResumeRejected();
void handleFileCompleted(lt::file_index_t nativeFileIndex);
void handleFileError(FileErrorInfo fileError);
void handleFileRenamed(lt::file_index_t nativeFileIndex, const Path &newActualFilePath, const Path &oldActualFilePath);
void handleFileRenameFailed(lt::file_index_t nativeFileIndex);
void handleMetadataReceived();
void handleSaveResumeData(lt::add_torrent_params params);
void handleTorrentChecked();
void handleTorrentFinished();
void handleQueueingModeChanged(); void handleQueueingModeChanged();
void handleCategoryOptionsChanged(); void handleCategoryOptionsChanged();
void handleAppendExtensionToggled(); void handleAppendExtensionToggled();
@ -283,6 +278,7 @@ namespace BitTorrent
void requestResumeData(lt::resume_data_flags_t flags = {}); void requestResumeData(lt::resume_data_flags_t flags = {});
void deferredRequestResumeData(); void deferredRequestResumeData();
void handleMoveStorageJobFinished(const Path &path, MoveStorageContext context, bool hasOutstandingJob); void handleMoveStorageJobFinished(const Path &path, MoveStorageContext context, bool hasOutstandingJob);
void fileSearchFinished(const Path &savePath, const PathList &fileNames);
TrackerEntryStatus updateTrackerEntryStatus(const lt::announce_entry &announceEntry, const QHash<lt::tcp::endpoint, QMap<int, int>> &updateInfo); TrackerEntryStatus updateTrackerEntryStatus(const lt::announce_entry &announceEntry, const QHash<lt::tcp::endpoint, QMap<int, int>> &updateInfo);
void resetTrackerEntryStatuses(); void resetTrackerEntryStatuses();
@ -295,6 +291,23 @@ namespace BitTorrent
void updateProgress(); void updateProgress();
void updateState(); void updateState();
void handleFastResumeRejectedAlert(const lt::fastresume_rejected_alert *p);
void handleFileCompletedAlert(const lt::file_completed_alert *p);
void handleFileErrorAlert(const lt::file_error_alert *p);
#ifdef QBT_USES_LIBTORRENT2
void handleFilePrioAlert(const lt::file_prio_alert *p);
#endif
void handleFileRenamedAlert(const lt::file_renamed_alert *p);
void handleFileRenameFailedAlert(const lt::file_rename_failed_alert *p);
void handleMetadataReceivedAlert(const lt::metadata_received_alert *p);
void handlePerformanceAlert(const lt::performance_alert *p) const;
void handleSaveResumeDataAlert(const lt::save_resume_data_alert *p);
void handleSaveResumeDataFailedAlert(const lt::save_resume_data_failed_alert *p);
void handleTorrentCheckedAlert(const lt::torrent_checked_alert *p);
void handleTorrentFinishedAlert(const lt::torrent_finished_alert *p);
void handleTorrentPausedAlert(const lt::torrent_paused_alert *p);
void handleTorrentResumedAlert(const lt::torrent_resumed_alert *p);
bool isMoveInProgress() const; bool isMoveInProgress() const;
void setAutoManaged(bool enable); void setAutoManaged(bool enable);
@ -307,23 +320,24 @@ namespace BitTorrent
void manageActualFilePaths(); void manageActualFilePaths();
void applyFirstLastPiecePriority(bool enabled); void applyFirstLastPiecePriority(bool enabled);
void prepareResumeData(lt::add_torrent_params resumeData); void prepareResumeData(const lt::add_torrent_params &params);
void endReceivedMetadataHandling(const Path &savePath, const PathList &fileNames); void endReceivedMetadataHandling(const Path &savePath, const PathList &fileNames);
void reload(); void reload();
nonstd::expected<lt::entry, QString> exportTorrent() const; nonstd::expected<lt::entry, QString> exportTorrent() const;
template <typename Func> template <typename Func, typename Callback>
QFuture<std::invoke_result_t<Func>> invokeAsync(Func &&func) const; void invokeAsync(Func func, Callback resultHandler) const;
SessionImpl *const m_session = nullptr; SessionImpl *const m_session = nullptr;
lt::session *m_nativeSession = nullptr;
lt::torrent_handle m_nativeHandle; lt::torrent_handle m_nativeHandle;
mutable lt::torrent_status m_nativeStatus; mutable lt::torrent_status m_nativeStatus;
TorrentState m_state = TorrentState::Unknown; TorrentState m_state = TorrentState::Unknown;
TorrentInfo m_torrentInfo; TorrentInfo m_torrentInfo;
PathList m_filePaths; PathList m_filePaths;
QHash<lt::file_index_t, int> m_indexMap; QHash<lt::file_index_t, int> m_indexMap;
QList<DownloadPriority> m_filePriorities; QVector<DownloadPriority> m_filePriorities;
QBitArray m_completedFiles; QBitArray m_completedFiles;
SpeedMonitor m_payloadRateMonitor; SpeedMonitor m_payloadRateMonitor;
@ -347,8 +361,8 @@ namespace BitTorrent
MaintenanceJob m_maintenanceJob = MaintenanceJob::None; MaintenanceJob m_maintenanceJob = MaintenanceJob::None;
QList<TrackerEntryStatus> m_trackerEntryStatuses; QVector<TrackerEntryStatus> m_trackerEntryStatuses;
QList<QUrl> m_urlSeeds; QVector<QUrl> m_urlSeeds;
FileErrorInfo m_lastFileError; FileErrorInfo m_lastFileError;
// Persistent data // Persistent data
@ -373,13 +387,13 @@ namespace BitTorrent
bool m_unchecked = false; bool m_unchecked = false;
mutable lt::add_torrent_params m_ltAddTorrentParams; lt::add_torrent_params m_ltAddTorrentParams;
int m_downloadLimit = 0; int m_downloadLimit = 0;
int m_uploadLimit = 0; int m_uploadLimit = 0;
QBitArray m_pieces; QBitArray m_pieces;
QList<std::int64_t> m_filesProgress; QVector<std::int64_t> m_filesProgress;
bool m_deferredRequestResumeDataInvoked = false; bool m_deferredRequestResumeDataInvoked = false;
}; };

View file

@ -1,6 +1,6 @@
/* /*
* Bittorrent Client using Qt and libtorrent. * Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2015-2024 Vladimir Golovnev <glassez@yandex.ru> * Copyright (C) 2015-2023 Vladimir Golovnev <glassez@yandex.ru>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
@ -28,15 +28,24 @@
#include "torrentinfo.h" #include "torrentinfo.h"
#include <libtorrent/create_torrent.hpp>
#include <libtorrent/error_code.hpp>
#include <libtorrent/version.hpp> #include <libtorrent/version.hpp>
#include <QByteArray> #include <QByteArray>
#include <QDateTime> #include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QString> #include <QString>
#include <QStringList>
#include <QUrl> #include <QUrl>
#include "base/global.h" #include "base/global.h"
#include "base/path.h" #include "base/path.h"
#include "base/preferences.h"
#include "base/utils/fs.h"
#include "base/utils/io.h"
#include "base/utils/misc.h"
#include "infohash.h" #include "infohash.h"
#include "trackerentry.h" #include "trackerentry.h"
@ -73,6 +82,66 @@ bool TorrentInfo::isValid() const
return (m_nativeInfo != nullptr); return (m_nativeInfo != nullptr);
} }
nonstd::expected<TorrentInfo, QString> TorrentInfo::load(const QByteArray &data) noexcept
{
// 2-step construction to overcome default limits of `depth_limit` & `token_limit` which are
// used in `torrent_info()` constructor
const auto *pref = Preferences::instance();
lt::error_code ec;
const lt::bdecode_node node = lt::bdecode(data, ec
, nullptr, pref->getBdecodeDepthLimit(), pref->getBdecodeTokenLimit());
if (ec)
return nonstd::make_unexpected(QString::fromStdString(ec.message()));
const lt::torrent_info nativeInfo {node, ec};
if (ec)
return nonstd::make_unexpected(QString::fromStdString(ec.message()));
return TorrentInfo(nativeInfo);
}
nonstd::expected<TorrentInfo, QString> TorrentInfo::loadFromFile(const Path &path) noexcept
{
QByteArray data;
try
{
const qint64 torrentSizeLimit = Preferences::instance()->getTorrentFileSizeLimit();
const auto readResult = Utils::IO::readFile(path, torrentSizeLimit);
if (!readResult)
return nonstd::make_unexpected(readResult.error().message);
data = readResult.value();
}
catch (const std::bad_alloc &e)
{
return nonstd::make_unexpected(tr("Failed to allocate memory when reading file. File: \"%1\". Error: \"%2\"")
.arg(path.toString(), QString::fromLocal8Bit(e.what())));
}
return load(data);
}
nonstd::expected<void, QString> TorrentInfo::saveToFile(const Path &path) const
{
if (!isValid())
return nonstd::make_unexpected(tr("Invalid metadata"));
try
{
const auto torrentCreator = lt::create_torrent(*m_nativeInfo);
const lt::entry torrentEntry = torrentCreator.generate();
const nonstd::expected<void, QString> result = Utils::IO::saveToFile(path, torrentEntry);
if (!result)
return result.get_unexpected();
}
catch (const lt::system_error &err)
{
return nonstd::make_unexpected(QString::fromLocal8Bit(err.what()));
}
return {};
}
InfoHash TorrentInfo::infoHash() const InfoHash TorrentInfo::infoHash() const
{ {
if (!isValid()) return {}; if (!isValid()) return {};
@ -91,6 +160,28 @@ QString TorrentInfo::name() const
return QString::fromStdString(m_nativeInfo->orig_files().name()); return QString::fromStdString(m_nativeInfo->orig_files().name());
} }
QDateTime TorrentInfo::creationDate() const
{
if (!isValid()) return {};
const std::time_t date = m_nativeInfo->creation_date();
return ((date != 0) ? QDateTime::fromSecsSinceEpoch(date) : QDateTime());
}
QString TorrentInfo::creator() const
{
if (!isValid()) return {};
return QString::fromStdString(m_nativeInfo->creator());
}
QString TorrentInfo::comment() const
{
if (!isValid()) return {};
return QString::fromStdString(m_nativeInfo->comment());
}
bool TorrentInfo::isPrivate() const bool TorrentInfo::isPrivate() const
{ {
if (!isValid()) return false; if (!isValid()) return false;
@ -179,7 +270,43 @@ qlonglong TorrentInfo::fileOffset(const int index) const
return m_nativeInfo->orig_files().file_offset(m_nativeIndexes[index]); return m_nativeInfo->orig_files().file_offset(m_nativeIndexes[index]);
} }
QByteArray TorrentInfo::rawData() const QVector<TrackerEntry> TorrentInfo::trackers() const
{
if (!isValid()) return {};
const std::vector<lt::announce_entry> trackers = m_nativeInfo->trackers();
QVector<TrackerEntry> ret;
ret.reserve(static_cast<decltype(ret)::size_type>(trackers.size()));
for (const lt::announce_entry &tracker : trackers)
ret.append({.url = QString::fromStdString(tracker.url), .tier = tracker.tier});
return ret;
}
QVector<QUrl> TorrentInfo::urlSeeds() const
{
if (!isValid()) return {};
const std::vector<lt::web_seed_entry> &nativeWebSeeds = m_nativeInfo->web_seeds();
QVector<QUrl> urlSeeds;
urlSeeds.reserve(static_cast<decltype(urlSeeds)::size_type>(nativeWebSeeds.size()));
for (const lt::web_seed_entry &webSeed : nativeWebSeeds)
{
#if LIBTORRENT_VERSION_NUM < 20100
if (webSeed.type == lt::web_seed_entry::url_seed)
urlSeeds.append(QUrl(QString::fromStdString(webSeed.url)));
#else
urlSeeds.append(QUrl(QString::fromStdString(webSeed.url)));
#endif
}
return urlSeeds;
}
QByteArray TorrentInfo::metadata() const
{ {
if (!isValid()) return {}; if (!isValid()) return {};
#ifdef QBT_USES_LIBTORRENT2 #ifdef QBT_USES_LIBTORRENT2
@ -193,7 +320,7 @@ QByteArray TorrentInfo::rawData() const
PathList TorrentInfo::filesForPiece(const int pieceIndex) const PathList TorrentInfo::filesForPiece(const int pieceIndex) const
{ {
// no checks here because fileIndicesForPiece() will return an empty list // no checks here because fileIndicesForPiece() will return an empty list
const QList<int> fileIndices = fileIndicesForPiece(pieceIndex); const QVector<int> fileIndices = fileIndicesForPiece(pieceIndex);
PathList res; PathList res;
res.reserve(fileIndices.size()); res.reserve(fileIndices.size());
@ -203,14 +330,14 @@ PathList TorrentInfo::filesForPiece(const int pieceIndex) const
return res; return res;
} }
QList<int> TorrentInfo::fileIndicesForPiece(const int pieceIndex) const QVector<int> TorrentInfo::fileIndicesForPiece(const int pieceIndex) const
{ {
if (!isValid() || (pieceIndex < 0) || (pieceIndex >= piecesCount())) if (!isValid() || (pieceIndex < 0) || (pieceIndex >= piecesCount()))
return {}; return {};
const std::vector<lt::file_slice> files = m_nativeInfo->map_block( const std::vector<lt::file_slice> files = m_nativeInfo->map_block(
lt::piece_index_t {pieceIndex}, 0, m_nativeInfo->piece_size(lt::piece_index_t {pieceIndex})); lt::piece_index_t {pieceIndex}, 0, m_nativeInfo->piece_size(lt::piece_index_t {pieceIndex}));
QList<int> res; QVector<int> res;
res.reserve(static_cast<decltype(res)::size_type>(files.size())); res.reserve(static_cast<decltype(res)::size_type>(files.size()));
for (const lt::file_slice &fileSlice : files) for (const lt::file_slice &fileSlice : files)
{ {
@ -222,13 +349,13 @@ QList<int> TorrentInfo::fileIndicesForPiece(const int pieceIndex) const
return res; return res;
} }
QList<QByteArray> TorrentInfo::pieceHashes() const QVector<QByteArray> TorrentInfo::pieceHashes() const
{ {
if (!isValid()) if (!isValid())
return {}; return {};
const int count = piecesCount(); const int count = piecesCount();
QList<QByteArray> hashes; QVector<QByteArray> hashes;
hashes.reserve(count); hashes.reserve(count);
for (int i = 0; i < count; ++i) for (int i = 0; i < count; ++i)
@ -239,7 +366,16 @@ QList<QByteArray> TorrentInfo::pieceHashes() const
TorrentInfo::PieceRange TorrentInfo::filePieces(const Path &filePath) const TorrentInfo::PieceRange TorrentInfo::filePieces(const Path &filePath) const
{ {
return filePieces(fileIndex(filePath)); if (!isValid()) // if we do not check here the debug message will be printed, which would be not correct
return {};
const int index = fileIndex(filePath);
if (index == -1)
{
qDebug() << "Filename" << filePath.toString() << "was not found in torrent" << name();
return {};
}
return filePieces(index);
} }
TorrentInfo::PieceRange TorrentInfo::filePieces(const int fileIndex) const TorrentInfo::PieceRange TorrentInfo::filePieces(const int fileIndex) const
@ -248,7 +384,10 @@ TorrentInfo::PieceRange TorrentInfo::filePieces(const int fileIndex) const
return {}; return {};
if ((fileIndex < 0) || (fileIndex >= filesCount())) if ((fileIndex < 0) || (fileIndex >= filesCount()))
{
qDebug() << "File index (" << fileIndex << ") is out of range for torrent" << name();
return {}; return {};
}
const lt::file_storage &files = m_nativeInfo->orig_files(); const lt::file_storage &files = m_nativeInfo->orig_files();
const auto fileSize = files.file_size(m_nativeIndexes[fileIndex]); const auto fileSize = files.file_size(m_nativeIndexes[fileIndex]);
@ -311,7 +450,7 @@ std::shared_ptr<lt::torrent_info> TorrentInfo::nativeInfo() const
return std::make_shared<lt::torrent_info>(*m_nativeInfo); return std::make_shared<lt::torrent_info>(*m_nativeInfo);
} }
QList<lt::file_index_t> TorrentInfo::nativeIndexes() const QVector<lt::file_index_t> TorrentInfo::nativeIndexes() const
{ {
return m_nativeIndexes; return m_nativeIndexes;
} }

View file

@ -1,6 +1,6 @@
/* /*
* Bittorrent Client using Qt and libtorrent. * Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2015-2024 Vladimir Golovnev <glassez@yandex.ru> * Copyright (C) 2015 Vladimir Golovnev <glassez@yandex.ru>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
@ -32,8 +32,9 @@
#include <QtContainerFwd> #include <QtContainerFwd>
#include <QCoreApplication> #include <QCoreApplication>
#include <QList> #include <QVector>
#include "base/3rdparty/expected.hpp"
#include "base/indexrange.h" #include "base/indexrange.h"
#include "base/pathfwd.h" #include "base/pathfwd.h"
@ -49,17 +50,26 @@ namespace BitTorrent
class TorrentInfo class TorrentInfo
{ {
Q_DECLARE_TR_FUNCTIONS(TorrentInfo)
public: public:
TorrentInfo() = default; TorrentInfo() = default;
TorrentInfo(const TorrentInfo &other) = default; TorrentInfo(const TorrentInfo &other) = default;
explicit TorrentInfo(const lt::torrent_info &nativeInfo); explicit TorrentInfo(const lt::torrent_info &nativeInfo);
static nonstd::expected<TorrentInfo, QString> load(const QByteArray &data) noexcept;
static nonstd::expected<TorrentInfo, QString> loadFromFile(const Path &path) noexcept;
nonstd::expected<void, QString> saveToFile(const Path &path) const;
TorrentInfo &operator=(const TorrentInfo &other); TorrentInfo &operator=(const TorrentInfo &other);
bool isValid() const; bool isValid() const;
InfoHash infoHash() const; InfoHash infoHash() const;
QString name() const; QString name() const;
QDateTime creationDate() const;
QString creator() const;
QString comment() const;
bool isPrivate() const; bool isPrivate() const;
qlonglong totalSize() const; qlonglong totalSize() const;
int filesCount() const; int filesCount() const;
@ -70,9 +80,12 @@ namespace BitTorrent
PathList filePaths() const; PathList filePaths() const;
qlonglong fileSize(int index) const; qlonglong fileSize(int index) const;
qlonglong fileOffset(int index) const; qlonglong fileOffset(int index) const;
QVector<TrackerEntry> trackers() const;
QVector<QUrl> urlSeeds() const;
QByteArray metadata() const;
PathList filesForPiece(int pieceIndex) const; PathList filesForPiece(int pieceIndex) const;
QList<int> fileIndicesForPiece(int pieceIndex) const; QVector<int> fileIndicesForPiece(int pieceIndex) const;
QList<QByteArray> pieceHashes() const; QVector<QByteArray> pieceHashes() const;
using PieceRange = IndexRange<int>; using PieceRange = IndexRange<int>;
// returns pair of the first and the last pieces into which // returns pair of the first and the last pieces into which
@ -80,12 +93,10 @@ namespace BitTorrent
PieceRange filePieces(const Path &filePath) const; PieceRange filePieces(const Path &filePath) const;
PieceRange filePieces(int fileIndex) const; PieceRange filePieces(int fileIndex) const;
QByteArray rawData() const;
bool matchesInfoHash(const InfoHash &otherInfoHash) const; bool matchesInfoHash(const InfoHash &otherInfoHash) const;
std::shared_ptr<lt::torrent_info> nativeInfo() const; std::shared_ptr<lt::torrent_info> nativeInfo() const;
QList<lt::file_index_t> nativeIndexes() const; QVector<lt::file_index_t> nativeIndexes() const;
private: private:
// returns file index or -1 if fileName is not found // returns file index or -1 if fileName is not found
@ -95,7 +106,7 @@ namespace BitTorrent
// internal indexes of files (payload only, excluding any .pad files) // internal indexes of files (payload only, excluding any .pad files)
// by which they are addressed in libtorrent // by which they are addressed in libtorrent
QList<lt::file_index_t> m_nativeIndexes; QVector<lt::file_index_t> m_nativeIndexes;
}; };
} }

View file

@ -380,7 +380,7 @@ void Tracker::registerPeer(const TrackerAnnounceRequest &announceReq)
{ {
// Reached max size, remove a random torrent // Reached max size, remove a random torrent
if (m_torrents.size() >= MAX_TORRENTS) if (m_torrents.size() >= MAX_TORRENTS)
m_torrents.erase(m_torrents.cbegin()); m_torrents.erase(m_torrents.begin());
} }
m_torrents[announceReq.torrentID].setPeer(announceReq.peer); m_torrents[announceReq.torrentID].setPeer(announceReq.peer);

View file

@ -1,6 +1,6 @@
/* /*
* Bittorrent Client using Qt and libtorrent. * Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2015-2025 Vladimir Golovnev <glassez@yandex.ru> * Copyright (C) 2015-2023 Vladimir Golovnev <glassez@yandex.ru>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License * modify it under the terms of the GNU General Public License
@ -28,11 +28,10 @@
#pragma once #pragma once
#include <QDateTime>
#include <QHash> #include <QHash>
#include <QString> #include <QString>
#include "announcetimepoint.h"
class QStringView; class QStringView;
namespace BitTorrent namespace BitTorrent
@ -41,6 +40,7 @@ namespace BitTorrent
{ {
NotContacted = 1, NotContacted = 1,
Working = 2, Working = 2,
Updating = 3,
NotWorking = 4, NotWorking = 4,
TrackerError = 5, TrackerError = 5,
Unreachable = 6 Unreachable = 6
@ -51,7 +51,6 @@ namespace BitTorrent
QString name {}; QString name {};
int btVersion = 1; int btVersion = 1;
bool isUpdating = false;
TrackerEndpointState state = TrackerEndpointState::NotContacted; TrackerEndpointState state = TrackerEndpointState::NotContacted;
QString message {}; QString message {};
@ -60,8 +59,8 @@ namespace BitTorrent
int numLeeches = -1; int numLeeches = -1;
int numDownloaded = -1; int numDownloaded = -1;
AnnounceTimePoint nextAnnounceTime {}; QDateTime nextAnnounceTime {};
AnnounceTimePoint minAnnounceTime {}; QDateTime minAnnounceTime {};
}; };
struct TrackerEntryStatus struct TrackerEntryStatus
@ -69,7 +68,6 @@ namespace BitTorrent
QString url {}; QString url {};
int tier = 0; int tier = 0;
bool isUpdating = false;
TrackerEndpointState state = TrackerEndpointState::NotContacted; TrackerEndpointState state = TrackerEndpointState::NotContacted;
QString message {}; QString message {};
@ -78,8 +76,8 @@ namespace BitTorrent
int numLeeches = -1; int numLeeches = -1;
int numDownloaded = -1; int numDownloaded = -1;
AnnounceTimePoint nextAnnounceTime {}; QDateTime nextAnnounceTime {};
AnnounceTimePoint minAnnounceTime {}; QDateTime minAnnounceTime {};
QHash<std::pair<QString, int>, TrackerEndpointStatus> endpoints {}; QHash<std::pair<QString, int>, TrackerEndpointStatus> endpoints {};

View file

@ -155,16 +155,12 @@ void Connection::read()
sendResponse(resp); sendResponse(resp);
} }
#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
m_receivedData.slice(result.frameSize);
#else
m_receivedData.remove(0, result.frameSize); m_receivedData.remove(0, result.frameSize);
#endif
} }
break; break;
default: default:
Q_UNREACHABLE(); Q_ASSERT(false);
return; return;
} }
} }

View file

@ -50,7 +50,7 @@ using QStringPair = std::pair<QString, QString>;
namespace namespace
{ {
const QByteArray EOH = CRLF.repeated(2); const QByteArray EOH = QByteArray(CRLF).repeated(2);
const QByteArrayView viewWithoutEndingWith(const QByteArrayView in, const QByteArrayView str) const QByteArrayView viewWithoutEndingWith(const QByteArrayView in, const QByteArrayView str)
{ {
@ -69,8 +69,8 @@ namespace
return false; return false;
} }
const QString name = line.first(i).trimmed().toString().toLower(); const QString name = line.left(i).trimmed().toString().toLower();
const QString value = line.sliced(i + 1).trimmed().toString(); const QString value = line.mid(i + 1).trimmed().toString();
out[name] = value; out[name] = value;
return true; return true;
@ -164,7 +164,7 @@ bool RequestParser::parseStartLines(const QStringView data)
if (line.at(0).isSpace() && !requestLines.isEmpty()) if (line.at(0).isSpace() && !requestLines.isEmpty())
{ {
// continuation of previous line // continuation of previous line
requestLines.last() += line; requestLines.last() += line.toString();
} }
else else
{ {
@ -204,15 +204,15 @@ bool RequestParser::parseRequestLine(const QString &line)
m_request.method = match.captured(1); m_request.method = match.captured(1);
// Request Target // Request Target
const QByteArray url {match.capturedView(2).toLatin1()}; const QByteArray url {match.captured(2).toLatin1()};
const int sepPos = url.indexOf('?'); const int sepPos = url.indexOf('?');
const QByteArrayView pathComponent = ((sepPos == -1) ? url : QByteArrayView(url).first(sepPos)); const QByteArrayView pathComponent = ((sepPos == -1) ? url : QByteArrayView(url).mid(0, sepPos));
m_request.path = QString::fromUtf8(QByteArray::fromPercentEncoding(asQByteArray(pathComponent))); m_request.path = QString::fromUtf8(QByteArray::fromPercentEncoding(asQByteArray(pathComponent)));
if (sepPos >= 0) if (sepPos >= 0)
{ {
const QByteArrayView query = QByteArrayView(url).sliced(sepPos + 1); const QByteArrayView query = QByteArrayView(url).mid(sepPos + 1);
// [rfc3986] 2.4 When to Encode or Decode // [rfc3986] 2.4 When to Encode or Decode
// URL components should be separated before percent-decoding // URL components should be separated before percent-decoding
@ -221,11 +221,13 @@ bool RequestParser::parseRequestLine(const QString &line)
const int eqCharPos = param.indexOf('='); const int eqCharPos = param.indexOf('=');
if (eqCharPos <= 0) continue; // ignores params without name if (eqCharPos <= 0) continue; // ignores params without name
const QByteArrayView nameComponent = param.first(eqCharPos); const QByteArrayView nameComponent = param.mid(0, eqCharPos);
const QByteArrayView valueComponent = param.sliced(eqCharPos + 1); const QByteArrayView valueComponent = param.mid(eqCharPos + 1);
const QString paramName = QString::fromUtf8( const QString paramName = QString::fromUtf8(
QByteArray::fromPercentEncoding(asQByteArray(nameComponent)).replace('+', ' ')); QByteArray::fromPercentEncoding(asQByteArray(nameComponent)).replace('+', ' '));
const QByteArray paramValue = QByteArray::fromPercentEncoding(asQByteArray(valueComponent)).replace('+', ' '); const QByteArray paramValue = valueComponent.isNull()
? QByteArray("")
: QByteArray::fromPercentEncoding(asQByteArray(valueComponent)).replace('+', ' ');
m_request.query[paramName] = paramValue; m_request.query[paramName] = paramValue;
} }
@ -270,7 +272,7 @@ bool RequestParser::parsePostMessage(const QByteArrayView data)
return false; return false;
} }
const QByteArray delimiter = Utils::String::unquote(QStringView(contentType).sliced(idx + boundaryFieldName.size())).toLatin1(); const QByteArray delimiter = Utils::String::unquote(QStringView(contentType).mid(idx + boundaryFieldName.size())).toLatin1();
if (delimiter.isEmpty()) if (delimiter.isEmpty())
{ {
qWarning() << Q_FUNC_INFO << "boundary delimiter field empty!"; qWarning() << Q_FUNC_INFO << "boundary delimiter field empty!";
@ -279,7 +281,7 @@ bool RequestParser::parsePostMessage(const QByteArrayView data)
// split data by "dash-boundary" // split data by "dash-boundary"
const QByteArray dashDelimiter = QByteArray("--") + delimiter + CRLF; const QByteArray dashDelimiter = QByteArray("--") + delimiter + CRLF;
QList<QByteArrayView> multipart = splitToViews(data, dashDelimiter); QList<QByteArrayView> multipart = splitToViews(data, dashDelimiter, Qt::SkipEmptyParts);
if (multipart.isEmpty()) if (multipart.isEmpty())
{ {
qWarning() << Q_FUNC_INFO << "multipart empty"; qWarning() << Q_FUNC_INFO << "multipart empty";
@ -310,8 +312,8 @@ bool RequestParser::parseFormData(const QByteArrayView data)
return false; return false;
} }
const QString headers = QString::fromLatin1(data.first(eohPos)); const QString headers = QString::fromLatin1(data.mid(0, eohPos));
const QByteArrayView payload = viewWithoutEndingWith(data.sliced((eohPos + EOH.size())), CRLF); const QByteArrayView payload = viewWithoutEndingWith(data.mid((eohPos + EOH.size()), data.size()), CRLF);
HeaderMap headersMap; HeaderMap headersMap;
const QList<QStringView> headerLines = QStringView(headers).split(QString::fromLatin1(CRLF), Qt::SkipEmptyParts); const QList<QStringView> headerLines = QStringView(headers).split(QString::fromLatin1(CRLF), Qt::SkipEmptyParts);
@ -328,14 +330,14 @@ bool RequestParser::parseFormData(const QByteArrayView data)
if (idx < 0) if (idx < 0)
continue; continue;
const QString name = directive.first(idx).trimmed().toString().toLower(); const QString name = directive.left(idx).trimmed().toString().toLower();
const QString value = Utils::String::unquote(directive.sliced(idx + 1).trimmed()).toString(); const QString value = Utils::String::unquote(directive.mid(idx + 1).trimmed()).toString();
headersMap[name] = value; headersMap[name] = value;
} }
} }
else else
{ {
if (!parseHeaderLine(line, headersMap)) if (!parseHeaderLine(line.toString(), headersMap))
return false; return false;
} }
} }
@ -346,8 +348,7 @@ bool RequestParser::parseFormData(const QByteArrayView data)
if (headersMap.contains(filename)) if (headersMap.contains(filename))
{ {
m_request.files.append({.filename = headersMap[filename], .type = headersMap[HEADER_CONTENT_TYPE] m_request.files.append({headersMap[filename], headersMap[HEADER_CONTENT_TYPE], payload.toByteArray()});
, .data = payload.toByteArray()});
} }
else if (headersMap.contains(name)) else if (headersMap.contains(name))
{ {

View file

@ -37,9 +37,8 @@
#include <QtLogging> #include <QtLogging>
#include <QNetworkProxy> #include <QNetworkProxy>
#include <QSslCertificate>
#include <QSslCipher> #include <QSslCipher>
#include <QSslKey> #include <QSslConfiguration>
#include <QSslSocket> #include <QSslSocket>
#include <QStringList> #include <QStringList>
#include <QTimer> #include <QTimer>
@ -101,12 +100,13 @@ using namespace Http;
Server::Server(IRequestHandler *requestHandler, QObject *parent) Server::Server(IRequestHandler *requestHandler, QObject *parent)
: QTcpServer(parent) : QTcpServer(parent)
, m_requestHandler(requestHandler) , m_requestHandler(requestHandler)
, m_sslConfig {QSslConfiguration::defaultConfiguration()}
{ {
setProxy(QNetworkProxy::NoProxy); setProxy(QNetworkProxy::NoProxy);
m_sslConfig.setCiphers(safeCipherList()); QSslConfiguration sslConf {QSslConfiguration::defaultConfiguration()};
m_sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone); sslConf.setProtocol(QSsl::TlsV1_2OrLater);
sslConf.setCiphers(safeCipherList());
QSslConfiguration::setDefaultConfiguration(sslConf);
auto *dropConnectionTimer = new QTimer(this); auto *dropConnectionTimer = new QTimer(this);
connect(dropConnectionTimer, &QTimer::timeout, this, &Server::dropTimedOutConnection); connect(dropConnectionTimer, &QTimer::timeout, this, &Server::dropTimedOutConnection);
@ -115,7 +115,7 @@ Server::Server(IRequestHandler *requestHandler, QObject *parent)
void Server::incomingConnection(const qintptr socketDescriptor) void Server::incomingConnection(const qintptr socketDescriptor)
{ {
std::unique_ptr<QTcpSocket> serverSocket = isHttps() ? std::make_unique<QSslSocket>(this) : std::make_unique<QTcpSocket>(this); std::unique_ptr<QTcpSocket> serverSocket = m_https ? std::make_unique<QSslSocket>(this) : std::make_unique<QTcpSocket>(this);
if (!serverSocket->setSocketDescriptor(socketDescriptor)) if (!serverSocket->setSocketDescriptor(socketDescriptor))
return; return;
@ -127,10 +127,13 @@ void Server::incomingConnection(const qintptr socketDescriptor)
try try
{ {
if (isHttps()) if (m_https)
{ {
auto *sslSocket = static_cast<QSslSocket *>(serverSocket.get()); auto *sslSocket = static_cast<QSslSocket *>(serverSocket.get());
sslSocket->setSslConfiguration(m_sslConfig); sslSocket->setProtocol(QSsl::SecureProtocols);
sslSocket->setPrivateKey(m_key);
sslSocket->setLocalCertificateChain(m_certificates);
sslSocket->setPeerVerifyMode(QSslSocket::VerifyNone);
sslSocket->startServerEncryption(); sslSocket->startServerEncryption();
} }
@ -175,17 +178,17 @@ bool Server::setupHttps(const QByteArray &certificates, const QByteArray &privat
return false; return false;
} }
m_sslConfig.setLocalCertificateChain(certs); m_key = key;
m_sslConfig.setPrivateKey(key); m_certificates = certs;
m_https = true; m_https = true;
return true; return true;
} }
void Server::disableHttps() void Server::disableHttps()
{ {
m_sslConfig.setLocalCertificateChain({});
m_sslConfig.setPrivateKey({});
m_https = false; m_https = false;
m_certificates.clear();
m_key.clear();
} }
bool Server::isHttps() const bool Server::isHttps() const

Some files were not shown because too many files have changed in this diff Show more