├── .github ├── ISSUE_TEMPLATE.md ├── ISSUE_TEMPLATE │ ├── BUG_REPORT.md │ ├── FEATURE_REQUEST.md │ └── OTHER_ISSUES.md ├── SUPPORT.md └── labels.json ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE.md ├── README.bak.md ├── README.md ├── assets └── logo.svg ├── config.py ├── config ├── config.json.sample └── config.json.windows.sample ├── db.py ├── google ├── __init__.py ├── cache.py └── drive.py ├── plex.py ├── rclone.py ├── requirements.txt ├── scan.py ├── scripts └── plex_token.sh ├── system └── plex_autoscan.service ├── test_threads.py ├── threads.py └── utils.py /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 8 | 9 | ## Support / Questions 10 | 11 | The [readme](https://github.com/l3uddz/plex_autoscan/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 `#plex-autoscan` 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/plex_autoscan/issues/new?template=BUG_REPORT.md 20 | 21 | ## Feature Request 22 | 23 | Use https://github.com/l3uddz/plex_autoscan/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 Plex Autoscan 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 server command (e.g. systemd). 27 | 28 | If this is a Google Drive monitoring issue, enable `SHOW_CACHE_LOGS` for detailed logs. 29 | 30 | **System Information** 31 | 32 | - Plex Autoscan Version: [e.g. Master (latest), Develop (latest)] 33 | - Operating System: [e.g. Ubuntu Server 16.04 LTS] 34 | 35 | **Additional context** 36 | Add any other context about the problem here. 37 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/FEATURE_REQUEST.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature Request 3 | about: Suggest an idea for Plex Autoscan 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/plex_autoscan/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 `#plex-autoscan` 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/plex_autoscan/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 `#plex-autoscan` 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 | *.pyc 15 | 16 | # logs 17 | *.log* 18 | 19 | # databases 20 | /*.db 21 | 22 | # configs 23 | *.cfg 24 | /config/config.json 25 | 26 | # generators 27 | *.bat 28 | 29 | # Pyenv 30 | **/.python-version 31 | 32 | # Venv 33 | venv/ 34 | -------------------------------------------------------------------------------- /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//plex_autoscan 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.bak.md: -------------------------------------------------------------------------------- 1 | # plex_autoscan 2 | Script to assist Sonarr/Radarr/Lidarr with Plex imports so that it will only scan the folder that has been imported, instead of the entire library section. 3 | 4 | # Install 5 | 6 | ## Debian/Ubuntu 7 | 8 | 1. `cd /opt` 9 | 2. `sudo git clone https://github.com/l3uddz/plex_autoscan` 10 | 3. `sudo chown -R user:user plex_autoscan` 11 | 4. `cd plex_autoscan` 12 | 5. `sudo pip install -r requirements.txt` 13 | 6. `python scan.py` to generate default config.json 14 | 15 | **The user that runs plex_autoscan needs to beable to sudo without a password otherwise it cannot execute the PLEX_SCANNER as plex. 16 | This can be disabled by config option USE_SUDO** 17 | 18 | ## Windows 19 | 20 | 1. Git clone / Download the master folder 21 | 2. Install python requirements.txt, e.g. c:\python27\scripts\pip install -r c:\plex_autoscan\requirements.txt 22 | 3. `python scan.py` to generate default config.json 23 | 24 | **The user running plex_autoscan MUST be the same user as the one running plex, e.g. Administrator)** 25 | 26 | # Configuration 27 | 28 | Example configuration: 29 | ```json 30 | { 31 | "DOCKER_NAME": "plex", 32 | "PLEX_DATABASE_PATH": "/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Plug-in Support/Databases/com.plexapp.plugins.library.db", 33 | "PLEX_EMPTY_TRASH": true, 34 | "PLEX_EMPTY_TRASH_CONTROL_FILES": [ 35 | "/mnt/unionfs/mounted.bin" 36 | ], 37 | "PLEX_EMPTY_TRASH_MAX_FILES": 100, 38 | "PLEX_EMPTY_TRASH_ZERO_DELETED": false, 39 | "PLEX_LD_LIBRARY_PATH": "/usr/lib/plexmediaserver", 40 | "PLEX_LOCAL_URL": "http://localhost:32400", 41 | "PLEX_SCANNER": "/usr/lib/plexmediaserver/Plex\\ Media\\ Scanner", 42 | "PLEX_SUPPORT_DIR": "/var/lib/plexmediaserver/Library/Application\\ Support", 43 | "PLEX_TOKEN": "XXXXXXXXXX", 44 | "PLEX_USER": "plex", 45 | "PLEX_WAIT_FOR_EXTERNAL_SCANNERS": true, 46 | "SERVER_ALLOW_MANUAL_SCAN": false, 47 | "SERVER_FILE_EXIST_PATH_MAPPINGS": { 48 | "/home/thompsons/plexdrive": [ 49 | "/data" 50 | ] 51 | }, 52 | "SERVER_IP": "0.0.0.0", 53 | "SERVER_MAX_FILE_CHECKS": 10, 54 | "SERVER_PASS": "0c1fa7c986fe48b2bb3aa055cb86f533", 55 | "SERVER_PATH_MAPPINGS": { 56 | "/mnt/unionfs": [ 57 | "/home/seed/media/fused" 58 | ] 59 | }, 60 | "SERVER_PORT": 3468, 61 | "SERVER_SCAN_DELAY": 5, 62 | "USE_DOCKER": false, 63 | "USE_SUDO": true 64 | } 65 | 66 | ``` 67 | 68 | Output: 69 | ![Config output](http://i.imgur.com/AfI0qWv.png) 70 | 71 | ## Plex 72 | 73 | Ensure the `PLEX_LD_LIBRARY_PATH` / `PLEX_SCANNER` / `PLEX_SUPPORT_DIR` variables are the correct locations (the defaults should be preset). 74 | You can verify this is working correctly by doing, `python scan.py sections` which will return a list of your Plex library Section Names & IDs. 75 | 76 | `PLEX_USER` is self explanatory, again this should be fine as the default plex. **Ignore for Windows installations** 77 | 78 | `PLEX_TOKEN` only needs to be used in conjunction with `PLEX_EMPTY_TRASH` and `PLEX_LOCAL_URL`. For more on how to retrieve this, visit https://support.plex.tv/hc/en-us/articles/204059436-Finding-an-authentication-token-X-Plex-Token 79 | 80 | `PLEX_LOCAL_URL` is the local url of plex server where the empty trash request is sent. 81 | 82 | `PLEX_EMPTY_TRASH` when set to true, after a scan was performed, empty trash will also be performed for that section. `PLEX_DATABASE_PATH` and `PLEX_EMPTY_TRASH_MAX_FILES` must be set when this is enabled. 83 | 84 | `PLEX_EMPTY_TRASH_CONTROL_FILES` is used before performing an empty trash request, this allows you to specify a list of files that must exist. If they dont then no empty trash request is sent. If this is not needed, you can leave the list empty to disable the check. 85 | 86 | `PLEX_EMPTY_TRASH_MAX_FILES` must be set when using `PLEX_EMPTY_TRASH`, this value is the maximum deleted items to delete, so if there is more than than this amount deleted items, abort the empty trash. 87 | 88 | `PLEX_EMPTY_TRASH_ZERO_DELETED` if set to True, will always perform an empty trash on the scanned section. If False, trash will only be emptied when the database returns more than 0 deleted items. 89 | 90 | `PLEX_DATABASE_PATH` is the plex library database location. Make sure the user running plex_autoscan has access to this file directly, e.g. chmod -R 777 /var/lib/plexmediaserver or the empty trash will never be performed. On Windows, this database filepath can usually be found at "%LOCALAPPDATA%\Plex Media Server\Plug-in Support\Databases" 91 | 92 | `PLEX_WAIT_FOR_EXTERNAL_SCANNERS` when set to true, the active scanner in the plex_autoscan queue will once the lock is acquired, before a plex scan is commenced, scan the process list looking for existing Plex Media Scanners. If one is found, it will sleep 60 seconds and check again in a constant loop. Once all Plex Media Scanner's are no longer in the process list, the scan will commence, thus continuing the plex_autoscan scan backlog. **Note: if USE_DOCKER is enabled, this will not work properly if there is multiple plex dockers being ran, as it will see all the plex scanners being ran in all the containers. So turn this off when using USE_DOCKER unless there is only 1 docker container** 93 | 94 | `DOCKER_NAME` is the name of the docker container to execute the plex scanner in, if USE_DOCKER is enabled. 95 | 96 | `USE_SUDO` is on by default. If the user that runs your plex_autoscan server is able to run the Plex CLI Scanner without sudo, you can disable the sudo requirement here. **Ignore for Windows installations** 97 | 98 | `USE_DOCKER` is off by default. If this is enabled, then docker exec will be used to execute the plex scanner inside the DOCKER_NAME container. 99 | 100 | ## Server 101 | 102 | `SERVER_IP` is the server IP that plex_autoscan will listen on. usually 0.0.0.0 for remote access and 127.0.0.1 for local. 103 | 104 | `SERVER_PORT` is the port that plex_autoscan will listen on. 105 | 106 | `SERVER_SCAN_DELAY` is the seconds that is slept before a scan request can continue. 107 | 108 | `SERVER_MAX_FILE_CHECKS` is an additional check that is performed after the `SERVER_SCAN_DELAY`. It will check if the file that was requested to be scanned exists, if it does not then it will sleep for 1 minute and check again until this value has been reached. **This setting does not work with sonarr until https://github.com/Sonarr/Sonarr/commit/4189bc6f76347aee00db4449dba142ae04961e0a has been merged with master** 109 | 110 | `SERVER_PASS` is a random 32 character string generated on config build. This is used in the URL given to sonarr/radarr of plex_autoscan server. 111 | 112 | `SERVER_PATH_MAPPINGS` is a list of paths that will be remapped before being scanned. This is useful for receiving scan requests from a remote sonarr/radarr installation. Lets take for example: 113 | 114 | ```json 115 | "SERVER_PATH_MAPPINGS": { 116 | "/mnt/unionfs": [ 117 | "/home/seed/media/fused" 118 | ] 119 | }, 120 | ``` 121 | 122 | If the filepath that was reported to plex_autoscan by sonarr/radarr was `/home/seed/media/fused/Movies/Die Hard/Die Hard.mkv` then the path that would be scanned by plex would become `/mnt/unionfs/Movies/Die Hard/Die Hard.mkv`. 123 | 124 | `SERVER_FILE_EXIST_PATH_MAPPINGS` this is exactly like the option above, but for the file exist checks. this is useful when using docker, because the folder being scanned by the plex container, may be different to the path on the host system running plex_autoscan. This config option allows you to specify a path mapping to be used exclusively for the file exist checks, and then continue using the remapped path using the setting above for the plex scanner. You can leave this empty if it is not required. 125 | 126 | `SERVER_ALLOW_MANUAL_SCAN` when set to true will allow GET requests to the webhook URL where you can perform manual scans on a filepath. Remember all path mappings and section id mappings of server apply. So this is a good way of testing your configuration manually. 127 | You can either visit your webhook url in a browser, or initiate a scan by curl e.g. `curl -d "eventType=Manual&filepath=/mnt/unionfs/Media/Movies/Shut In (20166f533t In (2016) - Bluray-1080p.x264.DTS-GECKOS.mkv" http://localhost:3468/0c1fa3c9867e48b1bb3aa055cb86` 128 | 129 | ## Windows 130 | 131 | Windows installations only need to be concerned with the `PLEX_SCANNER` and `PLEX_LIBRARY_PATH` if empty trash is being used, ignore the `USE_SUDO`, `PLEX_USER`, `PLEX_SUPPORT_DIR` and `PLEX_LD_LIBRARY_PATH` variables. 132 | 133 | `PLEX_SCANNER` can usually be found in the C:\Program Files (x86)\Plex folder. 134 | You must use double backslashes for this path, e.g. `C:\\Program Files (x86)\\Plex\\Plex Scanner.exe` 135 | 136 | Follow the same guidelines as above but instead of / in paths, use `\\`, so, /Movies/ becomes `\\Movies\\`. 137 | 138 | # Sonarr/Radarr 139 | 140 | To setup your sonarr/radarr installations to use plex_autoscan, simply go to Settings -> Connect -> Add New -> Webhook. 141 | Untick on Grab and tick Download, Rename, Upgrade. Then enter the url to your server which is normally: 142 | 143 | http://SERVER_IP:SERVER_PORT/SERVER_PASS 144 | 145 | ![Sonarr](http://i.imgur.com/KxaRlwo.png) 146 | 147 | ## Startup 148 | 149 | ## Linux 150 | 151 | To start the server, simply `python scan.py server` - this will start the request server. This is good todo too grab a quick file and ensure your configuration is correct, before configuring / starting / enabling the included systemd service file. 152 | 153 | ## Windows 154 | 155 | Follow the same steps as above to run the server. As for startup, this can be achieved using the Windows Task Scheduler. Bear in mind however you decide to get your script to startup, it must be executed as a user that has permissions to access the `PLEX_SCANNER` file, typically Administrator. If this is not the case, it will hang. 156 | -------------------------------------------------------------------------------- /assets/logo.svg: -------------------------------------------------------------------------------- 1 | logo -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import json 3 | import logging 4 | import os 5 | import sys 6 | import uuid 7 | from copy import copy 8 | 9 | logger = logging.getLogger("CONFIG") 10 | 11 | 12 | class Singleton(type): 13 | _instances = {} 14 | 15 | def __call__(cls, *args, **kwargs): 16 | if cls not in cls._instances: 17 | cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) 18 | 19 | return cls._instances[cls] 20 | 21 | 22 | class Config(object): 23 | __metaclass__ = Singleton 24 | 25 | base_config = { 26 | 'PLEX_USER': 'plex', 27 | 'PLEX_SCANNER': '/usr/lib/plexmediaserver/Plex\\ Media\\ Scanner', 28 | 'PLEX_SUPPORT_DIR': '/var/lib/plexmediaserver/Library/Application\ Support', 29 | 'PLEX_LD_LIBRARY_PATH': '/usr/lib/plexmediaserver/lib', 30 | 'PLEX_DATABASE_PATH': '/var/lib/plexmediaserver/Library/Application Support/Plex Media Server' 31 | '/Plug-in Support/Databases/com.plexapp.plugins.library.db', 32 | 'PLEX_LOCAL_URL': 'http://localhost:32400', 33 | 'PLEX_EMPTY_TRASH': False, 34 | 'PLEX_EMPTY_TRASH_MAX_FILES': 100, 35 | 'PLEX_EMPTY_TRASH_CONTROL_FILES': [], 36 | 'PLEX_EMPTY_TRASH_ZERO_DELETED': False, 37 | 'PLEX_WAIT_FOR_EXTERNAL_SCANNERS': True, 38 | 'PLEX_ANALYZE_TYPE': 'basic', 39 | 'PLEX_ANALYZE_DIRECTORY': True, 40 | 'PLEX_FIX_MISMATCHED': False, 41 | 'PLEX_FIX_MISMATCHED_LANG': 'en', 42 | 'PLEX_TOKEN': '', 43 | 'PLEX_CHECK_BEFORE_SCAN': False, 44 | 'SERVER_IP': '0.0.0.0', 45 | 'SERVER_PORT': 3467, 46 | 'SERVER_PASS': uuid.uuid4().hex, 47 | 'SERVER_PATH_MAPPINGS': {}, 48 | 'SERVER_SCAN_DELAY': 180, 49 | 'SERVER_MAX_FILE_CHECKS': 10, 50 | 'SERVER_FILE_CHECK_DELAY': 60, 51 | 'SERVER_FILE_EXIST_PATH_MAPPINGS': {}, 52 | 'SERVER_ALLOW_MANUAL_SCAN': False, 53 | 'SERVER_IGNORE_LIST': [], 54 | 'SERVER_USE_SQLITE': False, 55 | 'SERVER_SCAN_PRIORITIES': {}, 56 | 'SERVER_SCAN_FOLDER_ON_FILE_EXISTS_EXHAUSTION': False, 57 | 'RCLONE': { 58 | 'RC_CACHE_REFRESH': { 59 | 'ENABLED': False, 60 | 'FILE_EXISTS_TO_REMOTE_MAPPINGS': {}, 61 | 'RC_URL': 'http://localhost:5572' 62 | }, 63 | 'BINARY': '/usr/bin/rclone', 64 | 'CRYPT_MAPPINGS': {}, 65 | 'CONFIG': '' 66 | }, 67 | 'DOCKER_NAME': 'plex', 68 | 'RUN_COMMAND_BEFORE_SCAN': '', 69 | 'RUN_COMMAND_AFTER_SCAN': '', 70 | 'USE_DOCKER': False, 71 | 'USE_SUDO': True, 72 | 'GOOGLE': { 73 | 'ENABLED': False, 74 | 'CLIENT_ID': '', 75 | 'CLIENT_SECRET': '', 76 | 'ALLOWED': { 77 | 'FILE_PATHS': [], 78 | 'FILE_EXTENSIONS': False, 79 | 'FILE_EXTENSIONS_LIST': [], 80 | 'MIME_TYPES': False, 81 | 'MIME_TYPES_LIST': [] 82 | }, 83 | 'POLL_INTERVAL': 120, 84 | 'DISABLE_DISK_FILE_SIZE_CHECK': False, 85 | 'TEAMDRIVE': False, 86 | 'TEAMDRIVES': [], 87 | 'SHOW_CACHE_LOGS': True 88 | } 89 | } 90 | 91 | base_settings = { 92 | 'config': { 93 | 'argv': '--config', 94 | 'env': 'PLEX_AUTOSCAN_CONFIG', 95 | 'default': os.path.join(os.path.dirname(sys.argv[0]), 'config', 'config.json') 96 | }, 97 | 'logfile': { 98 | 'argv': '--logfile', 99 | 'env': 'PLEX_AUTOSCAN_LOGFILE', 100 | 'default': os.path.join(os.path.dirname(sys.argv[0]), 'plex_autoscan.log') 101 | }, 102 | 'loglevel': { 103 | 'argv': '--loglevel', 104 | 'env': 'PLEX_AUTOSCAN_LOGLEVEL', 105 | 'default': 'INFO' 106 | }, 107 | 'queuefile': { 108 | 'argv': '--queuefile', 109 | 'env': 'PLEX_AUTOSCAN_QUEUEFILE', 110 | 'default': os.path.join(os.path.dirname(sys.argv[0]), 'queue.db') 111 | }, 112 | 'cachefile': { 113 | 'argv': '--cachefile', 114 | 'env': 'PLEX_AUTOSCAN_CACHEFILE', 115 | 'default': os.path.join(os.path.dirname(sys.argv[0]), 'cache.db') 116 | } 117 | } 118 | 119 | def __init__(self): 120 | """Initializes config""" 121 | # Args and settings 122 | self.args = self.parse_args() 123 | self.settings = self.get_settings() 124 | # Configs 125 | self.configs = None 126 | 127 | @property 128 | def default_config(self): 129 | cfg = copy(self.base_config) 130 | 131 | if os.name == 'nt': 132 | cfg['PLEX_SCANNER'] = '%PROGRAMFILES(X86)%\\Plex\\Plex Media Server\\Plex Media Scanner.exe' 133 | cfg['PLEX_SUPPORT_DIR'] = '%LOCALAPPDATA%\\Plex Media Server' 134 | cfg['PLEX_LD_LIBRARY_PATH'] = '%LOCALAPPDATA%\\Plex Media Server' 135 | cfg[ 136 | 'PLEX_DATABASE_PATH'] = '%LOCALAPPDATA%\\Plex Media Server\\Plug-in Support\\Databases\\com.plexapp.plugins.library.db' 137 | cfg['RCLONE']['BINARY'] = '%ChocolateyInstall%\\bin\\rclone.exe' 138 | cfg['RCLONE']['CONFIG'] = '%HOMEDRIVE%%HOMEPATH%\\.config\\rclone\\rclone.conf' 139 | 140 | # add example scan priorities 141 | cfg['SERVER_SCAN_PRIORITIES'] = { 142 | "0": [ 143 | '/Movies/' 144 | ], 145 | "1": [ 146 | '/TV/' 147 | ], 148 | "2": [ 149 | '/Music/' 150 | ] 151 | } 152 | 153 | # add example file trash control files 154 | if os.name == 'nt': 155 | cfg['PLEX_EMPTY_TRASH_CONTROL_FILES'] = ["G:\\mounted.bin"] 156 | else: 157 | cfg['PLEX_EMPTY_TRASH_CONTROL_FILES'] = ['/mnt/unionfs/mounted.bin'] 158 | 159 | # add example server path mappings 160 | if os.name == 'nt': 161 | cfg['SERVER_PATH_MAPPINGS'] = { 162 | 'G:\\media': [ 163 | "/data/media", 164 | "DRIVENAME\\media" 165 | ] 166 | } 167 | else: 168 | cfg['SERVER_PATH_MAPPINGS'] = { 169 | '/mnt/unionfs/': [ 170 | '/home/user/media/fused/' 171 | ] 172 | } 173 | 174 | # add example file exist path mappings 175 | if os.name == 'nt': 176 | cfg['SERVER_FILE_EXIST_PATH_MAPPINGS'] = { 177 | "G:\\": [ 178 | "/data/" 179 | ] 180 | } 181 | else: 182 | cfg['SERVER_FILE_EXIST_PATH_MAPPINGS'] = { 183 | '/home/user/rclone/': [ 184 | '/data/' 185 | ] 186 | } 187 | 188 | # add example server ignore list 189 | cfg['SERVER_IGNORE_LIST'] = ['/.grab/', '.DS_Store', 'Thumbs.db'] 190 | 191 | # add example allowed scan paths to google 192 | if os.name == 'nt': 193 | cfg['GOOGLE']['ALLOWED']['FILE_PATHS'] = [ 194 | "My Drive\\Media\\Movies\\", 195 | "My Drive\\Media\\TV\\", 196 | "My Drive\\Media\\4K\\" 197 | ] 198 | else: 199 | cfg['GOOGLE']['ALLOWED']['FILE_PATHS'] = [ 200 | "My Drive/Media/Movies/", 201 | "My Drive/Media/TV/", 202 | "My Drive/Media/4K/" 203 | ] 204 | 205 | # add example scan extensions to google 206 | cfg['GOOGLE']['ALLOWED']['FILE_EXTENSIONS'] = True 207 | cfg['GOOGLE']['ALLOWED']['FILE_EXTENSIONS_LIST'] = ['webm', 'mkv', 'flv', 'vob', 'ogv', 'ogg', 'drc', 'gif', 208 | 'gifv', 'mng', 'avi', 'mov', 'qt', 'wmv', 'yuv', 'rm', 209 | 'rmvb', 'asf', 'amv', 'mp4', 'm4p', 'm4v', 'mpg', 'mp2', 210 | 'mpeg', 'mpe', 'mpv', 'm2v', 'm4v', 'svi', '3gp', 211 | '3g2', 'mxf', 'roq', 'nsv', 'f4v', 'f4p', 'f4a', 'f4b', 212 | 'mp3', 'flac', 'ts'] 213 | 214 | # add example scan mimes for google 215 | cfg['GOOGLE']['ALLOWED']['MIME_TYPES'] = True 216 | cfg['GOOGLE']['ALLOWED']['MIME_TYPES_LIST'] = ['video'] 217 | 218 | # add example Rclone file exists to remote mappings 219 | if os.name == 'nt': 220 | cfg['RCLONE']['RC_CACHE_REFRESH']['FILE_EXISTS_TO_REMOTE_MAPPINGS'] = { 221 | 'Media/': [ 222 | "G:\\Media" 223 | ] 224 | } 225 | else: 226 | cfg['RCLONE']['RC_CACHE_REFRESH']['FILE_EXISTS_TO_REMOTE_MAPPINGS'] = { 227 | 'Media/': [ 228 | '/mnt/rclone/Media/' 229 | ] 230 | } 231 | 232 | return cfg 233 | 234 | def __inner_upgrade(self, settings1, settings2, key=None, overwrite=False): 235 | sub_upgraded = False 236 | merged = copy(settings2) 237 | 238 | if isinstance(settings1, dict): 239 | for k, v in settings1.items(): 240 | # missing k 241 | if k not in settings2: 242 | merged[k] = v 243 | sub_upgraded = True 244 | if not key: 245 | logger.info("Added %r config option: %s", str(k), str(v)) 246 | else: 247 | logger.info("Added %r to config option %r: %s", str(k), str(key), str(v)) 248 | continue 249 | 250 | # iterate children 251 | if isinstance(v, dict) or isinstance(v, list): 252 | merged[k], did_upgrade = self.__inner_upgrade(settings1[k], settings2[k], key=k, 253 | overwrite=overwrite) 254 | sub_upgraded = did_upgrade if did_upgrade else sub_upgraded 255 | elif settings1[k] != settings2[k] and overwrite: 256 | merged = settings1 257 | sub_upgraded = True 258 | elif isinstance(settings1, list) and key: 259 | for v in settings1: 260 | if v not in settings2: 261 | merged.append(v) 262 | sub_upgraded = True 263 | logger.info("Added to config option %r: %s", str(key), str(v)) 264 | continue 265 | 266 | return merged, sub_upgraded 267 | 268 | def upgrade_settings(self, currents): 269 | fields_env = {} 270 | 271 | # ENV gets priority: ENV > config.json 272 | for name, data in self.base_config.items(): 273 | if name in os.environ: 274 | # Use JSON decoder to get same behaviour as config file 275 | fields_env[name] = json.JSONDecoder().decode(os.environ[name]) 276 | logger.info("Using ENV setting %s=%s", name, fields_env[name]) 277 | 278 | # Update in-memory config with environment settings 279 | currents.update(fields_env) 280 | 281 | # Do inner upgrade 282 | upgraded_settings, upgraded = self.__inner_upgrade(self.base_config, currents) 283 | return upgraded_settings, upgraded 284 | 285 | def load(self): 286 | logger.debug("Upgrading config...") 287 | if not os.path.exists(self.settings['config']): 288 | logger.info("No config file found. Creating a default config...") 289 | self.save(self.default_config) 290 | 291 | cfg = {} 292 | with open(self.settings['config'], 'r') as fp: 293 | cfg, upgraded = self.upgrade_settings(json.load(fp)) 294 | 295 | # Save config if upgraded 296 | if upgraded: 297 | self.save(cfg) 298 | exit(0) 299 | else: 300 | logger.debug("Config was not upgraded as there were no changes to add.") 301 | 302 | self.configs = cfg 303 | 304 | def save(self, cfg, exitOnSave=True): 305 | with open(self.settings['config'], 'w') as fp: 306 | json.dump(cfg, fp, indent=2, sort_keys=True) 307 | if exitOnSave: 308 | logger.info( 309 | "Your config was upgraded. You may check the changes here: %r", 310 | self.settings['config'] 311 | ) 312 | 313 | if exitOnSave: 314 | exit(0) 315 | 316 | def get_settings(self): 317 | setts = {} 318 | for name, data in self.base_settings.items(): 319 | # Argrument priority: cmd < environment < default 320 | try: 321 | value = None 322 | # Command line argument 323 | if self.args[name]: 324 | value = self.args[name] 325 | logger.info("Using ARG setting %s=%s", name, value) 326 | 327 | # Envirnoment variable 328 | elif data['env'] in os.environ: 329 | value = os.environ[data['env']] 330 | logger.info("Using ENV setting %s=%s" % ( 331 | data['env'], 332 | value 333 | )) 334 | 335 | # Default 336 | else: 337 | value = data['default'] 338 | logger.info("Using default setting %s=%s" % ( 339 | data['argv'], 340 | value 341 | )) 342 | 343 | setts[name] = os.path.expandvars(value) 344 | 345 | except Exception: 346 | logger.exception("Exception retrieving setting value: %r" % name) 347 | 348 | return setts 349 | 350 | # Parse command line arguments 351 | def parse_args(self): 352 | parser = argparse.ArgumentParser( 353 | description=( 354 | 'Script to assist Sonarr/Radarr/Lidarr with Plex imports so that it will only scan the folder \n' 355 | 'that has been imported, instead of the entire library section.' 356 | ), 357 | formatter_class=argparse.RawTextHelpFormatter 358 | ) 359 | 360 | # Mode 361 | parser.add_argument('cmd', 362 | choices=('sections', 'sections+', 'server', 'authorize', 'build_caches', 'update_config'), 363 | help=( 364 | '"sections": prints Plex Sections\n' 365 | '"sections+": prints Plex Sections with more details\n' 366 | '"server": starts the application\n' 367 | '"authorize": authorize against a Google account\n' 368 | '"build_caches": build complete Google Drive caches\n' 369 | '"update_config": perform upgrade of config' 370 | ) 371 | ) 372 | 373 | # Config file 374 | parser.add_argument(self.base_settings['config']['argv'], 375 | nargs='?', 376 | const=None, 377 | help='Config file location (default: %s)' % self.base_settings['config']['default'] 378 | ) 379 | 380 | # Log file 381 | parser.add_argument(self.base_settings['logfile']['argv'], 382 | nargs='?', 383 | const=None, 384 | help='Log file location (default: %s)' % self.base_settings['logfile']['default'] 385 | ) 386 | 387 | # Queue file 388 | parser.add_argument(self.base_settings['queuefile']['argv'], 389 | nargs='?', 390 | const=None, 391 | help='Queue file location (default: %s)' % self.base_settings['queuefile']['default'] 392 | ) 393 | 394 | # Cache file 395 | parser.add_argument(self.base_settings['cachefile']['argv'], 396 | nargs='?', 397 | const=None, 398 | help='Google cache file location (default: %s)' % self.base_settings['cachefile']['default'] 399 | ) 400 | 401 | # Logging level 402 | parser.add_argument(self.base_settings['loglevel']['argv'], 403 | choices=('WARN', 'INFO', 'DEBUG'), 404 | help='Log level (default: %s)' % self.base_settings['loglevel']['default'] 405 | ) 406 | 407 | # Print help by default if no arguments 408 | if len(sys.argv) == 1: 409 | parser.print_help() 410 | 411 | sys.exit(0) 412 | 413 | else: 414 | return vars(parser.parse_args()) 415 | -------------------------------------------------------------------------------- /config/config.json.sample: -------------------------------------------------------------------------------- 1 | { 2 | "DOCKER_NAME": "", 3 | "GOOGLE": { 4 | "ENABLED": false, 5 | "CLIENT_ID": "", 6 | "CLIENT_SECRET": "", 7 | "ALLOWED": { 8 | "FILE_PATHS": [], 9 | "FILE_EXTENSIONS": true, 10 | "FILE_EXTENSIONS_LIST": [ 11 | "webm","mkv","flv","vob","ogv","ogg","drc","gif", 12 | "gifv","mng","avi","mov","qt","wmv","yuv","rm", 13 | "rmvb","asf","amv","mp4","m4p","m4v","mpg","mp2", 14 | "mpeg","mpe","mpv","m2v","m4v","svi","3gp","3g2", 15 | "mxf","roq","nsv","f4v","f4p","f4a","f4b","mp3", 16 | "flac","ts" 17 | ], 18 | "MIME_TYPES": true, 19 | "MIME_TYPES_LIST": [ 20 | "video" 21 | ] 22 | }, 23 | "TEAMDRIVE": false, 24 | "TEAMDRIVES": [], 25 | "POLL_INTERVAL": 60, 26 | "SHOW_CACHE_LOGS": false 27 | }, 28 | "PLEX_ANALYZE_DIRECTORY": true, 29 | "PLEX_ANALYZE_TYPE": "basic", 30 | "PLEX_FIX_MISMATCHED": false, 31 | "PLEX_FIX_MISMATCHED_LANG": "en", 32 | "PLEX_DATABASE_PATH": "/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Plug-in Support/Databases/com.plexapp.plugins.library.db", 33 | "PLEX_EMPTY_TRASH": false, 34 | "PLEX_EMPTY_TRASH_CONTROL_FILES": [ 35 | "/mnt/unionfs/mounted.bin" 36 | ], 37 | "PLEX_EMPTY_TRASH_MAX_FILES": 100, 38 | "PLEX_EMPTY_TRASH_ZERO_DELETED": false, 39 | "PLEX_LD_LIBRARY_PATH": "/usr/lib/plexmediaserver/lib", 40 | "PLEX_LOCAL_URL": "http://localhost:32400", 41 | "PLEX_SCANNER": "/usr/lib/plexmediaserver/Plex\\ Media\\ Scanner", 42 | "PLEX_SUPPORT_DIR": "/var/lib/plexmediaserver/Library/Application\\ Support", 43 | "PLEX_USER": "plex", 44 | "PLEX_TOKEN": "", 45 | "PLEX_CHECK_BEFORE_SCAN": false, 46 | "PLEX_WAIT_FOR_EXTERNAL_SCANNERS": true, 47 | "RCLONE": { 48 | "BINARY": "/usr/bin/rclone", 49 | "CONFIG": "~/.config/rclone/rclone.conf", 50 | "CRYPT_MAPPINGS": { 51 | }, 52 | "RC_CACHE_REFRESH": { 53 | "ENABLED": false, 54 | "FILE_EXISTS_TO_REMOTE_MAPPINGS": { 55 | "Media/": [ 56 | "/mnt/rclone/Media/" 57 | ] 58 | }, 59 | "RC_URL": "http://localhost:5572" 60 | } 61 | }, 62 | "RUN_COMMAND_BEFORE_SCAN": "", 63 | "SERVER_ALLOW_MANUAL_SCAN": false, 64 | "SERVER_FILE_EXIST_PATH_MAPPINGS": { 65 | "/mnt/unionfs/media/": [ 66 | "/data/" 67 | ] 68 | }, 69 | "SERVER_IGNORE_LIST": [ 70 | "/.grab/", 71 | ".DS_Store", 72 | "Thumbs.db" 73 | ], 74 | "SERVER_IP": "0.0.0.0", 75 | "SERVER_MAX_FILE_CHECKS": 10, 76 | "SERVER_PASS": "9c4b81fe234e4d6eb9011cefe514d915", 77 | "SERVER_PATH_MAPPINGS": { 78 | "/mnt/unionfs/": [ 79 | "~/media/fused/" 80 | ] 81 | }, 82 | "SERVER_PORT": 3468, 83 | "SERVER_SCAN_DELAY": 180, 84 | "SERVER_SCAN_FOLDER_ON_FILE_EXISTS_EXHAUSTION": false, 85 | "SERVER_SCAN_PRIORITIES": { 86 | "1": [ 87 | "/Movies/" 88 | ], 89 | "2": [ 90 | "/TV/" 91 | ] 92 | }, 93 | "SERVER_USE_SQLITE": true, 94 | "USE_DOCKER": false, 95 | "USE_SUDO": false 96 | } 97 | -------------------------------------------------------------------------------- /config/config.json.windows.sample: -------------------------------------------------------------------------------- 1 | { 2 | "DOCKER_NAME": "", 3 | "GOOGLE": { 4 | "ENABLED": false, 5 | "CLIENT_ID": "", 6 | "CLIENT_SECRET": "", 7 | "ALLOWED": { 8 | "FILE_PATHS": [], 9 | "FILE_EXTENSIONS": true, 10 | "FILE_EXTENSIONS_LIST": [ 11 | "webm","mkv","flv","vob","ogv","ogg","drc","gif", 12 | "gifv","mng","avi","mov","qt","wmv","yuv","rm", 13 | "rmvb","asf","amv","mp4","m4p","m4v","mpg","mp2", 14 | "mpeg","mpe","mpv","m2v","m4v","svi","3gp","3g2", 15 | "mxf","roq","nsv","f4v","f4p","f4a","f4b","mp3", 16 | "flac","ts" 17 | ], 18 | "MIME_TYPES": true, 19 | "MIME_TYPES_LIST": [ 20 | "video" 21 | ] 22 | }, 23 | "TEAMDRIVE": false, 24 | "TEAMDRIVES": [], 25 | "POLL_INTERVAL": 60, 26 | "SHOW_CACHE_LOGS": false 27 | }, 28 | "PLEX_ANALYZE_DIRECTORY": true, 29 | "PLEX_ANALYZE_TYPE": "basic", 30 | "PLEX_FIX_MISMATCHED": false, 31 | "PLEX_FIX_MISMATCHED_LANG": "en", 32 | "PLEX_DATABASE_PATH": "%LOCALAPPDATA%\\Plex Media Server\\Plug-in Support\\Databases\\com.plexapp.plugins.library.db", 33 | "PLEX_EMPTY_TRASH": false, 34 | "PLEX_EMPTY_TRASH_CONTROL_FILES": [ 35 | "G:\\mounted.bin" 36 | ], 37 | "PLEX_EMPTY_TRASH_MAX_FILES": 100, 38 | "PLEX_EMPTY_TRASH_ZERO_DELETED": false, 39 | "PLEX_LD_LIBRARY_PATH": "%LOCALAPPDATA%\\Plex Media Server", 40 | "PLEX_LOCAL_URL": "http://localhost:32400", 41 | "PLEX_SCANNER": "%PROGRAMFILES(X86)%\\Plex\\Plex Media Server\\Plex Media Scanner.exe", 42 | "PLEX_SUPPORT_DIR": "%LOCALAPPDATA%\\Plex Media Server", 43 | "PLEX_USER": "plex", 44 | "PLEX_TOKEN": "", 45 | "PLEX_CHECK_BEFORE_SCAN": false, 46 | "PLEX_WAIT_FOR_EXTERNAL_SCANNERS": true, 47 | "RCLONE": { 48 | "BINARY": "%ChocolateyInstall%\\bin\\rclone.exe", 49 | "CONFIG": "%HOMEDRIVE%%HOMEPATH%\\.config\\rclone\\rclone.conf", 50 | "CRYPT_MAPPINGS": { 51 | }, 52 | "RC_CACHE_REFRESH": { 53 | "ENABLED": false, 54 | "FILE_EXISTS_TO_REMOTE_MAPPINGS": { 55 | "S:\\": [ 56 | "/data/media", 57 | "DRIVENAME\\media" 58 | ] 59 | }, 60 | "RC_URL": "http://localhost:5572" 61 | } 62 | }, 63 | "RUN_COMMAND_BEFORE_SCAN": "", 64 | "SERVER_ALLOW_MANUAL_SCAN": false, 65 | "SERVER_FILE_EXIST_PATH_MAPPINGS": { 66 | "G:\\media\\": [ 67 | "/data/" 68 | ] 69 | }, 70 | "SERVER_IGNORE_LIST": [ 71 | "/.grab/", 72 | ".DS_Store", 73 | "Thumbs.db" 74 | ], 75 | "SERVER_IP": "0.0.0.0", 76 | "SERVER_MAX_FILE_CHECKS": 10, 77 | "SERVER_PASS": "9c4b81fe234e4d6eb9011cefe514d915", 78 | "SERVER_PATH_MAPPINGS": { 79 | "G:\\media\\movies\\": [ 80 | "/data/media/movies/", 81 | "TEAMDRIVENAME/media/movies/" 82 | ], 83 | }, 84 | "SERVER_PORT": 3468, 85 | "SERVER_SCAN_DELAY": 180, 86 | "SERVER_SCAN_FOLDER_ON_FILE_EXISTS_EXHAUSTION": false, 87 | "SERVER_SCAN_PRIORITIES": { 88 | "1": [ 89 | "/Movies/" 90 | ], 91 | "2": [ 92 | "/TV/" 93 | ] 94 | }, 95 | "SERVER_USE_SQLITE": true, 96 | "USE_DOCKER": false, 97 | "USE_SUDO": false 98 | } 99 | -------------------------------------------------------------------------------- /db.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | 4 | from peewee import DeleteQuery 5 | from peewee import Model, SqliteDatabase, CharField, IntegerField 6 | 7 | import config 8 | 9 | logger = logging.getLogger("DB") 10 | 11 | # Config 12 | conf = config.Config() 13 | 14 | db_path = conf.settings['queuefile'] 15 | database = SqliteDatabase(db_path, threadlocals=True) 16 | 17 | 18 | class BaseQueueModel(Model): 19 | class Meta: 20 | database = database 21 | 22 | 23 | class QueueItemModel(BaseQueueModel): 24 | scan_path = CharField(max_length=256, unique=True, null=False) 25 | scan_for = CharField(max_length=64, null=False) 26 | scan_section = IntegerField(null=False) 27 | scan_type = CharField(max_length=64, null=False) 28 | 29 | 30 | def create_database(db, db_path): 31 | if not os.path.exists(db_path): 32 | db.create_tables([QueueItemModel]) 33 | logger.info("Created Plex Autoscan database tables.") 34 | 35 | 36 | def connect(db): 37 | if not db.is_closed(): 38 | return False 39 | return db.connect() 40 | 41 | 42 | def init(db, db_path): 43 | if not os.path.exists(db_path): 44 | create_database(db, db_path) 45 | connect(db) 46 | 47 | 48 | def get_next_item(): 49 | item = None 50 | try: 51 | item = QueueItemModel.get() 52 | except Exception: 53 | # logger.exception("Exception getting first item to scan: ") 54 | pass 55 | return item 56 | 57 | 58 | def exists_file_root_path(file_path): 59 | items = get_all_items() 60 | if '.' in file_path: 61 | dir_path = os.path.dirname(file_path) 62 | else: 63 | dir_path = file_path 64 | 65 | for item in items: 66 | if dir_path.lower() in item['scan_path'].lower(): 67 | return True, item['scan_path'] 68 | return False, None 69 | 70 | 71 | def get_all_items(): 72 | items = [] 73 | try: 74 | for item in QueueItemModel.select(): 75 | items.append({'scan_path': item.scan_path, 76 | 'scan_for': item.scan_for, 77 | 'scan_type': item.scan_type, 78 | 'scan_section': item.scan_section}) 79 | except Exception: 80 | logger.exception("Exception getting all items from Plex Autoscan database: ") 81 | return None 82 | return items 83 | 84 | 85 | def get_queue_count(): 86 | count = 0 87 | try: 88 | count = QueueItemModel.select().count() 89 | except Exception: 90 | logger.exception("Exception getting queued item count from Plex Autoscan database: ") 91 | return count 92 | 93 | 94 | def remove_item(scan_path): 95 | try: 96 | return DeleteQuery(QueueItemModel).where(QueueItemModel.scan_path == scan_path).execute() 97 | except Exception: 98 | logger.exception("Exception deleting %r from Plex Autoscan database: ", scan_path) 99 | return False 100 | 101 | 102 | def add_item(scan_path, scan_for, scan_section, scan_type): 103 | item = None 104 | try: 105 | return QueueItemModel.create(scan_path=scan_path, scan_for=scan_for, scan_section=scan_section, 106 | scan_type=scan_type) 107 | except AttributeError as ex: 108 | return item 109 | except Exception: 110 | pass 111 | # logger.exception("Exception adding %r to database: ", scan_path) 112 | return item 113 | 114 | 115 | def queued_count(): 116 | try: 117 | return QueueItemModel.select().count() 118 | except Exception: 119 | logger.exception("Exception retrieving queued count: ") 120 | return 0 121 | 122 | 123 | # Init 124 | init(database, db_path) 125 | -------------------------------------------------------------------------------- /google/__init__.py: -------------------------------------------------------------------------------- 1 | from .drive import GoogleDrive, GoogleDriveManager 2 | -------------------------------------------------------------------------------- /google/cache.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from sqlitedict import SqliteDict 4 | 5 | 6 | class Cache: 7 | def __init__(self, cache_file_path): 8 | self.cache_file_path = cache_file_path 9 | self.caches = {} 10 | 11 | def get_cache(self, cache_name, autocommit=False): 12 | if cache_name not in self.caches: 13 | self.caches[cache_name] = SqliteDict(self.cache_file_path, tablename=cache_name, encode=json.dumps, 14 | decode=json.loads, autocommit=autocommit) 15 | return self.caches[cache_name] 16 | -------------------------------------------------------------------------------- /google/drive.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import time 4 | from collections import OrderedDict 5 | from copy import copy 6 | from threading import Lock 7 | from time import time 8 | 9 | from requests_oauthlib import OAuth2Session 10 | 11 | from .cache import Cache 12 | 13 | logger = logging.getLogger("GOOGLE") 14 | 15 | 16 | class GoogleDriveManager: 17 | def __init__(self, client_id, client_secret, cache_path, allowed_config=None, show_cache_logs=True, 18 | crypt_decoder=None, allowed_teamdrives=None): 19 | self.client_id = client_id 20 | self.client_secret = client_secret 21 | self.cache_path = cache_path 22 | self.allowed_config = {} if not allowed_config else allowed_config 23 | self.show_cache_logs = show_cache_logs 24 | self.crypt_decoder = crypt_decoder 25 | self.allowed_teamdrives = [] if not allowed_teamdrives else allowed_teamdrives 26 | self.drives = OrderedDict({ 27 | 'drive_root': GoogleDrive(client_id, client_secret, cache_path, crypt_decoder=self.crypt_decoder, 28 | allowed_config=self.allowed_config, show_cache_logs=show_cache_logs) 29 | }) 30 | 31 | def load_teamdrives(self): 32 | loaded_teamdrives = 0 33 | teamdrives = self.drives['drive_root'].get_teamdrives() 34 | 35 | if not teamdrives or 'teamDrives' not in teamdrives: 36 | logger.error("Failed to retrieve teamdrive list...") 37 | return False 38 | 39 | teamdrives = teamdrives['teamDrives'] 40 | for teamdrive in teamdrives: 41 | teamdrive_name = None if 'name' not in teamdrive else teamdrive['name'] 42 | teamdrive_id = None if 'id' not in teamdrive else teamdrive['id'] 43 | if not teamdrive_id or not teamdrive_name: 44 | logger.error("TeamDrive had insufficient data associated with it, skipping:\n%s", teamdrive) 45 | continue 46 | if teamdrive_name not in self.allowed_teamdrives: 47 | continue 48 | 49 | drive_name = "teamdrive_%s" % teamdrive_name 50 | self.drives[drive_name] = GoogleDrive(self.client_id, self.client_secret, self.cache_path, 51 | allowed_config=self.allowed_config, 52 | show_cache_logs=self.show_cache_logs, 53 | crypt_decoder=self.crypt_decoder, 54 | teamdrive_id=teamdrive_id) 55 | logger.debug("Loaded TeamDrive GoogleDrive instance for: %s (id = %s)", teamdrive_name, teamdrive_id) 56 | loaded_teamdrives += 1 57 | 58 | logger.info("Loaded %d TeamDrive GoogleDrive instances", loaded_teamdrives) 59 | return True 60 | 61 | def get_changes(self): 62 | using_teamdrives = False if len(self.drives) <= 1 else True 63 | for drive_type, drive in self.drives.items(): 64 | if using_teamdrives: 65 | logger.info("Retrieving changes from drive: %s", drive_type) 66 | drive.get_changes() 67 | logger.debug("Finished retrieving changes from all loaded drives") 68 | 69 | def is_authorized(self): 70 | try: 71 | return self.drives['drive_root'].validate_access_token() 72 | except Exception: 73 | logger.exception("Exception validating authentication token: ") 74 | return False 75 | 76 | def set_callbacks(self, callbacks): 77 | for drive_name, drive in self.drives.items(): 78 | drive.set_callbacks(callbacks) 79 | 80 | def build_caches(self): 81 | for drive_type, drive in self.drives.items(): 82 | logger.info("Building cache for drive: %s", drive_type) 83 | drive.show_cache_logs = False 84 | drive.set_page_token(1) 85 | drive.get_changes() 86 | logger.info("Finished building cache for drive: %s", drive_type) 87 | return 88 | 89 | 90 | class GoogleDrive: 91 | auth_url = 'https://accounts.google.com/o/oauth2/v2/auth' 92 | token_url = 'https://www.googleapis.com/oauth2/v4/token' 93 | api_url = 'https://www.googleapis.com/drive/' 94 | redirect_url = 'urn:ietf:wg:oauth:2.0:oob' 95 | scopes = ['https://www.googleapis.com/auth/drive'] 96 | 97 | def __init__(self, client_id, client_secret, cache_path, allowed_config={}, show_cache_logs=True, 98 | crypt_decoder=None, 99 | teamdrive_id=None): 100 | self.client_id = client_id 101 | self.client_secret = client_secret 102 | self.cache_path = cache_path 103 | self.cache_manager = Cache(cache_path) 104 | self.cache = self.cache_manager.get_cache('drive_root' if not teamdrive_id else 'teamdrive_%s' % teamdrive_id) 105 | self.settings_cache = self.cache_manager.get_cache('settings', autocommit=True) 106 | self.support_team_drives = True if teamdrive_id is not None else False 107 | self.token = self._load_token() 108 | self.token_refresh_lock = Lock() 109 | self.http = self._new_http_object() 110 | self.callbacks = {} 111 | self.allowed_config = allowed_config 112 | self.show_cache_logs = show_cache_logs 113 | self.crypt_decoder = crypt_decoder 114 | self.teamdrive_id = teamdrive_id 115 | 116 | ############################################################ 117 | # CORE CLASS METHODS 118 | ############################################################ 119 | 120 | def set_page_token(self, page_token): 121 | self.cache['page_token'] = page_token 122 | return 123 | 124 | def set_callbacks(self, callbacks={}): 125 | for callback_type, callback_func in callbacks.items(): 126 | self.callbacks[callback_type] = callback_func 127 | return 128 | 129 | def get_auth_link(self): 130 | auth_url, state = self.http.authorization_url(self.auth_url, access_type='offline', prompt='select_account') 131 | return auth_url 132 | 133 | def exchange_code(self, code): 134 | token = self.http.fetch_token(self.token_url, code=code, client_secret=self.client_secret) 135 | if 'access_token' in token: 136 | self._token_saver(token) 137 | # pull in existing team drives and create cache for them 138 | return self.token 139 | 140 | def query(self, path, method='GET', page_type='changes', fetch_all_pages=False, callbacks={}, **kwargs): 141 | resp = None 142 | pages = 1 143 | resp_json = {} 144 | request_url = self.api_url + path.lstrip('/') if not path.startswith('http') else path 145 | 146 | try: 147 | while True: 148 | resp = self._do_query(request_url, method, **kwargs) 149 | logger.debug("Request URL: %s", resp.url) 150 | logger.debug("Request ARG: %s", kwargs) 151 | logger.debug('Response Status: %d %s', resp.status_code, resp.reason) 152 | logger.debug('Response Content:\n%s\n', resp.text) 153 | 154 | if 'Content-Type' in resp.headers and 'json' in resp.headers['Content-Type']: 155 | if fetch_all_pages: 156 | resp_json.pop('nextPageToken', None) 157 | new_json = resp.json() 158 | # does this page have changes 159 | extended_pages = False 160 | page_data = [] 161 | if page_type in new_json: 162 | if page_type in resp_json: 163 | page_data.extend(resp_json[page_type]) 164 | page_data.extend(new_json[page_type]) 165 | extended_pages = True 166 | 167 | resp_json.update(new_json) 168 | if extended_pages: 169 | resp_json[page_type] = page_data 170 | else: 171 | return False if resp.status_code != 200 else True, resp, resp.text 172 | 173 | # call page_token_callback to update cached page_token, if specified 174 | if page_type == 'changes' and 'page_token_callback' in callbacks: 175 | if 'nextPageToken' in resp_json: 176 | callbacks['page_token_callback'](resp_json['nextPageToken']) 177 | elif 'newStartPageToken' in resp_json: 178 | callbacks['page_token_callback'](resp_json['newStartPageToken']) 179 | 180 | # call data_callback, fetch_all_pages is true 181 | if page_type == 'changes' and fetch_all_pages and 'data_callback' in callbacks: 182 | callbacks['data_callback'](resp.json()) 183 | 184 | # handle nextPageToken 185 | if fetch_all_pages and 'nextPageToken' in resp_json and resp_json['nextPageToken']: 186 | # there are more pages 187 | pages += 1 188 | logger.info("Fetching extra results from page %d", pages) 189 | if 'params' in kwargs: 190 | kwargs['params'].update({'pageToken': resp_json['nextPageToken']}) 191 | elif 'json' in kwargs: 192 | kwargs['json'].update({'pageToken': resp_json['nextPageToken']}) 193 | elif 'data' in kwargs: 194 | kwargs['data'].update({'pageToken': resp_json['nextPageToken']}) 195 | continue 196 | 197 | break 198 | 199 | return True if resp_json and len(resp_json) else False, resp, resp_json if ( 200 | resp_json and len(resp_json)) else resp.text 201 | 202 | except Exception: 203 | logger.exception("Exception sending request to %s with kwargs=%s: ", request_url, kwargs) 204 | return False, resp, None 205 | 206 | ############################################################ 207 | # DRIVE FUNCTIONS 208 | ############################################################ 209 | 210 | def validate_access_token(self): 211 | success, resp, data = self.query('/v3/changes/startPageToken', 212 | params={'supportsTeamDrives': self.support_team_drives}, fetch_all_pages=True, 213 | page_type='auth') 214 | if success and resp.status_code == 200: 215 | if 'startPageToken' not in data: 216 | logger.error("Failed validate up to date access_token:\n\n%s\n", data) 217 | return False 218 | return True 219 | else: 220 | logger.error("Error validating access token, status_code = %d, data =\n\n%s\n", 221 | resp.status_code if resp is not None else 0, data) 222 | return False 223 | 224 | def get_changes_start_page_token(self): 225 | params = { 226 | 'supportsTeamDrives': self.support_team_drives 227 | } 228 | 229 | if self.teamdrive_id is not None and self.support_team_drives: 230 | params['teamDriveId'] = self.teamdrive_id 231 | 232 | success, resp, data = self.query('/v3/changes/startPageToken', 233 | params=params, fetch_all_pages=True) 234 | if success and resp.status_code == 200: 235 | if 'startPageToken' not in data: 236 | logger.error("Failed to retrieve changes startPageToken:\n\n%s\n", data) 237 | return None 238 | return data['startPageToken'] 239 | else: 240 | logger.error("Error retrieving changes startPageToken, status_code = %d, data =\n\n%s\n", 241 | resp.status_code if resp is not None else 0, data) 242 | return None 243 | 244 | def get_teamdrives(self): 245 | success, resp, data = self.query('/v3/teamdrives', params={'pageSize': 100}, fetch_all_pages=True, 246 | page_type='teamDrives') 247 | if success and resp.status_code == 200: 248 | return data 249 | else: 250 | logger.error('Failed to retrieve teamdrives, status_code = %d, content =\n', resp.status_code, resp.text) 251 | return None 252 | 253 | def get_changes(self): 254 | callbacks = {'page_token_callback': self._page_token_saver, 255 | 'data_callback': self._process_changes} 256 | 257 | # get page token 258 | page_token = None 259 | if 'page_token' in self.cache: 260 | page_token = self.cache['page_token'] 261 | else: 262 | page_token = self.get_changes_start_page_token() 263 | 264 | if not page_token: 265 | logger.error("Failed to determine a page_token to use...") 266 | return 267 | 268 | # build params 269 | params = { 270 | 'pageToken': page_token, 'pageSize': 1000, 271 | 'includeRemoved': True, 272 | 'includeTeamDriveItems': self.support_team_drives, 273 | 'supportsTeamDrives': self.support_team_drives, 274 | 'fields': 'changes(file(md5Checksum,mimeType,modifiedTime,' 275 | 'name,parents,teamDriveId,trashed),' 276 | 'fileId,removed,teamDrive(id,name),' 277 | 'teamDriveId),newStartPageToken,nextPageToken'} 278 | 279 | if self.teamdrive_id is not None and self.support_team_drives: 280 | params['teamDriveId'] = self.teamdrive_id 281 | 282 | # make call(s) 283 | success, resp, data = self.query('/v3/changes', params=params, fetch_all_pages=True, 284 | callbacks=callbacks) 285 | return 286 | 287 | ############################################################ 288 | # CACHE 289 | ############################################################ 290 | 291 | def get_id_metadata(self, item_id, teamdrive_id=None): 292 | # return cache from metadata if available 293 | cached_metadata = self._get_cached_metdata(item_id) 294 | if cached_metadata: 295 | return True, cached_metadata 296 | 297 | # does item_id match teamdrive_id? 298 | if teamdrive_id is not None and item_id == teamdrive_id: 299 | success, resp, data = self.query('v3/teamdrives/%s' % str(item_id)) 300 | if success and resp.status_code == 200 and 'name' in data: 301 | # we successfully retrieved this teamdrive info, lets place a mimeType key in the result 302 | # so we know it needs to be cached 303 | data['mimeType'] = 'application/vnd.google-apps.folder' 304 | # lets create a cache for this teamdrive aswell 305 | self.cache_manager.get_cache("teamdrive_%s" % teamdrive_id) 306 | self._do_callback('teamdrive_added', data) 307 | else: 308 | # retrieve file metadata 309 | success, resp, data = self.query('v3/files/%s' % str(item_id), 310 | params={ 311 | 'supportsTeamDrives': self.support_team_drives, 312 | 'fields': 'id,md5Checksum,mimeType,modifiedTime,name,parents,' 313 | 'trashed,teamDriveId'}) 314 | if success and resp.status_code == 200: 315 | return True, data 316 | else: 317 | logger.error("Error retrieving metadata for item %r:\n\n%s\n", item_id, data) 318 | return False, data 319 | 320 | def get_id_file_paths(self, item_id, teamdrive_id=None): 321 | file_paths = [] 322 | added_to_cache = 0 323 | 324 | try: 325 | def get_item_paths(obj_id, path, paths, new_cache_entries, teamdrive_id=None): 326 | success, obj = self.get_id_metadata(obj_id, teamdrive_id) 327 | if not success: 328 | return new_cache_entries 329 | 330 | teamdrive_id = teamdrive_id if 'teamDriveId' not in obj else obj['teamDriveId'] 331 | 332 | # add item object to cache if we know its not from cache 333 | if 'mimeType' in obj: 334 | # we know this is a new item fetched from the api, because the cache does not store this field 335 | self.add_item_to_cache(obj['id'], obj['name'], [] if 'parents' not in obj else obj['parents'], 336 | obj['md5Checksum'] if 'md5Checksum' in obj else None) 337 | new_cache_entries += 1 338 | 339 | if path.strip() == '': 340 | path = obj['name'] 341 | else: 342 | path = os.path.join(obj['name'], path) 343 | 344 | if 'parents' in obj and obj['parents']: 345 | for parent in obj['parents']: 346 | new_cache_entries += get_item_paths(parent, path, paths, new_cache_entries, teamdrive_id) 347 | 348 | if (not obj or 'parents' not in obj or not obj['parents']) and len(path): 349 | paths.append(path) 350 | return new_cache_entries 351 | return new_cache_entries 352 | 353 | added_to_cache += get_item_paths(item_id, '', file_paths, added_to_cache, teamdrive_id) 354 | if added_to_cache: 355 | logger.debug("Dumping cache due to new entries!") 356 | self._dump_cache() 357 | 358 | if len(file_paths): 359 | return True, file_paths 360 | else: 361 | return False, file_paths 362 | 363 | except Exception: 364 | logger.exception("Exception retrieving filepaths for %r: ", item_id) 365 | 366 | return False, [] 367 | 368 | def add_item_to_cache(self, item_id, item_name, item_parents, md5_checksum, file_paths=[]): 369 | if self.show_cache_logs and item_id not in self.cache: 370 | logger.info("Added '%s' to cache: %s", item_id, item_name) 371 | 372 | if not file_paths: 373 | existing_item = self.cache[item_id] if item_id in self.cache else None 374 | if existing_item is not None and 'paths' in existing_item: 375 | file_paths = existing_item['paths'] 376 | self.cache[item_id] = {'name': item_name, 'parents': item_parents, 'md5Checksum': md5_checksum, 377 | 'paths': file_paths} 378 | return 379 | 380 | def remove_item_from_cache(self, item_id): 381 | if self.cache.pop(item_id, None): 382 | return True 383 | return False 384 | 385 | def get_item_name_from_cache(self, item_id): 386 | try: 387 | item = self.cache.get(item_id) 388 | return item['name'] if isinstance(item, dict) else 'Unknown' 389 | except Exception: 390 | pass 391 | return 'Unknown' 392 | 393 | def get_item_from_cache(self, item_id): 394 | try: 395 | item = self.cache.get(item_id, None) 396 | return item 397 | except Exception: 398 | pass 399 | return None 400 | 401 | ############################################################ 402 | # INTERNALS 403 | ############################################################ 404 | 405 | def _do_query(self, request_url, method, **kwargs): 406 | tries = 0 407 | max_tries = 2 408 | lock_acquirer = False 409 | resp = None 410 | use_timeout = 30 411 | 412 | # override default timeout 413 | if 'timeout' in kwargs and isinstance(kwargs['timeout'], int): 414 | use_timeout = kwargs['timeout'] 415 | kwargs.pop('timeout', None) 416 | 417 | # remove un-needed kwargs 418 | kwargs.pop('fetch_all_pages', None) 419 | kwargs.pop('page_token_callback', None) 420 | 421 | # do query 422 | while tries < max_tries: 423 | if self.token_refresh_lock.locked() and not lock_acquirer: 424 | logger.debug("Token refresh lock is currently acquired. Trying again in 500ms...") 425 | time.sleep(0.5) 426 | continue 427 | 428 | if method == 'POST': 429 | resp = self.http.post(request_url, timeout=use_timeout, **kwargs) 430 | elif method == 'PATCH': 431 | resp = self.http.patch(request_url, timeout=use_timeout, **kwargs) 432 | elif method == 'DELETE': 433 | resp = self.http.delete(request_url, timeout=use_timeout, **kwargs) 434 | else: 435 | resp = self.http.get(request_url, timeout=use_timeout, **kwargs) 436 | tries += 1 437 | 438 | if resp.status_code == 401 and tries < max_tries: 439 | # unauthorized error, lets refresh token and retry 440 | self.token_refresh_lock.acquire(False) 441 | lock_acquirer = True 442 | logger.warning("Unauthorized Response (Attempts %d/%d)", tries, max_tries) 443 | self.token['expires_at'] = time() - 10 444 | self.http = self._new_http_object() 445 | else: 446 | break 447 | 448 | return resp 449 | 450 | def _load_token(self): 451 | try: 452 | if 'token' not in self.settings_cache: 453 | return {} 454 | return self.settings_cache['token'] 455 | except Exception: 456 | logger.exception("Exception loading token from cache: ") 457 | return {} 458 | 459 | def _dump_token(self): 460 | try: 461 | self.settings_cache['token'] = self.token 462 | return True 463 | except Exception: 464 | logger.exception("Exception dumping token to cache: ") 465 | return False 466 | 467 | def _token_saver(self, token): 468 | # update internal token dict 469 | self.token.update(token) 470 | try: 471 | if self.token_refresh_lock.locked(): 472 | self.token_refresh_lock.release() 473 | except Exception: 474 | logger.exception("Exception releasing token_refresh_lock: ") 475 | self._dump_token() 476 | logger.info("Renewed access token!") 477 | return 478 | 479 | def _page_token_saver(self, page_token): 480 | # update internal token dict 481 | self.cache['page_token'] = page_token 482 | self._dump_cache() 483 | logger.debug("Updated page_token: %s", page_token) 484 | return 485 | 486 | def _new_http_object(self): 487 | return OAuth2Session(client_id=self.client_id, redirect_uri=self.redirect_url, scope=self.scopes, 488 | auto_refresh_url=self.token_url, auto_refresh_kwargs={'client_id': self.client_id, 489 | 'client_secret': self.client_secret}, 490 | token_updater=self._token_saver, token=self.token) 491 | 492 | def _get_cached_metdata(self, item_id): 493 | if item_id in self.cache: 494 | return self.cache[item_id] 495 | return None 496 | 497 | def _dump_cache(self, blocking=True): 498 | self.cache.commit(blocking=blocking) 499 | return 500 | 501 | def _remove_unwanted_paths(self, paths_list, mime_type): 502 | removed_file_paths = [] 503 | # remove paths that were not allowed - this is always enabled 504 | if 'FILE_PATHS' in self.allowed_config: 505 | for item_path in copy(paths_list): 506 | allowed_path = False 507 | for allowed_file_path in self.allowed_config['FILE_PATHS']: 508 | if item_path.lower().startswith(allowed_file_path.lower()): 509 | allowed_path = True 510 | break 511 | if not allowed_path: 512 | logger.debug("Ignoring %r because its not an allowed path.", item_path) 513 | removed_file_paths.append(item_path) 514 | paths_list.remove(item_path) 515 | continue 516 | 517 | # remove unallowed extensions 518 | if 'FILE_EXTENSIONS' in self.allowed_config and 'FILE_EXTENSIONS_LIST' in self.allowed_config and \ 519 | self.allowed_config['FILE_EXTENSIONS'] and len(paths_list): 520 | for item_path in copy(paths_list): 521 | allowed_file = False 522 | for allowed_extension in self.allowed_config['FILE_EXTENSIONS_LIST']: 523 | if item_path.lower().endswith(allowed_extension.lower()): 524 | allowed_file = True 525 | break 526 | if not allowed_file: 527 | logger.debug("Ignoring %r because it was not an allowed extension.", item_path) 528 | removed_file_paths.append(item_path) 529 | paths_list.remove(item_path) 530 | 531 | # remove unallowed mimes 532 | if 'MIME_TYPES' in self.allowed_config and 'MIME_TYPES_LIST' in self.allowed_config and \ 533 | self.allowed_config['MIME_TYPES'] and len(paths_list): 534 | allowed_file = False 535 | for allowed_mime in self.allowed_config['MIME_TYPES_LIST']: 536 | if allowed_mime.lower() in mime_type.lower(): 537 | if 'video' in mime_type.lower(): 538 | # we want to validate this is not a .sub file, which for some reason, google shows as video/MP2G 539 | double_checked_allowed = True 540 | for item_path in paths_list: 541 | if item_path.lower().endswith('.sub'): 542 | double_checked_allowed = False 543 | if double_checked_allowed: 544 | allowed_file = True 545 | break 546 | else: 547 | allowed_file = True 548 | break 549 | 550 | if not allowed_file: 551 | logger.debug("Ignoring %r because it was not an allowed mime: %s", paths_list, mime_type) 552 | for item_path in copy(paths_list): 553 | removed_file_paths.append(item_path) 554 | paths_list.remove(item_path) 555 | return removed_file_paths 556 | 557 | def _process_changes(self, data): 558 | unwanted_file_paths = [] 559 | added_file_paths = {} 560 | ignored_file_paths = {} 561 | renamed_file_paths = {} 562 | moved_file_paths = {} 563 | removes = 0 564 | 565 | if not data or 'changes' not in data: 566 | logger.error("There were no changes to process") 567 | return 568 | logger.info("Processing %d changes", len(data['changes'])) 569 | 570 | # process changes 571 | for change in data['changes']: 572 | if 'file' in change and 'fileId' in change: 573 | # dont consider trashed/removed events for processing 574 | if ('trashed' in change['file'] and change['file']['trashed']) or ( 575 | 'removed' in change and change['removed']): 576 | if self.remove_item_from_cache(change['fileId']) and self.show_cache_logs: 577 | logger.info("Removed '%s' from cache: %s", change['fileId'], change['file']['name']) 578 | removes += 1 579 | continue 580 | 581 | # retrieve item from cache 582 | existing_cache_item = self.get_item_from_cache(change['fileId']) 583 | 584 | # we always want to add changes to the cache so renames etc can be reflected inside the cache 585 | self.add_item_to_cache(change['fileId'], change['file']['name'], 586 | [] if 'parents' not in change['file'] else change['file']['parents'], 587 | change['file']['md5Checksum'] if 'md5Checksum' in change['file'] else None) 588 | 589 | # get this files paths 590 | success, item_paths = self.get_id_file_paths(change['fileId'], 591 | change['file']['teamDriveId'] if 'teamDriveId' in change[ 592 | 'file'] else None) 593 | if success: 594 | # save item paths 595 | self.add_item_to_cache(change['fileId'], change['file']['name'], 596 | [] if 'parents' not in change['file'] else change['file']['parents'], 597 | change['file']['md5Checksum'] if 'md5Checksum' in change['file'] else None, 598 | item_paths) 599 | 600 | # check if decoder is present 601 | if self.crypt_decoder: 602 | decoded = self.crypt_decoder.decode_path(item_paths[0]) 603 | if decoded: 604 | item_paths = decoded 605 | 606 | # dont process folder events 607 | if 'mimeType' in change['file'] and 'vnd.google-apps.folder' in change['file']['mimeType']: 608 | # ignore this change as we dont want to scan folders 609 | logger.debug("Ignoring %r because it is a folder", item_paths) 610 | if change['fileId'] in ignored_file_paths: 611 | ignored_file_paths[change['fileId']].extend(item_paths) 612 | else: 613 | ignored_file_paths[change['fileId']] = item_paths 614 | continue 615 | 616 | # remove unwanted paths 617 | if success and len(item_paths): 618 | unwanted_paths = self._remove_unwanted_paths(item_paths, 619 | change['file']['mimeType'] if 'mimeType' in change[ 620 | 'file'] else 'Unknown') 621 | if isinstance(unwanted_paths, list) and len(unwanted_paths): 622 | unwanted_file_paths.extend(unwanted_paths) 623 | 624 | # was this an existing item? 625 | if existing_cache_item is not None and (success and len(item_paths)): 626 | # this was an existing item, and we are re-processing it again 627 | # we need to determine if this file has changed (md5Checksum) 628 | if 'md5Checksum' in change['file'] and 'md5Checksum' in existing_cache_item: 629 | # compare this changes md5Checksum and the existing cache item 630 | if change['file']['md5Checksum'] != existing_cache_item['md5Checksum']: 631 | # the file was modified 632 | if change['fileId'] in added_file_paths: 633 | added_file_paths[change['fileId']].extend(item_paths) 634 | else: 635 | added_file_paths[change['fileId']] = item_paths 636 | else: 637 | if ('name' in change['file'] and 'name' in existing_cache_item) and \ 638 | change['file']['name'] != existing_cache_item['name']: 639 | logger.debug("md5Checksum matches but file was server-side renamed: %s", item_paths) 640 | if change['fileId'] in added_file_paths: 641 | added_file_paths[change['fileId']].extend(item_paths) 642 | else: 643 | added_file_paths[change['fileId']] = item_paths 644 | 645 | if change['fileId'] in renamed_file_paths: 646 | renamed_file_paths[change['fileId']].extend(item_paths) 647 | else: 648 | renamed_file_paths[change['fileId']] = item_paths 649 | elif 'paths' in existing_cache_item and not self._list_matches(item_paths, 650 | existing_cache_item[ 651 | 'paths']): 652 | logger.debug("md5Checksum matches but file was server-side moved: %s", item_paths) 653 | 654 | if change['fileId'] in added_file_paths: 655 | added_file_paths[change['fileId']].extend(item_paths) 656 | else: 657 | added_file_paths[change['fileId']] = item_paths 658 | 659 | if change['fileId'] in moved_file_paths: 660 | moved_file_paths[change['fileId']].extend(item_paths) 661 | else: 662 | moved_file_paths[change['fileId']] = item_paths 663 | 664 | else: 665 | logger.debug("Ignoring %r because the md5Checksum was the same as cache: %s", 666 | item_paths, existing_cache_item['md5Checksum']) 667 | if change['fileId'] in ignored_file_paths: 668 | ignored_file_paths[change['fileId']].extend(item_paths) 669 | else: 670 | ignored_file_paths[change['fileId']] = item_paths 671 | else: 672 | logger.error("No md5Checksum for cache item:\n%s", existing_cache_item) 673 | 674 | elif success and len(item_paths): 675 | # these are new paths/files that were not already in the cache 676 | if change['fileId'] in added_file_paths: 677 | added_file_paths[change['fileId']].extend(item_paths) 678 | else: 679 | added_file_paths[change['fileId']] = item_paths 680 | 681 | elif 'teamDriveId' in change: 682 | # this is a teamdrive change 683 | # dont consider trashed/removed events for processing 684 | if 'removed' in change and change['removed']: 685 | # remove item from cache 686 | if self.remove_item_from_cache(change['teamDriveId']): 687 | if self.show_cache_logs and 'teamDrive' in change and 'name' in change['teamDrive']: 688 | teamdrive_name = 'Unknown teamDrive' 689 | teamdrive_name = change['teamDrive']['name'] 690 | logger.info("Removed teamDrive '%s' from cache: %s", change['teamDriveId'], teamdrive_name) 691 | 692 | self._do_callback('teamdrive_removed', change) 693 | 694 | removes += 1 695 | continue 696 | 697 | if 'teamDrive' in change and 'id' in change['teamDrive'] and 'name' in change['teamDrive']: 698 | # we always want to add changes to the cache so renames etc can be reflected inside the cache 699 | if change['teamDrive']['id'] not in self.cache: 700 | self.cache_manager.get_cache("teamdrive_%s" % change['teamDrive']['id']) 701 | self._do_callback('teamdrive_added', change) 702 | 703 | self.add_item_to_cache(change['teamDrive']['id'], change['teamDrive']['name'], [], None) 704 | continue 705 | 706 | # always dump the cache after running changes 707 | self._dump_cache() 708 | 709 | # display logging 710 | logger.debug("Added: %s", added_file_paths) 711 | logger.debug("Unwanted: %s", unwanted_file_paths) 712 | logger.debug("Ignored: %s", ignored_file_paths) 713 | logger.debug("Renamed: %s", renamed_file_paths) 714 | logger.debug("Moved: %s", moved_file_paths) 715 | 716 | logger.info('%d added / %d removed / %d unwanted / %d ignored / %d renamed / %d moved', len(added_file_paths), 717 | removes, len(unwanted_file_paths), len(ignored_file_paths), len(renamed_file_paths), 718 | len(moved_file_paths)) 719 | 720 | # call further callbacks 721 | self._do_callback('items_added', added_file_paths) 722 | self._do_callback('items_unwanted', unwanted_file_paths) 723 | self._do_callback('items_ignored', ignored_file_paths) 724 | 725 | return 726 | 727 | def _do_callback(self, callback_type, callback_data): 728 | if callback_type in self.callbacks and callback_data: 729 | self.callbacks[callback_type](callback_data) 730 | return 731 | 732 | @staticmethod 733 | def _list_matches(list_master, list_check): 734 | try: 735 | for item in list_master: 736 | if item not in list_check: 737 | return False 738 | return True 739 | except Exception: 740 | logger.exception('Exception checking if lists match: ') 741 | return False 742 | -------------------------------------------------------------------------------- /plex.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import sqlite3 4 | import time 5 | from contextlib import closing 6 | 7 | import db 8 | 9 | try: 10 | from shlex import quote as cmd_quote 11 | except ImportError: 12 | from pipes import quote as cmd_quote 13 | 14 | import requests 15 | import utils 16 | 17 | logger = logging.getLogger("PLEX") 18 | 19 | 20 | def show_detailed_sections_info(conf): 21 | from xml.etree import ElementTree 22 | try: 23 | logger.info("Requesting section info from Plex...") 24 | resp = requests.get('%s/library/sections/all?X-Plex-Token=%s' % ( 25 | conf.configs['PLEX_LOCAL_URL'], conf.configs['PLEX_TOKEN']), timeout=30) 26 | if resp.status_code == 200: 27 | logger.info("Requesting of section info was successful.") 28 | logger.debug("Request response: %s", resp.text) 29 | root = ElementTree.fromstring(resp.text) 30 | print('') 31 | print("Plex Sections:") 32 | print("==============") 33 | for document in root.findall("Directory"): 34 | print('') 35 | print(document.get('key') + ') ' + document.get('title')) 36 | dashes_length = len(document.get('key') + ') ' + document.get('title')) 37 | print('-' * dashes_length) 38 | print("\n".join([os.path.join(k.get('path'), '') for k in document.findall("Location")])) 39 | except Exception as e: 40 | logger.exception("Issue encountered when attempting to list detailed sections info.") 41 | 42 | 43 | def scan(config, lock, path, scan_for, section, scan_type, resleep_paths, scan_title=None, scan_lookup_type=None, 44 | scan_lookup_id=None): 45 | scan_path = "" 46 | 47 | # sleep for delay 48 | while True: 49 | logger.info("Scan request from %s for '%s'.", scan_for, path) 50 | 51 | if config['SERVER_SCAN_DELAY']: 52 | logger.info("Sleeping for %d seconds...", config['SERVER_SCAN_DELAY']) 53 | time.sleep(config['SERVER_SCAN_DELAY']) 54 | 55 | # check if root scan folder for 56 | if path in resleep_paths: 57 | logger.info("Another scan request occurred for folder of '%s'.", path) 58 | logger.info("Sleeping again for %d seconds...", config['SERVER_SCAN_DELAY']) 59 | utils.remove_item_from_list(path, resleep_paths) 60 | else: 61 | break 62 | 63 | # check file exists 64 | checks = 0 65 | check_path = utils.map_pushed_path_file_exists(config, path) 66 | scan_path_is_directory = os.path.isdir(check_path) 67 | 68 | while True: 69 | checks += 1 70 | if os.path.exists(check_path): 71 | logger.info("File '%s' exists on check %d of %d.", check_path, checks, config['SERVER_MAX_FILE_CHECKS']) 72 | if not scan_path or not len(scan_path): 73 | scan_path = os.path.dirname(path).strip() if not scan_path_is_directory else path.strip() 74 | break 75 | elif not scan_path_is_directory and config['SERVER_SCAN_FOLDER_ON_FILE_EXISTS_EXHAUSTION'] and \ 76 | config['SERVER_MAX_FILE_CHECKS'] - checks == 1: 77 | # penultimate check but SERVER_SCAN_FOLDER_ON_FILE_EXISTS_EXHAUSTION was turned on 78 | # lets make scan path the folder instead for the final check 79 | logger.warning( 80 | "File '%s' reached the penultimate file check. Changing scan path to '%s'. Final check commences " 81 | "in %s seconds...", check_path, os.path.dirname(path), config['SERVER_FILE_CHECK_DELAY']) 82 | check_path = os.path.dirname(check_path).strip() 83 | scan_path = os.path.dirname(path).strip() 84 | scan_path_is_directory = os.path.isdir(check_path) 85 | time.sleep(config['SERVER_FILE_CHECK_DELAY']) 86 | # send Rclone cache clear if enabled 87 | if config['RCLONE']['RC_CACHE_REFRESH']['ENABLED']: 88 | utils.rclone_rc_clear_cache(config, check_path) 89 | 90 | elif checks >= config['SERVER_MAX_FILE_CHECKS']: 91 | logger.warning("File '%s' exhausted all available checks. Aborting scan request.", check_path) 92 | # remove item from database if sqlite is enabled 93 | if config['SERVER_USE_SQLITE']: 94 | if db.remove_item(path): 95 | logger.info("Removed '%s' from Plex Autoscan database.", path) 96 | time.sleep(1) 97 | else: 98 | logger.error("Failed removing '%s' from Plex Autoscan database.", path) 99 | return 100 | 101 | else: 102 | logger.info("File '%s' did not exist on check %d of %d. Checking again in %s seconds...", check_path, 103 | checks, 104 | config['SERVER_MAX_FILE_CHECKS'], 105 | config['SERVER_FILE_CHECK_DELAY']) 106 | time.sleep(config['SERVER_FILE_CHECK_DELAY']) 107 | # send Rclone cache clear if enabled 108 | if config['RCLONE']['RC_CACHE_REFRESH']['ENABLED']: 109 | utils.rclone_rc_clear_cache(config, check_path) 110 | 111 | # build plex scanner command 112 | if os.name == 'nt': 113 | final_cmd = '"%s" --scan --refresh --section %s --directory "%s"' \ 114 | % (config['PLEX_SCANNER'], str(section), scan_path) 115 | else: 116 | cmd = 'export LD_LIBRARY_PATH=' + config['PLEX_LD_LIBRARY_PATH'] + ';' 117 | if not config['USE_DOCKER']: 118 | cmd += 'export PLEX_MEDIA_SERVER_APPLICATION_SUPPORT_DIR=' + config['PLEX_SUPPORT_DIR'] + ';' 119 | cmd += config['PLEX_SCANNER'] + ' --scan --refresh --section ' + str(section) + ' --directory ' + cmd_quote( 120 | scan_path) 121 | 122 | if config['USE_DOCKER']: 123 | final_cmd = 'docker exec -u %s -i %s bash -c %s' % \ 124 | (cmd_quote(config['PLEX_USER']), cmd_quote(config['DOCKER_NAME']), cmd_quote(cmd)) 125 | elif config['USE_SUDO']: 126 | final_cmd = 'sudo -u %s bash -c %s' % (config['PLEX_USER'], cmd_quote(cmd)) 127 | else: 128 | final_cmd = cmd 129 | 130 | # invoke plex scanner 131 | priority = utils.get_priority(config, scan_path) 132 | logger.debug("Waiting for turn in the scan request backlog with priority '%d'...", priority) 133 | 134 | lock.acquire(priority) 135 | try: 136 | logger.info("Scan request is now being processed...") 137 | # wait for existing scanners being ran by Plex 138 | if config['PLEX_WAIT_FOR_EXTERNAL_SCANNERS']: 139 | if os.name == 'nt': 140 | scanner_name = os.path.basename(config['PLEX_SCANNER']) 141 | else: 142 | scanner_name = os.path.basename(config['PLEX_SCANNER']).replace('\\', '') 143 | if not utils.wait_running_process(scanner_name, config['USE_DOCKER'], cmd_quote(config['DOCKER_NAME'])): 144 | logger.warning( 145 | "There was a problem waiting for existing '%s' process(s) to finish. Aborting scan.", scanner_name) 146 | # remove item from database if sqlite is enabled 147 | if config['SERVER_USE_SQLITE']: 148 | if db.remove_item(path): 149 | logger.info("Removed '%s' from Plex Autoscan database.", path) 150 | time.sleep(1) 151 | else: 152 | logger.error("Failed removing '%s' from Plex Autoscan database.", path) 153 | return 154 | else: 155 | logger.info("No '%s' processes were found.", scanner_name) 156 | 157 | # run external command before scan if supplied 158 | if len(config['RUN_COMMAND_BEFORE_SCAN']) > 2: 159 | logger.info("Running external command: %r", config['RUN_COMMAND_BEFORE_SCAN']) 160 | utils.run_command(config['RUN_COMMAND_BEFORE_SCAN']) 161 | logger.info("Finished running external command.") 162 | 163 | # wait for Plex to become responsive (if PLEX_CHECK_BEFORE_SCAN is enabled) 164 | if 'PLEX_CHECK_BEFORE_SCAN' in config and config['PLEX_CHECK_BEFORE_SCAN']: 165 | plex_account_user = wait_plex_alive(config) 166 | if plex_account_user is not None: 167 | logger.info("Plex is available for media scanning - (Server Account: '%s')", plex_account_user) 168 | 169 | # begin scan 170 | logger.info("Running Plex Media Scanner for: %s", scan_path) 171 | logger.debug(final_cmd) 172 | if os.name == 'nt': 173 | utils.run_command(final_cmd) 174 | else: 175 | utils.run_command(final_cmd.encode("utf-8")) 176 | logger.info("Finished scan!") 177 | 178 | # remove item from Plex database if sqlite is enabled 179 | if config['SERVER_USE_SQLITE']: 180 | if db.remove_item(path): 181 | logger.debug("Removed '%s' from Plex Autoscan database.", path) 182 | time.sleep(1) 183 | logger.info("There are %d queued item(s) remaining.", db.queued_count()) 184 | else: 185 | logger.error("Failed removing '%s' from Plex Autoscan database.", path) 186 | 187 | # empty trash if configured 188 | if config['PLEX_EMPTY_TRASH'] and config['PLEX_TOKEN'] and config['PLEX_EMPTY_TRASH_MAX_FILES']: 189 | logger.debug("Checking deleted items count in 10 seconds...") 190 | time.sleep(10) 191 | 192 | # check deleted item count, don't proceed if more than this value 193 | deleted_items = get_deleted_count(config) 194 | if deleted_items > config['PLEX_EMPTY_TRASH_MAX_FILES']: 195 | logger.warning("There were %d deleted files. Skip emptying of trash for Section '%s'.", deleted_items, 196 | section) 197 | elif deleted_items == -1: 198 | logger.error("Could not determine deleted item count. Abort emptying of trash.") 199 | elif not config['PLEX_EMPTY_TRASH_ZERO_DELETED'] and not deleted_items and scan_type != 'Upgrade': 200 | logger.debug("Skipping emptying trash as there were no deleted items.") 201 | else: 202 | logger.info("Emptying trash to clear %d deleted items...", deleted_items) 203 | empty_trash(config, str(section)) 204 | 205 | # analyze movie/episode 206 | if config['PLEX_ANALYZE_TYPE'].lower() != 'off' and not scan_path_is_directory: 207 | logger.debug("Sleeping for 10 seconds...") 208 | time.sleep(10) 209 | logger.debug("Sending analysis request...") 210 | analyze_item(config, path) 211 | 212 | # match item 213 | if config['PLEX_FIX_MISMATCHED'] and config['PLEX_TOKEN'] and not scan_path_is_directory: 214 | # were we initiated with the scan_title/scan_lookup_type/scan_lookup_id parameters? 215 | if scan_title is not None and scan_lookup_type is not None and scan_lookup_id is not None: 216 | logger.debug("Sleeping for 10 seconds...") 217 | time.sleep(10) 218 | logger.debug("Validating match for '%s' (%s ID: %s)...", 219 | scan_title, 220 | scan_lookup_type, str(scan_lookup_id)) 221 | match_item_parent(config, path, scan_title, scan_lookup_type, scan_lookup_id) 222 | 223 | # run external command after scan if supplied 224 | if len(config['RUN_COMMAND_AFTER_SCAN']) > 2: 225 | logger.info("Running external command: %r", config['RUN_COMMAND_AFTER_SCAN']) 226 | utils.run_command(config['RUN_COMMAND_AFTER_SCAN']) 227 | logger.info("Finished running external command.") 228 | 229 | except Exception: 230 | logger.exception("Unexpected exception occurred while processing: '%s'", scan_path) 231 | finally: 232 | lock.release() 233 | return 234 | 235 | 236 | def show_sections(config): 237 | if os.name == 'nt': 238 | final_cmd = '""%s" --list"' % config['PLEX_SCANNER'] 239 | else: 240 | cmd = 'export LD_LIBRARY_PATH=' + config['PLEX_LD_LIBRARY_PATH'] + ';' 241 | if not config['USE_DOCKER']: 242 | cmd += 'export PLEX_MEDIA_SERVER_APPLICATION_SUPPORT_DIR=' + config['PLEX_SUPPORT_DIR'] + ';' 243 | cmd += config['PLEX_SCANNER'] + ' --list' 244 | 245 | if config['USE_DOCKER']: 246 | final_cmd = 'docker exec -u %s -it %s bash -c %s' % ( 247 | cmd_quote(config['PLEX_USER']), cmd_quote(config['DOCKER_NAME']), cmd_quote(cmd)) 248 | elif config['USE_SUDO']: 249 | final_cmd = 'sudo -u %s bash -c "%s"' % (config['PLEX_USER'], cmd) 250 | else: 251 | final_cmd = cmd 252 | logger.info("Using Plex Scanner") 253 | print("\n") 254 | print("Plex Sections:") 255 | print("==============") 256 | logger.debug(final_cmd) 257 | os.system(final_cmd) 258 | 259 | 260 | def match_item_parent(config, scan_path, scan_title, scan_lookup_type, scan_lookup_id): 261 | if not os.path.exists(config['PLEX_DATABASE_PATH']): 262 | logger.info("Could not analyze '%s' because Plex database could not be found.", scan_path) 263 | return 264 | 265 | # get files metadata_item_id 266 | metadata_item_id = get_file_metadata_item_id(config, scan_path) 267 | if metadata_item_id is None: 268 | logger.error("Aborting match of '%s' as could not find 'metadata_item_id'.", scan_path) 269 | return 270 | 271 | # find metadata_item_id parent info 272 | metadata_item_parent_info = get_metadata_parent_info(config, int(metadata_item_id)) 273 | if metadata_item_parent_info is None or 'parent_id' not in metadata_item_parent_info \ 274 | or metadata_item_parent_info['parent_id'] is not None or 'id' not in metadata_item_parent_info \ 275 | or 'title' not in metadata_item_parent_info: 276 | # parent_id should always be null as we are looking for a series or movie metadata_item_id which has no parent! 277 | logger.error( 278 | "Aborting match of '%s' because could not find 'metadata_item_id' of parent for 'metadata_item_id': %d", 279 | scan_path, int(metadata_item_id)) 280 | return 281 | 282 | parent_metadata_item_id = metadata_item_parent_info['id'] 283 | parent_title = metadata_item_parent_info['title'] 284 | parent_guid = metadata_item_parent_info['guid'] 285 | logger.debug("Found parent 'metadata_item' of '%s': %d = '%s'.", scan_path, int(parent_metadata_item_id), 286 | parent_title) 287 | 288 | # did the metadata_item_id have matches already (dupes)? 289 | scan_directory = os.path.dirname(scan_path) 290 | metadata_item_id_has_dupes = get_metadata_item_id_has_duplicates(config, metadata_item_id, scan_directory) 291 | if metadata_item_id_has_dupes: 292 | # there are multiple media_items with this metadata_item_id who's folder does not match the scan directory 293 | # we must split the parent metadata_item, wait 10 seconds and then repeat the steps above 294 | if not split_plex_item(config, parent_metadata_item_id): 295 | logger.error( 296 | "Aborting match of '%s' as could not split duplicate 'media_items' with 'metadata_item_id': '%d'", 297 | scan_path, int(parent_metadata_item_id)) 298 | return 299 | 300 | # reset variables from last lookup 301 | metadata_item_id = None 302 | parent_metadata_item_id = None 303 | parent_title = None 304 | parent_guid = None 305 | 306 | # sleep before looking up metadata_item_id again 307 | time.sleep(10) 308 | metadata_item_id = get_file_metadata_item_id(config, scan_path) 309 | if metadata_item_id is None: 310 | logger.error("Aborting match of '%s' as could not find post split 'metadata_item_id'.", scan_path) 311 | return 312 | 313 | # now lookup parent again 314 | metadata_item_parent_info = get_metadata_parent_info(config, int(metadata_item_id)) 315 | if metadata_item_parent_info is None or 'parent_id' not in metadata_item_parent_info \ 316 | or metadata_item_parent_info['parent_id'] is not None or 'id' not in metadata_item_parent_info \ 317 | or 'title' not in metadata_item_parent_info: 318 | # parent_id should always be null as we are looking for a series or movie metadata_item_id 319 | # which has no parent! 320 | logger.error( 321 | "Aborting match of '%s' as could not find post-split 'metadata_item_id' of parent for " 322 | "'metadata_item_id': %d", scan_path, int(metadata_item_id)) 323 | return 324 | 325 | parent_metadata_item_id = metadata_item_parent_info['id'] 326 | parent_title = metadata_item_parent_info['title'] 327 | parent_guid = metadata_item_parent_info['guid'] 328 | logger.debug("Found parent 'metadata_item' of '%s': %d = '%s'.", scan_path, int(parent_metadata_item_id), 329 | parent_title) 330 | 331 | else: 332 | # there were no duplicate media_items with this metadata_item_id 333 | logger.info("No duplicate 'media_items' found with 'metadata_item_id': '%d'", int(parent_metadata_item_id)) 334 | 335 | # generate new guid 336 | new_guid = 'com.plexapp.agents.%s://%s?lang=%s' % (scan_lookup_type.lower(), str(scan_lookup_id).lower(), 337 | config['PLEX_FIX_MISMATCHED_LANG'].lower()) 338 | # does good match? 339 | if parent_guid and (parent_guid.lower() != new_guid): 340 | logger.debug("Fixing match for 'metadata_item' '%s' as existing 'GUID' '%s' does not match '%s' ('%s').", 341 | parent_title, 342 | parent_guid, new_guid, scan_title) 343 | logger.info("Fixing match of '%s' (%s) to '%s' (%s).", parent_title, parent_guid, scan_title, new_guid) 344 | # fix item 345 | match_plex_item(config, parent_metadata_item_id, new_guid, scan_title) 346 | refresh_plex_item(config, parent_metadata_item_id, scan_title) 347 | else: 348 | logger.debug( 349 | "Skipped match fixing for 'metadata_item' parent '%s' as existing 'GUID' (%s) matches what was " 350 | "expected (%s).", parent_title, parent_guid, new_guid) 351 | logger.info("Match validated for '%s' (%s).", parent_title, parent_guid) 352 | 353 | return 354 | 355 | 356 | def analyze_item(config, scan_path): 357 | if not os.path.exists(config['PLEX_DATABASE_PATH']): 358 | logger.warning("Could not analyze of '%s' because Plex database could not be found.", scan_path) 359 | return 360 | # get files metadata_item_id 361 | metadata_item_ids = get_file_metadata_ids(config, scan_path) 362 | if metadata_item_ids is None or not len(metadata_item_ids): 363 | logger.warning("Aborting analysis of '%s' because could not find any 'metadata_item_id' for it.", scan_path) 364 | return 365 | metadata_item_id = ','.join(str(x) for x in metadata_item_ids) 366 | 367 | # build Plex analyze command 368 | analyze_type = 'analyze-deeply' if config['PLEX_ANALYZE_TYPE'].lower() == 'deep' else 'analyze' 369 | if os.name == 'nt': 370 | final_cmd = '"%s" --%s --item %s' % (config['PLEX_SCANNER'], analyze_type, metadata_item_id) 371 | else: 372 | cmd = 'export LD_LIBRARY_PATH=' + config['PLEX_LD_LIBRARY_PATH'] + ';' 373 | if not config['USE_DOCKER']: 374 | cmd += 'export PLEX_MEDIA_SERVER_APPLICATION_SUPPORT_DIR=' + config['PLEX_SUPPORT_DIR'] + ';' 375 | cmd += config['PLEX_SCANNER'] + ' --' + analyze_type + ' --item ' + metadata_item_id 376 | 377 | if config['USE_DOCKER']: 378 | final_cmd = 'docker exec -u %s -i %s bash -c %s' % \ 379 | (cmd_quote(config['PLEX_USER']), cmd_quote(config['DOCKER_NAME']), cmd_quote(cmd)) 380 | elif config['USE_SUDO']: 381 | final_cmd = 'sudo -u %s bash -c %s' % (config['PLEX_USER'], cmd_quote(cmd)) 382 | else: 383 | final_cmd = cmd 384 | 385 | # begin analysis 386 | logger.debug("Starting %s analysis of 'metadata_item': %s", 387 | 'deep' if config['PLEX_ANALYZE_TYPE'].lower() == 'deep' else 'basic', metadata_item_id) 388 | logger.debug(final_cmd) 389 | if os.name == 'nt': 390 | utils.run_command(final_cmd) 391 | else: 392 | utils.run_command(final_cmd.encode("utf-8")) 393 | logger.info("Finished %s analysis of 'metadata_item': %s", 394 | 'deep' if config['PLEX_ANALYZE_TYPE'].lower() == 'deep' else 'basic', metadata_item_id) 395 | 396 | 397 | def get_file_metadata_item_id(config, file_path): 398 | try: 399 | with sqlite3.connect(config['PLEX_DATABASE_PATH']) as conn: 400 | conn.row_factory = sqlite3.Row 401 | with closing(conn.cursor()) as c: 402 | # query media_parts to retrieve media_item_row for this file 403 | for x in range(5): 404 | media_item_row = c.execute("SELECT * FROM media_parts WHERE file=?", (file_path,)).fetchone() 405 | if media_item_row: 406 | logger.debug("Found row in 'media_parts' where 'file' = '%s' after %d of 5 tries.", file_path, 407 | x + 1) 408 | break 409 | else: 410 | logger.error( 411 | "Could not locate record in 'media_parts' where 'file' = '%s' in %d of 5 attempts...", 412 | file_path, x + 1) 413 | time.sleep(10) 414 | 415 | if not media_item_row: 416 | logger.error("Could not locate record in 'media_parts' where 'file' = '%s' after 5 tries.", 417 | file_path) 418 | return None 419 | 420 | media_item_id = media_item_row['media_item_id'] 421 | if media_item_id and int(media_item_id): 422 | # query db to find metadata_item_id 423 | metadata_item_id = \ 424 | c.execute("SELECT * FROM media_items WHERE id=?", (int(media_item_id),)).fetchone()[ 425 | 'metadata_item_id'] 426 | if metadata_item_id and int(metadata_item_id): 427 | logger.debug("Found 'metadata_item_id' for '%s': %d", file_path, int(metadata_item_id)) 428 | return int(metadata_item_id) 429 | 430 | except Exception: 431 | logger.exception("Exception finding 'metadata_item_id' for '%s': ", file_path) 432 | return None 433 | 434 | 435 | def get_metadata_item_id_has_duplicates(config, metadata_item_id, scan_directory): 436 | try: 437 | with sqlite3.connect(config['PLEX_DATABASE_PATH']) as conn: 438 | conn.row_factory = sqlite3.Row 439 | with closing(conn.cursor()) as c: 440 | # retrieve matches for metadata_item_id 441 | metadata_item_id_matches = c.execute('select ' 442 | 'count(mi.id) as matches ' 443 | 'from media_items mi ' 444 | 'join media_parts mp on mp.media_item_id = mi.id ' 445 | 'where mi.metadata_item_id=? and mp.file not like ?', 446 | (metadata_item_id, scan_directory + '%',)).fetchone() 447 | if metadata_item_id_matches: 448 | row_dict = dict(metadata_item_id_matches) 449 | if 'matches' in row_dict and row_dict['matches'] >= 1: 450 | logger.info( 451 | "Found %d 'media_items' with 'metadata_item_id' %d where folder does not match: '%s'", 452 | int(row_dict['matches']), int(metadata_item_id), scan_directory) 453 | return True 454 | else: 455 | return False 456 | 457 | logger.error("Failed determining if 'metadata_item_id' '%d' has duplicate 'media_items'.", 458 | int(metadata_item_id)) 459 | except Exception: 460 | logger.exception("Exception determining if 'metadata_item_id' '%d' has duplicate 'media_items': ", 461 | int(metadata_item_id)) 462 | return False 463 | 464 | 465 | def get_metadata_parent_info(config, metadata_item_id): 466 | try: 467 | with sqlite3.connect(config['PLEX_DATABASE_PATH']) as conn: 468 | conn.row_factory = sqlite3.Row 469 | with closing(conn.cursor()) as c: 470 | # retrieve parent info for metadata_item_id 471 | metadata_item_parent_info = c.execute('WITH cte_MediaItems AS (' 472 | 'SELECT ' 473 | 'mi.* ' 474 | 'FROM metadata_items mi ' 475 | 'WHERE mi.id = ? ' 476 | 'UNION ' 477 | 'SELECT mi.* ' 478 | 'FROM cte_MediaItems cte ' 479 | 'JOIN metadata_items mi ON mi.id = cte.parent_id' 480 | ') ' 481 | 'SELECT ' 482 | 'cte.id' 483 | ', cte.parent_id' 484 | ', cte.guid' 485 | ', cte.title ' 486 | 'FROM cte_MediaItems cte ' 487 | 'WHERE cte.parent_id IS NULL ' 488 | 'LIMIT 1', (metadata_item_id,)).fetchone() 489 | if metadata_item_parent_info: 490 | metadata_item_row = dict(metadata_item_parent_info) 491 | if 'parent_id' in metadata_item_row and not metadata_item_row['parent_id']: 492 | logger.debug("Found parent row in 'metadata_items' for 'metadata_item_id' '%d': %s", 493 | int(metadata_item_id), metadata_item_row) 494 | return metadata_item_row 495 | 496 | logger.error("Failed finding parent row in 'metadata_items' for 'metadata_item_id': %d", 497 | int(metadata_item_id)) 498 | 499 | except Exception: 500 | logger.exception("Exception finding parent info for 'metadata_item_id' '%d': ", int(metadata_item_id)) 501 | return None 502 | 503 | 504 | def get_file_metadata_ids(config, file_path): 505 | results = [] 506 | media_item_row = None 507 | 508 | try: 509 | with sqlite3.connect(config['PLEX_DATABASE_PATH']) as conn: 510 | conn.row_factory = sqlite3.Row 511 | with closing(conn.cursor()) as c: 512 | # query media_parts to retrieve media_item_row for this file 513 | for x in range(5): 514 | media_item_row = c.execute("SELECT * FROM media_parts WHERE file=?", (file_path,)).fetchone() 515 | if media_item_row: 516 | logger.debug("Found row in 'media_parts' where 'file' = '%s' after %d of 5 tries.", file_path, 517 | x + 1) 518 | break 519 | else: 520 | logger.error( 521 | "Could not locate record in 'media_parts' where 'file' = '%s' in %d of 5 attempts...", 522 | file_path, x + 1) 523 | time.sleep(10) 524 | 525 | if not media_item_row: 526 | logger.error("Could not locate record in 'media_parts' where 'file' = '%s' after 5 tries", 527 | file_path) 528 | return None 529 | 530 | media_item_id = media_item_row['media_item_id'] 531 | if media_item_id and int(media_item_id): 532 | # query db to find metadata_item_id 533 | metadata_item_id = \ 534 | c.execute("SELECT * FROM media_items WHERE id=?", (int(media_item_id),)).fetchone()[ 535 | 'metadata_item_id'] 536 | if metadata_item_id and int(metadata_item_id): 537 | logger.debug("Found 'metadata_item_id' for '%s': %d", file_path, int(metadata_item_id)) 538 | 539 | # query db to find parent_id of metadata_item_id 540 | if config['PLEX_ANALYZE_DIRECTORY']: 541 | parent_id = \ 542 | c.execute("SELECT * FROM metadata_items WHERE id=?", 543 | (int(metadata_item_id),)).fetchone()['parent_id'] 544 | if not parent_id or not int(parent_id): 545 | # could not find parent_id of this item, likely its a movie... 546 | # lets just return the metadata_item_id 547 | return [int(metadata_item_id)] 548 | logger.debug("Found 'parent_id' for '%s': %d", file_path, int(parent_id)) 549 | 550 | # if mode is basic, single parent_id is enough 551 | if config['PLEX_ANALYZE_TYPE'].lower() == 'basic': 552 | return [int(parent_id)] 553 | 554 | # lets find all metadata_item_id's with this parent_id for use with deep analysis 555 | metadata_items = c.execute("SELECT * FROM metadata_items WHERE parent_id=?", 556 | (int(parent_id),)).fetchall() 557 | if not metadata_items: 558 | # could not find any results, lets just return metadata_item_id 559 | return [int(metadata_item_id)] 560 | 561 | for row in metadata_items: 562 | if row['id'] and int(row['id']) and int(row['id']) not in results: 563 | results.append(int(row['id'])) 564 | 565 | logger.debug("Found 'media_item_id' for '%s': %s", file_path, results) 566 | logger.info("Found %d 'media_item_id' to deep analyze for: '%s'", len(results), file_path) 567 | else: 568 | # user had PLEX_ANALYZE_DIRECTORY as False - lets just scan the single metadata_item_id 569 | results.append(int(metadata_item_id)) 570 | 571 | except Exception as ex: 572 | logger.exception("Exception finding metadata_item_id for '%s': ", file_path) 573 | return results 574 | 575 | 576 | def empty_trash(config, section): 577 | if len(config['PLEX_EMPTY_TRASH_CONTROL_FILES']): 578 | logger.info("Control file(s) are specified.") 579 | 580 | for control in config['PLEX_EMPTY_TRASH_CONTROL_FILES']: 581 | if not os.path.exists(control): 582 | logger.info("Skip emptying of trash as control file is not present: '%s'", control) 583 | return 584 | 585 | logger.info("Commence emptying of trash as control file(s) are present.") 586 | 587 | for x in range(5): 588 | try: 589 | resp = requests.put('%s/library/sections/%s/emptyTrash?X-Plex-Token=%s' % ( 590 | config['PLEX_LOCAL_URL'], section, config['PLEX_TOKEN']), data=None, timeout=30) 591 | if resp.status_code == 200: 592 | logger.info("Trash cleared for Section '%s' after %d of 5 tries.", section, x + 1) 593 | break 594 | else: 595 | logger.error("Unexpected response status_code for empty trash request: %d in %d of 5 attempts...", 596 | resp.status_code, x + 1) 597 | time.sleep(10) 598 | except Exception as ex: 599 | logger.exception("Exception sending empty trash for Section '%s' in %d of 5 attempts: ", section, x + 1) 600 | time.sleep(10) 601 | return 602 | 603 | 604 | def wait_plex_alive(config): 605 | if not config['PLEX_LOCAL_URL'] or not config['PLEX_TOKEN']: 606 | logger.error( 607 | "Unable to check if Plex was ready for scan requests because 'PLEX_LOCAL_URL' and/or 'PLEX_TOKEN' are missing in config.") 608 | return None 609 | 610 | # PLEX_LOCAL_URL and PLEX_TOKEN was provided 611 | check_attempts = 0 612 | while True: 613 | check_attempts += 1 614 | try: 615 | resp = requests.get('%s/myplex/account' % (config['PLEX_LOCAL_URL']), 616 | headers={'X-Plex-Token': config['PLEX_TOKEN'], 'Accept': 'application/json'}, 617 | timeout=30, verify=False) 618 | if resp.status_code == 200 and 'json' in resp.headers['Content-Type']: 619 | resp_json = resp.json() 620 | if 'MyPlex' in resp_json: 621 | plex_user = resp_json['MyPlex']['username'] if 'username' in resp_json['MyPlex'] else 'Unknown' 622 | return plex_user 623 | 624 | logger.error("Unexpected response when checking if Plex was available for scans " 625 | "(Attempt: %d): status_code = %d - resp_text =\n%s", 626 | check_attempts, resp.status_code, resp.text) 627 | except Exception: 628 | logger.exception("Exception checking if Plex was available at %s: ", config['PLEX_LOCAL_URL']) 629 | 630 | logger.warning("Checking again in 15 seconds (attempt %d)...", check_attempts) 631 | time.sleep(15) 632 | continue 633 | return None 634 | 635 | 636 | def get_deleted_count(config): 637 | try: 638 | with sqlite3.connect(config['PLEX_DATABASE_PATH']) as conn: 639 | with closing(conn.cursor()) as c: 640 | deleted_metadata = \ 641 | c.execute('SELECT count(*) FROM metadata_items WHERE deleted_at IS NOT NULL').fetchone()[0] 642 | deleted_media_parts = \ 643 | c.execute('SELECT count(*) FROM media_parts WHERE deleted_at IS NOT NULL').fetchone()[0] 644 | 645 | return int(deleted_metadata) + int(deleted_media_parts) 646 | 647 | except Exception as ex: 648 | logger.exception("Exception retrieving deleted item count from Plex DB: ") 649 | return -1 650 | 651 | 652 | def split_plex_item(config, metadata_item_id): 653 | try: 654 | url_params = { 655 | 'X-Plex-Token': config['PLEX_TOKEN'] 656 | } 657 | url_str = '%s/library/metadata/%d/split' % (config['PLEX_LOCAL_URL'], int(metadata_item_id)) 658 | 659 | # send options request first (webui does this) 660 | requests.options(url_str, params=url_params, timeout=30) 661 | resp = requests.put(url_str, params=url_params, timeout=30) 662 | if resp.status_code == 200: 663 | logger.info("Successfully split 'metadata_item_id': '%d'", int(metadata_item_id)) 664 | return True 665 | else: 666 | logger.error("Failed splitting 'metadata_item_id': '%d'... Response =\n%s\n", int(metadata_item_id), 667 | resp.text) 668 | 669 | except Exception: 670 | logger.exception("Exception splitting 'metadata_item' %d: ", int(metadata_item_id)) 671 | return False 672 | 673 | 674 | def match_plex_item(config, metadata_item_id, new_guid, new_name): 675 | try: 676 | url_params = { 677 | 'X-Plex-Token': config['PLEX_TOKEN'], 678 | 'guid': new_guid, 679 | 'name': new_name, 680 | } 681 | url_str = '%s/library/metadata/%d/match' % (config['PLEX_LOCAL_URL'], int(metadata_item_id)) 682 | 683 | requests.options(url_str, params=url_params, timeout=30) 684 | resp = requests.put(url_str, params=url_params, timeout=30) 685 | if resp.status_code == 200: 686 | logger.info("Successfully matched 'metadata_item_id' '%d' to '%s' (%s).", int(metadata_item_id), new_name, 687 | new_guid) 688 | return True 689 | else: 690 | logger.error("Failed matching 'metadata_item_id' '%d' to '%s': %s... Response =\n%s\n", 691 | int(metadata_item_id), 692 | new_name, new_guid, resp.text) 693 | 694 | except Exception: 695 | logger.exception("Exception matching 'metadata_item' %d: ", int(metadata_item_id)) 696 | return False 697 | 698 | 699 | def refresh_plex_item(config, metadata_item_id, new_name): 700 | try: 701 | url_params = { 702 | 'X-Plex-Token': config['PLEX_TOKEN'], 703 | } 704 | url_str = '%s/library/metadata/%d/refresh' % (config['PLEX_LOCAL_URL'], int(metadata_item_id)) 705 | 706 | requests.options(url_str, params=url_params, timeout=30) 707 | resp = requests.put(url_str, params=url_params, timeout=30) 708 | if resp.status_code == 200: 709 | logger.info("Successfully refreshed 'metadata_item_id' '%d' of '%s'.", int(metadata_item_id), 710 | new_name) 711 | return True 712 | else: 713 | logger.error("Failed refreshing 'metadata_item_id' '%d' of '%s': Response =\n%s\n", 714 | int(metadata_item_id), 715 | new_name, resp.text) 716 | 717 | except Exception: 718 | logger.exception("Exception refreshing 'metadata_item' %d: ", int(metadata_item_id)) 719 | return False -------------------------------------------------------------------------------- /rclone.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | import os 3 | import logging 4 | 5 | logger = logging.getLogger("RCLONE") 6 | 7 | class RcloneDecoder: 8 | def __init__(self, binary, crypt_mappings, config): 9 | self._binary = binary 10 | if self._binary == "" or not os.path.isfile(binary): 11 | self._binary = os.path.normpath(subprocess.check_output(["which", "rclone"]).decode().rstrip('\n')) 12 | logger.debug("Rclone binary path located as: '%s'", binary) 13 | 14 | self._config = config 15 | self._crypt_mappings = crypt_mappings 16 | 17 | def decode_path(self, path): 18 | for crypt_dir, mapped_remotes in self._crypt_mappings.items(): 19 | # Isolate root/file path and attempt to locate entry in mappings 20 | file_path = path.replace(crypt_dir,'') 21 | logger.debug("Encoded file path identified as: '%s'", file_path) 22 | if path.lower().startswith(crypt_dir.lower()): 23 | for mapped_remote in mapped_remotes: 24 | logger.debug("Crypt base directory identified as: '%s'", crypt_dir) 25 | logger.debug("Crypt base directory '%s' has mapping defined in config as remote '%s'.", crypt_dir, mapped_remote) 26 | logger.info("Attempting to decode...") 27 | logger.debug("Raw query is: '%s'", " ".join([self._binary, "--config", self._config, "cryptdecode", mapped_remote, file_path])) 28 | try: 29 | decoded = subprocess.check_output([self._binary, "--config", self._config, "cryptdecode", mapped_remote, file_path], stderr=subprocess.STDOUT).decode('utf-8').rstrip('\n') 30 | except subprocess.CalledProcessError as e: 31 | logger.error("Command '%s' returned with error (code %s): %s", e.cmd, e.returncode, e.output) 32 | return None 33 | 34 | decoded = decoded.split(' ',1)[1].lstrip() 35 | 36 | if "failed" in decoded.lower(): 37 | logger.error("Failed to decode path: '%s'", file_path) 38 | else: 39 | logger.debug("Decoded path of '%s' is: '%s'", file_path, os.path.join(crypt_dir, decoded)) 40 | logger.info("Decode successful.") 41 | return [os.path.join(crypt_dir, decoded)] 42 | else: 43 | logger.debug("Ignoring crypt decode for path '%s' because '%s' was not matched from 'CRYPT_MAPPINGS'.", path, crypt_dir) 44 | return None 45 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | backoff~=1.9.0 2 | certifi~=2019.9.11 3 | chardet~=3.0.4 4 | Click~=7.0 5 | Flask~=1.1.1 6 | idna~=2.8 7 | itsdangerous~=1.1.0 8 | Jinja2~=2.10 9 | MarkupSafe~=1.1.1 10 | oauthlib~=3.1.0 11 | peewee~=2.10.2 12 | psutil~=5.6.5 13 | requests~=2.22.0 14 | requests-oauthlib~=1.3.0 15 | sqlitedict~=1.6.0 16 | urllib3~=1.25.7 17 | Werkzeug~=0.16.0 18 | pyfiglet~=0.8.post1 19 | -------------------------------------------------------------------------------- /scan.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | import json 4 | import logging 5 | import os 6 | import sys 7 | import time 8 | from pyfiglet import Figlet 9 | from logging.handlers import RotatingFileHandler 10 | 11 | # urllib3 12 | import urllib3 13 | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) 14 | 15 | # Replace Python2.X input with raw_input, renamed to input in Python 3 16 | if hasattr(__builtins__, 'raw_input'): 17 | input = raw_input 18 | 19 | from flask import Flask 20 | from flask import abort 21 | from flask import jsonify 22 | from flask import request 23 | 24 | # Get config 25 | import config 26 | import threads 27 | 28 | ############################################################ 29 | # INIT 30 | ############################################################ 31 | 32 | # Logging 33 | logFormatter = logging.Formatter('%(asctime)24s - %(levelname)8s - %(name)9s [%(thread)5d]: %(message)s') 34 | rootLogger = logging.getLogger() 35 | rootLogger.setLevel(logging.INFO) 36 | 37 | # Decrease modules logging 38 | logging.getLogger('requests').setLevel(logging.ERROR) 39 | logging.getLogger('werkzeug').setLevel(logging.ERROR) 40 | logging.getLogger('peewee').setLevel(logging.ERROR) 41 | logging.getLogger('urllib3.connectionpool').setLevel(logging.ERROR) 42 | logging.getLogger('sqlitedict').setLevel(logging.ERROR) 43 | 44 | # Console logger, log to stdout instead of stderr 45 | consoleHandler = logging.StreamHandler(sys.stdout) 46 | consoleHandler.setFormatter(logFormatter) 47 | rootLogger.addHandler(consoleHandler) 48 | 49 | # Load initial config 50 | conf = config.Config() 51 | 52 | # File logger 53 | fileHandler = RotatingFileHandler( 54 | conf.settings['logfile'], 55 | maxBytes=1024 * 1024 * 2, 56 | backupCount=5, 57 | encoding='utf-8' 58 | ) 59 | fileHandler.setFormatter(logFormatter) 60 | rootLogger.addHandler(fileHandler) 61 | 62 | # Set configured log level 63 | rootLogger.setLevel(conf.settings['loglevel']) 64 | # Load config file 65 | conf.load() 66 | 67 | # Scan logger 68 | logger = rootLogger.getChild("AUTOSCAN") 69 | 70 | # Multiprocessing 71 | thread = threads.Thread() 72 | scan_lock = threads.PriorityLock() 73 | resleep_paths = [] 74 | 75 | # local imports 76 | import db 77 | import plex 78 | import utils 79 | import rclone 80 | import google 81 | 82 | google_drive = None 83 | manager = None 84 | 85 | 86 | ############################################################ 87 | # QUEUE PROCESSOR 88 | ############################################################ 89 | 90 | 91 | def queue_processor(): 92 | logger.info("Starting queue processor in 10 seconds...") 93 | try: 94 | time.sleep(10) 95 | logger.info("Queue processor started.") 96 | db_scan_requests = db.get_all_items() 97 | items = 0 98 | for db_item in db_scan_requests: 99 | thread.start(plex.scan, args=[conf.configs, scan_lock, db_item['scan_path'], db_item['scan_for'], 100 | db_item['scan_section'], 101 | db_item['scan_type'], resleep_paths]) 102 | items += 1 103 | time.sleep(2) 104 | logger.info("Restored %d scan request(s) from Plex Autoscan database.", items) 105 | except Exception: 106 | logger.exception("Exception while processing scan requests from Plex Autoscan database.") 107 | return 108 | 109 | 110 | ############################################################ 111 | # FUNCS 112 | ############################################################ 113 | 114 | 115 | def start_scan(path, scan_for, scan_type, scan_title=None, scan_lookup_type=None, scan_lookup_id=None): 116 | section = utils.get_plex_section(conf.configs, path) 117 | if section <= 0: 118 | return False 119 | else: 120 | logger.info("Using Section ID '%d' for '%s'", section, path) 121 | 122 | if conf.configs['SERVER_USE_SQLITE']: 123 | db_exists, db_file = db.exists_file_root_path(path) 124 | if not db_exists and db.add_item(path, scan_for, section, scan_type): 125 | logger.info("Added '%s' to Plex Autoscan database.", path) 126 | logger.info("Proceeding with scan...") 127 | else: 128 | logger.info( 129 | "Already processing '%s' from same folder. Skip adding extra scan request to the queue.", db_file) 130 | resleep_paths.append(db_file) 131 | return False 132 | 133 | thread.start(plex.scan, 134 | args=[conf.configs, scan_lock, path, scan_for, section, scan_type, resleep_paths, scan_title, 135 | scan_lookup_type, scan_lookup_id]) 136 | return True 137 | 138 | 139 | def start_queue_reloader(): 140 | thread.start(queue_processor) 141 | return True 142 | 143 | 144 | def start_google_monitor(): 145 | thread.start(thread_google_monitor) 146 | return True 147 | 148 | 149 | ############################################################ 150 | # GOOGLE DRIVE 151 | ############################################################ 152 | 153 | def process_google_changes(items_added): 154 | new_file_paths = [] 155 | 156 | # process items added 157 | if not items_added: 158 | return True 159 | 160 | for file_id, file_paths in items_added.items(): 161 | for file_path in file_paths: 162 | if file_path in new_file_paths: 163 | continue 164 | new_file_paths.append(file_path) 165 | 166 | # remove files that already exist in the plex database 167 | removed_rejected_exists = utils.remove_files_exist_in_plex_database(conf.configs, 168 | new_file_paths) 169 | 170 | if removed_rejected_exists: 171 | logger.info("Rejected %d file(s) from Google Drive changes for already being in Plex.", 172 | removed_rejected_exists) 173 | 174 | # process the file_paths list 175 | if len(new_file_paths): 176 | logger.info("Proceeding with scan of %d file(s) from Google Drive changes: %s", len(new_file_paths), 177 | new_file_paths) 178 | 179 | # loop each file, remapping and starting a scan thread 180 | for file_path in new_file_paths: 181 | final_path = utils.map_pushed_path(conf.configs, file_path) 182 | start_scan(final_path, 'Google Drive', 'Download') 183 | 184 | return True 185 | 186 | 187 | def thread_google_monitor(): 188 | global manager 189 | 190 | logger.info("Starting Google Drive monitoring in 30 seconds...") 191 | time.sleep(30) 192 | 193 | # initialize crypt_decoder to None 194 | crypt_decoder = None 195 | 196 | # load rclone client if crypt being used 197 | if conf.configs['RCLONE']['CRYPT_MAPPINGS'] != {}: 198 | logger.info("Crypt mappings have been defined. Initializing Rclone Crypt Decoder...") 199 | crypt_decoder = rclone.RcloneDecoder(conf.configs['RCLONE']['BINARY'], conf.configs['RCLONE']['CRYPT_MAPPINGS'], 200 | conf.configs['RCLONE']['CONFIG']) 201 | 202 | # load google drive manager 203 | manager = google.GoogleDriveManager(conf.configs['GOOGLE']['CLIENT_ID'], conf.configs['GOOGLE']['CLIENT_SECRET'], 204 | conf.settings['cachefile'], allowed_config=conf.configs['GOOGLE']['ALLOWED'], 205 | show_cache_logs=conf.configs['GOOGLE']['SHOW_CACHE_LOGS'], 206 | crypt_decoder=crypt_decoder, allowed_teamdrives=conf.configs['GOOGLE']['TEAMDRIVES']) 207 | 208 | if not manager.is_authorized(): 209 | logger.error("Failed to validate Google Drive Access Token.") 210 | exit(1) 211 | else: 212 | logger.info("Google Drive access token was successfully validated.") 213 | 214 | # load teamdrives (if enabled) 215 | if conf.configs['GOOGLE']['TEAMDRIVE'] and not manager.load_teamdrives(): 216 | logger.error("Failed to load Google Teamdrives.") 217 | exit(1) 218 | 219 | # set callbacks 220 | manager.set_callbacks({'items_added': process_google_changes}) 221 | 222 | try: 223 | logger.info("Google Drive changes monitor started.") 224 | while True: 225 | # poll for changes 226 | manager.get_changes() 227 | # sleep before polling for changes again 228 | time.sleep(conf.configs['GOOGLE']['POLL_INTERVAL']) 229 | 230 | except Exception: 231 | logger.exception("Fatal Exception occurred while monitoring Google Drive for changes: ") 232 | 233 | 234 | ############################################################ 235 | # SERVER 236 | ############################################################ 237 | 238 | app = Flask(__name__) 239 | app.config['JSON_AS_ASCII'] = False 240 | 241 | 242 | @app.route("/api/%s" % conf.configs['SERVER_PASS'], methods=['GET', 'POST']) 243 | def api_call(): 244 | data = {} 245 | try: 246 | if request.content_type == 'application/json': 247 | data = request.get_json(silent=True) 248 | elif request.method == 'POST': 249 | data = request.form.to_dict() 250 | else: 251 | data = request.args.to_dict() 252 | 253 | # verify cmd was supplied 254 | if 'cmd' not in data: 255 | logger.error("Unknown %s API call from %r", request.method, request.remote_addr) 256 | return jsonify({'error': 'No cmd parameter was supplied'}) 257 | else: 258 | logger.info("Client %s API call from %r, type: %s", request.method, request.remote_addr, data['cmd']) 259 | 260 | # process cmds 261 | cmd = data['cmd'].lower() 262 | if cmd == 'queue_count': 263 | # queue count 264 | if not conf.configs['SERVER_USE_SQLITE']: 265 | # return error if SQLITE db is not enabled 266 | return jsonify({'error': 'SERVER_USE_SQLITE must be enabled'}) 267 | return jsonify({'queue_count': db.get_queue_count()}) 268 | 269 | else: 270 | # unknown cmd 271 | return jsonify({'error': 'Unknown cmd: %s' % cmd}) 272 | 273 | except Exception: 274 | logger.exception("Exception parsing %s API call from %r: ", request.method, request.remote_addr) 275 | 276 | return jsonify({'error': 'Unexpected error occurred, check logs...'}) 277 | 278 | 279 | @app.route("/%s" % conf.configs['SERVER_PASS'], methods=['GET']) 280 | def manual_scan(): 281 | if not conf.configs['SERVER_ALLOW_MANUAL_SCAN']: 282 | return abort(401) 283 | page = """ 284 | 285 | 286 | Plex Autoscan 287 | 288 | 289 | 290 | 291 |
292 |
293 |
294 |

Plex Autoscan

295 | 296 |

Path to scan

297 |
298 |
299 | 300 |
301 | 302 |
303 |
304 | 305 |
306 |
307 |
308 | 309 | """ 310 | return page, 200 311 | 312 | 313 | @app.route("/%s" % conf.configs['SERVER_PASS'], methods=['POST']) 314 | def client_pushed(): 315 | if request.content_type == 'application/json': 316 | data = request.get_json(silent=True) 317 | else: 318 | data = request.form.to_dict() 319 | 320 | if not data: 321 | logger.error("Invalid scan request from: %r", request.remote_addr) 322 | abort(400) 323 | logger.debug("Client %r request dump:\n%s", request.remote_addr, json.dumps(data, indent=4, sort_keys=True)) 324 | 325 | if ('eventType' in data and data['eventType'] == 'Test') or ('EventType' in data and data['EventType'] == 'Test'): 326 | logger.info("Client %r made a test request, event: '%s'", request.remote_addr, 'Test') 327 | elif 'eventType' in data and data['eventType'] == 'Manual': 328 | logger.info("Client %r made a manual scan request for: '%s'", request.remote_addr, data['filepath']) 329 | final_path = utils.map_pushed_path(conf.configs, data['filepath']) 330 | # ignore this request? 331 | ignore, ignore_match = utils.should_ignore(final_path, conf.configs) 332 | if ignore: 333 | logger.info("Ignored scan request for '%s' because '%s' was matched from SERVER_IGNORE_LIST", final_path, 334 | ignore_match) 335 | return "Ignoring scan request because %s was matched from your SERVER_IGNORE_LIST" % ignore_match 336 | if start_scan(final_path, 'Manual', 'Manual'): 337 | return """ 338 | 339 | 340 | Plex Autoscan 341 | 342 | 343 | 344 | 345 |
346 |
347 |
348 |

Plex Autoscan

349 |

Success

350 | 353 |
354 |
355 |
356 | 357 | """.format(final_path) 358 | else: 359 | return """ 360 | 361 | 362 | Plex Autoscan 363 | 364 | 365 | 366 | 367 |
368 |
369 |
370 |

Plex Autoscan

371 |

Error

372 | 375 |
376 |
377 |
378 | 379 | """.format(data['filepath']) 380 | 381 | elif 'series' in data and 'eventType' in data and data['eventType'] == 'Rename' and 'path' in data['series']: 382 | # sonarr Rename webhook 383 | logger.info("Client %r scan request for series: '%s', event: '%s'", request.remote_addr, data['series']['path'], 384 | "Upgrade" if ('isUpgrade' in data and data['isUpgrade']) else data['eventType']) 385 | final_path = utils.map_pushed_path(conf.configs, data['series']['path']) 386 | start_scan(final_path, 'Sonarr', 387 | "Upgrade" if ('isUpgrade' in data and data['isUpgrade']) else data['eventType']) 388 | 389 | elif 'movie' in data and 'eventType' in data and data['eventType'] == 'Rename' and 'folderPath' in data['movie']: 390 | # radarr Rename webhook 391 | logger.info("Client %r scan request for movie: '%s', event: '%s'", request.remote_addr, 392 | data['movie']['folderPath'], 393 | "Upgrade" if ('isUpgrade' in data and data['isUpgrade']) else data['eventType']) 394 | final_path = utils.map_pushed_path(conf.configs, data['movie']['folderPath']) 395 | start_scan(final_path, 'Radarr', 396 | "Upgrade" if ('isUpgrade' in data and data['isUpgrade']) else data['eventType']) 397 | 398 | elif 'movie' in data and 'movieFile' in data and 'folderPath' in data['movie'] and \ 399 | 'relativePath' in data['movieFile'] and 'eventType' in data: 400 | # radarr download/upgrade webhook 401 | path = os.path.join(data['movie']['folderPath'], data['movieFile']['relativePath']) 402 | logger.info("Client %r scan request for movie: '%s', event: '%s'", request.remote_addr, path, 403 | "Upgrade" if ('isUpgrade' in data and data['isUpgrade']) else data['eventType']) 404 | final_path = utils.map_pushed_path(conf.configs, path) 405 | 406 | # parse scan inputs 407 | scan_title = None 408 | scan_lookup_type = None 409 | scan_lookup_id = None 410 | 411 | if 'remoteMovie' in data: 412 | if 'imdbId' in data['remoteMovie'] and data['remoteMovie']['imdbId']: 413 | # prefer imdb 414 | scan_lookup_id = data['remoteMovie']['imdbId'] 415 | scan_lookup_type = 'IMDB' 416 | elif 'tmdbId' in data['remoteMovie'] and data['remoteMovie']['tmdbId']: 417 | # fallback tmdb 418 | scan_lookup_id = data['remoteMovie']['tmdbId'] 419 | scan_lookup_type = 'TheMovieDB' 420 | 421 | scan_title = data['remoteMovie']['title'] if 'title' in data['remoteMovie'] and data['remoteMovie'][ 422 | 'title'] else None 423 | 424 | # start scan 425 | start_scan(final_path, 'Radarr', 426 | "Upgrade" if ('isUpgrade' in data and data['isUpgrade']) else data['eventType'], scan_title, 427 | scan_lookup_type, scan_lookup_id) 428 | 429 | elif 'series' in data and 'episodeFile' in data and 'eventType' in data: 430 | # sonarr download/upgrade webhook 431 | path = os.path.join(data['series']['path'], data['episodeFile']['relativePath']) 432 | logger.info("Client %r scan request for series: '%s', event: '%s'", request.remote_addr, path, 433 | "Upgrade" if ('isUpgrade' in data and data['isUpgrade']) else data['eventType']) 434 | final_path = utils.map_pushed_path(conf.configs, path) 435 | 436 | # parse scan inputs 437 | scan_title = None 438 | scan_lookup_type = None 439 | scan_lookup_id = None 440 | if 'series' in data: 441 | scan_lookup_id = data['series']['tvdbId'] if 'tvdbId' in data['series'] and data['series'][ 442 | 'tvdbId'] else None 443 | scan_lookup_type = 'TheTVDB' if scan_lookup_id is not None else None 444 | scan_title = data['series']['title'] if 'title' in data['series'] and data['series'][ 445 | 'title'] else None 446 | 447 | # start scan 448 | start_scan(final_path, 'Sonarr', 449 | "Upgrade" if ('isUpgrade' in data and data['isUpgrade']) else data['eventType'], scan_title, 450 | scan_lookup_type, scan_lookup_id) 451 | 452 | elif 'artist' in data and 'trackFiles' in data and 'eventType' in data: 453 | # lidarr download/upgrade webhook 454 | for track in data['trackFiles']: 455 | if 'path' not in track and 'relativePath' not in track: 456 | continue 457 | 458 | path = track['path'] if 'path' in track else os.path.join(data['artist']['path'], track['relativePath']) 459 | logger.info("Client %r scan request for album track: '%s', event: '%s'", request.remote_addr, path, 460 | "Upgrade" if ('isUpgrade' in data and data['isUpgrade']) else data['eventType']) 461 | final_path = utils.map_pushed_path(conf.configs, path) 462 | start_scan(final_path, 'Lidarr', 463 | "Upgrade" if ('isUpgrade' in data and data['isUpgrade']) else data['eventType']) 464 | 465 | else: 466 | logger.error("Unknown scan request from: %r", request.remote_addr) 467 | abort(400) 468 | 469 | return "OK" 470 | 471 | 472 | ############################################################ 473 | # MAIN 474 | ############################################################ 475 | 476 | if __name__ == "__main__": 477 | print("") 478 | 479 | f = Figlet(font='slant', width=100) 480 | print(f.renderText('Plex Autoscan')) 481 | 482 | logger.info(""" 483 | ######################################################################### 484 | # Title: Plex Autoscan # 485 | # Author: l3uddz # 486 | # URL: https://github.com/l3uddz/plex_autoscan # 487 | # -- # 488 | # Part of the Cloudbox project: https://cloudbox.works # 489 | ######################################################################### 490 | # GNU General Public License v3.0 # 491 | ######################################################################### 492 | """) 493 | if conf.args['cmd'] == 'sections': 494 | plex.show_sections(conf.configs) 495 | exit(0) 496 | elif conf.args['cmd'] == 'sections+': 497 | plex.show_detailed_sections_info(conf) 498 | exit(0) 499 | elif conf.args['cmd'] == 'update_config': 500 | exit(0) 501 | elif conf.args['cmd'] == 'authorize': 502 | if not conf.configs['GOOGLE']['ENABLED']: 503 | logger.error("You must enable the GOOGLE section in config.") 504 | exit(1) 505 | else: 506 | logger.debug("client_id: %r", conf.configs['GOOGLE']['CLIENT_ID']) 507 | logger.debug("client_secret: %r", conf.configs['GOOGLE']['CLIENT_SECRET']) 508 | 509 | google_drive = google.GoogleDrive(conf.configs['GOOGLE']['CLIENT_ID'], conf.configs['GOOGLE']['CLIENT_SECRET'], 510 | conf.settings['cachefile'], allowed_config=conf.configs['GOOGLE']['ALLOWED']) 511 | 512 | # Provide authorization link 513 | logger.info("Visit the link below and paste the authorization code: ") 514 | logger.info(google_drive.get_auth_link()) 515 | logger.info("Enter authorization code: ") 516 | auth_code = input() 517 | logger.debug("auth_code: %r", auth_code) 518 | 519 | # Exchange authorization code 520 | token = google_drive.exchange_code(auth_code) 521 | if not token or 'access_token' not in token: 522 | logger.error("Failed exchanging authorization code for an Access Token.") 523 | sys.exit(1) 524 | else: 525 | logger.info("Exchanged authorization code for an Access Token:\n\n%s\n", json.dumps(token, indent=2)) 526 | sys.exit(0) 527 | 528 | elif conf.args['cmd'] == 'server': 529 | if conf.configs['SERVER_USE_SQLITE']: 530 | start_queue_reloader() 531 | 532 | if conf.configs['GOOGLE']['ENABLED']: 533 | start_google_monitor() 534 | 535 | logger.info("Starting server: http://%s:%d/%s", 536 | conf.configs['SERVER_IP'], 537 | conf.configs['SERVER_PORT'], 538 | conf.configs['SERVER_PASS'] 539 | ) 540 | app.run(host=conf.configs['SERVER_IP'], port=conf.configs['SERVER_PORT'], debug=False, use_reloader=False) 541 | logger.info("Server stopped") 542 | exit(0) 543 | elif conf.args['cmd'] == 'build_caches': 544 | logger.info("Building caches") 545 | # load google drive manager 546 | manager = google.GoogleDriveManager(conf.configs['GOOGLE']['CLIENT_ID'], conf.configs['GOOGLE']['CLIENT_SECRET'], 547 | conf.settings['cachefile'], allowed_config=conf.configs['GOOGLE']['ALLOWED'], 548 | allowed_teamdrives=conf.configs['GOOGLE']['TEAMDRIVES']) 549 | 550 | if not manager.is_authorized(): 551 | logger.error("Failed to validate Google Drive Access Token.") 552 | exit(1) 553 | else: 554 | logger.info("Google Drive Access Token was successfully validated.") 555 | 556 | # load teamdrives (if enabled) 557 | if conf.configs['GOOGLE']['TEAMDRIVE'] and not manager.load_teamdrives(): 558 | logger.error("Failed to load Google Teamdrives.") 559 | exit(1) 560 | 561 | # build cache 562 | manager.build_caches() 563 | logger.info("Finished building all caches.") 564 | exit(0) 565 | else: 566 | logger.error("Unknown command.") 567 | exit(1) 568 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /system/plex_autoscan.service: -------------------------------------------------------------------------------- 1 | # /etc/systemd/system/plex_autoscan.service 2 | 3 | [Unit] 4 | Description=Plex Autoscan 5 | After=network-online.target 6 | 7 | [Service] 8 | User=YOUR_USER 9 | Group=YOUR_USER 10 | Type=simple 11 | WorkingDirectory=/opt/plex_autoscan/ 12 | ExecStart=/opt/plex_autoscan/scan.py server --loglevel=INFO 13 | Restart=always 14 | RestartSec=10 15 | 16 | [Install] 17 | WantedBy=default.target 18 | -------------------------------------------------------------------------------- /test_threads.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import time 3 | 4 | from threads import Thread, PriorityLock 5 | 6 | 7 | ############################################################ 8 | # MISC 9 | ############################################################ 10 | 11 | def test_thread(lock, priority): 12 | lock.acquire(priority) 13 | try: 14 | print("Hello from priority: %s" % str(priority)) 15 | time.sleep(5) 16 | finally: 17 | lock.release() 18 | print("Finished priority: %s" % str(priority)) 19 | 20 | 21 | ############################################################ 22 | # MAIN 23 | ############################################################ 24 | 25 | if __name__ == "__main__": 26 | lock = PriorityLock() 27 | threads = Thread() 28 | for pos in reversed(range(0, 100)): 29 | threads.start(test_thread, args=[lock, pos], track=True) 30 | print("Started first batch of threads") 31 | time.sleep(15) 32 | for pos in reversed(range(0, 100)): 33 | threads.start(test_thread, args=[lock, pos], track=True) 34 | print("Started second batch of threads") 35 | threads.join() 36 | print("All threads finished") 37 | -------------------------------------------------------------------------------- /threads.py: -------------------------------------------------------------------------------- 1 | try: 2 | # Try the Python 3 queue module 3 | import queue 4 | except ImportError: 5 | # Fallback to the Python 2 Queue module 6 | import Queue as queue 7 | import datetime 8 | import copy 9 | import threading 10 | 11 | 12 | class PriorityLock: 13 | def __init__(self): 14 | self._is_available = True 15 | self._mutex = threading.Lock() 16 | self._waiter_queue = queue.PriorityQueue() 17 | 18 | def acquire(self, priority=0): 19 | self._mutex.acquire() 20 | # First, just check the lock. 21 | if self._is_available: 22 | self._is_available = False 23 | self._mutex.release() 24 | return True 25 | event = threading.Event() 26 | self._waiter_queue.put((priority, datetime.datetime.now(), event)) 27 | self._mutex.release() 28 | event.wait() 29 | # When the event is triggered, we have the lock. 30 | return True 31 | 32 | def release(self): 33 | self._mutex.acquire() 34 | # Notify the next thread in line, if any. 35 | try: 36 | _, timeAdded, event = self._waiter_queue.get_nowait() 37 | except queue.Empty: 38 | self._is_available = True 39 | else: 40 | event.set() 41 | self._mutex.release() 42 | 43 | 44 | class Thread: 45 | def __init__(self): 46 | self.threads = [] 47 | 48 | def start(self, target, name=None, args=None, track=False): 49 | thread = threading.Thread(target=target, name=name, args=args if args else []) 50 | thread.daemon = True 51 | thread.start() 52 | if track: 53 | self.threads.append(thread) 54 | return thread 55 | 56 | def join(self): 57 | for thread in copy.copy(self.threads): 58 | thread.join() 59 | self.threads.remove(thread) 60 | return 61 | 62 | def kill(self): 63 | for thread in copy.copy(self.threads): 64 | thread.kill() 65 | self.threads.remove(thread) 66 | return 67 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | import os 4 | import sqlite3 5 | import subprocess 6 | import sys 7 | import time 8 | from contextlib import closing 9 | from copy import copy 10 | 11 | import requests 12 | 13 | try: 14 | from urlparse import urljoin 15 | except ImportError: 16 | from urllib.parse import urljoin 17 | 18 | import psutil 19 | 20 | logger = logging.getLogger("UTILS") 21 | 22 | 23 | def get_plex_section(config, path): 24 | try: 25 | with sqlite3.connect(config['PLEX_DATABASE_PATH']) as conn: 26 | conn.row_factory = sqlite3.Row 27 | conn.text_factory = str 28 | with closing(conn.cursor()) as c: 29 | # check if file exists in plex 30 | logger.debug("Checking if root folder path '%s' matches Plex Library root path in the Plex DB.", path) 31 | section_data = c.execute("SELECT library_section_id,root_path FROM section_locations").fetchall() 32 | for section_id, root_path in section_data: 33 | if path.startswith(root_path + os.sep): 34 | logger.debug("Plex Library Section ID '%d' matching root folder '%s' was found in the Plex DB.", 35 | section_id, root_path) 36 | return int(section_id) 37 | logger.error("Unable to map '%s' to a Section ID.", path) 38 | 39 | except Exception: 40 | logger.exception("Exception while trying to map '%s' to a Section ID in the Plex DB: ", path) 41 | return -1 42 | 43 | 44 | def ensure_valid_os_path_sep(path): 45 | try: 46 | if path.startswith('/'): 47 | # replace \ with / 48 | return path.replace('\\', '/') 49 | elif '\\' in path: 50 | # replace / with \ 51 | return path.replace('/', '\\') 52 | except Exception: 53 | logger.exception("Exception while trying to ensure valid os path seperator for: '%s'", path) 54 | 55 | return path 56 | 57 | 58 | def map_pushed_path(config, path): 59 | for mapped_path, mappings in config['SERVER_PATH_MAPPINGS'].items(): 60 | for mapping in mappings: 61 | if path.startswith(mapping): 62 | logger.debug("Mapping server path '%s' to '%s'.", mapping, mapped_path) 63 | return ensure_valid_os_path_sep(path.replace(mapping, mapped_path)) 64 | return path 65 | 66 | 67 | def map_pushed_path_file_exists(config, path): 68 | for mapped_path, mappings in config['SERVER_FILE_EXIST_PATH_MAPPINGS'].items(): 69 | for mapping in mappings: 70 | if path.startswith(mapping): 71 | logger.debug("Mapping file check path '%s' to '%s'.", mapping, mapped_path) 72 | return ensure_valid_os_path_sep(path.replace(mapping, mapped_path)) 73 | return path 74 | 75 | 76 | # For Rclone dir cache clear request 77 | def map_file_exists_path_for_rclone(config, path): 78 | for mapped_path, mappings in config['RCLONE']['RC_CACHE_REFRESH']['FILE_EXISTS_TO_REMOTE_MAPPINGS'].items(): 79 | for mapping in mappings: 80 | if path.startswith(mapping): 81 | logger.debug("Mapping Rclone file check path '%s' to '%s'.", mapping, mapped_path) 82 | return path.replace(mapping, mapped_path) 83 | return path 84 | 85 | 86 | def is_process_running(process_name, plex_container=None): 87 | try: 88 | for process in psutil.process_iter(): 89 | if process.name().lower() == process_name.lower(): 90 | if not plex_container: 91 | return True, process, plex_container 92 | # plex_container was not None 93 | # we need to check if this processes is from the container we are interested in 94 | get_pid_container = "docker inspect --format '{{.Name}}' \"$(cat /proc/%s/cgroup |head -n 1 " \ 95 | "|cut -d / -f 3)\" | sed 's/^\///'" % process.pid 96 | process_container = run_command(get_pid_container, True) 97 | logger.debug("Using: %s", get_pid_container) 98 | logger.debug("Docker Container For PID %s: %r", process.pid, 99 | process_container.strip() if process_container is not None else 'Unknown???') 100 | if process_container is not None and isinstance(process_container, str) and \ 101 | process_container.strip().lower() == plex_container.lower(): 102 | return True, process, process_container.strip() 103 | 104 | return False, None, plex_container 105 | except psutil.ZombieProcess: 106 | return False, None, plex_container 107 | except Exception: 108 | logger.exception("Exception checking for process: '%s': ", process_name) 109 | return False, None, plex_container 110 | 111 | 112 | def wait_running_process(process_name, use_docker=False, plex_container=None): 113 | try: 114 | running, process, container = is_process_running(process_name, 115 | None if not use_docker or not plex_container else 116 | plex_container) 117 | while running and process: 118 | logger.info("'%s' is running, pid: %d,%s cmdline: %r. Checking again in 60 seconds...", process.name(), 119 | process.pid, 120 | ' container: %s,' % container.strip() if use_docker and isinstance(container, str) else '', 121 | process.cmdline()) 122 | time.sleep(60) 123 | running, process, container = is_process_running(process_name, 124 | None if not use_docker or not plex_container else 125 | plex_container) 126 | 127 | return True 128 | 129 | except Exception: 130 | logger.exception("Exception waiting for process: '%s'", process_name()) 131 | 132 | return False 133 | 134 | 135 | def run_command(command, get_output=False): 136 | total_output = '' 137 | process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 138 | while True: 139 | output = str(process.stdout.readline()).lstrip('b').replace('\\n', '').strip() 140 | if output and len(output) >= 3: 141 | if not get_output: 142 | if len(output) >= 8: 143 | logger.info(output) 144 | else: 145 | total_output += output 146 | 147 | if process.poll() is not None: 148 | break 149 | 150 | rc = process.poll() 151 | return rc if not get_output else total_output 152 | 153 | 154 | def should_ignore(file_path, config): 155 | for item in config['SERVER_IGNORE_LIST']: 156 | if item.lower() in file_path.lower(): 157 | return True, item 158 | 159 | return False, None 160 | 161 | 162 | def remove_item_from_list(item, from_list): 163 | while item in from_list: 164 | from_list.pop(from_list.index(item)) 165 | return 166 | 167 | 168 | def get_priority(config, scan_path): 169 | try: 170 | for priority, paths in config['SERVER_SCAN_PRIORITIES'].items(): 171 | for path in paths: 172 | if path.lower() in scan_path.lower(): 173 | logger.debug("Using priority '%d' for path '%s'", int(priority), scan_path) 174 | return int(priority) 175 | logger.debug("Using default priority '0' for path '%s'", scan_path) 176 | except Exception: 177 | logger.exception("Exception determining priority to use for '%s': ", scan_path) 178 | return 0 179 | 180 | 181 | def rclone_rc_clear_cache(config, scan_path): 182 | try: 183 | rclone_rc_expire_url = urljoin(config['RCLONE']['RC_CACHE_REFRESH']['RC_URL'], 'cache/expire') 184 | rclone_rc_refresh_url = urljoin(config['RCLONE']['RC_CACHE_REFRESH']['RC_URL'], 'vfs/refresh') 185 | 186 | cache_clear_path = map_file_exists_path_for_rclone(config, scan_path).lstrip(os.path.sep) 187 | logger.debug("Top level cache_clear_path: '%s'", cache_clear_path) 188 | 189 | while True: 190 | last_clear_path = cache_clear_path 191 | cache_clear_path = os.path.dirname(cache_clear_path) 192 | if cache_clear_path == last_clear_path or not len(cache_clear_path): 193 | # is the last path we tried to clear, the same as this path, if so, abort 194 | logger.error( 195 | "Aborting Rclone dir cache clear request for '%s' due to directory level exhaustion, last level: '%s'", 196 | scan_path, last_clear_path) 197 | return False 198 | else: 199 | last_clear_path = cache_clear_path 200 | 201 | # send Rclone mount dir cache clear request 202 | logger.info("Sending Rclone mount dir cache clear request for: '%s'", cache_clear_path) 203 | try: 204 | # try cache clear 205 | resp = requests.post(rclone_rc_expire_url, json={'remote': cache_clear_path}, timeout=120) 206 | if '{' in resp.text and '}' in resp.text: 207 | data = resp.json() 208 | if 'error' in data: 209 | # try to vfs/refresh as fallback 210 | resp = requests.post(rclone_rc_refresh_url, json={'dir': cache_clear_path}, timeout=120) 211 | if '{' in resp.text and '}' in resp.text: 212 | data = resp.json() 213 | if 'result' in data and cache_clear_path in data['result'] \ 214 | and data['result'][cache_clear_path] == 'OK': 215 | # successfully vfs refreshed 216 | logger.info("Successfully refreshed Rclone VFS mount's dir cache for '%s'", 217 | cache_clear_path) 218 | return True 219 | 220 | logger.info("Failed to clear Rclone mount's dir cache for '%s': %s", cache_clear_path, 221 | data['error'] if 'error' in data else data) 222 | continue 223 | elif ('status' in data and 'message' in data) and data['status'] == 'ok': 224 | logger.info("Successfully cleared Rclone Cache mount's dir cache for '%s'", cache_clear_path) 225 | return True 226 | 227 | # abort on unexpected response (no json response, no error/status & message in returned json 228 | logger.error("Unexpected Rclone mount dir cache clear response from %s while trying to clear '%s': %s", 229 | rclone_rc_expire_url, cache_clear_path, resp.text) 230 | break 231 | 232 | except Exception: 233 | logger.exception("Exception sending Rclone mount dir cache clear request to %s for '%s': ", 234 | rclone_rc_expire_url, 235 | cache_clear_path) 236 | break 237 | 238 | except Exception: 239 | logger.exception("Exception clearing Rclone mount dir cache for '%s': ", scan_path) 240 | return False 241 | 242 | 243 | def load_json(file_path): 244 | if os.path.sep not in file_path: 245 | file_path = os.path.join(os.path.dirname(sys.argv[0]), file_path) 246 | 247 | with open(file_path, 'r') as fp: 248 | return json.load(fp) 249 | 250 | 251 | def dump_json(file_path, obj, processing=True): 252 | if os.path.sep not in file_path: 253 | file_path = os.path.join(os.path.dirname(sys.argv[0]), file_path) 254 | 255 | with open(file_path, 'w') as fp: 256 | if processing: 257 | json.dump(obj, fp, indent=2, sort_keys=True) 258 | else: 259 | json.dump(obj, fp) 260 | return 261 | 262 | 263 | def remove_files_exist_in_plex_database(config, file_paths): 264 | removed_items = 0 265 | plex_db_path = config['PLEX_DATABASE_PATH'] 266 | try: 267 | if plex_db_path and os.path.exists(plex_db_path): 268 | with sqlite3.connect(plex_db_path) as conn: 269 | conn.row_factory = sqlite3.Row 270 | with closing(conn.cursor()) as c: 271 | for file_path in copy(file_paths): 272 | # check if file exists in plex 273 | file_name = os.path.basename(file_path) 274 | file_path_plex = map_pushed_path(config, file_path) 275 | logger.debug("Checking to see if '%s' exists in the Plex DB located at '%s'", file_path_plex, 276 | plex_db_path) 277 | found_item = c.execute("SELECT size FROM media_parts WHERE file LIKE ?", 278 | ('%' + file_path_plex,)) \ 279 | .fetchone() 280 | file_path_actual = map_pushed_path_file_exists(config, file_path_plex) 281 | # should plex file size and file size on disk be checked? 282 | disk_file_size_check = True 283 | 284 | if 'DISABLE_DISK_FILE_SIZE_CHECK' in config['GOOGLE'] \ 285 | and config['GOOGLE']['DISABLE_DISK_FILE_SIZE_CHECK']: 286 | disk_file_size_check = False 287 | 288 | if found_item: 289 | logger.debug("'%s' was found in the Plex DB media_parts table.", file_name) 290 | skip_file = False 291 | if not disk_file_size_check: 292 | skip_file = True 293 | elif os.path.isfile(file_path_actual): 294 | # check if file sizes match in plex 295 | file_size = os.path.getsize(file_path_actual) 296 | logger.debug( 297 | "Checking to see if the file size of '%s' matches the existing file size of '%s' in the Plex DB.", 298 | file_size, found_item[0]) 299 | if file_size == found_item[0]: 300 | logger.debug("'%s' size matches size found in the Plex DB.", file_size) 301 | skip_file = True 302 | 303 | if skip_file: 304 | logger.debug("Removing path from scan queue: '%s'", file_path) 305 | file_paths.remove(file_path) 306 | removed_items += 1 307 | 308 | except Exception: 309 | logger.exception("Exception checking if %s exists in the Plex DB: ", file_paths) 310 | return removed_items 311 | 312 | 313 | def allowed_scan_extension(file_path, extensions): 314 | check_path = file_path.lower() 315 | for ext in extensions: 316 | if check_path.endswith(ext.lower()): 317 | logger.debug("'%s' had allowed extension: %s", file_path, ext) 318 | return True 319 | logger.debug("'%s' did not have an allowed extension.", file_path) 320 | return False 321 | --------------------------------------------------------------------------------