├── .dockerignore ├── .github ├── ISSUE_TEMPLATE.md ├── ISSUE_TEMPLATE │ ├── BUG_REPORT.md │ ├── FEATURE_REQUEST.md │ └── OTHER_ISSUES.md ├── SUPPORT.md └── labels.json ├── .gitignore ├── CONTRIBUTING.md ├── DONATIONS.md ├── LICENSE.md ├── README.md ├── assets ├── demo.gif ├── list_of_country_codes.md ├── list_of_language_codes.md ├── list_of_movie_genres.md ├── list_of_tv_show_genres.md └── logo.svg ├── docker ├── Dockerfile └── hooks │ └── build ├── helpers ├── misc.py ├── omdb.py ├── parameter.py ├── radarr.py ├── sonarr.py ├── str.py ├── tmdb.py ├── trakt.py └── tvdb.py ├── media ├── __init__.py ├── pvr.py ├── radarr.py ├── sonarr.py └── trakt.py ├── misc ├── __init__.py ├── config.py └── log.py ├── notifications ├── __init__.py ├── apprise.py ├── pushover.py └── slack.py ├── requirements.txt ├── sample └── config.json ├── systemd └── traktarr.service └── traktarr.py /.dockerignore: -------------------------------------------------------------------------------- 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 | *.json 25 | *.json.sample 26 | 27 | # documents 28 | *.md 29 | 30 | # generators 31 | *.bat 32 | 33 | # Pyenv 34 | **/.python-version 35 | 36 | # PyInstaller 37 | build/ 38 | dist/ 39 | *.manifest 40 | *.spec 41 | 42 | # Git 43 | .git 44 | 45 | # Systemd 46 | systemd 47 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 8 | 9 | ## Support / Questions 10 | 11 | The [readme](https://github.com/l3uddz/traktarr/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 `#traktarr` 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/traktarr/issues/new?template=BUG_REPORT.md 20 | 21 | ## Feature Request 22 | 23 | Use https://github.com/l3uddz/traktarr/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 Traktarr 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 with `core.debug` in the `config.json` file: 27 | 28 | ```json 29 | "core": { 30 | "debug": true 31 | }, 32 | ``` 33 | 34 | **System Information** 35 | 36 | - Traktarr Version: [e.g. Master (latest), Develop (latest)] 37 | - Operating System: [e.g. Ubuntu Server 16.04 LTS] 38 | 39 | **Additional context** 40 | Add any other context about the problem here. 41 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/FEATURE_REQUEST.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature Request 3 | about: Suggest an idea for Traktarr 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/traktarr/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 `#traktarr` 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/traktarr/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 `#traktarr` 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 | # VSCode 11 | .vscode/ 12 | 13 | # Byte-compiled / optimized / DLL files 14 | __pycache__/ 15 | *.py[cod] 16 | *$py.class 17 | *.pyc 18 | 19 | # logs 20 | *.log* 21 | 22 | # databases 23 | /cache.db 24 | 25 | # configs 26 | *.cfg 27 | /*.json 28 | 29 | # generators 30 | *.bat 31 | 32 | # Pyenv 33 | **/.python-version 34 | 35 | # Venv 36 | venv/ 37 | 38 | # PyInstaller 39 | build/ 40 | dist/ 41 | *.manifest 42 | *.spec 43 | -------------------------------------------------------------------------------- /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//traktarr 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 | -------------------------------------------------------------------------------- /DONATIONS.md: -------------------------------------------------------------------------------- 1 | # Donations 2 | 3 | If you find this project helpful, feel free to make a small donation to the developer. 4 | 5 | - [GitHub Sponsor](https://github.com/sponsors/l3uddz) 6 | 7 | - [Monzo](https://monzo.me/jamesbayliss9): Credit Cards, Apple Pay, Google Pay 8 | 9 | - [Paypal: l3uddz@gmail.com](https://www.paypal.me/l3uddz) 10 | 11 | - BTC: 3CiHME1HZQsNNcDL6BArG7PbZLa8zUUgjL 12 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Traktarr 2 | 3 | [![made-with-python](https://img.shields.io/badge/Made%20with-Python-blue.svg?style=flat-square)](https://www.python.org/) 4 | [![License: GPL v3](https://img.shields.io/badge/License-GPL%203-blue.svg?style=flat-square)](https://github.com/l3uddz/traktarr/blob/master/LICENSE.md) 5 | [![last commit (master)](https://img.shields.io/github/last-commit/l3uddz/traktarr/master.svg?colorB=177DC1&label=Last%20Commit&style=flat-square)](https://github.com/l3uddz/traktarr/commits/master) 6 | [![Discord](https://img.shields.io/discord/853755447970758686.svg?colorB=177DC1&label=Discord&style=flat-square)](https://discord.gg/ugfKXpFND8) 7 | [![Contributing](https://img.shields.io/badge/Contributing-gray.svg?style=flat-square)](CONTRIBUTING.md) 8 | [![Donate](https://img.shields.io/badge/Donate-gray.svg?style=flat-square)](DONATIONS.md) 9 | 10 | 11 | --- 12 | 13 | 14 | 15 | - [Introduction](#introduction) 16 | - [Demo](#demo) 17 | - [Requirements](#requirements) 18 | - [Installation](#installation) 19 | - [1. Base Install](#1-base-install) 20 | - [2. Create a Trakt Application](#2-create-a-trakt-application) 21 | - [3. Authenticate User(s) (optional)](#3-authenticate-users-optional) 22 | - [Configuration](#configuration) 23 | - [Sample Configuration](#sample-configuration) 24 | - [Core](#core) 25 | - [Automatic](#automatic) 26 | - [Personal Watchlists](#personal-watchlists) 27 | - [Custom Lists](#custom-lists) 28 | - [Public Lists](#public-lists) 29 | - [Private Lists](#private-lists) 30 | - [Filters](#filters) 31 | - [Movies](#movies) 32 | - [Shows](#shows) 33 | - [Notifications](#notifications) 34 | - [Apprise](#apprise) 35 | - [Pushover](#pushover) 36 | - [Slack](#slack) 37 | - [Radarr](#radarr) 38 | - [Sonarr](#sonarr) 39 | - [Trakt](#trakt) 40 | - [OMDb](#omdb) 41 | - [Usage](#usage) 42 | - [Automatic (Scheduled)](#automatic-scheduled) 43 | - [Setup](#setup) 44 | - [Customize](#customize) 45 | - [Manual (CLI)](#manual-cli) 46 | - [General](#general) 47 | - [Movie (Single Movie)](#movie-single-movie) 48 | - [Movies (Multiple Movies)](#movies-multiple-movies) 49 | - [Show (Single Show)](#show-single-show) 50 | - [Shows (Multiple Shows)](#shows-multiple-shows) 51 | - [Examples (CLI)](#examples-cli) 52 | - [Movies](#movies-1) 53 | - [Shows](#shows-1) 54 | - [Donate](#donate) 55 | 56 | 57 | 58 | --- 59 | 60 | # Introduction 61 | 62 | Traktarr uses Trakt.tv to find shows and movies to add in to Sonarr and Radarr, respectively. 63 | 64 | Types of Trakt lists supported: 65 | 66 | - Official Trakt Lists 67 | 68 | - Trending 69 | 70 | - Popular 71 | 72 | - Anticipated 73 | 74 | - Box Office 75 | 76 | - Most Watched 77 | 78 | - Most Played 79 | 80 | - Public Lists 81 | 82 | - Private Lists* 83 | 84 | - Watchlist 85 | 86 | - Custom List(s) 87 | 88 | \* Support for multiple (authenticated) users. 89 | 90 | # Demo 91 | 92 | Click to enlarge. 93 | 94 | [![asciicast](assets/demo.gif)](https://asciinema.org/a/180044) 95 | 96 | 97 | # Requirements 98 | 99 | 1. Debian OS (can work in other operating systems as well). 100 | 101 | 2. Python 3.5+ 102 | 103 | 3. Required Python modules. 104 | 105 | 106 | # Installation 107 | 108 | ## 1. Base Install 109 | 110 | Installs Traktarr to the system so that it can be ran with the `traktarr` command. 111 | 112 | 113 | 1. Clone the Traktarr repo. 114 | 115 | ``` 116 | sudo git clone https://github.com/l3uddz/traktarr /opt/traktarr 117 | ``` 118 | 119 | 1. Fix permissions of the `traktarr` folder (replace `user`/`group` with your info; run `id` to check). 120 | 121 | ``` 122 | sudo chown -R user:group /opt/traktarr 123 | ``` 124 | 125 | 1. Go into the `traktarr` folder. 126 | 127 | ``` 128 | cd /opt/traktarr 129 | ``` 130 | 131 | 1. Install Python and PIP. 132 | 133 | ``` 134 | sudo apt-get install python3 python3-pip 135 | ``` 136 | 137 | 1. Install the required python modules. 138 | 139 | ``` 140 | sudo python3 -m pip install -r requirements.txt 141 | ``` 142 | 143 | 1. Create a shortcut for `traktarr`. 144 | 145 | ``` 146 | sudo ln -s /opt/traktarr/traktarr.py /usr/local/bin/traktarr 147 | ``` 148 | 149 | 1. Generate a basic `config.json` file. 150 | 151 | ``` 152 | traktarr run 153 | ``` 154 | 155 | 1. Configure the `config.json` file. 156 | 157 | ``` 158 | nano config.json 159 | ``` 160 | 161 | ## 2. Create a Trakt Application 162 | 163 | 1. Create a Trakt application by going [here](https://trakt.tv/oauth/applications/new) 164 | 165 | 2. Enter a name for your application; for example `traktarr` 166 | 167 | 3. Enter `urn:ietf:wg:oauth:2.0:oob` in the `Redirect uri` field. 168 | 169 | 4. Click "SAVE APP". 170 | 171 | 5. Open the Traktarr configuration file `config.json` and insert your Trakt Client ID in the `client_id` and your Trakt Client Secret in the `client_secret`, like this: 172 | 173 | ```json 174 | "trakt": { 175 | "client_id": "your_trakt_client_id", 176 | "client_secret": "your_trakt_client_secret" 177 | } 178 | ``` 179 | 180 | ## 3. Authenticate User(s) (optional) 181 | 182 | For each user you want to access the private lists for (i.e. watchlist and/or custom lists), you will need to to authenticate that user. 183 | 184 | Repeat the following steps for every user you want to authenticate: 185 | 186 | 1. Run the following command: 187 | 188 | ``` 189 | traktarr trakt_authentication 190 | ``` 191 | 192 | 193 | 2. You wil get the following prompt: 194 | 195 | ``` 196 | - We're talking to Trakt to get your verification code. Please wait a moment... 197 | - Go to: https://trakt.tv/activate on any device and enter A0XXXXXX. We'll be polling Trakt every 5 seconds for a reply 198 | ``` 199 | 3. Go to https://trakt.tv/activate. 200 | 201 | 4. Enter the code you see in your terminal. 202 | 203 | 5. Click **Continue**. 204 | 205 | 6. If you are not logged in to Trakt.tv, login now. 206 | 207 | 7. Click **Accept**. 208 | 209 | 8. You will get the message: "Woohoo! Your device is now connected and will automatically refresh in a few seconds.". 210 | 211 | You've now authenticated the user. 212 | 213 | You can repeat this process for as many users as you like. 214 | 215 | 216 | # Configuration 217 | 218 | ## Sample Configuration 219 | 220 | ```json 221 | { 222 | "core": { 223 | "debug": false 224 | }, 225 | "automatic": { 226 | "movies": { 227 | "anticipated": 3, 228 | "boxoffice": 10, 229 | "interval": 24, 230 | "popular": 3, 231 | "trending": 2 232 | }, 233 | "shows": { 234 | "anticipated": 10, 235 | "interval": 48, 236 | "popular": 1, 237 | "trending": 2 238 | } 239 | }, 240 | "filters": { 241 | "movies": { 242 | "disabled_for": [], 243 | "allowed_countries": [ 244 | "us", 245 | "gb", 246 | "ca" 247 | ], 248 | "allowed_languages": [ 249 | "en" 250 | ], 251 | "blacklisted_genres": [ 252 | "documentary", 253 | "music", 254 | "animation" 255 | ], 256 | "blacklisted_max_runtime": 0, 257 | "blacklisted_min_runtime": 60, 258 | "blacklisted_min_year": 2000, 259 | "blacklisted_max_year": 2019, 260 | "blacklisted_title_keywords": [ 261 | "untitled", 262 | "barbie", 263 | "ufc" 264 | ], 265 | "blacklisted_tmdb_ids": [], 266 | "rotten_tomatoes": "" 267 | }, 268 | "shows": { 269 | "disabled_for": [], 270 | "allowed_countries": [ 271 | "us", 272 | "gb", 273 | "ca" 274 | ], 275 | "allowed_languages": [], 276 | "blacklisted_genres": [ 277 | "animation", 278 | "game-show", 279 | "talk-show", 280 | "home-and-garden", 281 | "children", 282 | "reality", 283 | "anime", 284 | "news", 285 | "documentary", 286 | "special-interest" 287 | ], 288 | "blacklisted_networks": [ 289 | "twitch", 290 | "youtube", 291 | "nickelodeon", 292 | "hallmark", 293 | "reelzchannel", 294 | "disney", 295 | "cnn", 296 | "cbbc", 297 | "the movie network", 298 | "teletoon", 299 | "cartoon network", 300 | "espn", 301 | "yahoo!", 302 | "fox sports" 303 | ], 304 | "blacklisted_max_runtime": 0, 305 | "blacklisted_min_runtime": 15, 306 | "blacklisted_min_year": 2000, 307 | "blacklisted_max_year": 2019, 308 | "blacklisted_title_keywords": [], 309 | "blacklisted_tvdb_ids": [] 310 | } 311 | }, 312 | "notifications": { 313 | "pushover": { 314 | "service": "pushover", 315 | "app_token": "", 316 | "user_token": "", 317 | "priority": 0 318 | }, 319 | "slack": { 320 | "service": "slack", 321 | "webhook_url": "" 322 | }, 323 | "verbose": true 324 | }, 325 | "radarr": { 326 | "api_key": "", 327 | "minimum_availability": "released", 328 | "quality": "HD-1080p", 329 | "root_folder": "/movies/", 330 | "url": "http://localhost:7878/" 331 | }, 332 | "sonarr": { 333 | "api_key": "", 334 | "language": "English", 335 | "quality": "HD-1080p", 336 | "root_folder": "/tv/", 337 | "season_folder": true, 338 | "tags": [], 339 | "url": "http://localhost:8989/" 340 | }, 341 | "trakt": { 342 | "client_id": "", 343 | "client_secret": "" 344 | }, 345 | "omdb": { 346 | "api_key": "" 347 | } 348 | } 349 | ``` 350 | 351 | 352 | ## Core 353 | 354 | ```json 355 | "core": { 356 | "debug": false 357 | }, 358 | ``` 359 | 360 | `debug` - Toggle debug messages in the log. Default is `false`. 361 | 362 | - Set to `true`, if you are having issues and want to diagnose why. 363 | 364 | 365 | ## Automatic 366 | 367 | ```json 368 | "automatic": { 369 | "movies": { 370 | "anticipated": 3, 371 | "boxoffice": 10, 372 | "interval": 24, 373 | "popular": 3, 374 | "trending": 0, 375 | "watched": 2, 376 | "played_all": 2, 377 | "watchlist": {}, 378 | "lists": {}, 379 | }, 380 | "shows": { 381 | "anticipated": 10, 382 | "interval": 48, 383 | "popular": 1, 384 | "trending": 2, 385 | "watched_monthly": 2, 386 | "played": 2, 387 | "watchlist": {}, 388 | "lists": {} 389 | } 390 | }, 391 | ``` 392 | Used for automatic / scheduled Traktarr tasks. 393 | 394 | Movies can be run on a separate schedule then from Shows. 395 | 396 | _Note: These settings are only needed if you plan to use Traktarr on a schedule (vs just using it as a CLI command only; see [Usage](#usage))._ 397 | 398 | Format: 399 | 400 | - "List Name": # of items to add into Radarr/Sonarr. 401 | 402 | _Note: The number specified is the number of items that will be added into Radarr/Sonarr. It is not a Trakt list limit, i.e. this is not going to lookup Top X items._ 403 | 404 | ### Interval 405 | 406 | `interval` - Specify how often (in hours) to run Traktarr task. 407 | 408 | - Setting `interval` to `0`, will skip the schedule for that task. 409 | 410 | - For example, if you only want to add movies and not TV shows, you can set show's `interval` to `0`. 411 | 412 | ### Official Trakt Lists 413 | 414 | `anticipated` - Trakt Anticipated List. 415 | 416 | - Most anticipated movies/shows based on the number of lists a movie/show appears on. 417 | 418 | `popular` - Trakt Popular List. 419 | 420 | - Most popular movies/shows. Popularity is calculated using the rating percentage and the number of ratings. 421 | 422 | `trending` - Trakt Trending List. 423 | 424 | - All movies/shows being watched right now. Movies with the most users are returned first. 425 | 426 | `boxoffice` - Trakt Box Office List. Movies only. 427 | 428 | - Top 10 grossing movies in the U.S. box office last weekend. Updated every Monday morning. 429 | 430 | `watched` - Most watched (unique users) movies in the specified time period. 431 | 432 | - `watched` / `watched_weekly` - Most watched in the week. 433 | 434 | - `watched_monthly` - Most watched in the month. 435 | 436 | - `watched_yearly` - Most watched in the year. 437 | 438 | - `watched_all` - Most watched of all time. 439 | 440 | `played` - Most played (a single user can watch multiple times) items in the specified time period. 441 | 442 | - `played` / `played_weekly` - Most played in the week. 443 | 444 | - `played_monthly` - Most played in the month. 445 | 446 | - `played_yearly` - Most played in the year. 447 | 448 | - `played_all` Most played of all time. 449 | 450 | `watchlist` - Specify which watchlists to fetch (see explanation below). 451 | 452 | ### Custom Lists 453 | 454 | `lists` - Specify which custom lists to fetch (see explanation below). 455 | 456 | You can also schedule any number of public or private custom lists. 457 | 458 | For both public and private lists you'll need the url to that list. When viewing the list on Trakt, simply copy the url from the address bar of the your browser. 459 | 460 | _Note: These are for non-watchlist lists. If you want to add a watchlist list, use the next section below._ 461 | 462 | #### Public Lists 463 | 464 | Public lists can be added by specifying the url and the item limit like this: 465 | 466 | ```json 467 | "automatic": { 468 | "movies": { 469 | "lists": { 470 | "https://trakt.tv/users/rkerwin/lists/top-100-movies": 10 471 | } 472 | }, 473 | "shows": { 474 | "lists": { 475 | "https://trakt.tv/users/claireaa/lists/top-100-tv-shows-of-all-time-ign": 10 476 | } 477 | } 478 | }, 479 | ``` 480 | 481 | 482 | #### Private Lists 483 | 484 | Private lists can be added in two ways: 485 | 486 | 1. If there is only one authenticated user, you can add the private list just like any other public list: 487 | 488 | ```json 489 | "automatic": { 490 | "movies": { 491 | "lists": { 492 | "https://trakt.tv/users/user/lists/my-private-movies-list": 10 493 | } 494 | }, 495 | "shows": { 496 | "lists": { 497 | "https://trakt.tv/users/user/lists/my-private-shows-list": 10 498 | } 499 | } 500 | }, 501 | ``` 502 | 503 | 2. If there are multiple authenticated users you want to fetch the lists from, you'll need to specify the username under `authenticate_as`. 504 | 505 | _Note: The user should have access to the list (either own the list or a list that was shared to them by a friend)._ 506 | 507 | ```json 508 | "automatic": { 509 | "movies": { 510 | "lists": { 511 | "https://trakt.tv/users/user/lists/my-private-movies-list": { 512 | "authenticate_as": "user2", 513 | "limit": 10 514 | } 515 | } 516 | }, 517 | "shows": { 518 | "lists": { 519 | "https://trakt.tv/users/user/lists/my-private-shows-list": { 520 | "authenticate_as": "user2", 521 | "limit": 10 522 | } 523 | } 524 | } 525 | }, 526 | ``` 527 | ### Personal Trakt Watchlists 528 | 529 | The watchlist task can be scheduled with a different item limit for every (authenticated) user. 530 | 531 | So for every user, you will add: `"username": limit` to the watchlist key. For example: 532 | 533 | ```json 534 | "automatic": { 535 | "movies": { 536 | "watchlist": { 537 | "user1": 10, 538 | "user2": 5 539 | } 540 | }, 541 | "shows": { 542 | "watchlist": { 543 | "user1": 2, 544 | "user3": 1 545 | } 546 | } 547 | }, 548 | ``` 549 | 550 | 551 | ## Filters 552 | 553 | Use filters to specify the movie/shows's country of origin or blacklist (i.e. filter-out) certain keywords, genres, years, runtime, or specific movies/shows. 554 | 555 | ### Movies 556 | 557 | ```json 558 | "movies": { 559 | "disabled_for": [], 560 | "allowed_countries": [ 561 | "us", 562 | "gb", 563 | "ca" 564 | ], 565 | "allowed_languages": [], 566 | "blacklisted_genres": [ 567 | "documentary", 568 | "music", 569 | "animation" 570 | ], 571 | "blacklisted_max_runtime": 0, 572 | "blacklisted_min_runtime": 60, 573 | "blacklisted_min_year": 2000, 574 | "blacklisted_max_year": 2019, 575 | "blacklisted_title_keywords": [ 576 | "untitled", 577 | "barbie" 578 | ], 579 | "blacklisted_tmdb_ids": [], 580 | "rotten_tomatoes": "" 581 | }, 582 | ``` 583 | 584 | `disabled_for` - Specify for which lists the blacklist is disabled for, when running in automatic mode. 585 | 586 | - This is similar to running `--ignore-blacklist` via the CLI command. 587 | 588 | - Example: 589 | 590 | ```json 591 | "disabled_for": [ 592 | "anticipated", 593 | "watchlist:user1", 594 | "list:http://url-to-list" 595 | ], 596 | ``` 597 | 598 | `allowed_countries` - Only add movies from these countries. Listed as two-letter country codes. 599 | 600 | - [List of available country codes](assets/list_of_country_codes.md). 601 | 602 | - Special keywords: 603 | 604 | - Blank list (i.e. `[]`) - Add movies from any country. 605 | 606 | - `ignore` (i.e. `["ignore"]`) - Add movies from any country, including ones with no country specified. 607 | 608 | `allowed_languages` - Only add movies with these languages. Listed as two-letter language codes. 609 | 610 | - Languages are in [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1) format (e.g. `ja` for Japanese.) 611 | 612 | - [List of available language codes](assets/list_of_language_codes.md). 613 | 614 | - Special keywords: 615 | 616 | - Blank list (i.e. `[]`) - Add movies with any language. 617 | 618 | - `ignore` (i.e. `["ignore"]`) - Add movies with any language, including ones with no language specified. 619 | 620 | `blacklisted_genres` - Blacklist certain genres. 621 | 622 | - [List of available movie genres](assets/list_of_movie_genres.md). 623 | 624 | - For an updated list, visit [here](https://trakt.docs.apiary.io/#reference/genres/list/get-genres). 625 | 626 | - Special Keywords: 627 | 628 | - Blank list (i.e. `[]`) - Add movies from any genre. 629 | 630 | - `ignore` (i.e. `["ignore"]`) - Add movies from any genre, including ones with no genre specified. 631 | 632 | `blacklisted_min_runtime` - Blacklist runtime duration shorter than specified time (in minutes). 633 | 634 | `blacklisted_max_runtime` - Blacklist runtime duration longer than specified time (in minutes). 635 | 636 | - Has to be longer than `blacklisted_min_runtime` or else it will be ignored. 637 | 638 | `blacklisted_min_year` - Blacklist release dates before specified year. This can be a 4 digit year, `0`, or `-` format. 639 | 640 | - If `0`, blacklist movies that came out before the current year. 641 | 642 | - If `-10`, blacklist movies that came out 10 years before the current year. 643 | 644 | `blacklisted_max_year` - Blacklist release dates after specified year. This can be a 4 digit year, `0`, or `+` format. 645 | 646 | - If `0`, blacklist movies that are coming out after the current year. 647 | 648 | - If `+1`, blacklist movies that are coming out after 1 year from current year. 649 | 650 | `blacklisted_title_keywords` - Blacklist certain words in titles. 651 | 652 | `blacklisted_tmdb_ids` - Blacklist certain movies with their TMDB IDs. 653 | 654 | - Example: 655 | 656 | ```json 657 | "blacklisted_tmdb_ids": [ 658 | 140607, 659 | 181808 660 | ], 661 | ``` 662 | 663 | `rotten_tomatoes` - Only add movies that are equal to or above this Rotten Tomatoes score. Requires an OMDb API Key (see [below](#omdb)). 664 | 665 | ### Shows 666 | 667 | ```json 668 | "shows": { 669 | "allowed_countries": [ 670 | "us", 671 | "gb", 672 | "ca" 673 | ], 674 | "allowed_languages": [], 675 | "blacklisted_genres": [ 676 | "animation", 677 | "game-show", 678 | "talk-show", 679 | "home-and-garden", 680 | "children", 681 | "reality", 682 | "anime", 683 | "news", 684 | "documentary", 685 | "special-interest" 686 | ], 687 | "blacklisted_networks": [ 688 | "twitch", 689 | "youtube", 690 | "nickelodeon", 691 | "hallmark", 692 | "reelzchannel", 693 | "disney", 694 | "cnn", 695 | "cbbc", 696 | "the movie network", 697 | "teletoon", 698 | "cartoon network", 699 | "espn", 700 | "yahoo!", 701 | "fox sports" 702 | ], 703 | "blacklisted_max_runtime": 0, 704 | "blacklisted_min_runtime": 15, 705 | "blacklisted_min_year": 2000, 706 | "blacklisted_max_year": 2019, 707 | "blacklisted_title_keywords": [], 708 | "blacklisted_tvdb_ids": [] 709 | } 710 | ``` 711 | 712 | `disabled_for` - Specify for which lists the blacklist is disabled for, when running in automatic mode. 713 | 714 | - This is similar to running `--ignore-blacklist` via the CLI command. 715 | 716 | - Example: 717 | 718 | ```json 719 | "disabled_for": [ 720 | "anticipated", 721 | "watchlist:user1", 722 | "list:http://url-to-list" 723 | ], 724 | ``` 725 | 726 | `allowed_countries` - Only add shows from these countries. Listed as two-letter country codes. 727 | 728 | - [List of available country codes](assets/list_of_country_codes.md). 729 | 730 | - Special keywords: 731 | 732 | - Blank list (i.e. `[]`) - Add shows from any country. 733 | 734 | - `ignore` (i.e. `["ignore"]`) - Add shows from any country, including ones with no country specified. 735 | 736 | `allowed_languages` - Only add shows with these languages. 737 | 738 | - Languages are in [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1) format (e.g. `ja` for Japanese.) 739 | 740 | - [List of available language codes](assets/list_of_language_codes.md). 741 | 742 | - Special keywords: 743 | 744 | - Blank list (i.e. `[]`) - Add shows with any language. 745 | 746 | - `ignore` (i.e. `["ignore"]`) - Add shows with any language, including ones with no language specified. 747 | 748 | `blacklisted_genres` - Blacklist certain genres. 749 | 750 | - [List of available TV show genres](assets/list_of_tv_show_genres.md). 751 | 752 | - For an updated list, visit [here](https://trakt.docs.apiary.io/#reference/genres/list/get-genres). 753 | 754 | - Special Keywords: 755 | 756 | - Blank list (i.e. `[]`) - Add shows from any genre. 757 | 758 | - `ignore` (i.e. `["ignore"]`) - Add shows from any genre, including ones with no genre specified. 759 | 760 | `blacklisted_networks` - Blacklist certain network. 761 | 762 | `blacklisted_min_runtime` - Blacklist runtime duration shorter than specified time (in minutes). 763 | 764 | `blacklisted_max_runtime` - Blacklist runtime duration longer than specified time (in minutes). 765 | 766 | - Has to be longer than `blacklisted_min_runtime` or else it will be ignored. 767 | 768 | `blacklisted_min_year` - Blacklist release dates before specified year. This can be a 4 digit year, `0`, or `-` format. 769 | 770 | - If `0`, blacklist shows that came out before the current year. 771 | 772 | - If `-10`, blacklist shows that came out 10 years before the current year. 773 | 774 | `blacklisted_max_year` - Blacklist release dates after specified year. This can be a 4 digit year, `0`, or `+` format. 775 | 776 | - If `0`, blacklist shows that are coming out after the current year. 777 | 778 | - If `+1`, blacklist shows that are coming out after 1 year from current year. 779 | 780 | `blacklisted_title_keywords` - Blacklist certain words in titles. 781 | 782 | `blacklisted_tvdb_ids` - Blacklist certain shows with their TVDB IDs. 783 | 784 | - Example: 785 | 786 | ```json 787 | "blacklisted_tvdb_ids": [ 788 | 79274, 789 | 85287, 790 | 71256, 791 | 194751, 792 | 76733, 793 | 336238 794 | ], 795 | ``` 796 | 797 | 798 | ## Notifications 799 | 800 | 801 | ```json 802 | "notifications": { 803 | "Apprise": { 804 | "service": "apprise", 805 | "url": "", 806 | "title": "" 807 | }, 808 | "verbose": false 809 | }, 810 | ``` 811 | 812 | Notification alerts for Traktarr tasks. 813 | 814 | For auto (i.e. scheduled) runs, notifications are enabled automatically when notification services are listed in this section. 815 | 816 | For manual (i.e. CLI) commands, you need to add the `--notifications` flag. 817 | 818 | Supported `services`: 819 | - `apprise` 820 | - `pushover` 821 | - `slack` 822 | 823 | _Note: The key name can be anything, but the `service` key must be must be the exact service name (e.g. `pushover`). See below for example._ 824 | 825 | 826 | ```json 827 | "notifications": { 828 | "anyname": { 829 | "service": "pushover", 830 | } 831 | }, 832 | ``` 833 | 834 | 835 | ### General 836 | 837 | `verbose` - Toggle detailed notifications. 838 | 839 | - Default is `true`. 840 | 841 | - Set to `false` if you want to reduce the amount of detailed notifications (e.g. just the total vs the names of the movies/shows added). 842 | 843 | ```json 844 | "notifications": { 845 | "verbose": true 846 | }, 847 | ``` 848 | 849 | ### Apprise 850 | 851 | ```json 852 | "notifications": { 853 | "Apprise": { 854 | "service": "apprise", 855 | "url": "", 856 | "title": "" 857 | }, 858 | "verbose": false 859 | }, 860 | ``` 861 | 862 | `url` - Apprise service URL (see [here](https://github.com/caronc/apprise)). 863 | 864 | - Required. 865 | 866 | `title` - Notification Title. 867 | 868 | - Optional. 869 | 870 | - Default is `Traktarr`. 871 | 872 | 873 | ### Pushover 874 | 875 | ```json 876 | "notifications": { 877 | "pushover": { 878 | "service": "pushover", 879 | "app_token": "", 880 | "user_token": "", 881 | "priority": 0 882 | }, 883 | "verbose": false 884 | }, 885 | ``` 886 | 887 | `app_token` - App Token from [Pushover.net](https://pushover.net). 888 | 889 | - Required. 890 | 891 | `user_token` - User Token from [Pushover.net](https://pushover.net). 892 | 893 | - Required. 894 | 895 | `priority` - [Priority](https://pushover.net/api#priority) of the notifications. 896 | 897 | - Optional. 898 | 899 | - Choices are: `-2`, `-1`, `0`, `1`, `2`. 900 | 901 | - Values are not quoted. 902 | 903 | - Default is `0`. 904 | 905 | 906 | ### Slack 907 | 908 | ```json 909 | "notifications": { 910 | "slack": { 911 | "service": "slack", 912 | "webhook_url": "", 913 | "channel": "", 914 | "sender_name": "Traktarr", 915 | "sender_icon": ":movie_camera:" 916 | }, 917 | "verbose": false 918 | }, 919 | ``` 920 | 921 | `webhook_url` - [Webhook URL](https://my.slack.com/services/new/incoming-webhook/). 922 | 923 | - Required. 924 | 925 | `channel` - Slack channel to send the notifications to. 926 | 927 | - Optional. 928 | 929 | - Default is blank. 930 | 931 | `sender_name` - Sender's name for the notifications. 932 | 933 | - Optional. 934 | 935 | - Default is `Traktarr`. 936 | 937 | `sender_icon` - Icon to use for the notifications. 938 | 939 | - Optional. 940 | 941 | - Default is `:movie_camera:` 942 | 943 | 944 | 945 | ## Radarr 946 | 947 | Radarr configuration. 948 | 949 | ```json 950 | "radarr": { 951 | "api_key": "", 952 | "minimum_availability": "released", 953 | "quality": "HD-1080p", 954 | "root_folder": "/movies/", 955 | "url": "http://localhost:7878" 956 | }, 957 | ``` 958 | `api_key` - Radarr's API Key. 959 | 960 | `quality` - Quality Profile that movies are assigned to. 961 | 962 | `minimum_availability` - The minimum availability the movies are set to. 963 | 964 | - Choices are `announced`, `in_cinemas` or `released` (Physical/Web). 965 | 966 | - Default is `released` (Physical/Web). 967 | 968 | `root_folder` - Root folder for movies. 969 | 970 | `url` - Radarr's URL. 971 | 972 | - Note: If you have URL Base enabled in Radarr's settings, you will need to add that into the URL as well. 973 | 974 | ## Sonarr 975 | 976 | Sonarr configuration. 977 | 978 | 979 | ```json 980 | "sonarr": { 981 | "api_key": "", 982 | "language": "English", 983 | "quality": "HD-1080p", 984 | "root_folder": "/tv/", 985 | "season_folder": true, 986 | "tags": [], 987 | "url": "http://localhost:8989" 988 | }, 989 | ``` 990 | 991 | `api_key` - Sonarr's API Key. 992 | 993 | `language` - Language Profile that TV shows are assigned to. Only applies to Sonarr v3. 994 | 995 | `quality` - Quality Profile that TV shows are assigned to. 996 | 997 | `root_folder` - Root folder for TV shows. 998 | 999 | `season_folder` - Sort episodes into season folders. 1000 | 1001 | `tags` - Assign tags to shows. Tags need to be created in Sonarr first. 1002 | 1003 | - Examples: 1004 | 1005 | ```json 1006 | "tags": ["anime"] 1007 | ``` 1008 | 1009 | ```json 1010 | "tags": ["anime", "jap"] 1011 | ``` 1012 | 1013 | ```json 1014 | "tags": [ 1015 | "anime", 1016 | "jap" 1017 | ] 1018 | ``` 1019 | 1020 | `url` - Sonarr's URL. 1021 | 1022 | - Note: If you have URL Base enabled in Sonarr's settings, you will need to add that into the URL as well. 1023 | 1024 | ## Trakt 1025 | 1026 | Trakt Authentication info: 1027 | 1028 | ```json 1029 | "trakt": { 1030 | "client_id": "", 1031 | "client_secret": "" 1032 | } 1033 | ``` 1034 | 1035 | `client_id` - Your Trakt API Key (_Client ID_). 1036 | 1037 | `client_secret` - Your Trakt Secret Key (_Client Secret_). 1038 | 1039 | ## OMDb 1040 | 1041 | [OMDb](https://www.omdbapi.com/) Authentication info. 1042 | 1043 | ```json 1044 | "omdb": { 1045 | "api_key":"" 1046 | } 1047 | ``` 1048 | 1049 | `api_key` - Your [OMDb](https://www.omdbapi.com/) API Key. 1050 | 1051 | - This is only needed if you wish to use a minimum Rotten Tomatoes score to filter out movies. 1052 | 1053 | - Use `rotten_tomatoes` in config for automatic scheduling or `--rotten_tomatoes` as an argument for CLI. 1054 | 1055 | # Usage 1056 | 1057 | ## Automatic (Scheduled) 1058 | 1059 | ### Setup 1060 | 1061 | To have Traktarr get Movies and Shows for you automatically, on set interval, do the following: 1062 | 1063 | 1. `sudo cp /opt/traktarr/systemd/traktarr.service /etc/systemd/system/` 1064 | 1065 | 2. `sudo nano /etc/systemd/system/traktarr.service` and edit user/group to match yours' (run `id` to check). 1066 | 1067 | 3. `sudo systemctl daemon-reload` 1068 | 1069 | 4. `sudo systemctl enable traktarr.service` 1070 | 1071 | 5. `sudo systemctl start traktarr.service` 1072 | 1073 | ### Customize 1074 | 1075 | You can customize how the scheduled Traktarr is ran by editing the `traktarr.service` file and adding any of the following options: 1076 | 1077 | \* Remember, other configuration options need to go into the `config.json` file under the `Automatic` section. 1078 | 1079 | ``` 1080 | traktarr run --help 1081 | ``` 1082 | 1083 | ``` 1084 | Usage: traktarr run [OPTIONS] 1085 | 1086 | Run in automatic mode. 1087 | 1088 | Options: 1089 | -d, --add-delay FLOAT Seconds between each add request to Sonarr / 1090 | Radarr. [default: 2.5] 1091 | -s, --sort [votes|rating|release] 1092 | Sort list to process. 1093 | --no-search Disable search when adding to Sonarr / 1094 | Radarr. 1095 | --run-now Do a first run immediately without waiting. 1096 | --no-notifications Disable notifications. 1097 | --ignore-blacklist Ignores the blacklist when running the 1098 | command. 1099 | --help Show this message and exit. 1100 | ``` 1101 | 1102 | 1103 | `-d`, `--add-delay` - Add seconds delay between each add request to Sonarr / Radarr. Default is `2.5` seconds. 1104 | 1105 | - Example: `-d 5` 1106 | 1107 | `-s`, `--sort` - Sort list by highest `votes`, highest `rating`, or the latest `release` dates. Default is highest `votes`. 1108 | 1109 | - Example: `-s release` 1110 | 1111 | `--no-search` - Tells Sonarr / Radarr to not automatically search for added shows / movies. 1112 | 1113 | `--run-now` - Traktarr will run first automated search on start, without waiting for next interval. 1114 | 1115 | `--no-notifications` - Disable notifications. Default is `enabled`. 1116 | 1117 | `--ignore-blacklist` - Ignores blacklist filtering. Equivalent of `disabled_for` in config.json. 1118 | 1119 | 1120 | Example of a modified line from the `traktarr.service` file that will always add from the most recent releases matched: 1121 | 1122 | ``` 1123 | ExecStart=/usr/bin/python3 /opt/traktarr/traktarr.py run -s release 1124 | ``` 1125 | 1126 | ## Manual (CLI) 1127 | 1128 | ### General 1129 | 1130 | ``` 1131 | traktarr 1132 | ``` 1133 | 1134 | ``` 1135 | Usage: traktarr [OPTIONS] COMMAND [ARGS]... 1136 | 1137 | Add new shows & movies to Sonarr/Radarr from Trakt. 1138 | 1139 | Options: 1140 | --version Show the version and exit. 1141 | --config PATH Configuration file [default: /Users/macuser/Documents/Git 1142 | Hub/l3uddz/traktarr/config.json] 1143 | --cachefile PATH Cache file [default: 1144 | /Users/macuser/Documents/GitHub/l3uddz/traktarr/cache.db] 1145 | --logfile PATH Log file [default: /Users/macuser/Documents/GitHub/l3uddz 1146 | /traktarr/activity.log] 1147 | --help Show this message and exit. 1148 | 1149 | Commands: 1150 | movie Add a single movie to Radarr. 1151 | movies Add multiple movies to Radarr. 1152 | run Run Traktarr in automatic mode. 1153 | show Add a single show to Sonarr. 1154 | shows Add multiple shows to Sonarr. 1155 | trakt_authentication Authenticate Traktarr. 1156 | ``` 1157 | 1158 | ### Movie (Single Movie) 1159 | 1160 | ``` 1161 | traktarr movie --help 1162 | ``` 1163 | 1164 | ``` 1165 | Usage: traktarr movie [OPTIONS] 1166 | 1167 | Add a single movie to Radarr. 1168 | 1169 | Options: 1170 | -id, --movie-id TEXT Trakt Movie ID. [required] 1171 | -f, --folder TEXT Add movie with this root folder to Radarr. 1172 | -ma, --minimum-availability [announced|in_cinemas|released] 1173 | Add movies with this minimum availability to Radarr. 1174 | --no-search Disable search when adding movie to Radarr. 1175 | --help Show this message and exit. 1176 | ``` 1177 | 1178 | `-id`, `--movie-id` - ID/slug of the movie to add to Radarr. Supports both Trakt and IMDB IDs. This arguent is required. 1179 | 1180 | `-f`, `--folder` - Add movie to a specific root folder in Radarr. 1181 | 1182 | - Example: `-f /mnt/unionfs/Media/Movies/Movies-Kids/` 1183 | 1184 | `minimum_availability` - The minimum availability the movies are set to. 1185 | 1186 | - Choices are `announced`, `in_cinemas` or `released` (Physical/Web). 1187 | 1188 | - Default is `released` (Physical/Web). 1189 | 1190 | `--no-search` - Tells Radarr to not automatically search for added movies. 1191 | 1192 | 1193 | ### Movies (Multiple Movies) 1194 | 1195 | ``` 1196 | traktarr movies --help 1197 | ``` 1198 | 1199 | 1200 | ``` 1201 | Usage: traktarr movies [OPTIONS] 1202 | 1203 | Add multiple movies to Radarr. 1204 | 1205 | Options: 1206 | -t, --list-type TEXT Trakt list to process. For example, 'anticipated', 'trending', 1207 | 'popular', 'person', 'watched', 'played', 'recommended', 1208 | 'watchlist', or any URL to a list. [required] 1209 | -l, --add-limit INTEGER Limit number of movies added to Radarr. 1210 | -d, --add-delay FLOAT Seconds between each add request to Radarr. [default: 2.5] 1211 | -s, --sort [rating|release|votes] 1212 | Sort list to process. [default: votes] 1213 | -rt, --rotten_tomatoes INTEGER Set a minimum Rotten Tomatoes score. 1214 | -y, --year, --years TEXT Can be a specific year or a range of years to search. For 1215 | example, '2000' or '2000-2010'. 1216 | -g, --genres TEXT Only add movies from this genre to Radarr. Multiple genres are 1217 | specified as a comma-separated list. Use 'ignore' to add movies 1218 | from any genre, including ones with no genre specified. 1219 | -f, --folder TEXT Add movies with this root folder to Radarr. 1220 | -ma, --minimum-availability [announced|in_cinemas|released] 1221 | Add movies with this minimum availability to Radarr. Default is 1222 | 'released'. 1223 | -p, --person TEXT Only add movies from this person (e.g. actor) to Radarr. Only 1224 | one person can be specified. Requires the 'person' list type. 1225 | --include-non-acting-roles Include non-acting roles such as 'Director', 'As Himself', 1226 | 'Narrator', etc. Requires the 'person' list type with the 1227 | 'person' argument. 1228 | --no-search Disable search when adding movies to Radarr. 1229 | --notifications Send notifications. 1230 | --authenticate-user TEXT Specify which user to authenticate with to retrieve Trakt lists. 1231 | Defaults to first user in the config. 1232 | --ignore-blacklist Ignores the blacklist when running the command. 1233 | --remove-rejected-from-recommended 1234 | Removes rejected/existing movies from recommended. 1235 | --help Show this message and exit. 1236 | ``` 1237 | 1238 | `-t`, `--list-type` - Trakt list to process. 1239 | 1240 | Choices are: `anticipated`, `trending`, `popular`, `boxoffice`, `watched`, `played`, `URL` (Trakt list), or `person` (used with `-p`/`--person` argument). 1241 | 1242 | - Top Watched List options: 1243 | 1244 | - `watched` / `watched_weekly` - Most watched in the week. 1245 | 1246 | - `watched_monthly` - Most watched in the month. 1247 | 1248 | - `watched_yearly` - Most watched in the year. 1249 | 1250 | - `watched_all` - Most watched of all time. 1251 | 1252 | - Top Played List options: 1253 | 1254 | - `played` / `played_weekly` - Most played in the week. 1255 | 1256 | - `played_monthly` - Most played in the month. 1257 | 1258 | - `played_yearly` - Most played in the year. 1259 | 1260 | - `played_all` Most played of all time. 1261 | 1262 | `-l`, `--add-limit` - Limit number of movies added to Radarr. 1263 | 1264 | - Note: This is a limit on how many items are added into Radarr. Not a limit on how many items to retrieve from Trakt. 1265 | 1266 | `-d`, `--add-delay` - Add seconds delay between each add request to Radarr. Default is 2.5 seconds. 1267 | 1268 | - Example: `-d 5` 1269 | 1270 | `-s`, `--sort` - Sort list by highest `votes`, highest `rating`, or the latest `release` dates. Default is highest `votes`. 1271 | 1272 | - Example: `-s release` 1273 | 1274 | `-rt`, `--rotten_tomatoes` - Only add movies equal to or above this Rotten Tomatoes score. 1275 | 1276 | - Example: `-rt 75` 1277 | 1278 | `-y`, `--year`, `--years` - Only add movies from from a specific year or range of years. 1279 | 1280 | - Examples: `-y 2010`, `--years 2010-2020` 1281 | 1282 | `-g`, `--genres` - Only add movies from these genre(s) to Radarr. 1283 | 1284 | - Multiple genres are passed as comma-separated lists. The effect of this is equivalent of boolean OR. (ie. include items from any of these genres). 1285 | 1286 | - Can find a list [here](assets/list_of_movie_genres.md). 1287 | 1288 | `-f`, `--folder` - Add movies to a specific root folder in Radarr. 1289 | 1290 | - Example: `-f /mnt/unionfs/Media/Movies/Movies-Kids/` 1291 | 1292 | `minimum_availability` - The minimum availability the movies are set to. 1293 | 1294 | - Choices are `announced`, `in_cinemas` or `released` (Physical/Web). 1295 | 1296 | - Default is `released` (Physical/Web). 1297 | 1298 | `-p`, `--person` - Only add movies with a specific person to Radarr. 1299 | 1300 | - Requires the list type `person`. 1301 | 1302 | `--include-non-acting-roles` - Include non-acting roles of the specified person. 1303 | 1304 | - Requires the list type `person` used with the `-p`/`--person` option. 1305 | 1306 | `--no-search` - Tells Radarr to not automatically search for added movies. 1307 | 1308 | `--notifications` - To enable notifications. Default is `disabled`. 1309 | 1310 | `--authenticate-user` - Specify which authenticated user to retrieve Trakt lists as. Default is the first user in the config. 1311 | 1312 | `--ignore-blacklist` - Ignores blacklist filtering. 1313 | 1314 | - Equivalent of `disabled_for` in `config.json`. 1315 | 1316 | `--remove-rejected-from-recommended` - Removes rejected/existing shows from the recommended list, so that it will be removed from further recommendations. 1317 | 1318 | 1319 | ### Show (Single Show) 1320 | 1321 | ``` 1322 | traktarr show --help 1323 | ``` 1324 | 1325 | 1326 | ``` 1327 | Usage: traktarr show [OPTIONS] 1328 | 1329 | Add a single show to Sonarr. 1330 | 1331 | Options: 1332 | -id, --show-id TEXT Trakt Show ID. [required] 1333 | -f, --folder TEXT Add show with this root folder to Sonarr. 1334 | --no-search Disable search when adding show to Sonarr. 1335 | --help Show this message and exit. 1336 | ``` 1337 | 1338 | `-id`, `--show-id` - ID/slug of the show to add to Sonarr. Supports both Trakt and IMDB IDs. This argument is required. 1339 | 1340 | 1341 | ### Shows (Multiple Shows) 1342 | 1343 | ``` 1344 | traktarr shows --help 1345 | ``` 1346 | 1347 | 1348 | ``` 1349 | Usage: traktarr shows [OPTIONS] 1350 | 1351 | Add multiple shows to Sonarr. 1352 | 1353 | Options: 1354 | -t, --list-type TEXT Trakt list to process. For example, 'anticipated', 'trending', 1355 | 'popular', 'person', 'watched', 'played', 'recommended', 1356 | 'watchlist', or any URL to a list. [required] 1357 | -l, --add-limit INTEGER Limit number of shows added to Sonarr. 1358 | -d, --add-delay FLOAT Seconds between each add request to Sonarr. [default: 2.5] 1359 | -s, --sort [rating|release|votes] 1360 | Sort list to process. [default: votes] 1361 | -y, --year, --years TEXT Can be a specific year or a range of years to search. For 1362 | example, '2000' or '2000-2010'. 1363 | -g, --genres TEXT Only add shows from this genre to Sonarr. Multiple genres are 1364 | specified as a comma-separated list. Use 'ignore' to add shows 1365 | from any genre, including ones with no genre specified. 1366 | -f, --folder TEXT Add shows with this root folder to Sonarr. 1367 | -p, --person TEXT Only add shows from this person (e.g. actor) to Sonarr. Only one 1368 | person can be specified. Requires the 'person' list type. 1369 | --include-non-acting-roles Include non-acting roles such as 'Director', 'As Himself', 1370 | 'Narrator', etc. Requires the 'person' list type with the 1371 | 'person' argument. 1372 | --no-search Disable search when adding shows to Sonarr. 1373 | --notifications Send notifications. 1374 | --authenticate-user TEXT Specify which user to authenticate with to retrieve Trakt lists. 1375 | Defaults to first user in the config 1376 | --ignore-blacklist Ignores the blacklist when running the command. 1377 | --remove-rejected-from-recommended 1378 | Removes rejected/existing shows from recommended. 1379 | --help Show this message and exit. 1380 | ``` 1381 | 1382 | 1383 | `-t`, `--list-type` - Trakt list to process. 1384 | 1385 | Choices are: `anticipated`, `trending`, `popular`, `watched`, `played`, `URL` (Trakt list), or `person` (used with `-p`/`--person` argument). 1386 | 1387 | - Top Watched List options: 1388 | 1389 | - `watched` / `watched_weekly` - Most watched in the week. 1390 | 1391 | - `watched_monthly` - Most watched in the month. 1392 | 1393 | - `watched_yearly` - Most watched in the year. 1394 | 1395 | - `watched_all` - Most watched of all time. 1396 | 1397 | - Top Played List options: 1398 | 1399 | - `played` / `played_weekly` - Most played in the week. 1400 | 1401 | - `played_monthly` - Most played in the month. 1402 | 1403 | - `played_yearly` - Most played in the year. 1404 | 1405 | - `played_all` Most played of all time. 1406 | 1407 | `-l`, `--add-limit` - Limit number of shows added to Sonarr. 1408 | 1409 | - Note: This is a limit on how many items are added into Sonarr. Not a limit on how many items to retrieve from Trakt. 1410 | 1411 | `-d`, `--add-delay` - Add seconds delay between each add request to Sonarr. Default is 2.5 seconds. 1412 | 1413 | - Example: `-d 5` 1414 | 1415 | `-s`, `--sort` - Sort list by highest `votes`, highest `rating`, or the latest `release` dates. Default is highest `votes`. 1416 | 1417 | - Example: `-s release` 1418 | 1419 | `-y`, `--year`, `--years` - Only add shows from from a specific year or range of years. 1420 | 1421 | - Examples: `-y 2010`, `--years 2010-2020` 1422 | 1423 | `-g`, `--genres` - Only add shows from this genre(s) to Sonarr. 1424 | 1425 | - Multiple genres are passed as comma-separated lists. The effect of this is equivalent of boolean OR. (ie. include items from any of these genres). 1426 | 1427 | - Can find a list [here](assets/list_of_tv_show_genres.md). 1428 | 1429 | `-f`, `--folder` - Add shows to a specific root folder in Sonarr. 1430 | 1431 | - Example: `-f /mnt/unionfs/Media/Shows/Shows-Kids/` 1432 | 1433 | `-p`, `--person` - Only add shows with a specific person to Sonarr. 1434 | 1435 | - Requires the list type `person`. 1436 | 1437 | `--include-non-acting-roles` - Include non-acting roles of the specified person. 1438 | 1439 | - Requires the list type `person` used with the `-p`/`--person` option. 1440 | 1441 | `--no-search` - Tells Sonarr to not automatically search for added shows. 1442 | 1443 | `--notifications` - To enable notifications. Default is `disabled`. 1444 | 1445 | `--authenticate-user` - Specify which authenticated user to retrieve Trakt lists as. Default is the first user in the config. 1446 | 1447 | `--ignore-blacklist` - Ignores blacklist filtering. Equivalent of `disabled_for` in `config.json`. 1448 | 1449 | `--remove-rejected-from-recommended` - Removes rejected/existing shows from the recommended list, so that it will be removed from further recommendations. 1450 | 1451 | 1452 | ## Examples (CLI) 1453 | 1454 | ### Movies 1455 | 1456 | - Add the movie "Black Panther (2018)": 1457 | 1458 | ``` 1459 | traktarr movie -id black-panther-2018 1460 | ``` 1461 | 1462 | - Add movies, from the popular list, labeled with the thriller genre, limited to 5 items, and sorted by latest release date. 1463 | 1464 | ``` 1465 | traktarr movies -t popular -g thriller -l 5 -s release 1466 | ``` 1467 | 1468 | - Add movies, from the Box Office list, labeled with the comedy genre, limited to 10 items, and send notifications: 1469 | 1470 | ``` 1471 | traktarr movies -t boxoffice -g comedy -l 10 --notifications 1472 | ``` 1473 | 1474 | - Add movies, from a list of most watched played this week, and limited to 5 items. 1475 | 1476 | ``` 1477 | traktarr movies -t watched -l 5 1478 | ``` 1479 | 1480 | - Add movies, from a list of most played movies this month, and limited to 5 items. 1481 | 1482 | ``` 1483 | traktarr movies -t played_monthly -l 5 1484 | ``` 1485 | 1486 | - Add (all) movies from the public list `https://trakt.tv/users/rkerwin/lists/top-100-movies`: 1487 | 1488 | ``` 1489 | traktarr movies -t https://trakt.tv/users/rkerwin/lists/top-100-movies 1490 | ``` 1491 | 1492 | - Add (all) movies from the private list `https://trakt.tv/users/user1/lists/private-movies-list` of `user1`: 1493 | 1494 | ``` 1495 | traktarr movies -t https://trakt.tv/users/user1/lists/private-movies-list --authenticate-user=user1 1496 | ``` 1497 | 1498 | - Add movies, from the trending list, with a minimum Rotten Tomatoes score of 80%. 1499 | 1500 | ``` 1501 | traktarr movies -t trending -rt 80 1502 | ``` 1503 | 1504 | - Add movies, from the trending list, from the year 2020. 1505 | 1506 | ``` 1507 | traktarr movies -t trending -y 2020 1508 | ``` 1509 | 1510 | - Add movies, with actor 'Keanu Reeves', limited to 10 items. 1511 | 1512 | ``` 1513 | traktarr movies -t person -p 'keanu reeves' -l 10 1514 | ``` 1515 | 1516 | - Add movies, with actor 'Tom Cruise', including movies where he has non-acting roles, limited to 10 items. 1517 | 1518 | ``` 1519 | traktarr movies -t person -p 'tom cruise' --include-non-acting-roles -l 10 1520 | ``` 1521 | 1522 | ### Shows 1523 | 1524 | - Add the show "The 100": 1525 | 1526 | ``` 1527 | traktarr show -id the-100 1528 | ``` 1529 | 1530 | - Add shows, from the popular list, limited to 5 items, and sorted by highest ratings. 1531 | 1532 | ``` 1533 | traktarr shows -t popular -l 5 -s rating 1534 | ``` 1535 | 1536 | - Add shows, from the popular list, limited to 2 items, and add them but don't search for episodes in Sonarr: 1537 | 1538 | ``` 1539 | traktarr shows -t popular -l 2 --no-search 1540 | ``` 1541 | 1542 | - Add shows, from a list of most watched shows this year, and limited to 5 items. 1543 | 1544 | ``` 1545 | traktarr shows -t watched_yearly -l 5 1546 | ``` 1547 | 1548 | - Add shows, from a list of most played shows this week, and limited to 5 items. 1549 | 1550 | ``` 1551 | traktarr shows -t played -l 5 1552 | ``` 1553 | 1554 | - Add shows, from a list of most played shows of all time, and limited to 5 items. 1555 | 1556 | ``` 1557 | traktarr shows -t played_all -l 5 1558 | ``` 1559 | 1560 | - Add (all) shows from the watchlist of `user1`: 1561 | 1562 | ``` 1563 | traktarr shows -t watchlist --authenticate-user user1 1564 | ``` 1565 | -------------------------------------------------------------------------------- /assets/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/l3uddz/traktarr/52d71964a2cd6504adda6e2b2d5cdfc68cc794c8/assets/demo.gif -------------------------------------------------------------------------------- /assets/list_of_country_codes.md: -------------------------------------------------------------------------------- 1 | | Country | Country Code | 2 | |:---------------------------------------|:-------------| 3 | | Australia | `au` | 4 | | Austria | `at` | 5 | | Belgium | `be` | 6 | | Bolivia, Plurinational State of | `bo` | 7 | | Bosnia and Herzegovina | `ba` | 8 | | Brazil | `br` | 9 | | British Indian Ocean Territory | `io` | 10 | | Bulgaria | `bg` | 11 | | Canada | `ca` | 12 | | Chile | `cl` | 13 | | China | `cn` | 14 | | Colombia | `co` | 15 | | Croatia | `hr` | 16 | | Cuba | `cu` | 17 | | Czech Republic | `cz` | 18 | | Denmark | `dk` | 19 | | Egypt | `eg` | 20 | | Estonia | `ee` | 21 | | Finland | `fi` | 22 | | France | `fr` | 23 | | French Polynesia | `pf` | 24 | | Georgia | `ge` | 25 | | Germany | `de` | 26 | | Greece | `gr` | 27 | | Hong Kong | `hk` | 28 | | Hungary | `hu` | 29 | | Iceland | `is` | 30 | | India | `in` | 31 | | Indonesia | `id` | 32 | | Iran, Islamic Republic of | `ir` | 33 | | Ireland | `ie` | 34 | | Israel | `il` | 35 | | Italy | `it` | 36 | | Japan | `jp` | 37 | | Kenya | `ke` | 38 | | Korea, Democratic People's Republic of | `kp` | 39 | | Korea, Republic of | `kr` | 40 | | Kuwait | `kw` | 41 | | Latvia | `lv` | 42 | | Lebanon | `lb` | 43 | | Lithuania | `lt` | 44 | | Macedonia, Republic of | `mk` | 45 | | Malaysia | `my` | 46 | | Maldives | `mv` | 47 | | Mexico | `mx` | 48 | | Mongolia | `mn` | 49 | | Montenegro | `me` | 50 | | Morocco | `ma` | 51 | | Netherlands | `nl` | 52 | | New Zealand | `nz` | 53 | | Nigeria | `ng` | 54 | | Norway | `no` | 55 | | Pakistan | `pk` | 56 | | Paraguay | `py` | 57 | | Philippines | `ph` | 58 | | Poland | `pl` | 59 | | Portugal | `pt` | 60 | | Romania | `ro` | 61 | | Russian Federation | `ru` | 62 | | Saudi Arabia | `sa` | 63 | | Serbia | `rs` | 64 | | Singapore | `sg` | 65 | | Slovakia | `sk` | 66 | | Slovenia | `si` | 67 | | South Africa | `za` | 68 | | Spain | `es` | 69 | | Swaziland | `sz` | 70 | | Sweden | `se` | 71 | | Switzerland | `ch` | 72 | | Taiwan | `tw` | 73 | | Thailand | `th` | 74 | | Turkey | `tr` | 75 | | Ukraine | `ua` | 76 | | United Arab Emirates | `ae` | 77 | | United Kingdom | `gb` | 78 | | United States | `us` | 79 | | United States Minor Outlying Islands | `um` | 80 | | Venezuela, Bolivarian Republic of | `ve` | 81 | | Vietnam | `vn` | 82 | -------------------------------------------------------------------------------- /assets/list_of_language_codes.md: -------------------------------------------------------------------------------- 1 | | Language | Language Code | 2 | |:--------------------------------------|:--------------| 3 | | Afrikaans | `af` | 4 | | Akan | `ak` | 5 | | Albanian | `sq` | 6 | | Amharic | `am` | 7 | | Arabic | `ar` | 8 | | Armenian | `hy` | 9 | | Assamese | `as` | 10 | | Aymara | `ay` | 11 | | Azerbaijani | `az` | 12 | | Bambara | `bm` | 13 | | Basque | `eu` | 14 | | Belarusian | `be` | 15 | | Bengali | `bn` | 16 | | Bokmål, Norwegian; Norwegian Bokmål | `nb` | 17 | | Bosnian | `bs` | 18 | | Breton | `br` | 19 | | Bulgarian | `bg` | 20 | | Burmese | `my` | 21 | | Catalan; Valencian | `ca` | 22 | | Central Khmer | `km` | 23 | | Chamorro | `ch` | 24 | | Chechen | `ce` | 25 | | Chinese | `zh` | 26 | | Cornish | `kw` | 27 | | Corsican | `co` | 28 | | Cree | `cr` | 29 | | Croatian | `hr` | 30 | | Czech | `cs` | 31 | | Danish | `da` | 32 | | Divehi; Dhivehi; Maldivian | `dv` | 33 | | Dutch; Flemish | `nl` | 34 | | Dzongkha | `dz` | 35 | | English | `en` | 36 | | Esperanto | `eo` | 37 | | Estonian | `et` | 38 | | Ewe | `ee` | 39 | | Faroese | `fo` | 40 | | Finnish | `fi` | 41 | | French | `fr` | 42 | | Gaelic; Scottish Gaelic | `gd` | 43 | | Galician | `gl` | 44 | | Georgian | `ka` | 45 | | German | `de` | 46 | | Greek, Modern (1453-) | `el` | 47 | | Guarani | `gn` | 48 | | Gujarati | `gu` | 49 | | Haitian; Haitian Creole | `ht` | 50 | | Hausa | `ha` | 51 | | Hebrew | `he` | 52 | | Hindi | `hi` | 53 | | Hungarian | `hu` | 54 | | Icelandic | `is` | 55 | | Igbo | `ig` | 56 | | Indonesian | `id` | 57 | | Inuktitut | `iu` | 58 | | Irish | `ga` | 59 | | Italian | `it` | 60 | | Japanese | `ja` | 61 | | Javanese | `jv` | 62 | | Kalaallisut; Greenlandic | `kl` | 63 | | Kannada | `kn` | 64 | | Kazakh | `kk` | 65 | | Kinyarwanda | `rw` | 66 | | Kirghiz; Kyrgyz | `ky` | 67 | | Korean | `ko` | 68 | | Kurdish | `ku` | 69 | | Lao | `lo` | 70 | | Latin | `la` | 71 | | Latvian | `lv` | 72 | | Lithuanian | `lt` | 73 | | Luxembourgish; Letzeburgesch | `lb` | 74 | | Macedonian | `mk` | 75 | | Malagasy | `mg` | 76 | | Malay | `ms` | 77 | | Malayalam | `ml` | 78 | | Maltese | `mt` | 79 | | Maori | `mi` | 80 | | Marathi | `mr` | 81 | | Marshallese | `mh` | 82 | | Mongolian | `mn` | 83 | | Navajo; Navaho | `nv` | 84 | | Ndebele, South; South Ndebele | `nr` | 85 | | Nepali | `ne` | 86 | | Norwegian | `no` | 87 | | Norwegian Nynorsk; Nynorsk, Norwegian | `nn` | 88 | | Occitan (post 1500); Provençal | `oc` | 89 | | Panjabi; Punjabi | `pa` | 90 | | Persian | `fa` | 91 | | Polish | `pl` | 92 | | Portuguese | `pt` | 93 | | Pushto; Pashto | `ps` | 94 | | Quechua | `qu` | 95 | | Romanian; Moldavian; Moldovan | `ro` | 96 | | Rundi | `rn` | 97 | | Russian | `ru` | 98 | | Samoan | `sm` | 99 | | Sango | `sg` | 100 | | Sanskrit | `sa` | 101 | | Serbian | `sr` | 102 | | Shona | `sn` | 103 | | Sinhala; Sinhalese | `si` | 104 | | Slovak | `sk` | 105 | | Slovenian | `sl` | 106 | | Somali | `so` | 107 | | Spanish; Castilian | `es` | 108 | | Swahili | `sw` | 109 | | Swedish | `sv` | 110 | | Tagalog | `tl` | 111 | | Tahitian | `ty` | 112 | | Tajik | `tg` | 113 | | Tamil | `ta` | 114 | | Tatar | `tt` | 115 | | Telugu | `te` | 116 | | Thai | `th` | 117 | | Tibetan | `bo` | 118 | | Tigrinya | `ti` | 119 | | Tonga (Tonga Islands) | `to` | 120 | | Turkish | `tr` | 121 | | Turkmen | `tk` | 122 | | Ukrainian | `uk` | 123 | | Urdu | `ur` | 124 | | Uzbek | `uz` | 125 | | Venda | `ve` | 126 | | Vietnamese | `vi` | 127 | | Welsh | `cy` | 128 | | Western Frisian | `fy` | 129 | | Wolof | `wo` | 130 | | Xhosa | `xh` | 131 | | Yiddish | `yi` | 132 | | Zhuang; Chuang | `za` | 133 | | Zulu | `zu` | 134 | -------------------------------------------------------------------------------- /assets/list_of_movie_genres.md: -------------------------------------------------------------------------------- 1 | | Movie Genres | 2 | |:------------------| 3 | | `action` | 4 | | `adventure` | 5 | | `animation` | 6 | | `anime` | 7 | | `comedy` | 8 | | `crime` | 9 | | `disaster` | 10 | | `documentary` | 11 | | `drama` | 12 | | `eastern` | 13 | | `family` | 14 | | `fan-film` | 15 | | `fantasy` | 16 | | `film-noir` | 17 | | `history` | 18 | | `holiday` | 19 | | `horror` | 20 | | `indie` | 21 | | `music` | 22 | | `musical` | 23 | | `mystery` | 24 | | `none` | 25 | | `road` | 26 | | `romance` | 27 | | `science-fiction` | 28 | | `short` | 29 | | `sporting-event` | 30 | | `sports` | 31 | | `superhero` | 32 | | `suspense` | 33 | | `thriller` | 34 | | `tv-movie` | 35 | | `war` | 36 | | `western` | 37 | -------------------------------------------------------------------------------- /assets/list_of_tv_show_genres.md: -------------------------------------------------------------------------------- 1 | | TV Show Genres | 2 | |:-------------------| 3 | | `action` | 4 | | `adventure` | 5 | | `animation` | 6 | | `anime` | 7 | | `biography` | 8 | | `children` | 9 | | `comedy` | 10 | | `crime` | 11 | | `disaster` | 12 | | `documentary` | 13 | | `drama` | 14 | | `eastern` | 15 | | `family` | 16 | | `fantasy` | 17 | | `game-show` | 18 | | `history` | 19 | | `holiday` | 20 | | `home-and-garden` | 21 | | `horror` | 22 | | `mini-series` | 23 | | `music` | 24 | | `musical` | 25 | | `mystery` | 26 | | `news` | 27 | | `none` | 28 | | `reality` | 29 | | `romance` | 30 | | `science-fiction` | 31 | | `short` | 32 | | `soap` | 33 | | `special-interest` | 34 | | `sporting-event` | 35 | | `sports` | 36 | | `superhero` | 37 | | `suspense` | 38 | | `talk-show` | 39 | | `thriller` | 40 | | `war` | 41 | | `western` | 42 | -------------------------------------------------------------------------------- /assets/logo.svg: -------------------------------------------------------------------------------- 1 | logo -------------------------------------------------------------------------------- /docker/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.7-alpine3.10 2 | 3 | # Arguments for build tracking 4 | ARG BRANCH= 5 | ARG COMMIT= 6 | 7 | ENV \ 8 | APP_DIR=traktarr \ 9 | BRANCH=${BRANCH} \ 10 | COMMIT=${COMMIT} \ 11 | TRAKTARR_CONFIG=/config/config.json \ 12 | TRAKTARR_CACHEFILE=/config/cache.db \ 13 | TRAKTARR_LOGFILE=/config/traktarr.log 14 | 15 | COPY . /${APP_DIR} 16 | 17 | RUN \ 18 | echo "** BRANCH: ${BRANCH} COMMIT: ${COMMIT} **" && \ 19 | echo "** Upgrade all packages **" && \ 20 | apk --no-cache -U upgrade && \ 21 | echo "** Install PIP dependencies **" && \ 22 | pip install --no-cache-dir --upgrade pip setuptools && \ 23 | pip install --no-cache-dir --upgrade -r /${APP_DIR}/requirements.txt 24 | 25 | # Change directory 26 | WORKDIR /${APP_DIR} 27 | 28 | # Config volume 29 | VOLUME /config 30 | 31 | # Entrypoint 32 | ENTRYPOINT ["python", "traktarr.py"] 33 | -------------------------------------------------------------------------------- /docker/hooks/build: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Docker cloud bug ?, working directory is not set acording to the config 4 | cd .. 5 | 6 | docker build --build-arg BRANCH=${SOURCE_BRANCH} --build-arg COMMIT=${SOURCE_COMMIT} -f ${DOCKERFILE_PATH} -t ${IMAGE_NAME} . 7 | -------------------------------------------------------------------------------- /helpers/misc.py: -------------------------------------------------------------------------------- 1 | from copy import copy 2 | 3 | from misc.log import logger 4 | 5 | log = logger.get_logger(__name__) 6 | 7 | 8 | def get_response_dict(response, key_field=None, key_value=None): 9 | found_response = None 10 | try: 11 | if isinstance(response, list): 12 | if not key_field or not key_value: 13 | found_response = response[0] 14 | else: 15 | for result in response: 16 | if isinstance(result, dict) and key_field in result and result[key_field] == key_value: 17 | found_response = result 18 | break 19 | 20 | if not found_response: 21 | log.error("Unable to find a result with key %s where the value is %s", key_field, key_value) 22 | 23 | elif isinstance(response, dict): 24 | found_response = response 25 | else: 26 | log.error("Unexpected response instance type of %s for %s", type(response).__name__, response) 27 | 28 | except Exception: 29 | log.exception("Exception determining response for %s: ", response) 30 | return found_response 31 | 32 | 33 | def backoff_handler(details): 34 | log.warning("Backing off {wait:0.1f} seconds afters {tries} tries " 35 | "calling function {target} with args {args} and kwargs " 36 | "{kwargs}".format(**details)) 37 | 38 | 39 | def dict_merge(dct, merge_dct): 40 | for k, v in merge_dct.items(): 41 | import collections 42 | 43 | if k in dct and isinstance(dct[k], dict) and isinstance(merge_dct[k], collections.Mapping): 44 | dict_merge(dct[k], merge_dct[k]) 45 | else: 46 | dct[k] = merge_dct[k] 47 | 48 | return dct 49 | 50 | 51 | def unblacklist_genres(genres, blacklisted_genres): 52 | for allow_genre in genres: 53 | if allow_genre in blacklisted_genres: 54 | blacklisted_genres.remove(allow_genre) 55 | return 56 | 57 | 58 | def allowed_genres(genres, object_type, trakt_object): 59 | allowed_object = False 60 | 61 | if len(genres) == 1 and genres[0].lower() == 'ignore': 62 | allowed_object = True 63 | else: 64 | for item in genres: 65 | if item.lower() in trakt_object[object_type]['genres']: 66 | allowed_object = True 67 | break 68 | return allowed_object 69 | 70 | 71 | def sorted_list(original_list, list_type, sort_key, reverse=True): 72 | prepared_list = copy(original_list) 73 | for item in prepared_list: 74 | if not item[list_type][sort_key]: 75 | if sort_key == 'released' or sort_key == 'first_aired': 76 | item[list_type][sort_key] = "" 77 | else: 78 | item[list_type][sort_key] = 0 79 | 80 | return sorted(prepared_list, key=lambda k: k[list_type][sort_key], reverse=reverse) 81 | 82 | 83 | # reference: https://stackoverflow.com/a/16712886 84 | def substring_after(s, delim): 85 | return s.partition(delim)[2] 86 | -------------------------------------------------------------------------------- /helpers/omdb.py: -------------------------------------------------------------------------------- 1 | from misc.log import logger 2 | import json 3 | import requests 4 | 5 | log = logger.get_logger(__name__) 6 | 7 | 8 | def get_movie_rt_score(omdb_api_key, movie_title, movie_year, movie_imdb_id): 9 | """ 10 | Lookup movie ratings via OMDb 11 | 12 | :param omdb_api_key: OMDb API Key 13 | :param movie_title: Movie Title 14 | :param movie_year: Movie Year 15 | :param movie_imdb_id: Movie IMDb ID 16 | :return: Rating score (int) or False if no rating found 17 | """ 18 | 19 | ratings_exist = False 20 | 21 | if movie_imdb_id: 22 | log.debug("Requesting info from OMDb for: \'%s (%s)\' [IMDb ID: %s]", 23 | movie_title, 24 | movie_year, 25 | movie_imdb_id) 26 | r = requests.get('http://www.omdbapi.com/?i=' + movie_imdb_id + '&apikey=' + omdb_api_key) 27 | if r.status_code == 200 and json.loads(r.text)["Response"] == 'True': 28 | log.debug("Successfully requested ratings from OMDB for \'%s (%s)\' [IMDb ID: %s]", 29 | movie_title, 30 | movie_year, 31 | movie_imdb_id) 32 | for source in json.loads(r.text)["Ratings"]: 33 | if source['Source'] == 'Rotten Tomatoes': 34 | # noinspection PyUnusedLocal 35 | ratings_exist = True 36 | log.debug("Rotten Tomatoes score for \'%s (%s)\' [IMDb ID: %s]: %s", 37 | movie_title, 38 | movie_year, 39 | movie_imdb_id, 40 | source['Value']) 41 | return int(source['Value'].split('%')[0]) 42 | if not ratings_exist: 43 | log.debug("No Rotten Tomatoes score found for: \'%s (%s)\' [IMDb ID: %s]", 44 | movie_title, 45 | movie_year, 46 | movie_imdb_id) 47 | else: 48 | log.debug("Error encountered when requesting ratings from OMDb for: \'%s (%s)\' [IMDb ID: %s]", 49 | movie_title, 50 | movie_year, 51 | movie_imdb_id) 52 | else: 53 | log.debug("Skipping OMDb ratings lookup because no IMDb ID was found for: \'%s (%s)\'", 54 | movie_title, 55 | movie_year) 56 | 57 | return False 58 | 59 | 60 | def does_movie_have_min_req_rt_score(omdb_api_key, movie_title, movie_year, movie_imdb_id, min_req_rt_score): 61 | 62 | # pull RT score 63 | movie_rt_score = get_movie_rt_score(omdb_api_key, movie_title, movie_year, movie_imdb_id) 64 | 65 | if not movie_rt_score: 66 | log.info("SKIPPING: \'%s (%s)\' because a Rotten Tomatoes score could not be found.", movie_title, 67 | movie_year) 68 | return False 69 | elif movie_rt_score < min_req_rt_score: 70 | log.info("SKIPPING: \'%s (%s)\' because its Rotten Tomatoes score of %d%% is below the required score of %d%%.", 71 | movie_title, movie_year, movie_rt_score, min_req_rt_score) 72 | return False 73 | elif movie_rt_score >= min_req_rt_score: 74 | log.info("ADDING: \'%s (%s)\' because its Rotten Tomatoes score of %d%% is above the required score of %d%%.", 75 | movie_title, movie_year, movie_rt_score, min_req_rt_score) 76 | return True 77 | -------------------------------------------------------------------------------- /helpers/parameter.py: -------------------------------------------------------------------------------- 1 | import time 2 | import re 3 | import operator 4 | 5 | 6 | def years(param_years: str, config_min_year: int, config_max_year: int): 7 | 8 | def operations(_year): 9 | _year = str(_year) 10 | current_year = time.localtime().tm_year 11 | ops = {"+": operator.add, "-": operator.sub} # https://stackoverflow.com/a/1740759 12 | 13 | if r1.match(_year): 14 | return int(_year) 15 | elif _year == '0': 16 | return current_year 17 | # add/subtract value from year 18 | elif r3.match(_year): 19 | _year_op = _year[0:1] 20 | _year_value = int(_year[1:]) 21 | return ops[_year_op](current_year, _year_value) 22 | else: 23 | return None 24 | 25 | r1 = re.compile('^[0-9]{4}$') 26 | r2 = re.compile('^[0-9]{4}-[0-9]{4}$') 27 | r3 = re.compile('^[+|-][0-9]+$') 28 | 29 | # return param_years if it is in proper format 30 | if param_years: 31 | if r1.match(param_years): 32 | return str(param_years), int(param_years), int(param_years) 33 | elif r2.match(param_years): 34 | return str(param_years), int(param_years.split('-')[0]), int(param_years.split('-')[1]) 35 | 36 | if config_min_year is not None: 37 | new_min_year = operations(config_min_year) 38 | else: 39 | new_min_year = None 40 | 41 | if config_max_year is not None: 42 | new_max_year = operations(config_max_year) 43 | else: 44 | new_max_year = None 45 | 46 | if new_min_year and new_max_year: 47 | new_years = str(new_min_year) + '-' + str(new_max_year) 48 | elif new_min_year: 49 | new_years = str(new_min_year) 50 | elif new_max_year: 51 | new_years = str(new_max_year) 52 | else: 53 | new_years = None 54 | 55 | return new_years, new_min_year, new_max_year 56 | -------------------------------------------------------------------------------- /helpers/radarr.py: -------------------------------------------------------------------------------- 1 | from misc.log import logger 2 | 3 | log = logger.get_logger(__name__) 4 | 5 | 6 | def filter_trakt_movies_list(trakt_movies, callback): 7 | new_movies_list = [] 8 | try: 9 | for tmp in trakt_movies: 10 | if 'movie' not in tmp or 'ids' not in tmp['movie'] or 'tmdb' not in tmp['movie']['ids']: 11 | log.debug("Removing movie from Trakt list as it did not have the required fields: %s", tmp) 12 | if callback: 13 | callback('movie', tmp) 14 | continue 15 | new_movies_list.append(tmp) 16 | 17 | return new_movies_list 18 | except Exception: 19 | log.exception("Exception filtering Trakt movies list: ") 20 | return None 21 | 22 | 23 | def movies_to_tmdb_dict(radarr_movies): 24 | movies = {} 25 | 26 | try: 27 | for tmp in radarr_movies: 28 | if 'tmdbId' not in tmp: 29 | log.debug("Could not handle movie: %s", tmp['title']) 30 | continue 31 | movies[tmp['tmdbId']] = tmp 32 | return movies 33 | except Exception: 34 | log.exception("Exception processing Radarr movies to TMDB dict: ") 35 | return None 36 | 37 | 38 | def remove_existing_movies_from_trakt_list(radarr_movies, trakt_movies, callback=None): 39 | new_movies_list = [] 40 | 41 | try: 42 | # turn radarr movies result into a dict with tmdb id as keys 43 | processed_movies = movies_to_tmdb_dict(radarr_movies) 44 | if not processed_movies: 45 | return None 46 | 47 | # loop list adding to movies that do not already exist 48 | for tmp in trakt_movies: 49 | # check if movie exists in processed_movies 50 | if tmp['movie']['ids']['tmdb'] in processed_movies: 51 | movie_year = str(tmp['movie']['year']) if tmp['movie']['year'] else '????' 52 | log.debug("Removing existing movie from Trakt list: \'%s (%s)\'", tmp['movie']['title'], movie_year) 53 | if callback: 54 | callback('movie', tmp) 55 | continue 56 | new_movies_list.append(tmp) 57 | 58 | removal_successful = True if len(new_movies_list) <= len(trakt_movies) else False 59 | 60 | movies_removed_count = len(trakt_movies) - len(new_movies_list) 61 | log.debug("Filtered %d movies from Trakt list that were already in Radarr.", movies_removed_count) 62 | 63 | return new_movies_list, removal_successful 64 | except Exception: 65 | log.exception("Exception removing existing movies from Trakt list: ") 66 | return None 67 | 68 | 69 | def exclusions_to_tmdb_dict(radarr_exclusions): 70 | movie_exclusions = {} 71 | 72 | try: 73 | for tmp in radarr_exclusions: 74 | if 'tmdbId' not in tmp: 75 | log.debug("Could not handle movie: %s", tmp['movieTitle']) 76 | continue 77 | movie_exclusions[tmp['tmdbId']] = tmp 78 | return movie_exclusions 79 | except Exception: 80 | log.exception("Exception processing Radarr movie exclusions to TMDB dict: ") 81 | return None 82 | 83 | 84 | def remove_excluded_movies_from_trakt_list(radarr_exclusions, trakt_movies, callback=None): 85 | new_movies_list = [] 86 | 87 | try: 88 | # turn radarr movie exclusions result into a dict with tmdb id as keys 89 | processed_movies = exclusions_to_tmdb_dict(radarr_exclusions) 90 | if not processed_movies: 91 | return None 92 | 93 | # loop list adding to movies that do not already exist 94 | for tmp in trakt_movies: 95 | # check if movie exists in processed_movies 96 | if tmp['movie']['ids']['tmdb'] in processed_movies: 97 | movie_year = str(tmp['movie']['year']) if tmp['movie']['year'] else '????' 98 | log.debug("Removing excluded movie from Trakt list: \'%s (%s)\'", tmp['movie']['title'], movie_year) 99 | if callback: 100 | callback('movie', tmp) 101 | continue 102 | new_movies_list.append(tmp) 103 | 104 | movies_removed_count = len(trakt_movies) - len(new_movies_list) 105 | log.debug("Filtered %d movies from Trakt list that were excluded in Radarr.", movies_removed_count) 106 | 107 | return new_movies_list 108 | except Exception: 109 | log.exception("Exception removing excluded movies from Trakt list: ") 110 | return None 111 | 112 | 113 | def remove_existing_and_excluded_movies_from_trakt_list(radarr_movies, radarr_exclusions, trakt_movies, callback=None): 114 | if not radarr_movies or not trakt_movies: 115 | log.error("Inappropriate parameters were supplied.") 116 | return None, False 117 | 118 | try: 119 | # clean up trakt_movies list 120 | trakt_movies = filter_trakt_movies_list(trakt_movies, callback) 121 | if not trakt_movies: 122 | return None, False 123 | 124 | # filter out existing movies in radarr from new trakt list 125 | processed_movies_list, removal_successful = remove_existing_movies_from_trakt_list(radarr_movies, trakt_movies, 126 | callback) 127 | if not processed_movies_list: 128 | return None, removal_successful 129 | 130 | # filter out radarr exclusions from the list above 131 | if radarr_exclusions: 132 | processed_movies_list = remove_excluded_movies_from_trakt_list(radarr_exclusions, processed_movies_list, 133 | callback) 134 | 135 | movies_removed_count = len(trakt_movies) - len(processed_movies_list) 136 | log.debug("Filtered a total of %d movies from the Trakt movies list.", movies_removed_count) 137 | log.debug("New Trakt movies list count: %d", len(processed_movies_list)) 138 | return processed_movies_list, removal_successful 139 | except Exception: 140 | log.exception("Exception removing existing and excluded movies from Trakt list: ") 141 | return None 142 | -------------------------------------------------------------------------------- /helpers/sonarr.py: -------------------------------------------------------------------------------- 1 | from misc.log import logger 2 | 3 | log = logger.get_logger(__name__) 4 | 5 | 6 | def series_tag_ids_list_builder(profile_tags, config_tags): 7 | try: 8 | tag_ids = [] 9 | for tag_name in config_tags: 10 | if tag_name.lower() in profile_tags: 11 | log.debug("Validated Tag: %s", tag_name) 12 | tag_ids.append(profile_tags[tag_name.lower()]) 13 | if tag_ids: 14 | return tag_ids 15 | except Exception: 16 | log.exception("Exception building Tags IDs list") 17 | return None 18 | 19 | 20 | def series_tag_names_list_builder(profile_tag_ids, chosen_tag_ids): 21 | try: 22 | if not chosen_tag_ids: 23 | return None 24 | 25 | tags = [] 26 | for tag_name, tag_id in profile_tag_ids.items(): 27 | if tag_id in chosen_tag_ids: 28 | tags.append(tag_name) 29 | if tags: 30 | return tags 31 | except Exception: 32 | log.exception("Exception building Tag Names list from Tag IDs %s: ", chosen_tag_ids) 33 | return None 34 | 35 | 36 | def filter_trakt_series_list(trakt_series, callback): 37 | new_series_list = [] 38 | try: 39 | for tmp in trakt_series: 40 | if 'show' not in tmp or 'ids' not in tmp['show'] or 'tvdb' not in tmp['show']['ids']: 41 | log.debug("Removing shows from Trakt list as it did not have the required fields: %s", tmp) 42 | if callback: 43 | callback('movie', tmp) 44 | continue 45 | new_series_list.append(tmp) 46 | 47 | return new_series_list 48 | except Exception: 49 | log.exception("Exception filtering Trakt shows list: ") 50 | return None 51 | 52 | 53 | def series_to_tvdb_dict(sonarr_series): 54 | series = {} 55 | try: 56 | for tmp in sonarr_series: 57 | if 'tvdbId' not in tmp: 58 | log.debug("Could not handle show: %s", tmp['title']) 59 | continue 60 | series[tmp['tvdbId']] = tmp 61 | return series 62 | except Exception: 63 | log.exception("Exception processing Sonarr shows to TVDB dict: ") 64 | return None 65 | 66 | 67 | def remove_existing_series_from_trakt_list(sonarr_series, trakt_series, callback=None): 68 | new_series_list = [] 69 | 70 | if not sonarr_series or not trakt_series: 71 | log.error("Inappropriate parameters were supplied.") 72 | return None 73 | 74 | try: 75 | # clean up trakt_series list 76 | trakt_series = filter_trakt_series_list(trakt_series, callback) 77 | if not trakt_series: 78 | return None 79 | 80 | # turn sonarr series result into a dict with tvdb id as keys 81 | processed_series = series_to_tvdb_dict(sonarr_series) 82 | if not processed_series: 83 | return None 84 | 85 | # loop list adding to series that do not already exist 86 | for tmp in trakt_series: 87 | # check if show exists in processed_series 88 | if tmp['show']['ids']['tvdb'] in processed_series: 89 | show_year = str(tmp['show']['year']) if tmp['show']['year'] else '????' 90 | log.debug("Removing existing show from Trakt list: \'%s (%s)\'", tmp['show']['title'], show_year) 91 | if callback: 92 | callback('show', tmp) 93 | continue 94 | 95 | new_series_list.append(tmp) 96 | 97 | series_removed = len(trakt_series) - len(new_series_list) 98 | log.debug("Filtered %d shows from Trakt list that were already in Sonarr.", series_removed) 99 | log.debug("New Trakt shows list count: %d", len(new_series_list)) 100 | return new_series_list 101 | except Exception: 102 | log.exception("Exception removing existing shows from Trakt list: ") 103 | return None 104 | -------------------------------------------------------------------------------- /helpers/str.py: -------------------------------------------------------------------------------- 1 | from misc.log import logger 2 | 3 | log = logger.get_logger(__name__) 4 | 5 | 6 | def get_year_from_timestamp(timestamp): 7 | year = 0 8 | try: 9 | if not timestamp: 10 | return 0 11 | 12 | year = timestamp[:timestamp.index('-')] 13 | except Exception: 14 | log.exception("Exception parsing year from %s: ", timestamp) 15 | return int(year) if str(year).isdigit() else 0 16 | 17 | 18 | def is_ascii(string): 19 | try: 20 | string.encode('ascii') 21 | except UnicodeEncodeError: 22 | return False 23 | except UnicodeDecodeError: 24 | return False 25 | except Exception: 26 | log.exception(u"Exception checking if %r was ascii: ", string) 27 | return False 28 | return True 29 | 30 | 31 | def ensure_endswith(data, endswith_key): 32 | if not data.strip().endswith(endswith_key): 33 | return "%s%s" % (data.strip(), endswith_key) 34 | else: 35 | return data 36 | -------------------------------------------------------------------------------- /helpers/tmdb.py: -------------------------------------------------------------------------------- 1 | from misc.log import logger 2 | import requests 3 | 4 | log = logger.get_logger(__name__) 5 | 6 | 7 | def validate_movie_tmdb_id(movie_title, movie_year, movie_tmdb_id): 8 | try: 9 | if not movie_tmdb_id or not isinstance(movie_tmdb_id, int): 10 | log.debug("SKIPPING: \'%s (%s)\' blacklisted it has an invalid TMDb ID", movie_title, movie_year) 11 | return False 12 | else: 13 | return True 14 | except Exception: 15 | log.exception("Exception validating TMDb ID for \'%s (%s)\'.", movie_title, movie_year) 16 | return False 17 | 18 | 19 | def verify_movie_exists_on_tmdb(movie_title, movie_year, movie_tmdb_id): 20 | try: 21 | headers = {"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"} 22 | req = requests.get('https://www.themoviedb.org/movie/%s' % movie_tmdb_id, headers=headers) 23 | if req.status_code == 200: 24 | log.debug("\'%s (%s)\' [TMDb ID: %s] exists on TMDb.", movie_title, movie_year, movie_tmdb_id) 25 | return True 26 | else: 27 | log.debug("SKIPPING: \'%s (%s)\' [TMDb ID: %s] because it does not exist on TMDb.", movie_title, movie_year, 28 | movie_tmdb_id) 29 | return False 30 | except Exception: 31 | log.exception("Exception verifying TMDb ID for \'%s (%s)\'.", movie_title, movie_year) 32 | return False 33 | 34 | 35 | def check_movie_tmdb_id(movie_title, movie_year, movie_tmdb_id): 36 | try: 37 | if validate_movie_tmdb_id(movie_title, movie_year, movie_tmdb_id) and \ 38 | verify_movie_exists_on_tmdb(movie_title, movie_year, movie_tmdb_id): 39 | return True 40 | except Exception: 41 | log.exception("Exception verifying/validating TMDb ID for \'%s (%s)\'.", movie_title, movie_year) 42 | return False 43 | -------------------------------------------------------------------------------- /helpers/trakt.py: -------------------------------------------------------------------------------- 1 | from helpers import str as misc_str 2 | from misc.log import logger 3 | 4 | log = logger.get_logger(__name__) 5 | 6 | 7 | def extract_list_user_and_key_from_url(list_url): 8 | try: 9 | import re 10 | list_user = re.search('\/users\/([^/]*)', list_url).group(1) 11 | list_key = re.search('\/lists\/([^/?]*)', list_url).group(1) 12 | 13 | return list_user, list_key 14 | except: 15 | log.error('The URL "%s" is not in the correct format', list_url) 16 | exit() 17 | 18 | 19 | def blacklisted_show_id(show, blacklisted_ids): 20 | blacklisted = False 21 | blacklisted_ids = sorted(map(int, blacklisted_ids)) 22 | try: 23 | if show['show']['ids']['tvdb'] in blacklisted_ids: 24 | log.debug("\'%s\' | Blacklisted IDs Check | Blacklisted because it had a blacklisted TVDB ID: %d", 25 | show['show']['title'], 26 | show['show']['ids']['tvdb']) 27 | blacklisted = True 28 | if not blacklisted: 29 | log.debug("\'%s\' | Blacklisted IDs Check | Passed.", show['show']['title']) 30 | except Exception: 31 | log.exception("Exception determining if show had a blacklisted TVDB ID %s: ", show) 32 | return blacklisted 33 | 34 | 35 | def blacklisted_show_title(show, blacklisted_keywords): 36 | blacklisted = False 37 | try: 38 | if not show['show']['title']: 39 | log.debug("Blacklisted Titles Check | Blacklisted show because it had no title: %s", show) 40 | blacklisted = True 41 | else: 42 | for keyword in blacklisted_keywords: 43 | if keyword.lower() in show['show']['title'].lower(): 44 | log.debug("\'%s\' | Blacklisted Titles Check | Blacklisted because it had the title keyword: %s", 45 | show['show']['title'], keyword) 46 | blacklisted = True 47 | break 48 | except Exception: 49 | log.exception("Exception determining if show had a blacklisted title %s: ", show) 50 | return blacklisted 51 | 52 | 53 | def blacklisted_show_year(show, earliest_year, latest_year): 54 | blacklisted = False 55 | try: 56 | year = misc_str.get_year_from_timestamp(show['show']['first_aired']) 57 | if not year: 58 | log.debug("\'%s\' | Blacklisted Years Check | Blacklisted because it had no " 59 | "first-aired date specified.", 60 | show['show']['title']) 61 | blacklisted = True 62 | else: 63 | if year < earliest_year or year > latest_year: 64 | log.debug("\'%s\' | Blacklisted Years Check | Blacklisted because it first aired in: %d", 65 | show['show']['title'], year) 66 | blacklisted = True 67 | if not blacklisted: 68 | log.debug("\'%s\' | Blacklisted Years Check | Passed.", show['show']['title']) 69 | except Exception: 70 | log.exception("Exception determining if show is within min_year and max_year range %s:", show) 71 | return blacklisted 72 | 73 | 74 | def blacklisted_show_network(show, networks): 75 | blacklisted = False 76 | try: 77 | if not show['show']['network']: 78 | log.debug("\'%s\' | Blacklisted Networks Check | Blacklisted because it had no network specified.", 79 | show['show']['title']) 80 | blacklisted = True 81 | else: 82 | for network in networks: 83 | if network.lower() in show['show']['network'].lower(): 84 | log.debug("\'%s\' | Blacklisted Networks Check | Blacklisted because it's from the network: %s", 85 | show['show']['title'], show['show']['network']) 86 | blacklisted = True 87 | break 88 | if not blacklisted: 89 | log.debug("\'%s\' | Blacklisted Networks Check | Passed.", show['show']['title']) 90 | except Exception: 91 | log.exception("Exception determining if show is from a blacklisted network %s: ", show) 92 | return blacklisted 93 | 94 | 95 | def blacklisted_show_country(show, allowed_countries): 96 | blacklisted = False 97 | try: 98 | # ["ignore"] - add show item even if it is missing a country 99 | if any('ignore' in s.lower() for s in allowed_countries): 100 | log.debug("\'%s\' | Blacklisted Countries Check | Ignored.", show['show']['title']) 101 | # List provided - skip adding show item because it is missing a country 102 | elif not show['show']['country']: 103 | log.debug("\'%s\' | Blacklisted Countries Check | Blacklisted because it had no country specified.", 104 | show['show']['title']) 105 | blacklisted = True 106 | # [] - add show item from any valid country 107 | elif not allowed_countries: 108 | log.debug("\'%s\' | Blacklisted Countries Check | Skipped.", 109 | show['show']['title']) 110 | # List provided - skip adding show item if the country is blacklisted 111 | elif not any(show['show']['country'].lower() in s.lower() for s in allowed_countries): 112 | log.debug("\'%s\' | Blacklisted Countries Check | Blacklisted because it's from the country: %s", 113 | show['show']['title'], 114 | show['show']['country'].upper()) 115 | blacklisted = True 116 | if not blacklisted: 117 | log.debug("\'%s\' | Blacklisted Countries Check | Passed.", show['show']['title']) 118 | except Exception: 119 | log.exception("Exception determining if show was from an allowed country %s: ", show) 120 | return blacklisted 121 | 122 | 123 | def blacklisted_show_language(show, allowed_languages): 124 | blacklisted = False 125 | try: 126 | # ["ignore"] - add show item even if it is missing a language 127 | if any('ignore' in s.lower() for s in allowed_languages): 128 | log.debug("\'%s\' | Blacklisted Languages Check | Ignored.", show['show']['title']) 129 | # List provided - skip adding show item because it is missing a language 130 | elif not show['show']['language']: 131 | log.debug("\'%s\' | Blacklisted Languages Check | Blacklisted because it had no language specified.", 132 | show['show']['title']) 133 | blacklisted = True 134 | # [] - add show item from any valid language 135 | elif not allowed_languages: 136 | log.debug("\'%s\' | Blacklisted Languages Check | Skipped.", 137 | show['show']['title']) 138 | # List provided - skip adding show item if the language is blacklisted 139 | elif not any(show['show']['language'].lower() in c.lower() for c in allowed_languages): 140 | log.debug("\'%s\' | Blacklisted Languages Check | Blacklisted because it's in the language: %s", 141 | show['show']['title'], show['show']['language'].upper()) 142 | blacklisted = True 143 | if not blacklisted: 144 | log.debug("\'%s\' | Blacklisted Languages Check | Passed.", show['show']['title']) 145 | except Exception: 146 | log.exception("Exception determining what language the show was in %s: ", show) 147 | return blacklisted 148 | 149 | 150 | def blacklisted_show_genre(show, genres): 151 | blacklisted = False 152 | try: 153 | # ["ignore"] - add show item even if it is missing a genre 154 | if any('ignore' in s.lower() for s in genres): 155 | log.debug("\'%s\' | Blacklisted Genres Check | Ignored.", show['show']['title']) 156 | elif not show['show']['genres']: 157 | log.debug("\'%s\' | Blacklisted Genres Check | Blacklisted because it had no genre specified.", 158 | show['show']['title']) 159 | blacklisted = True 160 | # [] - add show item with any valid genre 161 | elif not genres: 162 | log.debug("\'%s\' | Blacklisted Genres Check | Skipped.", 163 | show['show']['title']) 164 | # List provided - skip adding show item if the genre is blacklisted 165 | else: 166 | for genre in genres: 167 | if genre.lower() in show['show']['genres']: 168 | log.debug("\'%s\' | Blacklisted Genres Check | Blacklisted because it was from the genre: %s", 169 | show['show']['title'], genre.title()) 170 | blacklisted = True 171 | break 172 | if not blacklisted: 173 | log.debug("\'%s\' | Blacklisted Genres Check | Passed.", show['show']['title']) 174 | except Exception: 175 | log.exception("Exception determining if show has a blacklisted genre %s: ", show) 176 | return blacklisted 177 | 178 | 179 | def blacklisted_show_runtime(show, lowest_runtime): 180 | blacklisted = False 181 | try: 182 | if not show['show']['runtime'] or not isinstance(show['show']['runtime'], int): 183 | log.debug("\'%s\' | Blacklisted Runtime Check | Blacklisted because it had no runtime specified.", 184 | show['show']['title']) 185 | blacklisted = True 186 | elif int(show['show']['runtime']) < lowest_runtime: 187 | log.debug("\'%s\' | Blacklisted Runtime Check | Blacklisted because it had the runtime of: %d min.", 188 | show['show']['title'], show['show']['runtime']) 189 | blacklisted = True 190 | if not blacklisted: 191 | log.debug("\'%s\' | Blacklisted Runtime Check | Passed.", show['show']['title']) 192 | except Exception: 193 | log.exception("Exception determining if show had sufficient runtime %s: ", show) 194 | return blacklisted 195 | 196 | 197 | def is_show_blacklisted(show, blacklist_settings, ignore_blacklist, callback=None): 198 | if ignore_blacklist: 199 | return False 200 | 201 | blacklisted = False 202 | try: 203 | if blacklisted_show_id(show, blacklist_settings.blacklisted_tvdb_ids): 204 | blacklisted = True 205 | if blacklisted_show_title(show, blacklist_settings.blacklisted_title_keywords): 206 | blacklisted = True 207 | if blacklisted_show_year(show, blacklist_settings.blacklisted_min_year, 208 | blacklist_settings.blacklisted_max_year): 209 | blacklisted = True 210 | if blacklisted_show_network(show, blacklist_settings.blacklisted_networks): 211 | blacklisted = True 212 | if blacklisted_show_country(show, blacklist_settings.allowed_countries): 213 | blacklisted = True 214 | if blacklisted_show_language(show, blacklist_settings.allowed_languages): 215 | blacklisted = True 216 | if blacklisted_show_genre(show, blacklist_settings.blacklisted_genres): 217 | blacklisted = True 218 | if blacklisted_show_runtime(show, blacklist_settings.blacklisted_min_runtime): 219 | blacklisted = True 220 | if blacklisted and callback: 221 | callback('show', show) 222 | except Exception: 223 | log.exception("Exception determining if show was blacklisted %s: ", show) 224 | return blacklisted 225 | 226 | 227 | def blacklisted_movie_id(movie, blacklisted_ids): 228 | blacklisted = False 229 | blacklisted_ids = sorted(map(int, blacklisted_ids)) 230 | try: 231 | if movie['movie']['ids']['tmdb'] in blacklisted_ids: 232 | log.debug("\'%s\' | Blacklisted IDs Check | Blacklisted because it had a blacklisted TMDb ID: %d", 233 | movie['movie']['title'], movie['movie']['ids']['tmdb']) 234 | blacklisted = True 235 | if not blacklisted: 236 | log.debug("\'%s\' | Blacklisted IDs Check | Passed.", movie['movie']['title']) 237 | except Exception: 238 | log.exception("Exception determining if movie had a blacklisted TMDb ID %s: ", movie) 239 | return blacklisted 240 | 241 | 242 | def blacklisted_movie_title(movie, blacklisted_keywords): 243 | blacklisted = False 244 | try: 245 | if not movie['movie']['title']: 246 | log.debug("Blacklisted Titles Check | Blacklisted movie because it had no title: %s", movie) 247 | blacklisted = True 248 | else: 249 | for keyword in blacklisted_keywords: 250 | if keyword.lower() in movie['movie']['title'].lower(): 251 | log.debug("\'%s\' | Blacklisted Titles Check | Blacklisted because it had the title keyword: %s", 252 | movie['movie']['title'], keyword) 253 | blacklisted = True 254 | break 255 | if not blacklisted: 256 | log.debug("\'%s\' | Blacklisted Titles Check | Passed.", movie['movie']['title']) 257 | except Exception: 258 | log.exception("Exception determining if movie had a blacklisted title %s: ", movie) 259 | return blacklisted 260 | 261 | 262 | def blacklisted_movie_year(movie, earliest_year, latest_year): 263 | blacklisted = False 264 | try: 265 | year = movie['movie']['year'] 266 | if year is None or not isinstance(year, int): 267 | log.debug("\'%s\' | Blacklisted Years Check | Blacklisted because it had no year specified.", 268 | movie['movie']['title']) 269 | blacklisted = True 270 | else: 271 | if int(year) < earliest_year or int(year) > latest_year: 272 | log.debug("\'%s\' | Blacklisted Years Check | Blacklisted because its year is: %d", 273 | movie['movie']['title'], int(year)) 274 | blacklisted = True 275 | if not blacklisted: 276 | log.debug("\'%s\' | Blacklisted Years Check | Passed.", movie['movie']['title']) 277 | except Exception: 278 | log.exception("Exception determining if movie is within min_year and max_year ranger %s:", movie) 279 | return blacklisted 280 | 281 | 282 | def blacklisted_movie_country(movie, allowed_countries): 283 | blacklisted = False 284 | try: 285 | # ["ignore"] - add movie item even if it is missing a country 286 | if any('ignore' in s.lower() for s in allowed_countries): 287 | log.debug("\'%s\' | Blacklisted Countries Check | Ignored.", 288 | movie['movie']['title']) 289 | # List provided - skip adding movie item because it is missing a country 290 | elif not movie['movie']['country']: 291 | log.debug("\'%s\' | Blacklisted Countries Check | Blacklisted because it had no country specified.", 292 | movie['movie']['title']) 293 | blacklisted = True 294 | # [] - add movie item with from any valid country 295 | elif not allowed_countries: 296 | log.debug("\'%s\' | Blacklisted Countries Check | Skipped.", 297 | movie['movie']['title']) 298 | # List provided - skip adding movie item if the country is blacklisted 299 | elif not any(movie['movie']['country'].lower() in s.lower() for s in allowed_countries): 300 | log.debug("\'%s\' | Blacklisted Countries Check | Blacklisted because it's from the country: %s", 301 | movie['movie']['title'], movie['movie']['country'].upper()) 302 | blacklisted = True 303 | if not blacklisted: 304 | log.debug("\'%s\' | Blacklisted Countries Check | Passed.", movie['movie']['title']) 305 | except Exception: 306 | log.exception("Exception determining if movie was from an allowed country %s: ", movie) 307 | return blacklisted 308 | 309 | 310 | def blacklisted_movie_language(movie, allowed_languages): 311 | blacklisted = False 312 | try: 313 | # ["ignore"] - add movie item even if it is missing a language 314 | if any('ignore' in s.lower() for s in allowed_languages): 315 | log.debug("\'%s\' | Blacklisted Languages Check | Ignored.", 316 | movie['movie']['title']) 317 | # List provided - skip adding movie item because it is missing a language 318 | elif not movie['movie']['language']: 319 | log.debug("\'%s\' | Blacklisted Languages Check | Blacklisted because it had no language specified.", 320 | movie['movie']['title']) 321 | blacklisted = True 322 | # [] - add movie item from any valid language 323 | elif not allowed_languages: 324 | log.debug("\'%s\' | Blacklisted Languages Check | Skipped.", 325 | movie['movie']['title']) 326 | # List provided - skip adding movie item if the language is blacklisted 327 | elif not any(movie['movie']['language'].lower() in s.lower() for s in allowed_languages): 328 | log.debug("\'%s\' | Blacklisted Languages Check | Blacklisted because it's in the language: %s", 329 | movie['movie']['title'], movie['movie']['language'].upper()) 330 | blacklisted = True 331 | if not blacklisted: 332 | log.debug("\'%s\' | Blacklisted Languages Check | Passed.", movie['movie']['title']) 333 | except Exception: 334 | log.exception("Exception determining what language the movie was %s: ", movie) 335 | return blacklisted 336 | 337 | 338 | def blacklisted_movie_genre(movie, genres): 339 | blacklisted = False 340 | try: 341 | # ["ignore"] - add movie item even if it is missing a genre 342 | if any('ignore' in s.lower() for s in genres): 343 | log.debug("\'%s\' | Blacklisted Genres Check | Ignored.", movie['movie']['title']) 344 | elif not movie['movie']['genres']: 345 | log.debug("\'%s\' | Blacklisted Genres Check | Blacklisted because it had no genre specified.", 346 | movie['movie']['title']) 347 | blacklisted = True 348 | # [] - add movie item with any valid genre 349 | elif not genres: 350 | log.debug("\'%s\' | Blacklisted Genres Check | Skipped.", 351 | movie['movie']['title']) 352 | # List provided - skip adding movie item if the genre is blacklisted 353 | else: 354 | for genre in genres: 355 | if genre.lower() in movie['movie']['genres']: 356 | log.debug("\'%s\' | Blacklisted Genres Check | Blacklisted because it was from the genre: %s", 357 | movie['movie']['title'], genre.title()) 358 | blacklisted = True 359 | break 360 | if not blacklisted: 361 | log.debug("\'%s\' | Blacklisted Genres Check | Passed.", movie['movie']['title']) 362 | except Exception: 363 | log.exception("Exception determining if movie has a blacklisted genre %s: ", movie) 364 | return blacklisted 365 | 366 | 367 | def blacklisted_movie_runtime(movie, lowest_runtime): 368 | blacklisted = False 369 | try: 370 | if not movie['movie']['runtime'] or not isinstance(movie['movie']['runtime'], int): 371 | log.debug("\'%s\' | Blacklisted Runtime Check | Blacklisted because it had no runtime specified.", 372 | movie['movie']['title']) 373 | blacklisted = True 374 | elif int(movie['movie']['runtime']) < lowest_runtime: 375 | log.debug("\'%s\' | Blacklisted Runtime Check | Blacklisted because it had the runtime of: %d min.", 376 | movie['movie']['title'], movie['movie']['runtime']) 377 | blacklisted = True 378 | if not blacklisted: 379 | log.debug("\'%s\' | Blacklisted Runtime Check | Passed.", movie['movie']['title']) 380 | except Exception: 381 | log.exception("Exception determining if movie had sufficient runtime %s: ", movie) 382 | return blacklisted 383 | 384 | 385 | def is_movie_blacklisted(movie, blacklist_settings, ignore_blacklist, callback=None): 386 | if ignore_blacklist: 387 | return False 388 | 389 | blacklisted = False 390 | try: 391 | if blacklisted_movie_id(movie, blacklist_settings.blacklisted_tmdb_ids): 392 | blacklisted = True 393 | if blacklisted_movie_title(movie, blacklist_settings.blacklisted_title_keywords): 394 | blacklisted = True 395 | if blacklisted_movie_year(movie, blacklist_settings.blacklisted_min_year, 396 | blacklist_settings.blacklisted_max_year): 397 | blacklisted = True 398 | if blacklisted_movie_country(movie, blacklist_settings.allowed_countries): 399 | blacklisted = True 400 | if blacklisted_movie_language(movie, blacklist_settings.allowed_languages): 401 | blacklisted = True 402 | if blacklisted_movie_genre(movie, blacklist_settings.blacklisted_genres): 403 | blacklisted = True 404 | if blacklisted_movie_runtime(movie, blacklist_settings.blacklisted_min_runtime): 405 | blacklisted = True 406 | if blacklisted and callback: 407 | callback('movie', movie) 408 | except Exception: 409 | log.exception("Exception determining if movie was blacklisted %s: ", movie) 410 | return blacklisted 411 | -------------------------------------------------------------------------------- /helpers/tvdb.py: -------------------------------------------------------------------------------- 1 | from misc.log import logger 2 | import requests 3 | 4 | log = logger.get_logger(__name__) 5 | 6 | 7 | def validate_series_tvdb_id(series_title, series_year, series_tvdb_id): 8 | try: 9 | if not series_tvdb_id or not isinstance(series_tvdb_id, int): 10 | log.debug("SKIPPING: \'%s (%s)\' blacklisted it has an invalid TVDB ID", series_title, series_year) 11 | return False 12 | else: 13 | return True 14 | except Exception: 15 | log.exception("Exception validating TVDB ID for \'%s (%s)\'.", series_title, series_year) 16 | return False 17 | 18 | 19 | def verify_series_exists_on_tvdb(series_title, series_year, series_tvdb_id): 20 | try: 21 | req = requests.get('https://www.thetvdb.com/dereferrer/series/%s' % series_tvdb_id, allow_redirects=False) 22 | if 'This record has either been deleted or has never existed.' not in req.text: 23 | log.debug("\'%s (%s)\' [TVDB ID: %s] exists on TVDB.", series_title, series_year, series_tvdb_id) 24 | return True 25 | else: 26 | log.debug("SKIPPING: \'%s (%s)\' [TVDB ID: %s] because it does not exist on TVDB.", series_title, 27 | series_year, series_tvdb_id) 28 | return False 29 | except Exception: 30 | log.exception("Exception verifying TVDB ID for \'%s (%s)\'.", series_title, series_year) 31 | return False 32 | 33 | 34 | def check_series_tvdb_id(series_title, series_year, series_tvdb_id): 35 | try: 36 | if validate_series_tvdb_id(series_title, series_year, series_tvdb_id) and \ 37 | verify_series_exists_on_tvdb(series_title, series_year, series_tvdb_id): 38 | return True 39 | except Exception: 40 | log.exception("Exception verifying/validating TVDB ID for \'%s (%s)\'.", series_title, series_year) 41 | return False 42 | -------------------------------------------------------------------------------- /media/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/l3uddz/traktarr/52d71964a2cd6504adda6e2b2d5cdfc68cc794c8/media/__init__.py -------------------------------------------------------------------------------- /media/pvr.py: -------------------------------------------------------------------------------- 1 | import os.path 2 | from abc import ABC, abstractmethod 3 | from distutils.version import LooseVersion as Version 4 | 5 | import backoff 6 | import requests 7 | 8 | from helpers.misc import backoff_handler 9 | from helpers import str as misc_str 10 | from helpers import misc 11 | from misc.log import logger 12 | 13 | log = logger.get_logger(__name__) 14 | 15 | 16 | class PVR(ABC): 17 | def __init__(self, server_url, api_key): 18 | self.server_url = server_url 19 | self.api_key = api_key 20 | self.headers = { 21 | 'Content-Type': 'application/json', 22 | 'X-Api-Key': self.api_key, 23 | } 24 | 25 | def validate_api_key(self): 26 | try: 27 | # request system status to validate api_key 28 | req = requests.get( 29 | os.path.join(misc_str.ensure_endswith(self.server_url, "/"), 'api/v3/system/status'), 30 | headers=self.headers, 31 | timeout=60, 32 | allow_redirects=False 33 | ) 34 | log.debug("Request Response: %d", req.status_code) 35 | 36 | if req.status_code == 200 and 'version' in req.json(): 37 | return True 38 | return False 39 | except Exception: 40 | log.exception("Exception validating api_key: ") 41 | return False 42 | 43 | @abstractmethod 44 | def get_objects(self): 45 | pass 46 | 47 | @backoff.on_predicate(backoff.expo, lambda x: x is None, max_tries=4, on_backoff=backoff_handler) 48 | def _get_objects(self, endpoint): 49 | try: 50 | # make request 51 | req = requests.get( 52 | os.path.join(misc_str.ensure_endswith(self.server_url, "/"), endpoint), 53 | headers=self.headers, 54 | timeout=60, 55 | allow_redirects=False 56 | ) 57 | log.debug("Request URL: %s", req.url) 58 | log.debug("Request Response: %d", req.status_code) 59 | 60 | if req.status_code == 200: 61 | resp_json = req.json() 62 | log.debug("Found %d objects", len(resp_json)) 63 | return resp_json 64 | else: 65 | log.error("Failed to retrieve all objects, request response: %d", req.status_code) 66 | except Exception: 67 | log.exception("Exception retrieving objects: ") 68 | return None 69 | 70 | @backoff.on_predicate(backoff.expo, lambda x: x is None, max_tries=4, on_backoff=backoff_handler) 71 | def get_quality_profile_id(self, profile_name): 72 | try: 73 | # make request 74 | req = requests.get( 75 | os.path.join(misc_str.ensure_endswith(self.server_url, "/"), 'api/v3/qualityProfile'), 76 | headers=self.headers, 77 | timeout=60, 78 | allow_redirects=False 79 | ) 80 | log.debug("Request URL: %s", req.url) 81 | log.debug("Request Response: %d", req.status_code) 82 | 83 | if req.status_code == 200: 84 | resp_json = req.json() 85 | for profile in resp_json: 86 | if profile['name'].lower() == profile_name.lower(): 87 | log.debug("Found Quality Profile ID for \'%s\': %d", profile_name, profile['id']) 88 | return profile['id'] 89 | log.debug("Profile \'%s\' with ID \'%d\' did not match Quality Profile \'%s\'", profile['name'], 90 | profile['id'], profile_name) 91 | else: 92 | log.error("Failed to retrieve all quality profiles, request response: %d", req.status_code) 93 | except Exception: 94 | log.exception("Exception retrieving ID of quality profile %s: ", profile_name) 95 | return None 96 | 97 | @backoff.on_exception(backoff.expo, requests.exceptions.RequestException, max_tries=4, on_backoff=backoff_handler) 98 | def get_language_profile_id(self, language_name): 99 | try: 100 | # check if sonarr is v3 101 | 102 | # make request 103 | ver_req = requests.get( 104 | os.path.join(misc_str.ensure_endswith(self.server_url, "/"), 'api/system/status'), 105 | headers=self.headers, 106 | timeout=60, 107 | allow_redirects=False 108 | ) 109 | 110 | if ver_req.status_code == 200: 111 | ver_resp_json = ver_req.json() 112 | if not Version(ver_resp_json['version']) > Version('3'): 113 | log.debug("Skipping Language Profile lookup because Sonarr version is \'%s\'.", 114 | ver_resp_json['version']) 115 | return None 116 | 117 | except Exception: 118 | log.exception("Exception verifying Sonarr version.") 119 | return None 120 | 121 | try: 122 | # make request 123 | req = requests.get( 124 | os.path.join(misc_str.ensure_endswith(self.server_url, "/"), 'api/v3/languageprofile'), 125 | headers=self.headers, 126 | timeout=60, 127 | allow_redirects=False 128 | ) 129 | log.debug("Request URL: %s", req.url) 130 | log.debug("Request Response: %d", req.status_code) 131 | 132 | if req.status_code == 200: 133 | resp_json = req.json() 134 | for profile in resp_json: 135 | if profile['name'].lower() == language_name.lower(): 136 | log.debug("Found Language Profile ID for \'%s\': %d", language_name, profile['id']) 137 | return profile['id'] 138 | log.debug("Profile \'%s\' with ID \'%d\' did not match Language Profile \'%s\'", profile['name'], 139 | profile['id'], language_name) 140 | else: 141 | log.error("Failed to retrieve all language profiles, request response: %d", req.status_code) 142 | except Exception: 143 | log.exception("Exception retrieving ID of language profile %s: ", language_name) 144 | return None 145 | 146 | def _prepare_add_object_payload(self, title, title_slug, quality_profile_id, root_folder): 147 | return { 148 | 'title': title, 149 | 'titleSlug': title_slug, 150 | 'qualityProfileId': quality_profile_id, 151 | 'images': [], 152 | 'monitored': True, 153 | 'rootFolderPath': root_folder, 154 | 'addOptions': { 155 | 'ignoreEpisodesWithFiles': False, 156 | 'ignoreEpisodesWithoutFiles': False, 157 | } 158 | } 159 | 160 | @backoff.on_predicate(backoff.expo, lambda x: x is None, max_tries=4, on_backoff=backoff_handler) 161 | def _add_object(self, endpoint, payload, identifier_field, identifier): 162 | try: 163 | # make request 164 | req = requests.post( 165 | os.path.join(misc_str.ensure_endswith(self.server_url, "/"), endpoint), 166 | headers=self.headers, 167 | json=payload, 168 | timeout=60, 169 | allow_redirects=False 170 | ) 171 | log.debug("Request URL: %s", req.url) 172 | log.debug("Request Payload: %s", payload) 173 | log.debug("Request Response Code: %d", req.status_code) 174 | log.debug("Request Response Text:\n%s", req.text) 175 | 176 | response_json = None 177 | if 'json' in req.headers['Content-Type'].lower(): 178 | response_json = misc.get_response_dict(req.json(), identifier_field, identifier) 179 | 180 | if ( 181 | req.status_code in [201, 200] 182 | and (response_json and identifier_field in response_json) 183 | and response_json[identifier_field] == identifier 184 | ): 185 | log.debug("Successfully added: \'%s [%d]\'", payload['title'], identifier) 186 | return True 187 | elif response_json and ('errorMessage' in response_json or 'message' in response_json): 188 | message = response_json['errorMessage'] if 'errorMessage' in response_json else response_json['message'] 189 | 190 | log.error("Failed to add \'%s [%d]\' - status_code: %d, reason: %s", payload['title'], identifier, 191 | req.status_code, message) 192 | return False 193 | else: 194 | log.error("Failed to add \'%s [%d]\', unexpected response:\n%s", payload['title'], identifier, req.text) 195 | return False 196 | except Exception: 197 | log.exception("Exception adding \'%s [%d]\': ", payload['title'], identifier) 198 | return None 199 | -------------------------------------------------------------------------------- /media/radarr.py: -------------------------------------------------------------------------------- 1 | import backoff 2 | 3 | from helpers.misc import backoff_handler, dict_merge 4 | from media.pvr import PVR 5 | from misc.log import logger 6 | 7 | log = logger.get_logger(__name__) 8 | 9 | 10 | class Radarr(PVR): 11 | def get_objects(self): 12 | return self._get_objects('api/v3/movie') 13 | 14 | def get_exclusions(self): 15 | return self._get_objects('api/v3/exclusions') 16 | 17 | @backoff.on_predicate(backoff.expo, lambda x: x is None, max_tries=4, on_backoff=backoff_handler) 18 | def add_movie(self, movie_tmdb_id, movie_title, movie_year, movie_title_slug, quality_profile_id, root_folder, 19 | min_availability_temp, search_missing=False): 20 | payload = self._prepare_add_object_payload(movie_title, movie_title_slug, quality_profile_id, root_folder) 21 | 22 | # replace radarr minimum_availability if supplied 23 | if min_availability_temp == 'announced': 24 | minimum_availability = 'announced' 25 | elif min_availability_temp == 'in_cinemas': 26 | minimum_availability = 'inCinemas' 27 | else: 28 | minimum_availability = 'released' 29 | 30 | payload = dict_merge(payload, { 31 | 'tmdbId': movie_tmdb_id, 32 | 'year': int(movie_year), 33 | 'minimumAvailability': minimum_availability, 34 | 'addOptions': { 35 | 'searchForMovie': search_missing 36 | } 37 | }) 38 | 39 | return self._add_object('api/v3/movie', payload, identifier_field='tmdbId', identifier=movie_tmdb_id) 40 | -------------------------------------------------------------------------------- /media/sonarr.py: -------------------------------------------------------------------------------- 1 | import os.path 2 | 3 | import backoff 4 | import requests 5 | from helpers.misc import backoff_handler, dict_merge 6 | 7 | from helpers import str as misc_str 8 | from media.pvr import PVR 9 | from misc.log import logger 10 | 11 | log = logger.get_logger(__name__) 12 | 13 | 14 | class Sonarr(PVR): 15 | def get_objects(self): 16 | return self._get_objects('api/v3/series') 17 | 18 | @backoff.on_predicate(backoff.expo, lambda x: x is None, max_tries=4, on_backoff=backoff_handler) 19 | def get_tags(self): 20 | tags = {} 21 | try: 22 | # make request 23 | req = requests.get( 24 | os.path.join(misc_str.ensure_endswith(self.server_url, "/"), 'api/v3/tag'), 25 | headers=self.headers, 26 | timeout=60, 27 | allow_redirects=False 28 | ) 29 | log.debug("Request URL: %s", req.url) 30 | log.debug("Request Response: %d", req.status_code) 31 | 32 | if req.status_code == 200: 33 | resp_json = req.json() 34 | log.debug("Found Sonarr Tags: %d", len(resp_json)) 35 | for tag in resp_json: 36 | tags[tag['label']] = tag['id'] 37 | return tags 38 | else: 39 | log.error("Failed to retrieve all tags, request response: %d", req.status_code) 40 | except Exception: 41 | log.exception("Exception retrieving tags: ") 42 | return None 43 | 44 | @backoff.on_predicate(backoff.expo, lambda x: x is None, max_tries=4, on_backoff=backoff_handler) 45 | def add_series(self, series_tvdb_id, series_title, series_title_slug, quality_profile_id, language_profile_id, 46 | root_folder, season_folder=True, tag_ids=None, search_missing=False, series_type='standard'): 47 | payload = self._prepare_add_object_payload(series_title, series_title_slug, quality_profile_id, root_folder) 48 | 49 | payload = dict_merge(payload, { 50 | 'tvdbId': series_tvdb_id, 51 | 'tags': [] if not tag_ids or not isinstance(tag_ids, list) else tag_ids, 52 | 'seasons': [], 53 | 'seasonFolder': season_folder, 54 | 'seriesType': series_type, 55 | 'languageProfileId': language_profile_id, 56 | 'addOptions': { 57 | 'searchForMissingEpisodes': search_missing 58 | } 59 | }) 60 | 61 | endpoint = 'api/v3/series' 62 | 63 | return self._add_object(endpoint, payload, identifier_field='tvdbId', identifier=series_tvdb_id) 64 | -------------------------------------------------------------------------------- /media/trakt.py: -------------------------------------------------------------------------------- 1 | import json 2 | import time 3 | 4 | import backoff 5 | import requests 6 | from cashier import cache 7 | 8 | from helpers.misc import backoff_handler, dict_merge 9 | from helpers.trakt import extract_list_user_and_key_from_url 10 | from misc.log import logger 11 | from misc.config import Config 12 | 13 | log = logger.get_logger(__name__) 14 | cachefile = Config().cachefile 15 | 16 | 17 | class Trakt: 18 | non_user_lists = ['anticipated', 'trending', 'popular', 'boxoffice', 'watched', 'played'] 19 | 20 | def __init__(self, cfg): 21 | self.cfg = cfg 22 | 23 | ############################################################ 24 | # Requests 25 | ############################################################ 26 | 27 | def _make_request(self, url, payload=None, authenticate_user=None, request_type='get'): 28 | headers, authenticate_user = self._headers(authenticate_user) 29 | headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' \ 30 | '(KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36' 31 | 32 | if payload is None: 33 | payload = {} 34 | 35 | if authenticate_user: 36 | url = url.replace('{authenticate_user}', authenticate_user) 37 | 38 | # make request 39 | resp_data = '' 40 | if request_type == 'delete': 41 | with requests.delete(url, headers=headers, params=payload, timeout=30, stream=True) as req: 42 | for chunk in req.iter_content(chunk_size=250000, decode_unicode=True): 43 | if chunk: 44 | resp_data += chunk 45 | else: 46 | with requests.get(url, headers=headers, params=payload, timeout=30, stream=True) as req: 47 | for chunk in req.iter_content(chunk_size=250000, decode_unicode=True): 48 | if chunk: 49 | resp_data += chunk 50 | 51 | log.debug("Request URL: %s", req.url) 52 | log.debug("Request Payload: %s", payload) 53 | log.debug("Request User: %s", authenticate_user) 54 | log.debug("Response Code: %d", req.status_code) 55 | return req, resp_data 56 | 57 | @backoff.on_predicate(backoff.expo, lambda x: x is None, max_tries=4, on_backoff=backoff_handler) 58 | def _make_item_request(self, url, object_name, payload=None): 59 | 60 | if payload is None: 61 | payload = {} 62 | 63 | payload = dict_merge(payload, {'extended': 'full'}) 64 | 65 | try: 66 | req, resp_data = self._make_request(url, payload) 67 | 68 | if req.status_code == 200 and len(resp_data): 69 | return json.loads(resp_data) 70 | elif req.status_code == 401: 71 | log.error("The authentication to Trakt is revoked. Please re-authenticate.") 72 | exit() 73 | else: 74 | log.error("Failed to retrieve %s, request response: %d", object_name, req.status_code) 75 | return None 76 | except Exception: 77 | log.exception("Exception retrieving %s: ", object_name) 78 | return None 79 | 80 | @backoff.on_predicate(backoff.expo, lambda x: x is None, max_tries=6, on_backoff=backoff_handler) 81 | def _make_items_request( 82 | self, 83 | url, 84 | limit, 85 | type_name, 86 | object_name, 87 | authenticate_user=None, 88 | payload=None, 89 | sleep_between=5, 90 | years=None, 91 | countries=None, 92 | languages=None, 93 | genres=None, 94 | runtimes=None, 95 | include_non_acting_roles=False, 96 | ): 97 | 98 | # default payload 99 | if payload is None: 100 | payload = {} 101 | 102 | payload = dict_merge(payload, { 103 | 'extended': 'full', 104 | 'limit': limit, 105 | 'page': 1, 106 | }) 107 | 108 | # languages list 109 | if languages: 110 | payload['languages'] = ','.join(languages).lower() 111 | 112 | # years range 113 | if years: 114 | payload['years'] = years 115 | 116 | # countries list 117 | if countries: 118 | payload['countries'] = ','.join(countries).lower() 119 | 120 | # genres list 121 | if genres: 122 | payload['genres'] = ','.join(genres).lower() 123 | 124 | # runtimes range 125 | if runtimes: 126 | payload['runtimes'] = runtimes 127 | 128 | processed = [] 129 | 130 | if authenticate_user: 131 | type_name = type_name.replace('{authenticate_user}', self._user_used_for_authentication(authenticate_user)) 132 | 133 | try: 134 | resp_data = '' 135 | max_attempts = 6 136 | while True: 137 | attempts = 0 138 | retrieve_error = False 139 | while attempts <= max_attempts: 140 | try: 141 | req, resp_data = self._make_request(url, payload, authenticate_user) 142 | if resp_data is not None: 143 | retrieve_error = False 144 | break 145 | else: 146 | log.warning("Failed to retrieve valid response for Trakt %s %s from _make_item_request", 147 | type_name, object_name) 148 | 149 | except Exception: 150 | log.exception("Exception retrieving %s %s in _make_item_request: ", type_name, object_name) 151 | retrieve_error = True 152 | 153 | attempts += 1 154 | log.info("Sleeping for %d seconds before making attempt %d/%d", 3 * attempts, attempts + 1, 155 | max_attempts) 156 | time.sleep(3 * attempts) 157 | 158 | if retrieve_error or not resp_data or not len(resp_data): 159 | log.error("Failed retrieving %s %s from _make_item_request %d times, aborting...", type_name, 160 | object_name, attempts) 161 | return None 162 | 163 | current_page = payload['page'] 164 | total_pages = 0 if 'X-Pagination-Page-Count' not in req.headers else int( 165 | req.headers['X-Pagination-Page-Count']) 166 | 167 | log.debug("Response Page: %d of %d", current_page, total_pages) 168 | 169 | if req.status_code == 200 and len(resp_data): 170 | if (resp_data.startswith("[{") and resp_data.endswith("}]")) or \ 171 | (resp_data.startswith("{") and resp_data.endswith("}")): 172 | 173 | resp_json = json.loads(resp_data) 174 | 175 | if type_name == 'person' and 'cast' in resp_json: 176 | for item in resp_json['cast']: 177 | # filter out non-acting roles 178 | if not include_non_acting_roles and \ 179 | ((item['character'].strip() == '') or 180 | 'narrat' in item['character'].lower() or 181 | 'himself' in item['character'].lower()): 182 | continue 183 | if item not in processed: 184 | if object_name.rstrip('s') not in item and 'title' in item: 185 | processed.append({object_name.rstrip('s'): item}) 186 | else: 187 | processed.append(item) 188 | else: 189 | for item in resp_json: 190 | if item not in processed: 191 | if object_name.rstrip('s') not in item and 'title' in item: 192 | processed.append({object_name.rstrip('s'): item}) 193 | else: 194 | processed.append(item) 195 | 196 | elif resp_data == '[]': 197 | log.warning("Received empty JSON response for page: %d of %d", current_page, total_pages) 198 | else: 199 | log.warning("Received malformed JSON response for page: %d of %d", current_page, total_pages) 200 | 201 | # check if we have fetched the last page, break if so 202 | if total_pages == 0: 203 | log.debug("There were no more pages left to retrieve.") 204 | break 205 | elif current_page >= total_pages: 206 | log.debug("There are no more pages left to retrieve results from.") 207 | break 208 | else: 209 | log.info("There are %d page(s) left to retrieve results from.", total_pages - current_page) 210 | payload['page'] += 1 211 | time.sleep(sleep_between) 212 | 213 | elif req.status_code == 401: 214 | log.error("The authentication to Trakt is revoked. Please re-authenticate.") 215 | exit() 216 | else: 217 | log.error("Failed to retrieve %s %s, request response: %d", type_name, object_name, req.status_code) 218 | break 219 | 220 | if len(processed): 221 | log.debug("Found %d %s %s", len(processed), type_name, object_name) 222 | return processed 223 | 224 | return None 225 | except Exception: 226 | log.exception("Exception retrieving %s %s: ", type_name, object_name) 227 | return None 228 | 229 | def validate_client_id(self): 230 | try: 231 | # request anticipated shows to validate client_id 232 | req, req_data = self._make_request( 233 | url='https://api.trakt.tv/shows/anticipated', 234 | ) 235 | 236 | if req.status_code == 200: 237 | return True 238 | return False 239 | except Exception: 240 | log.exception("Exception validating client_id: ") 241 | return False 242 | 243 | def remove_recommended_item(self, item_type, trakt_id, authenticate_user=None): 244 | ret, ret_data = self._make_request( 245 | url='https://api.trakt.tv/recommendations/%ss/%s' % (item_type, str(trakt_id)), 246 | authenticate_user=authenticate_user, 247 | request_type='delete' 248 | ) 249 | if ret.status_code == 204: 250 | return True 251 | return False 252 | 253 | ############################################################ 254 | # OAuth Authentication 255 | ############################################################ 256 | 257 | def __oauth_request_device_code(self): 258 | log.info("We're talking to Trakt to get your verification code. Please wait a moment...") 259 | 260 | payload = {'client_id': self.cfg.trakt.client_id} 261 | 262 | print(self._headers_without_authentication()) 263 | 264 | # Request device code 265 | req = requests.post('https://api.trakt.tv/oauth/device/code', params=payload, 266 | headers=self._headers_without_authentication()) 267 | device_code_response = req.json() 268 | 269 | # Display needed information to the user 270 | log.info('Go to: %s on any device and enter %s. We\'ll be polling Trakt every %s seconds for a reply', 271 | device_code_response['verification_url'], device_code_response['user_code'], 272 | device_code_response['interval']) 273 | 274 | return device_code_response 275 | 276 | def __oauth_process_token_request(self, req): 277 | success = False 278 | 279 | if req.status_code == 200: 280 | # Success; saving the access token 281 | access_token_response = req.json() 282 | access_token = access_token_response['access_token'] 283 | 284 | # But first we need to find out what user this token belongs to 285 | temp_headers = self._headers_without_authentication() 286 | temp_headers['Authorization'] = 'Bearer ' + access_token 287 | 288 | req = requests.get('https://api.trakt.tv/users/me', headers=temp_headers) 289 | 290 | from misc.config import Config 291 | new_config = Config() 292 | 293 | new_config.merge_settings({ 294 | "trakt": { 295 | req.json()['username']: access_token_response 296 | } 297 | }) 298 | 299 | success = True 300 | elif req.status_code == 404: 301 | log.debug('The device code was wrong') 302 | log.error('Whoops, something went wrong; aborting the authentication process') 303 | elif req.status_code == 409: 304 | log.error('You\'ve already authenticated this application; aborting the authentication process') 305 | elif req.status_code == 410: 306 | log.error('The authentication process has expired; please start again') 307 | elif req.status_code == 418: 308 | log.error('You\'ve denied the authentication; are you sure? Please try again') 309 | elif req.status_code == 429: 310 | log.debug('We\'re polling too quickly.') 311 | 312 | return success, req.status_code 313 | 314 | def __oauth_poll_for_access_token(self, device_code, polling_interval=5, polling_expire=600): 315 | polling_start = time.time() 316 | time.sleep(polling_interval) 317 | tries = 0 318 | 319 | while time.time() - polling_start < polling_expire: 320 | tries += 1 321 | 322 | log.debug('Polling Trakt for the %sth time; %s seconds left', tries, 323 | polling_expire - round(time.time() - polling_start)) 324 | 325 | payload = {'code': device_code, 'client_id': self.cfg.trakt.client_id, 326 | 'client_secret': self.cfg.trakt.client_secret, 'grant_type': 'authorization_code'} 327 | 328 | # Poll Trakt for access token 329 | req = requests.post('https://api.trakt.tv/oauth/device/token', params=payload, 330 | headers=self._headers_without_authentication()) 331 | 332 | success, status_code = self.__oauth_process_token_request(req) 333 | 334 | if success: 335 | break 336 | elif status_code == 426: 337 | log.debug('Increasing the interval by one second') 338 | polling_interval += 1 339 | 340 | time.sleep(polling_interval) 341 | return False 342 | 343 | def __oauth_refresh_access_token(self, refresh_token): 344 | payload = {'refresh_token': refresh_token, 'client_id': self.cfg.trakt.client_id, 345 | 'client_secret': self.cfg.trakt.client_secret, 'grant_type': 'refresh_token'} 346 | 347 | req = requests.post('https://api.trakt.tv/oauth/token', params=payload, 348 | headers=self._headers_without_authentication()) 349 | 350 | success, status_code = self.__oauth_process_token_request(req) 351 | 352 | return success 353 | 354 | def oauth_authentication(self): 355 | try: 356 | device_code_response = self.__oauth_request_device_code() 357 | 358 | if self.__oauth_poll_for_access_token(device_code_response['device_code'], 359 | device_code_response['interval'], 360 | device_code_response['expires_in']): 361 | return True 362 | except Exception: 363 | log.exception("Exception occurred when authenticating user") 364 | return False 365 | 366 | def _get_first_authenticated_user(self): 367 | import copy 368 | 369 | users = copy.copy(self.cfg.trakt) 370 | 371 | if 'client_id' in users.keys(): 372 | users.pop('client_id') 373 | 374 | if 'client_secret' in users.keys(): 375 | users.pop('client_secret') 376 | 377 | if len(users) > 0: 378 | return list(users.keys())[0] 379 | 380 | def _user_is_authenticated(self, user): 381 | return user in self.cfg['trakt'].keys() 382 | 383 | def _renew_oauth_token_if_expired(self, user): 384 | token_information = self.cfg['trakt'][user] 385 | 386 | # Check if the access_token for the user is expired 387 | expires_at = token_information['created_at'] + token_information['expires_in'] 388 | if expires_at < round(time.time()): 389 | log.info("The access token for the user %s has expired. We're requesting a new one; please wait a moment.", 390 | user) 391 | 392 | if self.__oauth_refresh_access_token(token_information["refresh_token"]): 393 | log.info("The access token for the user %s has been refreshed. Please restart the application.", user) 394 | 395 | def _user_used_for_authentication(self, user=None): 396 | if user is None: 397 | user = self._get_first_authenticated_user() 398 | elif not self._user_is_authenticated(user): 399 | log.error('The user %s you specified to use for authentication is not authenticated yet. ' + 400 | 'Authenticate the user first, before you use it to retrieve lists.', user) 401 | 402 | exit() 403 | 404 | return user 405 | 406 | def _headers_without_authentication(self): 407 | return { 408 | 'Content-Type': 'application/json', 409 | 'trakt-api-version': '2', 410 | 'trakt-api-key': self.cfg.trakt.client_id 411 | } 412 | 413 | def _headers(self, user=None): 414 | headers = self._headers_without_authentication() 415 | 416 | user = self._user_used_for_authentication(user) 417 | 418 | if user is not None: 419 | self._renew_oauth_token_if_expired(user) 420 | headers['Authorization'] = 'Bearer ' + self.cfg['trakt'][user]['access_token'] 421 | else: 422 | log.info('No user') 423 | 424 | return headers, user 425 | 426 | ############################################################ 427 | # Shows 428 | ############################################################ 429 | 430 | def get_show(self, show_id): 431 | return self._make_item_request( 432 | url='https://api.trakt.tv/shows/%s' % str(show_id), 433 | object_name='show', 434 | ) 435 | 436 | @cache(cache_file=cachefile, retry_if_blank=True) 437 | def get_trending_shows( 438 | self, 439 | limit=1000, 440 | years=None, 441 | countries=None, 442 | languages=None, 443 | genres=None, 444 | runtimes=None, 445 | ): 446 | 447 | return self._make_items_request( 448 | url='https://api.trakt.tv/shows/trending', 449 | object_name='shows', 450 | type_name='trending', 451 | limit=limit, 452 | years=years, 453 | countries=countries, 454 | languages=languages, 455 | genres=genres, 456 | runtimes=runtimes, 457 | ) 458 | 459 | @cache(cache_file=cachefile, retry_if_blank=True) 460 | def get_popular_shows( 461 | self, 462 | limit=1000, 463 | years=None, 464 | countries=None, 465 | languages=None, 466 | genres=None, 467 | runtimes=None, 468 | ): 469 | 470 | return self._make_items_request( 471 | url='https://api.trakt.tv/shows/popular', 472 | object_name='shows', 473 | type_name='popular', 474 | limit=limit, 475 | years=years, 476 | countries=countries, 477 | languages=languages, 478 | genres=genres, 479 | runtimes=runtimes, 480 | ) 481 | 482 | @cache(cache_file=cachefile, retry_if_blank=True) 483 | def get_anticipated_shows( 484 | self, 485 | limit=1000, 486 | years=None, 487 | countries=None, 488 | languages=None, 489 | genres=None, 490 | runtimes=None, 491 | ): 492 | 493 | return self._make_items_request( 494 | url='https://api.trakt.tv/shows/anticipated', 495 | object_name='shows', 496 | type_name='anticipated', 497 | limit=limit, 498 | years=years, 499 | countries=countries, 500 | languages=languages, 501 | genres=genres, 502 | runtimes=runtimes, 503 | ) 504 | 505 | def get_person_shows( 506 | self, 507 | person, 508 | limit=1000, 509 | years=None, 510 | countries=None, 511 | languages=None, 512 | genres=None, 513 | runtimes=None, 514 | include_non_acting_roles=False, 515 | ): 516 | 517 | return self._make_items_request( 518 | url='https://api.trakt.tv/people/%s/shows' % person.replace(' ', '-').lower(), 519 | object_name='shows', 520 | type_name='person', 521 | limit=limit, 522 | years=years, 523 | countries=countries, 524 | languages=languages, 525 | genres=genres, 526 | runtimes=runtimes, 527 | include_non_acting_roles=include_non_acting_roles, 528 | ) 529 | 530 | @cache(cache_file=cachefile, retry_if_blank=True) 531 | def get_most_played_shows( 532 | self, 533 | limit=1000, 534 | years=None, 535 | countries=None, 536 | languages=None, 537 | genres=None, 538 | runtimes=None, 539 | most_type=None, 540 | ): 541 | 542 | return self._make_items_request( 543 | url='https://api.trakt.tv/shows/played/%s' % ('weekly' if not most_type else most_type), 544 | object_name='shows', 545 | type_name='played', 546 | limit=limit, 547 | years=years, 548 | countries=countries, 549 | languages=languages, 550 | genres=genres, 551 | runtimes=runtimes, 552 | ) 553 | 554 | @cache(cache_file=cachefile, retry_if_blank=True) 555 | def get_most_watched_shows( 556 | self, 557 | limit=1000, 558 | years=None, 559 | countries=None, 560 | languages=None, 561 | genres=None, 562 | runtimes=None, 563 | most_type=None, 564 | ): 565 | 566 | return self._make_items_request( 567 | url='https://api.trakt.tv/shows/watched/%s' % ('weekly' if not most_type else most_type), 568 | object_name='shows', 569 | type_name='watched', 570 | limit=limit, 571 | years=years, 572 | countries=countries, 573 | languages=languages, 574 | genres=genres, 575 | runtimes=runtimes, 576 | ) 577 | 578 | @cache(cache_file=cachefile, retry_if_blank=True) 579 | def get_recommended_shows( 580 | self, 581 | authenticate_user=None, 582 | limit=1000, 583 | years=None, 584 | countries=None, 585 | languages=None, 586 | genres=None, 587 | runtimes=None, 588 | ): 589 | 590 | return self._make_items_request( 591 | url='https://api.trakt.tv/recommendations/shows', 592 | object_name='shows', 593 | type_name='recommended from {authenticate_user}', 594 | authenticate_user=authenticate_user, 595 | limit=limit, 596 | years=years, 597 | countries=countries, 598 | languages=languages, 599 | genres=genres, 600 | runtimes=runtimes, 601 | ) 602 | 603 | def get_watchlist_shows( 604 | self, 605 | authenticate_user=None, 606 | limit=1000, 607 | years=None, 608 | countries=None, 609 | languages=None, 610 | genres=None, 611 | runtimes=None, 612 | ): 613 | 614 | return self._make_items_request( 615 | url='https://api.trakt.tv/users/{authenticate_user}/watchlist/shows', 616 | object_name='shows', 617 | type_name='watchlist from {authenticate_user}', 618 | authenticate_user=authenticate_user, 619 | limit=limit, 620 | years=years, 621 | countries=countries, 622 | languages=languages, 623 | genres=genres, 624 | runtimes=runtimes, 625 | ) 626 | 627 | def get_user_list_shows( 628 | self, 629 | list_url, 630 | authenticate_user=None, 631 | limit=1000, 632 | years=None, 633 | countries=None, 634 | languages=None, 635 | genres=None, 636 | runtimes=None, 637 | ): 638 | 639 | list_user, list_key = extract_list_user_and_key_from_url(list_url) 640 | 641 | log.debug('Fetching %s from %s', list_key, list_user) 642 | 643 | return self._make_items_request( 644 | url='https://api.trakt.tv/users/' + list_user + '/lists/' + list_key + '/items/shows', 645 | object_name='shows', 646 | type_name=(list_key + ' from ' + list_user), 647 | authenticate_user=authenticate_user, 648 | limit=limit, 649 | years=years, 650 | countries=countries, 651 | languages=languages, 652 | genres=genres, 653 | runtimes=runtimes, 654 | ) 655 | 656 | ############################################################ 657 | # Movies 658 | ############################################################ 659 | 660 | def get_movie(self, movie_id): 661 | return self._make_item_request( 662 | url='https://api.trakt.tv/movies/%s' % str(movie_id), 663 | object_name='movie', 664 | ) 665 | 666 | @cache(cache_file=cachefile, retry_if_blank=True) 667 | def get_trending_movies( 668 | self, 669 | limit=1000, 670 | years=None, 671 | countries=None, 672 | languages=None, 673 | genres=None, 674 | runtimes=None, 675 | ): 676 | 677 | return self._make_items_request( 678 | url='https://api.trakt.tv/movies/trending', 679 | object_name='movies', 680 | type_name='trending', 681 | limit=limit, 682 | years=years, 683 | countries=countries, 684 | languages=languages, 685 | genres=genres, 686 | runtimes=runtimes, 687 | ) 688 | 689 | @cache(cache_file=cachefile, retry_if_blank=True) 690 | def get_popular_movies( 691 | self, 692 | limit=1000, 693 | years=None, 694 | countries=None, 695 | languages=None, 696 | genres=None, 697 | runtimes=None, 698 | ): 699 | 700 | return self._make_items_request( 701 | url='https://api.trakt.tv/movies/popular', 702 | object_name='movies', 703 | type_name='popular', 704 | limit=limit, 705 | years=years, 706 | countries=countries, 707 | languages=languages, 708 | genres=genres, 709 | runtimes=runtimes, 710 | ) 711 | 712 | @cache(cache_file=cachefile, retry_if_blank=True) 713 | def get_anticipated_movies( 714 | self, 715 | limit=1000, 716 | years=None, 717 | countries=None, 718 | languages=None, 719 | genres=None, 720 | runtimes=None, 721 | ): 722 | 723 | return self._make_items_request( 724 | url='https://api.trakt.tv/movies/anticipated', 725 | object_name='movies', 726 | type_name='anticipated', 727 | limit=limit, 728 | years=years, 729 | countries=countries, 730 | languages=languages, 731 | genres=genres, 732 | runtimes=runtimes, 733 | ) 734 | 735 | def get_person_movies( 736 | self, 737 | person, 738 | limit=1000, 739 | years=None, 740 | countries=None, 741 | languages=None, 742 | genres=None, 743 | runtimes=None, 744 | include_non_acting_roles=False, 745 | ): 746 | 747 | return self._make_items_request( 748 | url='https://api.trakt.tv/people/%s/movies' % person.replace(' ', '-').lower(), 749 | object_name='movies', 750 | type_name='person', 751 | limit=limit, 752 | years=years, 753 | countries=countries, 754 | languages=languages, 755 | genres=genres, 756 | runtimes=runtimes, 757 | include_non_acting_roles=include_non_acting_roles, 758 | ) 759 | 760 | @cache(cache_file=cachefile, retry_if_blank=True) 761 | def get_most_played_movies( 762 | self, 763 | limit=1000, 764 | years=None, 765 | countries=None, 766 | languages=None, 767 | genres=None, 768 | runtimes=None, 769 | most_type=None, 770 | ): 771 | 772 | return self._make_items_request( 773 | url='https://api.trakt.tv/movies/played/%s' % ('weekly' if not most_type else most_type), 774 | object_name='movies', 775 | type_name='played', 776 | limit=limit, 777 | years=years, 778 | countries=countries, 779 | languages=languages, 780 | genres=genres, 781 | runtimes=runtimes, 782 | ) 783 | 784 | @cache(cache_file=cachefile, retry_if_blank=True) 785 | def get_most_watched_movies( 786 | self, 787 | limit=1000, 788 | years=None, 789 | countries=None, 790 | languages=None, 791 | genres=None, 792 | most_type=None, 793 | runtimes=None, 794 | ): 795 | 796 | return self._make_items_request( 797 | url='https://api.trakt.tv/movies/watched/%s' % ('weekly' if not most_type else most_type), 798 | object_name='movies', 799 | type_name='watched', 800 | limit=limit, 801 | years=years, 802 | countries=countries, 803 | languages=languages, 804 | genres=genres, 805 | runtimes=runtimes, 806 | ) 807 | 808 | def get_boxoffice_movies( 809 | self, 810 | limit=1000, 811 | ): 812 | 813 | return self._make_items_request( 814 | url='https://api.trakt.tv/movies/boxoffice', 815 | object_name='movies', 816 | type_name='anticipated', 817 | limit=limit, 818 | ) 819 | 820 | def get_recommended_movies( 821 | self, 822 | authenticate_user=None, 823 | limit=1000, 824 | years=None, 825 | countries=None, 826 | languages=None, 827 | genres=None, 828 | runtimes=None, 829 | ): 830 | 831 | return self._make_items_request( 832 | url='https://api.trakt.tv/recommendations/movies', 833 | object_name='movies', 834 | type_name='recommended from {authenticate_user}', 835 | authenticate_user=authenticate_user, 836 | limit=limit, 837 | years=years, 838 | countries=countries, 839 | languages=languages, 840 | genres=genres, 841 | runtimes=runtimes, 842 | ) 843 | 844 | def get_watchlist_movies( 845 | self, 846 | authenticate_user=None, 847 | limit=1000, 848 | years=None, 849 | countries=None, 850 | languages=None, 851 | genres=None, 852 | runtimes=None, 853 | ): 854 | 855 | return self._make_items_request( 856 | url='https://api.trakt.tv/users/{authenticate_user}/watchlist/movies', 857 | object_name='movies', 858 | type_name='watchlist from {authenticate_user}', 859 | authenticate_user=authenticate_user, 860 | limit=limit, 861 | years=years, 862 | countries=countries, 863 | languages=languages, 864 | genres=genres, 865 | runtimes=runtimes, 866 | ) 867 | 868 | def get_user_list_movies( 869 | self, 870 | list_url, 871 | authenticate_user=None, 872 | limit=1000, 873 | years=None, 874 | countries=None, 875 | languages=None, 876 | genres=None, 877 | runtimes=None, 878 | ): 879 | 880 | list_user, list_key = extract_list_user_and_key_from_url(list_url) 881 | 882 | log.debug('Fetching %s from %s', list_key, list_user) 883 | 884 | return self._make_items_request( 885 | url='https://api.trakt.tv/users/' + list_user + '/lists/' + list_key + '/items/movies', 886 | object_name='movies', 887 | type_name=(list_key + ' from ' + list_user), 888 | authenticate_user=authenticate_user, 889 | limit=limit, 890 | years=years, 891 | countries=countries, 892 | languages=languages, 893 | genres=genres, 894 | runtimes=runtimes, 895 | ) 896 | -------------------------------------------------------------------------------- /misc/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/l3uddz/traktarr/52d71964a2cd6504adda6e2b2d5cdfc68cc794c8/misc/__init__.py -------------------------------------------------------------------------------- /misc/config.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | import sys 4 | 5 | from attrdict import AttrDict 6 | 7 | 8 | class Singleton(type): 9 | _instances = {} 10 | 11 | def __call__(cls, *args, **kwargs): 12 | if cls not in cls._instances: 13 | cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) 14 | 15 | return cls._instances[cls] 16 | 17 | 18 | class AttrConfig(AttrDict): 19 | """ 20 | Simple AttrDict subclass to return None when requested attribute does not exist 21 | """ 22 | 23 | def __init__(self, config): 24 | super().__init__(config) 25 | 26 | def __getattr__(self, item): 27 | try: 28 | return super().__getattr__(item) 29 | except AttributeError: 30 | pass 31 | # Default behaviour 32 | return None 33 | 34 | 35 | class Config(object, metaclass=Singleton): 36 | base_config = { 37 | 'core': { 38 | 'debug': False 39 | }, 40 | 'notifications': { 41 | 'verbose': True 42 | }, 43 | 'automatic': { 44 | 'movies': { 45 | 'interval': 20, 46 | 'anticipated': 3, 47 | 'trending': 3, 48 | 'popular': 3, 49 | 'boxoffice': 10 50 | }, 51 | 'shows': { 52 | 'interval': 48, 53 | 'anticipated': 10, 54 | 'trending': 1, 55 | 'popular': 1 56 | } 57 | }, 58 | 'filters': { 59 | 'shows': { 60 | 'disabled_for': [], 61 | 'allowed_countries': [], 62 | 'allowed_languages': [], 63 | 'blacklisted_genres': [], 64 | 'blacklisted_networks': [], 65 | 'blacklisted_min_runtime': 15, 66 | 'blacklisted_max_runtime': 0, 67 | 'blacklisted_min_year': 2000, 68 | 'blacklisted_max_year': 2019, 69 | 'blacklisted_title_keywords': [], 70 | 'blacklisted_tvdb_ids': [], 71 | }, 72 | 'movies': { 73 | 'disabled_for': [], 74 | 'allowed_countries': [], 75 | 'allowed_languages': [], 76 | 'blacklisted_genres': [], 77 | 'blacklisted_min_runtime': 60, 78 | 'blacklisted_max_runtime': 0, 79 | 'blacklisted_min_year': 2000, 80 | 'blacklisted_max_year': 2019, 81 | 'blacklisted_title_keywords': [], 82 | 'blacklisted_tmdb_ids': [], 83 | 'rotten_tomatoes': "" 84 | } 85 | }, 86 | 'radarr': { 87 | 'api_key': '', 88 | 'minimum_availability': 'released', 89 | 'quality': 'HD-1080p', 90 | 'root_folder': '/movies/', 91 | 'url': 'http://localhost:7878/' 92 | }, 93 | 'sonarr': { 94 | 'api_key': '', 95 | 'language': 'English', 96 | 'quality': 'HD-1080p', 97 | 'root_folder': '/tv/', 98 | 'season_folder': True, 99 | 'tags': [], 100 | 'url': 'http://localhost:8989/' 101 | }, 102 | 'omdb': { 103 | 'api_key': '' 104 | }, 105 | 'trakt': { 106 | 'client_id': '', 107 | 'client_secret': '' 108 | } 109 | } 110 | 111 | def __init__(self, configfile, cachefile, logfile): 112 | """Initializes config""" 113 | self.conf = None 114 | 115 | self.config_path = configfile 116 | self.cache_path = cachefile 117 | self.log_path = logfile 118 | 119 | @property 120 | def cfg(self): 121 | # Return existing loaded config 122 | if self.conf: 123 | return self.conf 124 | 125 | # Built initial config if it doesn't exist 126 | if self.build_config(): 127 | print("Please edit the default configuration before running again!") 128 | sys.exit(0) 129 | # Load config, upgrade if necessary 130 | else: 131 | tmp = self.load_config() 132 | self.conf, upgraded = self.upgrade_settings(tmp) 133 | 134 | # Save config if upgraded 135 | if upgraded: 136 | self.dump_config() 137 | print("New config options were added, adjust and restart!") 138 | sys.exit(0) 139 | 140 | return self.conf 141 | 142 | @property 143 | def cachefile(self): 144 | return self.cache_path 145 | 146 | @property 147 | def logfile(self): 148 | return self.log_path 149 | 150 | def build_config(self): 151 | if os.path.exists(self.config_path): 152 | return False 153 | print("Dumping default config to: %s" % self.config_path) 154 | with open(self.config_path, 'w') as fp: 155 | json.dump(self.base_config, fp, sort_keys=True, indent=2) 156 | return True 157 | 158 | def dump_config(self): 159 | if os.path.exists(self.config_path): 160 | with open(self.config_path, 'w') as fp: 161 | json.dump(self.conf, fp, sort_keys=True, indent=2) 162 | return True 163 | else: 164 | return False 165 | 166 | def load_config(self): 167 | with open(self.config_path, 'r') as fp: 168 | return AttrConfig(json.load(fp)) 169 | 170 | def __inner_upgrade(self, settings1, settings2, key=None, overwrite=False): 171 | sub_upgraded = False 172 | merged = settings2.copy() 173 | 174 | if isinstance(settings1, dict): 175 | for k, v in settings1.items(): 176 | # missing k 177 | if k not in settings2: 178 | merged[k] = v 179 | sub_upgraded = True 180 | if not key: 181 | print("Added %r config option: %s" % (str(k), str(v))) 182 | else: 183 | print("Added %r to config option %r: %s" % (str(k), str(key), str(v))) 184 | continue 185 | 186 | # iterate children 187 | if isinstance(v, (dict, list)): 188 | merged[k], did_upgrade = self.__inner_upgrade(settings1[k], settings2[k], key=k, 189 | overwrite=overwrite) 190 | sub_upgraded = did_upgrade or sub_upgraded 191 | elif settings1[k] != settings2[k] and overwrite: 192 | merged = settings1 193 | sub_upgraded = True 194 | elif isinstance(settings1, list) and key: 195 | for v in settings1: 196 | if v not in settings2: 197 | merged.append(v) 198 | sub_upgraded = True 199 | print("Added to config option %r: %s" % (str(key), str(v))) 200 | continue 201 | 202 | return merged, sub_upgraded 203 | 204 | def upgrade_settings(self, currents): 205 | upgraded_settings, upgraded = self.__inner_upgrade(self.base_config, currents) 206 | return AttrConfig(upgraded_settings), upgraded 207 | 208 | def merge_settings(self, settings_to_merge): 209 | upgraded_settings, upgraded = self.__inner_upgrade(settings_to_merge, self.conf, overwrite=True) 210 | 211 | self.conf = upgraded_settings 212 | 213 | if upgraded: 214 | self.dump_config() 215 | 216 | return AttrConfig(upgraded_settings), upgraded 217 | -------------------------------------------------------------------------------- /misc/log.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import sys 4 | from logging.handlers import RotatingFileHandler 5 | 6 | from misc.config import Config 7 | 8 | 9 | class Logger: 10 | def __init__(self, file_name=None, log_level=logging.DEBUG, 11 | log_format='%(asctime)s - %(levelname)-10s - %(name)-35s - %(funcName)-35s - %(message)s'): 12 | self.log_format = log_format 13 | 14 | # init root_logger 15 | self.log_formatter = logging.Formatter(log_format) 16 | self.root_logger = logging.getLogger() 17 | self.root_logger.setLevel(log_level) 18 | 19 | # disable bloat loggers 20 | logging.getLogger("requests").setLevel(logging.WARNING) 21 | logging.getLogger('urllib3').setLevel(logging.ERROR) 22 | logging.getLogger('schedule').setLevel(logging.ERROR) 23 | 24 | # init console_logger 25 | self.console_handler = logging.StreamHandler(sys.stdout) 26 | self.console_handler.setFormatter(self.log_formatter) 27 | self.root_logger.addHandler(self.console_handler) 28 | 29 | # init file_logger 30 | if file_name: 31 | if os.path.sep not in file_name: 32 | # file_name was a filename, lets build a full file_path 33 | self.log_file_path = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), file_name) 34 | else: 35 | self.log_file_path = file_name 36 | 37 | self.file_handler = RotatingFileHandler( 38 | self.log_file_path, 39 | maxBytes=1024 * 1024 * 2, 40 | backupCount=5 41 | ) 42 | self.file_handler.setFormatter(self.log_formatter) 43 | self.root_logger.addHandler(self.file_handler) 44 | 45 | # Set chosen logging level 46 | self.root_logger.setLevel(log_level) 47 | 48 | def get_logger(self, name): 49 | return self.root_logger.getChild(name) 50 | 51 | 52 | # Default logger 53 | logger = Logger(Config().logfile, logging.DEBUG if Config().cfg.core.debug else logging.INFO) 54 | -------------------------------------------------------------------------------- /notifications/__init__.py: -------------------------------------------------------------------------------- 1 | from misc.log import logger 2 | 3 | from .apprise import Apprise 4 | from .pushover import Pushover 5 | from .slack import Slack 6 | 7 | log = logger.get_logger(__name__) 8 | 9 | SERVICES = { 10 | 'apprise': Apprise, 11 | 'pushover': Pushover, 12 | 'slack': Slack 13 | } 14 | 15 | 16 | class Notifications: 17 | def __init__(self): 18 | self.services = [] 19 | 20 | def load(self, **kwargs): 21 | if 'service' not in kwargs: 22 | log.error("You must specify a service to load with the service parameter") 23 | return False 24 | elif kwargs['service'] not in SERVICES: 25 | log.error("You specified an invalid service to load: %s", kwargs['service']) 26 | return False 27 | 28 | try: 29 | chosen_service = SERVICES[kwargs['service']] 30 | del kwargs['service'] 31 | 32 | # load service 33 | service = chosen_service(**kwargs) 34 | self.services.append(service) 35 | 36 | except Exception: 37 | log.exception("Exception while loading service, kwargs=%r: ", kwargs) 38 | 39 | def send(self, **kwargs): 40 | try: 41 | # remove service keyword if supplied 42 | if 'service' in kwargs: 43 | # send notification to specified service 44 | chosen_service = kwargs['service'].lower() 45 | del kwargs['service'] 46 | else: 47 | chosen_service = None 48 | 49 | # send notification(s) 50 | for service in self.services: 51 | if chosen_service and service.NAME.lower() != chosen_service: 52 | continue 53 | elif service.send(**kwargs): 54 | log.debug("Sent notification with %s", service.NAME) 55 | except Exception: 56 | log.exception("Exception sending notification, kwargs=%r: ", kwargs) 57 | -------------------------------------------------------------------------------- /notifications/apprise.py: -------------------------------------------------------------------------------- 1 | import apprise 2 | 3 | from misc.log import logger 4 | 5 | log = logger.get_logger(__name__) 6 | 7 | 8 | class Apprise: 9 | NAME = "Apprise" 10 | 11 | def __init__(self, url, title='Traktarr'): 12 | self.url = url 13 | self.title = title 14 | log.debug("Initialized Apprise notification agent") 15 | 16 | def send(self, **kwargs): 17 | if not self.url: 18 | log.error("You must specify a URL when initializing this class") 19 | return False 20 | 21 | # send notification 22 | try: 23 | apobj = apprise.Apprise() 24 | apobj.add(self.url) 25 | apobj.notify( 26 | title=self.title, 27 | body=kwargs['message'], 28 | ) 29 | 30 | except Exception: 31 | log.exception("Error sending notification to %r", self.url) 32 | return False 33 | -------------------------------------------------------------------------------- /notifications/pushover.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | from misc.log import logger 4 | 5 | log = logger.get_logger(__name__) 6 | 7 | 8 | class Pushover: 9 | NAME = "Pushover" 10 | 11 | def __init__(self, app_token, user_token, priority=0): 12 | self.app_token = app_token 13 | self.user_token = user_token 14 | self.priority = priority 15 | log.debug("Initialized Pushover notification agent") 16 | 17 | def send(self, **kwargs): 18 | if not self.app_token or not self.user_token: 19 | log.error("You must specify an app_token and user_token when initializing this class") 20 | return False 21 | 22 | # send notification 23 | try: 24 | payload = { 25 | 'token': self.app_token, 26 | 'user': self.user_token, 27 | 'message': kwargs['message'], 28 | 'priority': self.priority, 29 | } 30 | resp = requests.post('https://api.pushover.net/1/messages.json', data=payload, timeout=30) 31 | return resp.status_code == 200 32 | 33 | except Exception: 34 | log.exception("Error sending notification to %r", self.user_token) 35 | return False 36 | -------------------------------------------------------------------------------- /notifications/slack.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | from misc.log import logger 4 | 5 | log = logger.get_logger(__name__) 6 | 7 | 8 | class Slack: 9 | NAME = "Slack" 10 | 11 | def __init__(self, webhook_url, sender_name='Traktarr', sender_icon=':movie_camera:', channel=None): 12 | self.webhook_url = webhook_url 13 | self.sender_name = sender_name 14 | self.sender_icon = sender_icon 15 | self.channel = channel 16 | log.debug("Initialized Slack notification agent") 17 | 18 | def send(self, **kwargs): 19 | if not self.webhook_url or not self.sender_name or not self.sender_icon: 20 | log.error("You must specify an webhook_url, sender_name and sender_icon when initializing this class") 21 | return False 22 | 23 | # send notification 24 | try: 25 | payload = { 26 | 'text': kwargs['message'], 27 | 'username': self.sender_name, 28 | 'icon_emoji': self.sender_icon, 29 | } 30 | if self.channel: 31 | payload['channel'] = self.channel 32 | 33 | resp = requests.post(self.webhook_url, json=payload, timeout=30) 34 | return resp.status_code == 200 35 | 36 | except Exception: 37 | log.exception("Error sending notification to %r", self.webhook_url) 38 | return False 39 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | backoff==1.5.0 2 | schedule==0.5.0 3 | attrdict==2.0.0 4 | click==6.7 5 | requests~=2.20.0 6 | pyfiglet 7 | cashier~=1.3 8 | apprise~=0.8.2 9 | -------------------------------------------------------------------------------- /sample/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "core": { 3 | "debug": false 4 | }, 5 | "notifications": { 6 | "verbose": false 7 | }, 8 | "automatic": { 9 | "movies": { 10 | "anticipated": 3, 11 | "boxoffice": 10, 12 | "interval": 24, 13 | "popular": 3, 14 | "trending": 2 15 | }, 16 | "shows": { 17 | "anticipated": 10, 18 | "interval": 48, 19 | "popular": 1, 20 | "trending": 2 21 | } 22 | }, 23 | "filters": { 24 | "movies": { 25 | "disabled_for": [], 26 | "allowed_countries": [ 27 | "us", 28 | "gb", 29 | "ca" 30 | ], 31 | "allowed_languages": [ 32 | "en" 33 | ], 34 | "blacklisted_genres": [ 35 | "documentary", 36 | "music", 37 | "short", 38 | "sporting-event", 39 | "film-noir", 40 | "fan-film" 41 | ], 42 | "blacklisted_min_runtime": 60, 43 | "blacklisted_max_runtime": 0, 44 | "blacklisted_min_year": 2000, 45 | "blacklisted_max_year": 2019, 46 | "blacklisted_title_keywords": [ 47 | "untitled", 48 | "barbie", 49 | "ufc" 50 | ], 51 | "rotten_tomatoes": 80 52 | }, 53 | "shows": { 54 | "disabled_for": [], 55 | "allowed_countries": [ 56 | "us", 57 | "gb", 58 | "ca" 59 | ], 60 | "allowed_languages": [], 61 | "blacklisted_genres": [ 62 | "animation", 63 | "game-show", 64 | "talk-show", 65 | "home-and-garden", 66 | "children", 67 | "reality", 68 | "anime", 69 | "news", 70 | "documentary", 71 | "special-interest" 72 | ], 73 | "blacklisted_networks": [ 74 | "twitch", 75 | "youtube", 76 | "nickelodeon", 77 | "hallmark", 78 | "reelzchannel", 79 | "disney", 80 | "cnn", 81 | "cbbc", 82 | "the movie network", 83 | "teletoon", 84 | "cartoon network", 85 | "espn", 86 | "fox sports", 87 | "yahoo!" 88 | ], 89 | "blacklisted_min_runtime": 15, 90 | "blacklisted_max_runtime": 0, 91 | "blacklisted_min_year": 2010, 92 | "blacklisted_max_year": 2019, 93 | "blacklisted_title_keywords": [] 94 | } 95 | }, 96 | "radarr": { 97 | "api_key": "", 98 | "quality": "HD-1080p", 99 | "minimum_availability": "released", 100 | "url": "http://localhost:7878/", 101 | "root_folder": "/movies/" 102 | }, 103 | "sonarr": { 104 | "api_key": "", 105 | "language": "English", 106 | "quality": "HD-1080p", 107 | "url": "http://localhost:8989/", 108 | "root_folder": "/tv/", 109 | "season_folder": true, 110 | "tags": {} 111 | }, 112 | "omdb": { 113 | "api_key": "" 114 | }, 115 | "trakt": { 116 | "client_id": "", 117 | "client_secret": "" 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /systemd/traktarr.service: -------------------------------------------------------------------------------- 1 | # /etc/systemd/system/traktarr.service 2 | 3 | [Unit] 4 | Description=Traktarr 5 | After=network-online.target 6 | 7 | [Service] 8 | User=seed 9 | Group=seed 10 | Type=simple 11 | Environment="LC_ALL=C.UTF-8" 12 | Environment="LANG=C.UTF-8" 13 | WorkingDirectory=/opt/traktarr/ 14 | ExecStart=/usr/bin/python3 /opt/traktarr/traktarr.py run 15 | Restart=always 16 | RestartSec=10 17 | 18 | [Install] 19 | WantedBy=default.target 20 | --------------------------------------------------------------------------------