├── .dockerignore ├── .gitignore ├── .vscode └── launch.json ├── LICENSE ├── README.md ├── cmd └── deflix-stremio │ ├── config.go │ ├── handlers.go │ ├── main.go │ ├── middleware.go │ ├── oauth2.go │ ├── storage.go │ ├── storage_test.go │ └── user_data.go ├── docker └── Dockerfile ├── go.mod ├── go.sum ├── pkg ├── logadapter │ └── badgerdb.go └── metafetcher │ └── client.go ├── scripts └── build.sh └── web └── configure ├── deflix.css ├── favicon.ico ├── index-apikey.html ├── index-oauth2.html └── mvp.css /.dockerignore: -------------------------------------------------------------------------------- 1 | README.md 2 | /docker 3 | /cmd/rd-tester 4 | /cmd/rd-proxy 5 | 6 | /deflix-stremio* 7 | /rd-tester* 8 | /rd-proxy* 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io/api/go,visualstudiocode 2 | # Edit at https://www.gitignore.io/?templates=go,visualstudiocode 3 | 4 | ### Go ### 5 | # Binaries for programs and plugins 6 | *.exe 7 | *.exe~ 8 | *.dll 9 | *.so 10 | *.dylib 11 | 12 | # Test binary, built with `go test -c` 13 | *.test 14 | 15 | # Output of the go coverage tool, specifically when used with LiteIDE 16 | *.out 17 | 18 | # Dependency directories (remove the comment below to include it) 19 | # vendor/ 20 | 21 | ### Go Patch ### 22 | /vendor/ 23 | /Godeps/ 24 | 25 | ### VisualStudioCode ### 26 | .vscode/* 27 | !.vscode/settings.json 28 | !.vscode/tasks.json 29 | !.vscode/launch.json 30 | !.vscode/extensions.json 31 | 32 | ### VisualStudioCode Patch ### 33 | # Ignore all local history of files 34 | .history 35 | 36 | # End of https://www.gitignore.io/api/go,visualstudiocode 37 | 38 | /deflix-stremio 39 | /rd-tester 40 | /rd-proxy 41 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Launch Package", 9 | "type": "go", 10 | "request": "launch", 11 | "mode": "debug", 12 | "program": "${workspaceFolder}/cmd/deflix-stremio", 13 | "args": ["-webConfigurePath", "${workspaceFolder}/web/configure"] 14 | } 15 | ] 16 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Deflix Stremio addon 2 | ==================== 3 | 4 | [Deflix](https://www.deflix.tv) addon for [Stremio](https://stremio.com) 5 | 6 | Finds movies and TV shows from many different sources and automatically turns them into cached HTTP streams with a debrid service like [RealDebrid](https://real-debrid.com), [AllDebrid](https://alldebrid.com) or [Premiumize](https://www.premiumize.me), for high speed 4k streaming and **no P2P uploading**. 7 | 8 | Contents 9 | -------- 10 | 11 | 1. [Features](#features) 12 | 2. [Install](#install) 13 | 3. [Run locally](#run-locally) 14 | 1. [Configuration](#configuration) 15 | 2. [Warning](#warning) 16 | 4. [Disclaimer](#disclaimer) 17 | 18 | Features 19 | -------- 20 | 21 | - Supports several debrid services 22 | - [x] [RealDebrid](https://real-debrid.com) 23 | - [x] [AllDebrid](https://alldebrid.com) 24 | - [x] [Premiumize](https://www.premiumize.me) 25 | - [ ] Others can be added, please let me know which one you want to see next 26 | - Finds movies and TV shows from many different sources 27 | - [x] YTS 28 | - [x] The Pirate Bay 29 | - [x] 1337x 30 | - [x] RARBG 31 | - [x] ibit 32 | - [ ] Others like RapidMoviez and Scene-RLS are planned 33 | - Groups streams by quality so you don't have to choose between dozens of results 34 | - 720p 35 | - 1080p 36 | - 1080p 10bit 37 | - 2160p 38 | - 2160p 10bit 39 | - Configurable via the ⚙ button in Stremio 40 | 41 | Other *upcoming* features: Support for more sources, grouping by bitrate, more custom options (language filter, show *all single torrents* instead of grouped by quality) and more 42 | 43 | Install 44 | ------- 45 | 46 | This addon is a remote addon, so it's an HTTP web service and Stremio just sends HTTP requests to it. You dont't need to run any untrusted code on your machine. 47 | 48 | Here's the official Deflix website, that guides you through the installation: 49 | 50 | > Note: This repository contains all the latest features and fixes. Some of them might not be publicly deployed yet. If you want to use the version of this repository, run the addon locally. 51 | 52 | Run locally 53 | ----------- 54 | 55 | Alternatively to using the publicly deployed version you can also run the addon locally and use that in Stremio. The addon is written in Go and compiles to a single executable file without dependencies, so it's really easy to run on your machine. 56 | 57 | You can use one of the precompiled binaries from GitHub: 58 | 59 | 1. Download the binary for your OS from 60 | 2. Simply run the executable binary (`deflix-stremio.exe` for Windows, `deflix-stremio` for macOS and Linux) 61 | 3. Visit in the browser to configure and install the addon in Stremio 62 | 4. To stop the program press `Ctrl-C` (or `⌃-C` on macOS) in the terminal windows where `deflix-stremio` is running 63 | 64 | Or use Docker: 65 | 66 | 1. Update the image: `docker pull doingodswork/deflix-stremio` 67 | 2. Start the container: `docker run --name deflix-stremio -p 8080:8080 doingodswork/deflix-stremio` 68 | - > Note: `Ctrl-C` only detaches from the container. It doesn't stop it. 69 | - When detached, you can attach again with `docker attach deflix-stremio` 70 | 3. Visit in the browser to configure and install the addon in Stremio 71 | 4. To stop the container: `docker stop deflix-stremio` 72 | 5. To start the (still existing) container again: `docker start deflix-stremio` 73 | 74 | ### Configuration 75 | 76 | The following options can be configured via either command line argument or environment variable: 77 | 78 | ```text 79 | Usage of deflix-stremio: 80 | -baseURL string 81 | Base URL of this service. It's used in a stream URL that's delivered to Stremio and later used to redirect to RealDebrid, AllDebrid and Premiumize. If you enable OAuth2 handling this will also be used for the redirects and to determine whether the state cookie is a secure one or not. (default "http://localhost:8080") 82 | -baseURL1337x string 83 | Base URL for 1337x (default "https://1337x.to") 84 | -baseURLad string 85 | Base URL for AllDebrid (default "https://api.alldebrid.com") 86 | -baseURLibit string 87 | Base URL for ibit (default "https://ibit.am") 88 | -baseURLpm string 89 | Base URL for Premiumize (default "https://www.premiumize.me/api") 90 | -baseURLrarbg string 91 | Base URL for RARBG (default "https://torrentapi.org") 92 | -baseURLrd string 93 | Base URL for RealDebrid (default "https://api.real-debrid.com") 94 | -baseURLtpb string 95 | Base URL for the TPB API (default "https://apibay.org") 96 | -baseURLyts string 97 | Base URL for YTS (default "https://yts.mx") 98 | -bindAddr string 99 | Local interface address to bind to. "localhost" only allows access from the local host. "0.0.0.0" binds to all network interfaces. (default "localhost") 100 | -cacheAgeXD duration 101 | Max age of cache entries for instant availability responses from RealDebrid, AllDebrid and Premiumize. The format must be acceptable by Go's 'time.ParseDuration()', for example "24h". (default 24h0m0s) 102 | -cachePath string 103 | Path for loading persisted caches on startup and persisting the current cache in regular intervals. An empty value will lead to 'os.UserCacheDir()+"/deflix-stremio/cache"'. 104 | -envPrefix string 105 | Prefix for environment variables 106 | -extraHeadersXD string 107 | Additional HTTP request headers to set for requests to RealDebrid, AllDebrid and Premiumize, in a format like "X-Foo: bar", separated by newline characters ("\n") 108 | -forwardOriginIP 109 | Forward the user's original IP address to RealDebrid and Premiumize. The first "X-Forwarded-For" entry will be used. 110 | -imdb2metaAddr string 111 | Address of the imdb2meta gRPC server. Won't be used if empty. 112 | -logEncoding string 113 | Log encoding. Can be "console" or "json", where "json" makes more sense when using centralized logging solutions like ELK, Graylog or Loki. (default "console") 114 | -logFoundTorrents 115 | Set to true to log each single torrent that was found by one of the torrent site clients (with DEBUG level) 116 | -logLevel string 117 | Log level to show only logs with the given and more severe levels. Can be "debug", "info", "warn", "error". (default "debug") 118 | -maxAgeTorrents duration 119 | Max age of cache entries for torrents found per IMDb ID. The format must be acceptable by Go's 'time.ParseDuration()', for example "24h". Default is 7 days. (default 168h0m0s) 120 | -oauth2authURLpm string 121 | URL of the OAuth2 authorization endpoint of Premiumize (default "https://www.premiumize.me/authorize") 122 | -oauth2authURLrd string 123 | URL of the OAuth2 authorization endpoint of RealDebrid (default "https://api.real-debrid.com/oauth/v2/auth") 124 | -oauth2clientIDpm string 125 | Client ID for deflix-stremio on Premiumize 126 | -oauth2clientIDrd string 127 | Client ID for deflix-stremio on RealDebrid 128 | -oauth2clientSecretPM string 129 | Client secret for deflix-stremio on Premiumize 130 | -oauth2clientSecretRD string 131 | Client secret for deflix-stremio on RealDebrid 132 | -oauth2encryptionKey string 133 | OAuth2 data encryption key 134 | -oauth2tokenURLpm string 135 | URL of the OAuth2 token endpoint of Premiumize (default "https://www.premiumize.me/token") 136 | -oauth2tokenURLrd string 137 | URL of the OAuth2 token endpoint of RealDebrid (default "https://api.real-debrid.com/oauth/v2/token") 138 | -port int 139 | Port to listen on (default 8080) 140 | -redisAddr string 141 | Redis host and port, for example "localhost:6379". It's used for the redirect and stream cache. Keep empty to use in-memory go-cache. 142 | -redisCreds string 143 | Credentials for Redis. Password for Redis version 5 and older, username and password for Redis version 6 and newer. Use the colon character (":") for separating username and password. This implies you can't use a colon in the password when using Redis version 5 or older. 144 | -rootURL string 145 | Redirect target for the root (default "https://www.deflix.tv") 146 | -socksProxyAddrTPB string 147 | SOCKS5 proxy address for accessing TPB, required for accessing TPB via the TOR network (where "127.0.0.1:9050" would be typical value) 148 | -storagePath string 149 | Path for storing the data of the persistent DB which stores torrent results. An empty value will lead to 'os.UserCacheDir()+"/deflix-stremio/badger"'. 150 | -useOAUTH2 151 | Flag for indicating whether to use OAuth2 for Premiumize authorization. This leads to a different configuration webpage that doesn't require API keys. It requires a client ID to be configured. 152 | -webConfigurePath string 153 | Path to the directory with web files for the '/configure' endpoint. If empty, files compiled into the binary will be used 154 | ``` 155 | 156 | If you want to configure deflix-stremio via environment variables, you can use the according environment variable keys, like this: `baseURL1337x` -> `BASE_URL_1337X`. If you want to use an environment variable prefix you have to set it with the command line argument (for example `-envPrefix DEFLIX` and then the environment variable for the previous example would be `DEFLIX_BASE_URL_1337X`. 157 | 158 | ### Warning 159 | 160 | If you *run* this web service on your local laptop or server, i.e. if you *self-host* this, you should know the following: 161 | 162 | Deflix doesn't download or upload any torrents, but it *does* send HTTP requests to YTS, The Pirate Bay, 1337x, RARBG and ibit, which *might* be illegal in some countries. Streaming movies and TV shows from RealDebrid, AllDebrid or Premiumize *might* also be illegal in some countries. 163 | 164 | > To encrypt your traffic so that your ISP can't see where those HTTP requests are sent and to not expose your real IP address to RealDebrid, AllDebrid or Premiumize you can use a VPN. 165 | 166 | Disclaimer 167 | ---------- 168 | 169 | Deflix 170 | 171 | - doesn't *host* any media files or torrents 172 | - doesn't *provide link lists* to media files or torrents 173 | - isn't a *torrent indexer* 174 | - doesn't *facilitate the sharing* of any media files or torrents 175 | -------------------------------------------------------------------------------- /cmd/deflix-stremio/config.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "os" 6 | "path/filepath" 7 | "strconv" 8 | "strings" 9 | "time" 10 | 11 | "go.uber.org/zap" 12 | ) 13 | 14 | type config struct { 15 | BindAddr string `json:"bindAddr"` 16 | Port int `json:"port"` 17 | BaseURL string `json:"baseURL"` 18 | StoragePath string `json:"storagePath"` 19 | MaxAgeTorrents time.Duration `json:"maxAgeTorrents"` 20 | CachePath string `json:"cachePath"` 21 | CacheAgeXD time.Duration `json:"cacheAgeXD"` 22 | RedisAddr string `json:"redisAddr"` 23 | RedisCreds string `json:"redisCreds"` 24 | BaseURLyts string `json:"baseURLyts"` 25 | BaseURLtpb string `json:"baseURLtpb"` 26 | BaseURL1337x string `json:"baseURL1337x"` 27 | BaseURLibit string `json:"baseURLibit"` 28 | BaseURLrarbg string `json:"baseURLrarbg"` 29 | BaseURLrd string `json:"baseURLrd"` 30 | BaseURLad string `json:"baseURLad"` 31 | BaseURLpm string `json:"baseURLpm"` 32 | LogLevel string `json:"logLevel"` 33 | LogEncoding string `json:"logEncoding"` 34 | LogFoundTorrents bool `json:"logFoundTorrents"` 35 | RootURL string `json:"rootURL"` 36 | ExtraHeadersXD []string `json:"extraHeadersXD"` 37 | SocksProxyAddrTPB string `json:"socksProxyAddrTPB"` 38 | WebConfigurePath string `json:"webConfigurePath"` 39 | IMDB2metaAddr string `json:"imdb2metaAddr"` 40 | UseOAUTH2 bool `json:"useOAUTH2"` 41 | OAUTH2authorizeURLrd string `json:"oauth2authURLrd"` 42 | OAUTH2authorizeURLpm string `json:"oauth2authURLpm"` 43 | OAUTH2tokenURLrd string `json:"oauth2tokenURLrd"` 44 | OAUTH2tokenURLpm string `json:"oauth2tokenURLpm"` 45 | OAUTH2clientIDrd string `json:"oauth2clientIDrd"` 46 | OAUTH2clientIDpm string `json:"oauth2clientIDpm"` 47 | OAUTH2clientSecretRD string `json:"oauth2clientSecretRD"` 48 | OAUTH2clientSecretPM string `json:"oauth2clientSecretPM"` 49 | OAUTH2encryptionKey string `json:"oauth2encryptionKey"` 50 | ForwardOriginIP bool `json:"forwardOriginIP"` 51 | EnvPrefix string `json:"envPrefix"` 52 | } 53 | 54 | func parseConfig(logger *zap.Logger) config { 55 | result := config{} 56 | 57 | // Flags 58 | var ( 59 | bindAddr = flag.String("bindAddr", "localhost", `Local interface address to bind to. "localhost" only allows access from the local host. "0.0.0.0" binds to all network interfaces.`) 60 | port = flag.Int("port", 8080, "Port to listen on") 61 | baseURL = flag.String("baseURL", "http://localhost:8080", "Base URL of this service. It's used in a stream URL that's delivered to Stremio and later used to redirect to RealDebrid, AllDebrid and Premiumize. If you enable OAuth2 handling this will also be used for the redirects and to determine whether the state cookie is a secure one or not.") 62 | storagePath = flag.String("storagePath", "", `Path for storing the data of the persistent DB which stores torrent results. An empty value will lead to 'os.UserCacheDir()+"/deflix-stremio/badger"'.`) 63 | maxAgeTorrents = flag.Duration("maxAgeTorrents", 7*24*time.Hour, "Max age of cache entries for torrents found per IMDb ID. The format must be acceptable by Go's 'time.ParseDuration()', for example \"24h\". Default is 7 days.") 64 | cachePath = flag.String("cachePath", "", `Path for loading persisted caches on startup and persisting the current cache in regular intervals. An empty value will lead to 'os.UserCacheDir()+"/deflix-stremio/cache"'.`) 65 | cacheAgeXD = flag.Duration("cacheAgeXD", 24*time.Hour, "Max age of cache entries for instant availability responses from RealDebrid, AllDebrid and Premiumize. The format must be acceptable by Go's 'time.ParseDuration()', for example \"24h\".") 66 | redisAddr = flag.String("redisAddr", "", `Redis host and port, for example "localhost:6379". It's used for the redirect and stream cache. Keep empty to use in-memory go-cache.`) 67 | redisCreds = flag.String("redisCreds", "", `Credentials for Redis. Password for Redis version 5 and older, username and password for Redis version 6 and newer. Use the colon character (":") for separating username and password. This implies you can't use a colon in the password when using Redis version 5 or older.`) 68 | baseURLyts = flag.String("baseURLyts", "https://yts.mx", "Base URL for YTS") 69 | baseURLtpb = flag.String("baseURLtpb", "https://apibay.org", "Base URL for the TPB API") 70 | baseURL1337x = flag.String("baseURL1337x", "https://1337x.to", "Base URL for 1337x") 71 | baseURLibit = flag.String("baseURLibit", "https://ibit.am", "Base URL for ibit") 72 | baseURLrarbg = flag.String("baseURLrarbg", "https://torrentapi.org", "Base URL for RARBG") 73 | baseURLrd = flag.String("baseURLrd", "https://api.real-debrid.com", "Base URL for RealDebrid") 74 | baseURLad = flag.String("baseURLad", "https://api.alldebrid.com", "Base URL for AllDebrid") 75 | baseURLpm = flag.String("baseURLpm", "https://www.premiumize.me/api", "Base URL for Premiumize") 76 | logLevel = flag.String("logLevel", "debug", `Log level to show only logs with the given and more severe levels. Can be "debug", "info", "warn", "error".`) 77 | logEncoding = flag.String("logEncoding", "console", `Log encoding. Can be "console" or "json", where "json" makes more sense when using centralized logging solutions like ELK, Graylog or Loki.`) 78 | logFoundTorrents = flag.Bool("logFoundTorrents", false, "Set to true to log each single torrent that was found by one of the torrent site clients (with DEBUG level)") 79 | rootURL = flag.String("rootURL", "https://www.deflix.tv", "Redirect target for the root") 80 | extraHeadersXD = flag.String("extraHeadersXD", "", `Additional HTTP request headers to set for requests to RealDebrid, AllDebrid and Premiumize, in a format like "X-Foo: bar", separated by newline characters ("\n")`) 81 | socksProxyAddrTPB = flag.String("socksProxyAddrTPB", "", "SOCKS5 proxy address for accessing TPB, required for accessing TPB via the TOR network (where \"127.0.0.1:9050\" would be typical value)") 82 | webConfigurePath = flag.String("webConfigurePath", "", "Path to the directory with web files for the '/configure' endpoint. If empty, files compiled into the binary will be used") 83 | imdb2metaAddr = flag.String("imdb2metaAddr", "", "Address of the imdb2meta gRPC server. Won't be used if empty.") 84 | useOAUTH2 = flag.Bool("useOAUTH2", false, "Flag for indicating whether to use OAuth2 for Premiumize authorization. This leads to a different configuration webpage that doesn't require API keys. It requires a client ID to be configured.") 85 | oauth2authURLrd = flag.String("oauth2authURLrd", "https://api.real-debrid.com/oauth/v2/auth", "URL of the OAuth2 authorization endpoint of RealDebrid") 86 | oauth2authURLpm = flag.String("oauth2authURLpm", "https://www.premiumize.me/authorize", "URL of the OAuth2 authorization endpoint of Premiumize") 87 | oauth2tokenURLrd = flag.String("oauth2tokenURLrd", "https://api.real-debrid.com/oauth/v2/token", "URL of the OAuth2 token endpoint of RealDebrid") 88 | oauth2tokenURLpm = flag.String("oauth2tokenURLpm", "https://www.premiumize.me/token", "URL of the OAuth2 token endpoint of Premiumize") 89 | oauth2clientIDrd = flag.String("oauth2clientIDrd", "", "Client ID for deflix-stremio on RealDebrid") 90 | oauth2clientIDpm = flag.String("oauth2clientIDpm", "", "Client ID for deflix-stremio on Premiumize") 91 | oauth2clientSecretRD = flag.String("oauth2clientSecretRD", "", "Client secret for deflix-stremio on RealDebrid") 92 | oauth2clientSecretPM = flag.String("oauth2clientSecretPM", "", "Client secret for deflix-stremio on Premiumize") 93 | oauth2encryptionKey = flag.String("oauth2encryptionKey", "", "OAuth2 data encryption key") 94 | forwardOriginIP = flag.Bool("forwardOriginIP", false, `Forward the user's original IP address to RealDebrid and Premiumize. The first "X-Forwarded-For" entry will be used.`) 95 | envPrefix = flag.String("envPrefix", "", "Prefix for environment variables") 96 | ) 97 | 98 | flag.Parse() 99 | 100 | if *envPrefix != "" && !strings.HasSuffix(*envPrefix, "_") { 101 | *envPrefix += "_" 102 | } 103 | result.EnvPrefix = *envPrefix 104 | 105 | // Only overwrite the values by their env var counterparts that have not been set (and that *are* set via env var). 106 | var err error 107 | if !isArgSet("bindAddr") { 108 | if val, ok := os.LookupEnv(*envPrefix + "BIND_ADDR"); ok { 109 | *bindAddr = val 110 | } 111 | } 112 | result.BindAddr = *bindAddr 113 | 114 | if !isArgSet("port") { 115 | if val, ok := os.LookupEnv(*envPrefix + "PORT"); ok { 116 | if *port, err = strconv.Atoi(val); err != nil { 117 | logger.Fatal("Couldn't convert environment variable from string to int", zap.Error(err), zap.String("envVar", "PORT")) 118 | } 119 | } 120 | } 121 | result.Port = *port 122 | 123 | if !isArgSet("baseURL") { 124 | if val, ok := os.LookupEnv(*envPrefix + "BASE_URL"); ok { 125 | *baseURL = val 126 | } 127 | } 128 | result.BaseURL = *baseURL 129 | 130 | if !isArgSet("storagePath") { 131 | if val, ok := os.LookupEnv(*envPrefix + "STORAGE_PATH"); ok { 132 | *storagePath = val 133 | } 134 | } 135 | result.StoragePath = *storagePath 136 | 137 | if !isArgSet("maxAgeTorrents") { 138 | if val, ok := os.LookupEnv(*envPrefix + "MAX_AGE_TORRENTS"); ok { 139 | if *maxAgeTorrents, err = time.ParseDuration(val); err != nil { 140 | logger.Fatal("Couldn't convert environment variable from string to time.Duration", zap.Error(err), zap.String("envVar", "CACHE_AGE_TORRENTS")) 141 | } 142 | } 143 | } 144 | result.MaxAgeTorrents = *maxAgeTorrents 145 | 146 | if !isArgSet("cachePath") { 147 | if val, ok := os.LookupEnv(*envPrefix + "CACHE_PATH"); ok { 148 | *cachePath = val 149 | } 150 | } 151 | result.CachePath = *cachePath 152 | 153 | if !isArgSet("cacheAgeXD") { 154 | if val, ok := os.LookupEnv(*envPrefix + "CACHE_AGE_XD"); ok { 155 | if *cacheAgeXD, err = time.ParseDuration(val); err != nil { 156 | logger.Fatal("Couldn't convert environment variable from string to time.Duration", zap.Error(err), zap.String("envVar", "CACHE_AGE_XD")) 157 | } 158 | } 159 | } 160 | result.CacheAgeXD = *cacheAgeXD 161 | 162 | if !isArgSet("redisAddr") { 163 | if val, ok := os.LookupEnv(*envPrefix + "REDIS_ADDR"); ok { 164 | *redisAddr = val 165 | } 166 | } 167 | result.RedisAddr = *redisAddr 168 | 169 | if !isArgSet("redisCreds") { 170 | if val, ok := os.LookupEnv(*envPrefix + "REDIS_CREDS"); ok { 171 | *redisCreds = val 172 | } 173 | } 174 | result.RedisCreds = *redisCreds 175 | 176 | if !isArgSet("baseURLyts") { 177 | if val, ok := os.LookupEnv(*envPrefix + "BASE_URL_YTS"); ok { 178 | *baseURLyts = val 179 | } 180 | } 181 | result.BaseURLyts = *baseURLyts 182 | 183 | if !isArgSet("baseURLtpb") { 184 | if val, ok := os.LookupEnv(*envPrefix + "BASE_URL_TPB"); ok { 185 | *baseURLtpb = val 186 | } 187 | } 188 | result.BaseURLtpb = *baseURLtpb 189 | 190 | if !isArgSet("baseURL1337x") { 191 | if val, ok := os.LookupEnv(*envPrefix + "BASE_URL_1337X"); ok { 192 | *baseURL1337x = val 193 | } 194 | } 195 | result.BaseURL1337x = *baseURL1337x 196 | 197 | if !isArgSet("baseURLibit") { 198 | if val, ok := os.LookupEnv(*envPrefix + "BASE_URL_IBIT"); ok { 199 | *baseURLibit = val 200 | } 201 | } 202 | result.BaseURLibit = *baseURLibit 203 | 204 | if !isArgSet("baseURLrarbg") { 205 | if val, ok := os.LookupEnv(*envPrefix + "BASE_URL_RARBG"); ok { 206 | *baseURLrarbg = val 207 | } 208 | } 209 | result.BaseURLrarbg = *baseURLrarbg 210 | 211 | if !isArgSet("baseURLrd") { 212 | if val, ok := os.LookupEnv(*envPrefix + "BASE_URL_RD"); ok { 213 | *baseURLrd = val 214 | } 215 | } 216 | result.BaseURLrd = *baseURLrd 217 | 218 | if !isArgSet("baseURLad") { 219 | if val, ok := os.LookupEnv(*envPrefix + "BASE_URL_AD"); ok { 220 | *baseURLad = val 221 | } 222 | } 223 | result.BaseURLad = *baseURLad 224 | 225 | if !isArgSet("baseURLpm") { 226 | if val, ok := os.LookupEnv(*envPrefix + "BASE_URL_PM"); ok { 227 | *baseURLpm = val 228 | } 229 | } 230 | result.BaseURLpm = *baseURLpm 231 | 232 | if !isArgSet("logLevel") { 233 | if val, ok := os.LookupEnv(*envPrefix + "LOG_LEVEL"); ok { 234 | *logLevel = val 235 | } 236 | } 237 | result.LogLevel = *logLevel 238 | 239 | if !isArgSet("logEncoding") { 240 | if val, ok := os.LookupEnv(*envPrefix + "LOG_ENCODING"); ok { 241 | *logEncoding = val 242 | } 243 | } 244 | result.LogEncoding = *logEncoding 245 | 246 | if !isArgSet("logFoundTorrents") { 247 | if val, ok := os.LookupEnv(*envPrefix + "LOG_FOUND_TORRENTS"); ok { 248 | if *logFoundTorrents, err = strconv.ParseBool(val); err != nil { 249 | logger.Fatal("Couldn't convert environment variable from string to bool", zap.Error(err), zap.String("envVar", "LOG_FOUND_TORRENTS")) 250 | } 251 | } 252 | } 253 | result.LogFoundTorrents = *logFoundTorrents 254 | 255 | if !isArgSet("rootURL") { 256 | if val, ok := os.LookupEnv(*envPrefix + "ROOT_URL"); ok { 257 | *rootURL = val 258 | } 259 | } 260 | result.RootURL = *rootURL 261 | 262 | if !isArgSet("extraHeadersRD") { 263 | if val, ok := os.LookupEnv(*envPrefix + "EXTRA_HEADERS_RD"); ok { 264 | *extraHeadersXD = val 265 | } 266 | } 267 | if *extraHeadersXD != "" { 268 | headers := strings.Split(*extraHeadersXD, "\n") 269 | for _, header := range headers { 270 | header = strings.TrimSpace(header) 271 | if header != "" { 272 | result.ExtraHeadersXD = append(result.ExtraHeadersXD, header) 273 | } 274 | } 275 | } 276 | 277 | if !isArgSet("socksProxyAddrTPB") { 278 | if val, ok := os.LookupEnv(*envPrefix + "SOCKS_PROXY_ADDR_TPB"); ok { 279 | *socksProxyAddrTPB = val 280 | } 281 | } 282 | result.SocksProxyAddrTPB = *socksProxyAddrTPB 283 | 284 | if !isArgSet("webConfigurePath") { 285 | if val, ok := os.LookupEnv(*envPrefix + "WEB_CONFIGURE_PATH"); ok { 286 | *webConfigurePath = val 287 | } 288 | } 289 | result.WebConfigurePath = *webConfigurePath 290 | 291 | if !isArgSet("imdb2metaAddr") { 292 | if val, ok := os.LookupEnv(*envPrefix + "IMDB_2_META_ADDR"); ok { 293 | *imdb2metaAddr = val 294 | } 295 | } 296 | result.IMDB2metaAddr = *imdb2metaAddr 297 | 298 | if !isArgSet("useOAUTH2") { 299 | if val, ok := os.LookupEnv(*envPrefix + "USE_OAUTH2"); ok { 300 | if *useOAUTH2, err = strconv.ParseBool(val); err != nil { 301 | logger.Fatal("Couldn't convert environment variable from string to bool", zap.Error(err), zap.String("envVar", "USE_OAUTH2")) 302 | } 303 | } 304 | } 305 | result.UseOAUTH2 = *useOAUTH2 306 | 307 | if !isArgSet("oauth2authURLrd") { 308 | if val, ok := os.LookupEnv(*envPrefix + "OAUTH2_AUTH_URL_RD"); ok { 309 | *oauth2authURLrd = val 310 | } 311 | } 312 | result.OAUTH2authorizeURLrd = *oauth2authURLrd 313 | 314 | if !isArgSet("oauth2authURLpm") { 315 | if val, ok := os.LookupEnv(*envPrefix + "OAUTH2_AUTH_URL_PM"); ok { 316 | *oauth2authURLpm = val 317 | } 318 | } 319 | result.OAUTH2authorizeURLpm = *oauth2authURLpm 320 | 321 | if !isArgSet("oauth2tokenURLrd") { 322 | if val, ok := os.LookupEnv(*envPrefix + "OAUTH2_TOKEN_URL_RD"); ok { 323 | *oauth2tokenURLrd = val 324 | } 325 | } 326 | result.OAUTH2tokenURLrd = *oauth2tokenURLrd 327 | 328 | if !isArgSet("oauth2tokenURLpm") { 329 | if val, ok := os.LookupEnv(*envPrefix + "OAUTH2_TOKEN_URL_PM"); ok { 330 | *oauth2tokenURLpm = val 331 | } 332 | } 333 | result.OAUTH2tokenURLpm = *oauth2tokenURLpm 334 | 335 | if !isArgSet("oauth2clientIDrd") { 336 | if val, ok := os.LookupEnv(*envPrefix + "OAUTH2_CLIENT_ID_RD"); ok { 337 | *oauth2clientIDrd = val 338 | } 339 | } 340 | result.OAUTH2clientIDrd = *oauth2clientIDrd 341 | 342 | if !isArgSet("oauth2clientIDpm") { 343 | if val, ok := os.LookupEnv(*envPrefix + "OAUTH2_CLIENT_ID_PM"); ok { 344 | *oauth2clientIDpm = val 345 | } 346 | } 347 | result.OAUTH2clientIDpm = *oauth2clientIDpm 348 | 349 | if !isArgSet("oauth2clientSecretRD") { 350 | if val, ok := os.LookupEnv(*envPrefix + "OAUTH2_CLIENT_SECRET_RD"); ok { 351 | *oauth2clientSecretRD = val 352 | } 353 | } 354 | result.OAUTH2clientSecretRD = *oauth2clientSecretRD 355 | 356 | if !isArgSet("oauth2clientSecretPM") { 357 | if val, ok := os.LookupEnv(*envPrefix + "OAUTH2_CLIENT_SECRET_PM"); ok { 358 | *oauth2clientSecretPM = val 359 | } 360 | } 361 | result.OAUTH2clientSecretPM = *oauth2clientSecretPM 362 | 363 | if !isArgSet("oauth2encryptionKey") { 364 | if val, ok := os.LookupEnv(*envPrefix + "OAUTH2_ENCRYPTION_KEY"); ok { 365 | *oauth2encryptionKey = val 366 | } 367 | } 368 | result.OAUTH2encryptionKey = *oauth2encryptionKey 369 | 370 | if !isArgSet("forwardOriginIP") { 371 | if val, ok := os.LookupEnv(*envPrefix + "FORWARD_ORIGIN_IP"); ok { 372 | if *forwardOriginIP, err = strconv.ParseBool(val); err != nil { 373 | logger.Fatal("Couldn't convert environment variable from string to bool", zap.Error(err), zap.String("envVar", "FORWARD_ORIGIN_IP")) 374 | } 375 | } 376 | } 377 | result.ForwardOriginIP = *forwardOriginIP 378 | 379 | return result 380 | } 381 | 382 | func (c *config) validate(logger *zap.Logger) { 383 | if c.StoragePath == "" { 384 | userCacheDir, err := os.UserCacheDir() 385 | if err != nil { 386 | logger.Fatal("Couldn't determine user cache directory via `os.UserCacheDir()`", zap.Error(err)) 387 | } 388 | // Add two levels, because even if we're in `os.UserCacheDir()`, on Windows that's for example `C:\Users\John\AppData\Local` 389 | c.StoragePath = filepath.Join(userCacheDir, "deflix-stremio/badger") 390 | } else { 391 | c.StoragePath = filepath.Clean(c.StoragePath) 392 | } 393 | // If the dir doesn't exist, BadgerDB creates it when writing its DB files. 394 | 395 | if c.CachePath == "" { 396 | userCacheDir, err := os.UserCacheDir() 397 | if err != nil { 398 | logger.Fatal("Couldn't determine user cache directory via `os.UserCacheDir()`", zap.Error(err)) 399 | } 400 | // Add two levels, because even if we're in `os.UserCacheDir()`, on Windows that's for example `C:\Users\John\AppData\Local` 401 | c.CachePath = filepath.Join(userCacheDir, "deflix-stremio/cache") 402 | } else { 403 | c.CachePath = filepath.Clean(c.CachePath) 404 | } 405 | // If the dir doesn't exist, it's created when the files are written. 406 | 407 | if c.UseOAUTH2 && 408 | (c.OAUTH2authorizeURLpm == "" || c.OAUTH2clientIDpm == "" || c.OAUTH2clientSecretPM == "" || c.OAUTH2tokenURLpm == "" || 409 | c.OAUTH2authorizeURLrd == "" || c.OAUTH2clientIDrd == "" || c.OAUTH2clientSecretRD == "" || c.OAUTH2tokenURLrd == "" || 410 | c.OAUTH2encryptionKey == "") { 411 | logger.Fatal("Using OAuth2 requires setting all OAuth2 config values") 412 | } 413 | 414 | if c.LogEncoding != "console" && c.LogEncoding != "json" { 415 | logger.Fatal(`logEncoding must be one of "console" or "json"`, zap.String("logEncoding", c.LogEncoding)) 416 | } 417 | } 418 | 419 | // isArgSet returns true if the argument you're looking for is actually set as command line argument. 420 | // Pass without "-" prefix. 421 | func isArgSet(arg string) bool { 422 | found := false 423 | flag.Visit(func(f *flag.Flag) { 424 | if f.Name == arg { 425 | found = true 426 | } 427 | }) 428 | return found 429 | } 430 | -------------------------------------------------------------------------------- /cmd/deflix-stremio/handlers.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "crypto/sha256" 6 | "encoding/base64" 7 | "fmt" 8 | "net/url" 9 | "strconv" 10 | "strings" 11 | "sync" 12 | "time" 13 | 14 | "github.com/gofiber/fiber/v2" 15 | gocache "github.com/patrickmn/go-cache" 16 | "go.uber.org/zap" 17 | 18 | "github.com/deflix-tv/go-debrid/alldebrid" 19 | "github.com/deflix-tv/go-debrid/premiumize" 20 | "github.com/deflix-tv/go-debrid/realdebrid" 21 | "github.com/deflix-tv/go-stremio" 22 | "github.com/deflix-tv/imdb2torrent" 23 | ) 24 | 25 | const ( 26 | bigBuckBunnyMagnet = `magnet:?xt=urn:btih:dd8255ecdc7ca55fb0bbf81323d87062db1f6d1c&dn=Big+Buck+Bunny&tr=udp%3A%2F%2Fexplodie.org%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.empire-js.us%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2F&xs=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fbig-buck-bunny.torrent` 27 | ) 28 | 29 | // goCacher is a go-cache-compatible interface. 30 | type goCacher interface { 31 | Set(string, interface{}, time.Duration) 32 | Get(string) (interface{}, bool) 33 | } 34 | 35 | func createStreamHandler(config config, searchClient *imdb2torrent.Client, rdClient *realdebrid.Client, adClient *alldebrid.Client, pmClient *premiumize.Client, redirectCache goCacher, isTVShow bool, logger *zap.Logger) stremio.StreamHandler { 36 | return func(ctx context.Context, id string, userDataIface interface{}) ([]stremio.StreamItem, error) { 37 | var imdbID string 38 | var season int 39 | var episode int 40 | var err error 41 | if isTVShow { 42 | idParts := strings.Split(id, ":") 43 | if len(idParts) != 3 { 44 | logger.Info("Stream handler for TV shows called without exactly 3 ID parts", zap.String("id", id)) 45 | return nil, stremio.BadRequest 46 | } 47 | imdbID = idParts[0] 48 | season, err = strconv.Atoi(idParts[1]) 49 | if err != nil { 50 | logger.Info("Couldn't convert season to int", zap.String("id", id)) 51 | return nil, stremio.BadRequest 52 | } 53 | episode, err = strconv.Atoi(idParts[2]) 54 | if err != nil { 55 | logger.Info("Couldn't convert episode to int", zap.String("id", id)) 56 | return nil, stremio.BadRequest 57 | } 58 | } else { 59 | imdbID = id 60 | } 61 | 62 | var torrents []imdb2torrent.Result 63 | if isTVShow { 64 | torrents, err = searchClient.FindTVShow(ctx, imdbID, season, episode) 65 | } else { 66 | torrents, err = searchClient.FindMovie(ctx, imdbID) 67 | } 68 | if err != nil { 69 | logger.Warn("Couldn't find magnets", zap.Error(err)) 70 | return nil, fmt.Errorf("Couldn't find magnets: %w", err) 71 | } else if len(torrents) == 0 { 72 | logger.Info("No magnets found") 73 | return nil, stremio.NotFound 74 | } 75 | 76 | // Parse userData. 77 | // No need to check if the interface is a string or if the decoding worked, because the token middleware does that already. 78 | udString := userDataIface.(string) 79 | userData, _ := decodeUserData(udString, logger) 80 | 81 | // Filter out the ones that are not available 82 | var infoHashes []string 83 | for _, torrent := range torrents { 84 | infoHashes = append(infoHashes, torrent.InfoHash) 85 | } 86 | var debridID string 87 | var availableInfoHashes []string 88 | keyOrToken := ctx.Value("deflix_keyOrToken").(string) 89 | if userData.RDtoken != "" || userData.RDoauth2 != "" { 90 | debridID = "rd" 91 | availableInfoHashes = rdClient.CheckInstantAvailability(ctx, keyOrToken, infoHashes...) 92 | } else if userData.ADkey != "" { 93 | debridID = "ad" 94 | availableInfoHashes = adClient.CheckInstantAvailability(ctx, keyOrToken, infoHashes...) 95 | } else { 96 | debridID = "pm" 97 | availableInfoHashes = pmClient.CheckInstantAvailability(ctx, keyOrToken, infoHashes...) 98 | } 99 | if len(availableInfoHashes) == 0 { 100 | // TODO: queue for download on the debrid service, or log somewhere for an asynchronous process to go through them and queue them? 101 | logger.Info("None of the found torrents are instantly available on the debrid service") 102 | return nil, stremio.NotFound 103 | } 104 | // https://github.com/golang/go/wiki/SliceTricks#filter-in-place 105 | n := 0 106 | for _, torrent := range torrents { 107 | for _, availableInfoHash := range availableInfoHashes { 108 | if torrent.InfoHash == availableInfoHash { 109 | torrents[n] = torrent 110 | n++ 111 | break 112 | } 113 | } 114 | } 115 | torrents = torrents[:n] 116 | 117 | // Note: The torrents slice is guaranteed to not be empty at this point, because it already contained non-duplicate info hashes and then only unavailable ones were filtered and then a `len(availableInfoHashes) == 0` was done. 118 | 119 | // Separate all torrent results into a 720p, 1080p, 1080p 10bit, 2160p and 2160p 10bit list, so we can offer the user one stream for each quality now (or maybe just for one quality if there's no torrent for the other), cache the torrents for each apiToken-ID-quality combination and later (at the redirect endpoint) go through the respective torrent list to turn it into a streamable video URL via RealDebrid. 120 | var torrents720p []imdb2torrent.Result 121 | var torrents1080p []imdb2torrent.Result 122 | var torrents1080p10bit []imdb2torrent.Result 123 | var torrents2160p []imdb2torrent.Result 124 | var torrents2160p10bit []imdb2torrent.Result 125 | for _, torrent := range torrents { 126 | if strings.HasPrefix(torrent.Quality, "720p") { 127 | torrents720p = append(torrents720p, torrent) 128 | } else if strings.HasPrefix(torrent.Quality, "1080p") && strings.Contains(torrent.Quality, "10bit") { 129 | torrents1080p10bit = append(torrents1080p10bit, torrent) 130 | } else if strings.HasPrefix(torrent.Quality, "1080p") { 131 | torrents1080p = append(torrents1080p, torrent) 132 | } else if strings.HasPrefix(torrent.Quality, "2160p") && strings.Contains(torrent.Quality, "10bit") { 133 | torrents2160p10bit = append(torrents2160p10bit, torrent) 134 | } else if strings.HasPrefix(torrent.Quality, "2160p") { 135 | torrents2160p = append(torrents2160p, torrent) 136 | } else { 137 | logger.Warn("Unknown quality, can't sort into one of the torrent lists", zap.String("quality", torrent.Quality)) 138 | } 139 | } 140 | 141 | // Cache results to make this data available in the redirect handler. It will pick the first torrent from the list and convert it via RD / AD / PM, or pick the next if the previous didn't work. 142 | // There's no need to cache this for a specific user, but it MUST be cached per debrid service - otherwise during concurrent requests, when a RD user goes to the redirect endpoint it could fetch torrents from the cache which are only available on AD / PM leading to a worse experience for the RD user. 143 | // This cache *must* be a cache where items aren't evicted when the cache is full, because otherwise if the cache is full and two users fetch available streams, then the second one could lead to the first cache item being evicted before the first user clicks on the stream, leading to an error inside the redirect handler after he clicks on the stream. 144 | redirectCache.Set(id+"-"+debridID+"-720p", torrents720p, redirectExpiration) 145 | redirectCache.Set(id+"-"+debridID+"-1080p", torrents1080p, redirectExpiration) 146 | redirectCache.Set(id+"-"+debridID+"-1080p.10bit", torrents1080p10bit, redirectExpiration) 147 | redirectCache.Set(id+"-"+debridID+"-2160p", torrents2160p, redirectExpiration) 148 | redirectCache.Set(id+"-"+debridID+"-2160p.10bit", torrents2160p10bit, redirectExpiration) 149 | 150 | // We already respond with several URLs (one for each quality, as long as we have torrents for the different qualities), but they point to our server for now. 151 | // Only when the user clicks on a stream and arrives at our redirect endpoint, we go through the list of torrents for the selected quality and try to convert them into a streamable video URL via RealDebrid. 152 | // There it should usually work for the first torrent we try, because we already checked the "instant availability" on RealDebrid here. If the "instant availability" info is stale (because we cached it), the next torrent will be used. 153 | var streams []stremio.StreamItem 154 | if len(torrents720p) > 0 { 155 | stream := createStreamItem(ctx, config, udString, id+"-"+debridID+"-720p", "720p", torrents720p) 156 | streams = append(streams, stream) 157 | } 158 | if len(torrents1080p) > 0 { 159 | stream := createStreamItem(ctx, config, udString, id+"-"+debridID+"-1080p", "1080p", torrents1080p) 160 | streams = append(streams, stream) 161 | } 162 | if len(torrents1080p10bit) > 0 { 163 | stream := createStreamItem(ctx, config, udString, id+"-"+debridID+"-1080p.10bit", "1080p 10bit", torrents1080p10bit) 164 | streams = append(streams, stream) 165 | } 166 | if len(torrents2160p) > 0 { 167 | stream := createStreamItem(ctx, config, udString, id+"-"+debridID+"-2160p", "2160p", torrents2160p) 168 | streams = append(streams, stream) 169 | } 170 | if len(torrents2160p10bit) > 0 { 171 | stream := createStreamItem(ctx, config, udString, id+"-"+debridID+"-2160p.10bit", "2160p 10bit", torrents2160p10bit) 172 | streams = append(streams, stream) 173 | } 174 | 175 | return streams, nil 176 | } 177 | } 178 | 179 | func createStreamItem(ctx context.Context, config config, encodedUserData string, redirectID, quality string, torrents []imdb2torrent.Result) stremio.StreamItem { 180 | // Path escaping required for TV shows, which contain ":" 181 | redirectID = url.PathEscape(redirectID) 182 | stream := stremio.StreamItem{ 183 | URL: config.BaseURL + "/" + encodedUserData + "/redirect/" + redirectID, 184 | // Stremio docs recommend to use the stream quality as title. 185 | // See https://github.com/Stremio/stremio-addon-sdk/blob/ddaa3b80def8a44e553349734dd02ec9c3fea52c/docs/api/responses/stream.md#additional-properties-to-provide-information--behaviour-flags 186 | Title: quality, 187 | } 188 | // We can only set the exact quality string if there's only one torrent. 189 | // Otherwise maybe the upcoming RealDebrid conversion fails for one torrent, but works for the next, which has a slightly different quality string. 190 | if len(torrents) == 1 { 191 | stream.Title = torrents[0].Quality 192 | } 193 | 194 | // Create and assign lock object. 195 | // Note: A lock object might exist already from a previous stream handler call, or even after a service restart when a user first resumed a movie (and so called the redirect handler first) before calling the stream handler for the same movie again. 196 | redirectLockMapLock.Lock() 197 | defer redirectLockMapLock.Unlock() 198 | if _, ok := redirectLock[redirectID]; !ok { 199 | redirectLock[redirectID] = &sync.Mutex{} 200 | } 201 | 202 | return stream 203 | } 204 | 205 | func createRedirectHandler(redirectCache, streamCache goCacher, rdClient *realdebrid.Client, adClient *alldebrid.Client, pmClient *premiumize.Client, forwardOriginIP bool, logger *zap.Logger) fiber.Handler { 206 | return func(c *fiber.Ctx) error { 207 | logger.Debug("redirectHandler called", zap.String("request", fmt.Sprintf("%+v", c.Request()))) 208 | 209 | udString := c.Params("userData") 210 | redirectID := c.Params("id", "") 211 | if redirectID == "" { 212 | return c.SendStatus(fiber.StatusNotFound) 213 | } 214 | zapFieldRedirectID := zap.String("redirectID", redirectID) 215 | 216 | // Before we look into the cache, we need to set a lock so that concurrent calls to this endpoint (including the redirectID) don't unnecessarily lead to the full sharade of RD requests again, only because the first handling of the request wasn't fast enough to fill the cache. 217 | // The lock objects are created in the stream handler. But if the service was restarted the map is empty. So we need to create lock objects in that case for the users arriving at the redirect handler without having been at the stream handler after a service restart. 218 | redirectLockMapLock.Lock() 219 | if _, ok := redirectLock[redirectID]; !ok { 220 | redirectLock[redirectID] = &sync.Mutex{} 221 | } 222 | redirectLockMapLock.Unlock() 223 | redirectLock[redirectID].Lock() 224 | defer redirectLock[redirectID].Unlock() 225 | 226 | // Check stream cache first. 227 | // Here we don't get the data that's passed from the stream handler to this redirect handler, but instead the the RD / AD / PM HTTP stream URL, which is cached after it was converted in a previous call. 228 | // This cache is important, because for a single click on a stream in Stremio there are multiple requests to this endpoint in a short timeframe. 229 | // This cache is also useful for when a user resumes his stream via Stremio after closing it. In this case the same RealDebrid HTTP stream must be delivered (or even if it would work with another one, using the same one would be beneficial). 230 | // Because the actual stream URLs are cached here, it MUST be user-specific! No need to use the full userData string though - we just hash it and use that as "user identifier". 231 | // TODO: Regarding stream resuming: We don't know how long RD / AD / PM HTTP stream URLs are valid. If it's shorter, we can shorten this as well. Also see similar TODO comment in main.go file. 232 | userHash := sha256.Sum256([]byte(udString)) 233 | userHashEncoded := base64.RawURLEncoding.EncodeToString(userHash[:]) 234 | streamCacheID := userHashEncoded + "-" + redirectID 235 | if streamURLiface, found := streamCache.Get(streamCacheID); found { 236 | logger.Debug("Hit stream cache", zapFieldRedirectID) 237 | if streamURLitem, ok := streamURLiface.(cacheItem); !ok { 238 | logger.Error("Stream cache item couldn't be cast into cacheItem", zap.String("cacheItemType", fmt.Sprintf("%T", streamURLiface)), zapFieldRedirectID) 239 | } else if len(streamURLitem.Value) == 0 && time.Since(streamURLitem.Created) > time.Minute { 240 | logger.Warn("The torrents for this stream where previously tried to be converted into a stream but it didn't work. This was more than one minute ago though, so we'll try again.", zapFieldRedirectID) 241 | } else if len(streamURLitem.Value) == 0 { 242 | logger.Warn("The torrents for this stream where previously tried to be converted into a stream but it didn't work", zapFieldRedirectID) 243 | return c.SendStatus(fiber.StatusNotFound) 244 | } else { 245 | logger.Debug("Responding with redirect to stream", zap.String("redirectLocation", streamURLitem.Value), zapFieldRedirectID) 246 | c.Set("Location", streamURLitem.Value) 247 | return c.SendStatus(fiber.StatusMovedPermanently) 248 | } 249 | } 250 | 251 | // Here we get the data from the cache that the stream handler filled. 252 | torrentsIface, found := redirectCache.Get(redirectID) 253 | if !found { 254 | logger.Warn("No torrents cache item found, did 24h pass?", zapFieldRedirectID) 255 | // TODO: Just run the same stuff the stream handler does! This way we can drastically reduce the required cache time for the redirect cache, and the scraping doesn't really take long! Take care of concurrent requests - maybe lock! 256 | return c.SendStatus(fiber.StatusNotFound) 257 | } 258 | torrents, ok := torrentsIface.([]imdb2torrent.Result) 259 | if !ok { 260 | logger.Error("Torrents cache item couldn't be cast into []imdb2torrent.Result", zap.String("cacheItemType", fmt.Sprintf("%T", torrentsIface)), zapFieldRedirectID) 261 | return c.SendStatus(fiber.StatusInternalServerError) 262 | } 263 | // Parse userData. 264 | // No need to check if decoding worked, because the token middleware does that already. 265 | userData, _ := decodeUserData(udString, logger) 266 | var streamURL string 267 | var err error 268 | keyOrToken := c.Locals("deflix_keyOrToken").(string) 269 | if forwardOriginIP && len(c.IPs()) > 0 { 270 | c.Locals("debrid_originIP", c.IPs()[0]) 271 | } 272 | for _, torrent := range torrents { 273 | if userData.RDtoken != "" || userData.RDoauth2 != "" { 274 | streamURL, err = rdClient.GetStreamURL(c.Context(), torrent.MagnetURL, keyOrToken, userData.RDremote) 275 | } else if userData.ADkey != "" { 276 | streamURL, err = adClient.GetStreamURL(c.Context(), torrent.MagnetURL, keyOrToken) 277 | } else { 278 | streamURL, err = pmClient.GetStreamURL(c.Context(), torrent.MagnetURL, keyOrToken) 279 | } 280 | if err != nil { 281 | logger.Warn("Couldn't get stream URL", zap.Error(err), zapFieldRedirectID) 282 | } else { 283 | break 284 | } 285 | } 286 | 287 | // Fill cache, even if no actual video stream was found, because it seems to be the current state on RealDebrid 288 | streamURLitem := cacheItem{ 289 | Value: streamURL, 290 | Created: time.Now(), 291 | } 292 | streamCache.Set(streamCacheID, streamURLitem, streamExpiration) 293 | 294 | if streamURL == "" { 295 | return c.SendStatus(fiber.StatusNotFound) 296 | } 297 | 298 | logger.Debug("Responding with redirect to stream", zap.String("redirectLocation", streamURL), zapFieldRedirectID) 299 | c.Set("Location", streamURL) 300 | return c.SendStatus(fiber.StatusMovedPermanently) 301 | } 302 | } 303 | 304 | func createStatusHandler(magnetSearchers map[string]imdb2torrent.MagnetSearcher, rdClient *realdebrid.Client, adClient *alldebrid.Client, pmClient *premiumize.Client, goCaches map[string]*gocache.Cache, forwardOriginIP bool, logger *zap.Logger) fiber.Handler { 305 | return func(c *fiber.Ctx) error { 306 | logger.Debug("statusHandler called", zap.String("request", fmt.Sprintf("%+v", c.Request()))) 307 | 308 | imdbID := c.Query("imdbid", "") 309 | rdToken := c.Query("rdtoken", "") 310 | adKey := c.Query("adkey", "") 311 | pmKey := c.Query("pmkey", "") 312 | if imdbID == "" || rdToken == "" || adKey == "" || pmKey == "" { 313 | logger.Warn("\"/status\" was called without IMDb ID or RD API token or AD API key or Premiumize API key") 314 | return c.SendStatus(fiber.StatusBadRequest) 315 | } 316 | 317 | start := time.Now() 318 | res := "{\n" 319 | 320 | // Check magnet searchers 321 | 322 | res += "\t" + `"magnetSearchers": {` + "\n" 323 | // Lock for writing to the same string 324 | lock := sync.Mutex{} 325 | wg := sync.WaitGroup{} 326 | wg.Add(len(magnetSearchers)) 327 | for name, client := range magnetSearchers { 328 | go func(goName string, goClient imdb2torrent.MagnetSearcher) { 329 | defer wg.Done() 330 | if goClient.IsSlow() { 331 | res += "\t\t" + `"` + goName + `": "quick skip",` + "\n" 332 | return 333 | } 334 | startSearch := time.Now() 335 | results, err := goClient.FindMovie(c.Context(), imdbID) 336 | lock.Lock() 337 | defer lock.Unlock() 338 | res += "\t\t" + `"` + goName + `": {` + "\n" 339 | if err != nil { 340 | res += "\t\t\t" + `"err":"` + err.Error() + `",` + "\n" 341 | } else { 342 | resCount := len(results) 343 | res += "\t\t\t" + `"resCount":"` + strconv.Itoa(resCount) + `",` + "\n" 344 | if resCount > 0 { 345 | resExample := fmt.Sprintf("%+v", results[0]) 346 | resExample = strings.ReplaceAll(resExample, "\n", " ") 347 | res += "\t\t\t" + `"resExample":"` + resExample + `",` + "\n" 348 | } 349 | } 350 | durationSearchmillis := time.Since(startSearch).Milliseconds() 351 | res += "\t\t\t" + `"duration": "` + strconv.FormatInt(durationSearchmillis, 10) + `ms"` + "\n" 352 | res += "\t\t" + `},` + "\n" 353 | }(name, client) 354 | } 355 | wg.Wait() 356 | res = strings.TrimRight(res, ",\n") + "\n" 357 | res += "\t" + `},` + "\n" 358 | 359 | // Check debrid clients 360 | 361 | if forwardOriginIP && len(c.IPs()) > 0 { 362 | c.Locals("debrid_originIP", c.IPs()[0]) 363 | } 364 | 365 | // Check RD client 366 | 367 | res += "\t" + `"RD": {` + "\n" 368 | startRD := time.Now() 369 | streamURL, err := rdClient.GetStreamURL(c.Context(), bigBuckBunnyMagnet, rdToken, false) 370 | if err != nil { 371 | res += "\t\t" + `"err":"` + err.Error() + `",` + "\n" 372 | } else { 373 | res += "\t\t" + `"res":"` + streamURL + `",` + "\n" 374 | } 375 | durationRDmillis := time.Since(startRD).Milliseconds() 376 | res += "\t\t" + `"duration": "` + strconv.FormatInt(durationRDmillis, 10) + `ms"` + "\n" 377 | res += "\t" + `},` + "\n" 378 | 379 | // Check AD client 380 | 381 | res += "\t" + `"AD": {` + "\n" 382 | startAD := time.Now() 383 | streamURL, err = adClient.GetStreamURL(c.Context(), bigBuckBunnyMagnet, adKey) 384 | if err != nil { 385 | res += "\t\t" + `"err":"` + err.Error() + `",` + "\n" 386 | } else { 387 | res += "\t\t" + `"res":"` + streamURL + `",` + "\n" 388 | } 389 | durationADmillis := time.Since(startAD).Milliseconds() 390 | res += "\t\t" + `"duration": "` + strconv.FormatInt(durationADmillis, 10) + `ms"` + "\n" 391 | res += "\t" + `},` + "\n" 392 | 393 | // Check PM client 394 | 395 | res += "\t" + `"PM": {` + "\n" 396 | startPM := time.Now() 397 | streamURL, err = pmClient.GetStreamURL(c.Context(), bigBuckBunnyMagnet, pmKey) 398 | if err != nil { 399 | res += "\t\t" + `"err":"` + err.Error() + `",` + "\n" 400 | } else { 401 | res += "\t\t" + `"res":"` + streamURL + `",` + "\n" 402 | } 403 | durationPMmillis := time.Since(startPM).Milliseconds() 404 | res += "\t\t" + `"duration": "` + strconv.FormatInt(durationPMmillis, 10) + `ms"` + "\n" 405 | res += "\t" + `},` + "\n" 406 | 407 | // Check caches 408 | 409 | res += "\t" + `"caches": {` + "\n" 410 | for name, cache := range goCaches { 411 | res += "\t\t" + `"` + name + `": {` + "\n" 412 | res += "\t\t\t" + `"Items": "` + strconv.Itoa(cache.ItemCount()) + `"` + ",\n" 413 | res += "\t\t" + `},` + "\n" 414 | } 415 | res = strings.TrimRight(res, ",\n") + "\n" 416 | res += "\t" + `},` + "\n" 417 | 418 | durationMillis := time.Since(start).Milliseconds() 419 | res += "\t" + `"duration": "` + strconv.FormatInt(durationMillis, 10) + `ms"` + "\n" 420 | res += "}" 421 | 422 | logger.Debug("Responding", zap.String("response", res)) 423 | c.Set("Content-Type", "application/json") 424 | return c.SendString(res) 425 | } 426 | } 427 | -------------------------------------------------------------------------------- /cmd/deflix-stremio/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "crypto/sha256" 6 | "encoding/json" 7 | "io/ioutil" 8 | "math/rand" 9 | "net/http" 10 | "path/filepath" 11 | "reflect" 12 | "strconv" 13 | "strings" 14 | "sync" 15 | "time" 16 | 17 | "github.com/dgraph-io/badger/v2" 18 | "github.com/go-redis/redis/v8" 19 | "github.com/markbates/pkger" 20 | gocache "github.com/patrickmn/go-cache" 21 | "github.com/spf13/afero" 22 | "go.uber.org/multierr" 23 | "go.uber.org/zap" 24 | "golang.org/x/oauth2" 25 | 26 | "github.com/deflix-tv/go-debrid/alldebrid" 27 | "github.com/deflix-tv/go-debrid/premiumize" 28 | "github.com/deflix-tv/go-debrid/realdebrid" 29 | "github.com/deflix-tv/go-stremio" 30 | "github.com/deflix-tv/go-stremio/pkg/cinemeta" 31 | "github.com/deflix-tv/imdb2torrent" 32 | "github.com/doingodswork/deflix-stremio/pkg/logadapter" 33 | "github.com/doingodswork/deflix-stremio/pkg/metafetcher" 34 | ) 35 | 36 | const ( 37 | version = "0.11.1" 38 | ) 39 | 40 | var manifest = stremio.Manifest{ 41 | ID: "tv.deflix.stremio", 42 | Name: "Deflix - Debrid flicks", 43 | Description: "Finds movies and TV shows on YTS, The Pirate Bay, 1337x, RARBG and ibit and automatically turns them into cached HTTP streams with a debrid service like RealDebrid, AllDebrid or Premiumize, for high speed 4k streaming and no P2P uploading (!). For more info see https://www.deflix.tv", 44 | Version: version, 45 | 46 | ResourceItems: []stremio.ResourceItem{ 47 | { 48 | Name: "stream", 49 | Types: []string{"movie", "series"}, 50 | // Shouldn't be required as long as they're defined globally in the manifest, but some Stremio clients send stream requests for non-IMDb IDs, so maybe setting this here as well helps 51 | IDprefixes: []string{"tt"}, 52 | }, 53 | }, 54 | Types: []string{"movie", "series"}, 55 | // An empty slice is required for serializing to a JSON that Stremio expects 56 | Catalogs: []stremio.CatalogItem{}, 57 | 58 | IDprefixes: []string{"tt"}, 59 | // Must use www.deflix.tv instead of just deflix.tv because GitHub takes care of redirecting non-www to www and this leads to HTTPS certificate issues. 60 | Background: "https://www.deflix.tv/images/Logo-1024px.png", 61 | Logo: "https://www.deflix.tv/images/Logo-250px.png", 62 | 63 | BehaviorHints: stremio.BehaviorHints{ 64 | P2P: false, 65 | Configurable: true, 66 | ConfigurationRequired: true, 67 | }, 68 | } 69 | 70 | var ( 71 | // Timeout used for HTTP requests in the cinemeta, imdb2torrent and realdebrid clients. 72 | timeout = 5 * time.Second 73 | // Expiration for the data that's passed from the stream handler to the redirect handler. 74 | // 24h so that a user who selects a movie and sees the list of streams can click on a stream within this time. 75 | // If a user stops/exits a stream and later resumes it, Stremio sends him to the redirect handler. If the stream cache doesn't hold the cache anymore, we just get fresh torrents - no need to cache this for so long. 76 | redirectExpiration = 24 * time.Hour 77 | // Expiration for the converted stream inside the stream handler. 78 | // A long expiration is important for a user who stops/exits a stream and later resumes it. Stremio sends him to the redirect handler. 79 | // 10 days: weekend -> next weekend. 80 | // TODO: We don't know how long an RealDebrid stream URL is valid - so maybe this should be shorter (returning an invalid stream URL is worse then doing another torrent lookup + RealDebrid conversion, but keep in mind that the video player might have issues when another URL of the same file, or a completely other file (for example because the previous one isn't available on RealDebrid anymore) is returned). Also see similar TODO comment in handlers.go file. 81 | streamExpiration = 10 * 24 * time.Hour // 10 days 82 | // Expiration for cached users' RealDebrid API tokens 83 | tokenExpiration = 24 * time.Hour 84 | ) 85 | 86 | // Persistent stores 87 | var ( 88 | // BadgerDB 89 | torrentCache *resultStore 90 | cinemetaCache *metaStore 91 | ) 92 | 93 | // In-memory caches, filled from a file on startup and persisted to a file in regular intervals. 94 | var ( 95 | // go-cache 96 | rdAvailabilityCache *creationCache 97 | adAvailabilityCache *creationCache 98 | pmAvailabilityCache *creationCache 99 | tokenCache *creationCache 100 | // go-cache or Redis, depending on config 101 | redirectCache *goCache 102 | streamCache *goCache 103 | ) 104 | 105 | // Clients 106 | var ( 107 | metaFetcher *metafetcher.Client 108 | searchClient *imdb2torrent.Client 109 | rdClient *realdebrid.Client 110 | adClient *alldebrid.Client 111 | pmClient *premiumize.Client 112 | ) 113 | 114 | var ( 115 | // Locks the redirectLock map 116 | redirectLockMapLock = sync.Mutex{} 117 | // Locks redirect handler cache lookup/write and execution per redirectID 118 | redirectLock = map[string]*sync.Mutex{} 119 | ) 120 | 121 | func init() { 122 | // Timeout for global default HTTP client (for when using `http.Get()`) 123 | http.DefaultClient.Timeout = 5 * time.Second 124 | 125 | // Make predicting "random" numbers harder 126 | rand.NewSource(time.Now().UnixNano()) 127 | 128 | // Register types for gob en- and decoding, required when using go-cache, because a go-cache item is always an `interface{}`. 129 | registerTypes() 130 | } 131 | 132 | func main() { 133 | ctx, cancel := context.WithCancel(context.Background()) 134 | 135 | // Create an "info" logger at first, replace later in case the logging level is configured to be something else 136 | logger, err := stremio.NewLogger("info", stremio.DefaultOptions.LogEncoding) 137 | if err != nil { 138 | panic(err) 139 | } 140 | 141 | // Parse and validate config 142 | 143 | logger.Info("Parsing config...") 144 | config := parseConfig(logger) 145 | configJSON, err := json.Marshal(config) 146 | if err != nil { 147 | logger.Fatal("Couldn't marshal config to JSON", zap.Error(err)) 148 | } 149 | if config.LogLevel != "info" || config.LogEncoding != stremio.DefaultOptions.LogEncoding { 150 | // Replace previously created logger 151 | if logger, err = stremio.NewLogger(config.LogLevel, config.LogEncoding); err != nil { 152 | logger.Fatal("Couldn't create new logger", zap.Error(err)) 153 | } 154 | } 155 | logger.Info("Parsed config", zap.ByteString("config", configJSON)) 156 | 157 | config.validate(logger) 158 | logger.Info("Validated config") 159 | 160 | // Load or create caches and stores 161 | 162 | // Caches first, because some things can go wrong here, and we don't have the store closer yet, which can lead to corrupted BadgerDB files. 163 | initCaches(config, logger) 164 | 165 | closer := initStores(config, logger) 166 | defer func() { 167 | if err := closer(); err != nil { 168 | logger.Error("Couldn't close all stores", zap.Error(err)) 169 | } 170 | }() 171 | 172 | // Create clients 173 | 174 | initClients(config, logger) 175 | 176 | // Init cache maps 177 | 178 | goCaches := map[string]*gocache.Cache{ 179 | "availability-rd": rdAvailabilityCache.cache, 180 | "availability-ad": adAvailabilityCache.cache, 181 | "availability-pm": pmAvailabilityCache.cache, 182 | "token": tokenCache.cache, 183 | } 184 | if redirectCache.cache != nil { 185 | goCaches["redirect"] = redirectCache.cache 186 | } 187 | if streamCache.cache != nil { 188 | goCaches["stream"] = streamCache.cache 189 | } 190 | // Log cache stats every hour 191 | go func() { 192 | // Don't run at the same time as the persistence 193 | time.Sleep(time.Minute) 194 | for { 195 | logCacheStats(goCaches, logger) 196 | time.Sleep(time.Hour) 197 | } 198 | }() 199 | 200 | // Prepare addon creation 201 | 202 | movieStreamHandler := createStreamHandler(config, searchClient, rdClient, adClient, pmClient, redirectCache, false, logger) 203 | tvShowStreamHandler := createStreamHandler(config, searchClient, rdClient, adClient, pmClient, redirectCache, true, logger) 204 | streamHandlers := map[string]stremio.StreamHandler{"movie": movieStreamHandler, "series": tvShowStreamHandler} 205 | 206 | var httpFS http.FileSystem 207 | if config.WebConfigurePath == "" { 208 | pkgerDir := pkger.Dir("/web/configure") 209 | mm := afero.NewMemMapFs() 210 | // Copy all files from pkger to afero memory-mapped FS. 211 | // This is a workaround so we can *write* a file to it. 212 | // TODO: Replace all this as soon as Go 1.16 supports embedding files into a binary. 213 | for _, fName := range []string{"/deflix.css", "/favicon.ico", "/index-apikey.html", "/index-oauth2.html", "/mvp.css"} { 214 | f, err := pkgerDir.Open(fName) 215 | if err != nil { 216 | logger.Fatal("Couldn't open "+fName, zap.Error(err)) 217 | } 218 | fData, err := ioutil.ReadAll(f) 219 | if err != nil { 220 | logger.Fatal("Couldn't read "+fName, zap.Error(err)) 221 | } 222 | absPath := "/" + fName 223 | if err = afero.WriteFile(mm, absPath, fData, 0644); err != nil { 224 | logger.Fatal("Couldn't write to "+absPath, zap.Error(err)) 225 | } 226 | } 227 | 228 | // Rename one of the index.html files depending on OAuth2 configuration 229 | var fromPath string 230 | if config.UseOAUTH2 { 231 | fromPath = "/index-oauth2.html" 232 | } else { 233 | fromPath = "/index-apikey.html" 234 | } 235 | from, err := mm.Open(fromPath) 236 | if err != nil { 237 | logger.Fatal("Couldn't open "+fromPath, zap.Error(err)) 238 | } 239 | to, err := mm.Create("/index.html") 240 | if err != nil { 241 | logger.Fatal(`Couldn't create "/index.html"`, zap.Error(err)) 242 | } 243 | fromBytes, err := ioutil.ReadAll(from) 244 | if err != nil { 245 | logger.Fatal("Couldn't read "+fromPath, zap.Error(err)) 246 | } 247 | _, err = to.Write(fromBytes) 248 | if err != nil { 249 | logger.Fatal(`Couldn't write "/index.html"`, zap.Error(err)) 250 | } 251 | 252 | // Clean up memory and FS a bit by removing the unnecessary files. 253 | // FS because we don't want people to access `www.example.com/index-apikey.html` for example. 254 | if err = mm.Remove("/index-oauth2.html"); err != nil { 255 | logger.Fatal(`Couldn't remove "/index-oauth2.html"`, zap.Error(err)) 256 | } 257 | if err = mm.Remove("/index-apikey.html"); err != nil { 258 | logger.Fatal(`Couldn't remove "/index-apikey.html"`, zap.Error(err)) 259 | } 260 | httpFS = afero.NewHttpFs(mm) 261 | } else { 262 | configurePath := filepath.Clean(config.WebConfigurePath) 263 | logger.Info("Cleaned web configure path", zap.String("path", configurePath)) 264 | httpFS = http.Dir(configurePath) 265 | } 266 | options := stremio.Options{ 267 | BindAddr: config.BindAddr, 268 | Port: config.Port, 269 | // We already have a logger 270 | Logger: logger, 271 | LogIPs: true, 272 | RedirectURL: config.RootURL, 273 | LogMediaName: true, 274 | // We already have a metaFetcher Client 275 | MetaClient: metaFetcher, 276 | ConfigureHTMLfs: httpFS, 277 | // Regular IMDb IDs or for TV shows (IMDbID:season:episode) 278 | StreamIDregex: `^tt\d{7,8}(:\d+:\d+)?$`, 279 | } 280 | 281 | // Create addon 282 | 283 | addon, err := stremio.NewAddon(manifest, nil, streamHandlers, options) 284 | if err != nil { 285 | logger.Fatal("Couldn't create new addon", zap.Error(err)) 286 | } 287 | 288 | // Customize addon 289 | 290 | var confRD oauth2.Config 291 | var confPM oauth2.Config 292 | var aesKey []byte 293 | if config.UseOAUTH2 { 294 | confRD = oauth2.Config{ 295 | ClientID: config.OAUTH2clientIDrd, 296 | ClientSecret: config.OAUTH2clientSecretRD, 297 | RedirectURL: config.BaseURL + "/oauth2/install/rd", 298 | Endpoint: oauth2.Endpoint{ 299 | AuthURL: config.OAUTH2authorizeURLrd, 300 | TokenURL: config.OAUTH2tokenURLrd, 301 | }, 302 | } 303 | confPM = oauth2.Config{ 304 | ClientID: config.OAUTH2clientIDpm, 305 | ClientSecret: config.OAUTH2clientSecretPM, 306 | RedirectURL: config.BaseURL + "/oauth2/install/pm", 307 | Endpoint: oauth2.Endpoint{ 308 | AuthURL: config.OAUTH2authorizeURLpm, 309 | TokenURL: config.OAUTH2tokenURLpm, 310 | }, 311 | } 312 | // We need 32 bytes for AES-256, but the provided password might not be 32 bytes long. 313 | // => Simply hash the password. 314 | // Hashing it doesn't reduce the security. Also: Using a slow hash (like bcrypt) doesn't help much, 315 | // because we don't store the hash anywhere where an attacker could start calculating hashes of values in dictionaries to find a match. 316 | hash := sha256.Sum256([]byte(config.OAUTH2encryptionKey)) 317 | // SHA-256 result is 32 bytes, exactly as many as we need. 318 | aesKey = hash[:] 319 | } 320 | authMiddleware := createAuthMiddleware(rdClient, adClient, pmClient, config.UseOAUTH2, confRD, confPM, aesKey, logger) 321 | addon.AddMiddleware("/:userData/manifest.json", authMiddleware) 322 | addon.AddMiddleware("/:userData/stream/:type/:id.json", authMiddleware) 323 | addon.AddMiddleware("/:userData/redirect/:id", authMiddleware) 324 | // No need to set the middleware to the stream route without user data because go-stremio blocks it (with a 400 Bad Request response) if BehaviorHints.ConfigurationRequired is true. 325 | 326 | // Requires URL query: "?imdbid=123&apitoken=foo" 327 | statusEndpoint := createStatusHandler(searchClient.GetMagnetSearchers(), rdClient, adClient, pmClient, goCaches, config.ForwardOriginIP, logger) 328 | addon.AddEndpoint("GET", "/status", statusEndpoint) 329 | 330 | // Redirects stream URLs (previously sent to Stremio) to the actual RealDebrid stream URLs 331 | redirHandler := createRedirectHandler(redirectCache, streamCache, rdClient, adClient, pmClient, config.ForwardOriginIP, logger) 332 | addon.AddEndpoint("GET", "/:userData/redirect/:id", redirHandler) 333 | // Stremio sends a HEAD request before starting a stream. 334 | addon.AddEndpoint("HEAD", "/:userData/redirect/:id", redirHandler) 335 | 336 | // For OAuth2 redirect handling for RealDebrid and Premiumize 337 | isHTTPS := strings.HasPrefix(config.BaseURL, "https") 338 | oauth2initHandler := createOAUTH2initHandler(confRD, confPM, isHTTPS, logger) 339 | addon.AddEndpoint("GET", "/oauth2/init/:service", oauth2initHandler) 340 | oauth2installHandler := createOAUTH2installHandler(confRD, confPM, aesKey, logger) 341 | addon.AddEndpoint("GET", "/oauth2/install/:service", oauth2installHandler) 342 | 343 | // Save cache to file every hour 344 | go func() { 345 | for { 346 | time.Sleep(time.Hour) 347 | persistCaches(ctx, config.CachePath, goCaches, logger) 348 | } 349 | }() 350 | 351 | // Start addon 352 | 353 | stoppingChan := make(chan bool, 1) 354 | go func() { 355 | <-stoppingChan 356 | cancel() 357 | }() 358 | 359 | addon.Run(stoppingChan) 360 | } 361 | 362 | func initStores(config config, logger *zap.Logger) (closer func() error) { 363 | logger.Info("Initializing stores...") 364 | start := time.Now() 365 | 366 | var closers []func() error 367 | multiCloser := func() error { 368 | var result error 369 | for _, closer := range closers { 370 | if err := closer(); err != nil { 371 | multierr.Append(result, err) 372 | } 373 | } 374 | return result 375 | } 376 | 377 | // BadgerDB 378 | badgerLogger := logadapter.NewBadger2Zap(logger) 379 | options := badger.DefaultOptions(config.StoragePath). 380 | WithLogger(badgerLogger). 381 | WithLoggingLevel(badger.WARNING). 382 | WithSyncWrites(false) 383 | db, err := badger.Open(options) 384 | if err != nil { 385 | logger.Fatal("Couldn't open BadgerDB", zap.Error(err)) 386 | } 387 | closers = append(closers, db.Close) 388 | 389 | torrentCache = &resultStore{ 390 | db: db, 391 | keyPrefix: "torrent_", 392 | } 393 | cinemetaCache = &metaStore{ 394 | db: db, 395 | keyPrefix: "meta_", 396 | } 397 | 398 | // Periodically call RunValueLogGC() 399 | go func() { 400 | time.Sleep(time.Hour) 401 | for { 402 | db.RunValueLogGC(0.5) 403 | time.Sleep(time.Hour) 404 | } 405 | }() 406 | 407 | duration := time.Since(start).Milliseconds() 408 | durationString := strconv.FormatInt(duration, 10) + "ms" 409 | logger.Info("Initialized stores", zap.String("duration", durationString)) 410 | 411 | return multiCloser 412 | } 413 | 414 | func initCaches(config config, logger *zap.Logger) { 415 | logger.Info("Initializing caches...") 416 | start := time.Now() 417 | 418 | rdAvailabilityCacheItems, err := loadGoCache(config.CachePath + "/availability-rd.gob") 419 | if err != nil { 420 | logger.Error("Couldn't load RD availability cache from file - continuing with an empty cache", zap.Error(err)) 421 | rdAvailabilityCacheItems = map[string]gocache.Item{} 422 | } 423 | rdAvailabilityCache = &creationCache{ 424 | cache: gocache.NewFrom(config.CacheAgeXD, 24*time.Hour, rdAvailabilityCacheItems), 425 | } 426 | 427 | adAvailabilityCacheItems, err := loadGoCache(config.CachePath + "/availability-ad.gob") 428 | if err != nil { 429 | logger.Error("Couldn't load AD availability cache from file - continuing with an empty cache", zap.Error(err)) 430 | adAvailabilityCacheItems = map[string]gocache.Item{} 431 | } 432 | adAvailabilityCache = &creationCache{ 433 | cache: gocache.NewFrom(config.CacheAgeXD, 24*time.Hour, adAvailabilityCacheItems), 434 | } 435 | 436 | pmAvailabilityCacheItems, err := loadGoCache(config.CachePath + "/availability-pm.gob") 437 | if err != nil { 438 | logger.Error("Couldn't load Premiumize availability cache from file - continuing with an empty cache", zap.Error(err)) 439 | pmAvailabilityCacheItems = map[string]gocache.Item{} 440 | } 441 | pmAvailabilityCache = &creationCache{ 442 | cache: gocache.NewFrom(config.CacheAgeXD, 24*time.Hour, pmAvailabilityCacheItems), 443 | } 444 | 445 | // TODO: Return closer func like in the stores initialization function. 446 | var rdb *redis.Client 447 | if config.RedisAddr != "" { 448 | redisOpts := redis.Options{ 449 | Addr: config.RedisAddr, 450 | } 451 | if config.RedisCreds != "" { 452 | if strings.Contains(config.RedisCreds, ":") { 453 | creds := strings.SplitN(config.RedisCreds, ":", 2) 454 | redisOpts.Username = creds[0] 455 | redisOpts.Password = creds[1] 456 | } else { 457 | redisOpts.Password = config.RedisCreds 458 | } 459 | } 460 | rdb = redis.NewClient(&redisOpts) 461 | logger.Info("Testing connection to Redis...") 462 | if err := rdb.Ping(context.Background()).Err(); err != nil { 463 | logger.Fatal("Couldn't ping Redis", zap.Error(err)) 464 | } 465 | logger.Info("Connection to Redis established!") 466 | } 467 | 468 | if config.RedisAddr == "" { 469 | if redirectCacheItems, err := loadGoCache(config.CachePath + "/redirect.gob"); err != nil { 470 | logger.Error("Couldn't load redirect cache from file - continuing with an empty cache", zap.Error(err)) 471 | redirectCache = &goCache{ 472 | cache: gocache.New(redirectExpiration, 24*time.Hour), 473 | } 474 | } else { 475 | redirectCache = &goCache{ 476 | cache: gocache.NewFrom(redirectExpiration, 24*time.Hour, redirectCacheItems), 477 | } 478 | } 479 | } else { 480 | var t []imdb2torrent.Result 481 | redirectCache = &goCache{ 482 | rdb: rdb, 483 | t: reflect.TypeOf(t), 484 | logger: logger, 485 | } 486 | } 487 | 488 | if config.RedisAddr == "" { 489 | if streamCacheItems, err := loadGoCache(config.CachePath + "/stream.gob"); err != nil { 490 | logger.Error("Couldn't load stream cache from file - continuing with an empty cache", zap.Error(err)) 491 | streamCache = &goCache{ 492 | cache: gocache.New(streamExpiration, 24*time.Hour), 493 | } 494 | } else { 495 | streamCache = &goCache{ 496 | cache: gocache.NewFrom(streamExpiration, 24*time.Hour, streamCacheItems), 497 | } 498 | } 499 | } else { 500 | var t cacheItem 501 | streamCache = &goCache{ 502 | rdb: rdb, 503 | t: reflect.TypeOf(t), 504 | logger: logger, 505 | } 506 | } 507 | 508 | tokenCacheItems, err := loadGoCache(config.CachePath + "/token.gob") 509 | if err != nil { 510 | logger.Error("Couldn't load token cache from file - continuing with an empty cache", zap.Error(err)) 511 | tokenCacheItems = map[string]gocache.Item{} 512 | } 513 | tokenCache = &creationCache{ 514 | cache: gocache.NewFrom(tokenExpiration, 24*time.Hour, tokenCacheItems), 515 | } 516 | 517 | duration := time.Since(start).Milliseconds() 518 | durationString := strconv.FormatInt(duration, 10) + "ms" 519 | logger.Info("Initialized caches", zap.String("duration", durationString)) 520 | } 521 | 522 | func initClients(config config, logger *zap.Logger) { 523 | logger.Info("Initializing clients...") 524 | start := time.Now() 525 | 526 | // TODO: Return closer func like in the stores initialization function. 527 | var err error 528 | cinemetaClient := cinemeta.NewClient(cinemeta.DefaultClientOpts, cinemetaCache, logger) 529 | metaFetcher, err = metafetcher.NewClient(config.IMDB2metaAddr, cinemetaClient, logger) 530 | if err != nil { 531 | logger.Fatal("Couldn't create metafetcher client", zap.Error(err)) 532 | } 533 | 534 | ytsClientOpts := imdb2torrent.NewYTSclientOpts(config.BaseURLyts, timeout, config.MaxAgeTorrents) 535 | tpbClientOpts := imdb2torrent.NewTPBclientOpts(config.BaseURLtpb, config.SocksProxyAddrTPB, timeout, config.MaxAgeTorrents) 536 | leetxClientOpts := imdb2torrent.NewLeetxClientOpts(config.BaseURL1337x, timeout, config.MaxAgeTorrents) 537 | ibitClientOpts := imdb2torrent.NewIbitClientOpts(config.BaseURLibit, timeout, config.MaxAgeTorrents) 538 | rarbgClientOpts := imdb2torrent.NewRARBGclientOpts(config.BaseURLrarbg, timeout, config.MaxAgeTorrents) 539 | rdClientOpts := realdebrid.NewClientOpts(config.BaseURLrd, timeout, config.CacheAgeXD, config.ExtraHeadersXD, config.ForwardOriginIP) 540 | adClientOpts := alldebrid.NewClientOpts(config.BaseURLad, timeout, config.CacheAgeXD, config.ExtraHeadersXD) 541 | pmClientOpts := premiumize.NewClientOpts(config.BaseURLpm, timeout, config.CacheAgeXD, config.ExtraHeadersXD, config.ForwardOriginIP) 542 | 543 | tpbClient, err := imdb2torrent.NewTPBclient(tpbClientOpts, torrentCache, metaFetcher, logger, config.LogFoundTorrents) 544 | if err != nil { 545 | logger.Fatal("Couldn't create TPB client", zap.Error(err)) 546 | } 547 | siteClients := map[string]imdb2torrent.MagnetSearcher{ 548 | "YTS": imdb2torrent.NewYTSclient(ytsClientOpts, torrentCache, logger, config.LogFoundTorrents), 549 | "TPB": tpbClient, 550 | "1337X": imdb2torrent.NewLeetxClient(leetxClientOpts, torrentCache, metaFetcher, logger, config.LogFoundTorrents), 551 | "ibit": imdb2torrent.NewIbitClient(ibitClientOpts, torrentCache, logger, config.LogFoundTorrents), 552 | "RARBG": imdb2torrent.NewRARBGclient(rarbgClientOpts, torrentCache, logger, config.LogFoundTorrents), 553 | } 554 | searchClient = imdb2torrent.NewClient(siteClients, timeout, logger) 555 | rdClient, err = realdebrid.NewClient(rdClientOpts, tokenCache, rdAvailabilityCache, logger) 556 | if err != nil { 557 | logger.Fatal("Couldn't create RealDebrid client", zap.Error(err)) 558 | } 559 | adClient, err = alldebrid.NewClient(adClientOpts, tokenCache, adAvailabilityCache, logger) 560 | if err != nil { 561 | logger.Fatal("Couldn't create AllDebrid client", zap.Error(err)) 562 | } 563 | pmClient, err = premiumize.NewClient(pmClientOpts, tokenCache, pmAvailabilityCache, logger) 564 | if err != nil { 565 | logger.Fatal("Couldn't create Premiumize client", zap.Error(err)) 566 | } 567 | 568 | duration := time.Since(start).Milliseconds() 569 | durationString := strconv.FormatInt(duration, 10) + "ms" 570 | logger.Info("Initialized clients", zap.String("duration", durationString)) 571 | } 572 | -------------------------------------------------------------------------------- /cmd/deflix-stremio/middleware.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/aes" 5 | "crypto/cipher" 6 | "encoding/base64" 7 | "encoding/json" 8 | "errors" 9 | "fmt" 10 | "io/ioutil" 11 | "net/http" 12 | "net/url" 13 | "strings" 14 | "time" 15 | 16 | "github.com/gofiber/fiber/v2" 17 | "go.uber.org/zap" 18 | "golang.org/x/oauth2" 19 | 20 | "github.com/deflix-tv/go-debrid/alldebrid" 21 | "github.com/deflix-tv/go-debrid/premiumize" 22 | "github.com/deflix-tv/go-debrid/realdebrid" 23 | ) 24 | 25 | // createAuthMiddleware creates a middleware that checks the validity of RealDebrid, AllDebrid and Premiumize API tokens/keys as well as Premiumize OAuth2 data. 26 | func createAuthMiddleware(rdClient *realdebrid.Client, adClient *alldebrid.Client, pmClient *premiumize.Client, useOAUTH2 bool, confRD, confPM oauth2.Config, aesKey []byte, logger *zap.Logger) fiber.Handler { 27 | httpClient := &http.Client{ 28 | Timeout: 2 * time.Second, 29 | } 30 | 31 | return func(c *fiber.Ctx) error { 32 | rCtx := c.Context() 33 | udString := c.Params("userData", "") 34 | if udString == "" { 35 | // Should never occur, because the manifest states that configuration is required and go-stremio's route matcher middleware filters these out. 36 | logger.Error("User data is empty, but this should have been handled by go-stremio's router matcher middleware alraedy") 37 | return c.SendStatus(fiber.StatusUnauthorized) 38 | } 39 | userData, err := decodeUserData(udString, logger) 40 | if err != nil { 41 | // The error is already logged in the decodeUserData function. 42 | // It's most likely a client-side encoding error. 43 | return c.SendStatus(fiber.StatusBadRequest) 44 | } 45 | 46 | // Note: Even when useOAUTH2 is true, some Stremio clients might still use the API key from the past. 47 | if useOAUTH2 && (userData.RDoauth2 != "" || userData.PMoauth2 != "") { 48 | if userData.RDoauth2 != "" { 49 | accessToken, err, fiberErr := getAccessTokenForOAuth2data(c, confRD, aesKey, userData.RDoauth2, true, httpClient, logger) 50 | if err != nil { 51 | logger.Warn("Couldn't get access token for OAUTH2 data", zap.Error(err)) 52 | // HTTP responses are already handled 53 | return fiberErr 54 | } 55 | if err = rdClient.TestToken(c.Context(), accessToken); err != nil { 56 | logger.Info("Access token is invalid or validation failed", zap.Error(err)) 57 | return c.SendStatus(fiber.StatusForbidden) 58 | } 59 | c.Locals("deflix_keyOrToken", accessToken) 60 | } else if userData.PMoauth2 != "" { 61 | accessToken, err, fiberErr := getAccessTokenForOAuth2data(c, confPM, aesKey, userData.PMoauth2, false, nil, logger) 62 | if err != nil { 63 | logger.Warn("Couldn't get access token for OAUTH2 data", zap.Error(err)) 64 | // HTTP responses are already handled 65 | return fiberErr 66 | } 67 | c.Locals("debrid_OAUTH2", struct{}{}) 68 | if err = pmClient.TestAPIkey(c.Context(), accessToken); err != nil { 69 | logger.Info("Access token is invalid or validation failed", zap.Error(err)) 70 | return c.SendStatus(fiber.StatusForbidden) 71 | } 72 | c.Locals("deflix_keyOrToken", accessToken) 73 | } 74 | } else { 75 | // Log "legacy" info. Only for RD and PM, because we're still using API keys for AD even if useOAUTH2 is true. 76 | if useOAUTH2 && (userData.RDtoken != "" || userData.PMkey != "") { 77 | logger.Info("Using OAUTH2, but a client used an API key") 78 | } 79 | // We expect a user to have *either* an RD token *or* an AD key *or* a Premiumize key 80 | if userData.RDtoken != "" { 81 | if err := rdClient.TestToken(rCtx, userData.RDtoken); err != nil { 82 | logger.Info("API key is invalid or validation failed", zap.Error(err)) 83 | return c.SendStatus(fiber.StatusForbidden) 84 | } 85 | c.Locals("deflix_keyOrToken", userData.RDtoken) 86 | } else if userData.ADkey != "" { 87 | if err := adClient.TestAPIkey(rCtx, userData.ADkey); err != nil { 88 | logger.Info("API key is invalid or validation failed", zap.Error(err)) 89 | return c.SendStatus(fiber.StatusForbidden) 90 | } 91 | c.Locals("deflix_keyOrToken", userData.ADkey) 92 | } else if userData.PMkey != "" { 93 | if err := pmClient.TestAPIkey(rCtx, userData.PMkey); err != nil { 94 | logger.Info("API key is invalid or validation failed", zap.Error(err)) 95 | return c.SendStatus(fiber.StatusForbidden) 96 | } 97 | c.Locals("deflix_keyOrToken", userData.PMkey) 98 | } else { 99 | logger.Info("API key is empty", zap.String("userData", fmt.Sprintf("%+v", userData))) 100 | return c.SendStatus(fiber.StatusUnauthorized) 101 | } 102 | } 103 | 104 | return c.Next() 105 | } 106 | } 107 | 108 | // getAccessTokenForOAuth2data is a convenience function that decrypts the OAUTH2 data and returns a valid (potentially refreshed) access token, 109 | // while taking care of Fiber responses in error cases. 110 | // The first error return value is the error that occurred inside this function. The second is from sending the response via Fiber. 111 | func getAccessTokenForOAuth2data(c *fiber.Ctx, conf oauth2.Config, aesKey []byte, oauth2data string, rdWorkaround bool, httpClient *http.Client, logger *zap.Logger) (string, error, error) { 112 | ciphertext, err := base64.RawURLEncoding.DecodeString(oauth2data) 113 | if err != nil { 114 | // It's most likely a client-side encoding error 115 | return "", err, c.SendStatus(fiber.StatusBadRequest) 116 | } 117 | 118 | block, err := aes.NewCipher(aesKey) 119 | if err != nil { 120 | logger.Warn("Couldn't create block cipher from AES key", zap.Error(err)) 121 | return "", err, c.SendStatus(fiber.StatusInternalServerError) 122 | } 123 | aesgcm, err := cipher.NewGCM(block) 124 | if err != nil { 125 | logger.Error("Couldn't create AES GCM", zap.Error(err)) 126 | return "", err, c.SendStatus(fiber.StatusInternalServerError) 127 | } 128 | // The nonce is prepended 129 | nonce := ciphertext[:aesgcm.NonceSize()] 130 | ciphertext = ciphertext[aesgcm.NonceSize():] 131 | 132 | tokenJSON, err := aesgcm.Open(nil, nonce, ciphertext, nil) 133 | if err != nil { 134 | return "", err, c.SendStatus(fiber.StatusForbidden) 135 | } 136 | token := &oauth2.Token{} 137 | if err = json.Unmarshal(tokenJSON, token); err != nil { 138 | // How likely is it that if the previous decoding worked, that it's now the client's fault vs ours? 139 | return "", err, c.SendStatus(fiber.StatusBadRequest) 140 | } 141 | // This is a workaround for RD, as they don't seem to implement the OAuth2 flow the way the Go OAuth2 package expects 142 | // (for example they require grant_type: "http://oauth.net/grant_type/device/1.0", instead of "refresh_token") 143 | var accessToken string 144 | if rdWorkaround { 145 | // Example call from RD docs: 146 | // curl -X POST "https://api.real-debrid.com/oauth/v2/token" -d "client_id=ABCDEFGHIJKLM&client_secret=abcdefghsecret0123456789&code=ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789&grant_type=http://oauth.net/grant_type/device/1.0" 147 | data := url.Values{} 148 | data.Add("client_id", conf.ClientID) 149 | data.Add("client_secret", conf.ClientSecret) 150 | data.Add("code", token.RefreshToken) 151 | data.Add("grant_type", "http://oauth.net/grant_type/device/1.0") 152 | req, err := http.NewRequest("POST", conf.Endpoint.TokenURL, strings.NewReader(data.Encode())) 153 | if err != nil { 154 | logger.Error("Couldn't create request object for RD token refresh", zap.Error(err)) 155 | return "", err, c.SendStatus(fiber.StatusInternalServerError) 156 | } 157 | req.Header.Set(fiber.HeaderContentType, fiber.MIMEApplicationForm) 158 | res, err := httpClient.Do(req) 159 | if err != nil { 160 | logger.Warn("Error during request to RD token refresh", zap.Error(err)) 161 | return "", err, c.SendStatus(fiber.StatusInternalServerError) 162 | } 163 | defer res.Body.Close() 164 | // RD API usually always responds with 200 and a JSON object (even for bad requests / invalid accounts etc), 165 | // with the actual potential error codes are then inside the JSON body, 166 | // but in case of the OAuth2 refresh token request this is different. 167 | // So we have to treat non-OK responses as errors from the client side, not from us. 168 | if res.StatusCode != fiber.StatusOK { 169 | var errBody []byte 170 | errBody, _ = ioutil.ReadAll(res.Body) 171 | logger.Info("RD token refresh response != OK", zap.Int("status", res.StatusCode), zap.ByteString("body", errBody)) 172 | return "", errors.New("RD response != OK"), c.SendStatus(fiber.StatusForbidden) 173 | } 174 | tokenJSON, err = ioutil.ReadAll(res.Body) 175 | if err != nil { 176 | logger.Warn("Couldn't read response body from RD token refresh", zap.Error(err)) 177 | return "", err, c.SendStatus(fiber.StatusInternalServerError) 178 | } 179 | if err = json.Unmarshal(tokenJSON, token); err != nil { 180 | logger.Warn("Couldn't unmarshal RD response body into OAuth2 token", zap.Error(err), zap.ByteString("body", tokenJSON)) 181 | return "", err, c.SendStatus(fiber.StatusInternalServerError) 182 | } 183 | accessToken = token.AccessToken 184 | } else { 185 | tokenSource := conf.TokenSource(c.Context(), token) 186 | // The token source automatically refreshes the token with the refresh token 187 | validToken, err := tokenSource.Token() 188 | if err != nil { 189 | return "", err, c.SendStatus(fiber.StatusForbidden) 190 | } 191 | accessToken = validToken.AccessToken 192 | } 193 | 194 | return accessToken, nil, nil 195 | } 196 | -------------------------------------------------------------------------------- /cmd/deflix-stremio/oauth2.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "crypto/aes" 5 | "crypto/cipher" 6 | crand "crypto/rand" 7 | "encoding/base64" 8 | "encoding/json" 9 | "math/big" 10 | "net/http" 11 | 12 | "github.com/gofiber/fiber/v2" 13 | "go.uber.org/zap" 14 | "golang.org/x/oauth2" 15 | ) 16 | 17 | // createOAUTH2initHandler returns a handler for OAuth2 initialization requests from the deflix-stremio frontend. 18 | // The handler returns a redirect to the RealDebrid or Premiumize OAuth2 *authorize* endpoint. 19 | func createOAUTH2initHandler(confRD, confPM oauth2.Config, isHTTPS bool, logger *zap.Logger) fiber.Handler { 20 | confMap := map[string]oauth2.Config{ 21 | "rd": confRD, 22 | "pm": confPM, 23 | } 24 | 25 | return func(c *fiber.Ctx) error { 26 | service := c.Params("service") 27 | if service == "" { 28 | return c.SendStatus(fiber.StatusBadRequest) 29 | } else if service != "rd" && service != "pm" { 30 | return c.SendStatus(fiber.StatusNotFound) 31 | } 32 | 33 | conf := confMap[service] 34 | 35 | // Create random state string 36 | randInt, err := crand.Int(crand.Reader, big.NewInt(6)) // 0-5 37 | if err != nil { 38 | logger.Error("Couldn't generate random number", zap.Error(err)) 39 | return c.SendStatus(fiber.StatusInternalServerError) 40 | } 41 | statusLength := randInt.Add(randInt, big.NewInt(5)) // 5-10 42 | if !statusLength.IsUint64() { 43 | logger.Error("Random status length can't be represendted as uint64", zap.String("statusLength", statusLength.String())) 44 | return c.SendStatus(fiber.StatusInternalServerError) 45 | } 46 | b := make([]byte, statusLength.Uint64()) 47 | if _, err = crand.Read(b); err != nil { 48 | logger.Error("Couldn't generate random bytes", zap.Error(err)) 49 | return c.SendStatus(fiber.StatusInternalServerError) 50 | } 51 | // URL-safe, no padding 52 | state := base64.RawURLEncoding.EncodeToString(b) 53 | 54 | // Create redirect URL with random state string 55 | redirectURL := conf.AuthCodeURL(state, oauth2.AccessTypeOffline) 56 | // Set as cookie, so when the redirect endpoint is hit we can make sure the state is the one we set in the user session 57 | statusCookie := &fiber.Cookie{ 58 | Name: "deflix_oauth2state", 59 | Value: state, 60 | Secure: isHTTPS, 61 | HTTPOnly: true, 62 | // We need the cookie to be sent upon redirect from RealDebrid or Premiumize to deflix-stremio. 63 | SameSite: "lax", 64 | // The cookie shouldn't be set forever 65 | MaxAge: 1 * 60 * 60, // One hour in seconds 66 | } 67 | c.Cookie(statusCookie) 68 | c.Set(fiber.HeaderLocation, redirectURL) 69 | return c.SendStatus(fiber.StatusTemporaryRedirect) 70 | } 71 | } 72 | 73 | // createOAUTH2installHandler returns a handler for redirected requests from RealDebrid or Premiumize after authorization. 74 | // It returns something like the "/configure" page, but pre-filled with the required RealDebrid or Premiumize data. 75 | // aesKey should be 32 bytes so that AES-256 is used. 76 | func createOAUTH2installHandler(confRD, confPM oauth2.Config, aesKey []byte, logger *zap.Logger) fiber.Handler { 77 | confMap := map[string]oauth2.Config{ 78 | "rd": confRD, 79 | "pm": confPM, 80 | } 81 | 82 | return func(c *fiber.Ctx) error { 83 | service := c.Params("service") 84 | if service == "" { 85 | return c.SendStatus(fiber.StatusBadRequest) 86 | } else if service != "rd" && service != "pm" { 87 | return c.SendStatus(fiber.StatusNotFound) 88 | } 89 | 90 | conf := confMap[service] 91 | 92 | // Verify state 93 | stateFromURL := c.Query("state") 94 | stateFromCookie := c.Cookies("deflix_oauth2state") 95 | if stateFromURL == "" || stateFromURL != stateFromCookie { 96 | return c.SendStatus(fiber.StatusForbidden) 97 | } 98 | 99 | // Exchange authorization code for access token 100 | code := c.Query("code") 101 | if code == "" { 102 | return c.SendStatus(fiber.StatusForbidden) 103 | } 104 | token, err := conf.Exchange(c.Context(), code, oauth2.AccessTypeOffline) 105 | if err != nil { 106 | // Can be both client-side errors (e.g. faked code) or ours. 107 | logger.Warn("Couldn't exchange authorization code for access token", zap.Error(err)) 108 | return c.SendStatus(fiber.StatusForbidden) 109 | } 110 | 111 | // Encrypt token so we can deliver it to the Stremio client without revealing the tokens. 112 | // We do this so we don't have to store it server-side, which is 1. error-prone (makes DB a single point of failure) and 2. a liability (DB hacks, leaks). 113 | tokenJSON, err := json.Marshal(token) 114 | if err != nil { 115 | logger.Error("Couldn't marshal the token into JSON", zap.Error(err)) 116 | return c.SendStatus(fiber.StatusInternalServerError) 117 | } 118 | block, err := aes.NewCipher(aesKey) 119 | if err != nil { 120 | logger.Warn("Couldn't create block cipher from AES key", zap.Error(err)) 121 | return c.SendStatus(fiber.StatusInternalServerError) 122 | } 123 | aesgcm, err := cipher.NewGCM(block) 124 | if err != nil { 125 | logger.Error("Couldn't create AES GCM", zap.Error(err)) 126 | return c.SendStatus(fiber.StatusInternalServerError) 127 | } 128 | nonce := make([]byte, aesgcm.NonceSize()) 129 | if _, err = crand.Read(nonce); err != nil { 130 | logger.Error("Couldn't create nonce", zap.Error(err)) 131 | return c.SendStatus(fiber.StatusInternalServerError) 132 | } 133 | // We prepend the nonce because we don't want to store it 134 | ciphertext := aesgcm.Seal(nonce, nonce, tokenJSON, nil) 135 | 136 | // Redirect to the "/configure" webpage, but with the OAuth2 data in the URL so that the site's JavaScript can read and use it. 137 | // The encoding below leads to double Base64 encoding, but using `string(ciphertext)` leads to much longer and uglier Base64-encoded user data. 138 | var ud userData 139 | if service == "rd" { 140 | ud = userData{ 141 | RDoauth2: base64.RawURLEncoding.EncodeToString(ciphertext), 142 | } 143 | } else if service == "pm" { 144 | ud = userData{ 145 | PMoauth2: base64.RawURLEncoding.EncodeToString(ciphertext), 146 | } 147 | } 148 | // else is taken care of at the start of the handler 149 | userDataEncoded, err := ud.encode(logger) 150 | if err != nil { 151 | logger.Error("Couldn't encode user data with OAuth2 data", zap.Error(err)) 152 | return c.SendStatus(fiber.StatusInternalServerError) 153 | } 154 | // If a redirect URL is set in a cookie, it could be from www.deflix.tv or from a promo page and we must redirect there instead of to our "/configure#..." page. 155 | redirectURL := "/configure#" + userDataEncoded 156 | if c.Cookies("deflix_oauth2redirect") != "" { 157 | redirectURL = c.Cookies("deflix_oauth2redirect") 158 | redirectURL += "?data=" + userDataEncoded 159 | } 160 | 161 | c.Set(fiber.HeaderLocation, redirectURL) 162 | return c.SendStatus(http.StatusTemporaryRedirect) 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /cmd/deflix-stremio/storage.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "encoding/gob" 7 | "errors" 8 | "fmt" 9 | "os" 10 | "reflect" 11 | "strconv" 12 | "time" 13 | 14 | "github.com/dgraph-io/badger/v2" 15 | "github.com/go-redis/redis/v8" 16 | gocache "github.com/patrickmn/go-cache" 17 | "go.uber.org/zap" 18 | 19 | "github.com/deflix-tv/go-debrid" 20 | "github.com/deflix-tv/go-stremio/pkg/cinemeta" 21 | "github.com/deflix-tv/imdb2torrent" 22 | ) 23 | 24 | func registerTypes() { 25 | // For RealDebrid availability and token cache 26 | gob.Register(time.Time{}) 27 | // For cinemeta cache 28 | gob.Register(cinemeta.CacheItem{}) 29 | // For redirect cache 30 | gob.Register([]imdb2torrent.Result{}) 31 | // For stream cache 32 | gob.Register(cacheItem{}) 33 | } 34 | 35 | type cacheItem struct { 36 | Value string 37 | Created time.Time 38 | } 39 | 40 | var _ imdb2torrent.Cache = (*resultStore)(nil) 41 | 42 | // resultStore is the store for imdb2torrent.Result objects, backed by BadgerDB. 43 | type resultStore struct { 44 | db *badger.DB 45 | keyPrefix string 46 | } 47 | 48 | // Set implements the imdb2torrent.Cache interface. 49 | func (c *resultStore) Set(key string, results []imdb2torrent.Result) error { 50 | item := imdb2torrent.CacheItem{ 51 | Results: results, 52 | Created: time.Now(), 53 | } 54 | return gobSet(c.db, c.keyPrefix+key, item) 55 | } 56 | 57 | // Get implements the imdb2torrent.Cache interface. 58 | func (c *resultStore) Get(key string) ([]imdb2torrent.Result, time.Time, bool, error) { 59 | var item imdb2torrent.CacheItem 60 | found, err := gobGet(c.db, c.keyPrefix+key, &item) 61 | return item.Results, item.Created, found, err 62 | } 63 | 64 | var _ cinemeta.Cache = (*metaStore)(nil) 65 | 66 | // metaStore is the store for cinemeta.Meta objects, backed by BadgerDB. 67 | type metaStore struct { 68 | db *badger.DB 69 | keyPrefix string 70 | } 71 | 72 | // Set implements the cinemeta.Cache interface. 73 | func (c *metaStore) Set(key string, meta cinemeta.Meta) error { 74 | item := cinemeta.CacheItem{ 75 | Meta: meta, 76 | Created: time.Now(), 77 | } 78 | return gobSet(c.db, c.keyPrefix+key, item) 79 | } 80 | 81 | // Get implements the cinemeta.Cache interface. 82 | func (c *metaStore) Get(key string) (cinemeta.Meta, time.Time, bool, error) { 83 | var item cinemeta.CacheItem 84 | found, err := gobGet(c.db, c.keyPrefix+key, &item) 85 | if err != nil { 86 | return cinemeta.Meta{}, time.Time{}, found, err 87 | } else if !found { 88 | return cinemeta.Meta{}, time.Time{}, found, nil 89 | } 90 | return item.Meta, item.Created, found, nil 91 | } 92 | 93 | var _ debrid.Cache = (*creationCache)(nil) 94 | 95 | // creationCache caches if a key exists and the time this was cached. 96 | type creationCache struct { 97 | cache *gocache.Cache 98 | } 99 | 100 | // Set implements the cinemeta.Cache interface. 101 | func (c *creationCache) Set(key string) error { 102 | c.cache.Set(key, time.Now(), 0) 103 | return nil 104 | } 105 | 106 | // Get implements the cinemeta.Cache interface. 107 | func (c *creationCache) Get(key string) (time.Time, bool, error) { 108 | createdIface, found := c.cache.Get(key) 109 | if !found { 110 | return time.Time{}, found, nil 111 | } 112 | created, ok := createdIface.(time.Time) 113 | if !ok { 114 | return time.Time{}, found, fmt.Errorf("Couldn't cast cached value to time.Time: type was: %T", createdIface) 115 | } 116 | return created, found, nil 117 | } 118 | 119 | var _ goCacher = (*goCache)(nil) 120 | 121 | // goCache wraps both a go-cache instance and Redis and offers methods with the exact same signature as go-cache. 122 | // If the Redis client is not nil, it's the one that's used exclusively. Otherwise go-cache is used. 123 | // The data in this cache is meant to be temporary, while also important to be the same across multiple nodes. 124 | // This is why there's no reason to for example read data from Redis and (during the same Get call) store the fetched data in go-cache to have a local copy in case of a Redis connection error, or to store data in both at the same time during a Set call. 125 | type goCache struct { 126 | cache *gocache.Cache 127 | rdb *redis.Client 128 | // Only required when using Redis. Must be the actual type. So if you have a pointer, set this to the "element" of the pointer. 129 | t reflect.Type 130 | // Only required when using Redis. 131 | logger *zap.Logger 132 | } 133 | 134 | func (c *goCache) Set(k string, v interface{}, d time.Duration) { 135 | if c.rdb != nil { 136 | // Note: We can only decode into a pointer. And when working with interfaces gob requires to encode a pointer. 137 | if b, err := toGob(&v); err != nil { 138 | c.logger.Error("Couldn't encode value as gob", zap.Error(err)) 139 | } else if err := c.rdb.Set(context.Background(), k, b, d).Err(); err != nil { 140 | c.logger.Error("Couldn't set value in Redis", zap.Error(err)) 141 | } 142 | } else { 143 | c.cache.Set(k, v, d) 144 | } 145 | } 146 | 147 | func (c *goCache) Get(k string) (interface{}, bool) { 148 | if c.rdb != nil { 149 | if v, err := c.rdb.Get(context.Background(), k).Result(); err != nil && err != redis.Nil { 150 | // Note: We only log this when there's an error *and* it's not `redis.Nil` (which just indicates that the value was not found). 151 | c.logger.Error("Couldn't get value from Redis", zap.Error(err)) 152 | // Note: Don't return `nil, true` here, although that would be more correct. But given that the implementation is meant to have the same behavior as go-cache, where there are never encoding errors, a `nil, true` would lead to a caller assuming they can work with the value, but it's nil. 153 | } else if err != redis.Nil { 154 | var vi interface{} 155 | if c.t.Kind() == reflect.Slice { 156 | vi = reflect.MakeSlice(c.t, 0, 0) 157 | } else { 158 | vi = reflect.New(c.t) 159 | } 160 | if err := fromGob([]byte(v), &vi); err != nil { 161 | c.logger.Error("Couldn't decode gob", zap.Error(err)) 162 | } else { 163 | return vi, true 164 | } 165 | } 166 | // Else: err == redis.Nil, which we don't need to explicitly handle, as returning `nil, false` is perfect for that. 167 | return nil, false 168 | } else { 169 | return c.cache.Get(k) 170 | } 171 | } 172 | 173 | func toGob(v interface{}) ([]byte, error) { 174 | writer := bytes.Buffer{} 175 | encoder := gob.NewEncoder(&writer) 176 | if err := encoder.Encode(v); err != nil { 177 | return nil, err 178 | } 179 | return writer.Bytes(), nil 180 | } 181 | 182 | func fromGob(b []byte, v interface{}) error { 183 | reader := bytes.NewReader(b) 184 | decoder := gob.NewDecoder(reader) 185 | if err := decoder.Decode(v); err != nil { 186 | return err 187 | } 188 | return nil 189 | } 190 | 191 | func gobSet(db *badger.DB, key string, item interface{}) error { 192 | b, err := toGob(item) 193 | if err != nil { 194 | return fmt.Errorf("Couldn't encode item: %v", err) 195 | } 196 | return db.Update(func(txn *badger.Txn) error { 197 | return txn.Set([]byte(key), b) 198 | }) 199 | } 200 | 201 | func gobGet(db *badger.DB, key string, target interface{}) (bool, error) { 202 | err := db.View(func(txn *badger.Txn) error { 203 | item, err := txn.Get([]byte(key)) 204 | if err != nil { 205 | return err 206 | } 207 | item.Value(func(val []byte) error { 208 | return fromGob(val, target) 209 | }) 210 | return nil 211 | }) 212 | if err == badger.ErrKeyNotFound { 213 | return false, nil 214 | } else if err != nil { 215 | return true, err 216 | } 217 | return true, nil 218 | } 219 | 220 | func saveGoCache(items map[string]gocache.Item, filePath string) error { 221 | file, err := os.Create(filePath) 222 | if err != nil { 223 | return fmt.Errorf("Couldn't create go-cache file: %v", err) 224 | } 225 | encoder := gob.NewEncoder(file) 226 | if err = encoder.Encode(items); err != nil { 227 | return fmt.Errorf("Couldn't encode items for go-cache file: %v", err) 228 | } 229 | return nil 230 | } 231 | 232 | func loadGoCache(filePath string) (map[string]gocache.Item, error) { 233 | file, err := os.Open(filePath) 234 | if err != nil { 235 | return nil, fmt.Errorf("Couldn't open go-cache file: %v", err) 236 | } 237 | decoder := gob.NewDecoder(file) 238 | result := map[string]gocache.Item{} 239 | if err = decoder.Decode(&result); err != nil { 240 | return nil, fmt.Errorf("Couldn't decode items from go-cache file: %v", err) 241 | } 242 | return result, nil 243 | } 244 | 245 | func persistCaches(ctx context.Context, cacheFilePath string, goCaches map[string]*gocache.Cache, logger *zap.Logger) { 246 | // TODO: We might want to overthink this - persisting caches on shutdown might be useful, especially for the redirect cache! 247 | if ctx.Err() != nil { 248 | logger.Warn("Regular cache persistence triggered, but server is shutting down") 249 | return 250 | } 251 | 252 | logger.Info("Persisting caches...", zap.String("cacheFilePath", cacheFilePath)) 253 | start := time.Now() 254 | 255 | // If the dir doesn't exist yet, we'll create it 256 | _, err := os.Stat(cacheFilePath) 257 | if err != nil { 258 | if errors.Is(err, os.ErrNotExist) { 259 | if err = os.Mkdir(cacheFilePath, os.ModeDir); err != nil { 260 | logger.Error("Couldn't create cache directory", zap.Error(err), zap.String("dir", cacheFilePath)) 261 | return 262 | } 263 | logger.Info("Created cache directory", zap.String("dir", cacheFilePath)) 264 | } else { 265 | logger.Error("Couldn't get cache directory info", zap.Error(err), zap.String("dir", cacheFilePath)) 266 | return 267 | } 268 | } 269 | 270 | for name, goCache := range goCaches { 271 | if err := saveGoCache(goCache.Items(), cacheFilePath+"/"+name+".gob"); err != nil { 272 | logger.Error("Couldn't save cache to file", zap.Error(err), zap.String("cache", name)) 273 | } 274 | } 275 | 276 | duration := time.Since(start).Milliseconds() 277 | durationString := strconv.FormatInt(duration, 10) + "ms" 278 | logger.Info("Persisted caches", zap.String("duration", durationString)) 279 | } 280 | 281 | func logCacheStats(goCaches map[string]*gocache.Cache, logger *zap.Logger) { 282 | for name, goCache := range goCaches { 283 | logger.Info("Cache stats", zap.String("cache", name), zap.Int("itemCount", goCache.ItemCount())) 284 | } 285 | } 286 | -------------------------------------------------------------------------------- /cmd/deflix-stremio/storage_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math" 5 | "math/rand" 6 | "os" 7 | "reflect" 8 | "strconv" 9 | "testing" 10 | "time" 11 | 12 | "github.com/go-redis/redis/v8" 13 | "github.com/google/go-cmp/cmp" 14 | gocache "github.com/patrickmn/go-cache" 15 | "github.com/stretchr/testify/require" 16 | 17 | "github.com/deflix-tv/go-stremio" 18 | "github.com/deflix-tv/imdb2torrent" 19 | ) 20 | 21 | func TestGoCacheItem(t *testing.T) { 22 | cache := gocache.New(0, 0) 23 | exp := cacheItem{ 24 | Value: "foo", 25 | Created: time.Now(), 26 | } 27 | cache.Set("123", exp, 0) 28 | actualIface, found := cache.Get("123") 29 | require.True(t, found) 30 | actual, ok := actualIface.(cacheItem) 31 | require.True(t, ok) 32 | require.Equal(t, exp, actual) 33 | } 34 | 35 | func TestGoCachePersistence(t *testing.T) { 36 | registerTypes() 37 | 38 | cache := gocache.New(0, 0) 39 | exp1 := cacheItem{ 40 | Value: "foo", 41 | Created: time.Now(), 42 | } 43 | exp2 := []imdb2torrent.Result{ 44 | {Title: "Big Buck Bunny"}, 45 | {Title: "Sintel"}, 46 | } 47 | cache.Set("123", exp1, 0) 48 | cache.Set("456", exp2, 0) 49 | filePath := os.TempDir() + ".gocache" 50 | err := saveGoCache(cache.Items(), filePath) 51 | require.NoError(t, err) 52 | 53 | items, err := loadGoCache(filePath) 54 | require.NoError(t, err) 55 | cache = gocache.NewFrom(0, 0, items) 56 | 57 | actualIface, found := cache.Get("123") 58 | require.True(t, found) 59 | actual1, ok := actualIface.(cacheItem) 60 | require.True(t, ok) 61 | // We can't use require.Equal here, because the marshalled time loses its wall time, leading to a difference for the internally used reflect.DeepEquals. 62 | equal := cmp.Equal(exp1, actual1) 63 | require.True(t, equal) 64 | 65 | actualIface, found = cache.Get("456") 66 | require.True(t, found) 67 | actual2, ok := actualIface.([]imdb2torrent.Result) 68 | require.True(t, ok) 69 | // We can't use require.Equal here, because the marshalled time loses its wall time, leading to a difference for the internally used reflect.DeepEquals. 70 | equal = cmp.Equal(exp2, actual2) 71 | require.True(t, equal) 72 | } 73 | 74 | func TestRedis(t *testing.T) { 75 | // Doesn't work on Windows: https://github.com/testcontainers/testcontainers-go/issues/152 76 | // ip, port, deferFunc := startRedis(t) 77 | // defer deferFunc() 78 | ip, port := "localhost", "6379" 79 | 80 | logger, err := stremio.NewLogger("debug", "") 81 | require.NoError(t, err) 82 | 83 | // Type: torrent result slice (for redirect cache use case) 84 | 85 | var type1 []imdb2torrent.Result 86 | gc := goCache{ 87 | rdb: redis.NewClient(&redis.Options{ 88 | Addr: ip + ":" + port, 89 | }), 90 | t: reflect.TypeOf(type1), 91 | logger: logger, 92 | } 93 | k := strconv.Itoa(rand.Intn(math.MaxUint32)) 94 | // Empty Get 95 | _, found := gc.Get(k) 96 | require.False(t, found) 97 | // Set 98 | v1 := []imdb2torrent.Result{ 99 | { 100 | InfoHash: "123", 101 | MagnetURL: "magnet:?xt=urn:btih:123", 102 | Title: "foo", 103 | Quality: "720p", 104 | }, 105 | { 106 | InfoHash: "456", 107 | MagnetURL: "magnet:?xt=urn:btih:456", 108 | Title: "foo", 109 | Quality: "720p", 110 | }, 111 | } 112 | gc.Set(k, v1, time.Minute) 113 | // Get 114 | res, found := gc.Get(k) 115 | require.True(t, found) 116 | require.Equal(t, v1, res) 117 | 118 | // Type: cacheItem (for stream cache use case) 119 | 120 | var type2 cacheItem 121 | gc.t = reflect.TypeOf(type2) 122 | k = strconv.Itoa(rand.Intn(math.MaxUint32)) 123 | // Empty Get 124 | _, found = gc.Get(k) 125 | require.False(t, found) 126 | // Set 127 | v2 := cacheItem{ 128 | Value: "foo", 129 | Created: time.Now().Truncate(0), // Truncate to strip monotonic clock, which doesn't get included when encoding/decoding 130 | } 131 | gc.Set(k, v2, time.Minute) 132 | // Get 133 | res, found = gc.Get(k) 134 | require.True(t, found) 135 | require.Equal(t, v2, res) 136 | } 137 | 138 | // Doesn't work on Windows in v0.9.0: https://github.com/testcontainers/testcontainers-go/issues/152 139 | // We need to comment out the function to not have the dependency in the go.mod, which leads to compile errors due to the linked bug. 140 | // func startRedis(t *testing.T) (string, string, func()) { 141 | // ctx := context.Background() 142 | // p, err := nat.NewPort("tcp", "6379") 143 | // require.NoError(t, err) 144 | // req := testcontainers.ContainerRequest{ 145 | // Image: "redis:6-alpine", 146 | // ExposedPorts: []string{"6379/tcp"}, 147 | // WaitingFor: wait.ForListeningPort(p), 148 | // } 149 | // redisC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ 150 | // ContainerRequest: req, 151 | // Started: true, 152 | // }) 153 | // require.NoError(t, err) 154 | // ip, err := redisC.Host(ctx) 155 | // if err != nil { 156 | // redisC.Terminate(ctx) 157 | // require.NoError(t, err) 158 | // } 159 | // port, err := redisC.MappedPort(ctx, "6379") 160 | // if err != nil { 161 | // redisC.Terminate(ctx) 162 | // require.NoError(t, err) 163 | // } 164 | 165 | // return ip, port.Port(), func() { redisC.Terminate(ctx) } 166 | // } 167 | -------------------------------------------------------------------------------- /cmd/deflix-stremio/user_data.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/base64" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "strings" 9 | 10 | "go.uber.org/zap" 11 | ) 12 | 13 | type userData struct { 14 | // RealDebrid 15 | RDtoken string `json:"rdToken,omitempty"` 16 | RDoauth2 string `json:"rdOAUTH2,omitempty"` 17 | RDremote bool `json:"rdRemote,omitempty"` 18 | // AllDebrid 19 | ADkey string `json:"adKey,omitempty"` 20 | // Premiumize 21 | PMkey string `json:"pmKey,omitempty"` 22 | PMoauth2 string `json:"pmOAUTH2,omitempty"` 23 | } 24 | 25 | func (ud userData) encode(logger *zap.Logger) (string, error) { 26 | logger.Debug("Encoding user data") 27 | userDataJSON, err := json.Marshal(ud) 28 | if err != nil { 29 | return "", err 30 | } 31 | userDataEncoded := base64.RawURLEncoding.EncodeToString(userDataJSON) 32 | return userDataEncoded, nil 33 | } 34 | 35 | func decodeUserData(data string, logger *zap.Logger) (userData, error) { 36 | logger.Debug("Decoding user data", zap.String("userData", data)) 37 | 38 | // Legacy user data (plain string, RD only). 39 | // - If it's ending with "-remote" it's 100% clear 40 | // - RD API tokens always seem to be 52 chars long 41 | // - Base64 encoded JSON starts with "eyJ" or "eyI" 42 | if strings.HasSuffix(data, "-remote") { 43 | tokenParts := strings.Split(data, "-") 44 | if len(tokenParts) > 2 { 45 | return userData{}, errors.New("legacy userData was not correctly formatted") 46 | } 47 | logger.Info("A legacy API token is being used", zap.Bool("remote", true)) 48 | return userData{ 49 | RDtoken: tokenParts[0], 50 | RDremote: true, 51 | }, nil 52 | } else if len(data) == 52 && !strings.HasPrefix(data, "eyJ") && !strings.HasPrefix(data, "eyI") { 53 | logger.Info("A legacy API token is being used", zap.Bool("remote", false)) 54 | return userData{ 55 | RDtoken: data, 56 | RDremote: false, 57 | }, nil 58 | } 59 | 60 | // If there's padding, we remove it, so that the decoding works with both: 61 | data = strings.TrimSuffix(data, "=") 62 | var userDataDecoded []byte 63 | userDataDecoded, err := base64.RawURLEncoding.DecodeString(data) 64 | if err != nil { 65 | // We use WARN instead of ERROR because it's most likely an *encoding* error on the client side 66 | logger.Warn("Couldn't decode user data", zap.Error(err)) 67 | return userData{}, err 68 | } 69 | 70 | ud := userData{} 71 | if err := json.Unmarshal(userDataDecoded, &ud); err != nil { 72 | logger.Warn("Couldn't unmarshal user data", zap.Error(err)) 73 | return userData{}, err 74 | } 75 | logger.Debug("Decoded user data", zap.String("userData", fmt.Sprintf("%+v", ud))) 76 | return ud, nil 77 | } 78 | -------------------------------------------------------------------------------- /docker/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.15-alpine as builder 2 | 3 | WORKDIR /go/src/app/ 4 | 5 | # We require Bash for executing the build script 6 | RUN apk add --update bash 7 | 8 | # Fill cache with source code of dependencies 9 | COPY go.mod go.sum ./ 10 | RUN go mod download -x 11 | 12 | COPY . . 13 | RUN scripts/build.sh linux 14 | 15 | FROM gcr.io/distroless/static 16 | 17 | COPY --from=builder /go/src/app/deflix-stremio / 18 | COPY --from=builder /go/src/app/web/configure /web/configure 19 | 20 | # Default bind addr is localhost, which wouldn't allow connections from outside the container. 21 | # Should be overwritten when using `--network host` and not wanting to expose the service to other hosts. 22 | ENV BIND_ADDR 0.0.0.0 23 | 24 | # distroless/static `os.UserCacheDir()` leads to "/root/.cache", so the persisted cache will be in "/root/.cache/deflix-stremio/" 25 | # Using a proper volume makes the data accessible outside the container and is apparently faster. 26 | VOLUME [ "/root/.cache/deflix-stremio/" ] 27 | VOLUME [ "/web/configure/" ] 28 | EXPOSE 8080 29 | 30 | # Using ENTRYPOINT instead of CMD allows the user to easily just *add* command line arguments when using `docker run` 31 | ENTRYPOINT ["/deflix-stremio"] 32 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/doingodswork/deflix-stremio 2 | 3 | go 1.15 4 | 5 | require ( 6 | github.com/deflix-tv/go-debrid v0.1.0 7 | github.com/deflix-tv/go-stremio v0.9.2-0.20210202204625-e3e7a578d4d7 8 | github.com/deflix-tv/imdb2meta v0.2.1 9 | github.com/deflix-tv/imdb2torrent v0.1.0 10 | github.com/dgraph-io/badger/v2 v2.2007.2 11 | github.com/go-redis/redis/v8 v8.4.10 12 | github.com/gofiber/fiber/v2 v2.3.3 13 | github.com/google/go-cmp v0.5.4 14 | github.com/markbates/pkger v0.17.1 15 | github.com/patrickmn/go-cache v2.1.0+incompatible 16 | github.com/spf13/afero v1.5.1 17 | github.com/stretchr/testify v1.7.0 18 | go.uber.org/multierr v1.6.0 19 | go.uber.org/zap v1.16.0 20 | golang.org/x/oauth2 v0.0.0-20210113205817-d3ed898aa8a3 21 | google.golang.org/grpc v1.35.0 22 | ) 23 | -------------------------------------------------------------------------------- /pkg/logadapter/badgerdb.go: -------------------------------------------------------------------------------- 1 | package logadapter 2 | 3 | import "go.uber.org/zap" 4 | 5 | type Badger2Zap struct { 6 | *zap.SugaredLogger 7 | } 8 | 9 | // NewBadger2Zap creates a new Badger2Zap logger 10 | func NewBadger2Zap(logger *zap.Logger) *Badger2Zap { 11 | return &Badger2Zap{ 12 | SugaredLogger: logger.Sugar(), 13 | } 14 | } 15 | 16 | func (logger *Badger2Zap) Warningf(template string, args ...interface{}) { 17 | logger.Warnf(template, args...) 18 | } 19 | -------------------------------------------------------------------------------- /pkg/metafetcher/client.go: -------------------------------------------------------------------------------- 1 | package metafetcher 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "strconv" 7 | "time" 8 | 9 | "go.uber.org/zap" 10 | "google.golang.org/grpc" 11 | 12 | "github.com/deflix-tv/go-stremio" 13 | "github.com/deflix-tv/go-stremio/pkg/cinemeta" 14 | "github.com/deflix-tv/imdb2meta/pb" 15 | "github.com/deflix-tv/imdb2torrent" 16 | ) 17 | 18 | var _ stremio.MetaFetcher = (*Client)(nil) 19 | var _ imdb2torrent.MetaGetter = (*Client)(nil) 20 | 21 | // Client is used to implement stremio.MetaFetcher. 22 | type Client struct { 23 | imdb2metaClient pb.MetaFetcherClient 24 | cinemetaClient *cinemeta.Client 25 | conn *grpc.ClientConn 26 | logger *zap.Logger 27 | } 28 | 29 | // NewClient creates a new metafetcher client. 30 | // One of imdb2metaAddress and cinemetaClient can be empty/nil. 31 | // If imdb2metaAddress is passed, an imdb2meta gRPC client is created and used. 32 | // If both are passed, for GetMovie and GetTVShow calls the imdb2meta gRPC client is used first, and only if it fails the cinemetaClient is used. 33 | // You should call Close() when finished. 34 | func NewClient(imdb2metaAddress string, cinemetaClient *cinemeta.Client, logger *zap.Logger) (*Client, error) { 35 | if imdb2metaAddress == "" && cinemetaClient == nil { 36 | return nil, errors.New("one of the arguments must not be empty/nil") 37 | } 38 | 39 | var imdb2metaClient pb.MetaFetcherClient 40 | var conn *grpc.ClientConn 41 | if imdb2metaAddress != "" { 42 | // Set up a connection to the server. 43 | logger.Info("Connecting to imdb2meta gRPC server...", zap.String("address", imdb2metaAddress)) 44 | var err error 45 | ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) 46 | defer cancel() 47 | conn, err = grpc.DialContext(ctx, imdb2metaAddress, grpc.WithInsecure(), grpc.WithBlock()) 48 | if err != nil { 49 | return nil, err 50 | } 51 | imdb2metaClient = pb.NewMetaFetcherClient(conn) 52 | logger.Info("Connected to imdb2meta gRPC server") 53 | } 54 | 55 | return &Client{ 56 | imdb2metaClient: imdb2metaClient, 57 | cinemetaClient: cinemetaClient, 58 | conn: conn, 59 | logger: logger, 60 | }, nil 61 | } 62 | 63 | // GetMovie implements stremio.MetaFetcher. 64 | // Note that if the context has a timeout and it times out during the initial imdb2meta gRPC request, 65 | // the Cinemeta HTTP request will fail immediately. 66 | // TODO: Do both requests in parallel? 67 | func (c *Client) GetMovie(ctx context.Context, imdbID string) (cinemeta.Meta, error) { 68 | if c.imdb2metaClient != nil { 69 | request := &pb.MetaRequest{ 70 | Id: imdbID, 71 | } 72 | res, err := c.imdb2metaClient.Get(ctx, request) 73 | if err == nil { 74 | // No need to fill all data *for our purposes in deflix-stremio* 75 | return cinemeta.Meta{ 76 | ID: res.GetId(), 77 | Name: res.GetPrimaryTitle(), 78 | ReleaseInfo: strconv.Itoa(int(res.GetStartYear())), 79 | }, nil 80 | } 81 | c.logger.Error("Couldn't get movie from imdb2meta gRPC server. Falling back to Cinemeta.", zap.Error(err), zap.String("imdbID", imdbID)) 82 | } 83 | if c.cinemetaClient != nil { 84 | return c.cinemetaClient.GetMovie(ctx, imdbID) 85 | } 86 | return cinemeta.Meta{}, nil 87 | } 88 | 89 | // GetTVShow implements stremio.MetaFetcher. 90 | // Note that if the context has a timeout and it times out during the initial imdb2meta gRPC request, 91 | // the Cinemeta HTTP request will fail immediately. 92 | // TODO: Do both requests in parallel? 93 | func (c *Client) GetTVShow(ctx context.Context, imdbID string, season, episode int) (cinemeta.Meta, error) { 94 | // We only need to know the title of the TV show in general, so the match for the IMDb ID we get passed is fine. 95 | if c.imdb2metaClient != nil { 96 | request := &pb.MetaRequest{ 97 | Id: imdbID, 98 | } 99 | res, err := c.imdb2metaClient.Get(ctx, request) 100 | if err == nil { 101 | // No need to fill all data *for our purposes in deflix-stremio* 102 | return cinemeta.Meta{ 103 | ID: res.GetId(), 104 | Name: res.GetPrimaryTitle(), 105 | ReleaseInfo: strconv.Itoa(int(res.GetStartYear())), 106 | }, nil 107 | } 108 | c.logger.Error("Couldn't get TV show from imdb2meta gRPC server. Falling back to Cinemeta.", zap.Error(err), zap.String("imdbID", imdbID)) 109 | } 110 | if c.cinemetaClient != nil { 111 | return c.cinemetaClient.GetTVShow(ctx, imdbID, season, episode) 112 | } 113 | return cinemeta.Meta{}, nil 114 | } 115 | 116 | // GetMovieSimple implements imdb2torrent.MetaGetter. 117 | func (c *Client) GetMovieSimple(ctx context.Context, imdbID string) (imdb2torrent.Meta, error) { 118 | movieMeta, err := c.GetMovie(ctx, imdbID) 119 | if err != nil { 120 | return imdb2torrent.Meta{}, err 121 | } 122 | year, err := strconv.Atoi(movieMeta.ReleaseInfo) 123 | if err != nil { 124 | c.logger.Error("Couldn't convert movieMeta.ReleaseInfo to int", zap.Error(err), zap.String("releaseInfo", movieMeta.ReleaseInfo)) 125 | return imdb2torrent.Meta{}, err 126 | } 127 | return imdb2torrent.Meta{ 128 | Title: movieMeta.Name, 129 | Year: year, 130 | }, nil 131 | } 132 | 133 | // GetTVShowSimple implements imdb2torrent.MetaGetter. 134 | func (c *Client) GetTVShowSimple(ctx context.Context, imdbID string, season, episode int) (imdb2torrent.Meta, error) { 135 | showMeta, err := c.GetTVShow(ctx, imdbID, season, episode) 136 | if err != nil { 137 | return imdb2torrent.Meta{}, err 138 | } 139 | var year int 140 | if len(showMeta.ReleaseInfo) > 4 { 141 | showMeta.ReleaseInfo = showMeta.ReleaseInfo[:4] 142 | } 143 | year, err = strconv.Atoi(showMeta.ReleaseInfo) 144 | if err != nil { 145 | c.logger.Error("Couldn't convert showMeta.ReleaseInfo to int", zap.Error(err), zap.String("releaseInfo", showMeta.ReleaseInfo)) 146 | return imdb2torrent.Meta{}, err 147 | } 148 | return imdb2torrent.Meta{ 149 | Title: showMeta.Name, 150 | Year: year, 151 | }, nil 152 | } 153 | 154 | func (c *Client) Close() error { 155 | return c.conn.Close() 156 | } 157 | -------------------------------------------------------------------------------- /scripts/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # This script builds deflix-stremio. 4 | # It requires Go to be installed already. 5 | # It doesn't matter what the working directory is when calling this script. 6 | 7 | set -euxo pipefail 8 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" 9 | 10 | if [ "$#" -eq 0 ]; then 11 | echo "You have to pass a target operating system as argument, like windows, darwin or linux" 12 | exit 1 13 | fi 14 | 15 | # Create pkger files 16 | cd "${DIR}/.." 17 | go run github.com/markbates/pkger/cmd/pkger 18 | sed -i "s/package .*/package main/" pkged.go 19 | mv pkged.go cmd/deflix-stremio/ 20 | 21 | # Compile 22 | # Without disabling CGO the binary doesn't run in distroless/static 23 | CGO_ENABLED=0 GOOS="$1" go build -v -ldflags="-s -w" ./cmd/deflix-stremio/ 24 | -------------------------------------------------------------------------------- /web/configure/deflix.css: -------------------------------------------------------------------------------- 1 | :root { 2 | --color: #0f0; 3 | --color-accent: #00ff004f; 4 | --color-bg: #222; 5 | --color-bg-secondary: #555; 6 | --color-secondary: #009f00; 7 | --color-secondary-accent: #009f004f; 8 | --color-shadow: #bbbbbb20; 9 | --color-text: #f7f7f7; 10 | --color-text-secondary: #aaa; 11 | } 12 | 13 | nav{ 14 | --color-secondary: #0f0; 15 | margin-bottom: 30px; 16 | } 17 | 18 | #addons div { 19 | text-align: left; 20 | } 21 | 22 | #comparison table td { 23 | text-align: var(--justify-normal); 24 | } 25 | 26 | header img { 27 | margin-top: 100px; 28 | } 29 | 30 | .promo-banner{ 31 | width: 100%; 32 | background-color: var(--color); 33 | box-shadow: 0px 5px 6px rgba(0, 0, 0, 0.5); 34 | } 35 | 36 | .promo-banner h3{ 37 | margin: 10px 0; 38 | } -------------------------------------------------------------------------------- /web/configure/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/doingodswork/deflix-stremio/df04c6bdd7d611d32810a1114b12fc6bf67bdc90/web/configure/favicon.ico -------------------------------------------------------------------------------- /web/configure/index-apikey.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | Deflix - Debrid flicks 14 | 15 | 16 | 17 |
18 | 24 |
25 |
26 |
27 |

Deflix - Debrid flicks

28 |

Stream movies and TV shows without torrenting.

29 |
30 |
31 |

The Deflix addon for Stremio finds movies and TV shows from many different sources (YTS, The Pirate Bay, 1337x, RARBG and ibit) and automatically 32 | turns them into cached HTTP streams with a debrid service like RealDebrid ↗, 33 | AllDebrid ↗ or Premiumize ↗, for high speed 4k streaming and no P2P uploading.

34 |

The addon is under constant development and more features will be added in the future: Support for more sources, grouping by bitrate, more custom options (like language filter) and more.

35 |

Source code ↗

36 |
37 |
38 |
39 |

Install

40 |

Here you can configure and then install the addon:

41 |
42 |
43 | 44 | 50 | 68 | 80 | 92 |
93 |
94 |
95 | 99 | 100 | 178 | 179 | 180 | -------------------------------------------------------------------------------- /web/configure/index-oauth2.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | Deflix - Debrid flicks 14 | 15 | 16 | 17 |
18 | 24 |
25 |
26 |
27 |

Deflix - Debrid flicks

28 |

Stream movies and TV shows without torrenting.

29 |
30 |
31 |

The Deflix addon for Stremio finds movies and TV shows from many different sources (YTS, The Pirate Bay, 1337x, RARBG and ibit) and automatically 32 | turns them into cached HTTP streams with a debrid service like RealDebrid ↗, 33 | AllDebrid ↗ or Premiumize ↗, for high speed 4k streaming and no P2P uploading.

34 |

The addon is under constant development and more features will be added in the future: Support for more sources, grouping by bitrate, more custom options (like language filter) and more.

35 |

Source code ↗

36 |
37 |
38 |
39 |

Install

40 |

Here you can configure and then install the addon:

41 |
42 |
43 | 44 | 50 | 68 | 80 | 89 |
90 |
91 |
92 | 96 | 97 | 208 | 209 | 210 | -------------------------------------------------------------------------------- /web/configure/mvp.css: -------------------------------------------------------------------------------- 1 | /* MVP.css v1.6.2 - https://github.com/andybrewer/mvp */ 2 | 3 | :root { 4 | --border-radius: 5px; 5 | --box-shadow: 2px 2px 10px; 6 | --color: #118bee; 7 | --color-accent: #118bee15; 8 | --color-bg: #fff; 9 | --color-bg-secondary: #e9e9e9; 10 | --color-secondary: #920de9; 11 | --color-secondary-accent: #920de90b; 12 | --color-shadow: #f4f4f4; 13 | --color-text: #000; 14 | --color-text-secondary: #999; 15 | --font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif; 16 | --hover-brightness: 1.2; 17 | --justify-important: center; 18 | --justify-normal: left; 19 | --line-height: 1.5; 20 | --width-card: 285px; 21 | --width-card-medium: 460px; 22 | --width-card-wide: 800px; 23 | --width-content: 1080px; 24 | } 25 | 26 | /* 27 | @media (prefers-color-scheme: dark) { 28 | :root { 29 | --color: #0097fc; 30 | --color-accent: #0097fc4f; 31 | --color-bg: #333; 32 | --color-bg-secondary: #555; 33 | --color-secondary: #e20de9; 34 | --color-secondary-accent: #e20de94f; 35 | --color-shadow: #bbbbbb20; 36 | --color-text: #f7f7f7; 37 | --color-text-secondary: #aaa; 38 | } 39 | } 40 | */ 41 | 42 | /* Layout */ 43 | article aside { 44 | background: var(--color-secondary-accent); 45 | border-left: 4px solid var(--color-secondary); 46 | padding: 0.01rem 0.8rem; 47 | } 48 | 49 | body { 50 | background: var(--color-bg); 51 | color: var(--color-text); 52 | font-family: var(--font-family); 53 | line-height: var(--line-height); 54 | margin: 0; 55 | overflow-x: hidden; 56 | padding: 1rem 0; 57 | } 58 | 59 | footer, 60 | header, 61 | main { 62 | margin: 0 auto; 63 | max-width: var(--width-content); 64 | padding: 2rem 1rem; 65 | } 66 | 67 | hr { 68 | background-color: var(--color-bg-secondary); 69 | border: none; 70 | height: 1px; 71 | margin: 4rem 0; 72 | } 73 | 74 | section { 75 | display: flex; 76 | flex-wrap: wrap; 77 | justify-content: var(--justify-important); 78 | } 79 | 80 | section aside { 81 | border: 1px solid var(--color-bg-secondary); 82 | border-radius: var(--border-radius); 83 | box-shadow: var(--box-shadow) var(--color-shadow); 84 | margin: 1rem; 85 | padding: 1.25rem; 86 | width: var(--width-card); 87 | } 88 | 89 | section aside:hover { 90 | box-shadow: var(--box-shadow) var(--color-bg-secondary); 91 | } 92 | 93 | section aside img { 94 | max-width: 100%; 95 | } 96 | 97 | [hidden] { 98 | display: none; 99 | } 100 | 101 | /* Headers */ 102 | article header, 103 | div header, 104 | main header { 105 | padding-top: 0; 106 | } 107 | 108 | header { 109 | text-align: var(--justify-important); 110 | } 111 | 112 | header a b, 113 | header a em, 114 | header a i, 115 | header a strong { 116 | margin-left: 0.5rem; 117 | margin-right: 0.5rem; 118 | } 119 | 120 | header nav img { 121 | margin: 1rem 0; 122 | } 123 | 124 | section header { 125 | padding-top: 0; 126 | width: 100%; 127 | } 128 | 129 | /* Nav */ 130 | nav { 131 | align-items: center; 132 | display: flex; 133 | font-weight: bold; 134 | justify-content: space-between; 135 | margin-bottom: 7rem; 136 | } 137 | 138 | nav ul { 139 | list-style: none; 140 | padding: 0; 141 | } 142 | 143 | nav ul li { 144 | display: inline-block; 145 | margin: 0 0.5rem; 146 | position: relative; 147 | text-align: left; 148 | } 149 | 150 | /* Nav Dropdown */ 151 | nav ul li:hover ul { 152 | display: block; 153 | } 154 | 155 | nav ul li ul { 156 | background: var(--color-bg); 157 | border: 1px solid var(--color-bg-secondary); 158 | border-radius: var(--border-radius); 159 | box-shadow: var(--box-shadow) var(--color-shadow); 160 | display: none; 161 | height: auto; 162 | left: -2px; 163 | padding: .5rem 1rem; 164 | position: absolute; 165 | top: 1.7rem; 166 | white-space: nowrap; 167 | width: auto; 168 | } 169 | 170 | nav ul li ul li, 171 | nav ul li ul li a { 172 | display: block; 173 | } 174 | 175 | /* Typography */ 176 | code, 177 | samp { 178 | background-color: var(--color-accent); 179 | border-radius: var(--border-radius); 180 | color: var(--color-text); 181 | display: inline-block; 182 | margin: 0 0.1rem; 183 | padding: 0 0.5rem; 184 | } 185 | 186 | details { 187 | margin: 1.3rem 0; 188 | } 189 | 190 | details summary { 191 | font-weight: bold; 192 | cursor: pointer; 193 | } 194 | 195 | h1, 196 | h2, 197 | h3, 198 | h4, 199 | h5, 200 | h6 { 201 | line-height: var(--line-height); 202 | } 203 | 204 | mark { 205 | padding: 0.1rem; 206 | } 207 | 208 | ol li, 209 | ul li { 210 | padding: 0.2rem 0; 211 | } 212 | 213 | p { 214 | margin: 0.75rem 0; 215 | padding: 0; 216 | } 217 | 218 | pre { 219 | margin: 1rem 0; 220 | max-width: var(--width-card-wide); 221 | padding: 1rem 0; 222 | } 223 | 224 | pre code, 225 | pre samp { 226 | display: block; 227 | max-width: var(--width-card-wide); 228 | padding: 0.5rem 2rem; 229 | white-space: pre-wrap; 230 | } 231 | 232 | small { 233 | color: var(--color-text-secondary); 234 | } 235 | 236 | sup { 237 | background-color: var(--color-secondary); 238 | border-radius: var(--border-radius); 239 | color: var(--color-bg); 240 | font-size: xx-small; 241 | font-weight: bold; 242 | margin: 0.2rem; 243 | padding: 0.2rem 0.3rem; 244 | position: relative; 245 | top: -2px; 246 | } 247 | 248 | /* Links */ 249 | a { 250 | color: var(--color-secondary); 251 | display: inline-block; 252 | font-weight: bold; 253 | text-decoration: none; 254 | } 255 | 256 | a:hover { 257 | filter: brightness(var(--hover-brightness)); 258 | text-decoration: underline; 259 | } 260 | 261 | a b, 262 | a em, 263 | a i, 264 | a strong, 265 | button { 266 | border-radius: var(--border-radius); 267 | display: inline-block; 268 | font-size: medium; 269 | font-weight: bold; 270 | line-height: var(--line-height); 271 | margin: 0.5rem 0; 272 | padding: 1rem 2rem; 273 | } 274 | 275 | button { 276 | font-family: var(--font-family); 277 | } 278 | 279 | button:hover { 280 | cursor: pointer; 281 | filter: brightness(var(--hover-brightness)); 282 | } 283 | 284 | a b, 285 | a strong, 286 | button { 287 | background-color: var(--color); 288 | border: 2px solid var(--color); 289 | color: var(--color-bg); 290 | } 291 | 292 | a em, 293 | a i { 294 | border: 2px solid var(--color); 295 | border-radius: var(--border-radius); 296 | color: var(--color); 297 | display: inline-block; 298 | padding: 1rem 2rem; 299 | } 300 | 301 | /* Images */ 302 | figure { 303 | margin: 0; 304 | padding: 0; 305 | } 306 | 307 | figure img { 308 | max-width: 100%; 309 | } 310 | 311 | figure figcaption { 312 | color: var(--color-text-secondary); 313 | } 314 | 315 | /* Forms */ 316 | 317 | button:disabled, 318 | input:disabled { 319 | background: var(--color-bg-secondary); 320 | border-color: var(--color-bg-secondary); 321 | color: var(--color-text-secondary); 322 | cursor: not-allowed; 323 | } 324 | 325 | button[disabled]:hover { 326 | filter: none; 327 | } 328 | 329 | form { 330 | border: 1px solid var(--color-bg-secondary); 331 | border-radius: var(--border-radius); 332 | box-shadow: var(--box-shadow) var(--color-shadow); 333 | display: block; 334 | max-width: var(--width-card-wide); 335 | min-width: var(--width-card); 336 | padding: 1.5rem; 337 | text-align: var(--justify-normal); 338 | } 339 | 340 | form header { 341 | margin: 1.5rem 0; 342 | padding: 1.5rem 0; 343 | } 344 | 345 | input, 346 | label, 347 | select, 348 | textarea { 349 | display: block; 350 | font-size: inherit; 351 | max-width: var(--width-card-wide); 352 | } 353 | 354 | input[type="checkbox"], 355 | input[type="radio"] { 356 | display: inline-block; 357 | } 358 | 359 | input[type="checkbox"]+label, 360 | input[type="radio"]+label { 361 | display: inline-block; 362 | font-weight: normal; 363 | position: relative; 364 | top: 1px; 365 | } 366 | 367 | input, 368 | select, 369 | textarea { 370 | border: 1px solid var(--color-bg-secondary); 371 | border-radius: var(--border-radius); 372 | margin-bottom: 1rem; 373 | padding: 0.4rem 0.8rem; 374 | } 375 | 376 | input[readonly], 377 | textarea[readonly] { 378 | background-color: var(--color-bg-secondary); 379 | } 380 | 381 | label { 382 | font-weight: bold; 383 | margin-bottom: 0.2rem; 384 | } 385 | 386 | /* Tables */ 387 | table { 388 | border: 1px solid var(--color-bg-secondary); 389 | border-radius: var(--border-radius); 390 | border-spacing: 0; 391 | display: inline-block; 392 | max-width: 100%; 393 | overflow-x: auto; 394 | padding: 0; 395 | white-space: nowrap; 396 | } 397 | 398 | table td, 399 | table th, 400 | table tr { 401 | padding: 0.4rem 0.8rem; 402 | text-align: var(--justify-important); 403 | } 404 | 405 | table thead { 406 | background-color: var(--color); 407 | border-collapse: collapse; 408 | border-radius: var(--border-radius); 409 | color: var(--color-bg); 410 | margin: 0; 411 | padding: 0; 412 | } 413 | 414 | table thead th:first-child { 415 | border-top-left-radius: var(--border-radius); 416 | } 417 | 418 | table thead th:last-child { 419 | border-top-right-radius: var(--border-radius); 420 | } 421 | 422 | table thead th:first-child, 423 | table tr td:first-child { 424 | text-align: var(--justify-normal); 425 | } 426 | 427 | table tr:nth-child(even) { 428 | background-color: var(--color-accent); 429 | } 430 | 431 | /* Quotes */ 432 | blockquote { 433 | display: block; 434 | font-size: x-large; 435 | line-height: var(--line-height); 436 | margin: 1rem auto; 437 | max-width: var(--width-card-medium); 438 | padding: 1.5rem 1rem; 439 | text-align: var(--justify-important); 440 | } 441 | 442 | blockquote footer { 443 | color: var(--color-text-secondary); 444 | display: block; 445 | font-size: small; 446 | line-height: var(--line-height); 447 | padding: 1.5rem 0; 448 | } --------------------------------------------------------------------------------