├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE.md ├── ISSUE_TEMPLATE │ ├── BUG_REPORT.md │ ├── FEATURE_REQUEST.md │ └── OTHER_ISSUES.md ├── SUPPORT.md └── labels.json ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── assets └── logo.svg ├── cloudplow.py ├── config.json.sample ├── requirements.txt ├── scripts └── plex_token.sh ├── systemd └── cloudplow.service └── utils ├── __init__.py ├── cache.py ├── config.py ├── decorators.py ├── lock.py ├── misc.py ├── notifications ├── __init__.py ├── apprise.py ├── pushover.py └── slack.py ├── nzbget.py ├── path.py ├── plex.py ├── process.py ├── rclone.py ├── sabnzbd.py ├── syncer ├── __init__.py ├── local.py └── scaleway.py ├── threads.py ├── unionfs.py ├── uploader.py ├── version.py └── xmlrpc.py /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [l3uddz,saltydk] 2 | custom: ["https://www.paypal.me/l3uddz"] 3 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 8 | 9 | ## Support / Questions 10 | 11 | The [readme](https://github.com/l3uddz/cloudplow/blob/master/README.md) page is very detailed and updated often. It should be the first thing used to find the answers to your questions. 12 | 13 | If you still have a support question, use the [Discord](https://discord.io/cloudbox) chat server to post your question in the `#cloudplow` channel. 14 | 15 | Support questions or requests will be redirected there and the issue ticket will be closed. 16 | 17 | ## Bug Report 18 | 19 | Use https://github.com/l3uddz/cloudplow/issues/new?template=BUG_REPORT.md 20 | 21 | ## Feature Request 22 | 23 | Use https://github.com/l3uddz/cloudplow/issues/new?template=FEATURE_REQUEST.md 24 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/BUG_REPORT.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug Report 3 | about: Create a report to help us improve Cloudplow 4 | labels: Bug 5 | --- 6 | 7 | **Describe the bug** 8 | A clear and concise description of what the bug is. 9 | 10 | **To Reproduce** 11 | Steps to reproduce the behavior: 12 | 1. Go to '...' 13 | 2. Click on '....' 14 | 3. Scroll down to '....' 15 | 4. See error 16 | 17 | **Expected behavior** 18 | A clear and concise description of what you expected to happen. 19 | 20 | **Screenshots** 21 | If applicable, add screenshots to help explain your problem. 22 | 23 | **Logs** 24 | Link to debug or trace log files. 25 | 26 | You can enable debug mode by adding `--loglevel=DEBUG` to the run command (e.g. systemd). 27 | 28 | **System Information** 29 | 30 | - Cloudplow Version: [e.g. Master (latest), Develop (latest)] 31 | - Operating System: [e.g. Ubuntu Server 16.04 LTS] 32 | 33 | **Additional context** 34 | Add any other context about the problem here. 35 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/FEATURE_REQUEST.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature Request 3 | about: Suggest an idea for Cloudplow 4 | labels: Feature Request 5 | --- 6 | 7 | **Describe the problem** 8 | A clear and concise description of the problem you're looking to solve. 9 | 10 | **Describe any solutions you think might work** 11 | A clear and concise description of any solutions or features you've considered. 12 | 13 | **Additional context** 14 | Add any other context or screenshots about the feature request here. 15 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/OTHER_ISSUES.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Other Issues 3 | about: How to get support or ask questions 4 | --- 5 | 6 | The [readme](https://github.com/l3uddz/cloudplow/blob/master/README.md) page is very detailed and updated often. It should be the first thing used to find the answers to your questions. 7 | 8 | If you still have a support question, use the [Discord](https://discord.io/cloudbox) chat server to post your question in the `#cloudplow` channel. 9 | 10 | Support questions or requests will be redirected there and the issue ticket will be closed. 11 | -------------------------------------------------------------------------------- /.github/SUPPORT.md: -------------------------------------------------------------------------------- 1 | ## Support 2 | 3 | The [readme](https://github.com/l3uddz/cloudplow/blob/master/README.md) page is very detailed and updated often. It should be the first thing used to find the answers to your questions. 4 | 5 | If you still have a support question, use the [Discord](https://discord.io/cloudbox) chat server to post your question in the `#cloudplow` channel. 6 | -------------------------------------------------------------------------------- /.github/labels.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "Bug", 4 | "color": "#ee0701" 5 | }, 6 | { 7 | "name": "Docs", 8 | "color": "#abfcee" 9 | }, 10 | { 11 | "name": "Duplicate", 12 | "color": "#cccccc" 13 | }, 14 | { 15 | "name": "Expected Behavior", 16 | "color": "#cccccc" 17 | }, 18 | { 19 | "name": "Feature Request", 20 | "color": "#2f58b7" 21 | }, 22 | { 23 | "name": "Invalid", 24 | "color": "#e6e6e6" 25 | }, 26 | { 27 | "name": "Support", 28 | "color": "#cc317c" 29 | }, 30 | { 31 | "name": "Waiting For Info", 32 | "color": "#13db34" 33 | }, 34 | { 35 | "name": "Wont Fix", 36 | "color": "#ffffff" 37 | }, 38 | { 39 | "name": "Work In Progress", 40 | "color": "#dd3087" 41 | } 42 | ] 43 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # User-specific stuff: 2 | /.idea/* 3 | 4 | ## File-based project format: 5 | *.iws 6 | 7 | # IntelliJ 8 | /out/ 9 | 10 | # Byte-compiled / optimized / DLL files 11 | __pycache__/ 12 | *.py[cod] 13 | *$py.class 14 | 15 | # logs 16 | *.log* 17 | 18 | # databases 19 | /cache.db 20 | 21 | # configs 22 | *.cfg 23 | /config.json 24 | 25 | # generators 26 | *.bat 27 | 28 | # locks 29 | locks/* 30 | 31 | # Venv 32 | venv/* 33 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Contributing 2 | 3 | Guide below will explain the process of submitting a pull request (PR). 4 | 5 | 1. Fork it. 6 | 7 | 1. Clone your forked project: 8 | 9 | ``` 10 | git clone http://github.com//cloudplow 11 | ``` 12 | 13 | 1. Create a feature branch off of the **develop** branch: 14 | 15 | ``` 16 | git checkout -b 'feature/my-new-feature' develop 17 | ``` 18 | 19 | 1. Keep up to date with latest **develop** branch changes: 20 | 21 | ``` 22 | git pull --rebase upstream develop 23 | ``` 24 | 25 | 1. Commit your changes: 26 | 27 | ``` 28 | git commit -am 'Added some feature' 29 | ``` 30 | 31 | 1. Push commits to the feature branch: 32 | 33 | ``` 34 | git push origin feature/my-new-feature 35 | ``` 36 | 37 | 1. Submit feature branch as a PR to _our_ **develop** branch. 38 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 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 | 635 | Copyright (C) 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 | Copyright (C) 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Cloudplow 2 | 3 | 4 | [![made-with-python](https://img.shields.io/badge/Made%20with-Python-blue.svg?style=flat-square)](https://www.python.org/) 5 | [![License: GPL v3](https://img.shields.io/badge/License-GPL%203-blue.svg?style=flat-square)](https://github.com/l3uddz/cloudplow/blob/master/LICENSE.md) 6 | [![last commit (master)](https://img.shields.io/github/last-commit/l3uddz/cloudplow/master.svg?colorB=177DC1&label=Last%20Commit&style=flat-square)](https://github.com/l3uddz/cloudplow/commits/master) 7 | [![Discord](https://img.shields.io/discord/853755447970758686.svg?colorB=177DC1&label=Discord&style=flat-square)](https://discord.gg/ugfKXpFND8) 8 | [![Contributing](https://img.shields.io/badge/Contributing-gray.svg?style=flat-square)](CONTRIBUTING.md) 9 | [![Donate](https://img.shields.io/badge/Donate-gray.svg?style=flat-square)](#donate) 10 | 11 | --- 12 | 13 | 14 | 15 | - [Introduction](#introduction) 16 | - [Requirements](#requirements) 17 | - [Installation](#installation) 18 | - [Configuration](#configuration) 19 | - [Sample](#sample) 20 | - [Core](#core) 21 | - [Hidden](#hidden) 22 | - [Notifications](#notifications) 23 | - [NZBGet](#nzbget) 24 | - [Sabnzbd](#sabnzbd) 25 | - [Plex](#plex) 26 | - [Remotes](#remotes) 27 | - [Uploader](#uploader) 28 | - [Syncer](#syncer) 29 | - [Usage](#usage) 30 | - [Automatic (Scheduled)](#automatic-scheduled) 31 | - [Manual (CLI)](#manual-cli) 32 | - [Donate](#donate) 33 | 34 | 35 | 36 | --- 37 | 38 | 39 | 40 | # Introduction 41 | 42 | Cloudplow has 3 main functions: 43 | 44 | 1. Automatic uploader to Rclone remote : Files are moved off local storage. With support for multiple uploaders (i.e. remote/folder pairings). 45 | 46 | 2. UnionFS Cleaner functionality: Deletion of UnionFS-Fuse whiteout files (`*_HIDDEN~`) and their corresponding "whited-out" files on Rclone remotes. With support for multiple remotes (useful if you have multiple Rclone remotes mounted). 47 | 48 | 3. Automatic remote syncer: Sync between two different Rclone remotes using 3rd party VM instances. With support for multiple remote/folder pairings. With support for multiple syncers (i.e. remote/remote pairings). 49 | 50 | 51 | # Requirements 52 | 53 | 1. Ubuntu/Debian OS (could work in other OSes with some tweaks). 54 | 55 | 2. Python 3.6 or higher (`sudo apt install python3 python3-pip`). 56 | 57 | 3. Required Python modules (see below). 58 | 59 | # Installation 60 | 61 | 1. Clone the Cloudplow repo. 62 | 63 | ``` 64 | sudo git clone https://github.com/l3uddz/cloudplow /opt/cloudplow 65 | ``` 66 | 67 | 2. Fix permissions of the Cloudplow folder (replace `user`/`group` with your info; run `id` to check). 68 | 69 | ``` 70 | sudo chown -R user:group /opt/cloudplow 71 | ``` 72 | 73 | 3. Go into the Cloudplow folder. 74 | 75 | ``` 76 | cd /opt/cloudplow 77 | ``` 78 | 79 | 4. Install Python PIP. 80 | 81 | ``` 82 | sudo apt-get install python3-pip 83 | ``` 84 | 85 | 5. Install the required python modules. 86 | 87 | ``` 88 | sudo python3 -m pip install -r requirements.txt 89 | ``` 90 | 91 | 6. Create a shortcut for Cloudplow. 92 | 93 | ``` 94 | sudo ln -s /opt/cloudplow/cloudplow.py /usr/local/bin/cloudplow 95 | ``` 96 | 97 | 7. Generate a basic `config.json` file. 98 | 99 | ``` 100 | cloudplow run 101 | ``` 102 | 103 | 8. Configure the `config.json` file. 104 | 105 | ``` 106 | nano config.json 107 | ``` 108 | 109 | 110 | # Configuration 111 | 112 | 113 | ## Sample 114 | 115 | ```json 116 | { 117 | "core": { 118 | "dry_run": false, 119 | "rclone_binary_path": "/usr/bin/rclone", 120 | "rclone_config_path": "/home/seed/.config/rclone/rclone.conf" 121 | }, 122 | "hidden": { 123 | "/mnt/local/.unionfs-fuse": { 124 | "hidden_remotes": [ 125 | "google" 126 | ] 127 | } 128 | }, 129 | "notifications": { 130 | "Pushover": { 131 | "app_token": "", 132 | "service": "pushover", 133 | "user_token": "", 134 | "priority": "0" 135 | }, 136 | "Slack": { 137 | "webhook_url": "", 138 | "sender_name": "cloudplow", 139 | "sender_icon": ":heavy_exclamation_mark:", 140 | "channel": "", 141 | "service": "slack" 142 | } 143 | }, 144 | "nzbget": { 145 | "enabled": false, 146 | "url": "https://user:pass@nzbget.domain.com" 147 | }, 148 | "sabnzbd": { 149 | "enabled": false, 150 | "url": "https://sabnzbd.domain.com", 151 | "api-key": "1314234234" 152 | }, 153 | "plex": { 154 | "enabled": true, 155 | "max_streams_before_throttle": 1, 156 | "ignore_local_streams": true, 157 | "poll_interval": 60, 158 | "notifications": false, 159 | "rclone": { 160 | "throttle_speeds": { 161 | "0": "100M", 162 | "1": "50M", 163 | "2": "40M", 164 | "3": "30M", 165 | "4": "20M", 166 | "5": "10M" 167 | }, 168 | "url": "http://localhost:7949" 169 | }, 170 | "token": "", 171 | "url": "https://plex.domain.com" 172 | }, 173 | "remotes": { 174 | "google": { 175 | "hidden_remote": "google:", 176 | "rclone_excludes": [ 177 | "**partial~", 178 | "**_HIDDEN~", 179 | ".unionfs/**", 180 | ".unionfs-fuse/**" 181 | ], 182 | "rclone_extras": { 183 | "--checkers": 16, 184 | "--drive-chunk-size": "64M", 185 | "--stats": "60s", 186 | "--transfers": 8, 187 | "--verbose": 1, 188 | "--skip-links": null, 189 | "--drive-stop-on-upload-limit": null, 190 | "--user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36" 191 | }, 192 | "rclone_sleeps": { 193 | "Failed to copy: googleapi: Error 403: User rate limit exceeded": { 194 | "count": 5, 195 | "sleep": 25, 196 | "timeout": 3600 197 | }, 198 | " 0/s,": { 199 | "count": 15, 200 | "sleep": 25, 201 | "timeout": 140 202 | } 203 | }, 204 | "rclone_command": "move", 205 | "remove_empty_dir_depth": 2, 206 | "sync_remote": "google:/Backups", 207 | "upload_folder": "/mnt/local/Media", 208 | "upload_remote": "google:/Media" 209 | }, 210 | "google_downloads": { 211 | "hidden_remote": "", 212 | "rclone_excludes": [ 213 | "**partial~", 214 | "**_HIDDEN~", 215 | ".unionfs/**", 216 | ".unionfs-fuse/**" 217 | ], 218 | "rclone_extras": { 219 | "--checkers": 32, 220 | "--stats": "60s", 221 | "--transfers": 16, 222 | "--verbose": 1, 223 | "--skip-links": null 224 | }, 225 | "rclone_sleeps": { 226 | }, 227 | "rclone_command": "copy", 228 | "remove_empty_dir_depth": 2, 229 | "sync_remote": "", 230 | "upload_folder": "/mnt/local/Downloads", 231 | "upload_remote": "google:/Downloads" 232 | }, 233 | "box": { 234 | "hidden_remote": "box:", 235 | "rclone_excludes": [ 236 | "**partial~", 237 | "**_HIDDEN~", 238 | ".unionfs/**", 239 | ".unionfs-fuse/**" 240 | ], 241 | "rclone_extras": { 242 | "--user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36", 243 | "--checkers": 32, 244 | "--stats": "60s", 245 | "--transfers": 16, 246 | "--verbose": 1, 247 | "--skip-links": null 248 | }, 249 | "rclone_sleeps": { 250 | "Failed to copy: googleapi: Error 403: User rate limit exceeded": { 251 | "count": 5, 252 | "sleep": 25, 253 | "timeout": 300 254 | }, 255 | " 0/s,": { 256 | "count": 15, 257 | "sleep": 25, 258 | "timeout": 140 259 | } 260 | }, 261 | "rclone_command": "move", 262 | "remove_empty_dir_depth": 2, 263 | "sync_remote": "box:/Backups", 264 | "upload_folder": "/mnt/local/Media", 265 | "upload_remote": "box:/Media" 266 | }, 267 | "google_with_mover": { 268 | "hidden_remote": "google:", 269 | "rclone_excludes": [ 270 | "**partial~", 271 | "**_HIDDEN~", 272 | ".unionfs/**", 273 | ".unionfs-fuse/**" 274 | ], 275 | "rclone_extras": { 276 | "--checkers": 16, 277 | "--drive-chunk-size": "64M", 278 | "--stats": "60s", 279 | "--transfers": 8, 280 | "--verbose": 1, 281 | "--skip-links": null, 282 | "--drive-stop-on-upload-limit": null, <-- this one 283 | "--user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36" 284 | }, 285 | "rclone_sleeps": { 286 | "Failed to copy: googleapi: Error 403: User rate limit exceeded": { 287 | "count": 5, 288 | "sleep": 25, 289 | "timeout": 3600 290 | }, 291 | " 0/s,": { 292 | "count": 15, 293 | "sleep": 25, 294 | "timeout": 140 295 | } 296 | }, 297 | "rclone_command": "move", 298 | "remove_empty_dir_depth": 2, 299 | "sync_remote": "google:/Backups", 300 | "upload_folder": "/mnt/local/Media", 301 | "upload_remote": "google:/Media" 302 | } 303 | }, 304 | "syncer": { 305 | "google2box": { 306 | "rclone_extras": { 307 | "--bwlimit": "80M", 308 | "--checkers": 32, 309 | "--drive-chunk-size": "64M", 310 | "--stats": "60s", 311 | "--transfers": 16, 312 | "--verbose": 1 313 | }, 314 | "service": "scaleway", 315 | "sync_from": "google", 316 | "sync_interval": 24, 317 | "sync_to": "box", 318 | "tool_path": "/home/seed/go/bin/scw", 319 | "use_copy": true, 320 | "instance_destroy": false 321 | } 322 | }, 323 | "uploader": { 324 | "google": { 325 | "can_be_throttled": true, 326 | "check_interval": 30, 327 | "exclude_open_files": true, 328 | "max_size_gb": 400, 329 | "opened_excludes": [ 330 | "/downloads/" 331 | ], 332 | "schedule": { 333 | "allowed_from": "04:00", 334 | "allowed_until": "08:00", 335 | "enabled": false 336 | }, 337 | "size_excludes": [ 338 | "downloads/*" 339 | ], 340 | "service_account_path":"/home/user/.config/cloudplow/service_accounts/" 341 | }, 342 | "google_downloads": { 343 | "check_interval": 30, 344 | "exclude_open_files": true, 345 | "max_size_gb": 400, 346 | "opened_excludes": [ 347 | ], 348 | "schedule": {}, 349 | "size_excludes": [ 350 | ] 351 | }, 352 | "google_with_mover": { 353 | "check_interval": 30, 354 | "exclude_open_files": true, 355 | "max_size_gb": 400, 356 | "opened_excludes": [ 357 | "/downloads/" 358 | ], 359 | "schedule": {}, 360 | "size_excludes": [ 361 | "downloads/*" 362 | ], 363 | "service_account_path":"/home/user/.config/cloudplow/service_accounts/", 364 | "mover": { 365 | "enabled": false, 366 | "move_from_remote": "staging:Media", 367 | "move_to_remote": "gdrive:Media", 368 | "rclone_extras": { 369 | "--delete-empty-src-dirs": null, 370 | "--create-empty-src-dirs": null, 371 | "--stats": "60s", 372 | "--verbose": 1, 373 | "--no-traverse": null, 374 | "--drive-server-side-across-configs": null, 375 | "--user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36" 376 | } 377 | } 378 | } 379 | } 380 | } 381 | ``` 382 | 383 | 384 | ## Core 385 | 386 | ``` 387 | "core": { 388 | "dry_run": false, 389 | "rclone_binary_path": "/usr/bin/rclone", 390 | "rclone_config_path": "/home/seed/.config/rclone/rclone.conf" 391 | }, 392 | ``` 393 | 394 | `"dry_run": true` - prevent any files being uploaded or deleted - use this to test out your config. 395 | 396 | `rclone_binary_path` - full path to Rclone binary file. 397 | 398 | `rclone_config_path` - full path to Rclone config file. 399 | 400 | ## Hidden 401 | 402 | UnionFS Hidden File Cleaner: Deletion of UnionFS whiteout files and their corresponding files on rclone remotes. 403 | 404 | ``` 405 | "hidden": { 406 | "/mnt/local/.unionfs-fuse": { 407 | "hidden_remotes": [ 408 | "google" 409 | ] 410 | } 411 | }, 412 | ``` 413 | 414 | This is where you specify the location of the UnionFS `_HIDDEN~` files (i.e. whiteout files) and the Rclone remotes where the corresponding files will need to be deleted from. You may specify more than one remote here. 415 | 416 | The specific remote path, where those corresponding files are, will be specified in the `remotes` section. 417 | 418 | Note: If you plan on using this with any other file system, eg MergerFS, you can leave this section blank (`"hidden": {}`). 419 | 420 | ## Notifications 421 | 422 | ```json 423 | "notifications": { 424 | "apprise": { 425 | "service": "apprise", 426 | "url": "", 427 | "title": "" 428 | } 429 | }, 430 | ``` 431 | 432 | Notifications alerts for both scheduled and manual Cloudplow tasks. 433 | 434 | Supported `services`: 435 | - `apprise` 436 | - `pushover` 437 | - `slack` 438 | 439 | _Note: The key name can be anything, but the `service` key must be must be the exact service name (e.g. `pushover`). See below for example._ 440 | 441 | ```json 442 | "notifications": { 443 | "anyname": { 444 | "service": "pushover", 445 | } 446 | }, 447 | ``` 448 | 449 | ### Apprise 450 | 451 | ```json 452 | "notifications": { 453 | "Apprise": { 454 | "service": "apprise", 455 | "url": "", 456 | "title": "" 457 | } 458 | }, 459 | ``` 460 | 461 | `url` - Apprise service URL (see [here](https://github.com/caronc/apprise)). 462 | 463 | - Required. 464 | 465 | `title` - Notification Title. 466 | 467 | - Optional. 468 | 469 | - Default is `Cloudplow`. 470 | 471 | ### Pushover 472 | 473 | ```json 474 | "notifications": { 475 | "Pushover": { 476 | "app_token": "", 477 | "service": "pushover", 478 | "user_token": "", 479 | "priority": 0 480 | } 481 | }, 482 | ``` 483 | 484 | `app_token` - App Token from [Pushover.net](https://pushover.net). 485 | 486 | - Required. 487 | 488 | `user_token` - User Token from [Pushover.net](https://pushover.net). 489 | 490 | - Required. 491 | 492 | `priority` - [Priority](https://pushover.net/api#priority) of the notifications. 493 | 494 | - Optional. 495 | 496 | - Choices are: `-2`, `-1`, `0`, `1`, `2`. 497 | 498 | - Values are not quoted. 499 | 500 | - Default is `0`. 501 | 502 | ### Slack 503 | 504 | ```json 505 | "notifications": { 506 | "Slack": { 507 | "service": "slack", 508 | "webhook_url": "", 509 | "channel": "", 510 | "sender_name": "Cloudplow", 511 | "sender_icon": ":heavy_exclamation_mark:" 512 | } 513 | }, 514 | ``` 515 | 516 | `webhook_url` - [Webhook URL](https://my.slack.com/services/new/incoming-webhook/). 517 | 518 | - Required. 519 | 520 | `channel` - Slack channel to send the notifications to. 521 | 522 | - Optional. 523 | 524 | - Default is blank. 525 | 526 | `sender_name` - Sender's name for the notifications. 527 | 528 | - Optional. 529 | 530 | - Default is `Cloudplow`. 531 | 532 | `sender_icon` - Icon to use for the notifications. 533 | 534 | - Optional. 535 | 536 | - Default is `:heavy_exclamation_mark:` 537 | 538 | 539 | ## NZBGet 540 | 541 | Cloudplow can pause the NZBGet download queue when an upload starts; and then resume it upon the upload finishing. 542 | 543 | ``` 544 | "nzbget": { 545 | "enabled": false, 546 | "url": "https://user:pass@nzbget.domain.com" 547 | }, 548 | ``` 549 | 550 | `enabled` - `true` to enable. 551 | 552 | `url` - Your NZBGet URL. Can be either `http://user:pass@localhost:6789` or `https://user:pass@nzbget.domain.com`. 553 | 554 | ## Sabnzbd 555 | 556 | Cloudplow can pause the Sabnzbd download queue when an upload starts; and then resume it upon the upload finishing. 557 | 558 | ``` 559 | "sabnzbd": { 560 | "enabled": false, 561 | "url": "https://sabnzbd.domain.com" 562 | "apikey": "1314234234" 563 | }, 564 | ``` 565 | 566 | `enabled` - `true` to enable. 567 | ## Plex 568 | 569 | Cloudplow can throttle Rclone uploads during active, playing Plex streams (paused streams are ignored). 570 | 571 | 572 | ``` 573 | "plex": { 574 | "enabled": true, 575 | "max_streams_before_throttle": 1, 576 | "ignore_local_streams": true, 577 | "poll_interval": 60, 578 | "notifications": false, 579 | "rclone": { 580 | "throttle_speeds": { 581 | "0": "1000M", 582 | "1": "50M", 583 | "2": "40M", 584 | "3": "30M", 585 | "4": "20M", 586 | "5": "10M" 587 | }, 588 | "url": "http://localhost:7949" 589 | }, 590 | "token": "", 591 | "url": "https://plex.domain.com" 592 | }, 593 | ``` 594 | 595 | 596 | `enabled` - `true` to enable. 597 | 598 | `url` - Your Plex URL. Can be either `http://localhost:32400` or `https://plex.domain.com`. 599 | 600 | `token` - Your Plex Access Token. 601 | 602 | - Run the Plex Token script by [Werner Beroux](https://github.com/wernight): `/opt/cloudplow/scripts/plex_token.sh`. 603 | 604 | or 605 | 606 | - Visit https://support.plex.tv/hc/en-us/articles/204059436-Finding-an-authentication-token-X-Plex-Token 607 | 608 | `poll_interval` - How often (in seconds) Plex is checked for active streams. 609 | 610 | `max_streams_before_throttle` - How many playing streams are allowed before enabling throttling. 611 | 612 | `ignore_local_streams` - Whether streaming local files should count for throttling. 613 | 614 | `notifications` - Send notifications when throttling is set, adjusted, or unset, depending on stream count. 615 | 616 | `rclone` 617 | 618 | - `url` - Leave as default. 619 | 620 | - `throttle_speed` - Categorized option to configure upload speeds for various stream counts (where `5` represents 5 streams or more). Stream count `0` represents speeds when no active stream is playing. `M` is MB/s. 621 | 622 | - Format: `"STREAM COUNT": "THROTTLED UPLOAD SPEED",` 623 | 624 | 625 | ## Remotes 626 | 627 | This is the heart of the configuration, most of the config references this section one way or another (e.g. hidden path references). 628 | 629 | You can specify more than one remote here. 630 | 631 | #### Basic 632 | 633 | ``` 634 | "remotes": { 635 | "google": { 636 | ``` 637 | 638 | Under `"remote"`, you have the name of the remote as the key (in the example above, it is `"google"`). The remote name can be anything (e.g. google1, google2, google3, dropbox1, etc). 639 | 640 | 641 | 642 | #### Hidden Cleaner 643 | 644 | ``` 645 | "remotes": { 646 | "google": { 647 | "hidden_remote": "google:", 648 | ``` 649 | 650 | 651 | `"hidden_remote"`: is the remote path where the UnionFS hidden cleaner will remove files from (if the remote is listed under the `hidden` section). 652 | 653 | #### Rclone Excludes 654 | 655 | 656 | ``` 657 | "rclone_excludes": [ 658 | "**partial~", 659 | "**_HIDDEN~", 660 | ".unionfs/**", 661 | ".unionfs-fuse/**" 662 | ], 663 | ``` 664 | 665 | These are the excludes to be used when uploading to this remote. 666 | 667 | 668 | #### Rclone Extras 669 | 670 | 671 | ``` 672 | "rclone_extras": { 673 | "--user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36", 674 | "--checkers": 16, 675 | "--drive-chunk-size": "64M", 676 | "--drive-stop-on-upload-limit": null, 677 | "--stats": "60s", 678 | "--transfers": 8, 679 | "--verbose": 1 680 | }, 681 | ``` 682 | These are Rclone parameters that will be used when uploading to this remote. You may use the given examples or add your own. 683 | 684 | Note: An argument with no value (e.g. `--no-traverse`) will be be given the value `null` (e.g. `"no-traverse": null`). 685 | 686 | 687 | #### Rclone Sleep (i.e. Ban Sleep) 688 | 689 | Format: 690 | ``` 691 | "rclone_sleeps": { 692 | "keyword or phrase to be monitored": { 693 | "count": 5, 694 | "sleep": 25, 695 | "timeout": 300 696 | } 697 | }, 698 | ``` 699 | 700 | Example: 701 | 702 | ``` 703 | "rclone_sleeps": { 704 | "Failed to copy: googleapi: Error 403: User rate limit exceeded": { 705 | "count": 5, 706 | "sleep": 25, 707 | "timeout": 300 708 | } 709 | }, 710 | ``` 711 | 712 | `"rclone_sleeps"` are keywords or phrases that are monitored during Rclone tasks that will cause this remote's upload task to abort and go into a sleep for a specified amount of time. When a remote is asleep, it will not do its regularly scheduled uploads (as defined in `check_intervals`). 713 | 714 | You may list multiple keywords or phrases here. 715 | 716 | In the example above, the phrase `"Failed to copy: googleapi: Error 403: User rate limit exceeded"` is being monitored. 717 | 718 | `"count"`: How many times this keyword/phrase has to occur within a specific time period (i.e. `timeout`), from the very first occurrence, to cause the remote to go to sleep. 719 | 720 | `"timeout"`: The time period (in seconds) during which the the phrase is counted in after its first occurrence. 721 | 722 | - On its first occurrence, the time is logged and if the `count` is reached within this `timeout` period, the upload task will abort and the remote will go into `sleep`. 723 | 724 | - If the `timeout` period expires without reaching the `count`, the `count` will reset back to `0`. 725 | 726 | - The `timeout` period will restart again after the first new occurrence of the monitored phrase. 727 | 728 | `"sleep"`: How many hours the remote goes to sleep for, when the monitored phrase is `count`-ed during the `timeout` period. 729 | 730 | #### Rclone Command 731 | ``` 732 | "rclone_command": "move", 733 | ``` 734 | This is the desired command to be used when running any Rclone uploads. Options are `move` or `copy`. Default is `move`. 735 | 736 | #### Remove Empty Directories 737 | 738 | ``` 739 | "remove_empty_dir_depth": 2, 740 | ``` 741 | This is the depth to min-depth to delete empty folders from relative to `upload_folder` (1 = `/Media/ ` ; 2 = `/Media/Movies/`; 3 = `/Media/Movies/Movies-Kids/`) 742 | 743 | 744 | ``` 745 | "upload_folder": "/mnt/local/Media/", 746 | "upload_remote": "google:/Media/" 747 | ``` 748 | 749 | #### Local/Remote Paths 750 | 751 | 752 | `"upload_folder"`: is the local path that is uploaded by the `uploader` task, once it reaches the size threshold as specified in `max_size_gb`. 753 | 754 | `"upload_remote"`: is the remote path that the `uploader` task will uploaded to. 755 | 756 | #### Sync From/To Paths 757 | 758 | `"sync_remote"`: Used by the `syncer` task. This specifies the from/to destinations used to build the Rclone command. See the [syncer](#syncer) section for more on this. 759 | 760 | ## Uploader 761 | 762 | Each entry to `uploader` references a remote inside `remotes` (i.e. the names have to match). The remote can only be referenced ONCE. 763 | 764 | If another folder needs to be uploaded, even to the same remote, then another uploader/remote combo must be created. The example at the top of this page shows 2 uploader/remote configs. 765 | 766 | If multiple uploader tasks are specified, the tasks will run sequentially (vs in parallel). 767 | 768 | ``` 769 | "uploader": { 770 | "google": { 771 | "can_be_throttled": true, 772 | "check_interval": 30, 773 | "exclude_open_files": true, 774 | "max_size_gb": 500, 775 | "opened_excludes": [ 776 | "/downloads/" 777 | ], 778 | "schedule": { 779 | "allowed_from": "04:00", 780 | "allowed_until": "08:00", 781 | "enabled": false 782 | }, 783 | "size_excludes": [ 784 | "downloads/*" 785 | ], 786 | "service_account_path":"/home/user/config/cloudplow/service_accounts/" 787 | } 788 | } 789 | ``` 790 | 791 | In the example above, the uploader references `"google"` from the `remotes` section. 792 | 793 | `"can_be_throttled"`: When this attribute is missing or set to `true`, this uploader can be throttled if enabled in the Plex config section. When set to `false`, no throttling will be attempted on this uploader. 794 | 795 | `"check_interval"`: How often (in minutes) to check the size of this remotes `upload_folder`. Once it reaches the size threshold as specified in `max_size_gb`, the uploader will start. 796 | 797 | `"exclude_open_files"`: When set to `true`, open files will be excluded from the Rclone upload (i.e. upload will occur without them). 798 | 799 | `"max_size_gb"`: Maximum size (in gigabytes) before uploading can commence 800 | 801 | `"opened_excludes"`: Paths the open file checker will check for when searching for open files. In the example above, any open files with `/downloads/` in its path, would be ignored. 802 | 803 | `"schedule"`: Allows you to specify a time period, in 24H (HH:MM) format, for when uploads are allowed to start. Uploads in progress will not stop when `allowed_until` is reached. 804 | 805 | - This setting will not affect manual uploads, only the automatic uploader in `run` mode. 806 | 807 | `"size_excludes"`: Paths that will not be counted in the total size calculation for `max_size_gb`. 808 | 809 | `"service_account_path"`: Path that will be scanned for Google Drive service account keys (\*.json) to be used when performing upload operations. 810 | 811 | - This is currently not supported with sync operations. 812 | 813 | ### Mover 814 | 815 | Move operations occur at the end of an upload task (regardless if the task was successful or aborted). 816 | 817 | Can be used to move uploads from one folder to another on the same remote (i.e. server side move) or moves between Google Team Drives and Google "My Drives" with the same ownership (for this we recommend Rclone 1.48+ with the `--drive-server-side-across-configs` argument). 818 | 819 | ```json 820 | "mover": { 821 | "enabled": true, 822 | "move_from_remote": "staging:Media", 823 | "move_to_remote": "gdrive:Media", 824 | "rclone_extras": { 825 | "--delete-empty-src-dirs": null, 826 | "--create-empty-src-dirs": null, 827 | "--stats": "60s", 828 | "--verbose": 1, 829 | "--no-traverse": null, 830 | "--drive-server-side-across-configs": null, 831 | "--user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36" 832 | } 833 | } 834 | ``` 835 | 836 | `"enabled"` - Enable or disable mover function. 837 | 838 | `"move_from_remote"` - Where to move the file/folders from. 839 | 840 | `"move_to_remote"` - Where to move the file/folders to. 841 | 842 | `"rclone_extras"` - Optional Rclone parameters. 843 | 844 | 845 | ## Syncer 846 | 847 | Each entry to the `syncer` corresponds to a single sync task. 848 | 849 | New `remotes` entries should be created for a single `syncer` task. 850 | 851 | Further documentation refers to the example configurations below. 852 | 853 | ```json 854 | "remotes": { 855 | "local_torrents": { 856 | "hidden_remote": "", 857 | "rclone_excludes": [], 858 | "rclone_extras": {}, 859 | "rclone_sleeps": { 860 | "Failed to copy: googleapi: Error 403: User rate limit exceeded": { 861 | "count": 5, 862 | "sleep": 25, 863 | "timeout": 3600 864 | }, 865 | " 0/s,": { 866 | "count": 15, 867 | "sleep": 25, 868 | "timeout": 140 869 | } 870 | }, 871 | "remove_empty_dir_depth": 2, 872 | "sync_remote": "/mnt/local/downloads/torrents", 873 | "upload_folder": "", 874 | "upload_remote": "" 875 | }, 876 | "google_torrents": { 877 | "hidden_remote": "", 878 | "rclone_excludes": [], 879 | "rclone_extras": {}, 880 | "rclone_sleeps": {}, 881 | "remove_empty_dir_depth": 2, 882 | "sync_remote": "gdrive:/downloads/torrents", 883 | "upload_folder": "", 884 | "upload_remote": "" 885 | } 886 | }, 887 | "syncer": { 888 | "torrents2google": { 889 | "rclone_extras": { 890 | "--checkers": 16, 891 | "--drive-chunk-size": "128M", 892 | "--drive-stop-on-upload-limit": null, 893 | "--stats": "60s", 894 | "--transfers": 8, 895 | "--verbose": 1, 896 | "--fast-list": null 897 | }, 898 | "service": "local", 899 | "sync_from": "local_torrents", 900 | "sync_interval": 26, 901 | "sync_to": "google_torrents", 902 | "tool_path": "/usr/bin/rclone", 903 | "use_copy": false, 904 | "instance_destroy": false 905 | } 906 | }, 907 | ``` 908 | 909 | ### Remotes 910 | 911 | ```json 912 | "remotes": { 913 | "local_torrents": { 914 | "hidden_remote": "", 915 | "rclone_excludes": [], 916 | "rclone_extras": {}, 917 | "rclone_sleeps": { 918 | "Failed to copy: googleapi: Error 403: User rate limit exceeded": { 919 | "count": 5, 920 | "sleep": 25, 921 | "timeout": 3600 922 | }, 923 | " 0/s,": { 924 | "count": 15, 925 | "sleep": 25, 926 | "timeout": 140 927 | } 928 | }, 929 | "remove_empty_dir_depth": 2, 930 | "sync_remote": "/mnt/local/downloads/torrents", 931 | "upload_folder": "", 932 | "upload_remote": "" 933 | }, 934 | "google_torrents": { 935 | "hidden_remote": "", 936 | "rclone_excludes": [], 937 | "rclone_extras": {}, 938 | "rclone_sleeps": {}, 939 | "remove_empty_dir_depth": 2, 940 | "sync_remote": "gdrive:/downloads/torrents", 941 | "upload_folder": "", 942 | "upload_remote": "" 943 | } 944 | }, 945 | ``` 946 | 947 | `sync_remote`: In the example above, there are two remote entries, both of which have `sync_remote` filled-in. This is used by the syncer task to specify the sync source and destination (i.e. `sync_remote` of `sync_from` remote is the source and `sync_remote` of `sync_to` remote is the destination). 948 | 949 | `rclone_sleeps`: Entries from both remotes are collated by the `syncer`, so there is only need for one `rclone_sleeps` to be filled in. 950 | 951 | `rclone_extras`: Are not used by the syncer. 952 | 953 | ### Syncer 954 | 955 | ```json 956 | "syncer": { 957 | "torrents2google": { 958 | "rclone_extras": { 959 | "--checkers": 16, 960 | "--drive-chunk-size": "128M", 961 | "--drive-stop-on-upload-limit": null, 962 | "--stats": "60s", 963 | "--transfers": 8, 964 | "--verbose": 1, 965 | "--fast-list": null 966 | }, 967 | "service": "local", 968 | "sync_from": "local_torrents", 969 | "sync_interval": 26, 970 | "sync_to": "google_torrents", 971 | "tool_path": "/usr/bin/rclone", 972 | "use_copy": false, 973 | "instance_destroy": false 974 | } 975 | }, 976 | ``` 977 | 978 | `"rclone_extras"`: These are extra Rclone parameters that will be passed to the Rclone sync command (the `rclone_extras` in the remote entries are not used by the syncer). 979 | 980 | `"service"`: Which syncer agent to use for the syncer task. Choices are `local` and `scaleway`. Other service providers can be added in the future. 981 | 982 | - `local`: a remote-to-remote sync that runs locally (i.e. on the same system as the one running Cloudplow). 983 | 984 | - `scaleway`: a remote-to-remote sync that runs on a Scaleway instance. Further documentation will be needed to describe the setup process. 985 | 986 | `"sync_from"`: Where the sync is coming FROM. 987 | 988 | - In the example above, this is a local torrents folder. 989 | 990 | `"sync_to"`: Where the sync is going TO. 991 | 992 | - In the example above, this is the `gdrive:/downloads/torrents` path. 993 | 994 | `"sync_interval"`: How often to execute the sync, in hours. Only applies when Cloudplow is being ran as a service (see [here](#automatic-scheduled)). 995 | 996 | `"tool_path"`: Which binary to use to execute the sync. 997 | 998 | - When using the `local` service, this will be the Rclone binary path. 999 | 1000 | - When using `scaleway`, this will be the binary path of the `scw` tool. 1001 | 1002 | `"use_copy"`: This tells the syncer to use the `rclone copy` command (vs the default `rclone sync` one). Default is `false`. 1003 | 1004 | `"instance_destroy"`: 1005 | 1006 | - When this is `true`, the instance that is created for the sync task is destroyed after the task finishes. This only applies to non-local sync services (e.g. `scaleway`). 1007 | 1008 | - When this is set to `false`, it will re-use the existing instance that was previously created/shutdown after the last sync ran. 1009 | 1010 | - Note: It is able todo this because the instances being created are named after the `syncer` task (e.g. `torrents2google` in the example above). It uses this name to determine if an instance already exists, to start/stop it, rather than destroy it. 1011 | 1012 | 1013 | # Usage 1014 | 1015 | ## Automatic (Scheduled) 1016 | 1017 | To have Cloudplow run automatically, do the following: 1018 | 1019 | 1. `sudo cp /opt/cloudplow/systemd/cloudplow.service /etc/systemd/system/` 1020 | 1021 | 2. `sudo systemctl daemon-reload` 1022 | 1023 | 3. `sudo systemctl enable cloudplow.service` 1024 | 1025 | 4. `sudo systemctl start cloudplow.service` 1026 | 1027 | ## Manual (CLI) 1028 | 1029 | Command: 1030 | ``` 1031 | cloudplow 1032 | ``` 1033 | 1034 | ``` 1035 | usage: cloudplow [-h] [--config [CONFIG]] [--logfile [LOGFILE]] 1036 | [--loglevel {WARN,INFO,DEBUG}] 1037 | {clean,upload,sync,run} 1038 | 1039 | Script to assist cloud mount users. 1040 | Can remove UnionFS hidden files from Rclone remotes, upload local content to Rclone remotes, and keep Rclone Remotes in sync. 1041 | 1042 | positional arguments: 1043 | {clean,upload,sync,run} 1044 | "clean": perform clean of UnionFS HIDDEN files from Rclone remotes 1045 | "upload": perform clean of UnionFS HIDDEN files and upload local content to Rclone remotes 1046 | "sync": perform sync between Rclone remotes 1047 | "run": starts the application in automatic mode 1048 | 1049 | optional arguments: 1050 | -h, --help show this help message and exit 1051 | --config [CONFIG] Config file location (default: /opt/cloudplow/config.json) 1052 | --logfile [LOGFILE] Log file location (default: /opt/cloudplow/cloudplow.log) 1053 | --loglevel {WARN,INFO,DEBUG} 1054 | Log level (default: INFO) 1055 | ``` 1056 | 1057 | *** 1058 | 1059 | # Donate 1060 | 1061 | If you find this project helpful, feel free to make a small donation to the developer: 1062 | 1063 | - [Monzo](https://monzo.me/today): Credit Cards, Apple Pay, Google Pay 1064 | 1065 | - [Beerpay](https://beerpay.io/l3uddz/cloudplow): Credit Cards 1066 | 1067 | - [Paypal: l3uddz@gmail.com](https://www.paypal.me/l3uddz) 1068 | 1069 | - BTC: 3CiHME1HZQsNNcDL6BArG7PbZLa8zUUgjL 1070 | -------------------------------------------------------------------------------- /assets/logo.svg: -------------------------------------------------------------------------------- 1 | logo -------------------------------------------------------------------------------- /config.json.sample: -------------------------------------------------------------------------------- 1 | { 2 | "core": { 3 | "dry_run": false, 4 | "rclone_binary_path": "/usr/bin/rclone", 5 | "rclone_config_path": "/home/user/.config/rclone/rclone.conf" 6 | }, 7 | "hidden": { 8 | "/mnt/local/.unionfs-fuse": { 9 | "hidden_remotes": [ 10 | "google" 11 | ] 12 | } 13 | }, 14 | "notifications": { 15 | }, 16 | "nzbget": { 17 | "enabled": false, 18 | "url": "https://user:pass@nzbget.domain.com" 19 | }, 20 | "sabnzbd": { 21 | "enabled": false, 22 | "url": "https://sabnzbd.domain.com", 23 | "apikey": "1314234234" 24 | }, 25 | "plex": { 26 | "enabled": false, 27 | "url": "http://localhost:32400", 28 | "token": "", 29 | "poll_interval": 60, 30 | "max_streams_before_throttle": 1, 31 | "ignore_local_streams": true, 32 | "notifications": false, 33 | "rclone": { 34 | "throttle_speeds": { 35 | "0": "100M", 36 | "1": "50M", 37 | "2": "40M", 38 | "3": "30M", 39 | "4": "20M", 40 | "5": "10M" 41 | }, 42 | "url": "http://localhost:7949" 43 | } 44 | }, 45 | "remotes": { 46 | "google": { 47 | "hidden_remote": "google:", 48 | "rclone_excludes": [ 49 | "**partial~", 50 | "**_HIDDEN~", 51 | ".unionfs/**", 52 | ".unionfs-fuse/**", 53 | "**.fuse_hidden**" 54 | ], 55 | "rclone_extras": { 56 | "--checkers": 16, 57 | "--drive-chunk-size": "64M", 58 | "--stats": "60s", 59 | "--transfers": 8, 60 | "--verbose": 1, 61 | "--skip-links": null, 62 | "--drive-stop-on-upload-limit": null, 63 | "--user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36" 64 | }, 65 | "rclone_sleeps": { 66 | "Failed to copy: googleapi: Error 403: User rate limit exceeded": { 67 | "count": 5, 68 | "sleep": 25, 69 | "timeout": 3600 70 | }, 71 | " 0/s,": { 72 | "count": 15, 73 | "sleep": 25, 74 | "timeout": 140 75 | } 76 | }, 77 | "rclone_command":"move", 78 | "remove_empty_dir_depth": 2, 79 | "sync_remote": "google:/Media", 80 | "upload_folder": "/mnt/local/Media", 81 | "upload_remote": "google:/Media" 82 | } 83 | }, 84 | "syncer": { 85 | }, 86 | "uploader": { 87 | "google": { 88 | "can_be_throttled": true, 89 | "check_interval": 30, 90 | "exclude_open_files": true, 91 | "max_size_gb": 200, 92 | "opened_excludes": [ 93 | "/downloads/" 94 | ], 95 | "schedule": { 96 | "allowed_from": "04:00", 97 | "allowed_until": "08:00", 98 | "enabled": false 99 | }, 100 | "size_excludes": [ 101 | "downloads/*" 102 | ], 103 | "service_account_path":"/home/user/.config/cloudplow/service_accounts/", 104 | "mover": { 105 | "enabled": false, 106 | "move_from_remote": "staging:Media", 107 | "move_to_remote": "gdrive:Media", 108 | "rclone_extras": { 109 | "--delete-empty-src-dirs": null, 110 | "--create-empty-src-dirs": null, 111 | "--stats": "60s", 112 | "--verbose": 1, 113 | "--no-traverse": null, 114 | "--drive-server-side-across-configs": null, 115 | "--user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36" 116 | } 117 | } 118 | } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | lockfile~=0.12.2 2 | schedule==1.2.0 3 | requests==2.31.0 4 | GitPython==3.1.32 5 | sqlitedict==2.1.0 6 | apprise 7 | jsonpickle==3.0.1 8 | urllib3==2.0.4 9 | -------------------------------------------------------------------------------- /scripts/plex_token.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | ######################################################################### 3 | # Title: Retrieve Plex Token # 4 | # Author(s): Werner Beroux (https://github.com/wernight) # 5 | # URL: https://github.com/wernight/docker-plex-media-server # 6 | # Description: Prompts for Plex login and prints Plex access token. # 7 | ######################################################################### 8 | # MIT License # 9 | ######################################################################### 10 | 11 | if [ -z "$PLEX_LOGIN" ] || [ -z "$PLEX_PASSWORD" ]; then 12 | PLEX_LOGIN=$1 13 | PLEX_PASSWORD=$2 14 | fi 15 | 16 | while [ -z "$PLEX_LOGIN" ]; do 17 | >&2 echo -n 'Your Plex login (e-mail or username): ' 18 | read PLEX_LOGIN 19 | done 20 | 21 | while [ -z "$PLEX_PASSWORD" ]; do 22 | >&2 echo -n 'Your Plex password: ' 23 | read PLEX_PASSWORD 24 | done 25 | 26 | >&2 echo 'Retrieving a X-Plex-Token using Plex login/password...' 27 | 28 | curl -qu "${PLEX_LOGIN}":"${PLEX_PASSWORD}" 'https://plex.tv/users/sign_in.xml' \ 29 | -X POST -H 'X-Plex-Device-Name: PlexMediaServer' \ 30 | -H 'X-Plex-Provides: server' \ 31 | -H 'X-Plex-Version: 0.9' \ 32 | -H 'X-Plex-Platform-Version: 0.9' \ 33 | -H 'X-Plex-Platform: xcid' \ 34 | -H 'X-Plex-Product: Plex Media Server'\ 35 | -H 'X-Plex-Device: Linux'\ 36 | -H 'X-Plex-Client-Identifier: XXXX' --compressed >/tmp/plex_sign_in 37 | X_PLEX_TOKEN=$(sed -n 's/.*\(.*\)<\/authentication-token>.*/\1/p' /tmp/plex_sign_in) 38 | if [ -z "$X_PLEX_TOKEN" ]; then 39 | cat /tmp/plex_sign_in 40 | rm -f /tmp/plex_sign_in 41 | >&2 echo 'Failed to retrieve the X-Plex-Token.' 42 | exit 1 43 | fi 44 | rm -f /tmp/plex_sign_in 45 | 46 | >&2 echo "Your X_PLEX_TOKEN:" 47 | 48 | echo $X_PLEX_TOKEN 49 | -------------------------------------------------------------------------------- /systemd/cloudplow.service: -------------------------------------------------------------------------------- 1 | # /etc/systemd/system/cloudplow.service 2 | 3 | [Unit] 4 | Description=cloudplow 5 | After=network-online.target 6 | 7 | [Service] 8 | User=seed 9 | Group=seed 10 | Type=simple 11 | WorkingDirectory=/opt/cloudplow/ 12 | ExecStart=/usr/bin/python3 /opt/cloudplow/cloudplow.py run --loglevel=INFO 13 | ExecStopPost=/bin/rm -rf /opt/cloudplow/locks 14 | Restart=always 15 | RestartSec=10 16 | 17 | [Install] 18 | WantedBy=default.target 19 | -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/l3uddz/cloudplow/4a4e9cf7579ce4ba91761c12ad1bc88ae2707f8c/utils/__init__.py -------------------------------------------------------------------------------- /utils/cache.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | 4 | from sqlitedict import SqliteDict 5 | 6 | log = logging.getLogger('cache') 7 | 8 | 9 | class Cache: 10 | def __init__(self, cache_file_path): 11 | self.cache_file_path = cache_file_path 12 | self.caches = { 13 | 'uploader_bans': SqliteDict(self.cache_file_path, tablename='uploader_bans', encode=json.dumps, 14 | decode=json.loads, autocommit=True), 15 | 'syncer_bans': SqliteDict(self.cache_file_path, tablename='syncer_bans', encode=json.dumps, 16 | decode=json.loads, autocommit=True), 17 | 'sa_bans': SqliteDict(self.cache_file_path, tablename='sa_bans', encode=json.dumps, 18 | decode=json.loads, autocommit=True) 19 | } 20 | 21 | def get_cache(self, cache_name): 22 | return None if cache_name not in self.caches else self.caches[cache_name] 23 | -------------------------------------------------------------------------------- /utils/config.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import json 3 | import logging 4 | import os 5 | import sys 6 | from copy import copy 7 | 8 | log = logging.getLogger('config') 9 | 10 | 11 | class Singleton(type): 12 | _instances = {} 13 | 14 | def __call__(cls, *args, **kwargs): 15 | if cls not in cls._instances: 16 | cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) 17 | 18 | return cls._instances[cls] 19 | 20 | 21 | class Config(object): 22 | __metaclass__ = Singleton 23 | 24 | base_config = { 25 | # core settings 26 | 'core': { 27 | 'dry_run': False, 28 | 'rclone_binary_path': '/usr/bin/rclone', 29 | 'rclone_config_path': '/home/seed/.config/rclone/rclone.conf' 30 | }, 31 | # hidden cleaner settings 32 | 'hidden': { 33 | }, 34 | # uploader settings 35 | 'uploader': { 36 | }, 37 | # rclone settings 38 | 'remotes': { 39 | }, 40 | # syncer settings 41 | 'syncer': { 42 | }, 43 | # notification settings 44 | 'notifications': { 45 | }, 46 | # plex settings 47 | 'plex': { 48 | 'enabled': False, 49 | 'url': 'https://plex.domain.com', 50 | 'token': '', 51 | 'poll_interval': 60, 52 | 'max_streams_before_throttle': 1, 53 | 'ignore_local_streams': True, 54 | 'notifications': False, 55 | 'rclone': { 56 | 'url': 'http://localhost:7949', 57 | 'throttle_speeds': { 58 | '1': '50M', 59 | '2': '40M', 60 | '3': '30M', 61 | '4': '20M', 62 | '5': '10M' 63 | } 64 | } 65 | }, 66 | # nzbget settings 67 | 'nzbget': { 68 | 'enabled': False, 69 | 'url': 'https://user:password@nzbget.domain.com' 70 | }, 71 | # sabnzbd settings 72 | 'sabnzbd': { 73 | 'enabled': False, 74 | 'url': 'https://sabnzbd.domain.com', 75 | 'apikey': '' 76 | } 77 | } 78 | 79 | base_settings = { 80 | 'config': { 81 | 'argv': '--config', 82 | 'env': 'CLOUDPLOW_CONFIG', 83 | 'default': os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), 'config.json') 84 | }, 85 | 'logfile': { 86 | 'argv': '--logfile', 87 | 'env': 'CLOUDPLOW_LOGFILE', 88 | 'default': os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), 'cloudplow.log') 89 | }, 90 | 'cachefile': { 91 | 'argv': '--cachefile', 92 | 'env': 'CLOUDPLOW_CACHEFILE', 93 | 'default': os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), 'cache.db') 94 | }, 95 | 'loglevel': { 96 | 'argv': '--loglevel', 97 | 'env': 'CLOUDPLOW_LOGLEVEL', 98 | 'default': 'INFO' 99 | } 100 | } 101 | 102 | def __init__(self): 103 | """Initializes config""" 104 | # Args and settings 105 | self.args = self.parse_args() 106 | self.settings = self.get_settings() 107 | # Configs 108 | self.configs = None 109 | 110 | @property 111 | def default_config(self): 112 | cfg = self.base_config.copy() 113 | 114 | # add example remote 115 | cfg['remotes'] = { 116 | 'google': { 117 | 'upload_folder': '/mnt/local/Media', 118 | 'upload_remote': 'google:/Media', 119 | 'hidden_remote': 'google:', 120 | 'sync_remote': 'google:/Media', 121 | 'rclone_command': 'move', 122 | 'rclone_excludes': [ 123 | '**partial~', 124 | '**_HIDDEN~', 125 | '.unionfs/**', 126 | '.unionfs-fuse/**', 127 | ], 128 | 'rclone_extras': { 129 | '--drive-chunk-size': '64M', 130 | '--transfers': 8, 131 | '--checkers': 16, 132 | '--stats': '60s', 133 | '--verbose': 1, 134 | '--skip-links': None, 135 | '--user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 ' 136 | '(KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36' 137 | }, 138 | 'rclone_sleeps': { 139 | 'Failed to copy: googleapi: Error 403: User rate limit exceeded': { 140 | 'count': 5, 141 | 'timeout': 3600, 142 | 'sleep': 25 143 | } 144 | }, 145 | 'remove_empty_dir_depth': 2 146 | } 147 | } 148 | 149 | # add example uploader 150 | cfg['uploader'] = { 151 | 'google': { 152 | 'can_be_throttled': True, 153 | 'check_interval': 30, 154 | 'max_size_gb': 200, 155 | 'size_excludes': [ 156 | 'downloads/*' 157 | ], 158 | 'opened_excludes': [ 159 | '/downloads/' 160 | ], 161 | 'exclude_open_files': True, 162 | 'schedule': { 163 | 'enabled': False, 164 | 'allowed_from': '04:00', 165 | 'allowed_until': '08:00' 166 | } 167 | } 168 | } 169 | 170 | # add example hidden 171 | cfg['hidden'] = { 172 | '/mnt/local/.unionfs-fuse': { 173 | 'hidden_remotes': ['google'] 174 | } 175 | } 176 | 177 | return cfg 178 | 179 | def __inner_upgrade(self, settings1, settings2, key=None, overwrite=False): 180 | sub_upgraded = False 181 | merged = copy(settings2) 182 | 183 | if isinstance(settings1, dict): 184 | for k, v in settings1.items(): 185 | # missing k 186 | if k not in settings2: 187 | merged[k] = v 188 | sub_upgraded = True 189 | if not key: 190 | log.info(f"Added {k} config option: {v}") 191 | else: 192 | log.info(f"Added {k} to config option {key}: {v}") 193 | continue 194 | 195 | # iterate children 196 | if isinstance(v, (dict, list)): 197 | merged[k], did_upgrade = self.__inner_upgrade(settings1[k], settings2[k], key=k, 198 | overwrite=overwrite) 199 | sub_upgraded = did_upgrade or sub_upgraded 200 | elif settings1[k] != settings2[k] and overwrite: 201 | merged = settings1 202 | sub_upgraded = True 203 | elif isinstance(settings1, list) and key: 204 | for v in settings1: 205 | if v not in settings2: 206 | merged.append(v) 207 | sub_upgraded = True 208 | log.info(f"Added to config option {key}: {v}") 209 | continue 210 | 211 | return merged, sub_upgraded 212 | 213 | def upgrade_settings(self, currents): 214 | fields_env = {} 215 | 216 | # ENV gets priority: ENV > config.json 217 | for name, data in self.base_config.items(): 218 | if name in os.environ: 219 | # Use JSON decoder to get same behaviour as config file 220 | fields_env[name] = json.JSONDecoder().decode(os.environ[name]) 221 | log.info(f"Using ENV setting {name}={fields_env[name]}") 222 | 223 | # Update in-memory config with environment settings 224 | currents.update(fields_env) 225 | 226 | # Do inner upgrade 227 | upgraded_settings, upgraded = self.__inner_upgrade(self.base_config, currents) 228 | return upgraded_settings, upgraded 229 | 230 | def upgrade(self, cfg): 231 | fields = [] 232 | fields_env = {} 233 | 234 | # ENV gets priority: ENV < config.json 235 | for name, data in self.base_config.items(): 236 | if name not in cfg: 237 | cfg[name] = data 238 | fields.append(name) 239 | 240 | if name in os.environ: 241 | # Use JSON decoder to get same behaviour as config file 242 | fields_env[name] = json.JSONDecoder().decode(os.environ[name]) 243 | log.info(f"Using ENV setting {name}={fields_env[name]}") 244 | 245 | # Only rewrite config file if new fields added 246 | if len(fields): 247 | log.info(f"Upgraded config. Added {len(fields)} new field(s): {fields}") 248 | self.save(cfg) 249 | 250 | # Update in-memory config with environment settings 251 | cfg.update(fields_env) 252 | 253 | return cfg 254 | 255 | def load(self): 256 | if not os.path.exists(self.settings['config']): 257 | log.warning("No config file found, creating default config.") 258 | self.save(self.default_config) 259 | 260 | log.debug("Upgrading config...") 261 | with open(self.settings['config'], 'r') as fp: 262 | cfg, upgraded = self.upgrade_settings(json.load(fp)) 263 | 264 | # Save config if upgraded 265 | if upgraded: 266 | self.save(cfg) 267 | exit(0) 268 | else: 269 | log.debug("Config was not upgraded as there were no changes to add.") 270 | 271 | self.configs = cfg 272 | 273 | def save(self, cfg): 274 | with open(self.settings['config'], 'w') as fp: 275 | json.dump(cfg, fp, indent=4, sort_keys=True) 276 | log.info(f"Your config was upgraded. You may check the changes here: {self.settings['config']}") 277 | 278 | exit(0) 279 | 280 | def get_settings(self): 281 | setts = {} 282 | for name, data in self.base_settings.items(): 283 | # Argrument priority: cmd < environment < default 284 | try: 285 | # Command line argument 286 | if self.args[name]: 287 | value = self.args[name] 288 | log.info(f"Using ARG setting {name}={value}") 289 | 290 | elif data['env'] in os.environ: 291 | value = os.environ[data['env']] 292 | log.debug(f"Using ENV setting {data['env']}={value}") 293 | 294 | else: 295 | value = data['default'] 296 | log.debug(f"Using default setting {data['argv']}={value}") 297 | 298 | setts[name] = value 299 | 300 | except Exception: 301 | log.exception(f"Exception retrieving setting value: {name}") 302 | 303 | return setts 304 | 305 | # Parse command line arguments 306 | def parse_args(self): 307 | parser = argparse.ArgumentParser( 308 | description=( 309 | 'Script to assist cloud mount users. \n' 310 | 'Can remove UnionFS hidden files from Rclone remotes, ' 311 | 'upload local content to Rclone remotes, and keep Rclone remotes in sync.' 312 | ), 313 | formatter_class=argparse.RawTextHelpFormatter 314 | ) 315 | 316 | # Mode 317 | parser.add_argument('cmd', 318 | choices=('clean', 'upload', 'sync', 'run', 'update_config'), 319 | help=( 320 | '"clean": perform clean of UnionFS HIDDEN files from Rclone remotes\n' 321 | '"upload": perform clean of UnionFS HIDDEN files and upload local content to Rclone remotes\n' 322 | '"sync": perform sync between Rclone remotes\n' 323 | '"run": starts the application in automatic mode\n' 324 | '"update_config": perform simple update of config' 325 | ) 326 | ) 327 | 328 | # Config file 329 | parser.add_argument(self.base_settings['config']['argv'], nargs='?', const=None, 330 | help=f"Config file location (default: {self.base_settings['config']['default']})") 331 | 332 | # Log file 333 | parser.add_argument(self.base_settings['logfile']['argv'], nargs='?', const=None, 334 | help=f"Log file location (default: {self.base_settings['logfile']['default']})") 335 | 336 | # Cache file 337 | parser.add_argument(self.base_settings['cachefile']['argv'], nargs='?', const=None, 338 | help=f"Cache file location (default: {self.base_settings['cachefile']['default']})") 339 | 340 | # Logging level 341 | parser.add_argument(self.base_settings['loglevel']['argv'], choices=('WARN', 'INFO', 'DEBUG'), 342 | help=f"Log level (default: {self.base_settings['loglevel']['default']})") 343 | 344 | if len(sys.argv) != 1: 345 | return vars(parser.parse_args()) 346 | parser.print_help() 347 | 348 | sys.exit(0) 349 | -------------------------------------------------------------------------------- /utils/decorators.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import timeit 4 | 5 | from . import misc 6 | 7 | log = logging.getLogger("decorators") 8 | 9 | 10 | def timed(method): 11 | def timer(*args, **kw): 12 | start_time = timeit.default_timer() 13 | result = method(*args, **kw) 14 | time_taken = timeit.default_timer() - start_time 15 | try: 16 | log.info(f"{method.__name__} from {os.path.basename(method.__code__.co_filename)} finished in {misc.seconds_to_string(time_taken)}") 17 | except Exception: 18 | log.exception("Exception while logging time taken to run function: ") 19 | return result 20 | 21 | return timer 22 | -------------------------------------------------------------------------------- /utils/lock.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import sys 4 | 5 | import lockfile 6 | 7 | log = logging.getLogger("lock") 8 | lock_folder = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), 'locks') 9 | 10 | 11 | def ensure_lock_folder(): 12 | # ensure lock folder exists, otherwise create it 13 | try: 14 | if not os.path.exists(lock_folder): 15 | os.mkdir(lock_folder) 16 | log.info(f"Created lock folder: {lock_folder}") 17 | except Exception: 18 | log.exception(f"Exception verifying/creating lock folder {lock_folder}: ") 19 | sys.exit(1) 20 | 21 | 22 | def upload(): 23 | return lockfile.LockFile(os.path.join(lock_folder, 'upload')) 24 | 25 | 26 | def sync(): 27 | return lockfile.LockFile(os.path.join(lock_folder, 'sync')) 28 | 29 | 30 | def hidden(): 31 | return lockfile.LockFile(os.path.join(lock_folder, 'hidden')) 32 | -------------------------------------------------------------------------------- /utils/misc.py: -------------------------------------------------------------------------------- 1 | import contextlib 2 | import logging 3 | import re 4 | import time 5 | 6 | log = logging.getLogger("misc") 7 | 8 | 9 | def get_lowest_remaining_time(data): 10 | sorted_data = sorted(data.items(), key=lambda x: x[1]) 11 | return sorted_data[0][1] 12 | 13 | 14 | def seconds_to_string(seconds): 15 | """ reference: https://codereview.stackexchange.com/a/120595 """ 16 | resp = '' 17 | try: 18 | minutes, seconds = divmod(seconds, 60) 19 | hours, minutes = divmod(minutes, 60) 20 | days, hours = divmod(hours, 24) 21 | if days: 22 | resp += f'{days} days' 23 | if hours: 24 | if len(resp): 25 | resp += ', ' 26 | resp += f'{hours} hours' 27 | if minutes: 28 | if len(resp): 29 | resp += ', ' 30 | resp += f'{minutes} minutes' 31 | if seconds: 32 | if len(resp): 33 | resp += ' and ' 34 | resp += f'{seconds} seconds' 35 | except Exception: 36 | log.exception(f"Exception occurred converting {seconds} seconds to readable string: ") 37 | resp = f'{seconds} seconds' 38 | return resp 39 | 40 | 41 | def merge_dicts(*dicts): 42 | """ reference: https://stackoverflow.com/a/24745412 """ 43 | d = {} 44 | for dict in dicts: 45 | for key in dict: 46 | with contextlib.suppress(KeyError): 47 | d[key] = dict[key] 48 | return d 49 | 50 | 51 | def get_nearest_less_element(data, num): 52 | """ reference: https://stackoverflow.com/a/7934624 """ 53 | return data[str(num)] if str(num) in data else data[min(data.keys(), key=lambda k: abs(int(k) - num))] 54 | 55 | 56 | def is_time_between(time_range, current_time=None): 57 | """ reference: https://stackoverflow.com/a/45265202 """ 58 | if not current_time: 59 | current_time = time.strftime('%H:%M') 60 | 61 | try: 62 | if time_range[1] < time_range[0]: 63 | return current_time >= time_range[0] or current_time <= time_range[1] 64 | return time_range[0] <= current_time <= time_range[1] 65 | except Exception: 66 | log.exception("Exception determining if current time was between the supplied range: ") 67 | return True 68 | 69 | 70 | def sorted_list_by_digit_asc(list_to_sort): 71 | """ reference: https://stackoverflow.com/a/46772952 """ 72 | return sorted(list_to_sort, key=lambda x: [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', x) if s]) 73 | -------------------------------------------------------------------------------- /utils/notifications/__init__.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from .apprise import Apprise 4 | from .pushover import Pushover 5 | from .slack import Slack 6 | 7 | log = logging.getLogger("notifications") 8 | 9 | SERVICES = { 10 | 'apprise': Apprise, 11 | 'pushover': Pushover, 12 | 'slack': Slack 13 | } 14 | 15 | 16 | class Notifications: 17 | def __init__(self): 18 | self.services = [] 19 | 20 | def load(self, **kwargs): 21 | if 'service' not in kwargs: 22 | log.error("You must specify a service to load with the service parameter") 23 | return False 24 | elif kwargs['service'] not in SERVICES: 25 | log.error("You specified an invalid service to load: %s", kwargs['service']) 26 | return False 27 | 28 | try: 29 | chosen_service = SERVICES[kwargs['service']] 30 | del kwargs['service'] 31 | 32 | # load service 33 | service = chosen_service(**kwargs) 34 | self.services.append(service) 35 | 36 | except Exception: 37 | log.exception("Exception while loading service, kwargs=%r: ", kwargs) 38 | 39 | def send(self, **kwargs): 40 | try: 41 | # remove service keyword if supplied 42 | if 'service' in kwargs: 43 | # send notification to specified service 44 | chosen_service = kwargs['service'].lower() 45 | del kwargs['service'] 46 | else: 47 | chosen_service = None 48 | 49 | # send notification(s) 50 | for service in self.services: 51 | if chosen_service and service.NAME.lower() != chosen_service: 52 | continue 53 | elif service.send(**kwargs): 54 | log.info("Sent notification with %s", service.NAME) 55 | except Exception: 56 | log.exception("Exception sending notification, kwargs=%r: ", kwargs) 57 | -------------------------------------------------------------------------------- /utils/notifications/apprise.py: -------------------------------------------------------------------------------- 1 | import apprise 2 | 3 | import logging 4 | 5 | log = logging.getLogger('apprise') 6 | 7 | 8 | class Apprise: 9 | NAME = "Apprise" 10 | 11 | def __init__(self, url, title='Cloudplow'): 12 | self.url = url 13 | self.title = title 14 | log.debug("Initialized Apprise notification agent") 15 | 16 | def send(self, **kwargs): 17 | if not self.url: 18 | log.error("You must specify a URL when initializing this class") 19 | return False 20 | 21 | # send notification 22 | try: 23 | apobj = apprise.Apprise() 24 | apobj.add(self.url) 25 | apobj.notify( 26 | title=self.title, 27 | body=kwargs['message'], 28 | ) 29 | 30 | except Exception: 31 | log.exception(f"Error sending notification to {self.url}") 32 | return False 33 | -------------------------------------------------------------------------------- /utils/notifications/pushover.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import requests 4 | 5 | logging.getLogger("requests").setLevel(logging.WARNING) 6 | log = logging.getLogger("pushover") 7 | 8 | 9 | class Pushover: 10 | NAME = "Pushover" 11 | 12 | def __init__(self, app_token, user_token, priority=0): 13 | self.app_token = app_token 14 | self.user_token = user_token 15 | self.priority = priority 16 | log.info("Initialized Pushover notification agent") 17 | 18 | def send(self, **kwargs): 19 | if not self.app_token or not self.user_token: 20 | log.error("You must specify an app_token and user_token when initializing this class") 21 | return False 22 | 23 | # send notification 24 | try: 25 | payload = { 26 | 'token': self.app_token, 27 | 'user': self.user_token, 28 | 'priority': self.priority, 29 | 'message': kwargs['message'], 30 | } 31 | resp = requests.post('https://api.pushover.net/1/messages.json', data=payload, timeout=30) 32 | return resp.status_code == 200 33 | 34 | except Exception: 35 | log.exception(f"Error sending notification to {self.user_token}") 36 | return False 37 | -------------------------------------------------------------------------------- /utils/notifications/slack.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import requests 4 | 5 | logging.getLogger("requests").setLevel(logging.WARNING) 6 | log = logging.getLogger("slack") 7 | 8 | 9 | class Slack: 10 | NAME = "Slack" 11 | 12 | def __init__(self, webhook_url, sender_name='Cloudplow', sender_icon=':heavy_exclamation_mark:', channel=None): 13 | self.webhook_url = webhook_url 14 | self.sender_name = sender_name 15 | self.sender_icon = sender_icon 16 | self.channel = channel 17 | log.info("Initialized Slack notification agent") 18 | 19 | def send(self, **kwargs): 20 | if not self.webhook_url or not self.sender_name or not self.sender_icon: 21 | log.error("You must specify an webhook_url, sender_name and sender_icon when initializing this class") 22 | return False 23 | 24 | # send notification 25 | try: 26 | payload = { 27 | 'text': kwargs['message'], 28 | 'username': self.sender_name, 29 | 'icon_emoji': self.sender_icon, 30 | } 31 | if self.channel: 32 | payload['channel'] = self.channel 33 | 34 | resp = requests.post(self.webhook_url, json=payload, timeout=30) 35 | return resp.status_code == 200 36 | 37 | except Exception: 38 | log.exception(f"Error sending notification to {self.webhook_url}") 39 | return False 40 | -------------------------------------------------------------------------------- /utils/nzbget.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from .xmlrpc import ServerProxy 4 | 5 | log = logging.getLogger(__name__) 6 | 7 | 8 | class Nzbget: 9 | def __init__(self, url): 10 | self.url = f"{url}/xmlrpc" 11 | self.xmlrpc = ServerProxy(self.url) 12 | 13 | def pause_queue(self): 14 | paused = False 15 | try: 16 | with self.xmlrpc as proxy: 17 | paused = proxy.pausedownload() 18 | except Exception: 19 | log.exception("Exception pausing NzbGet queue: ") 20 | return paused 21 | 22 | def resume_queue(self): 23 | resumed = False 24 | try: 25 | with self.xmlrpc as proxy: 26 | resumed = proxy.resumedownload() 27 | except Exception: 28 | log.exception("Exception resuming NzbGet queue: ") 29 | return resumed 30 | -------------------------------------------------------------------------------- /utils/path.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import os 3 | from pathlib import Path 4 | 5 | from . import process 6 | 7 | try: 8 | from shlex import quote as cmd_quote 9 | except ImportError: 10 | from pipes import quote as cmd_quote 11 | 12 | import logging 13 | 14 | log = logging.getLogger('path') 15 | 16 | 17 | def get_file_extension(filepath): 18 | extensions = Path(filepath).suffixes 19 | extension = ''.join(extensions).lstrip('.') 20 | return extension.lower() 21 | 22 | 23 | def get_file_hash(filepath): 24 | # get file size for hash 25 | file_size = 0 26 | try: 27 | file_size = os.path.getsize(filepath) 28 | except Exception: 29 | log.exception(f"Exception getting file size of {filepath}: ") 30 | # set basic string to use for hash 31 | key = "{filename}-{size}".format(filename=os.path.basename(filepath), size=file_size) 32 | return hashlib.md5(key.encode('utf-8')).hexdigest() 33 | 34 | 35 | def find_items(folder, extension=None, depth=None): 36 | folder_list = [] 37 | start_count = folder.count(os.sep) 38 | for path, subdirs, files in os.walk(folder, topdown=True): 39 | for name in subdirs: 40 | if depth and path.count(os.sep) - start_count >= depth: 41 | del subdirs[:] 42 | continue 43 | filepath = os.path.join(path, name) 44 | if not extension: 45 | folder_list.append(filepath) 46 | elif filepath.lower().endswith(extension.lower()): 47 | folder_list.append(filepath) 48 | return sorted(folder_list, key=lambda x: x.count(os.path.sep), reverse=True) 49 | 50 | 51 | def opened_files(path): 52 | files = [] 53 | 54 | try: 55 | process = os.popen(f'lsof -wFn +D {cmd_quote(path)} | tail -n +2 | cut -c2-') 56 | data = process.read() 57 | files.extend(item for item in data.split('\n') if item and len(item) > 3 and not item.isdigit() and os.path.isfile(item)) 58 | 59 | return files 60 | 61 | except Exception: 62 | log.exception(f"Exception retrieving open files from {path}: ") 63 | return [] 64 | 65 | 66 | def delete(path): 67 | if isinstance(path, list): 68 | for item in path: 69 | if os.path.exists(item): 70 | log.debug("Removing %r", item) 71 | try: 72 | if not os.path.isdir(item): 73 | os.remove(item) 74 | else: 75 | os.rmdir(item) 76 | except Exception: 77 | log.exception("Exception deleting '%s': ", item) 78 | else: 79 | log.debug("Skipping deletion of '%s' as it does not exist", item) 80 | elif os.path.exists(path): 81 | log.debug("Removing %r", path) 82 | try: 83 | if not os.path.isdir(path): 84 | os.remove(path) 85 | else: 86 | os.rmdir(path) 87 | except Exception: 88 | log.exception("Exception deleting '%s': ", path) 89 | else: 90 | log.debug("Skipping deletion of '%s' as it does not exist", path) 91 | 92 | 93 | def remove_empty_dirs(path, depth): 94 | if os.path.exists(path): 95 | log.debug("Removing empty directories from '%s' with mindepth %d", path, depth) 96 | cmd = 'find %s -mindepth %d -type d -empty -delete' % (cmd_quote(path), depth) 97 | try: 98 | log.debug("Using: %s", cmd) 99 | process.execute(cmd, logs=False) 100 | return True 101 | except Exception: 102 | log.exception("Exception while removing empty directories from '%s': ", path) 103 | return False 104 | else: 105 | log.error("Cannot remove empty directories from '%s' as it does not exist", path) 106 | return False 107 | 108 | 109 | def get_size(path, excludes=None): 110 | try: 111 | cmd = "du -s --block-size=1G" 112 | if excludes: 113 | for item in excludes: 114 | cmd += f' --exclude={cmd_quote(item)}' 115 | cmd += f' {cmd_quote(path)} | cut -f1' 116 | log.debug("Using: %s", cmd) 117 | # get size 118 | proc = os.popen(cmd) 119 | data = proc.read().strip("\n") 120 | proc.close() 121 | return int(data) if data.isdigit() else 0 122 | except Exception: 123 | log.exception("Exception getting size of %r: ", path) 124 | return 0 125 | -------------------------------------------------------------------------------- /utils/plex.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import platform 3 | from urllib.parse import urljoin 4 | from uuid import getnode 5 | 6 | import requests 7 | import urllib3 8 | log = logging.getLogger('plex') 9 | urllib3.disable_warnings() 10 | 11 | 12 | class Plex: 13 | def __init__(self, url, token): 14 | self.url = url 15 | self.token = token 16 | self.headers = {'X-Plex-Token': self.token, 17 | 'Accept': 'application/json', 18 | 'X-Plex-Provides': 'controller', 19 | 'X-Plex-Platform': platform.uname()[0], 20 | 'X-Plex-Platform-Version': platform.uname()[2], 21 | 'X-Plex-Product': 'cloudplow', 22 | 'X-Plex-Version': '0.9.5', 23 | 'X-Plex-Device': platform.platform(), 24 | 'X-Plex-Client-Identifier': hex(getnode())} 25 | 26 | def validate(self): 27 | try: 28 | request_url = urljoin(self.url, 'status/sessions') 29 | r = requests.get(request_url, headers=self.headers, timeout=15, verify=False) 30 | if r.status_code == 200 and r.headers['Content-Type'] == 'application/json': 31 | log.debug(f"Server responded with status_code={r.status_code}, content: {r.json()}") 32 | return True 33 | else: 34 | log.error(f"Server responded with status_code={r.status_code}, content: {r.content}") 35 | return False 36 | except Exception: 37 | log.exception(f"Exception validating server token={self.token}, url={self.url}: ") 38 | return False 39 | 40 | def get_streams(self): 41 | request_url = urljoin(self.url, 'status/sessions') 42 | try: 43 | r = requests.get(request_url, headers=self.headers, timeout=15, verify=False) 44 | if r.status_code == 200 and r.headers['Content-Type'] == 'application/json': 45 | result = r.json() 46 | log.debug(f"Server responded with status_code={r.status_code}, content: {r.content}") 47 | 48 | if 'MediaContainer' not in result: 49 | log.error(f"Failed to retrieve streams from server at {self.url}") 50 | return None 51 | elif 'Video' not in result['MediaContainer'] and 'Metadata' not in result['MediaContainer']: 52 | log.debug(f"There were no streams to check for server at {self.url}") 53 | return [] 54 | 55 | return [ 56 | PlexStream(stream) 57 | for stream in result['MediaContainer'][ 58 | 'Video' 59 | if 'Video' in result['MediaContainer'] 60 | else 'Metadata' 61 | ] 62 | ] 63 | 64 | else: 65 | log.error(f"Server url or token was invalid, token={self.token}, request_url={request_url}, status_code={r.status_code}, content: {r.content}") 66 | return None 67 | except Exception: 68 | log.exception(f"Exception retrieving streams from request_url={request_url}, token={self.token}: ") 69 | return None 70 | 71 | 72 | # helper classes (parsing responses etc...) 73 | class PlexStream: 74 | def __init__(self, stream): 75 | self.user = stream['User']['title'] if 'User' in stream else 'Unknown' 76 | if 'Player' in stream: 77 | self.player = stream['Player']['product'] 78 | self.state = stream['Player']['state'] 79 | self.local = stream['Player']['local'] 80 | else: 81 | self.player = 'Unknown' 82 | self.ip = 'Unknown' 83 | self.state = 'Unknown' 84 | self.local = None 85 | 86 | self.session_id = stream['Session']['id'] if 'Session' in stream else 'Unknown' 87 | if 'Media' in stream: 88 | self.type = self.get_decision(stream['Media']) 89 | else: 90 | self.type = 'Unknown' 91 | 92 | if self.type == 'transcode': 93 | if 'TranscodeSession' in stream: 94 | self.video_decision = stream['TranscodeSession']['videoDecision'] 95 | self.audio_decision = stream['TranscodeSession']['audioDecision'] 96 | else: 97 | self.video_decision = 'Unknown' 98 | self.audio_decision = 'Unknown' 99 | else: 100 | self.video_decision = 'directplay' 101 | self.audio_decision = 'directplay' 102 | 103 | if 'title' not in stream or 'type' not in stream: 104 | self.title = 'Unknown' 105 | elif stream['type'] == 'episode': 106 | self.title = f"{stream['grandparentTitle']} {stream['parentIndex']}x{stream['index']}" 107 | 108 | else: 109 | self.title = stream['title'] 110 | 111 | @staticmethod 112 | def get_decision(medias): 113 | for media in medias: 114 | if 'Part' not in media: 115 | continue 116 | for part in media['Part']: 117 | if 'decision' in part: 118 | return part['decision'] 119 | return 'Unknown' 120 | 121 | def __str__(self): 122 | if self.type == 'transcode': 123 | transcode_type = "(" 124 | if self.video_decision == 'transcode': 125 | transcode_type += "video" 126 | if self.audio_decision == 'transcode': 127 | if 'video' in transcode_type: 128 | transcode_type += " & " 129 | transcode_type += "audio" 130 | transcode_type += ")" 131 | stream_type = f"transcode {transcode_type}" 132 | else: 133 | stream_type = self.type 134 | 135 | return u"{user} is playing {media} using {player}. " \ 136 | "Stream state: {state}, local: {local}, type: {type}.".format(user=self.user, 137 | media=self.title, 138 | player=self.player, 139 | state=self.state, 140 | local=self.local, 141 | type=stream_type) 142 | 143 | def __repr__(self): 144 | return str(self) 145 | -------------------------------------------------------------------------------- /utils/process.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import shlex 3 | import subprocess 4 | 5 | log = logging.getLogger("process") 6 | 7 | 8 | def execute(command, callback=None, env=None, logs=True, shell=False): 9 | total_output = '' 10 | process = subprocess.Popen(command if shell else shlex.split(command), 11 | shell=shell, 12 | env=env, 13 | stdout=subprocess.PIPE, 14 | stderr=subprocess.STDOUT) 15 | 16 | while True: 17 | output = process.stdout.readline().decode().strip() 18 | if process.poll() is not None: 19 | break 20 | if output and len(output): 21 | if logs: 22 | log.info(output) 23 | if callback: 24 | cancel = callback(output) 25 | if cancel: 26 | if logs: 27 | log.info("Callback requested termination, terminating...") 28 | log.debug(f"Callback output {cancel}") 29 | process.kill() 30 | else: 31 | total_output += "%s\n" % output 32 | 33 | return process.poll() if callback else total_output 34 | 35 | 36 | def popen(command, shell=False): 37 | try: 38 | return subprocess.check_output(command if shell else shlex.split(command), 39 | shell=shell).decode().strip() 40 | 41 | except Exception: 42 | log.exception("Exception while executing process: ") 43 | return None 44 | -------------------------------------------------------------------------------- /utils/rclone.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import logging 3 | import os 4 | import time 5 | from urllib.parse import urljoin 6 | import re 7 | import requests 8 | import urllib3 9 | import subprocess 10 | import jsonpickle 11 | from . import process, misc 12 | 13 | try: 14 | from shlex import quote as cmd_quote 15 | except ImportError: 16 | from pipes import quote as cmd_quote 17 | 18 | log = logging.getLogger('rclone') 19 | 20 | urllib3.disable_warnings() 21 | 22 | 23 | class RcloneMover: 24 | def __init__(self, config, rclone_binary_path, rclone_config_path, plex, dry_run=False): 25 | self.config = config 26 | self.rclone_binary_path = rclone_binary_path 27 | self.rclone_config_path = rclone_config_path 28 | self.plex = plex 29 | self.dry_run = dry_run 30 | 31 | def move(self): 32 | try: 33 | log.debug(f"Moving '{self.config['move_from_remote']}' to '{self.config['move_to_remote']}'") 34 | 35 | # build cmd 36 | cmd = f"{cmd_quote(self.rclone_binary_path)} move {cmd_quote(self.config['move_from_remote'])} {cmd_quote(self.config['move_to_remote'])} --config={cmd_quote(self.rclone_config_path)}" 37 | 38 | extras = self.__extras2string() 39 | if len(extras) > 2: 40 | cmd += f' {extras}' 41 | excludes = self.__excludes2string() 42 | if len(excludes) > 2: 43 | cmd += f' {excludes}' 44 | if self.plex.get('enabled'): 45 | r = re.compile(r"https?://(www\.)?") 46 | rc_url = r.sub('', self.plex['rclone']['url']).strip().strip('/') 47 | cmd += f' --rc --rc-addr={cmd_quote(rc_url)}' 48 | if self.dry_run: 49 | cmd += ' --dry-run' 50 | 51 | # exec 52 | log.debug(f"Using: {cmd}") 53 | process.execute(cmd, logs=True) 54 | return True 55 | 56 | except Exception: 57 | log.exception(f"Exception occurred while moving '{self.config['move_from_remote']}' to '{self.config['move_to_remote']}':") 58 | 59 | return False 60 | 61 | # internals 62 | def __extras2string(self): 63 | if 'rclone_extras' not in self.config: 64 | return '' 65 | 66 | return ' '.join(f"{key}={cmd_quote(value) if isinstance(value, str) else value}" for (key, value) in self.config['rclone_extras'].items()).replace('=None', '').strip() 67 | 68 | def __excludes2string(self): 69 | if 'rclone_excludes' not in self.config: 70 | return '' 71 | 72 | return ' '.join(f"--exclude={cmd_quote(glob.escape(value) if value.startswith(os.path.sep) else value) if isinstance(value,str) else value}" for value in self.config['rclone_excludes']).replace('=None', '').strip() 73 | 74 | 75 | class RcloneUploader: 76 | def __init__(self, name, config, rclone_binary_path, rclone_config_path, plex, dry_run=False, 77 | service_account=None): 78 | self.name = name 79 | self.config = config 80 | self.rclone_binary_path = rclone_binary_path 81 | self.rclone_config_path = rclone_config_path 82 | self.plex = plex 83 | self.dry_run = dry_run 84 | self.service_account = service_account 85 | 86 | def delete_file(self, path): 87 | try: 88 | log.debug(f"Deleting file '{path}' from remote {self.name}") 89 | cmd = f"{cmd_quote(self.rclone_binary_path)} delete {cmd_quote(path)} --config={cmd_quote(self.rclone_config_path)} --user-agent={cmd_quote('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36')}" 90 | 91 | if self.dry_run: 92 | cmd += ' --dry-run' 93 | log.debug(f"Using: {cmd}") 94 | resp = process.execute(cmd, logs=False) 95 | return 'Failed to delete' not in resp 96 | except Exception: 97 | log.exception(f"Exception deleting file '{path}' from remote {self.name}: ") 98 | return False 99 | 100 | def delete_folder(self, path): 101 | try: 102 | log.debug(f"Deleting folder '{path}' from remote {self.name}") 103 | cmd = f"{cmd_quote(self.rclone_binary_path)} rmdir {cmd_quote(path)} --config={cmd_quote(self.rclone_config_path)} --user-agent={cmd_quote('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36')}" 104 | 105 | if self.dry_run: 106 | cmd += ' --dry-run' 107 | log.debug("Using: %s", cmd) 108 | resp = process.execute(cmd, logs=False) 109 | return 'Failed to rmdir' not in resp 110 | except Exception: 111 | log.exception(f"Exception deleting folder '{path}' from remote {self.name}: ") 112 | 113 | return False 114 | 115 | def upload(self, callback): 116 | try: 117 | log.debug(f"Uploading '{self.config['upload_folder']}' to '{self.config['upload_remote']}'") 118 | log.debug(f"Rclone command set to '{self.config['rclone_command'] if ('rclone_command' in self.config and self.config['rclone_command'].lower() != 'sync') else 'move'}'") 119 | # build cmd 120 | cmd = f"{cmd_quote(self.rclone_binary_path)} {cmd_quote(self.config['rclone_command'] if ('rclone_command' in self.config and self.config['rclone_command'].lower() != 'sync') else 'move')} {cmd_quote(self.config['upload_folder'])} {cmd_quote(self.config['upload_remote'])} --config={cmd_quote(self.rclone_config_path)}" 121 | subprocess_env = os.environ.copy() 122 | 123 | if self.service_account is not None: 124 | 125 | rclone_data = subprocess.check_output(f'rclone config dump --config={cmd_quote(self.rclone_config_path)}', shell=True) 126 | rclone_remotes = jsonpickle.decode(rclone_data) 127 | config_remote = self.config['upload_remote'].split(":")[0] 128 | 129 | def find_crypt_upstream(crypt_remote): 130 | crypt_remote_upstream = rclone_remotes[crypt_remote]['remote'].split(":")[0] 131 | try: 132 | crypt_upstream_remote_type = rclone_remotes[crypt_remote_upstream]['type'] 133 | if crypt_upstream_remote_type == "drive": 134 | return [crypt_remote_upstream] 135 | elif crypt_upstream_remote_type == "union": 136 | return find_union_upstreams(crypt_remote_upstream) 137 | elif crypt_upstream_remote_type == "chunker": 138 | return find_chunker_upstream(crypt_remote_upstream) 139 | else: 140 | log.warning(f'{crypt_remote_upstream} is an unsupported type: {rclone_remotes[crypt_remote_upstream]["type"]}.') 141 | return [] 142 | except KeyError: 143 | log.error(f'Upstream remote {crypt_remote_upstream} does not exist in rclone.') 144 | exit(1) 145 | 146 | def find_chunker_upstream(chunker_remote): 147 | chunker_remote_upstream = rclone_remotes[chunker_remote]['remote'].split(":")[0] 148 | try: 149 | chunker_upstream_remote_type = rclone_remotes[chunker_remote_upstream]['type'] 150 | if chunker_upstream_remote_type == "drive": 151 | return [chunker_remote_upstream] 152 | elif chunker_upstream_remote_type == "union": 153 | return find_union_upstreams(chunker_remote_upstream) 154 | elif chunker_upstream_remote_type == "crypt": 155 | return find_crypt_upstream(chunker_remote_upstream) 156 | else: 157 | log.warning(f'{chunker_remote_upstream} is an unsupported type: {rclone_remotes[chunker_remote_upstream]["type"]}.') 158 | return [] 159 | except KeyError: 160 | log.error(f'Upstream remote {chunker_remote_upstream} does not exist in rclone.') 161 | exit(1) 162 | 163 | def find_union_upstreams(union_remote): 164 | union_parsed_upstream = [] 165 | for upstream_remote in rclone_remotes[union_remote]['upstreams'].split(' '): 166 | remote_string = upstream_remote.split(":")[0] 167 | try: 168 | upstream_remote_type = rclone_remotes[remote_string]['type'] 169 | if upstream_remote_type == "drive": 170 | union_parsed_upstream.append(upstream_remote.split(":")[0]) 171 | elif upstream_remote_type == "crypt": 172 | union_parsed_upstream.extend(find_crypt_upstream(remote_string)) 173 | elif remote_type == "chunker": 174 | union_parsed_upstream.extend(find_chunker_upstream(union_remote)) 175 | else: 176 | log.warning(f'{remote_string} is an unsupported type: {rclone_remotes[remote_string]["type"]}.') 177 | except KeyError: 178 | log.error(f'Upstream remote {remote_string} does not exist in rclone.') 179 | exit(1) 180 | return union_parsed_upstream 181 | 182 | parsed_remotes = [] 183 | try: 184 | remote_type = rclone_remotes[config_remote]['type'] 185 | if remote_type == "crypt": 186 | parsed_remotes.extend(find_crypt_upstream(config_remote)) 187 | elif remote_type == "chunker": 188 | parsed_remotes.extend(find_chunker_upstream(config_remote)) 189 | elif remote_type == "drive": 190 | parsed_remotes.append(config_remote) 191 | elif remote_type == "union": 192 | parsed_remotes.extend(find_union_upstreams(config_remote)) 193 | else: 194 | log.warning(f'{config_remote} has an unsupported type: {rclone_remotes[config_remote]["type"]}.') 195 | 196 | except KeyError: 197 | log.error(f'{config_remote} is an invalid remote.') 198 | exit(1) 199 | 200 | finally: 201 | log.debug(f"Parsed remotes: {parsed_remotes}") 202 | 203 | if parsed_remotes: 204 | for remote in list(dict.fromkeys(parsed_remotes)): 205 | remote_env = f'RCLONE_CONFIG_{remote.upper()}_SERVICE_ACCOUNT_FILE' 206 | subprocess_env[remote_env] = self.service_account 207 | log.debug(subprocess_env) 208 | else: 209 | log.warning('No remotes were added to ENV.') 210 | 211 | extras = self.__extras2string() 212 | if len(extras) > 2: 213 | cmd += f' {extras}' 214 | excludes = self.__excludes2string() 215 | if len(excludes) > 2: 216 | cmd += f' {excludes}' 217 | if self.plex.get('enabled'): 218 | r = re.compile(r"https?://(www\.)?") 219 | rc_url = r.sub('', self.plex['rclone']['url']).strip().strip('/') 220 | cmd += f' --rc --rc-addr={cmd_quote(rc_url)}' 221 | if self.dry_run: 222 | cmd += ' --dry-run' 223 | 224 | # exec 225 | log.debug("Using: %s", cmd) 226 | return_code = process.execute(cmd, callback, subprocess_env) 227 | return True, return_code 228 | except Exception: 229 | log.exception("Exception occurred while uploading '%s' to remote: %s", self.config['upload_folder'], 230 | self.name) 231 | return_code = 9999 232 | 233 | return False, return_code 234 | 235 | # internals 236 | def __extras2string(self): 237 | return ' '.join(f"{key}={cmd_quote(value) if isinstance(value, str) else value}" for (key, value) in 238 | self.config['rclone_extras'].items()).replace('=None', '').strip() 239 | 240 | def __excludes2string(self): 241 | return ' '.join( 242 | "--exclude=%s" % ( 243 | cmd_quote(glob.escape(value) if value.startswith(os.path.sep) else value) if isinstance(value, 244 | str) else value) 245 | for value in 246 | self.config['rclone_excludes']).replace('=None', '').strip() 247 | 248 | 249 | class RcloneSyncer: 250 | def __init__(self, from_remote, to_remote, **kwargs): 251 | self.from_config = from_remote 252 | self.to_config = to_remote 253 | 254 | # trigger logic 255 | self.rclone_sleeps = misc.merge_dicts(self.from_config['rclone_sleeps'], self.to_config['rclone_sleeps']) 256 | self.trigger_tracks = {} 257 | self.delayed_check = 0 258 | self.delayed_trigger = None 259 | 260 | # parse rclone_extras from kwargs 261 | self.rclone_extras = kwargs.get('rclone_extras', {}) 262 | # parse dry_run from kwargs 263 | self.dry_run = kwargs.get('dry_run', False) 264 | # parse use_copy from kwargs 265 | self.use_copy = kwargs.get('use_copy', False) 266 | 267 | def sync(self, cmd_wrapper): 268 | if not cmd_wrapper: 269 | log.error( 270 | "You must provide a cmd_wrapper method to wrap the rclone sync command for the desired sync agent") 271 | return False, self.delayed_check, self.delayed_trigger 272 | 273 | # build sync command 274 | cmd = f"rclone {'copy' if self.use_copy else 'sync'} {cmd_quote(self.from_config['sync_remote'])} {cmd_quote(self.to_config['sync_remote'])}" 275 | 276 | extras = self.__extras2string() 277 | if len(extras) > 2: 278 | cmd += f' {extras}' 279 | if self.dry_run: 280 | cmd += ' --dry-run' 281 | 282 | sync_agent_cmd = cmd_wrapper(cmd) 283 | log.debug("Using: %s", sync_agent_cmd) 284 | 285 | # exec 286 | process.execute(sync_agent_cmd, self._sync_logic) 287 | return not self.delayed_check, self.delayed_check, self.delayed_trigger 288 | 289 | # internals 290 | 291 | def _sync_logic(self, data): 292 | # loop sleep triggers 293 | for trigger_text, trigger_config in self.rclone_sleeps.items(): 294 | # check/reset trigger timeout 295 | if ( 296 | trigger_text in self.trigger_tracks 297 | and self.trigger_tracks[trigger_text]['expires'] != '' 298 | and time.time() >= self.trigger_tracks[trigger_text]['expires'] 299 | ): 300 | log.warning("Tracking of trigger: %r has expired, resetting occurrence count and timeout", 301 | trigger_text) 302 | self.trigger_tracks[trigger_text] = {'count': 0, 'expires': ''} 303 | 304 | # check if trigger_text is in data 305 | if trigger_text.lower() in data.lower(): 306 | # check / increase tracking count of trigger_text 307 | if trigger_text not in self.trigger_tracks or self.trigger_tracks[trigger_text]['count'] == 0: 308 | # set initial tracking info for trigger 309 | self.trigger_tracks[trigger_text] = {'count': 1, 'expires': time.time() + trigger_config['timeout']} 310 | log.warning("Tracked first occurrence of trigger: %r. Expiring in %d seconds at %s", trigger_text, 311 | trigger_config['timeout'], time.strftime('%Y-%m-%d %H:%M:%S', 312 | time.localtime( 313 | self.trigger_tracks[trigger_text][ 314 | 'expires']))) 315 | else: 316 | # trigger_text WAS seen before increase count 317 | self.trigger_tracks[trigger_text]['count'] += 1 318 | log.warning("Tracked trigger: %r has occurred %d/%d times within %d seconds", trigger_text, 319 | self.trigger_tracks[trigger_text]['count'], trigger_config['count'], 320 | trigger_config['timeout']) 321 | 322 | # check if trigger_text was found the required amount of times to abort 323 | if self.trigger_tracks[trigger_text]['count'] >= trigger_config['count']: 324 | log.warning( 325 | "Tracked trigger %r has reached the maximum limit of %d occurrences within %d seconds," 326 | " aborting upload...", trigger_text, trigger_config['count'], trigger_config['timeout']) 327 | self.delayed_check = trigger_config['sleep'] 328 | self.delayed_trigger = trigger_text 329 | return True 330 | return False 331 | 332 | def __extras2string(self): 333 | return ' '.join(f"{key}={cmd_quote(value) if isinstance(value, str) else value}" for (key, value) in 334 | self.rclone_extras.items()).replace('=None', '').strip() 335 | 336 | 337 | class RcloneThrottler: 338 | def __init__(self, url): 339 | self.url = url 340 | 341 | def validate(self): 342 | success = False 343 | payload = {'validated': True} 344 | try: 345 | resp = requests.post(urljoin(self.url, 'rc/noop'), json=payload, timeout=15, verify=False) 346 | if '{' in resp.text and '}' in resp.text: 347 | data = resp.json() 348 | success = data['validated'] 349 | except Exception: 350 | log.exception("Exception validating rc url %s: ", self.url) 351 | return success 352 | 353 | def throttle_active(self, speed): 354 | if speed: 355 | try: 356 | resp = requests.post(urljoin(self.url, 'core/stats'), timeout=15, verify=False) 357 | if '{' in resp.text and '}' in resp.text: 358 | data = resp.json() 359 | if 'transferring' in data and len(data['transferring']) > 0: 360 | # Sum total speed of all active transfers to determine if greater than current_speed 361 | current_speed = sum( 362 | float(transfer['speed']) 363 | for transfer in data['transferring'] 364 | ) 365 | 366 | return (current_speed / 1000000) - 10 <= float(speed.rstrip('M')) 367 | except Exception: 368 | log.exception("Exception checking if throttle currently active") 369 | 370 | return False 371 | 372 | def throttle(self, speed): 373 | success = False 374 | payload = {'rate': speed} 375 | try: 376 | resp = requests.post(urljoin(self.url, 'core/bwlimit'), json=payload, timeout=15, verify=False) 377 | if '{' in resp.text and '}' in resp.text: 378 | data = resp.json() 379 | if 'error' in data: 380 | log.error("Failed to throttle %s: %s", self.url, data['error']) 381 | elif 'rate' in data and speed in data['rate']: 382 | log.warning("Successfully throttled %s to %s.", self.url, speed) 383 | success = True 384 | 385 | except Exception: 386 | log.exception("Exception sending throttle request to %s: ", self.url) 387 | return success 388 | 389 | def no_throttle(self): 390 | success = False 391 | payload = {'rate': 'off'} 392 | try: 393 | resp = requests.post(urljoin(self.url, 'core/bwlimit'), json=payload, timeout=15, verify=False) 394 | if '{' in resp.text and '}' in resp.text: 395 | data = resp.json() 396 | if 'error' in data: 397 | log.error("Failed to un-throttle %s: %s", self.url, data['error']) 398 | elif 'rate' in data and data['rate'] == 'off': 399 | log.warning("Successfully un-throttled %s", self.url) 400 | success = True 401 | except Exception: 402 | log.exception("Exception sending un-throttle request to %s: ", self.url) 403 | return success 404 | -------------------------------------------------------------------------------- /utils/sabnzbd.py: -------------------------------------------------------------------------------- 1 | import urllib 2 | 3 | 4 | class Sabnzbd(object): 5 | 6 | def __init__(self, url, apikey=''): 7 | self.url = url 8 | self.apikey = apikey 9 | 10 | def request(self, mode, output=True, **kwargs): 11 | kwargs['apikey'] = self.apikey 12 | kwargs['mode'] = mode 13 | 14 | if output: 15 | kwargs['output'] = 'json' 16 | url = f'{self.url}/api?{urllib.parse.urlencode(kwargs)}' 17 | 18 | try: 19 | result = urllib.request.urlopen(url) 20 | if output: 21 | print("Result is ", result.reason) 22 | if mode == "pause": 23 | self.paused = True 24 | if mode == "resume": 25 | self.resumed = True 26 | except urllib.error.HTTPError as error: 27 | print(f"Failed to {mode} with error code {error.code}") 28 | return None 29 | 30 | def pause_queue(self): 31 | self.paused = False 32 | self.request('pause') 33 | return self.paused 34 | 35 | def resume_queue(self): 36 | self.resumed = False 37 | self.request('resume') 38 | return self.resumed 39 | 40 | # Can we use this in the furture ?? 41 | # def shutdown(self): 42 | # self.request('shutdown') 43 | 44 | # def status(self, advanced=False): 45 | # if advanced: 46 | # return self.request('status', True) 47 | # else: 48 | # return self.request('qstatus', True) 49 | 50 | # def limit(self): 51 | # try: 52 | # return self.status(advanced=True)['limit'] 53 | # except: 54 | # return 55 | 56 | # def setLimit(self, value=0): 57 | # self.request('config', name='speedlimit', value=value) 58 | -------------------------------------------------------------------------------- /utils/syncer/__init__.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import uuid 3 | 4 | from .local import Local 5 | from .scaleway import Scaleway 6 | 7 | log = logging.getLogger("syncer") 8 | 9 | SERVICES = { 10 | 'scaleway': Scaleway, 11 | 'local': Local 12 | } 13 | 14 | 15 | class Syncer: 16 | def __init__(self, config): 17 | self.config = config 18 | self.services = [] 19 | 20 | def load(self, **kwargs): 21 | # validate required keywords were supplied 22 | if 'service' not in kwargs: 23 | log.error("You must specify a service to load with the service parameter") 24 | return False 25 | elif kwargs['service'] not in SERVICES: 26 | log.error("You specified an invalid service to load: %s", kwargs['service']) 27 | return False 28 | 29 | if 'tool_path' not in kwargs: 30 | log.error("You must specify a tool_path for each syncer in your service") 31 | return False 32 | 33 | if 'sync_from' not in kwargs or 'sync_to' not in kwargs: 34 | log.error("You must specify a sync_form and sync_to in your configuration") 35 | return False 36 | 37 | try: 38 | # retrieve remotes config for sync_from and sync_to 39 | sync_from_config = self.config['remotes'][kwargs['sync_from']] 40 | sync_to_config = self.config['remotes'][kwargs['sync_to']] 41 | 42 | # clean kwargs before initializing the service 43 | tool_path = kwargs['tool_path'] 44 | chosen_service = SERVICES[kwargs['service']] 45 | del kwargs['service'] 46 | del kwargs['sync_from'] 47 | del kwargs['sync_to'] 48 | del kwargs['tool_path'] 49 | 50 | # load service 51 | service = chosen_service(tool_path, sync_from_config, sync_to_config, **kwargs) 52 | self.services.append(service) 53 | 54 | except Exception: 55 | log.exception("Exception while loading service, kwargs=%r: ", kwargs) 56 | 57 | """ 58 | Methods below require minimum 1 or 2 keyword parameter (service and name). 59 | """ 60 | 61 | def startup(self, **kwargs): 62 | if 'service' not in kwargs: 63 | log.error("You must specify a service to startup") 64 | return False 65 | if 'name' not in kwargs: 66 | kwargs['name'] = str(uuid.uuid4()) 67 | 68 | try: 69 | # clean kwargs before passing this on 70 | chosen_service = kwargs['service'] 71 | del kwargs['service'] 72 | 73 | for syncer in self.services: 74 | if chosen_service and syncer.NAME.lower() != chosen_service: 75 | continue 76 | if syncer.syncer_name != kwargs['name']: 77 | continue 78 | 79 | return syncer.startup(**kwargs) 80 | except Exception: 81 | log.exception("Exception starting instance kwargs=%r: ", kwargs) 82 | 83 | """ 84 | Methods below require minimum 1 or 2 keyword parameter (service and instance_id). 85 | """ 86 | 87 | def setup(self, **kwargs): 88 | if 'service' not in kwargs: 89 | log.error("You must specify a service to setup") 90 | return False 91 | 92 | try: 93 | # clean kwargs before passing this on 94 | chosen_service = kwargs['service'] 95 | del kwargs['service'] 96 | 97 | for syncer in self.services: 98 | if chosen_service and syncer.NAME.lower() != chosen_service: 99 | continue 100 | # ignore syncer if instance_id does not match otherwise setup all syncers from service 101 | if 'instance_id' in kwargs and syncer.instance_id != kwargs['instance_id']: 102 | continue 103 | return syncer.setup(**kwargs) 104 | except Exception: 105 | log.exception("Exception setting up instance kwargs=%r: ", kwargs) 106 | 107 | def destroy(self, **kwargs): 108 | if 'service' not in kwargs: 109 | log.error("You must specify a service to destroy") 110 | return False 111 | 112 | try: 113 | # clean kwargs before passing this on 114 | chosen_service = kwargs['service'] 115 | del kwargs['service'] 116 | 117 | for syncer in self.services: 118 | if chosen_service and syncer.NAME.lower() != chosen_service: 119 | continue 120 | # ignore syncer if instance_id does not match otherwise destroy all syncers from service 121 | if 'instance_id' in kwargs and syncer.instance_id != kwargs['instance_id']: 122 | continue 123 | return syncer.destroy(**kwargs) 124 | except Exception: 125 | log.exception("Exception destroying instance kwargs=%r: ", kwargs) 126 | 127 | def sync(self, **kwargs): 128 | if 'service' not in kwargs: 129 | log.error("You must specify a service to sync") 130 | return False 131 | 132 | try: 133 | # clean kwargs before passing this on 134 | chosen_service = kwargs['service'] 135 | del kwargs['service'] 136 | 137 | for syncer in self.services: 138 | if chosen_service and syncer.NAME.lower() != chosen_service: 139 | continue 140 | # ignore syncer if instance_id does not match otherwise destroy all syncers from service 141 | if 'instance_id' in kwargs and syncer.instance_id != kwargs['instance_id']: 142 | continue 143 | return syncer.sync(**kwargs) 144 | except Exception: 145 | log.exception("Exception syncing instance kwargs=%r: ", kwargs) 146 | -------------------------------------------------------------------------------- /utils/syncer/local.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import random 3 | 4 | from utils.rclone import RcloneSyncer 5 | 6 | try: 7 | from shlex import quote as cmd_quote 8 | except ImportError: 9 | from pipes import quote as cmd_quote 10 | 11 | log = logging.getLogger("local") 12 | 13 | 14 | class Local: 15 | NAME = 'Local' 16 | 17 | def __init__(self, tool_path, from_config, to_config, **kwargs): 18 | self.tool_path = tool_path 19 | self.sync_from_config = from_config 20 | self.sync_to_config = to_config 21 | self.kwargs = kwargs 22 | self.instance_id = None 23 | self.rclone_config_path = None 24 | self.syncer_name = kwargs.get('syncer_name', 'Unknown Syncer') 25 | 26 | log.info(f"Initialized Local syncer agent for {self.syncer_name} - {self.sync_from_config['sync_remote']} -> {self.sync_to_config['sync_remote']} using tool: {self.tool_path}") 27 | return 28 | 29 | def startup(self, **kwargs): 30 | if 'name' not in kwargs: 31 | log.error("You must provide an name for this instance") 32 | return False, None 33 | 34 | # fake instance_id 35 | self.instance_id = random.randint(1, 10000) 36 | 37 | return True, self.instance_id 38 | 39 | def setup(self, **kwargs): 40 | if not self.instance_id: 41 | log.error("Setup was called, but no instance_id was found, aborting...") 42 | return False 43 | if 'rclone_config' not in kwargs: 44 | log.error("Setup was called, but no rclone_config was found, aborting...") 45 | self.destroy() 46 | return False 47 | 48 | # store the rclone_config path provided in kwargs 49 | self.rclone_config_path = kwargs['rclone_config'] 50 | 51 | return True 52 | 53 | def destroy(self): 54 | if not self.instance_id: 55 | log.error("Destroy was called, but no instance_id was found, aborting...") 56 | return False 57 | 58 | return True 59 | 60 | def sync(self, **kwargs): 61 | if not self.instance_id: 62 | log.error("Sync was called, but no instance_id was found, aborting...") 63 | return False, None, None 64 | kwargs.update(self.kwargs) 65 | 66 | # create RcloneSyncer object 67 | rclone = RcloneSyncer(self.sync_from_config, self.sync_to_config, **kwargs) 68 | 69 | # start sync 70 | log.info(f"Starting sync for instance: {self.instance_id}") 71 | resp, delayed_check, delayed_trigger = rclone.sync(self._wrap_command) 72 | log.info(f"Finished syncing for instance: {self.instance_id}") 73 | 74 | return resp, delayed_check, delayed_trigger 75 | 76 | # internals 77 | 78 | def _wrap_command(self, command): 79 | return f"{cmd_quote(self.tool_path)} {command[7:]} --config={cmd_quote(self.rclone_config_path)}" 80 | -------------------------------------------------------------------------------- /utils/syncer/scaleway.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import time 3 | 4 | from utils import process 5 | from utils.rclone import RcloneSyncer 6 | 7 | try: 8 | from shlex import quote as cmd_quote 9 | except ImportError: 10 | from pipes import quote as cmd_quote 11 | 12 | log = logging.getLogger("scaleway") 13 | 14 | 15 | class Scaleway: 16 | NAME = 'Scaleway' 17 | 18 | def __init__(self, tool_path, from_config, to_config, **kwargs): 19 | self.tool_path = tool_path 20 | self.sync_from_config = from_config 21 | self.sync_to_config = to_config 22 | self.kwargs = kwargs 23 | self.instance_id = None 24 | 25 | # parse region from kwargs (default France) 26 | self.region = kwargs.get('region', 'par1') 27 | # parse type from kwargs (default X64-2GB) 28 | self.type = kwargs.get('type', 'X64-2GB') 29 | # parse image from kwargs (default Ubuntu 16.04) 30 | self.image = kwargs.get('image', 'ubuntu-xenial') 31 | # parse instance_destroy from kwargs (default True) 32 | self.instance_destroy = kwargs.get('instance_destroy', True) 33 | self.syncer_name = kwargs.get('syncer_name', 'Unknown Syncer') 34 | 35 | log.info(f"Initialized Scaleway syncer agent for {self.syncer_name} - {self.sync_from_config['sync_remote']} -> {self.sync_to_config['sync_remote']} using tool: {self.tool_path}") 36 | return 37 | 38 | def startup(self, **kwargs): 39 | if 'name' not in kwargs: 40 | log.error("You must provide an name for this instance") 41 | return False, None 42 | 43 | # check if instance exists 44 | cmd = f"{cmd_quote(self.tool_path)} ps -a" 45 | resp = process.popen(cmd) 46 | if not resp or 'zone' not in resp.lower(): 47 | log.error(f"Unexpected response while checking if instance {kwargs['name']} exists: {resp}") 48 | return False, self.instance_id 49 | 50 | if self.instance_destroy or kwargs['name'].lower() not in resp.lower(): 51 | # create instance 52 | cmd = f"{cmd_quote(self.tool_path)} --region={cmd_quote(self.region)} run -d --name={cmd_quote(kwargs['name'])} --ipv6 --commercial-type={cmd_quote(self.type)} {cmd_quote(self.image)}" 53 | 54 | resp = self.start_instance(cmd, "Creating new instance...") 55 | if not resp or 'failed' in resp.lower(): 56 | log.error(f"Unexpected response while creating instance: {resp}") 57 | return False, self.instance_id 58 | else: 59 | self.instance_id = resp 60 | log.info(f"Created new instance: {self.instance_id}") 61 | else: 62 | # start existing instance 63 | cmd = f"{cmd_quote(self.tool_path)} --region={cmd_quote(self.region)} start {cmd_quote(kwargs['name'])}" 64 | 65 | resp = self.start_instance(cmd, "Starting instance...") 66 | if not resp or 'failed' in resp.lower(): 67 | log.error(f"Unexpected response while creating instance: {resp}") 68 | return False, kwargs['name'] 69 | else: 70 | self.instance_id = kwargs['name'] 71 | log.info(f"Started existing instance: {self.instance_id}") 72 | 73 | # wait for instance to finish booting 74 | log.info("Waiting for instance to finish booting...") 75 | time.sleep(60) 76 | cmd = f"{cmd_quote(self.tool_path)} --region={cmd_quote(self.region)} exec -w {cmd_quote(self.instance_id)} {cmd_quote('uname -a')}" 77 | 78 | log.debug(f"Using: {cmd}") 79 | 80 | resp = process.popen(cmd) 81 | if not resp or 'gnu/linux' not in resp.lower(): 82 | log.error(f"Unexpected response while waiting for instance to boot: {resp}") 83 | self.destroy() 84 | return False, self.instance_id 85 | 86 | log.info(f"Instance has finished booting, uname: {resp}") 87 | return True, self.instance_id 88 | 89 | def start_instance(self, cmd, arg1): 90 | log.debug(f"Using: {cmd}") 91 | 92 | log.debug(arg1) 93 | return process.popen(cmd) 94 | 95 | def setup(self, **kwargs): 96 | if not self.instance_id: 97 | log.error("Setup was called, but no instance_id was found, aborting...") 98 | return False 99 | if 'rclone_config' not in kwargs: 100 | log.error("Setup was called, but no rclone_config was found, aborting...") 101 | self.destroy() 102 | return False 103 | 104 | # install unzip 105 | cmd_exec = "apt-get -qq update && apt-get -y -qq install unzip && which unzip" 106 | cmd = f"{cmd_quote(self.tool_path)} --region={cmd_quote(self.region)} exec {cmd_quote(self.instance_id)} {cmd_quote(cmd_exec)}" 107 | 108 | log.debug(f"Using: {cmd}") 109 | 110 | log.debug(f"Installing rclone to instance: {self.instance_id}") 111 | resp = process.popen(cmd) 112 | if not resp or '/usr/bin/unzip' not in resp.lower(): 113 | return self.error_handling(f"Unexpected response while installing unzip: {resp}") 114 | 115 | log.info("Installed unzip") 116 | 117 | # install rclone to instance 118 | cmd_exec = "cd ~ && curl -sO https://downloads.rclone.org/rclone-current-linux-amd64.zip && " \ 119 | "unzip -oq rclone-current-linux-amd64.zip && cd rclone-*-linux-amd64 && " \ 120 | "cp -rf rclone /usr/bin/ && cd ~ && rm -rf rclone-* && chown root:root /usr/bin/rclone && " \ 121 | "chmod 755 /usr/bin/rclone && mkdir -p /root/.config/rclone && which rclone" 122 | cmd = f"{cmd_quote(self.tool_path)} --region={cmd_quote(self.region)} exec {cmd_quote(self.instance_id)} {cmd_quote(cmd_exec)}" 123 | 124 | log.debug(f"Using: {cmd}") 125 | 126 | log.debug(f"Installing rclone to instance: {self.instance_id}") 127 | resp = process.popen(cmd) 128 | if not resp or '/usr/bin/rclone' not in resp.lower(): 129 | return self.error_handling(f"Unexpected response while installing rclone: {resp}") 130 | 131 | log.info("Installed rclone") 132 | 133 | # copy rclone.conf to instance 134 | cmd = f"{cmd_quote(self.tool_path)} --region={cmd_quote(self.region)} cp {cmd_quote(kwargs['rclone_config'])} {cmd_quote(self.instance_id)}:/root/.config/rclone/" 135 | 136 | log.debug(f"Using: {cmd}") 137 | 138 | log.debug(f"Copying rclone config {kwargs['rclone_config']} to instance: {self.instance_id}") 139 | resp = process.popen(cmd) 140 | if resp is None or len(resp) >= 2: 141 | return self.error_handling(f"Unexpected response while copying rclone config: {resp}") 142 | 143 | log.info("Copied across rclone.conf") 144 | 145 | log.info(f"Successfully setup instance: {self.instance_id}") 146 | return True 147 | 148 | def error_handling(self, arg0, resp): 149 | log.error(arg0, resp) 150 | self.destroy() 151 | return False 152 | 153 | def destroy(self): 154 | if not self.instance_id: 155 | log.error("Destroy was called, but no instance_id was found, aborting...") 156 | return False 157 | 158 | if self.instance_destroy: 159 | # destroy the instance 160 | cmd = f"{cmd_quote(self.tool_path)} --region={cmd_quote(self.region)} rm -f {cmd_quote(self.instance_id)}" 161 | 162 | log.debug(f"Using: {cmd}") 163 | 164 | log.debug(f"Destroying instance: {self.instance_id}") 165 | resp = process.popen(cmd) 166 | if not resp or self.instance_id.lower() not in resp.lower(): 167 | log.error(f"Unexpected response while destroying instance {self.instance_id}: {resp}") 168 | return False 169 | 170 | log.info(f"Destroyed instance: {self.instance_id}") 171 | else: 172 | # stop the instance 173 | cmd = f"{cmd_quote(self.tool_path)} --region={cmd_quote(self.region)} stop {cmd_quote(self.instance_id)}" 174 | 175 | log.debug(f"Using: {cmd}") 176 | 177 | log.debug(f"Stopping instance: {self.instance_id}") 178 | resp = process.popen(cmd) 179 | if not resp or self.instance_id.lower() not in resp.lower(): 180 | log.error(f"Unexpected response while stopping instance {self.instance_id}: {resp}") 181 | return False 182 | 183 | log.info(f"Stopped instance: {self.instance_id}") 184 | 185 | return True 186 | 187 | def sync(self, **kwargs): 188 | if not self.instance_id: 189 | log.error("Sync was called, but no instance_id was found, aborting...") 190 | return False, None, None 191 | kwargs.update(self.kwargs) 192 | 193 | # create RcloneSyncer object 194 | rclone = RcloneSyncer(self.sync_from_config, self.sync_to_config, **kwargs) 195 | 196 | # start sync 197 | log.info(f"Starting sync for instance: {self.instance_id}") 198 | resp, delayed_check, delayed_trigger = rclone.sync(self._wrap_command) 199 | log.info(f"Finished syncing for instance: {self.instance_id}") 200 | 201 | # copy rclone.conf back from instance (in-case refresh tokens were used) (Copy seems not to be working atm) 202 | # cmd = "%s --region=%s cp %s:/root/.config/rclone/rclone.conf %s" % ( 203 | # cmd_quote(self.tool_path), cmd_quote(self.region), cmd_quote(self.instance_id), 204 | # cmd_quote(os.path.dirname(kwargs['rclone_config']))) 205 | 206 | # Use exec cat > rclone config until cp is resolved 207 | cmd = f"{cmd_quote(self.tool_path)} --region={cmd_quote(self.region)} exec {cmd_quote(self.instance_id)} cat /root/.config/rclone/rclone.conf > {cmd_quote(kwargs['rclone_config'])}" 208 | 209 | log.debug(f"Using: {cmd}") 210 | 211 | log.debug(f"Copying rclone config from instance {self.instance_id} to: {kwargs['rclone_config']}") 212 | config_resp = process.popen(cmd, shell=True) 213 | if config_resp is None or len(config_resp) >= 2: 214 | log.error(f"Unexpected response while copying rclone config from instance: {config_resp}") 215 | else: 216 | log.info("Copied rclone.conf from instance") 217 | 218 | return resp, delayed_check, delayed_trigger 219 | 220 | # internals 221 | 222 | def _wrap_command(self, command): 223 | return f"{cmd_quote(self.tool_path)} --region={cmd_quote(self.region)} exec {cmd_quote(self.instance_id)} {cmd_quote(command)}" 224 | -------------------------------------------------------------------------------- /utils/threads.py: -------------------------------------------------------------------------------- 1 | import copy 2 | import threading 3 | 4 | 5 | class Thread: 6 | def __init__(self): 7 | self.threads = [] 8 | 9 | def start(self, target, name=None, args=None, track=False): 10 | thread = threading.Thread(target=target, name=name, args=args or []) 11 | thread.daemon = True 12 | thread.start() 13 | if track: 14 | self.threads.append(thread) 15 | return thread 16 | 17 | def join(self): 18 | for thread in copy.copy(self.threads): 19 | thread.join() 20 | self.threads.remove(thread) 21 | return 22 | -------------------------------------------------------------------------------- /utils/unionfs.py: -------------------------------------------------------------------------------- 1 | import concurrent.futures 2 | import logging 3 | 4 | from . import path 5 | from .rclone import RcloneUploader 6 | 7 | log = logging.getLogger('unionfs') 8 | 9 | 10 | class UnionfsHiddenFolder: 11 | def __init__(self, hidden_folder, dry_run, rclone_binary_path, rclone_config_path): 12 | self.unionfs_fuse = hidden_folder 13 | self.dry_run = dry_run 14 | self.hidden_files = self.__files() 15 | self.hidden_folders = self.__folders() 16 | self.rclone_binary_path = rclone_binary_path 17 | self.rclone_config_path = rclone_config_path 18 | 19 | def clean_remote(self, name, remote): 20 | """ 21 | Delete hidden_files and hidden_folders from remote 22 | 23 | :param name: name of the rclone remote 24 | :param remote: rclone remote item from config.json 25 | :return: True or False based on whether clean was successful 26 | """ 27 | delete_success = 0 28 | delete_failed = 0 29 | 30 | try: 31 | rclone = RcloneUploader(name, remote, self.rclone_binary_path, self.rclone_config_path, self.dry_run) 32 | # clean hidden files from remote using threadpool 33 | if self.hidden_files: 34 | with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor: 35 | log.info(f"Cleaning {len(self.hidden_files)} hidden file(s) from remote: {name}") 36 | future_to_remote_file = {} 37 | for hidden_file in self.hidden_files: 38 | remote_file = self.__hidden2remote(remote, hidden_file) 39 | if remote_file: 40 | future_to_remote_file[executor.submit(rclone.delete_file, remote_file)] = remote_file 41 | else: 42 | log.error(f"Failed mapping file '{hidden_file}' to a remote file") 43 | delete_failed += 1 44 | 45 | for future in concurrent.futures.as_completed(future_to_remote_file): 46 | remote_file = future_to_remote_file[future] 47 | try: 48 | if future.result(): 49 | log.info(f"Removed file '{remote_file}'") 50 | delete_success += 1 51 | else: 52 | log.error(f"Failed removing file '{remote_file}'") 53 | delete_failed += 1 54 | except Exception: 55 | log.exception("Exception processing result from rclone delete file future for '{remote_file}': ") 56 | delete_failed += 1 57 | 58 | # clean hidden folders from remote 59 | if self.hidden_folders: 60 | log.info(f"Cleaning {len(self.hidden_folders)} hidden folder(s) from remote: {name}") 61 | for hidden_folder in self.hidden_folders: 62 | remote_folder = self.__hidden2remote(remote, hidden_folder) 63 | if remote_folder and rclone.delete_folder(remote_folder): 64 | log.info(f"Removed folder '{remote_folder}'") 65 | delete_success += 1 66 | else: 67 | log.error(f"Failed removing folder '{remote_folder}'") 68 | delete_failed += 1 69 | 70 | if self.hidden_folders or self.hidden_files: 71 | log.info(f"Completed cleaning hidden(s) from remote: {name}") 72 | log.info(f"{delete_success} items were deleted, {delete_failed} items failed to delete") 73 | 74 | return True, delete_success, delete_failed 75 | 76 | except Exception: 77 | log.exception(f"Exception cleaning hidden(s) from {self.unionfs_fuse}: ") 78 | 79 | return False, delete_success, delete_failed 80 | 81 | def remove_local_hidden(self): 82 | if len(self.hidden_files): 83 | path.delete(self.hidden_files) 84 | log.info(f"Removed {len(self.hidden_files)} local hidden file(s) from disk") 85 | if len(self.hidden_folders): 86 | path.delete(self.hidden_folders) 87 | log.info(f"Removed {len(self.hidden_folders)} local hidden folder(s) from disk") 88 | return 89 | 90 | def remove_empty_dirs(self): 91 | path.remove_empty_dirs(self.unionfs_fuse, 1) 92 | log.info(f"Removed empty directories from '{self.unionfs_fuse}'") 93 | 94 | # internals 95 | def __files(self): 96 | hidden_files = [] 97 | try: 98 | hidden_files = path.find_items(self.unionfs_fuse, '_HIDDEN~') 99 | log.info(f"Found {len(hidden_files)} hidden files in {self.unionfs_fuse}") 100 | except Exception: 101 | log.exception(f"Exception finding hidden files for {self.unionfs_fuse}: ") 102 | hidden_files = None 103 | return hidden_files 104 | 105 | def __folders(self): 106 | try: 107 | hidden_folders = path.find_items(self.unionfs_fuse, '_HIDDEN~') 108 | log.info(f"Found {len(hidden_folders)} hidden folders in {self.unionfs_fuse}") 109 | except Exception: 110 | log.exception(f"Exception finding hidden folders for {self.unionfs_fuse}: ") 111 | hidden_folders = None 112 | return hidden_folders 113 | 114 | def __hidden2remote(self, remote, hidden_path): 115 | try: 116 | remote_path = hidden_path.replace(self.unionfs_fuse, remote['hidden_remote']).rstrip('_HIDDEN~') 117 | log.debug(f"Mapped '{hidden_path}' to '{remote_path}'") 118 | return remote_path 119 | except Exception: 120 | log.exception(f"Exception mapping hidden file '{hidden_path}' to its rclone remote path") 121 | return None 122 | -------------------------------------------------------------------------------- /utils/uploader.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import glob 3 | import time 4 | 5 | from . import path 6 | from .rclone import RcloneUploader 7 | 8 | log = logging.getLogger("uploader") 9 | 10 | 11 | class Uploader: 12 | def __init__(self, name, uploader_config, rclone_config, rclone_binary_path, rclone_config_path, plex, dry_run): 13 | self.name = name 14 | self.uploader_config = uploader_config 15 | self.rclone_config = rclone_config 16 | self.trigger_tracks = {} 17 | self.delayed_check = 0 18 | self.delayed_trigger = "" 19 | self.rclone_binary_path = rclone_binary_path 20 | self.rclone_config_path = rclone_config_path 21 | self.plex = plex 22 | self.dry_run = dry_run 23 | self.service_account = None 24 | 25 | def set_service_account(self, sa_file): 26 | self.service_account = sa_file 27 | log.info(f"Using service account: {sa_file}") 28 | 29 | def upload(self): 30 | rclone_config = self.rclone_config.copy() 31 | 32 | # should we exclude open files 33 | if self.uploader_config['exclude_open_files']: 34 | files_to_exclude = self.__opened_files() 35 | if len(files_to_exclude): 36 | log.info(f"Excluding these files from being uploaded because they were open: {files_to_exclude}") 37 | # add files_to_exclude to rclone_config 38 | for item in files_to_exclude: 39 | rclone_config['rclone_excludes'].append(glob.escape(item)) 40 | 41 | # do upload 42 | if self.service_account is not None: 43 | rclone = RcloneUploader(self.name, rclone_config, self.rclone_binary_path, self.rclone_config_path, 44 | self.plex, self.dry_run, self.service_account) 45 | else: 46 | rclone = RcloneUploader(self.name, rclone_config, self.rclone_binary_path, self.rclone_config_path, 47 | self.plex, self.dry_run) 48 | 49 | log.info(f"Uploading '{rclone_config['upload_folder']}' to remote: {self.name}") 50 | self.delayed_check = 0 51 | self.trigger_tracks = {} 52 | success = False 53 | upload_status, return_code = rclone.upload(self.__logic) 54 | 55 | log.debug("return_code is: %s", return_code) 56 | 57 | if return_code == 7: 58 | success = True 59 | log.info("Received 'Max Transfer Reached' signal from Rclone.") 60 | self.delayed_trigger = "Rclone's 'Max Transfer Reached' signal" 61 | self.delayed_check = 25 62 | 63 | elif return_code == -9: 64 | success = True 65 | log.info("Trigger reached configuration limit.") 66 | self.delayed_trigger = "Trigger reached limit" 67 | self.delayed_check = 25 68 | 69 | elif upload_status and return_code == 0: 70 | success = True 71 | log.info(f"Finished uploading to remote: {self.name}") 72 | elif return_code == 9999: 73 | self.delayed_trigger = "Rclone exception occured" 74 | else: 75 | self.delayed_trigger = f"Unhandled situation: Exit code: {return_code} - Upload Status: {upload_status}" 76 | 77 | return self.delayed_check, self.delayed_trigger, success 78 | 79 | def remove_empty_dirs(self): 80 | path.remove_empty_dirs(self.rclone_config['upload_folder'], self.rclone_config['remove_empty_dir_depth']) 81 | log.info(f"Removed empty directories from '{self.rclone_config['upload_folder']}' with min depth: {self.rclone_config['remove_empty_dir_depth']}") 82 | return 83 | 84 | # internals 85 | def __opened_files(self): 86 | open_files = path.opened_files(self.rclone_config['upload_folder']) 87 | return [ 88 | item.replace(self.rclone_config['upload_folder'], '') 89 | for item in open_files 90 | if not self.__is_opened_file_excluded(item) 91 | ] 92 | 93 | def __is_opened_file_excluded(self, file_path): 94 | return any( 95 | item.lower() in file_path.lower() 96 | for item in self.uploader_config['opened_excludes'] 97 | ) 98 | 99 | def __logic(self, data): 100 | # loop sleep triggers 101 | for trigger_text, trigger_config in self.rclone_config['rclone_sleeps'].items(): 102 | # check/reset trigger timeout 103 | if ( 104 | trigger_text in self.trigger_tracks 105 | and self.trigger_tracks[trigger_text]['expires'] != '' 106 | and time.time() >= self.trigger_tracks[trigger_text]['expires'] 107 | ): 108 | log.warning(f"Tracking of trigger: {trigger_text} has expired, resetting occurrence count and timeout") 109 | self.trigger_tracks[trigger_text] = {'count': 0, 'expires': ''} 110 | 111 | # check if trigger_text is in data 112 | if trigger_text.lower() in data.lower(): 113 | # check / increase tracking count of trigger_text 114 | if trigger_text not in self.trigger_tracks or self.trigger_tracks[trigger_text]['count'] == 0: 115 | # set initial tracking info for trigger 116 | self.trigger_tracks[trigger_text] = {'count': 1, 'expires': time.time() + trigger_config['timeout']} 117 | log.warning(f"Tracked first occurrence of trigger: {trigger_text}. Expiring in {trigger_config['timeout']} seconds at {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(self.trigger_tracks[trigger_text]['expires']))}") 118 | else: 119 | # trigger_text WAS seen before increase count 120 | self.trigger_tracks[trigger_text]['count'] += 1 121 | log.warning(f"Tracked trigger: {trigger_text} has occurred {self.trigger_tracks[trigger_text]['count']}/{trigger_config['count']} times within {trigger_config['timeout']} seconds") 122 | 123 | # check if trigger_text was found the required amount of times to abort 124 | if self.trigger_tracks[trigger_text]['count'] >= trigger_config['count']: 125 | log.warning(f"Tracked trigger {trigger_text} has reached the maximum limit of {trigger_config['count']} occurrences within {trigger_config['timeout']} seconds, aborting upload...") 126 | self.delayed_check = trigger_config['sleep'] 127 | self.delayed_trigger = trigger_text 128 | return True 129 | return False 130 | -------------------------------------------------------------------------------- /utils/version.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import sys 4 | 5 | try: 6 | from git import Repo 7 | except ImportError: 8 | sys.exit("You are missing the GitPython requirement or executing from the wrong working directory.") 9 | 10 | log = logging.getLogger("git") 11 | 12 | repo = Repo.init(os.path.dirname(os.path.realpath(sys.argv[0]))) 13 | 14 | 15 | def active_branch(): 16 | global repo 17 | 18 | try: 19 | return repo.active_branch.name 20 | 21 | except Exception: 22 | log.exception("Exception retrieving current branch: ") 23 | return 'Unknown' 24 | 25 | 26 | def latest_version(): 27 | global repo 28 | 29 | try: 30 | fetch_info = repo.remotes.origin.fetch() 31 | return str(fetch_info[0].commit) 32 | 33 | except Exception: 34 | log.exception("Exception retrieving the latest commit id: ") 35 | return 'Unknown' 36 | 37 | 38 | def current_version(): 39 | global repo 40 | 41 | try: 42 | result = repo.active_branch.commit 43 | return str(result) 44 | 45 | except Exception: 46 | log.exception("Exception retrieving the current commit id: ") 47 | return 'Unknown' 48 | 49 | 50 | def missing_commits(using_version): 51 | global repo 52 | missing = 0 53 | 54 | try: 55 | for commit in repo.iter_commits(): 56 | if str(commit) == using_version: 57 | break 58 | missing += 1 59 | 60 | except Exception: 61 | log.exception("Exception iterating commits: ") 62 | return missing 63 | 64 | 65 | def check_version(): 66 | current = current_version() 67 | latest = latest_version() 68 | 69 | if current == 'Unknown' or latest == 'Unknown': 70 | log.debug("Unable to check version due to failure to determine current/latest commits") 71 | return 72 | 73 | if current != latest: 74 | log.debug("You are NOT using the latest %s: %s", active_branch(), latest) 75 | else: 76 | log.debug("You are using the latest %s: %s", active_branch(), latest) 77 | return 78 | -------------------------------------------------------------------------------- /utils/xmlrpc.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import xmlrpc.client 3 | 4 | """ referemce: https://stackoverflow.com/a/14397619 """ 5 | 6 | 7 | class ServerProxy: 8 | def __init__(self, url, timeout=10): 9 | self.__url = url 10 | self.__timeout = timeout 11 | self.__prevDefaultTimeout = None 12 | 13 | def __enter__(self): 14 | try: 15 | if self.__timeout: 16 | self.__prevDefaultTimeout = socket.getdefaulttimeout() 17 | socket.setdefaulttimeout(self.__timeout) 18 | proxy = xmlrpc.client.ServerProxy(self.__url, allow_none=True) 19 | except Exception as ex: 20 | raise Exception("Unable create XMLRPC-proxy for url '%s': %s" % (self.__url, ex)) 21 | return proxy 22 | 23 | def __exit__(self, type, value, traceback): 24 | if self.__prevDefaultTimeout is None: 25 | socket.setdefaulttimeout(self.__prevDefaultTimeout) 26 | --------------------------------------------------------------------------------