├── .github └── workflows │ └── ci.yml ├── CMakeLists.txt ├── Codec ├── BencodeCodec.cpp ├── BencodeCodec.h ├── CMakeLists.txt ├── IStructuredDataCodec.cpp ├── IStructuredDataCodec.h ├── JsonCodec.cpp ├── JsonCodec.h ├── PickleCodec.cpp └── PickleCodec.h ├── Common ├── CMakeLists.txt ├── Exception.cpp ├── Exception.h ├── IFileStreamProvider.cpp ├── IFileStreamProvider.h ├── IForwardIterator.h ├── Logger.cpp ├── Logger.h ├── SignalHandler.cpp ├── SignalHandler.h ├── ThreadSafeIterator.h ├── Util.cpp └── Util.h ├── ImportHelper.cpp ├── ImportHelper.h ├── LICENSE ├── MigrationTransaction.cpp ├── MigrationTransaction.h ├── README.md ├── Store ├── CMakeLists.txt ├── DebugTorrentStateIterator.cpp ├── DebugTorrentStateIterator.h ├── DelugeStateStore.cpp ├── DelugeStateStore.h ├── ITorrentStateStore.cpp ├── ITorrentStateStore.h ├── TorrentStateStoreFactory.cpp ├── TorrentStateStoreFactory.h ├── TransmissionStateStore.cpp ├── TransmissionStateStore.h ├── rTorrentStateStore.cpp ├── rTorrentStateStore.h ├── uTorrentStateStore.cpp ├── uTorrentStateStore.h ├── uTorrentWebStateStore.cpp └── uTorrentWebStateStore.h ├── Torrent ├── Box.cpp ├── Box.h ├── BoxHelper.cpp ├── BoxHelper.h ├── CMakeLists.txt ├── Intention.h ├── TorrentClient.cpp ├── TorrentClient.h ├── TorrentInfo.cpp └── TorrentInfo.h ├── fetch.cmake ├── main.cpp ├── vcpkg.cmake └── vcpkg.json /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: [push, pull_request] 3 | env: 4 | VCPKG_DEFAULT_BINARY_CACHE: ${{ github.workspace }}/_vcpkg_cache 5 | jobs: 6 | build: 7 | runs-on: ["${{ matrix.image }}"] 8 | strategy: 9 | matrix: 10 | os: [linux, mac, windows] 11 | include: 12 | - os: linux 13 | image: ubuntu-latest 14 | - os: mac 15 | image: macOS-latest 16 | - os: windows 17 | image: windows-latest 18 | cmake_args: -A x64 19 | fail-fast: false 20 | steps: 21 | - name: Checkout 22 | uses: actions/checkout@v4 23 | - name: Create vcpkg cache directory 24 | run: mkdir _vcpkg_cache 25 | - name: Cache node modules 26 | uses: actions/cache@v4 27 | env: 28 | cache_name: vcpkg 29 | with: 30 | path: ${{ env.VCPKG_DEFAULT_BINARY_CACHE }} 31 | key: ${{ runner.os }}-build-${{ env.cache_name }}-${{ hashFiles('vcpkg.cmake', 'vcpkg.json') }} 32 | restore-keys: | 33 | ${{ runner.os }}-build-${{ env.cache_name }}- 34 | ${{ runner.os }}-build- 35 | ${{ runner.os }}- 36 | - name: Install dependencies (linux) 37 | if: matrix.os == 'linux' 38 | run: curl -sSL https://cmake.org/files/v3.18/cmake-3.18.5-Linux-x86_64.tar.gz -o - | sudo tar xzf - --strip-components 1 -C /usr/local 39 | - name: CMake version 40 | run: cmake --version 41 | - name: Configure 42 | run: cmake -S . -B _build -DCMAKE_BUILD_TYPE=RelWithDebInfo ${{ matrix.cmake_args }} 43 | - name: Build 44 | run: cmake --build _build --config RelWithDebInfo 45 | - name: Prepare artifacts (linux) 46 | if: matrix.os == 'linux' 47 | run: | 48 | mkdir _bin 49 | cd _bin 50 | cp ../_build/BtMigrate . 51 | objcopy --only-keep-debug BtMigrate BtMigrate.debug 52 | objcopy --add-gnu-debuglink=BtMigrate.debug BtMigrate 53 | strip -x BtMigrate 54 | - name: Prepare artifacts (mac) 55 | if: matrix.os == 'mac' 56 | run: | 57 | mkdir _bin 58 | cd _bin 59 | cp ../_build/BtMigrate . 60 | dsymutil -f BtMigrate 61 | strip -x BtMigrate 62 | - name: Prepare artifacts (windows) 63 | if: matrix.os == 'windows' 64 | run: | 65 | mkdir _bin 66 | cd _bin 67 | copy ..\_build\RelWithDebInfo\BtMigrate.exe . 68 | copy ..\_build\RelWithDebInfo\BtMigrate.pdb . 69 | - uses: actions/upload-artifact@v4 70 | with: 71 | name: ${{ matrix.os }}-binaries 72 | path: _bin 73 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.18) 2 | 3 | option(USE_VCPKG "Use vcpkg to resolve dependencies" ON) 4 | 5 | if(USE_VCPKG) 6 | include(vcpkg.cmake) 7 | endif() 8 | 9 | project(BtMigrate VERSION 0.1) 10 | 11 | option(USE_FETCHCONTENT "Use FetchContent to resolve dependencies" ON) 12 | 13 | if(USE_FETCHCONTENT) 14 | include(fetch.cmake) 15 | endif() 16 | 17 | find_package(Threads REQUIRED) 18 | 19 | find_package(cxxopts REQUIRED) 20 | find_package(fmt REQUIRED) 21 | find_package(jsoncons REQUIRED) 22 | find_package(pugixml REQUIRED) 23 | find_package(SqliteOrm REQUIRED) 24 | 25 | if(NOT TARGET digestpp::digestpp) 26 | find_package(digestpp REQUIRED) 27 | endif() 28 | 29 | set(CMAKE_CXX_STANDARD 20) 30 | set(CMAKE_CXX_STANDARD_REQUIRED ON) 31 | set(CMAKE_CXX_EXTENSIONS OFF) 32 | 33 | add_definitions( 34 | -DBOOST_ALL_NO_LIB 35 | -DBTMIGRATE_VERSION="${PROJECT_VERSION}") 36 | 37 | if(WIN32) 38 | add_definitions( 39 | -DUNICODE 40 | -D_UNICODE 41 | -D_CRT_SECURE_NO_WARNINGS 42 | -D_SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING 43 | -DWIN32_LEAN_AND_MEAN 44 | -DNOMINMAX) 45 | endif() 46 | 47 | if(MSVC) 48 | add_compile_options(/W4) 49 | else() 50 | add_compile_options(-Wall -Wextra) 51 | endif() 52 | 53 | include_directories(.) 54 | 55 | add_subdirectory(Codec) 56 | add_subdirectory(Common) 57 | add_subdirectory(Store) 58 | add_subdirectory(Torrent) 59 | 60 | add_executable(BtMigrate 61 | ImportHelper.cpp 62 | ImportHelper.h 63 | MigrationTransaction.cpp 64 | MigrationTransaction.h 65 | main.cpp) 66 | 67 | target_link_libraries(BtMigrate 68 | PUBLIC 69 | BtMigrateCommon 70 | PRIVATE 71 | BtMigrateStore 72 | BtMigrateTorrent) 73 | 74 | target_link_libraries(BtMigrate 75 | PRIVATE 76 | cxxopts::cxxopts 77 | fmt::fmt) 78 | -------------------------------------------------------------------------------- /Codec/BencodeCodec.cpp: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "BencodeCodec.h" 18 | 19 | #include "Common/Exception.h" 20 | #include "Common/Util.h" 21 | 22 | #include 23 | #include 24 | 25 | #include 26 | #include 27 | 28 | namespace 29 | { 30 | 31 | ojson DecodeOneValue(std::istream& stream) 32 | { 33 | ojson result; 34 | 35 | std::string buffer; 36 | int c = stream.get(); 37 | switch (c) 38 | { 39 | case 'i': 40 | buffer.clear(); 41 | while ((c = stream.get()) != 'e') 42 | { 43 | buffer += static_cast(c); 44 | } 45 | result = Util::StringToInt(buffer); 46 | break; 47 | 48 | case 'l': 49 | result = ojson::array(); 50 | while (stream.get() != 'e') 51 | { 52 | stream.unget(); 53 | result.push_back(DecodeOneValue(stream)); 54 | } 55 | break; 56 | 57 | case 'd': 58 | result = ojson::object(); 59 | while (stream.get() != 'e') 60 | { 61 | stream.unget(); 62 | ojson key = DecodeOneValue(stream); 63 | ojson value = DecodeOneValue(stream); 64 | result.insert_or_assign(key.as(), value); 65 | } 66 | break; 67 | 68 | case '0': 69 | case '1': 70 | case '2': 71 | case '3': 72 | case '4': 73 | case '5': 74 | case '6': 75 | case '7': 76 | case '8': 77 | case '9': 78 | buffer.clear(); 79 | while (c != ':') 80 | { 81 | buffer += static_cast(c); 82 | c = stream.get(); 83 | } 84 | buffer.resize(Util::StringToInt(buffer)); 85 | stream.read(&buffer[0], buffer.size()); 86 | result = buffer; 87 | break; 88 | 89 | default: 90 | throw Exception(fmt::format("Unable to decode value: {}", c)); 91 | } 92 | 93 | return result; 94 | } 95 | 96 | void EncodeOneValue(std::ostream& stream, ojson const& value) 97 | { 98 | if (value.is_object()) 99 | { 100 | stream << 'd'; 101 | for (auto const& item : value.object_range()) 102 | { 103 | EncodeOneValue(stream, item.key()); 104 | EncodeOneValue(stream, item.value()); 105 | } 106 | stream << 'e'; 107 | } 108 | else if (value.is_array()) 109 | { 110 | stream << 'l'; 111 | for (auto const& item : value.array_range()) 112 | { 113 | EncodeOneValue(stream, item); 114 | } 115 | stream << 'e'; 116 | } 117 | else if (value.is()) 118 | { 119 | stream << value.as().size(); 120 | stream << ':'; 121 | stream << value.as(); 122 | } 123 | else if (value.is()) 124 | { 125 | stream << 'i'; 126 | stream << value.as(); 127 | stream << 'e'; 128 | } 129 | else if (value.is()) 130 | { 131 | stream << 'i'; 132 | stream << value.as(); 133 | stream << 'e'; 134 | } 135 | else 136 | { 137 | throw Exception(fmt::format("Unable to encode value: {}", fmt::streamed(value))); 138 | } 139 | } 140 | 141 | } // namespace 142 | 143 | BencodeCodec::BencodeCodec() = default; 144 | BencodeCodec::~BencodeCodec() = default; 145 | 146 | void BencodeCodec::Decode(std::istream& stream, ojson& root) const 147 | { 148 | root = DecodeOneValue(stream); 149 | } 150 | 151 | void BencodeCodec::Encode(std::ostream& stream, ojson const& root) const 152 | { 153 | EncodeOneValue(stream, root); 154 | } 155 | -------------------------------------------------------------------------------- /Codec/BencodeCodec.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | #include "IStructuredDataCodec.h" 20 | 21 | class BencodeCodec : public IStructuredDataCodec 22 | { 23 | public: 24 | BencodeCodec(); 25 | ~BencodeCodec() override; 26 | 27 | public: 28 | // IStructuredDataCodec 29 | void Decode(std::istream& stream, ojson& root) const override; 30 | void Encode(std::ostream& stream, ojson const& root) const override; 31 | }; 32 | -------------------------------------------------------------------------------- /Codec/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_library(BtMigrateCodec 2 | BencodeCodec.cpp 3 | BencodeCodec.h 4 | IStructuredDataCodec.cpp 5 | IStructuredDataCodec.h 6 | JsonCodec.cpp 7 | JsonCodec.h 8 | PickleCodec.cpp 9 | PickleCodec.h) 10 | 11 | target_link_libraries(BtMigrateCodec 12 | PRIVATE 13 | BtMigrateCommon) 14 | 15 | target_link_libraries(BtMigrateCodec 16 | PUBLIC 17 | jsoncons 18 | PRIVATE 19 | fmt::fmt) 20 | -------------------------------------------------------------------------------- /Codec/IStructuredDataCodec.cpp: -------------------------------------------------------------------------------- 1 | #include "IStructuredDataCodec.h" 2 | 3 | IStructuredDataCodec::~IStructuredDataCodec() = default; 4 | -------------------------------------------------------------------------------- /Codec/IStructuredDataCodec.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | #include 20 | 21 | #include 22 | 23 | using jsoncons::ojson; 24 | 25 | class IStructuredDataCodec 26 | { 27 | public: 28 | virtual ~IStructuredDataCodec(); 29 | 30 | virtual void Decode(std::istream& stream, ojson& root) const = 0; 31 | virtual void Encode(std::ostream& stream, ojson const& root) const = 0; 32 | }; 33 | -------------------------------------------------------------------------------- /Codec/JsonCodec.cpp: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "JsonCodec.h" 18 | 19 | #include 20 | 21 | JsonCodec::JsonCodec() = default; 22 | JsonCodec::~JsonCodec() = default; 23 | 24 | void JsonCodec::Decode(std::istream& stream, ojson& root) const 25 | { 26 | stream >> root; 27 | } 28 | 29 | void JsonCodec::Encode(std::ostream& stream, ojson const& root) const 30 | { 31 | stream << root; 32 | } 33 | -------------------------------------------------------------------------------- /Codec/JsonCodec.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | #include "IStructuredDataCodec.h" 20 | 21 | class JsonCodec : public IStructuredDataCodec 22 | { 23 | public: 24 | JsonCodec(); 25 | ~JsonCodec() override; 26 | 27 | public: 28 | // IStructuredDataCodec 29 | void Decode(std::istream& stream, ojson& root) const override; 30 | void Encode(std::ostream& stream, ojson const& root) const override; 31 | }; 32 | -------------------------------------------------------------------------------- /Codec/PickleCodec.cpp: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "PickleCodec.h" 18 | 19 | #include "Common/Exception.h" 20 | #include "Common/Util.h" 21 | 22 | #include 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | 32 | namespace 33 | { 34 | 35 | // Taken from Python sources 36 | enum opcode 37 | { 38 | MARK = '(', 39 | STOP = '.', 40 | POP = '0', 41 | POP_MARK = '1', 42 | DUP = '2', 43 | FLOAT = 'F', 44 | INT = 'I', 45 | BININT = 'J', 46 | BININT1 = 'K', 47 | LONG = 'L', 48 | BININT2 = 'M', 49 | NONE = 'N', 50 | PERSID = 'P', 51 | BINPERSID = 'Q', 52 | REDUCE = 'R', 53 | STRING = 'S', 54 | BINSTRING = 'T', 55 | SHORT_BINSTRING = 'U', 56 | UNICODE_ = 'V', 57 | BINUNICODE = 'X', 58 | APPEND = 'a', 59 | BUILD = 'b', 60 | GLOBAL = 'c', 61 | DICT = 'd', 62 | EMPTY_DICT = '}', 63 | APPENDS = 'e', 64 | GET = 'g', 65 | BINGET = 'h', 66 | INST = 'i', 67 | LONG_BINGET = 'j', 68 | LIST = 'l', 69 | EMPTY_LIST = ']', 70 | OBJ = 'o', 71 | PUT = 'p', 72 | BINPUT = 'q', 73 | LONG_BINPUT = 'r', 74 | SETITEM = 's', 75 | TUPLE = 't', 76 | EMPTY_TUPLE = ')', 77 | SETITEMS = 'u', 78 | BINFLOAT = 'G', 79 | 80 | /* Protocol 2. */ 81 | PROTO = 0x80, 82 | NEWOBJ = 0x81, 83 | EXT1 = 0x82, 84 | EXT2 = 0x83, 85 | EXT4 = 0x84, 86 | TUPLE1 = 0x85, 87 | TUPLE2 = 0x86, 88 | TUPLE3 = 0x87, 89 | NEWTRUE = 0x88, 90 | NEWFALSE = 0x89, 91 | LONG1 = 0x8a, 92 | LONG4 = 0x8b, 93 | 94 | /* Protocol 3 (Python 3.x) */ 95 | BINBYTES = 'B', 96 | SHORT_BINBYTES = 'C', 97 | 98 | /* Protocol 4 */ 99 | SHORT_BINUNICODE = 0x8c, 100 | BINUNICODE8 = 0x8d, 101 | BINBYTES8 = 0x8e, 102 | EMPTY_SET = 0x8f, 103 | ADDITEMS = 0x90, 104 | FROZENSET = 0x91, 105 | NEWOBJ_EX = 0x92, 106 | STACK_GLOBAL = 0x93, 107 | MEMOIZE = 0x94, 108 | FRAME = 0x95, 109 | 110 | /* Protocol 5 */ 111 | BYTEARRAY8 = 0x96, 112 | NEXT_BUFFER = 0x97, 113 | READONLY_BUFFER = 0x98 114 | }; 115 | 116 | struct StackItem 117 | { 118 | StackItem() : 119 | Type(0), 120 | Value() 121 | { 122 | 123 | } 124 | 125 | explicit StackItem(int type, ojson const& value = ojson()) : 126 | Type(type), 127 | Value(value) 128 | { 129 | // 130 | } 131 | 132 | int Type; 133 | ojson Value; 134 | }; 135 | 136 | std::string UnicodeCodePointToUtf8(unsigned int code) 137 | { 138 | std::string result; 139 | 140 | if (code <= 0x7f) 141 | { 142 | result.resize(1); 143 | result[0] = static_cast(code); 144 | } 145 | else if (code <= 0x7FF) 146 | { 147 | result.resize(2); 148 | result[1] = static_cast(0x80 | (0x3f & code)); 149 | result[0] = static_cast(0xc0 | (0x1f & (code >> 6))); 150 | } 151 | else if (code <= 0xFFFF) 152 | { 153 | result.resize(3); 154 | result[2] = static_cast(0x80 | (0x3f & code)); 155 | result[1] = static_cast(0x80 | (0x3f & (code >> 6))); 156 | result[0] = static_cast(0xe0 | (0x0f & (code >> 12))); 157 | } 158 | else if (code <= 0x10FFFF) 159 | { 160 | result.resize(4); 161 | result[3] = static_cast(0x80 | (0x3f & code)); 162 | result[2] = static_cast(0x80 | (0x3f & (code >> 6))); 163 | result[1] = static_cast(0x80 | (0x3f & (code >> 12))); 164 | result[0] = static_cast(0xf0 | (0x07 & (code >> 18))); 165 | } 166 | else 167 | { 168 | throw Exception("Invalid unicode code point"); 169 | } 170 | 171 | return result; 172 | } 173 | 174 | std::string UnicodeToUtf8(std::string const& text) 175 | { 176 | std::string result; 177 | 178 | for (auto it = text.cbegin(), end = text.cend(); it != end; ++it) 179 | { 180 | if (*it != '\\') 181 | { 182 | result += *it; 183 | continue; 184 | } 185 | 186 | ++it; 187 | switch (*it) 188 | { 189 | case 'u': 190 | break; 191 | case 'b': 192 | result += '\b'; 193 | continue; 194 | case 'f': 195 | result += '\f'; 196 | continue; 197 | case 'n': 198 | result += '\n'; 199 | continue; 200 | case 'r': 201 | result += '\r'; 202 | continue; 203 | case 't': 204 | result += '\t'; 205 | continue; 206 | case '"': 207 | case '\\': 208 | default: 209 | result += *it; 210 | continue; 211 | } 212 | 213 | std::string codeBuffer; 214 | codeBuffer += *(++it); 215 | codeBuffer += *(++it); 216 | codeBuffer += *(++it); 217 | codeBuffer += *(++it); 218 | 219 | unsigned int code = std::strtol(codeBuffer.c_str(), nullptr, 16); 220 | if (code >= 0xd800 && code <= 0xdbff) 221 | { 222 | if (*(++it) != '\\') 223 | { 224 | throw Exception("Invalid unicode code point"); 225 | } 226 | 227 | if (*(++it) != 'u') 228 | { 229 | throw Exception("Invalid unicode code point"); 230 | } 231 | 232 | codeBuffer.clear(); 233 | codeBuffer += *(++it); 234 | codeBuffer += *(++it); 235 | codeBuffer += *(++it); 236 | codeBuffer += *(++it); 237 | 238 | unsigned int const code2 = std::strtol(codeBuffer.c_str(), nullptr, 16); 239 | if (code2 >= 0xdc00 && code2 <= 0xdfff) 240 | { 241 | throw Exception("Invalid unicode code point"); 242 | } 243 | 244 | code = ((code - 0xd800) << 10) | (code2 - 0xdc00); 245 | } 246 | 247 | result += UnicodeCodePointToUtf8(code); 248 | } 249 | 250 | return result; 251 | } 252 | 253 | void PopMark(std::stack& stack) 254 | { 255 | while (!stack.empty() && stack.top().Type != MARK) 256 | { 257 | stack.pop(); 258 | } 259 | if (!stack.empty()) 260 | { 261 | stack.pop(); 262 | } 263 | } 264 | 265 | template 266 | T GetBinNumber(std::istream& stream, std::endian order = std::endian::little) 267 | { 268 | static_assert(std::is_integral_v || std::is_floating_point_v); 269 | 270 | char result[sizeof(T)]; 271 | stream.read(result, sizeof(result)); 272 | 273 | if (order != std::endian::native) 274 | { 275 | std::reverse(result, result + sizeof(result)); 276 | } 277 | 278 | return *reinterpret_cast(result); 279 | } 280 | 281 | template 282 | std::string GetBinUnicode(std::istream& stream, std::endian order = std::endian::little) 283 | { 284 | LengthT const length = GetBinNumber(stream, order); 285 | 286 | std::string result; 287 | result.resize(length); 288 | stream.read(result.data(), length); 289 | return result; 290 | } 291 | 292 | } // namespace 293 | 294 | PickleCodec::PickleCodec() = default; 295 | PickleCodec::~PickleCodec() = default; 296 | 297 | void PickleCodec::Decode(std::istream& stream, ojson& root) const 298 | { 299 | std::stack stack, stack2; 300 | std::map memo; 301 | 302 | [[maybe_unused]] int proto = 0; 303 | 304 | bool stopped = false; 305 | StackItem currentItem, currentItem2; 306 | std::string buffer, buffer2; 307 | while (!stopped && !stream.eof()) 308 | { 309 | int const code = GetBinNumber(stream); 310 | switch (code) 311 | { 312 | case MARK: 313 | stack.push(StackItem(code)); 314 | break; 315 | 316 | case STOP: 317 | root = stack.top().Value; 318 | stack.pop(); // result 319 | stopped = true; 320 | break; 321 | 322 | case POP: 323 | stack.pop(); 324 | break; 325 | 326 | case POP_MARK: 327 | PopMark(stack); 328 | break; 329 | 330 | case DUP: 331 | stack.push(stack.top()); 332 | break; 333 | 334 | case INT: 335 | std::getline(stream, buffer, '\n'); 336 | if (buffer == "00") 337 | { 338 | stack.push(StackItem(code, false)); 339 | } 340 | else if (buffer == "01") 341 | { 342 | stack.push(StackItem(code, true)); 343 | } 344 | else 345 | { 346 | stack.push(StackItem(code, Util::StringToInt(buffer))); 347 | } 348 | break; 349 | 350 | case FLOAT: 351 | std::getline(stream, buffer, '\n'); 352 | stack.push(StackItem(code, std::strtod(buffer.c_str(), nullptr))); 353 | break; 354 | 355 | case LONG: 356 | std::getline(stream, buffer, '\n'); 357 | if (!buffer.empty() && buffer.back() == 'L') 358 | { 359 | buffer.resize(buffer.size() - 1); 360 | } 361 | stack.push(StackItem(code, Util::StringToInt(buffer))); 362 | break; 363 | 364 | case STRING: 365 | std::getline(stream, buffer, '\n'); 366 | stack.push(StackItem(code, UnicodeToUtf8(buffer.substr(1, buffer.size() - 2)))); 367 | break; 368 | 369 | case UNICODE_: 370 | std::getline(stream, buffer, '\n'); 371 | stack.push(StackItem(code, UnicodeToUtf8(buffer))); 372 | break; 373 | 374 | case INST: 375 | std::getline(stream, buffer, '\n'); 376 | std::getline(stream, buffer, '\n'); 377 | [[fallthrough]]; 378 | 379 | case DICT: 380 | currentItem = StackItem(code, ojson::object()); 381 | while (stack.top().Type != MARK) 382 | { 383 | currentItem2 = stack.top(); 384 | stack.pop(); 385 | currentItem.Value.insert_or_assign(stack.top().Value.as(), currentItem2.Value); 386 | stack.pop(); 387 | } 388 | stack.top() = currentItem; 389 | break; 390 | 391 | case LIST: 392 | case TUPLE: 393 | currentItem = StackItem(code, ojson::array()); 394 | while (stack.top().Type != MARK) 395 | { 396 | currentItem.Value.push_back(stack.top().Value); 397 | stack.pop(); 398 | } 399 | stack.top() = currentItem; 400 | break; 401 | 402 | case NONE: 403 | stack.push(StackItem(code, ojson::null())); 404 | break; 405 | 406 | case EMPTY_DICT: 407 | stack.push(StackItem(code, ojson::object())); 408 | break; 409 | 410 | case EMPTY_LIST: 411 | stack.push(StackItem(code, ojson::array())); 412 | break; 413 | 414 | case TUPLE3: 415 | stack2.push(std::move(stack.top())); 416 | stack.pop(); 417 | [[fallthrough]]; 418 | 419 | case TUPLE2: 420 | stack2.push(std::move(stack.top())); 421 | stack.pop(); 422 | [[fallthrough]]; 423 | 424 | case TUPLE1: 425 | stack2.push(std::move(stack.top())); 426 | stack.pop(); 427 | [[fallthrough]]; 428 | 429 | case EMPTY_TUPLE: 430 | stack.push(StackItem(code, ojson::array())); 431 | while (!stack2.empty()) 432 | { 433 | stack.top().Value.push_back(std::move(stack2.top().Value)); 434 | stack2.pop(); 435 | } 436 | break; 437 | 438 | case APPEND: 439 | currentItem = stack.top(); 440 | stack.pop(); 441 | stack.top().Value.push_back(currentItem.Value); 442 | break; 443 | 444 | case BUILD: 445 | currentItem = stack.top(); 446 | stack.pop(); 447 | stack.top() = currentItem; 448 | break; 449 | 450 | case GET: 451 | std::getline(stream, buffer, '\n'); 452 | stack.push(memo.at(Util::StringToInt(buffer))); 453 | break; 454 | 455 | case PUT: 456 | std::getline(stream, buffer, '\n'); 457 | memo[Util::StringToInt(buffer)] = stack.top(); 458 | break; 459 | 460 | case SETITEM: 461 | currentItem = stack.top(); 462 | stack.pop(); 463 | currentItem2 = stack.top(); 464 | stack.pop(); 465 | stack.top().Value.insert_or_assign(currentItem2.Value.as(), currentItem.Value); 466 | break; 467 | 468 | case PROTO: 469 | proto = static_cast(stream.get()); 470 | break; 471 | 472 | case GLOBAL: 473 | std::getline(stream, buffer, '\n'); 474 | std::getline(stream, buffer2, '\n'); 475 | stack.push(StackItem(code, buffer + ':' + buffer2)); 476 | break; 477 | 478 | case BINPUT: 479 | memo[GetBinNumber(stream)] = stack.top(); 480 | break; 481 | 482 | case NEWOBJ: 483 | currentItem = stack.top(); 484 | stack.pop(); 485 | currentItem2 = stack.top(); 486 | stack.pop(); 487 | stack.push(StackItem(code, ojson::object())); 488 | break; 489 | 490 | case BINUNICODE: 491 | stack.push(StackItem(code, GetBinUnicode(stream))); 492 | break; 493 | 494 | case NEWTRUE: 495 | stack.push(StackItem(code, true)); 496 | break; 497 | 498 | case NEWFALSE: 499 | stack.push(StackItem(code, false)); 500 | break; 501 | 502 | case BINFLOAT: 503 | stack.push(StackItem(code, GetBinNumber(stream, std::endian::big))); 504 | break; 505 | 506 | case BININT1: 507 | stack.push(StackItem(code, GetBinNumber(stream))); 508 | break; 509 | 510 | case APPENDS: 511 | while (!stack.empty() && stack.top().Type != MARK) 512 | { 513 | stack2.push(std::move(stack.top())); 514 | stack.pop(); 515 | } 516 | stack.pop(); 517 | while (!stack2.empty()) 518 | { 519 | stack.top().Value.push_back(std::move(stack2.top().Value)); 520 | stack2.pop(); 521 | } 522 | break; 523 | 524 | case BININT: 525 | stack.push(StackItem(code, GetBinNumber(stream))); 526 | break; 527 | 528 | case BINGET: 529 | stack.push(memo[GetBinNumber(stream)]); 530 | break; 531 | 532 | case SETITEMS: 533 | while (!stack.empty() && stack.top().Type != MARK) 534 | { 535 | stack2.push(std::move(stack.top())); 536 | stack.pop(); 537 | } 538 | stack.pop(); 539 | while (!stack2.empty()) 540 | { 541 | currentItem = std::move(stack2.top()); 542 | stack2.pop(); 543 | currentItem2 = std::move(stack2.top()); 544 | stack2.pop(); 545 | stack.top().Value.insert_or_assign(currentItem.Value.as(), std::move(currentItem2.Value)); 546 | } 547 | break; 548 | 549 | case LONG_BINPUT: 550 | memo[GetBinNumber(stream)] = stack.top(); 551 | break; 552 | 553 | case LONG_BINGET: 554 | stack.push(memo[GetBinNumber(stream)]); 555 | break; 556 | 557 | default: 558 | throw Exception(fmt::format("Pickle opcode {} not yet supported", code)); 559 | } 560 | } 561 | 562 | if (!stack.empty()) 563 | { 564 | throw Exception("Pickle stack is not empty at the end"); 565 | } 566 | } 567 | 568 | void PickleCodec::Encode(std::ostream& /*stream*/, ojson const& /*root*/) const 569 | { 570 | throw NotImplementedException(__func__); 571 | } 572 | -------------------------------------------------------------------------------- /Codec/PickleCodec.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | #include "IStructuredDataCodec.h" 20 | 21 | class PickleCodec : public IStructuredDataCodec 22 | { 23 | public: 24 | PickleCodec(); 25 | ~PickleCodec() override; 26 | 27 | public: 28 | // IStructuredDataCodec 29 | void Decode(std::istream& stream, ojson& root) const override; 30 | void Encode(std::ostream& stream, ojson const& root) const override; 31 | }; 32 | -------------------------------------------------------------------------------- /Common/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_library(BtMigrateCommon 2 | Exception.cpp 3 | Exception.h 4 | IFileStreamProvider.cpp 5 | IFileStreamProvider.h 6 | IForwardIterator.h 7 | Logger.cpp 8 | Logger.h 9 | SignalHandler.cpp 10 | SignalHandler.h 11 | ThreadSafeIterator.h 12 | Util.cpp 13 | Util.h) 14 | 15 | target_link_libraries(BtMigrateCommon 16 | PUBLIC 17 | jsoncons 18 | PRIVATE 19 | digestpp::digestpp 20 | fmt::fmt 21 | Threads::Threads) 22 | -------------------------------------------------------------------------------- /Common/Exception.cpp: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "Exception.h" 18 | 19 | Exception::Exception(std::string const& message) : 20 | m_message(message) 21 | { 22 | // 23 | } 24 | 25 | char const* Exception::what() const noexcept 26 | { 27 | return m_message.c_str(); 28 | } 29 | 30 | Exception::~Exception() = default; 31 | 32 | NotImplementedException::NotImplementedException(std::string const& place) : 33 | Exception("Not implemented: " + place) 34 | { 35 | // 36 | } 37 | 38 | NotImplementedException::~NotImplementedException() = default; 39 | -------------------------------------------------------------------------------- /Common/Exception.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | #include 20 | #include 21 | 22 | class Exception : public std::exception 23 | { 24 | public: 25 | explicit Exception(std::string const& message); 26 | ~Exception() override; 27 | 28 | public: 29 | // std::exception 30 | char const* what() const noexcept override; 31 | 32 | private: 33 | std::string const m_message; 34 | }; 35 | 36 | class NotImplementedException : public Exception 37 | { 38 | public: 39 | explicit NotImplementedException(std::string const& place); 40 | ~NotImplementedException() override; 41 | }; 42 | -------------------------------------------------------------------------------- /Common/IFileStreamProvider.cpp: -------------------------------------------------------------------------------- 1 | #include "IFileStreamProvider.h" 2 | 3 | IFileStreamProvider::~IFileStreamProvider() noexcept(false) 4 | { 5 | } 6 | -------------------------------------------------------------------------------- /Common/IFileStreamProvider.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | #include 20 | #include 21 | #include 22 | 23 | typedef std::unique_ptr IReadStreamPtr; 24 | typedef std::unique_ptr IWriteStreamPtr; 25 | 26 | class IFileStreamProvider 27 | { 28 | public: 29 | virtual ~IFileStreamProvider() noexcept(false); 30 | 31 | virtual IReadStreamPtr GetReadStream(std::filesystem::path const& path) const = 0; 32 | virtual IWriteStreamPtr GetWriteStream(std::filesystem::path const& path) = 0; 33 | }; 34 | -------------------------------------------------------------------------------- /Common/IForwardIterator.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | template 20 | class IForwardIterator 21 | { 22 | public: 23 | virtual ~IForwardIterator() = default; 24 | 25 | virtual bool GetNext(ArgsT&... value) = 0; 26 | }; 27 | -------------------------------------------------------------------------------- /Common/Logger.cpp: -------------------------------------------------------------------------------- 1 | #include "Logger.h" 2 | 3 | #include 4 | #include 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | namespace 11 | { 12 | 13 | std::mutex LogFlushMutex; 14 | Logger::Level MinimumLevel = Logger::Info; 15 | 16 | std::string LevelToString(Logger::Level level) 17 | { 18 | switch (level) 19 | { 20 | case Logger::Debug: 21 | return "D"; 22 | case Logger::Info: 23 | return "I"; 24 | case Logger::Warning: 25 | return "W"; 26 | case Logger::Error: 27 | return "E"; 28 | } 29 | 30 | return "?"; 31 | } 32 | 33 | } // namespace 34 | 35 | Logger::Logger(Level level) : 36 | m_level(level), 37 | m_message() 38 | { 39 | // 40 | } 41 | 42 | Logger::~Logger() 43 | { 44 | if (!NeedToLog()) 45 | { 46 | return; 47 | } 48 | 49 | std::lock_guard lock(LogFlushMutex); 50 | fmt::print("[{:%F %T}] [{}] {}\n", std::chrono::system_clock::now(), LevelToString(m_level), m_message.str()); 51 | } 52 | 53 | void Logger::SetMinimumLevel(Level level) 54 | { 55 | MinimumLevel = level; 56 | } 57 | 58 | bool Logger::NeedToLog() const 59 | { 60 | return m_level >= MinimumLevel; 61 | } 62 | -------------------------------------------------------------------------------- /Common/Logger.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | class Logger 6 | { 7 | public: 8 | enum Level 9 | { 10 | Debug, 11 | Info, 12 | Warning, 13 | Error 14 | }; 15 | 16 | public: 17 | Logger(Level level); 18 | ~Logger(); 19 | 20 | template 21 | Logger& operator << (T&& value) 22 | { 23 | if (NeedToLog()) 24 | { 25 | m_message << std::forward(value); 26 | } 27 | 28 | return *this; 29 | } 30 | 31 | static void SetMinimumLevel(Level level); 32 | 33 | private: 34 | bool NeedToLog() const; 35 | 36 | private: 37 | Level const m_level; 38 | std::ostringstream m_message; 39 | }; 40 | -------------------------------------------------------------------------------- /Common/SignalHandler.cpp: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "SignalHandler.h" 18 | 19 | #include 20 | 21 | namespace 22 | { 23 | 24 | volatile std::sig_atomic_t SignalStatus = 0; 25 | 26 | void HandleSignal(int signal) 27 | { 28 | SignalStatus = signal; 29 | } 30 | 31 | } // namespace 32 | 33 | SignalHandler::SignalHandler() : 34 | m_oldIntHandler(std::signal(SIGINT, &HandleSignal)), 35 | m_oldTermHandler(std::signal(SIGTERM, &HandleSignal)) 36 | { 37 | // 38 | } 39 | 40 | SignalHandler::~SignalHandler() 41 | { 42 | std::signal(SIGTERM, m_oldTermHandler); 43 | std::signal(SIGINT, m_oldIntHandler); 44 | } 45 | 46 | bool SignalHandler::IsInterrupted() const 47 | { 48 | return SignalStatus != 0; 49 | } 50 | -------------------------------------------------------------------------------- /Common/SignalHandler.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | class SignalHandler 20 | { 21 | typedef void (*HandlerType)(int); 22 | 23 | public: 24 | SignalHandler(); 25 | ~SignalHandler(); 26 | 27 | SignalHandler(SignalHandler const& other) = delete; 28 | SignalHandler& operator = (SignalHandler const& other) = delete; 29 | 30 | bool IsInterrupted() const; 31 | 32 | private: 33 | HandlerType const m_oldIntHandler; 34 | HandlerType const m_oldTermHandler; 35 | }; 36 | -------------------------------------------------------------------------------- /Common/ThreadSafeIterator.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | #include "IForwardIterator.h" 20 | 21 | #include 22 | 23 | template 24 | class ThreadSafeIterator : public IForwardIterator 25 | { 26 | public: 27 | ThreadSafeIterator(std::unique_ptr> decoratee) : 28 | m_decoratee(std::move(decoratee)), 29 | m_mutex() 30 | { 31 | // 32 | } 33 | 34 | ~ThreadSafeIterator() override = default; 35 | 36 | public: 37 | // IForwardIterator 38 | bool GetNext(ArgsT&... value) override 39 | { 40 | std::lock_guard lock(m_mutex); 41 | return m_decoratee->GetNext(std::forward(value...)); 42 | } 43 | 44 | private: 45 | std::unique_ptr> const m_decoratee; 46 | std::mutex m_mutex; 47 | }; 48 | -------------------------------------------------------------------------------- /Common/Util.cpp: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "Util.h" 18 | 19 | #include "Exception.h" 20 | #include "Logger.h" 21 | 22 | #include 23 | #include 24 | 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | 32 | namespace fs = std::filesystem; 33 | 34 | using namespace std::string_view_literals; 35 | 36 | namespace Util 37 | { 38 | 39 | namespace 40 | { 41 | 42 | std::string FixPathSeparators(std::string_view nativePath) 43 | { 44 | if (nativePath.size() >= 3 && std::isalpha(nativePath[0]) && nativePath[1] == ':' && 45 | (nativePath[2] == '/' || nativePath[2] == '\\')) 46 | { 47 | // Looks like Windows path 48 | auto result = std::string(nativePath); 49 | std::replace(result.begin(), result.end(), '\\', '/'); 50 | return result; 51 | } 52 | 53 | return std::string(nativePath); 54 | } 55 | 56 | } // namespace 57 | 58 | long long StringToInt(std::string const& text) 59 | { 60 | errno = 0; 61 | long long const result = std::strtoll(text.c_str(), nullptr, 10); 62 | if (result == 0 && errno != 0) 63 | { 64 | throw Exception(fmt::format("Unable to convert \"{}\" to integer", text)); 65 | } 66 | 67 | return result; 68 | } 69 | 70 | fs::path GetPath(std::string_view nativePath) 71 | { 72 | std::string const fixedPath = FixPathSeparators(nativePath); 73 | 74 | try 75 | { 76 | return fs::path{std::u8string_view{reinterpret_cast(fixedPath.data()), fixedPath.size()}}; 77 | } 78 | catch (std::exception const&) 79 | { 80 | Logger(Logger::Warning) << "Path " << std::quoted(fixedPath) << " is invalid"; 81 | return fs::path{fixedPath}; 82 | } 83 | } 84 | 85 | std::string CalculateSha1(std::string const& data) 86 | { 87 | return digestpp::sha1().absorb(data).hexdigest(); 88 | } 89 | 90 | std::string BinaryToHex(std::string const& data) 91 | { 92 | static char const* const HexAlphabet = "0123456789abcdef"; 93 | 94 | std::string result; 95 | 96 | for (char const c : data) 97 | { 98 | result += HexAlphabet[(c >> 4) & 0x0f]; 99 | result += HexAlphabet[c & 0x0f]; 100 | } 101 | 102 | return result; 103 | } 104 | 105 | void SortJsonObjectKeys(ojson& object) 106 | { 107 | std::sort(object.object_range().begin(), object.object_range().end(), 108 | [](auto const& lhs, auto const& rhs) { return lhs.key().compare(rhs.key()) < 0; }); 109 | } 110 | 111 | std::string GetEnvironmentVariable(std::string const& name, std::string const& defaultValue) 112 | { 113 | auto const* value = std::getenv(name.c_str()); 114 | return value != nullptr ? value : defaultValue; 115 | } 116 | 117 | bool IsEqualNoCase(std::string_view lhs, std::string_view rhs, std::locale const& locale) 118 | { 119 | return lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin(), 120 | [&locale](char lhsChar, char rhsChar){ return std::tolower(lhsChar, locale) == std::tolower(rhsChar, locale); }); 121 | } 122 | 123 | std::string_view Trim(std::string_view text) 124 | { 125 | static constexpr auto Blanks = " \t\r\n"sv; 126 | 127 | if (auto const pos = text.find_first_not_of(Blanks); pos != std::string_view::npos) 128 | { 129 | text.remove_prefix(pos); 130 | } 131 | 132 | if (auto const pos = text.find_last_not_of(Blanks); pos != std::string_view::npos) 133 | { 134 | text.remove_suffix(text.size() - pos - 1); 135 | } 136 | 137 | return text; 138 | } 139 | 140 | } // namespace Util 141 | -------------------------------------------------------------------------------- /Common/Util.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | #include 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | using jsoncons::ojson; 27 | 28 | namespace Util 29 | { 30 | 31 | long long StringToInt(std::string const& text); 32 | 33 | std::filesystem::path GetPath(std::string_view nativePath); 34 | 35 | std::string CalculateSha1(std::string const& data); 36 | 37 | std::string BinaryToHex(std::string const& data); 38 | 39 | void SortJsonObjectKeys(ojson& object); 40 | 41 | std::string GetEnvironmentVariable(std::string const& name, std::string const& defaultValue); 42 | 43 | bool IsEqualNoCase(std::string_view lhs, std::string_view rhs, std::locale const& locale = {}); 44 | 45 | std::string_view Trim(std::string_view text); 46 | 47 | } // namespace Util 48 | -------------------------------------------------------------------------------- /ImportHelper.cpp: -------------------------------------------------------------------------------- 1 | #include "ImportHelper.h" 2 | 3 | #include "Common/IFileStreamProvider.h" 4 | #include "Common/IForwardIterator.h" 5 | #include "Common/Logger.h" 6 | #include "Common/SignalHandler.h" 7 | #include "Store/DebugTorrentStateIterator.h" 8 | #include "Store/ITorrentStateStore.h" 9 | #include "Torrent/Box.h" 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | namespace fs = std::filesystem; 18 | 19 | ImportHelper::Result::Result() : 20 | SuccessCount(0), 21 | FailCount(0), 22 | SkipCount(0) 23 | { 24 | // 25 | } 26 | 27 | ImportHelper::ImportHelper(ITorrentStateStorePtr sourceStore, fs::path const& sourceDataDir, 28 | ITorrentStateStorePtr targetStore, fs::path const& targetDataDir, IFileStreamProvider& fileStreamProvider, 29 | SignalHandler const& signalHandler) : 30 | m_sourceStore(std::move(sourceStore)), 31 | m_sourceDataDir(sourceDataDir), 32 | m_targetStore(std::move(targetStore)), 33 | m_targetDataDir(targetDataDir), 34 | m_fileStreamProvider(fileStreamProvider), 35 | m_signalHandler(signalHandler) 36 | { 37 | // 38 | } 39 | 40 | ImportHelper::~ImportHelper() = default; 41 | 42 | ImportHelper::Result ImportHelper::Import(unsigned int threadCount) 43 | { 44 | Result result; 45 | 46 | try 47 | { 48 | ITorrentStateIteratorPtr boxes = m_sourceStore->Export(m_sourceDataDir, m_fileStreamProvider); 49 | boxes = std::make_unique(std::move(boxes)); 50 | 51 | std::vector threads; 52 | for (unsigned int i = 0; i < threadCount; ++i) 53 | { 54 | threads.emplace_back(&ImportHelper::ImportImpl, this, std::cref(m_targetDataDir), std::ref(*boxes), 55 | std::ref(result)); 56 | } 57 | 58 | for (auto& thread : threads) 59 | { 60 | thread.join(); 61 | } 62 | } 63 | catch (std::exception const& e) 64 | { 65 | Logger(Logger::Error) << "Error: " << e.what(); 66 | throw; 67 | } 68 | 69 | if (m_signalHandler.IsInterrupted()) 70 | { 71 | throw Exception("Execution has been interrupted"); 72 | } 73 | 74 | Logger(Logger::Info) << "Finished: " << result.SuccessCount << " succeeded, " << result.FailCount << " failed, " << 75 | result.SkipCount << " skipped"; 76 | 77 | return result; 78 | } 79 | 80 | void ImportHelper::ImportImpl(fs::path const& targetDataDir, ITorrentStateIterator& boxes, Result& result) 81 | { 82 | Box box; 83 | while (!m_signalHandler.IsInterrupted() && boxes.GetNext(box)) 84 | { 85 | std::string const prefix = "[" + box.SavePath.filename().string() + "] "; 86 | 87 | try 88 | { 89 | Logger(Logger::Info) << prefix << "Import started"; 90 | m_targetStore->Import(targetDataDir, box, m_fileStreamProvider); 91 | ++result.SuccessCount; 92 | Logger(Logger::Info) << prefix << "Import succeeded"; 93 | } 94 | catch (ImportCancelledException const& e) 95 | { 96 | ++result.SkipCount; 97 | Logger(Logger::Warning) << prefix << "Import skipped: " << e.what(); 98 | } 99 | catch (std::exception const& e) 100 | { 101 | ++result.FailCount; 102 | Logger(Logger::Error) << prefix << "Import failed: " << e.what(); 103 | } 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /ImportHelper.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | template 7 | class IForwardIterator; 8 | 9 | struct Box; 10 | typedef IForwardIterator ITorrentStateIterator; 11 | typedef std::unique_ptr ITorrentStateIteratorPtr; 12 | 13 | class IFileStreamProvider; 14 | 15 | class ITorrentStateStore; 16 | typedef std::unique_ptr ITorrentStateStorePtr; 17 | 18 | class SignalHandler; 19 | 20 | class ImportHelper 21 | { 22 | public: 23 | struct Result 24 | { 25 | std::size_t SuccessCount; 26 | std::size_t FailCount; 27 | std::size_t SkipCount; 28 | 29 | Result(); 30 | }; 31 | 32 | public: 33 | ImportHelper(ITorrentStateStorePtr sourceStore, std::filesystem::path const& sourceDataDir, 34 | ITorrentStateStorePtr targetStore, std::filesystem::path const& targetDataDir, 35 | IFileStreamProvider& fileStreamProvider, SignalHandler const& signalHandler); 36 | ~ImportHelper(); 37 | 38 | Result Import(unsigned int threadCount); 39 | 40 | private: 41 | void ImportImpl(std::filesystem::path const& targetDataDir, ITorrentStateIterator& boxes, Result& result); 42 | 43 | private: 44 | ITorrentStateStorePtr const m_sourceStore; 45 | std::filesystem::path const m_sourceDataDir; 46 | ITorrentStateStorePtr const m_targetStore; 47 | std::filesystem::path const m_targetDataDir; 48 | IFileStreamProvider& m_fileStreamProvider; 49 | SignalHandler const& m_signalHandler; 50 | }; 51 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /MigrationTransaction.cpp: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "MigrationTransaction.h" 18 | 19 | #include "Common/Exception.h" 20 | #include "Common/Logger.h" 21 | 22 | #include 23 | #include 24 | #include 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | 32 | namespace fs = std::filesystem; 33 | 34 | MigrationTransaction::MigrationTransaction(bool writeThrough, bool dryRun) : 35 | m_writeThrough(writeThrough), 36 | m_dryRun(dryRun), 37 | m_transactionId(fmt::format("{:%FT%T%z}", std::chrono::system_clock::now())), 38 | m_safePaths(), 39 | m_safePathsMutex() 40 | { 41 | // 42 | } 43 | 44 | MigrationTransaction::~MigrationTransaction() noexcept(false) 45 | { 46 | if (m_writeThrough || m_dryRun) 47 | { 48 | return; 49 | } 50 | 51 | if (m_safePaths.empty()) 52 | { 53 | return; 54 | } 55 | 56 | Logger(Logger::Info) << "Reverting changes"; 57 | 58 | for (fs::path const& safePath : m_safePaths) 59 | { 60 | if (!fs::exists(safePath) && fs::exists(GetBackupPath(safePath))) 61 | { 62 | fs::rename(GetBackupPath(safePath), safePath); 63 | } 64 | 65 | fs::remove(GetTemporaryPath(safePath)); 66 | } 67 | } 68 | 69 | void MigrationTransaction::Commit() 70 | { 71 | if (m_writeThrough || m_dryRun) 72 | { 73 | return; 74 | } 75 | 76 | Logger(Logger::Info) << "Committing changes"; 77 | 78 | for (fs::path const& safePath : m_safePaths) 79 | { 80 | if (fs::exists(safePath)) 81 | { 82 | fs::rename(safePath, GetBackupPath(safePath)); 83 | } 84 | 85 | fs::rename(GetTemporaryPath(safePath), safePath); 86 | } 87 | 88 | m_safePaths.clear(); 89 | } 90 | 91 | IReadStreamPtr MigrationTransaction::GetReadStream(fs::path const& path) const 92 | { 93 | auto result = std::make_unique(); 94 | result->exceptions(std::ios_base::failbit | std::ios_base::badbit); 95 | 96 | try 97 | { 98 | if (m_safePaths.find(path) != m_safePaths.end()) 99 | { 100 | result->open(GetTemporaryPath(path), std::ios_base::in | std::ios_base::binary); 101 | } 102 | else 103 | { 104 | result->open(path, std::ios_base::in | std::ios_base::binary); 105 | } 106 | } 107 | catch (std::exception const&) 108 | { 109 | throw Exception(fmt::format("Unable to open file for reading: {}", path)); 110 | } 111 | 112 | return result; 113 | } 114 | 115 | IWriteStreamPtr MigrationTransaction::GetWriteStream(fs::path const& path) 116 | { 117 | static std::string const BlackHoleFilename = 118 | #ifdef _WIN32 119 | "nul"; 120 | #else 121 | "/dev/null"; 122 | #endif 123 | 124 | auto result = std::make_unique(); 125 | result->exceptions(std::ios_base::failbit | std::ios_base::badbit); 126 | 127 | try 128 | { 129 | if (m_dryRun) 130 | { 131 | result->open(BlackHoleFilename, std::ios_base::out | std::ios_base::binary); 132 | } 133 | else if (m_writeThrough) 134 | { 135 | result->open(path, std::ios_base::out | std::ios_base::binary | std::ios_base::trunc); 136 | } 137 | else 138 | { 139 | std::lock_guard lock(m_safePathsMutex); 140 | 141 | result->open(GetTemporaryPath(path), std::ios_base::out | std::ios_base::binary | std::ios_base::trunc); 142 | m_safePaths.insert(path); 143 | } 144 | } 145 | catch (std::exception const&) 146 | { 147 | throw Exception(fmt::format("Unable to open file for writing: {}", path)); 148 | } 149 | 150 | return result; 151 | } 152 | 153 | fs::path MigrationTransaction::GetTemporaryPath(fs::path const& path) const 154 | { 155 | fs::path result = path; 156 | result += ".tmp." + m_transactionId; 157 | return result; 158 | } 159 | 160 | fs::path MigrationTransaction::GetBackupPath(fs::path const& path) const 161 | { 162 | fs::path result = path; 163 | result += ".bak." + m_transactionId; 164 | return result; 165 | } 166 | -------------------------------------------------------------------------------- /MigrationTransaction.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | #include "Common/IFileStreamProvider.h" 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | class MigrationTransaction : public IFileStreamProvider 27 | { 28 | public: 29 | MigrationTransaction(bool writeThrough, bool dryRun); 30 | ~MigrationTransaction() noexcept(false) override; 31 | 32 | void Commit(); 33 | 34 | public: 35 | // IFileStreamProvider 36 | IReadStreamPtr GetReadStream(std::filesystem::path const& path) const override; 37 | IWriteStreamPtr GetWriteStream(std::filesystem::path const& path) override; 38 | 39 | private: 40 | std::filesystem::path GetTemporaryPath(std::filesystem::path const& path) const; 41 | std::filesystem::path GetBackupPath(std::filesystem::path const& path) const; 42 | 43 | private: 44 | bool const m_writeThrough; 45 | bool const m_dryRun; 46 | std::string const m_transactionId; 47 | std::set m_safePaths; 48 | std::mutex m_safePathsMutex; 49 | }; 50 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Travis Build Status](https://travis-ci.org/mikedld/bt-migrate.svg?branch=master)](https://travis-ci.org/mikedld/bt-migrate) 2 | [![Coverity Scan Build Status](https://scan.coverity.com/projects/7775/badge.svg)](https://scan.coverity.com/projects/mikedld-bt-migrate) 3 | 4 | About 5 | ========== 6 | 7 | Inspired by [old 'wontfix' Transmission ticket](https://trac.transmissionbt.com/ticket/2642) and couple of mentions on [Transmission IRC channel](irc://irc.freenode.net/transmission), here is a tool to ease migration from one BitTorrent client to another. 8 | 9 | Building 10 | ======== 11 | 12 | You will need [boost](http://www.boost.org/) library installed. 13 | 14 | Clone, generate environment for your favorite build system (we use CMake as abstraction layer), then compile. For example, 15 | 16 | % git clone https://github.com/mikedld/bt-migrate 17 | % cd bt-migrate 18 | % git submodule update --init --force 19 | % mkdir _build 20 | % cd _build 21 | % cmake .. 22 | % cmake --build . 23 | 24 | Running 25 | ======= 26 | 27 | There are a number of command-line arguments you could use: 28 | * `--source ` — BitTorrent client name you're migrating from (see below) 29 | * `--source-dir ` — path to source BitTorrent client data directory 30 | * `--target ` — BitTorrent client name you're migrating to (see below) 31 | * `--target-dir ` — path to target BitTorrent client data directory 32 | 33 | Currently supported clients include (names are case-insensitive): 34 | * "Deluge" (only export) 35 | * "rTorrent" (only export) 36 | * "Transmission" (only import) 37 | * "TransmissionMac" (only import) 38 | * "uTorrent" (only export) 39 | * "uTorrentWeb" (only export) 40 | 41 | Whether only `--source`, only `--source-dir`, or both (same goes for target arguments) are required depends on program ability to guess needed information. If client name allows (by checking various places) to find data directory, then the latter is optional. If path to data directory allows (by analyzing its content) to guess corresponding client name, then the latter is optional. Sometimes it's not possible to guess anything, or name/path guessed don't suit you, so both arguments are required. 42 | 43 | Some other possible arguments include: 44 | * `--no-backup` — do not backup (but simply overwrite) any existing files 45 | * `--dry-run` — do not write anything to disk (useful to check if migration is possible at all) 46 | 47 | Example use: 48 | 49 | % ./BtMigrate --source deluge --target-dir ~/.config/transmission --dry-run 50 | % ./BtMigrate --source rtorrent --source-dir ~/.session --target transmission --target-dir ~/.config/transmission-daemon --dry-run 51 | 52 | For a complete set of arguments, execute: 53 | 54 | % ./BtMigrate --help 55 | 56 | License 57 | ======= 58 | 59 | Code is distributed under the terms of [GNU GPL v3](https://gnu.org/licenses/gpl.html) or later. Feel free to fork, hack and get back to me. 60 | -------------------------------------------------------------------------------- /Store/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_library(BtMigrateStore 2 | DebugTorrentStateIterator.cpp 3 | DebugTorrentStateIterator.h 4 | DelugeStateStore.cpp 5 | DelugeStateStore.h 6 | ITorrentStateStore.cpp 7 | ITorrentStateStore.h 8 | TorrentStateStoreFactory.cpp 9 | TorrentStateStoreFactory.h 10 | TransmissionStateStore.cpp 11 | TransmissionStateStore.h 12 | rTorrentStateStore.cpp 13 | rTorrentStateStore.h 14 | uTorrentStateStore.cpp 15 | uTorrentStateStore.h 16 | uTorrentWebStateStore.cpp 17 | uTorrentWebStateStore.h) 18 | 19 | target_link_libraries(BtMigrateStore 20 | PUBLIC 21 | BtMigrateCodec 22 | BtMigrateCommon 23 | BtMigrateTorrent) 24 | 25 | target_link_libraries(BtMigrateStore 26 | PRIVATE 27 | fmt::fmt 28 | jsoncons 29 | pugixml::pugixml 30 | sqlite_orm::sqlite_orm 31 | Threads::Threads) 32 | -------------------------------------------------------------------------------- /Store/DebugTorrentStateIterator.cpp: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "DebugTorrentStateIterator.h" 18 | 19 | #include "Torrent/Box.h" 20 | 21 | template 22 | StreamT& operator << (StreamT& stream, TorrentInfo const& value) 23 | { 24 | stream << "(" << value.GetInfoHash() << ")"; 25 | return stream; 26 | } 27 | 28 | template 29 | StreamT& operator << (StreamT& stream, Box::LimitInfo const& value) 30 | { 31 | switch (value.Mode) 32 | { 33 | case Box::LimitMode::Inherit: 34 | stream << "Inherit"; 35 | break; 36 | case Box::LimitMode::Enabled: 37 | stream << "Enabled"; 38 | break; 39 | case Box::LimitMode::Disabled: 40 | stream << "Disabled"; 41 | break; 42 | } 43 | 44 | stream << "/" << value.Value; 45 | 46 | return stream; 47 | } 48 | 49 | template 50 | StreamT& operator << (StreamT& stream, Box::FileInfo const& value) 51 | { 52 | stream << 53 | "(" << 54 | std::boolalpha << value.DoNotDownload << "/" << 55 | value.Priority << "/" << 56 | value.Path << 57 | ")"; 58 | 59 | return stream; 60 | } 61 | 62 | template 63 | StreamT& operator << (StreamT& stream, std::vector const& value) 64 | { 65 | stream << '['; 66 | 67 | bool first = true; 68 | for (T const& x : value) 69 | { 70 | if (!first) 71 | { 72 | stream << ", "; 73 | } 74 | 75 | stream << x; 76 | first = false; 77 | } 78 | 79 | stream << ']'; 80 | return stream; 81 | } 82 | 83 | template 84 | StreamT& operator << (StreamT& stream, std::vector const& value) 85 | { 86 | for (bool const x : value) 87 | { 88 | stream << (x ? '#' : '-'); 89 | } 90 | 91 | return stream; 92 | } 93 | 94 | // Including after operator declarations so that lookup works 95 | #include "Common/Logger.h" 96 | 97 | DebugTorrentStateIterator::DebugTorrentStateIterator(ITorrentStateIteratorPtr decoratee) : 98 | m_decoratee(std::move(decoratee)) 99 | { 100 | // 101 | } 102 | 103 | DebugTorrentStateIterator::~DebugTorrentStateIterator() = default; 104 | 105 | bool DebugTorrentStateIterator::GetNext(Box& nextBox) 106 | { 107 | if (!m_decoratee->GetNext(nextBox)) 108 | { 109 | return false; 110 | } 111 | 112 | Logger(Logger::Debug) << 113 | "Torrent=" << nextBox.Torrent << " " 114 | "AddedAt=" << nextBox.AddedAt << " " 115 | "CompletedAt=" << nextBox.CompletedAt << " " 116 | "IsPaused=" << std::boolalpha << nextBox.IsPaused << " " 117 | "DownloadedSize=" << nextBox.DownloadedSize << " " 118 | "UploadedSize=" << nextBox.UploadedSize << " " 119 | "CorruptedSize=" << nextBox.CorruptedSize << " " 120 | "SavePath=" << nextBox.SavePath << " " 121 | "BlockSize=" << nextBox.BlockSize << " " 122 | "RatioLimit=" << nextBox.RatioLimit << " " 123 | "DownloadSpeedLimit=" << nextBox.DownloadSpeedLimit << " " 124 | "UploadSpeedLimit=" << nextBox.UploadSpeedLimit << " " 125 | "Files<" << nextBox.Files.size() << ">=" << nextBox.Files << " " 126 | "ValidBlocks<" << nextBox.ValidBlocks.size() << ">=" << nextBox.ValidBlocks << " " 127 | "Trackers<" << nextBox.Trackers.size() << ">=" << nextBox.Trackers; 128 | 129 | return true; 130 | } 131 | -------------------------------------------------------------------------------- /Store/DebugTorrentStateIterator.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | #include "ITorrentStateStore.h" 20 | 21 | #include "Common/IForwardIterator.h" 22 | 23 | class DebugTorrentStateIterator : public ITorrentStateIterator 24 | { 25 | public: 26 | DebugTorrentStateIterator(ITorrentStateIteratorPtr decoratee); 27 | ~DebugTorrentStateIterator() override; 28 | 29 | public: 30 | // ITorrentStateIterator 31 | bool GetNext(Box& nextBox) override; 32 | 33 | private: 34 | ITorrentStateIteratorPtr const m_decoratee; 35 | }; 36 | -------------------------------------------------------------------------------- /Store/DelugeStateStore.cpp: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "DelugeStateStore.h" 18 | 19 | #include "Codec/BencodeCodec.h" 20 | #include "Codec/PickleCodec.h" 21 | #include "Common/Exception.h" 22 | #include "Common/IFileStreamProvider.h" 23 | #include "Common/IForwardIterator.h" 24 | #include "Common/Logger.h" 25 | #include "Common/Util.h" 26 | #include "Torrent/Box.h" 27 | #include "Torrent/BoxHelper.h" 28 | 29 | #include 30 | #include 31 | 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | 39 | namespace fs = std::filesystem; 40 | 41 | namespace 42 | { 43 | namespace Detail 44 | { 45 | 46 | namespace FastResumeField 47 | { 48 | 49 | std::string const AddedTime = "added_time"; 50 | std::string const CompletedTime = "completed_time"; 51 | std::string const MappedFiles = "mapped_files"; 52 | std::string const Pieces = "pieces"; 53 | std::string const TotalDownloaded = "total_downloaded"; 54 | std::string const TotalUploaded = "total_uploaded"; 55 | 56 | } // namespace FastResumeField 57 | 58 | namespace StateField 59 | { 60 | 61 | std::string const Torrents = "torrents"; 62 | 63 | namespace TorrentField 64 | { 65 | 66 | std::string const FilePriorities = "file_priorities"; 67 | std::string const MaxDownloadSpeed = "max_download_speed"; 68 | std::string const MaxUploadSpeed = "max_upload_speed"; 69 | std::string const Paused = "paused"; 70 | std::string const SavePath = "save_path"; 71 | std::string const StopAtRatio = "stop_at_ratio"; 72 | std::string const StopRatio = "stop_ratio"; 73 | std::string const TorrentId = "torrent_id"; 74 | std::string const Trackers = "trackers"; 75 | 76 | namespace TrackerField 77 | { 78 | 79 | std::string const Tier = "tier"; 80 | std::string const Url = "url"; 81 | 82 | } // namespace TrackersField 83 | 84 | } // namespace TorrentField 85 | 86 | } // namespace StateField 87 | 88 | enum Priority 89 | { 90 | DoNotDownloadPriority = 0, 91 | MinPriority = -6, 92 | MaxPriority = 6 93 | }; 94 | 95 | std::string const DataDirName = "deluge"; 96 | std::string const FastResumeFilename = "torrents.fastresume"; 97 | std::string const StateFilename = "torrents.state"; 98 | std::string const TorrentFileExtension = ".torrent"; 99 | 100 | fs::path GetStateDir(fs::path const& dataDir) 101 | { 102 | return dataDir / "state"; 103 | } 104 | 105 | } // namespace Detail 106 | } // namespace 107 | 108 | namespace 109 | { 110 | 111 | Box::LimitInfo FromStoreRatioLimit(ojson const& enabled, ojson const& storeLimit) 112 | { 113 | Box::LimitInfo result; 114 | result.Mode = enabled.as() ? Box::LimitMode::Enabled : Box::LimitMode::Inherit; 115 | result.Value = storeLimit.as(); 116 | return result; 117 | } 118 | 119 | Box::LimitInfo FromStoreSpeedLimit(ojson const& storeLimit) 120 | { 121 | Box::LimitInfo result; 122 | result.Mode = storeLimit.as() > 0 ? Box::LimitMode::Enabled : 123 | (storeLimit.as() == 0 ? Box::LimitMode::Disabled : Box::LimitMode::Inherit); 124 | result.Value = std::max(0, storeLimit.as() * 1000.); 125 | return result; 126 | } 127 | 128 | fs::path GetChangedFilePath(ojson const& mappedFiles, std::size_t index) 129 | { 130 | fs::path result; 131 | 132 | if (!mappedFiles.is_null() && index < mappedFiles.size()) 133 | { 134 | if (const auto maybePath = mappedFiles[index].as(); !maybePath.empty()) 135 | { 136 | fs::path const path = Util::GetPath(maybePath); 137 | fs::path::iterator pathIt = path.begin(); 138 | while (++pathIt != path.end()) 139 | { 140 | result /= *pathIt; 141 | } 142 | } 143 | } 144 | 145 | return result; 146 | } 147 | 148 | class DelugeTorrentStateIterator : public ITorrentStateIterator 149 | { 150 | public: 151 | DelugeTorrentStateIterator(fs::path const& stateDir, ojson&& fastResume, ojson&& state, 152 | IFileStreamProvider const& fileStreamProvider); 153 | 154 | public: 155 | // ITorrentStateIterator 156 | bool GetNext(Box& nextBox) override; 157 | 158 | private: 159 | bool GetNext(fs::path& torrentFilePath, ojson& state, std::string& fastResumeData); 160 | 161 | private: 162 | fs::path const m_stateDir; 163 | ojson const m_fastResume; 164 | ojson const m_state; 165 | IFileStreamProvider const& m_fileStreamProvider; 166 | ojson::const_array_iterator m_stateIt; 167 | ojson::const_array_iterator const m_stateEnd; 168 | std::mutex m_stateItMutex; 169 | BencodeCodec const m_bencoder; 170 | }; 171 | 172 | DelugeTorrentStateIterator::DelugeTorrentStateIterator(fs::path const& stateDir, ojson&& fastResume, ojson&& state, 173 | IFileStreamProvider const& fileStreamProvider) : 174 | m_stateDir(stateDir), 175 | m_fastResume(std::move(fastResume)), 176 | m_state(std::move(state)), 177 | m_fileStreamProvider(fileStreamProvider), 178 | m_stateIt(m_state[Detail::StateField::Torrents].array_range().begin()), 179 | m_stateEnd(m_state[Detail::StateField::Torrents].array_range().end()), 180 | m_stateItMutex(), 181 | m_bencoder() 182 | { 183 | // 184 | } 185 | 186 | bool DelugeTorrentStateIterator::GetNext(Box& nextBox) 187 | { 188 | namespace FRField = Detail::FastResumeField; 189 | namespace STField = Detail::StateField::TorrentField; 190 | 191 | fs::path torrentFilePath; 192 | ojson state; 193 | std::string fastResumeData; 194 | if (!GetNext(torrentFilePath, state, fastResumeData)) 195 | { 196 | return false; 197 | } 198 | 199 | ojson fastResume; 200 | { 201 | std::istringstream stream(fastResumeData, std::ios_base::in | std::ios_base::binary); 202 | m_bencoder.Decode(stream, fastResume); 203 | } 204 | 205 | Box box; 206 | 207 | { 208 | IReadStreamPtr const stream = m_fileStreamProvider.GetReadStream(torrentFilePath); 209 | box.Torrent = TorrentInfo::Decode(*stream, m_bencoder); 210 | 211 | std::string const infoHash = state[STField::TorrentId].as(); 212 | if (!Util::IsEqualNoCase(box.Torrent.GetInfoHash(), infoHash, std::locale::classic())) 213 | { 214 | throw Exception(fmt::format("Info hashes don't match: {} vs. {}", box.Torrent.GetInfoHash(), infoHash)); 215 | } 216 | } 217 | 218 | box.AddedAt = fastResume[FRField::AddedTime].as(); 219 | box.CompletedAt = fastResume[FRField::CompletedTime].as(); 220 | box.IsPaused = state[STField::Paused].as(); 221 | box.DownloadedSize = fastResume[FRField::TotalDownloaded].as(); 222 | box.UploadedSize = fastResume[FRField::TotalUploaded].as(); 223 | box.CorruptedSize = 0; 224 | box.SavePath = Util::GetPath(state[STField::SavePath].as()) / (fastResume.contains(FRField::MappedFiles) ? 225 | *Util::GetPath(fastResume[FRField::MappedFiles][0].as()).begin() : Util::GetPath(box.Torrent.GetName())); 226 | box.BlockSize = box.Torrent.GetPieceSize(); 227 | box.RatioLimit = FromStoreRatioLimit(state[STField::StopAtRatio], state[STField::StopRatio]); 228 | box.DownloadSpeedLimit = FromStoreSpeedLimit(state[STField::MaxDownloadSpeed]); 229 | box.UploadSpeedLimit = FromStoreSpeedLimit(state[STField::MaxUploadSpeed]); 230 | 231 | ojson const& filePriorities = state[STField::FilePriorities]; 232 | ojson const& mappedFiles = fastResume.at_or_null(FRField::MappedFiles); 233 | Logger(Logger::Debug) << "Got " << filePriorities.size() << " file priorities, " << 234 | (mappedFiles.is_null() ? 0 : mappedFiles.size()) << " mapped files"; 235 | 236 | box.Files.reserve(filePriorities.size()); 237 | for (std::size_t i = 0; i < filePriorities.size(); ++i) 238 | { 239 | int const filePriority = filePriorities[i].as(); 240 | fs::path const changedPath = GetChangedFilePath(mappedFiles, i); 241 | fs::path const originalPath = box.Torrent.GetFilePath(i); 242 | 243 | Box::FileInfo file; 244 | file.DoNotDownload = filePriority == Detail::DoNotDownloadPriority; 245 | file.Priority = file.DoNotDownload ? Box::NormalPriority : BoxHelper::Priority::FromStore(filePriority - 1, 246 | Detail::MinPriority, Detail::MaxPriority); 247 | file.Path = changedPath == fs::path() || changedPath == originalPath ? fs::path() : changedPath; 248 | box.Files.push_back(std::move(file)); 249 | } 250 | 251 | std::uint64_t const totalSize = box.Torrent.GetTotalSize(); 252 | std::uint64_t const totalBlockCount = (totalSize + box.BlockSize - 1) / box.BlockSize; 253 | box.ValidBlocks.reserve(totalBlockCount); 254 | for (bool const isPieceValid : fastResume[FRField::Pieces].as()) 255 | { 256 | box.ValidBlocks.push_back(isPieceValid); 257 | } 258 | 259 | for (ojson const& tracker : state[STField::Trackers].array_range()) 260 | { 261 | namespace tf = STField::TrackerField; 262 | 263 | std::size_t const tier = tracker[tf::Tier].as(); 264 | std::string const url = tracker[tf::Url].as(); 265 | 266 | box.Trackers.resize(std::max(box.Trackers.size(), tier + 1)); 267 | box.Trackers[tier].push_back(url); 268 | } 269 | 270 | nextBox = std::move(box); 271 | return true; 272 | } 273 | 274 | bool DelugeTorrentStateIterator::GetNext(fs::path& torrentFilePath, ojson& state, std::string& fastResumeData) 275 | { 276 | namespace STField = Detail::StateField::TorrentField; 277 | 278 | std::lock_guard lock(m_stateItMutex); 279 | 280 | for (; m_stateIt != m_stateEnd; ++m_stateIt) 281 | { 282 | state = *m_stateIt; 283 | 284 | auto const torrentIdIt = state.find(STField::TorrentId); 285 | if (torrentIdIt == state.object_range().end()) 286 | { 287 | Logger(Logger::Warning) << "Torrent ID is missing from state entry #" << 288 | std::distance(m_state[Detail::StateField::Torrents].array_range().begin(), m_stateIt) << ", skipping"; 289 | continue; 290 | } 291 | 292 | std::string const infoHash = state[STField::TorrentId].as(); 293 | 294 | torrentFilePath = m_stateDir / (infoHash + Detail::TorrentFileExtension); 295 | if (!fs::is_regular_file(torrentFilePath)) 296 | { 297 | Logger(Logger::Warning) << "File " << torrentFilePath << " is not a regular file, skipping"; 298 | continue; 299 | } 300 | 301 | auto const resumeIt = m_fastResume.find(infoHash); 302 | if (resumeIt == m_fastResume.object_range().end()) 303 | { 304 | Logger(Logger::Warning) << "Resume info for infohash " << infoHash << " is missing, skipping"; 305 | continue; 306 | } 307 | 308 | fastResumeData = resumeIt->value().as(); 309 | 310 | ++m_stateIt; 311 | return true; 312 | } 313 | 314 | return false; 315 | } 316 | 317 | } // namespace 318 | 319 | DelugeStateStore::DelugeStateStore() = default; 320 | DelugeStateStore::~DelugeStateStore() = default; 321 | 322 | TorrentClient::Enum DelugeStateStore::GetTorrentClient() const 323 | { 324 | return TorrentClient::Deluge; 325 | } 326 | 327 | fs::path DelugeStateStore::GuessDataDir(Intention::Enum intention) const 328 | { 329 | #ifndef _WIN32 330 | 331 | fs::path const homeDir = Util::GetEnvironmentVariable("HOME", {}); 332 | 333 | if (!homeDir.empty() && IsValidDataDir(homeDir / ".config" / Detail::DataDirName, intention)) 334 | { 335 | return homeDir / ".config" / Detail::DataDirName; 336 | } 337 | 338 | #else 339 | 340 | fs::path const appDataDir = Util::GetEnvironmentVariable("APPDATA", {}); 341 | 342 | if (!appDataDir.empty() && IsValidDataDir(appDataDir / Detail::DataDirName, intention)) 343 | { 344 | return appDataDir / Detail::DataDirName; 345 | } 346 | 347 | #endif 348 | 349 | return {}; 350 | } 351 | 352 | bool DelugeStateStore::IsValidDataDir(fs::path const& dataDir, Intention::Enum /*intention*/) const 353 | { 354 | fs::path const stateDir = Detail::GetStateDir(dataDir); 355 | return 356 | fs::is_regular_file(stateDir / Detail::FastResumeFilename) && 357 | fs::is_regular_file(stateDir / Detail::StateFilename); 358 | } 359 | 360 | ITorrentStateIteratorPtr DelugeStateStore::Export(fs::path const& dataDir, IFileStreamProvider const& fileStreamProvider) const 361 | { 362 | fs::path const stateDir = Detail::GetStateDir(dataDir); 363 | 364 | Logger(Logger::Debug) << "[Deluge] Loading " << Detail::FastResumeFilename; 365 | 366 | ojson fastResume; 367 | { 368 | IReadStreamPtr const stream = fileStreamProvider.GetReadStream(stateDir / Detail::FastResumeFilename); 369 | BencodeCodec().Decode(*stream, fastResume); 370 | } 371 | 372 | Logger(Logger::Debug) << "[Deluge] Loading " << Detail::StateFilename; 373 | 374 | ojson state; 375 | { 376 | IReadStreamPtr const stream = fileStreamProvider.GetReadStream(stateDir / Detail::StateFilename); 377 | PickleCodec().Decode(*stream, state); 378 | } 379 | 380 | return std::make_unique(stateDir, std::move(fastResume), std::move(state), fileStreamProvider); 381 | } 382 | 383 | void DelugeStateStore::Import(fs::path const& /*dataDir*/, Box const& /*box*/, 384 | IFileStreamProvider& /*fileStreamProvider*/) const 385 | { 386 | throw NotImplementedException(__func__); 387 | } 388 | -------------------------------------------------------------------------------- /Store/DelugeStateStore.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | #include "ITorrentStateStore.h" 20 | 21 | class DelugeStateStore : public ITorrentStateStore 22 | { 23 | public: 24 | DelugeStateStore(); 25 | ~DelugeStateStore() override; 26 | 27 | public: 28 | // ITorrentStateStore 29 | TorrentClient::Enum GetTorrentClient() const override; 30 | 31 | std::filesystem::path GuessDataDir(Intention::Enum intention) const override; 32 | bool IsValidDataDir(std::filesystem::path const& dataDir, Intention::Enum intention) const override; 33 | 34 | ITorrentStateIteratorPtr Export(std::filesystem::path const& dataDir, 35 | IFileStreamProvider const& fileStreamProvider) const override; 36 | void Import(std::filesystem::path const& dataDir, Box const& box, IFileStreamProvider& fileStreamProvider) const override; 37 | }; 38 | -------------------------------------------------------------------------------- /Store/ITorrentStateStore.cpp: -------------------------------------------------------------------------------- 1 | #include "ITorrentStateStore.h" 2 | 3 | ITorrentStateStore::~ITorrentStateStore() = default; 4 | 5 | ImportCancelledException::~ImportCancelledException() = default; 6 | -------------------------------------------------------------------------------- /Store/ITorrentStateStore.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | #include "Common/Exception.h" 20 | #include "Torrent/Intention.h" 21 | #include "Torrent/TorrentClient.h" 22 | 23 | #include 24 | #include 25 | 26 | template 27 | class IForwardIterator; 28 | 29 | struct Box; 30 | typedef IForwardIterator ITorrentStateIterator; 31 | typedef std::unique_ptr ITorrentStateIteratorPtr; 32 | 33 | class IFileStreamProvider; 34 | 35 | class ITorrentStateStore 36 | { 37 | public: 38 | virtual ~ITorrentStateStore(); 39 | 40 | virtual TorrentClient::Enum GetTorrentClient() const = 0; 41 | 42 | virtual std::filesystem::path GuessDataDir(Intention::Enum intention) const = 0; 43 | virtual bool IsValidDataDir(std::filesystem::path const& dataDir, Intention::Enum intention) const = 0; 44 | 45 | virtual ITorrentStateIteratorPtr Export(std::filesystem::path const& dataDir, 46 | IFileStreamProvider const& fileStreamProvider) const = 0; 47 | virtual void Import(std::filesystem::path const& dataDir, Box const& box, 48 | IFileStreamProvider& fileStreamProvider) const = 0; 49 | }; 50 | 51 | class ImportCancelledException : public Exception 52 | { 53 | public: 54 | using Exception::Exception; 55 | ~ImportCancelledException() override; 56 | }; 57 | -------------------------------------------------------------------------------- /Store/TorrentStateStoreFactory.cpp: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "TorrentStateStoreFactory.h" 18 | 19 | #include "DelugeStateStore.h" 20 | #include "rTorrentStateStore.h" 21 | #include "TransmissionStateStore.h" 22 | #include "uTorrentStateStore.h" 23 | #include "uTorrentWebStateStore.h" 24 | 25 | #include "Common/Exception.h" 26 | 27 | #include 28 | 29 | namespace fs = std::filesystem; 30 | 31 | TorrentStateStoreFactory::TorrentStateStoreFactory() = default; 32 | 33 | ITorrentStateStorePtr TorrentStateStoreFactory::CreateForClient(TorrentClient::Enum client) const 34 | { 35 | switch (client) 36 | { 37 | case TorrentClient::Deluge: 38 | return std::make_unique(); 39 | case TorrentClient::rTorrent: 40 | return std::make_unique(); 41 | case TorrentClient::Transmission: 42 | return std::make_unique(TransmissionStateType::Generic); 43 | case TorrentClient::TransmissionMac: 44 | return std::make_unique(TransmissionStateType::Mac); 45 | case TorrentClient::uTorrent: 46 | return std::make_unique(); 47 | case TorrentClient::uTorrentWeb: 48 | return std::make_unique(); 49 | } 50 | 51 | throw Exception("Unknown torrent client"); 52 | } 53 | 54 | ITorrentStateStorePtr TorrentStateStoreFactory::GuessByDataDir(fs::path const& dataDir, Intention::Enum intention) const 55 | { 56 | ITorrentStateStorePtr result; 57 | for (int client = TorrentClient::FirstClient; client <= TorrentClient::LastClient; ++client) 58 | { 59 | ITorrentStateStorePtr store = CreateForClient(static_cast(client)); 60 | if (store->IsValidDataDir(dataDir, intention)) 61 | { 62 | if (result != nullptr) 63 | { 64 | throw Exception("More than one torrent client matched data directory"); 65 | } 66 | 67 | result = std::move(store); 68 | } 69 | } 70 | 71 | if (result == nullptr) 72 | { 73 | throw Exception("No torrent client matched data directory"); 74 | } 75 | 76 | return result; 77 | } 78 | -------------------------------------------------------------------------------- /Store/TorrentStateStoreFactory.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | #include "Torrent/Intention.h" 20 | #include "Torrent/TorrentClient.h" 21 | 22 | #include 23 | #include 24 | 25 | class ITorrentStateStore; 26 | typedef std::unique_ptr ITorrentStateStorePtr; 27 | 28 | class TorrentStateStoreFactory 29 | { 30 | public: 31 | TorrentStateStoreFactory(); 32 | 33 | ITorrentStateStorePtr CreateForClient(TorrentClient::Enum client) const; 34 | ITorrentStateStorePtr GuessByDataDir(std::filesystem::path const& dataDir, Intention::Enum intention) const; 35 | }; 36 | -------------------------------------------------------------------------------- /Store/TransmissionStateStore.cpp: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "TransmissionStateStore.h" 18 | 19 | #include "Common/Exception.h" 20 | #include "Common/IFileStreamProvider.h" 21 | #include "Common/IForwardIterator.h" 22 | #include "Common/Util.h" 23 | #include "Torrent/Box.h" 24 | #include "Torrent/BoxHelper.h" 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | 39 | namespace fs = std::filesystem; 40 | 41 | namespace 42 | { 43 | namespace Detail 44 | { 45 | 46 | namespace ResumeField 47 | { 48 | 49 | std::string const AddedDate = "added-date"; 50 | std::string const Corrupt = "corrupt"; 51 | std::string const Destination = "destination"; 52 | std::string const Dnd = "dnd"; 53 | std::string const DoneDate = "done-date"; 54 | std::string const Downloaded = "downloaded"; 55 | std::string const Name = "name"; 56 | std::string const Paused = "paused"; 57 | std::string const Priority = "priority"; 58 | std::string const Progress = "progress"; 59 | std::string const RatioLimit = "ratio-limit"; 60 | std::string const SpeedLimitDown = "speed-limit-down"; 61 | std::string const SpeedLimitUp = "speed-limit-up"; 62 | std::string const Uploaded = "uploaded"; 63 | 64 | namespace ProgressField 65 | { 66 | 67 | std::string const Blocks = "blocks"; 68 | std::string const Have = "have"; 69 | std::string const TimeChecked = "time-checked"; 70 | 71 | } // namespace ProgressField 72 | 73 | namespace RatioLimitField 74 | { 75 | 76 | std::string const RatioMode = "ratio-mode"; 77 | std::string const RatioLimit = "ratio-limit"; 78 | 79 | } // namespace RatioLimitField 80 | 81 | namespace SpeedLimitField 82 | { 83 | 84 | std::string const SpeedBps = "speed-Bps"; 85 | std::string const UseGlobalSpeedLimit = "use-global-speed-limit"; 86 | std::string const UseSpeedLimit = "use-speed-limit"; 87 | 88 | } // namespace SpeedLimitField 89 | 90 | } // namespace ResumeField 91 | 92 | enum Priority 93 | { 94 | MinPriority = -1, 95 | MaxPriority = 1 96 | }; 97 | 98 | std::string const CommonDataDirName = "transmission"; 99 | std::string const DaemonDataDirName = "transmission-daemon"; 100 | std::string const MacDataDirName = "Transmission"; 101 | 102 | std::uint32_t const BlockSize = 16 * 1024; 103 | 104 | fs::path GetResumeDir(fs::path const& dataDir, TransmissionStateType stateType) 105 | { 106 | return dataDir / (stateType == TransmissionStateType::Mac ? "Resume" : "resume"); 107 | } 108 | 109 | fs::path GetResumeFilePath(fs::path const& dataDir, std::string const& basename, TransmissionStateType stateType) 110 | { 111 | return GetResumeDir(dataDir, stateType) / (basename + ".resume"); 112 | } 113 | 114 | fs::path GetTorrentsDir(fs::path const& dataDir, TransmissionStateType stateType) 115 | { 116 | return dataDir / (stateType == TransmissionStateType::Mac ? "Torrents" : "torrents"); 117 | } 118 | 119 | fs::path GetTorrentFilePath(fs::path const& dataDir, std::string const& basename, TransmissionStateType stateType) 120 | { 121 | return GetTorrentsDir(dataDir, stateType) / (basename + ".torrent"); 122 | } 123 | 124 | fs::path GetMacTransfersFilePath(fs::path const& dataDir) 125 | { 126 | return dataDir / "Transfers.plist"; 127 | } 128 | 129 | } // namespace Detail 130 | 131 | ojson ToStoreDoNotDownload(std::vector const& files) 132 | { 133 | ojson result = ojson::array(); 134 | for (Box::FileInfo const& file : files) 135 | { 136 | result.push_back(file.DoNotDownload ? 1 : 0); 137 | } 138 | return result; 139 | } 140 | 141 | ojson ToStorePriority(std::vector const& files) 142 | { 143 | ojson result = ojson::array(); 144 | for (Box::FileInfo const& file : files) 145 | { 146 | result.push_back(BoxHelper::Priority::ToStore(file.Priority, Detail::MinPriority, Detail::MaxPriority)); 147 | } 148 | return result; 149 | } 150 | 151 | ojson ToStoreProgress(std::vector const& validBlocks, std::uint32_t blockSize, std::uint64_t totalSize, 152 | std::size_t fileCount) 153 | { 154 | namespace RPField = Detail::ResumeField::ProgressField; 155 | 156 | std::size_t const validBlockCount = std::count(validBlocks.begin(), validBlocks.end(), true); 157 | 158 | ojson result = ojson::object(); 159 | if (validBlockCount == validBlocks.size()) 160 | { 161 | result[RPField::Blocks] = "all"; 162 | result[RPField::Have] = "all"; 163 | } 164 | else if (validBlockCount == 0) 165 | { 166 | result[RPField::Blocks] = "none"; 167 | } 168 | else 169 | { 170 | std::uint32_t const trBlocksPerBlock = blockSize / Detail::BlockSize; 171 | 172 | std::string trBlocks; 173 | trBlocks.reserve((validBlocks.size() * trBlocksPerBlock + 7) / 8); 174 | 175 | std::uint8_t blockPack = 0; 176 | std::int8_t blockPackShift = 7; 177 | for (bool const isValidBlock : validBlocks) 178 | { 179 | for (std::uint32_t i = 0; i < trBlocksPerBlock; ++i) 180 | { 181 | blockPack |= (isValidBlock ? 1 : 0) << blockPackShift; 182 | if (--blockPackShift < 0) 183 | { 184 | trBlocks += static_cast(blockPack); 185 | blockPack = 0; 186 | blockPackShift = 7; 187 | } 188 | } 189 | } 190 | 191 | if (blockPackShift < 7) 192 | { 193 | trBlocks += static_cast(blockPack); 194 | } 195 | 196 | trBlocks.resize(((totalSize + Detail::BlockSize - 1) / Detail::BlockSize + 7) / 8); 197 | 198 | result[RPField::Blocks] = trBlocks; 199 | } 200 | 201 | std::int64_t const timeChecked = std::time(nullptr); 202 | result[RPField::TimeChecked] = ojson::array(); 203 | for (std::size_t i = 0; i < fileCount; ++i) 204 | { 205 | result[RPField::TimeChecked].push_back(timeChecked); 206 | } 207 | 208 | return result; 209 | } 210 | 211 | ojson ToStoreRatioLimit(Box::LimitInfo const& boxLimit) 212 | { 213 | namespace RRLField = Detail::ResumeField::RatioLimitField; 214 | 215 | ojson result = ojson::object(); 216 | result[RRLField::RatioMode] = boxLimit.Mode == Box::LimitMode::Inherit ? 0 : 217 | (boxLimit.Mode == Box::LimitMode::Enabled ? 1 : 2); 218 | result[RRLField::RatioLimit] = fmt::format("{:.06f}", boxLimit.Value); 219 | return result; 220 | } 221 | 222 | ojson ToStoreSpeedLimit(Box::LimitInfo const& boxLimit) 223 | { 224 | namespace RSLField = Detail::ResumeField::SpeedLimitField; 225 | 226 | ojson result = ojson::object(); 227 | result[RSLField::SpeedBps] = static_cast(boxLimit.Value); 228 | result[RSLField::UseGlobalSpeedLimit] = boxLimit.Mode != Box::LimitMode::Disabled ? 1 : 0; 229 | result[RSLField::UseSpeedLimit] = boxLimit.Mode == Box::LimitMode::Enabled ? 1 : 0; 230 | return result; 231 | } 232 | 233 | std::tuple CreateMacPropertyList() 234 | { 235 | pugi::xml_document doc; 236 | 237 | auto xmlDecl = doc.append_child(pugi::node_declaration); 238 | xmlDecl.append_attribute("version") = "1.0"; 239 | xmlDecl.append_attribute("encoding") = "UTF-8"; 240 | 241 | auto docType = doc.append_child(pugi::node_doctype); 242 | docType.set_value(R"(plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd")"); 243 | 244 | auto plist = doc.append_child("plist"); 245 | plist.append_attribute("version") = "1.0"; 246 | 247 | return {std::move(doc), std::move(plist)}; 248 | } 249 | 250 | void ToMacStoreTransfer(Box const& box, fs::path const& torrentFilePath, pugi::xml_node& transfer) 251 | { 252 | transfer.append_child("key").text() = "Active"; 253 | transfer.append_child(box.IsPaused ? "false" : "true"); 254 | 255 | transfer.append_child("key").text() = "GroupValue"; 256 | transfer.append_child("integer").text() = "-1"; 257 | 258 | transfer.append_child("key").text() = "InternalTorrentPath"; 259 | transfer.append_child("string").text() = torrentFilePath.string().c_str(); 260 | 261 | transfer.append_child("key").text() = "RemoveWhenFinishedSeeding"; 262 | transfer.append_child("false"); 263 | 264 | transfer.append_child("key").text() = "TorrentHash"; 265 | transfer.append_child("string").text() = box.Torrent.GetInfoHash().c_str(); 266 | 267 | transfer.append_child("key").text() = "WaitToStart"; 268 | transfer.append_child("false"); 269 | } 270 | 271 | } // namespace 272 | 273 | TransmissionStateStore::TransmissionStateStore(TransmissionStateType stateType) : 274 | m_stateType(stateType), 275 | m_bencoder(), 276 | m_tranfersPlistMutex() 277 | { 278 | // 279 | } 280 | 281 | TransmissionStateStore::~TransmissionStateStore() = default; 282 | 283 | TorrentClient::Enum TransmissionStateStore::GetTorrentClient() const 284 | { 285 | return TorrentClient::Transmission; 286 | } 287 | 288 | fs::path TransmissionStateStore::GuessDataDir([[maybe_unused]] Intention::Enum intention) const 289 | { 290 | #if !defined(_WIN32) 291 | 292 | fs::path const homeDir = Util::GetEnvironmentVariable("HOME", {}); 293 | if (homeDir.empty()) 294 | { 295 | return {}; 296 | } 297 | 298 | #if defined(__APPLE__) 299 | 300 | fs::path const appSupportDir = homeDir / "Library" / "Application Support"; 301 | 302 | fs::path const macDataDir = appSupportDir / Detail::MacDataDirName; 303 | if (!homeDir.empty() && IsValidDataDir(macDataDir, intention)) 304 | { 305 | return macDataDir; 306 | } 307 | 308 | #endif 309 | 310 | fs::path const xdgConfigHome = Util::GetEnvironmentVariable("XDG_CONFIG_HOME", {}); 311 | fs::path const xdgConfigDir = !xdgConfigHome.empty() ? xdgConfigHome : homeDir / ".config"; 312 | 313 | fs::path const commonDataDir = xdgConfigDir / Detail::CommonDataDirName; 314 | if (IsValidDataDir(commonDataDir, intention)) 315 | { 316 | return commonDataDir; 317 | } 318 | 319 | fs::path const daemonDataDir = xdgConfigDir / Detail::DaemonDataDirName; 320 | if (IsValidDataDir(daemonDataDir, intention)) 321 | { 322 | return daemonDataDir; 323 | } 324 | 325 | #endif 326 | 327 | return {}; 328 | } 329 | 330 | bool TransmissionStateStore::IsValidDataDir(fs::path const& dataDir, Intention::Enum intention) const 331 | { 332 | if (intention == Intention::Import) 333 | { 334 | return fs::is_directory(dataDir); 335 | } 336 | 337 | return 338 | fs::is_directory(Detail::GetResumeDir(dataDir, m_stateType)) && 339 | fs::is_directory(Detail::GetTorrentsDir(dataDir, m_stateType)); 340 | } 341 | 342 | ITorrentStateIteratorPtr TransmissionStateStore::Export(fs::path const& /*dataDir*/, 343 | IFileStreamProvider const& /*fileStreamProvider*/) const 344 | { 345 | throw NotImplementedException(__func__); 346 | } 347 | 348 | void TransmissionStateStore::Import(fs::path const& dataDir, Box const& box, IFileStreamProvider& fileStreamProvider) const 349 | { 350 | namespace RField = Detail::ResumeField; 351 | 352 | if (box.BlockSize % Detail::BlockSize != 0) 353 | { 354 | // See trac #4005. 355 | throw ImportCancelledException(fmt::format("Transmission does not support torrents with piece length not multiple of two: {}", 356 | box.BlockSize)); 357 | } 358 | 359 | for (Box::FileInfo const& file : box.Files) 360 | { 361 | if (!file.Path.is_relative()) 362 | { 363 | throw ImportCancelledException(fmt::format("Transmission does not support moving files outside of download directory: {}", 364 | file.Path)); 365 | } 366 | } 367 | 368 | ojson resume = ojson::object(); 369 | 370 | //resume["activity-date"] = 0; 371 | resume[RField::AddedDate] = static_cast(box.AddedAt); 372 | //resume["bandwidth-priority"] = 0; 373 | resume[RField::Corrupt] = box.CorruptedSize; 374 | resume[RField::Destination] = box.SavePath.parent_path().string(); 375 | resume[RField::Dnd] = ToStoreDoNotDownload(box.Files); 376 | resume[RField::DoneDate] = static_cast(box.CompletedAt); 377 | resume[RField::Downloaded] = box.DownloadedSize; 378 | //resume["downloading-time-seconds"] = 0; 379 | //resume["idle-limit"] = ojson::object(); 380 | //resume["max-peers"] = 5; 381 | resume[RField::Name] = box.SavePath.filename().string(); 382 | resume[RField::Paused] = box.IsPaused ? 1 : 0; 383 | //resume["peers2"] = ""; 384 | resume[RField::Priority] = ToStorePriority(box.Files); 385 | resume[RField::Progress] = ToStoreProgress(box.ValidBlocks, box.BlockSize, box.Torrent.GetTotalSize(), box.Files.size()); 386 | resume[RField::RatioLimit] = ToStoreRatioLimit(box.RatioLimit); 387 | //resume["seeding-time-seconds"] = 0; 388 | resume[RField::SpeedLimitDown] = ToStoreSpeedLimit(box.DownloadSpeedLimit); 389 | resume[RField::SpeedLimitUp] = ToStoreSpeedLimit(box.UploadSpeedLimit); 390 | resume[RField::Uploaded] = box.UploadedSize; 391 | 392 | Util::SortJsonObjectKeys(resume); 393 | 394 | TorrentInfo torrent = box.Torrent; 395 | torrent.SetTrackers(box.Trackers); 396 | 397 | std::string const baseName = Util::GetEnvironmentVariable("BT_MIGRATE_TRANSMISSION_2_9X", {}).empty() ? 398 | torrent.GetInfoHash() : resume[RField::Name].as_string() + '.' + torrent.GetInfoHash().substr(0, 16); 399 | 400 | fs::path const torrentFilePath = Detail::GetTorrentFilePath(dataDir, baseName, m_stateType); 401 | fs::create_directories(torrentFilePath.parent_path()); 402 | 403 | fs::path const resumeFilePath = Detail::GetResumeFilePath(dataDir, baseName, m_stateType); 404 | fs::create_directories(resumeFilePath.parent_path()); 405 | 406 | if (m_stateType == TransmissionStateType::Mac) 407 | { 408 | fs::path const transfersPlistPath = Detail::GetMacTransfersFilePath(dataDir); 409 | 410 | pugi::xml_document plistDoc; 411 | pugi::xml_node plistNode; 412 | pugi::xml_node arrayNode; 413 | 414 | // Avoid concurrent access to Transfers.plist, could lead to file corruption 415 | std::lock_guard lock(m_tranfersPlistMutex); 416 | 417 | try 418 | { 419 | IReadStreamPtr const readStream = fileStreamProvider.GetReadStream(transfersPlistPath); 420 | plistDoc.load(*readStream, pugi::parse_default | pugi::parse_declaration | pugi::parse_doctype); 421 | plistNode = plistDoc.child("plist"); 422 | arrayNode = plistNode.child("array"); 423 | } 424 | catch (Exception const&) 425 | { 426 | } 427 | 428 | if (arrayNode.empty()) 429 | { 430 | std::tie(plistDoc, plistNode) = CreateMacPropertyList(); 431 | arrayNode = plistNode.append_child("array"); 432 | } 433 | 434 | pugi::xml_node dictNode = arrayNode.append_child("dict"); 435 | ToMacStoreTransfer(box, torrentFilePath, dictNode); 436 | 437 | IWriteStreamPtr const writeStream = fileStreamProvider.GetWriteStream(transfersPlistPath); 438 | plistDoc.save(*writeStream); 439 | } 440 | 441 | { 442 | IWriteStreamPtr const stream = fileStreamProvider.GetWriteStream(torrentFilePath); 443 | torrent.Encode(*stream, m_bencoder); 444 | } 445 | 446 | { 447 | IWriteStreamPtr const stream = fileStreamProvider.GetWriteStream(resumeFilePath); 448 | m_bencoder.Encode(*stream, resume); 449 | } 450 | } 451 | -------------------------------------------------------------------------------- /Store/TransmissionStateStore.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | #include "ITorrentStateStore.h" 20 | 21 | #include "Codec/BencodeCodec.h" 22 | 23 | #include 24 | 25 | enum class TransmissionStateType 26 | { 27 | Generic, 28 | Mac 29 | }; 30 | 31 | class TransmissionStateStore : public ITorrentStateStore 32 | { 33 | public: 34 | explicit TransmissionStateStore(TransmissionStateType stateType); 35 | ~TransmissionStateStore() override; 36 | 37 | public: 38 | // ITorrentStateStore 39 | TorrentClient::Enum GetTorrentClient() const override; 40 | 41 | std::filesystem::path GuessDataDir(Intention::Enum intention) const override; 42 | bool IsValidDataDir(std::filesystem::path const& dataDir, Intention::Enum intention) const override; 43 | 44 | ITorrentStateIteratorPtr Export(std::filesystem::path const& dataDir, 45 | IFileStreamProvider const& fileStreamProvider) const override; 46 | void Import(std::filesystem::path const& dataDir, Box const& box, IFileStreamProvider& fileStreamProvider) const override; 47 | 48 | private: 49 | TransmissionStateType const m_stateType; 50 | BencodeCodec const m_bencoder; 51 | std::mutex mutable m_tranfersPlistMutex; 52 | }; 53 | -------------------------------------------------------------------------------- /Store/rTorrentStateStore.cpp: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "rTorrentStateStore.h" 18 | 19 | #include "Codec/BencodeCodec.h" 20 | #include "Common/Exception.h" 21 | #include "Common/IFileStreamProvider.h" 22 | #include "Common/IForwardIterator.h" 23 | #include "Common/Logger.h" 24 | #include "Common/Util.h" 25 | #include "Torrent/Box.h" 26 | #include "Torrent/BoxHelper.h" 27 | 28 | #include 29 | #include 30 | 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | 38 | namespace fs = std::filesystem; 39 | 40 | using namespace std::string_view_literals; 41 | 42 | namespace 43 | { 44 | namespace Detail 45 | { 46 | 47 | namespace ResumeField 48 | { 49 | 50 | std::string const Bitfield = "bitfield"; 51 | std::string const Files = "files"; 52 | std::string const Trackers = "trackers"; 53 | 54 | namespace FileField 55 | { 56 | 57 | std::string const Priority = "priority"; 58 | 59 | } // namespace FileField 60 | 61 | namespace TrackerField 62 | { 63 | 64 | std::string const Enabled = "enabled"; 65 | 66 | } // namespace TrackerField 67 | 68 | } // namespace ResumeField 69 | 70 | namespace StateField 71 | { 72 | 73 | std::string const Directory = "directory"; 74 | std::string const Priority = "priority"; 75 | std::string const TimestampFinished = "timestamp.finished"; 76 | std::string const TimestampStarted = "timestamp.started"; 77 | std::string const TotalUploaded = "total_uploaded"; 78 | 79 | } // namespace StateField 80 | 81 | enum Priority 82 | { 83 | DoNotDownloadPriority = 0, 84 | MinPriority = -1, 85 | MaxPriority = 1 86 | }; 87 | 88 | std::string const ConfigFilename = ".rtorrent.rc"; 89 | std::string const StateFileExtension = ".rtorrent"; 90 | std::string const LibTorrentStateFileExtension = ".libtorrent_resume"; 91 | 92 | } // namespace Detail 93 | } // namespace 94 | 95 | namespace 96 | { 97 | 98 | class rTorrentTorrentStateIterator : public ITorrentStateIterator 99 | { 100 | public: 101 | rTorrentTorrentStateIterator(fs::path const& dataDir, IFileStreamProvider const& fileStreamProvider); 102 | 103 | public: 104 | // ITorrentStateIterator 105 | bool GetNext(Box& nextBox) override; 106 | 107 | private: 108 | bool GetNext(fs::path& stateFilePath, fs::path& torrentFilePath, fs::path& libTorrentStateFilePath); 109 | 110 | private: 111 | fs::path const m_dataDir; 112 | IFileStreamProvider const& m_fileStreamProvider; 113 | fs::directory_iterator m_directoryIt; 114 | fs::directory_iterator const m_directoryEnd; 115 | std::mutex m_directoryItMutex; 116 | BencodeCodec const m_bencoder; 117 | }; 118 | 119 | 120 | rTorrentTorrentStateIterator::rTorrentTorrentStateIterator(fs::path const& dataDir, IFileStreamProvider const& fileStreamProvider) : 121 | m_dataDir(dataDir), 122 | m_fileStreamProvider(fileStreamProvider), 123 | m_directoryIt(m_dataDir), 124 | m_directoryEnd(), 125 | m_directoryItMutex(), 126 | m_bencoder() 127 | { 128 | // 129 | } 130 | 131 | bool rTorrentTorrentStateIterator::GetNext(Box& nextBox) 132 | { 133 | namespace RField = Detail::ResumeField; 134 | namespace SField = Detail::StateField; 135 | 136 | fs::path stateFilePath; 137 | fs::path torrentFilePath; 138 | fs::path libTorrentStateFilePath; 139 | if (!GetNext(stateFilePath, torrentFilePath, libTorrentStateFilePath)) 140 | { 141 | return false; 142 | } 143 | 144 | Box box; 145 | 146 | { 147 | IReadStreamPtr const stream = m_fileStreamProvider.GetReadStream(torrentFilePath); 148 | box.Torrent = TorrentInfo::Decode(*stream, m_bencoder); 149 | 150 | std::string const infoHash = torrentFilePath.stem().string(); 151 | if (!Util::IsEqualNoCase(box.Torrent.GetInfoHash(), infoHash, std::locale::classic())) 152 | { 153 | throw Exception(fmt::format("Info hashes don't match: {} vs. {}", box.Torrent.GetInfoHash(), infoHash)); 154 | } 155 | } 156 | 157 | ojson state; 158 | { 159 | IReadStreamPtr const stream = m_fileStreamProvider.GetReadStream(stateFilePath); 160 | m_bencoder.Decode(*stream, state); 161 | } 162 | 163 | ojson resume; 164 | { 165 | IReadStreamPtr const stream = m_fileStreamProvider.GetReadStream(libTorrentStateFilePath); 166 | m_bencoder.Decode(*stream, resume); 167 | } 168 | 169 | box.AddedAt = state[SField::TimestampStarted].as(); 170 | box.CompletedAt = state[SField::TimestampFinished].as(); 171 | box.IsPaused = state[SField::Priority].as() == 0; 172 | box.UploadedSize = state[SField::TotalUploaded].as(); 173 | box.SavePath = Util::GetPath(state[SField::Directory].as()); 174 | box.BlockSize = box.Torrent.GetPieceSize(); 175 | 176 | box.Files.reserve(resume[RField::Files].size()); 177 | for (ojson const& file : resume[RField::Files].array_range()) 178 | { 179 | namespace ff = RField::FileField; 180 | 181 | int const filePriority = file[ff::Priority].as(); 182 | 183 | Box::FileInfo boxFile; 184 | boxFile.DoNotDownload = filePriority == Detail::DoNotDownloadPriority; 185 | boxFile.Priority = boxFile.DoNotDownload ? Box::NormalPriority : BoxHelper::Priority::FromStore(filePriority - 1, 186 | Detail::MinPriority, Detail::MaxPriority); 187 | box.Files.push_back(std::move(boxFile)); 188 | } 189 | 190 | std::uint64_t const totalSize = box.Torrent.GetTotalSize(); 191 | std::uint64_t const totalBlockCount = (totalSize + box.BlockSize - 1) / box.BlockSize; 192 | box.ValidBlocks.reserve(totalBlockCount + 8); 193 | for (unsigned char const c : resume[RField::Bitfield].as()) 194 | { 195 | for (int i = 7; i >= 0; --i) 196 | { 197 | bool const isPieceValid = (c & (1 << i)) != 0; 198 | box.ValidBlocks.push_back(isPieceValid); 199 | } 200 | } 201 | 202 | box.ValidBlocks.resize(totalBlockCount); 203 | 204 | for (auto const& tracker : resume[RField::Trackers].object_range()) 205 | { 206 | namespace tf = RField::TrackerField; 207 | 208 | std::string const url{tracker.key()}; 209 | if (url == "dht://") 210 | { 211 | continue; 212 | } 213 | 214 | ojson const& params = tracker.value(); 215 | if (params[tf::Enabled].as() == 1) 216 | { 217 | box.Trackers.push_back({url}); 218 | } 219 | } 220 | 221 | nextBox = std::move(box); 222 | return true; 223 | } 224 | 225 | bool rTorrentTorrentStateIterator::GetNext(fs::path& stateFilePath, fs::path& torrentFilePath, 226 | fs::path& libTorrentStateFilePath) 227 | { 228 | std::lock_guard lock(m_directoryItMutex); 229 | 230 | for (; m_directoryIt != m_directoryEnd; ++m_directoryIt) 231 | { 232 | stateFilePath = m_directoryIt->path(); 233 | if (stateFilePath.extension().string() != Detail::StateFileExtension) 234 | { 235 | continue; 236 | } 237 | 238 | if (!fs::is_regular_file(*m_directoryIt)) 239 | { 240 | Logger(Logger::Warning) << "File " << stateFilePath << " is not a regular file, skipping"; 241 | continue; 242 | } 243 | 244 | torrentFilePath = stateFilePath; 245 | torrentFilePath.replace_extension(fs::path()); 246 | if (!fs::is_regular_file(torrentFilePath)) 247 | { 248 | Logger(Logger::Warning) << "File " << torrentFilePath << " is not a regular file, skipping"; 249 | continue; 250 | } 251 | 252 | libTorrentStateFilePath = stateFilePath; 253 | libTorrentStateFilePath.replace_extension(Detail::LibTorrentStateFileExtension); 254 | if (!fs::is_regular_file(libTorrentStateFilePath)) 255 | { 256 | Logger(Logger::Warning) << "File " << libTorrentStateFilePath << " is not a regular file, skipping"; 257 | continue; 258 | } 259 | 260 | ++m_directoryIt; 261 | return true; 262 | } 263 | 264 | return false; 265 | } 266 | 267 | } // namespace 268 | 269 | rTorrentStateStore::rTorrentStateStore() = default; 270 | rTorrentStateStore::~rTorrentStateStore() = default; 271 | 272 | TorrentClient::Enum rTorrentStateStore::GetTorrentClient() const 273 | { 274 | return TorrentClient::rTorrent; 275 | } 276 | 277 | fs::path rTorrentStateStore::GuessDataDir([[maybe_unused]] Intention::Enum intention) const 278 | { 279 | #ifndef _WIN32 280 | 281 | fs::path const homeDir = Util::GetEnvironmentVariable("HOME", {}); 282 | 283 | if (homeDir.empty() || !fs::is_regular_file(homeDir / Detail::ConfigFilename)) 284 | { 285 | return {}; 286 | } 287 | 288 | auto dataDirPath = fs::path(); 289 | 290 | { 291 | auto stream = std::ifstream(); 292 | stream.exceptions(std::ifstream::badbit | std::ifstream::failbit); 293 | stream.open(homeDir / Detail::ConfigFilename); 294 | 295 | auto line = std::string(); 296 | while (std::getline(stream, line)) 297 | { 298 | auto const equalsPos = line.find('='); 299 | if (equalsPos == std::string::npos) 300 | { 301 | continue; 302 | } 303 | 304 | if (auto const key = Util::Trim(std::string_view(line).substr(0, equalsPos)); key != "session"sv) 305 | { 306 | continue; 307 | } 308 | 309 | dataDirPath = Util::GetPath(Util::Trim(std::string_view(line).substr(equalsPos + 1))); 310 | break; 311 | } 312 | } 313 | 314 | if (!dataDirPath.empty() && IsValidDataDir(dataDirPath, intention)) 315 | { 316 | return dataDirPath; 317 | } 318 | 319 | #endif 320 | 321 | return {}; 322 | } 323 | 324 | bool rTorrentStateStore::IsValidDataDir(fs::path const& dataDir, Intention::Enum intention) const 325 | { 326 | if (intention == Intention::Import) 327 | { 328 | return fs::is_directory(dataDir); 329 | } 330 | 331 | for (fs::directory_iterator it(dataDir), end; it != end; ++it) 332 | { 333 | fs::path path = it->path(); 334 | if (path.extension() != Detail::StateFileExtension || !fs::is_regular_file(it->status())) 335 | { 336 | continue; 337 | } 338 | 339 | if (!fs::is_regular_file(path.replace_extension(Detail::LibTorrentStateFileExtension))) 340 | { 341 | continue; 342 | } 343 | 344 | if (!fs::is_regular_file(path.replace_extension(fs::path()))) 345 | { 346 | continue; 347 | } 348 | 349 | return true; 350 | } 351 | 352 | return false; 353 | } 354 | 355 | ITorrentStateIteratorPtr rTorrentStateStore::Export(fs::path const& dataDir, IFileStreamProvider const& fileStreamProvider) const 356 | { 357 | return std::make_unique(dataDir, fileStreamProvider); 358 | } 359 | 360 | void rTorrentStateStore::Import(fs::path const& /*dataDir*/, Box const& /*box*/, 361 | IFileStreamProvider& /*fileStreamProvider*/) const 362 | { 363 | throw NotImplementedException(__func__); 364 | } 365 | -------------------------------------------------------------------------------- /Store/rTorrentStateStore.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | #include "ITorrentStateStore.h" 20 | 21 | class rTorrentStateStore : public ITorrentStateStore 22 | { 23 | public: 24 | rTorrentStateStore(); 25 | ~rTorrentStateStore() override; 26 | 27 | public: 28 | // ITorrentStateStore 29 | TorrentClient::Enum GetTorrentClient() const override; 30 | 31 | std::filesystem::path GuessDataDir(Intention::Enum intention) const override; 32 | bool IsValidDataDir(std::filesystem::path const& dataDir, Intention::Enum intention) const override; 33 | 34 | ITorrentStateIteratorPtr Export(std::filesystem::path const& dataDir, 35 | IFileStreamProvider const& fileStreamProvider) const override; 36 | void Import(std::filesystem::path const& dataDir, Box const& box, IFileStreamProvider& fileStreamProvider) const override; 37 | }; 38 | -------------------------------------------------------------------------------- /Store/uTorrentStateStore.cpp: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "uTorrentStateStore.h" 18 | 19 | #include "Codec/BencodeCodec.h" 20 | #include "Common/Exception.h" 21 | #include "Common/IFileStreamProvider.h" 22 | #include "Common/IForwardIterator.h" 23 | #include "Common/Logger.h" 24 | #include "Common/Util.h" 25 | #include "Torrent/Box.h" 26 | #include "Torrent/BoxHelper.h" 27 | 28 | #include 29 | 30 | #include 31 | #include 32 | #include 33 | 34 | namespace fs = std::filesystem; 35 | 36 | namespace 37 | { 38 | namespace Detail 39 | { 40 | 41 | namespace ResumeField 42 | { 43 | 44 | std::string const AddedOn = "added_on"; 45 | std::string const CompletedOn = "completed_on"; 46 | std::string const Corrupt = "corrupt"; 47 | std::string const Downloaded = "downloaded"; 48 | std::string const DownSpeed = "downspeed"; 49 | std::string const Have = "have"; 50 | std::string const OverrideSeedSettings = "override_seedsettings"; 51 | std::string const Path = "path"; 52 | std::string const Prio = "prio"; 53 | std::string const Started = "started"; 54 | std::string const Targets = "targets"; 55 | std::string const Trackers = "trackers"; 56 | std::string const Uploaded = "uploaded"; 57 | std::string const UpSpeed = "upspeed"; 58 | std::string const WantedRatio = "wanted_ratio"; 59 | 60 | } // namespace ResumeField 61 | 62 | enum Priority 63 | { 64 | DoNotDownloadPriority = 0, 65 | MinPriority = 4, 66 | MaxPriority = 12 67 | }; 68 | 69 | enum TorrentState 70 | { 71 | StoppedState = 0, 72 | StartedState = 2, 73 | PausedState = 3 74 | }; 75 | 76 | std::string const ResumeFilename = "resume.dat"; 77 | std::string const TorrentFileExtension = ".torrent"; 78 | 79 | } // namespace Detail 80 | } // namespace 81 | 82 | namespace 83 | { 84 | 85 | Box::LimitInfo FromStoreRatioLimit(ojson const& enabled, ojson const& storeLimit) 86 | { 87 | Box::LimitInfo result; 88 | result.Mode = enabled.as() != 0 ? Box::LimitMode::Enabled : Box::LimitMode::Inherit; 89 | result.Value = storeLimit.as() / 1000.; 90 | return result; 91 | } 92 | 93 | Box::LimitInfo FromStoreSpeedLimit(ojson const& storeLimit) 94 | { 95 | Box::LimitInfo result; 96 | result.Mode = storeLimit.as() > 0 ? Box::LimitMode::Enabled : Box::LimitMode::Inherit; 97 | result.Value = storeLimit.as(); 98 | return result; 99 | } 100 | 101 | fs::path GetChangedFilePath(ojson const& targets, std::size_t index) 102 | { 103 | fs::path result; 104 | 105 | if (!targets.is_null()) 106 | { 107 | for (ojson const& target : targets.array_range()) 108 | { 109 | if (target[0].as() == index) 110 | { 111 | result = Util::GetPath(target[1].as()); 112 | break; 113 | } 114 | } 115 | } 116 | 117 | return result; 118 | } 119 | 120 | class uTorrentTorrentStateIterator : public ITorrentStateIterator 121 | { 122 | public: 123 | uTorrentTorrentStateIterator(fs::path const& dataDir, ojson&& resume, IFileStreamProvider const& fileStreamProvider); 124 | 125 | public: 126 | // ITorrentStateIterator 127 | bool GetNext(Box& nextBox) override; 128 | 129 | private: 130 | bool GetNext(fs::path& torrentFilePath, ojson& resume); 131 | 132 | private: 133 | fs::path const m_dataDir; 134 | ojson const m_resume; 135 | IFileStreamProvider const& m_fileStreamProvider; 136 | ojson::const_object_iterator m_torrentIt; 137 | ojson::const_object_iterator const m_torrentEnd; 138 | std::mutex m_torrentItMutex; 139 | BencodeCodec const m_bencoder; 140 | }; 141 | 142 | uTorrentTorrentStateIterator::uTorrentTorrentStateIterator(fs::path const& dataDir, ojson&& resume, 143 | IFileStreamProvider const& fileStreamProvider) : 144 | m_dataDir(dataDir), 145 | m_resume(std::move(resume)), 146 | m_fileStreamProvider(fileStreamProvider), 147 | m_torrentIt(m_resume.object_range().begin()), 148 | m_torrentEnd(m_resume.object_range().end()), 149 | m_torrentItMutex(), 150 | m_bencoder() 151 | { 152 | // 153 | } 154 | 155 | bool uTorrentTorrentStateIterator::GetNext(Box& nextBox) 156 | { 157 | namespace RField = Detail::ResumeField; 158 | 159 | fs::path torrentFilePath; 160 | ojson resume; 161 | if (!GetNext(torrentFilePath, resume)) 162 | { 163 | return false; 164 | } 165 | 166 | Box box; 167 | 168 | { 169 | IReadStreamPtr const stream = m_fileStreamProvider.GetReadStream(torrentFilePath); 170 | box.Torrent = TorrentInfo::Decode(*stream, m_bencoder); 171 | } 172 | 173 | box.AddedAt = resume[RField::AddedOn].as(); 174 | box.CompletedAt = resume[RField::CompletedOn].as(); 175 | box.IsPaused = resume[RField::Started].as() == Detail::PausedState || 176 | resume[RField::Started].as() == Detail::StoppedState; 177 | box.DownloadedSize = resume[RField::Downloaded].as(); 178 | box.UploadedSize = resume[RField::Uploaded].as(); 179 | box.CorruptedSize = resume[RField::Corrupt].as(); 180 | box.SavePath = Util::GetPath(resume[RField::Path].as()); 181 | box.BlockSize = box.Torrent.GetPieceSize(); 182 | box.RatioLimit = FromStoreRatioLimit(resume[RField::OverrideSeedSettings], resume[RField::WantedRatio]); 183 | box.DownloadSpeedLimit = FromStoreSpeedLimit(resume[RField::DownSpeed]); 184 | box.UploadSpeedLimit = FromStoreSpeedLimit(resume[RField::UpSpeed]); 185 | 186 | std::string const filePriorities = resume[RField::Prio].as(); 187 | ojson const& targets = resume.at_or_null(RField::Targets); 188 | box.Files.reserve(filePriorities.size()); 189 | for (std::size_t i = 0; i < filePriorities.size(); ++i) 190 | { 191 | int const filePriority = filePriorities[i]; 192 | fs::path const changedPath = GetChangedFilePath(targets, i); 193 | 194 | Box::FileInfo file; 195 | file.DoNotDownload = filePriority == Detail::DoNotDownloadPriority; 196 | file.Priority = file.DoNotDownload ? Box::NormalPriority : BoxHelper::Priority::FromStore(filePriority, 197 | Detail::MinPriority, Detail::MaxPriority); 198 | file.Path = changedPath; 199 | box.Files.push_back(std::move(file)); 200 | } 201 | 202 | std::uint64_t const totalSize = box.Torrent.GetTotalSize(); 203 | std::uint64_t const totalBlockCount = (totalSize + box.BlockSize - 1) / box.BlockSize; 204 | box.ValidBlocks.reserve(totalBlockCount + 8); 205 | for (unsigned char const c : resume[RField::Have].as()) 206 | { 207 | for (int i = 0; i < 8; ++i) 208 | { 209 | bool const isPieceValid = (c & (1 << i)) != 0; 210 | box.ValidBlocks.push_back(isPieceValid); 211 | } 212 | } 213 | 214 | box.ValidBlocks.resize(totalBlockCount); 215 | 216 | for (ojson const& trackerUrl : resume[RField::Trackers].array_range()) 217 | { 218 | box.Trackers.push_back({trackerUrl.as()}); 219 | } 220 | 221 | nextBox = std::move(box); 222 | return true; 223 | } 224 | 225 | bool uTorrentTorrentStateIterator::GetNext(fs::path& torrentFilePath, ojson& resume) 226 | { 227 | std::lock_guard lock(m_torrentItMutex); 228 | 229 | for (; m_torrentIt != m_torrentEnd; ++m_torrentIt) 230 | { 231 | torrentFilePath = m_dataDir / std::string(m_torrentIt->key()); 232 | if (torrentFilePath.extension().string() != Detail::TorrentFileExtension) 233 | { 234 | continue; 235 | } 236 | 237 | if (!fs::is_regular_file(torrentFilePath)) 238 | { 239 | Logger(Logger::Warning) << "File " << torrentFilePath << " is not a regular file, skipping"; 240 | continue; 241 | } 242 | 243 | resume = m_torrentIt->value(); 244 | 245 | ++m_torrentIt; 246 | return true; 247 | } 248 | 249 | return false; 250 | } 251 | 252 | } // namespace 253 | 254 | uTorrentStateStore::uTorrentStateStore() = default; 255 | uTorrentStateStore::~uTorrentStateStore() = default; 256 | 257 | TorrentClient::Enum uTorrentStateStore::GetTorrentClient() const 258 | { 259 | return TorrentClient::uTorrent; 260 | } 261 | 262 | fs::path uTorrentStateStore::GuessDataDir(Intention::Enum /*intention*/) const 263 | { 264 | throw NotImplementedException(__func__); 265 | } 266 | 267 | bool uTorrentStateStore::IsValidDataDir(fs::path const& dataDir, Intention::Enum /*intention*/) const 268 | { 269 | return fs::is_regular_file(dataDir / Detail::ResumeFilename); 270 | } 271 | 272 | ITorrentStateIteratorPtr uTorrentStateStore::Export(fs::path const& dataDir, IFileStreamProvider const& fileStreamProvider) const 273 | { 274 | Logger(Logger::Debug) << "[uTorrent] Loading " << Detail::ResumeFilename; 275 | 276 | ojson resume; 277 | { 278 | IReadStreamPtr const stream = fileStreamProvider.GetReadStream(dataDir / Detail::ResumeFilename); 279 | BencodeCodec().Decode(*stream, resume); 280 | } 281 | 282 | return std::make_unique(dataDir, std::move(resume), fileStreamProvider); 283 | } 284 | 285 | void uTorrentStateStore::Import(fs::path const& /*dataDir*/, Box const& /*box*/, 286 | IFileStreamProvider& /*fileStreamProvider*/) const 287 | { 288 | throw NotImplementedException(__func__); 289 | } 290 | -------------------------------------------------------------------------------- /Store/uTorrentStateStore.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | #include "ITorrentStateStore.h" 20 | 21 | class uTorrentStateStore : public ITorrentStateStore 22 | { 23 | public: 24 | uTorrentStateStore(); 25 | ~uTorrentStateStore() override; 26 | 27 | public: 28 | // ITorrentStateStore 29 | TorrentClient::Enum GetTorrentClient() const override; 30 | 31 | std::filesystem::path GuessDataDir(Intention::Enum intention) const override; 32 | bool IsValidDataDir(std::filesystem::path const& dataDir, Intention::Enum intention) const override; 33 | 34 | ITorrentStateIteratorPtr Export(std::filesystem::path const& dataDir, 35 | IFileStreamProvider const& fileStreamProvider) const override; 36 | void Import(std::filesystem::path const& dataDir, Box const& box, IFileStreamProvider& fileStreamProvider) const override; 37 | }; 38 | -------------------------------------------------------------------------------- /Store/uTorrentWebStateStore.cpp: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2019 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "uTorrentWebStateStore.h" 18 | 19 | #include "Codec/BencodeCodec.h" 20 | #include "Common/Exception.h" 21 | #include "Common/IFileStreamProvider.h" 22 | #include "Common/IForwardIterator.h" 23 | #include "Common/Logger.h" 24 | #include "Common/Util.h" 25 | #include "Torrent/Box.h" 26 | 27 | #include 28 | 29 | #include 30 | 31 | #include 32 | #include 33 | #include 34 | 35 | namespace fs = std::filesystem; 36 | 37 | namespace 38 | { 39 | namespace Detail 40 | { 41 | 42 | struct ResumeInfo 43 | { 44 | std::string InfoHash; 45 | std::vector ResumeData; 46 | std::unique_ptr SavePath; 47 | 48 | ResumeInfo Copy() const 49 | { 50 | return {InfoHash, ResumeData, SavePath != nullptr ? std::make_unique(*SavePath) : nullptr}; 51 | } 52 | }; 53 | 54 | namespace ResumeField 55 | { 56 | 57 | std::string const AddedTime = "added_time"; 58 | std::string const CompletedTime = "completed_time"; 59 | std::string const Info = "info"; 60 | std::string const Paused = "paused"; 61 | std::string const Pieces = "pieces"; 62 | std::string const SavePath = "save_path"; 63 | std::string const TotalDownloaded = "total_downloaded"; 64 | std::string const TotalUploaded = "total_uploaded"; 65 | std::string const Trackers = "trackers"; 66 | std::string const UrlList = "url-list"; 67 | 68 | } // namespace ResumeField 69 | 70 | namespace TorrentField 71 | { 72 | 73 | std::string const Info = "info"; 74 | std::string const UrlList = "url-list"; 75 | 76 | } // namespace TorrentField 77 | 78 | std::string const DataDirName = "uTorrent Web"; 79 | std::string const ResumeFilename = "resume.dat"; 80 | std::string const StoreFilename = "store.dat"; 81 | 82 | } // namespace Detail 83 | } // namespace 84 | 85 | namespace 86 | { 87 | 88 | auto OpenResumeDatabase(fs::path const& path) 89 | { 90 | using namespace sqlite_orm; 91 | 92 | return make_storage(path.string(), 93 | make_table("TORRENTS", 94 | make_column("INFOHASH", &Detail::ResumeInfo::InfoHash, primary_key()), 95 | make_column("RESUME", &Detail::ResumeInfo::ResumeData), 96 | make_column("SAVE_PATH", &Detail::ResumeInfo::SavePath))); 97 | } 98 | 99 | class uTorrentWebTorrentStateIterator : public ITorrentStateIterator 100 | { 101 | using ResumeDatabase = decltype(OpenResumeDatabase({})); 102 | using ResumeInfoEnumerator = std::invoke_result_t), ResumeDatabase>; 103 | using ResumeInfoIterator = std::invoke_result_t; 104 | 105 | public: 106 | uTorrentWebTorrentStateIterator(fs::path const& stateDir, ResumeDatabase&& resumeDb); 107 | 108 | public: 109 | // ITorrentStateIterator 110 | bool GetNext(Box& nextBox) override; 111 | 112 | private: 113 | bool GetNext(Detail::ResumeInfo& resumeInfo); 114 | 115 | private: 116 | fs::path const m_stateDir; 117 | ResumeDatabase m_resumeDb; 118 | ResumeInfoEnumerator m_resumeInfoEnumerator; 119 | ResumeInfoIterator m_resumeInfoIt; 120 | ResumeInfoIterator m_resumeInfoEnd; 121 | std::mutex m_resumeItMutex; 122 | BencodeCodec const m_bencoder; 123 | }; 124 | 125 | uTorrentWebTorrentStateIterator::uTorrentWebTorrentStateIterator(fs::path const& stateDir, ResumeDatabase&& resumeDb) : 126 | m_stateDir(stateDir), 127 | m_resumeDb(resumeDb), 128 | m_resumeInfoEnumerator(m_resumeDb.iterate()), 129 | m_resumeInfoIt(m_resumeInfoEnumerator.begin()), 130 | m_resumeInfoEnd(m_resumeInfoEnumerator.end()), 131 | m_resumeItMutex() 132 | { 133 | // 134 | } 135 | 136 | bool uTorrentWebTorrentStateIterator::GetNext(Box& nextBox) 137 | { 138 | namespace RField = Detail::ResumeField; 139 | namespace TField = Detail::TorrentField; 140 | 141 | Detail::ResumeInfo resumeInfo; 142 | if (!GetNext(resumeInfo)) 143 | { 144 | return false; 145 | } 146 | 147 | ojson resume; 148 | { 149 | std::string resumeData{resumeInfo.ResumeData.begin(), resumeInfo.ResumeData.end()}; 150 | std::istringstream stream(resumeData, std::ios_base::in | std::ios_base::binary); 151 | m_bencoder.Decode(stream, resume); 152 | } 153 | 154 | Box box; 155 | 156 | box.Torrent = ojson{ojson::object{ 157 | {TField::Info, resume[RField::Info]}, 158 | {TField::UrlList, resume.get_value_or>(RField::UrlList, std::vector())} 159 | }}; 160 | 161 | box.AddedAt = resume[RField::AddedTime].as(); 162 | box.CompletedAt = resume[RField::CompletedTime].as(); 163 | box.IsPaused = resume[RField::Paused].as(); 164 | box.DownloadedSize = resume[RField::TotalDownloaded].as(); 165 | box.UploadedSize = resume[RField::TotalUploaded].as(); 166 | box.CorruptedSize = 0; 167 | box.SavePath = Util::GetPath(resume[RField::SavePath].as_string()) / box.Torrent.GetName(); 168 | box.BlockSize = box.Torrent.GetPieceSize(); 169 | 170 | std::uint64_t const totalSize = box.Torrent.GetTotalSize(); 171 | std::uint64_t const totalBlockCount = (totalSize + box.BlockSize - 1) / box.BlockSize; 172 | box.ValidBlocks.reserve(totalBlockCount); 173 | for (bool const isPieceValid : resume[RField::Pieces].as()) 174 | { 175 | box.ValidBlocks.push_back(isPieceValid); 176 | } 177 | 178 | box.Trackers = resume.get_value_or(RField::Trackers, decltype(box.Trackers)()); 179 | 180 | nextBox = std::move(box); 181 | return true; 182 | } 183 | 184 | bool uTorrentWebTorrentStateIterator::GetNext(Detail::ResumeInfo& resumeInfo) 185 | { 186 | std::lock_guard lock(m_resumeItMutex); 187 | 188 | if (m_resumeInfoIt == m_resumeInfoEnd) 189 | { 190 | return false; 191 | } 192 | 193 | resumeInfo = m_resumeInfoIt->Copy(); 194 | 195 | ++m_resumeInfoIt; 196 | return true; 197 | } 198 | 199 | } // namespace 200 | 201 | uTorrentWebStateStore::uTorrentWebStateStore() = default; 202 | uTorrentWebStateStore::~uTorrentWebStateStore() = default; 203 | 204 | TorrentClient::Enum uTorrentWebStateStore::GetTorrentClient() const 205 | { 206 | return TorrentClient::uTorrentWeb; 207 | } 208 | 209 | fs::path uTorrentWebStateStore::GuessDataDir([[maybe_unused]] Intention::Enum intention) const 210 | { 211 | #ifdef _WIN32 212 | 213 | fs::path const appDataDir = Util::GetEnvironmentVariable("APPDATA", {}); 214 | 215 | if (IsValidDataDir(appDataDir / Detail::DataDirName, intention)) 216 | { 217 | return appDataDir / Detail::DataDirName; 218 | } 219 | 220 | #endif 221 | 222 | return {}; 223 | } 224 | 225 | bool uTorrentWebStateStore::IsValidDataDir(fs::path const& dataDir, Intention::Enum /*intention*/) const 226 | { 227 | return 228 | fs::is_regular_file(dataDir / Detail::ResumeFilename) && 229 | fs::is_regular_file(dataDir / Detail::StoreFilename); 230 | } 231 | 232 | ITorrentStateIteratorPtr uTorrentWebStateStore::Export(fs::path const& dataDir, IFileStreamProvider const& /*fileStreamProvider*/) const 233 | { 234 | Logger(Logger::Debug) << "[uTorrentWeb] Loading " << Detail::ResumeFilename; 235 | 236 | auto resumeDb = OpenResumeDatabase(dataDir / Detail::ResumeFilename); 237 | 238 | return std::make_unique(dataDir, std::move(resumeDb)); 239 | } 240 | 241 | void uTorrentWebStateStore::Import(fs::path const& /*dataDir*/, Box const& /*box*/, 242 | IFileStreamProvider& /*fileStreamProvider*/) const 243 | { 244 | throw NotImplementedException(__func__); 245 | } 246 | -------------------------------------------------------------------------------- /Store/uTorrentWebStateStore.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2019 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | #include "ITorrentStateStore.h" 20 | 21 | class uTorrentWebStateStore : public ITorrentStateStore 22 | { 23 | public: 24 | uTorrentWebStateStore(); 25 | ~uTorrentWebStateStore() override; 26 | 27 | public: 28 | // ITorrentStateStore 29 | TorrentClient::Enum GetTorrentClient() const override; 30 | 31 | std::filesystem::path GuessDataDir(Intention::Enum intention) const override; 32 | bool IsValidDataDir(std::filesystem::path const& dataDir, Intention::Enum intention) const override; 33 | 34 | ITorrentStateIteratorPtr Export(std::filesystem::path const& dataDir, 35 | IFileStreamProvider const& fileStreamProvider) const override; 36 | void Import(std::filesystem::path const& dataDir, Box const& box, IFileStreamProvider& fileStreamProvider) const override; 37 | }; 38 | -------------------------------------------------------------------------------- /Torrent/Box.cpp: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "Box.h" 18 | 19 | Box::LimitInfo::LimitInfo() : 20 | Mode(LimitMode::Inherit), 21 | Value(0) 22 | { 23 | // 24 | } 25 | 26 | Box::FileInfo::FileInfo() : 27 | DoNotDownload(false), 28 | Priority(0) 29 | { 30 | // 31 | } 32 | 33 | Box::Box() : 34 | Torrent(), 35 | AddedAt(0), 36 | CompletedAt(0), 37 | IsPaused(false), 38 | DownloadedSize(0), 39 | UploadedSize(0), 40 | CorruptedSize(0), 41 | SavePath(), 42 | BlockSize(0), 43 | RatioLimit(), 44 | DownloadSpeedLimit(), 45 | UploadSpeedLimit(), 46 | Files(), 47 | ValidBlocks(), 48 | Trackers() 49 | { 50 | // 51 | } 52 | -------------------------------------------------------------------------------- /Torrent/Box.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | #include "TorrentInfo.h" 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | struct Box 28 | { 29 | enum Priority 30 | { 31 | MinPriority = -20, 32 | NormalPriority = 0, 33 | MaxPriority = 20 34 | }; 35 | 36 | enum struct LimitMode 37 | { 38 | Inherit, 39 | Enabled, 40 | Disabled 41 | }; 42 | 43 | struct LimitInfo 44 | { 45 | LimitMode Mode; 46 | double Value; 47 | 48 | LimitInfo(); 49 | }; 50 | 51 | struct FileInfo 52 | { 53 | bool DoNotDownload; 54 | int Priority; 55 | std::filesystem::path Path; 56 | 57 | FileInfo(); 58 | }; 59 | 60 | Box(); 61 | 62 | TorrentInfo Torrent; 63 | std::time_t AddedAt; 64 | std::time_t CompletedAt; 65 | bool IsPaused; 66 | std::uint64_t DownloadedSize; 67 | std::uint64_t UploadedSize; 68 | std::uint64_t CorruptedSize; 69 | std::filesystem::path SavePath; 70 | std::uint32_t BlockSize; 71 | LimitInfo RatioLimit; 72 | LimitInfo DownloadSpeedLimit; 73 | LimitInfo UploadSpeedLimit; 74 | std::vector Files; 75 | std::vector ValidBlocks; 76 | std::vector> Trackers; 77 | }; 78 | -------------------------------------------------------------------------------- /Torrent/BoxHelper.cpp: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "BoxHelper.h" 18 | 19 | #include "Box.h" 20 | 21 | #include 22 | 23 | int BoxHelper::Priority::FromStore(int storeValue, int storeMinValue, int storeMaxValue) 24 | { 25 | int const boxScaleSize = Box::MaxPriority - Box::MinPriority; 26 | int const storeScaleSize = storeMaxValue - storeMinValue; 27 | double const storeMiddleValue = storeMinValue + storeScaleSize / 2.; 28 | return std::lround(1. * (storeValue - storeMiddleValue) * boxScaleSize / storeScaleSize); 29 | } 30 | 31 | int BoxHelper::Priority::ToStore(int boxValue, int storeMinValue, int storeMaxValue) 32 | { 33 | int const storeScaleSize = storeMaxValue - storeMinValue; 34 | int const boxScaleSize = Box::MaxPriority - Box::MinPriority; 35 | double const boxMiddleValue = double{Box::MinPriority} + boxScaleSize / 2.; 36 | return std::lround(1. * (boxValue - boxMiddleValue) * storeScaleSize / boxScaleSize); 37 | } 38 | -------------------------------------------------------------------------------- /Torrent/BoxHelper.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | #include 20 | 21 | struct Box; 22 | 23 | struct BoxHelper 24 | { 25 | struct Priority 26 | { 27 | static int FromStore(int storeValue, int storeMinValue, int storeMaxValue); 28 | static int ToStore(int boxValue, int storeMinValue, int storeMaxValue); 29 | }; 30 | }; 31 | -------------------------------------------------------------------------------- /Torrent/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | add_library(BtMigrateTorrent 2 | Box.cpp 3 | Box.h 4 | BoxHelper.cpp 5 | BoxHelper.h 6 | Intention.h 7 | TorrentClient.cpp 8 | TorrentClient.h 9 | TorrentInfo.cpp 10 | TorrentInfo.h) 11 | 12 | target_link_libraries(BtMigrateTorrent 13 | PRIVATE 14 | BtMigrateCodec 15 | BtMigrateCommon) 16 | 17 | target_link_libraries(BtMigrateTorrent 18 | PUBLIC 19 | jsoncons 20 | PRIVATE 21 | fmt::fmt) 22 | -------------------------------------------------------------------------------- /Torrent/Intention.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | struct Intention 20 | { 21 | enum Enum 22 | { 23 | Export, 24 | Import 25 | }; 26 | 27 | // 28 | }; 29 | -------------------------------------------------------------------------------- /Torrent/TorrentClient.cpp: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "TorrentClient.h" 18 | 19 | #include "Common/Exception.h" 20 | #include "Common/Util.h" 21 | 22 | namespace ClientName 23 | { 24 | 25 | std::string const Deluge = "Deluge"; 26 | std::string const rTorrent = "rTorrent"; 27 | std::string const Transmission = "Transmission"; 28 | std::string const TransmissionMac = "TransmissionMac"; 29 | std::string const uTorrent = "uTorrent"; 30 | std::string const uTorrentWeb = "uTorrentWeb"; 31 | 32 | } // namespace 33 | 34 | std::string TorrentClient::ToString(Enum client) 35 | { 36 | switch (client) 37 | { 38 | case Deluge: 39 | return ClientName::Deluge; 40 | case rTorrent: 41 | return ClientName::rTorrent; 42 | case Transmission: 43 | return ClientName::Transmission; 44 | case TransmissionMac: 45 | return ClientName::TransmissionMac; 46 | case uTorrent: 47 | return ClientName::uTorrent; 48 | case uTorrentWeb: 49 | return ClientName::uTorrentWeb; 50 | } 51 | 52 | throw Exception("Unknown torrent client"); 53 | } 54 | 55 | TorrentClient::Enum TorrentClient::FromString(std::string client) 56 | { 57 | if (Util::IsEqualNoCase(client, ClientName::Deluge)) 58 | { 59 | return Deluge; 60 | } 61 | else if (Util::IsEqualNoCase(client, ClientName::rTorrent)) 62 | { 63 | return rTorrent; 64 | } 65 | else if (Util::IsEqualNoCase(client, ClientName::Transmission)) 66 | { 67 | return Transmission; 68 | } 69 | else if (Util::IsEqualNoCase(client, ClientName::TransmissionMac)) 70 | { 71 | return TransmissionMac; 72 | } 73 | else if (Util::IsEqualNoCase(client, ClientName::uTorrent)) 74 | { 75 | return uTorrent; 76 | } 77 | else if (Util::IsEqualNoCase(client, ClientName::uTorrentWeb)) 78 | { 79 | return uTorrentWeb; 80 | } 81 | 82 | throw Exception("Unknown torrent client"); 83 | } 84 | -------------------------------------------------------------------------------- /Torrent/TorrentClient.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | #include 20 | 21 | struct TorrentClient 22 | { 23 | enum Enum 24 | { 25 | Deluge, 26 | rTorrent, 27 | Transmission, 28 | TransmissionMac, 29 | uTorrent, 30 | uTorrentWeb 31 | }; 32 | 33 | static Enum const FirstClient = Deluge; 34 | static Enum const LastClient = uTorrent; 35 | 36 | static std::string ToString(Enum client); 37 | static Enum FromString(std::string client); 38 | }; 39 | -------------------------------------------------------------------------------- /Torrent/TorrentInfo.cpp: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "TorrentInfo.h" 18 | 19 | #include "Codec/BencodeCodec.h" 20 | #include "Codec/IStructuredDataCodec.h" 21 | #include "Common/Exception.h" 22 | #include "Common/Util.h" 23 | 24 | #include 25 | 26 | #include 27 | #include 28 | 29 | namespace fs = std::filesystem; 30 | 31 | namespace 32 | { 33 | 34 | std::string CalculateInfoHash(ojson const& torrent) 35 | { 36 | if (!torrent.contains("info")) 37 | { 38 | throw Exception("Torrent file is missing info dictionary"); 39 | } 40 | 41 | std::ostringstream infoStream; 42 | BencodeCodec().Encode(infoStream, torrent["info"]); 43 | return Util::CalculateSha1(infoStream.str()); 44 | } 45 | 46 | } // namespace 47 | 48 | TorrentInfo::TorrentInfo() = default; 49 | 50 | TorrentInfo::TorrentInfo(ojson const& torrent) : 51 | m_torrent(torrent), 52 | m_infoHash(CalculateInfoHash(m_torrent)) 53 | { 54 | // 55 | } 56 | 57 | void TorrentInfo::Encode(std::ostream& stream, IStructuredDataCodec const& codec) const 58 | { 59 | codec.Encode(stream, m_torrent); 60 | } 61 | 62 | std::string const& TorrentInfo::GetInfoHash() const 63 | { 64 | return m_infoHash; 65 | } 66 | 67 | std::uint64_t TorrentInfo::GetTotalSize() const 68 | { 69 | std::uint64_t result = 0; 70 | 71 | ojson const& info = m_torrent["info"]; 72 | 73 | if (!info.contains("files")) 74 | { 75 | result += info["length"].as(); 76 | } 77 | else 78 | { 79 | for (ojson const& file : info["files"].array_range()) 80 | { 81 | result += file["length"].as(); 82 | } 83 | } 84 | 85 | return result; 86 | } 87 | 88 | std::uint32_t TorrentInfo::GetPieceSize() const 89 | { 90 | ojson const& info = m_torrent["info"]; 91 | 92 | return info["piece length"].as(); 93 | } 94 | 95 | std::string TorrentInfo::GetName() const 96 | { 97 | ojson const& info = m_torrent["info"]; 98 | 99 | return info["name"].as(); 100 | } 101 | 102 | fs::path TorrentInfo::GetFilePath(std::size_t fileIndex) const 103 | { 104 | fs::path result; 105 | 106 | ojson const& info = m_torrent["info"]; 107 | 108 | if (!info.contains("files")) 109 | { 110 | if (fileIndex != 0) 111 | { 112 | throw Exception(fmt::format("Torrent file #{} does not exist", fileIndex)); 113 | } 114 | 115 | result /= GetName(); 116 | } 117 | else 118 | { 119 | ojson const& files = info["files"]; 120 | 121 | if (fileIndex >= files.size()) 122 | { 123 | throw Exception(fmt::format("Torrent file #{} does not exist", fileIndex)); 124 | } 125 | 126 | for (ojson const& pathPart : files[fileIndex]["path"].array_range()) 127 | { 128 | result /= pathPart.as(); 129 | } 130 | } 131 | 132 | return result; 133 | } 134 | 135 | void TorrentInfo::SetTrackers(std::vector> const& trackers) 136 | { 137 | ojson announceList = ojson::array(); 138 | 139 | for (auto const& tier : trackers) 140 | { 141 | announceList.emplace_back(tier); 142 | } 143 | 144 | m_torrent["announce-list"] = announceList; 145 | 146 | if (announceList.empty()) 147 | { 148 | m_torrent.erase("announce"); 149 | } 150 | else 151 | { 152 | m_torrent["announce"] = announceList[0][0]; 153 | } 154 | 155 | Util::SortJsonObjectKeys(m_torrent); 156 | } 157 | 158 | TorrentInfo TorrentInfo::Decode(std::istream& stream, IStructuredDataCodec const& codec) 159 | { 160 | ojson torrent; 161 | codec.Decode(stream, torrent); 162 | return TorrentInfo(torrent); 163 | } 164 | -------------------------------------------------------------------------------- /Torrent/TorrentInfo.h: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #pragma once 18 | 19 | #include 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | using jsoncons::ojson; 28 | 29 | class IStructuredDataCodec; 30 | 31 | class TorrentInfo 32 | { 33 | public: 34 | TorrentInfo(); 35 | TorrentInfo(ojson const& torrent); 36 | 37 | void Encode(std::ostream& stream, IStructuredDataCodec const& codec) const; 38 | 39 | std::string const& GetInfoHash() const; 40 | std::uint64_t GetTotalSize() const; 41 | std::uint32_t GetPieceSize() const; 42 | std::string GetName() const; 43 | std::filesystem::path GetFilePath(std::size_t fileIndex) const; 44 | 45 | void SetTrackers(std::vector> const& trackers); 46 | 47 | static TorrentInfo Decode(std::istream& stream, IStructuredDataCodec const& codec); 48 | 49 | private: 50 | ojson m_torrent; 51 | std::string m_infoHash; 52 | }; 53 | -------------------------------------------------------------------------------- /fetch.cmake: -------------------------------------------------------------------------------- 1 | include(FetchContent) 2 | 3 | FetchContent_Declare(digestpp 4 | GIT_REPOSITORY https://github.com/kerukuro/digestpp.git 5 | GIT_TAG e5ace19f96f951772404d4587ea471b1be21b811) 6 | 7 | FetchContent_MakeAvailable(digestpp) 8 | 9 | add_library(digestpp::digestpp INTERFACE IMPORTED) 10 | target_include_directories(digestpp::digestpp INTERFACE "${digestpp_SOURCE_DIR}") 11 | -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | // bt-migrate, torrent state migration tool 2 | // Copyright (C) 2014 Mike Gelfand 3 | // 4 | // This program is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | // 9 | // This program is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | // 14 | // You should have received a copy of the GNU General Public License 15 | // along with this program. If not, see . 16 | 17 | #include "ImportHelper.h" 18 | #include "MigrationTransaction.h" 19 | 20 | #include "Common/Exception.h" 21 | #include "Common/Logger.h" 22 | #include "Common/SignalHandler.h" 23 | #include "Store/ITorrentStateStore.h" 24 | #include "Store/TorrentStateStoreFactory.h" 25 | #include "Torrent/Box.h" 26 | 27 | #include 28 | #include 29 | #include 30 | 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | 39 | #ifdef _WIN32 40 | #include 41 | #endif 42 | 43 | namespace fs = std::filesystem; 44 | 45 | namespace 46 | { 47 | 48 | void PrintVersion() 49 | { 50 | std::cout << 51 | "Torrent state migration tool, version " << BTMIGRATE_VERSION << std::endl << 52 | "Copyright (C) 2014-2021 Mike Gelfand " << std::endl << 53 | std::endl << 54 | "This program comes with ABSOLUTELY NO WARRANTY. This is free software," << std::endl << 55 | "and you are welcome to redistribute it under certain conditions;" << std::endl << 56 | "see for details." << std::endl; 57 | } 58 | 59 | void PrintUsage(cxxopts::Options const& options) 60 | { 61 | std::cout << options.help(); 62 | } 63 | 64 | ITorrentStateStorePtr FindStateStore(TorrentStateStoreFactory const& storeFactory, Intention::Enum intention, 65 | std::string& clientName, fs::path& clientDataDir) 66 | { 67 | std::string const lowerCaseClientName = intention == Intention::Export ? "source" : "target"; 68 | std::string const upperCaseClientName = intention == Intention::Export ? "Source" : "Target"; 69 | 70 | ITorrentStateStorePtr result; 71 | 72 | if (!clientName.empty()) 73 | { 74 | result = storeFactory.CreateForClient(TorrentClient::FromString(clientName)); 75 | if (clientDataDir.empty()) 76 | { 77 | clientDataDir = result->GuessDataDir(intention); 78 | if (clientDataDir.empty()) 79 | { 80 | throw Exception(fmt::format("No data directory found for {} torrent client", lowerCaseClientName)); 81 | } 82 | } 83 | } 84 | else if (!clientDataDir.empty()) 85 | { 86 | result = storeFactory.GuessByDataDir(clientDataDir, intention); 87 | } 88 | else 89 | { 90 | throw Exception(fmt::format("{} torrent client name and/or data directory are not specified", upperCaseClientName)); 91 | } 92 | 93 | clientName = TorrentClient::ToString(result->GetTorrentClient()); 94 | clientDataDir = fs::canonical(clientDataDir); 95 | 96 | if (!result->IsValidDataDir(clientDataDir, intention)) 97 | { 98 | throw Exception(fmt::format("Bad {} data directory: {}", lowerCaseClientName, clientDataDir)); 99 | } 100 | 101 | Logger(Logger::Info) << upperCaseClientName << ": " << clientName << " (" << clientDataDir << ")"; 102 | 103 | return result; 104 | } 105 | 106 | } // namespace 107 | 108 | #ifdef _WIN32 109 | int wmain(int argc, wchar_t* wideArgv[]) 110 | #else 111 | int main(int argc, char* argv[]) 112 | #endif 113 | { 114 | try 115 | { 116 | #ifdef _WIN32 117 | auto argvStrings = std::vector(argc); 118 | auto argvCStrings = std::vector(argc); 119 | char** const argv = argvCStrings.data(); 120 | 121 | for (int i = 0; i < argc; ++i) 122 | { 123 | int length = ::WideCharToMultiByte(CP_UTF8, 0, wideArgv[i], -1, nullptr, 0, nullptr, nullptr); 124 | if (length != 0) 125 | { 126 | argvStrings[i].resize(length); 127 | argvCStrings[i] = argvStrings[i].data(); 128 | length = ::WideCharToMultiByte(CP_UTF8, 0, wideArgv[i], -1, argv[i], length, nullptr, nullptr); 129 | } 130 | 131 | if (length == 0) 132 | { 133 | throw Exception("Failed to parse Win32 command line"); 134 | } 135 | } 136 | #endif 137 | 138 | std::string const programName = fs::path(argv[0]).filename().string(); 139 | 140 | std::string sourceName; 141 | std::string targetName; 142 | std::string sourceDirString; 143 | std::string targetDirString; 144 | unsigned int maxThreads = std::max(1u, std::thread::hardware_concurrency()); 145 | bool noBackup = false; 146 | bool dryRun = false; 147 | bool verboseOutput = false; 148 | 149 | auto options = cxxopts::Options(programName); 150 | 151 | options.add_options("Main") 152 | ("source", "source client name", cxxopts::value(sourceName), "name") 153 | ("source-dir", "source client data directory", cxxopts::value(sourceDirString), "path") 154 | ("target", "target client name", cxxopts::value(targetName), "name") 155 | ("target-dir", "target client data directory", cxxopts::value(targetDirString), "path") 156 | ("max-threads", "maximum number of migration threads", 157 | cxxopts::value(maxThreads)->default_value(std::to_string(maxThreads)), "N") 158 | ("no-backup", "do not backup target client data directory", cxxopts::value(noBackup)) 159 | ("dry-run", "do not write anything to disk", cxxopts::value(dryRun)); 160 | 161 | options.add_options("Other") 162 | ("verbose", "produce verbose output", cxxopts::value(verboseOutput)) 163 | ("version", "print program version") 164 | ("help", "print this help message"); 165 | 166 | auto const args = options.parse(argc, argv); 167 | 168 | if (args.count("version") != 0) 169 | { 170 | PrintVersion(); 171 | return 0; 172 | } 173 | 174 | if (args.count("help") != 0) 175 | { 176 | PrintVersion(); 177 | PrintUsage(options); 178 | return 0; 179 | } 180 | 181 | if (verboseOutput) 182 | { 183 | Logger::SetMinimumLevel(Logger::Debug); 184 | } 185 | 186 | TorrentStateStoreFactory const storeFactory; 187 | 188 | fs::path sourceDir = sourceDirString; 189 | ITorrentStateStorePtr sourceStore = FindStateStore(storeFactory, Intention::Export, sourceName, sourceDir); 190 | fs::path targetDir = targetDirString; 191 | ITorrentStateStorePtr targetStore = FindStateStore(storeFactory, Intention::Import, targetName, targetDir); 192 | 193 | unsigned int const threadCount = std::max(1u, maxThreads); 194 | 195 | MigrationTransaction transaction(noBackup, dryRun); 196 | 197 | SignalHandler const signalHandler; 198 | 199 | ImportHelper importHelper(std::move(sourceStore), sourceDir, std::move(targetStore), targetDir, transaction, 200 | signalHandler); 201 | ImportHelper::Result const result = importHelper.Import(threadCount); 202 | 203 | bool shouldCommit = true; 204 | 205 | if ((result.FailCount != 0 || result.SkipCount != 0) && !noBackup && !dryRun) 206 | { 207 | while (!signalHandler.IsInterrupted()) 208 | { 209 | std::cout << "Import is not clean, do you want to commit? [yes/no]: " << std::flush; 210 | 211 | std::string answer; 212 | std::getline(std::cin, answer); 213 | 214 | if (answer == "yes") 215 | { 216 | break; 217 | } 218 | 219 | if (answer == "no") 220 | { 221 | shouldCommit = false; 222 | break; 223 | } 224 | } 225 | } 226 | 227 | if (shouldCommit && !signalHandler.IsInterrupted()) 228 | { 229 | transaction.Commit(); 230 | } 231 | } 232 | catch (std::exception const& e) 233 | { 234 | Logger(Logger::Error) << "Error: " << e.what(); 235 | return 1; 236 | } 237 | 238 | return 0; 239 | } 240 | -------------------------------------------------------------------------------- /vcpkg.cmake: -------------------------------------------------------------------------------- 1 | include(FetchContent) 2 | 3 | FetchContent_Declare(vcpkg 4 | GIT_REPOSITORY https://github.com/microsoft/vcpkg.git 5 | GIT_TAG 2025.04.09) 6 | FetchContent_MakeAvailable(vcpkg) 7 | 8 | set(VCPKG_VERBOSE ON CACHE INTERNAL "") 9 | 10 | set(CMAKE_TOOLCHAIN_FILE ${vcpkg_SOURCE_DIR}/scripts/buildsystems/vcpkg.cmake 11 | CACHE STRING "CMake toolchain file") 12 | -------------------------------------------------------------------------------- /vcpkg.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "bt-migrate", 3 | "version-string": "0.1", 4 | "dependencies": [ 5 | "cxxopts", 6 | "fmt", 7 | "jsoncons", 8 | "pugixml", 9 | "sqlite-orm" 10 | ] 11 | } 12 | --------------------------------------------------------------------------------