├── .classpath ├── .gitignore ├── .project ├── .settings ├── org.eclipse.jdt.core.prefs └── org.eclipse.m2e.core.prefs ├── LICENSE ├── Readme.md ├── distribution.zip ├── pom.xml └── src ├── assembly └── bundle.xml ├── main ├── R │ ├── CreateInfographics.r │ └── images │ │ ├── calendar.png │ │ ├── cash.png │ │ ├── clock.png │ │ ├── grandpa.png │ │ ├── hashtag.png │ │ ├── like.png │ │ ├── numberOne.png │ │ ├── running.png │ │ ├── star.png │ │ ├── ticket.png │ │ └── time.png └── java │ ├── com │ └── github │ │ └── kilianB │ │ ├── fileHandling │ │ ├── in │ │ │ ├── NetflixParser.java │ │ │ └── NetflixViewingActivityDownloader.java │ │ └── out │ │ │ ├── CSVMovieWriter.java │ │ │ ├── CSVShowWriter.java │ │ │ └── CSVWriter.java │ │ ├── launcher │ │ └── NetflixAnalyzer.java │ │ └── model │ │ ├── BaseEntityWrapper.java │ │ └── netflix │ │ ├── NetflixMovie.java │ │ ├── NetflixShowEpisode.java │ │ └── ViewItem.java │ └── trakt │ └── TraktHelper.java └── test └── java └── fileHandling └── in └── TestNetflixParser.java /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | /bin/ 3 | /distribution/ 4 | 5 | *.csv 6 | 7 | # History files 8 | .Rhistory 9 | .Rapp.history 10 | 11 | # Session Data files 12 | .RData 13 | 14 | # Compiled class file 15 | *.class 16 | 17 | # Log file 18 | *.log 19 | 20 | # BlueJ files 21 | *.ctxt 22 | 23 | # Mobile Tools for Java (J2ME) 24 | .mtj.tmp/ 25 | 26 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 27 | hs_err_pid* -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | NetflixAnalyzer 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.m2e.core.maven2Builder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.m2e.core.maven2Nature 21 | org.eclipse.jdt.core.javanature 22 | 23 | 24 | -------------------------------------------------------------------------------- /.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 3 | org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate 4 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=10 5 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 6 | org.eclipse.jdt.core.compiler.compliance=10 7 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 8 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 9 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 10 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 11 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 12 | org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning 13 | org.eclipse.jdt.core.compiler.release=disabled 14 | org.eclipse.jdt.core.compiler.source=10 15 | -------------------------------------------------------------------------------- /.settings/org.eclipse.m2e.core.prefs: -------------------------------------------------------------------------------- 1 | activeProfiles= 2 | eclipse.preferences.version=1 3 | resolveWorkspaceProjects=true 4 | version=1 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # Netflix Viewing Activity Visualizer 2 | 3 | Visualize your personal netflix statistics, a small sample project utilizing *new features* found in Java 8, 9 and 10. 4 | 5 | Before you ask, no, I did not accumulate all those hours and episodes on my own. While the viewing history of sub accounts is seperated some people tend to use the service utilizing my profile. 6 | 7 | If you create your own graphics and stumble upon a great looking color theme feel free to send me a message and I'll add a small collection of presets. 8 | 9 | ## Sample Output 10 | 11 | ![netflixinfographics](https://user-images.githubusercontent.com/9025925/44119605-05d28f44-a01a-11e8-9e02-7d381b2d6ff7.png) 12 | 13 | ## Usage 14 | 15 | ### 0. Prerequisites 16 | 17 |
    18 |
  • Java 10 Runtime Environment. 19 |
    Used to parse the viewing activity file and download additional information for movies and series.
  • 20 |
  • R 3.5.1 and RStudio (optional) for visualization
  • 21 |
  • A Trakt account to gain access to a movie metadata database. 22 |
      23 |
    1. Create an account at Trakt.tv
    2. 24 |
    3. Create an "App" to retrieve your api key. https://trakt.tv/oauth/applications/new. All you need to do is choose a random name and put a redirect uri doesn't need to be valid (e.g. "https://localhost.de")
    4. 25 |
    5. Copy the client id and save it somewhere for later usage
    6. 26 |
    27 |
  • 28 |
  • Download the distribution.zip archive and extract the files
  • 29 |
30 | 31 | Check your java version by opening the terminal and type `java -version` 32 | 33 | 34 | ### 1 Gather information regarding your viewing activity 35 | 36 | First we need to retrieve the viewing history file from Netflix. Sadly Netflix offers only a very limited data set, namely the series/movie title as well as the date it was watched. To generate more interesting statistics additional 37 | information like the runtime, genre, actors ... are needed. The java program will query the trakt database and do it's best to collect whatever material it can get it's hands on. 38 | 39 | #### Manually download viewing activity file 40 | 41 | Go to https://www.netflix.com/viewingactivity scroll to the bottom and download your viewing activity file. 42 | 43 | ![download](https://user-images.githubusercontent.com/9025925/44120336-5832a7fe-a01c-11e8-9bad-c5010a6d1e2d.png) 44 | 45 | 46 | Locate the NetflixAnalyzer.jar file and place the downloaded csv alongside the jar 47 | 48 | Open the terminal and type 49 | 50 | ````Shell 51 | cd PathToJarFile 52 | java -jar NetflixAnalyzer.jar traktClientId 53 | ````` 54 | 55 | ![howto0_censored](https://user-images.githubusercontent.com/9025925/44120472-bac779ee-a01c-11e8-8da6-4c5b2a6373bc.jpg) 56 | 57 | __Hint:__ on windows you only need to type `cd` and drag and drop the .jar file in the terminal. This will copy and paste the file location automatically for you. Alternatively you can click the *url bar* of the explorer and copy paste the path. 58 | 59 | Click enter and after a minute 3 additional csv files will appear. Warnings are perfectly fine. 60 | 61 | ![howto1](https://user-images.githubusercontent.com/9025925/44120546-fa10671e-a01c-11e8-9563-8953a3606257.png) 62 | 63 | ### Convert the data to an awesome looking infographic 64 | 65 | Now R comes into play. Fire up R Studio and open the CreateInfographics.r file. (Open the R folder and double click the file). 66 | 67 | __Important__: After the R file opened click `File -> Reopen with encoding` and choose __UTF-8__. 68 | 69 | Scroll down to the settings section (around line 43) and adjust the paths (optinally adjust the color settings). Now you are good to go. Select the entire code block and click run. `Ctrl + A -> Ctrl + Enter` 70 | 71 | ![rhowto](https://user-images.githubusercontent.com/9025925/44121016-989ee03a-a01e-11e8-8634-c4c16e6482c8.png) 72 | 73 | After a few seconds the infographics should be generated. 74 | 75 |

76 | 77 | 78 | 79 | 80 | ## Compile yourself 81 | 82 | 83 | If you wish to modify the code go ahead and clone the repository 84 | `git clone https://github.com/KilianB/NetflixViewingActivityVisualizer.git`. 85 | `mvn package` will run the tests compile classes and bundle the binaries in the distribution.zip. 86 | 87 | 88 | ## Data Accuracy 89 | The netflix viewing activity data can be described as minimalistic at best. Once you started watching an episode/movie it will appear in the history file. We have no way to distinguish if someone just peeked at an item or fully watched it therefor the runtime will be overestimated. On the flipside, if an episode/movie was watched a second time the first entry will be removed from the history file resulting in an underestimation. All you can do is to reguarily download your viewing activity file and merge it to get a better representation of the data. 90 | 91 | Selenium + a daily batch job + h2database anyone? Maybe a great next weekend project. 92 | 93 | A small amount of items are misclassified (movie as a show, show as a movie), either due to the fact that Trakt is not aware of those shows or because the parser's regex isn't good enough. Netflix doesn't make it easy either. Movies may have multiple colons, quotation marks, series may have titles without season number etc. A range of examples can be found in the Unit test TestNetflixParser.java 94 | 95 | 96 | ### 2 Ideas to increase the retrieval rate: 97 | 98 | 1. Attemp to improve the parser (have a look at NetflixParser.java) 99 | 100 | So far I used a rather easy regex, be my guest and improve it: 101 | 102 | ````java 103 | private final static Pattern splitLine = Pattern.compile("\"(?.*)\""+INPUT_DELIMITER+"\"(?<Date>.*)\""); 104 | 105 | /** 106 | * If we have a show try to separate the series, season and episode title 107 | */ 108 | private final static Pattern showPattern = Pattern.compile( 109 | "(?<series>.*(?:(?:Season|Staffel|Part) [0-9]+)(?=:)): (?<epTitle>.*)", 110 | java.util.regex.Pattern.UNICODE_CHARACTER_CLASS); 111 | 112 | /** 113 | * Once we get the season extract the season number 114 | */ 115 | private final static Pattern seasonPattern = Pattern.compile( 116 | "(?<series>.*(?=:)): (?<seasonText>[^0-9]*)(?<season>[0-9]*)", 117 | java.util.regex.Pattern.UNICODE_CHARACTER_CLASS); 118 | ```` 119 | 120 | A catch. Some series don't have season numbers which this regex assumes they do!. 121 | 122 | 2. If Trakt does not return a result when querying for a movie/show try the opposite and see if we receive anything useful. 123 | 124 | Take a look at <a href="src/main/java/com/github/kilianB/launcher/NetflixAnalyzer.java">NetflixAnalyzer.java</a> 125 | 126 | 127 | ## Disclaimer 128 | 129 | The source was never intended to go public therefore no time was spend on the code being understandable or optimized. The main objective was to use some new concepts I haven't had much exposure to recently. 130 | 131 | The interesting stuff happens in the gigantic blob <a href="src/main/java/com/github/kilianB/launcher/NetflixAnalyzer.java">NetflixAnalyzer.java</a> 132 | 133 | 134 | * Java 8 135 | * Method reference :: 136 | * Predicates 137 | * Java 9: 138 | * streams 139 | * lambda expressions 140 | * Java 10 141 | *local variable type inference 142 | 143 | I have no idea how to use R. Everything in the R file should not be considered good coding. I am aware of the glitches in `gridTextMulticolor`. I just wrote it to be good enough for the use cases I encountered. 144 | 145 | 146 | ## License & Credit 147 | 148 | The project is licensed under <a href="">GPLv3</a>. 149 | Icons used were downloaded from <a href="https://www.flaticon.com">flaticon</a> and <a href="freepik.com">freepik</a> and are licensed 150 | by <a href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0" target="_blank">CC 3.0 BY</a>. 151 | Individual authors : 152 | - <a href="https://www.flaticon.com/authors/alfredo-hernandez" title="Alfredo Hernandez">Alfredo Hernandez</a> 153 | - <a href="https://www.flaticon.com/authors/smashicons" title="Smashicons">Smashicons</a> 154 | - <a href="https://www.flaticon.com/authors/vectors-market" title="Vectors Market">Vectors Market</a> 155 | - <a href="http://www.freepik.com" title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a> 156 | - <a href="https://www.flaticon.com/authors/ocha" title="OCHA">OCHA</a> 157 | - <a href="https://www.flaticon.com/authors/alessio-atzeni" title="Alessio Atzeni">Alessio Atzeni</a>. 158 | 159 | The basic theme and layout is based on a blog post by <a href="https://www.r-bloggers.com/r-how-to-layout-and-design-an-infographic/">Al-Ahmadgaid Asaad</a>. 160 | -------------------------------------------------------------------------------- /distribution.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KilianB/NetflixViewingActivityVisualizer/dab2c81b2a43f8d049380fb66820d5d7e4ce3964/distribution.zip -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | <project xmlns="http://maven.apache.org/POM/4.0.0" 2 | xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 | xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4 | <modelVersion>4.0.0</modelVersion> 5 | <groupId>NetflixAnalyzer</groupId> 6 | <artifactId>NetflixAnalyzer</artifactId> 7 | <version>0.0.1-SNAPSHOT</version> 8 | 9 | <properties> 10 | <maven.compiler.source>10</maven.compiler.source> 11 | <maven.compiler.target>10</maven.compiler.target> 12 | <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 13 | </properties> 14 | 15 | 16 | <build> 17 | <sourceDirectory>src</sourceDirectory> 18 | <plugins> 19 | <plugin> 20 | <groupId>org.apache.maven.plugins</groupId> 21 | <artifactId>maven-surefire-plugin</artifactId> 22 | <version>2.22.0</version> 23 | <dependencies> 24 | <dependency> 25 | <groupId>org.junit.jupiter</groupId> 26 | <artifactId>junit-jupiter-engine</artifactId> 27 | <version>5.2.0</version> 28 | </dependency> 29 | <dependency> 30 | <groupId>org.junit.platform</groupId> 31 | <artifactId>junit-platform-surefire-provider</artifactId> 32 | <version>1.2.0</version> 33 | </dependency> 34 | </dependencies> 35 | </plugin> 36 | <plugin> 37 | 38 | <artifactId>maven-assembly-plugin</artifactId> 39 | <version>3.1.0</version> 40 | 41 | <executions> 42 | <execution> 43 | <id>createRunnableJar</id> 44 | <goals> 45 | <goal>single</goal> 46 | </goals> 47 | <phase>package</phase> 48 | <configuration> 49 | <descriptorRefs> 50 | <descriptorRef>jar-with-dependencies</descriptorRef> 51 | </descriptorRefs> 52 | <appendAssemblyId>false</appendAssemblyId> 53 | <finalName>${project.artifactId}</finalName> 54 | <archive> 55 | <manifest> 56 | <mainClass>com.github.kilianB.launcher.NetflixAnalyzer</mainClass> 57 | </manifest> 58 | </archive> 59 | </configuration> 60 | </execution> 61 | <execution> 62 | <id>make-assembly</id> 63 | <phase>package</phase> 64 | <goals> 65 | <goal>single</goal> 66 | </goals> 67 | <configuration> 68 | <descriptors> 69 | <descriptor>src/assembly/bundle.xml</descriptor> 70 | </descriptors> 71 | <appendAssemblyId>false</appendAssemblyId> 72 | <outputDirectory>${project.basedir}</outputDirectory> 73 | <finalName>distribution</finalName> 74 | </configuration> 75 | </execution> 76 | </executions> 77 | </plugin> 78 | 79 | <plugin> 80 | <artifactId>maven-clean-plugin</artifactId> 81 | <version>3.1.0</version> 82 | <configuration> 83 | <filesets> 84 | <fileset> 85 | <directory>${project.basedir}</directory> 86 | <includes> 87 | <include>distribution.zip</include> 88 | <include>distribution/</include> 89 | </includes> 90 | <followSymlinks>false</followSymlinks> 91 | </fileset> 92 | </filesets> 93 | </configuration> 94 | </plugin> 95 | </plugins> 96 | </build> 97 | 98 | <dependencies> 99 | <dependency> 100 | <groupId>com.uwetrottmann.trakt5</groupId> 101 | <artifactId>trakt-java</artifactId> 102 | <version>5.10.0</version> 103 | </dependency> 104 | <dependency> 105 | <groupId>org.apache.commons</groupId> 106 | <artifactId>commons-text</artifactId> 107 | <version>1.4</version> 108 | </dependency> 109 | <dependency> 110 | <groupId>org.junit.jupiter</groupId> 111 | <artifactId>junit-jupiter-api</artifactId> 112 | <version>5.1.0</version> 113 | <!-- <scope>test</scope> see https://bugs.eclipse.org/bugs/show_bug.cgi?id=526828 --> 114 | </dependency> 115 | 116 | 117 | <!-- <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> 118 | <version>3.14.0</version> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> 119 | <artifactId>selenium-chrome-driver</artifactId> <version>3.14.0</version> 120 | </dependency> --> 121 | </dependencies> 122 | </project> -------------------------------------------------------------------------------- /src/assembly/bundle.xml: -------------------------------------------------------------------------------- 1 | <assembly xmlns="http://maven.apache.org/ASSEMBLY/2.0.0" 2 | xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 | xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.0.0 http://maven.apache.org/xsd/assembly-2.0.0.xsd"> 4 | <id>bundle</id> 5 | <formats> 6 | <format>zip</format> 7 | </formats> 8 | <includeBaseDirectory>false</includeBaseDirectory> 9 | <fileSets> 10 | <fileSet> 11 | <directory>${project.basedir}/src/main</directory> 12 | <outputDirectory>/</outputDirectory> 13 | <includes> 14 | <include>*R/**</include> 15 | </includes> 16 | </fileSet> 17 | <fileSet> 18 | <directory>${project.build.directory}</directory> 19 | <outputDirectory>/</outputDirectory> 20 | <includes> 21 | <include>${project.artifactId}.jar</include> 22 | </includes> 23 | </fileSet> 24 | </fileSets> 25 | </assembly> -------------------------------------------------------------------------------- /src/main/R/CreateInfographics.r: -------------------------------------------------------------------------------- 1 | # CreateInfographics.r 2 | # Copyright (C) 2018 Kilian Brachtendorf 3 | # This code is licensed under GPL v3. For further information and the license of the images used 4 | # please refer to http://github.com/kilianB/NetflixAnalyzer 5 | 6 | #Helper functions 7 | 8 | #' Install and load libaries 9 | #' 10 | #' @param library names in a vector to be installed and loaded. Libraries already present 11 | #' will not be installed. The loading occurs in the order the libs are mentioned in the vector 12 | #' 13 | #' @return nothing 14 | #' @export 15 | #' 16 | #' @examples 17 | #' installAndLoadLibraries(c("zoo","ggplot")) 18 | installAndLoadLibraries <- function(libNames) { 19 | notInstalledLibs <- libNames[!(libNames %in% .packages(all = TRUE))] 20 | if (length(notInstalledLibs) != 0) { 21 | install.packages(notInstalledLibs) 22 | } 23 | invisible(lapply(libNames, FUN = require, character.only = TRUE)) 24 | } 25 | 26 | librariesToLoad <- c("grid","extrafont","lubridate","plyr","scales","zoo", 27 | "reshape2","dplyr","tidyr","ggridges","ggplot2","magick", 28 | "rlist") 29 | installAndLoadLibraries(librariesToLoad) 30 | rm(librariesToLoad,installAndLoadLibraries) 31 | 32 | #Load fonts before ggplot 2? 33 | 34 | if(!"Impact" %in% fonts()){ 35 | font_import(prompt = FALSE) 36 | } 37 | loadfonts() 38 | 39 | ##Define custom date format 40 | setClass("customDate",representation(Date = "Date")) 41 | setAs("character","customDate",function(from) as.Date(from,format="%d/%m/%Y")) 42 | 43 | ############################################################################################### 44 | # Settings # 45 | ############################################################################################### 46 | 47 | # Path to the extracted .csv files and images 48 | setwd("C:/Users/Kilian/git/NetflixViewingactivityVisualizer/distribution/R"); 49 | # Path of the final infographics 50 | outputPath <- "C:/Users/Kilian/git/NetflixViewingactivityVisualizer/distribution/R/NetflixInfographics.png" 51 | 52 | ###Theme 53 | 54 | #Plot and image color 55 | primaryColor <- "#552683" 56 | #Heatmap low range color 57 | primaryColorBright <- "#be7cff" 58 | #Axis color and sections 59 | secondaryColor <- "#E7A922" 60 | #Heading color 61 | headingColor <- "white" 62 | #Plot background color 63 | backgroundColor <- "#E2E2E3" 64 | #Footer text 65 | footerColor <- "#d8d8d8" 66 | #Summary background text 67 | summaryColor <- "#CA8B01" 68 | #Infographics header text 69 | infoColor <- "#A9A8A7" 70 | 71 | netflixCostPerMonth <- (13.99 / 4) 72 | currency <- "€" 73 | averageCinemaTicket <- 8.63 #https://www.statista.com/statistics/382600/cinema-ticket-price-germany/ 74 | 75 | # To calculate the cost/episode we need to know how how many months we are already paying 76 | # TRUE : Current. FALSE last mentioned in history file 77 | useCurrentDate <- TRUE #FALSE 78 | 79 | ############################################################################################### 80 | # Helper Function And Themes # 81 | ############################################################################################### 82 | 83 | #https://stackoverflow.com/a/42997511/3244464 84 | #TODO fix. sunday is still last week. We shit but this causes inconsistencies 85 | # at months with the first day of the week being a sunday. e.g. the 1st of april 2018 86 | firstDayOfMonth <- function(date){ 87 | day(date) <- 1 88 | wday(date) 89 | } 90 | 91 | #' Capitalize the first letter of the given string 92 | #' 93 | #' @param str String 94 | #' 95 | #' @return the str with the first letter capitalized 96 | capitalize <- function(str){ 97 | paste(toupper(substr(str, 1, 1)), substr(str, 2, nchar(str)), sep="") 98 | } 99 | 100 | # https://stackoverflow.com/a/26640698/3244464 101 | elapsed_months <- function(end_date, start_date) { 102 | ed <- as.POSIXlt(end_date) 103 | sd <- as.POSIXlt(start_date) 104 | 12 * (ed$year - sd$year) + (ed$mon - sd$mon) 105 | } 106 | 107 | 108 | #'String length based on viewport aestehtics consideration 109 | #' 110 | #' @param x string length should be evaluated of 111 | #' 112 | #' @return the length of the string absed on font size and font familiy of the current viewport 113 | #' @export 114 | #' 115 | #' @examples 116 | stringLength <- function(x){ 117 | calcStringMetric(x)$width 118 | } 119 | 120 | 121 | #' Print a multiline multi color text on the current grid. This method attempts to mimic the 122 | #' same functionality as grid.print but with added support of colors 123 | #' 124 | #' @param x xLocation of the text in npc units 125 | #' @param y yLocation of the text in npc units 126 | #' @param txt vector of text being printed 127 | #' @param col vector of colors applied to the same index of txt. Empty strings "" and online line breaks "\\n" 128 | #' will not be counted toward index mapping 129 | #' @param fontSize The font size of the printed text 130 | #' @param fontFamiliy The font familiy of the printed text 131 | #' @param rightAlign if TRUE right align the text. if false left align (default) 132 | #' 133 | #' @return nothing. prints text on plot 134 | #' @export 135 | #' 136 | #' @examples 137 | #' grid.newpage() 138 | #' pushViewport(viewport()) 139 | #' gridTextMulticolor(x = unit(0.5,"npc"), y = unit(0.5,"npc"), c("Red Text","Blue Text\n","Orange Text"), 140 | #' col = c("Red","Blue","Orange")) 141 | gridTextMulticolor<-function(x,y,txt,col,fontSize = 1, fontFamiliy = "Impact", rightAlign = FALSE) { 142 | 143 | if(!is.unit(x) || !is.unit(y)){ 144 | stop("X and Y have to be npc units") 145 | } 146 | 147 | #Find all line breaks which might be nested inside strings 148 | txt <- unlist(sapply(gsub(pattern = "\n",replacement = "$§$\n$§$",x = txt),split="$§$",fixed=TRUE,FUN = strsplit), use.names = FALSE) 149 | txt[txt != ""] 150 | 151 | #We need to set the cex and font families default for calcStringMetric 152 | #There has to be a better way e.g. using update_geom_defaults but for now 153 | #just create a new viewport and use it 154 | currentViewPort <- current.viewport() 155 | pushViewport(viewport(gp = gpar(fontfamily = fontFamiliy, cex = fontSize)),recording = FALSE) 156 | 157 | thisx <- x 158 | thisy <- y 159 | 160 | lineHeight <- convertHeight(unit(calcStringMetric(text = "\n")$ascent,"inches"),unitTo = "npc") 161 | #lineHeight <- get.gpar()$lineheight 162 | #Join the string to one big string and seperate it by line breaks 163 | 164 | maxLineWidth <- 165 | convertWidth( 166 | unit(max(sapply(strsplit(paste(c(txt), collapse=""),"\n"),FUN = stringLength)) 167 | ,units="inches"),unitTo = "npc") 168 | 169 | #To support hjust get the current line width and devide by the max line width for proper alignment 170 | 171 | colIndex <- 1 172 | if(!rightAlign){ 173 | for(i in 1:length(txt)) { 174 | if(grepl("\n",txt[i],fixed=TRUE)){ 175 | #Reset x 176 | thisx <- x 177 | thisy <- thisy - lineHeight 178 | }else{ 179 | grid.text(vp = currentViewPort, txt[i],x = thisx, y = thisy, gp = gpar(fontfamily = fontFamiliy, col = col[colIndex], cex = fontSize),just=0) 180 | thisx<-thisx+convertWidth(unit(calcStringMetric(txt[i])$width,"inches"),"npc") * fontSize 181 | colIndex <- colIndex +1 182 | } 183 | } 184 | }else{ 185 | 186 | lineCount <- 1 187 | tokensByLine <- list() 188 | tokensByLine[[1]] <- list() 189 | for(token in txt){ 190 | if(token == "\n"){ 191 | lineCount <- lineCount + 1 192 | tokensByLine[[lineCount]] <- list() 193 | }else{ 194 | tokensByLine[[lineCount]] <- append(tokensByLine[[lineCount]],token) 195 | } 196 | } 197 | #for each token 198 | 199 | for(line in tokensByLine){ 200 | 201 | colIndex <- (colIndex + length(line)-1) 202 | 203 | for(i in length(line):1){ 204 | grid.text(vp = currentViewPort, line[i],x = thisx, y = thisy, gp = gpar(fontfamily = fontFamiliy, col = col[colIndex], cex = fontSize),just=1) 205 | thisx<-thisx-convertWidth(unit(calcStringMetric(line[i])$width,"inches"),"npc") * fontSize 206 | colIndex <- colIndex - 1 207 | } 208 | #Reset x 209 | thisx <- x 210 | thisy <- thisy - lineHeight 211 | 212 | colIndex <- colIndex + length(line) 213 | 214 | } 215 | } 216 | #Remove the artificially created viewport 217 | popViewport(recording = FALSE) 218 | } 219 | 220 | 221 | ## function 222 | vplayout <- function(x,y) 223 | viewport(layout.pos.row = x, layout.pos.col = y) 224 | 225 | # Configure theme 226 | kobe_theme <- function() { 227 | theme( 228 | plot.background = element_rect(fill = backgroundColor, colour = backgroundColor), 229 | panel.background = element_rect(fill = backgroundColor), 230 | axis.text = element_text(colour = secondaryColor, family = "Impact"), 231 | plot.title = element_text(colour = primaryColor, face = "bold", size = 18, hjust = 0.5, family = "Impact"), 232 | axis.title = element_text(colour = primaryColor, face = "bold", size = 13, family = "Impact"), 233 | panel.grid.major.x = element_line(colour = secondaryColor), 234 | panel.grid.minor.x = element_blank(), 235 | panel.grid.major.y = element_blank(), 236 | panel.grid.minor.y = element_blank(), 237 | strip.text = element_text(family = "Impact", colour = headingColor), 238 | strip.background = element_rect(fill = secondaryColor), 239 | axis.ticks = element_line(colour = secondaryColor) 240 | ) 241 | } 242 | 243 | kobe_theme2 <- function() { 244 | theme( 245 | legend.position = "bottom", legend.title = element_text(family = "Impact", colour = primaryColor, size = 10), 246 | legend.background = element_rect(fill = backgroundColor), 247 | legend.key = element_rect(fill = backgroundColor, colour = backgroundColor), 248 | legend.text = element_text(family = "Impact", colour = secondaryColor, size = 10), 249 | plot.background = element_rect(fill = backgroundColor, colour = backgroundColor), 250 | panel.background = element_rect(fill = backgroundColor), 251 | axis.text = element_text(colour = secondaryColor, family = "Impact"), 252 | plot.title = element_text(colour = primaryColor, face = "bold", size = 18, hjust = 0.5, family = "Impact"), 253 | axis.title = element_text(colour = primaryColor, face = "bold", size = 13, family = "Impact"), 254 | panel.grid.major.y = element_line(colour = secondaryColor), 255 | panel.grid.minor.y = element_blank(), 256 | panel.grid.major.x = element_blank(), 257 | panel.grid.minor.x = element_blank(), 258 | strip.text = element_text(family = "Impact", colour = headingColor), 259 | strip.background = element_rect(fill = secondaryColor), 260 | axis.ticks = element_line(colour = secondaryColor) 261 | ) 262 | } 263 | 264 | 265 | 266 | ############################################################################################### 267 | # Data Prep # 268 | ############################################################################################### 269 | clockImage <- image_colorize(image_read("images/time.png"),opacity=100,color =primaryColor) 270 | heartImage <- image_colorize(image_read("images/like.png"),opacity=100,color =primaryColor) 271 | marathonImage <- image_colorize(image_read("images/running.png"),opacity=100,color =primaryColor) 272 | hashtagImage <- image_colorize(image_read("images/hashtag.png"),opacity=100,color =primaryColor) 273 | starImage <- image_colorize(image_read("images/star.png"),opacity=100,color =primaryColor) 274 | cashImage <- image_colorize(image_read("images/cash.png"),opacity=100,color =primaryColor) 275 | ticketImage <- image_colorize(image_read("images/ticket.png"),opacity=100,color =primaryColor) 276 | grandpaImage <- image_colorize(image_read("images/grandpa.png"),opacity=100,color =primaryColor) 277 | numberOne <- image_colorize(image_read("images/numberOne.png"),opacity=100,color =primaryColor) 278 | 279 | movieHistory <- read.csv("../MovieViewingHistory.csv",sep = ";",colClasses = c("customDate","factor","integer","factor","Date","character")) 280 | showHistory <- read.csv("../ShowViewingHistory.csv",sep =";",colClasses = c("customDate","factor","factor","integer","integer","factor","customDate","factor","character")) 281 | unknownHistory <- read.csv("../UnknownViewingHistory.csv",sep =";",colClasses = c("customDate","factor","factor","factor")) 282 | 283 | ##Prepare genre data 284 | 285 | movieHistory.long <- movieHistory %>% 286 | mutate(Genres = strsplit(substring(movieHistory$Genres,2,nchar(movieHistory$Genres)-1),", ")) %>% 287 | unnest(Genres) 288 | movieHistory.long$dummy <- 1 289 | #Drop unnecessary fields 290 | genre.movie <- movieHistory.long[,6:7] 291 | 292 | showHistory.long <- showHistory %>% 293 | mutate(Genres = strsplit(substring(showHistory$Genres,2,nchar(showHistory$Genres)-1),", ")) %>% 294 | unnest(Genres) 295 | showHistory.long$dummy <- 1 296 | genre.show <- showHistory.long[,9:10] 297 | 298 | genre <- rbind(genre.movie,genre.show) 299 | 300 | genre <- aggregate(genre$dummy, by=list(Category=genre$Genres), FUN = sum) 301 | colnames(genre) <- c("Genre","Count") 302 | genre <- genre[order(genre$Count,decreasing = TRUE),] 303 | 304 | #Some sample plots 305 | #movieHistory.long %>% ggplot(aes(x=Released,y=Genres)) + geom_point(size=2, shape=23) + kobe_theme() 306 | #movieHistory %>% ggplot(aes(x=Released,y=Runtime)) + geom_point(size=2, shape=23) 307 | #movieHistory %>% ggplot(aes(x=Released,y=Released)) + geom_point(size=2, shape=23) 308 | 309 | ##### Runtime 310 | 311 | dates <- c(movieHistory$Date,showHistory$Date,unknownHistory$Date) 312 | runtime.Total <- sum(c(movieHistory$Runtime,showHistory$Runtime)) 313 | runtime.Combined <- rbind(showHistory[,c(1,5)],movieHistory[,c(1,3)]) 314 | 315 | #Runtime by day 316 | runtime.ByDay <- aggregate(runtime.Combined$Runtime, by=list(Category=runtime.Combined$Date), FUN = sum) 317 | colnames(runtime.ByDay) <- c("Date","Runtime") 318 | 319 | ##Runtime by series 320 | runtime.BySeries <- aggregate(showHistory$Runtime, by=list(Category=showHistory$Series), FUN = sum) 321 | colnames(runtime.BySeries) <- c("Series","Runtime") 322 | 323 | episodeCountBySeries <- showHistory 324 | episodeCountBySeries$dummy <- 1 325 | episodeCountBySeries <- aggregate(episodeCountBySeries$dummy, by=list(Category=episodeCountBySeries$Series), FUN = sum) 326 | colnames(episodeCountBySeries) <- c("Series","Episode Count") 327 | 328 | ## Prepare calendar heatmap (based on http://r-statistics.co/Top50-Ggplot2-Visualizations-MasterList-R-Code.html) 329 | 330 | # Init heat map data 331 | hmd <- runtime.ByDay 332 | dayRange <- seq.Date(from = min(runtime.ByDay$Date),to= max(runtime.ByDay$Date), by ="days") 333 | 334 | 335 | #Select all days which are not present in the original data (e.g. we didn't watch anything at those) 336 | missingDates <- data.frame(dayRange[!(dayRange %in% runtime.ByDay$Date)]) 337 | missingDates$Runtime <- NA 338 | colnames(missingDates)[1] <- "Date" 339 | 340 | hmd <- rbind(runtime.ByDay,missingDates) 341 | hmd$year <- as.numeric(format(hmd$Date,"%Y")) 342 | hmd$month <- as.numeric(format(hmd$Date,"%m")) 343 | hmd$monthf<-factor(hmd$month,levels=as.character(1:12),labels=c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"),ordered=TRUE) 344 | hmd$weekday <- as.POSIXlt(hmd$Date)$wday 345 | ##We don't work with american date formats here (sunday is 7 not 0...) 346 | hmd$weekday[hmd$weekday==0] <- 7 347 | hmd$weekdayf <- factor(hmd$weekday,levels=rev(1:7),labels=rev(c("Mon","Tue","Wed","Thu","Fri","Sat","Sun")),ordered=TRUE) 348 | #Calculate the week of the moneth 349 | hmd$yearmonth <- as.yearmon(hmd$Date) 350 | hmd$yearmonthf<-factor(hmd$yearmonth) 351 | hmd$weekOfMonth <- ceiling(as.numeric(day(hmd$Date) + firstDayOfMonth(hmd$Date) - 2)/7) 352 | 353 | ##Insert dummy empty values for days we have not watched anythign 354 | heatmap <- ggplot(hmd, aes(weekOfMonth, weekdayf, fill = Runtime)) + 355 | geom_tile(colour = headingColor) + facet_grid(year~monthf) + scale_fill_gradient(low=primaryColorBright, high=primaryColor, na.value = "#cecccc") + 356 | ggtitle("Time Watched") + xlab("\n\nWeek of Month") + ylab("") + scale_x_continuous(limits = c(0, 5)) + 357 | coord_fixed() 358 | 359 | heatmap <- heatmap + kobe_theme2() 360 | rm(hmd,dayRange,missingDates) 361 | 362 | 363 | 364 | 365 | 366 | ## Calculate money 367 | 368 | if(useCurrentDate){ 369 | monthsNetflixOwned <- elapsed_months( Sys.time(),min(dates)) 370 | }else{ 371 | monthsNetflixOwned <- elapsed_months(max(dates),min(dates)) 372 | } 373 | 374 | totalCost <- netflixCostPerMonth * monthsNetflixOwned 375 | 376 | costPerHour <- round(totalCost / (runtime.Total/60),2) 377 | 378 | cinemaVisits <- round(totalCost/averageCinemaTicket) 379 | 380 | rm(totalCost,monthsNetflixOwned) 381 | 382 | ## Prepare data 383 | showHistoryNetworkCount <- showHistory 384 | showHistoryNetworkCount$dummy <- 1 385 | showHistoryNetworkCount <- aggregate(showHistoryNetworkCount$dummy, by=list(Category=showHistoryNetworkCount$Network), FUN = sum) 386 | showHistoryNetworkCount$grp <- "Network" 387 | 388 | ############################################################################################### 389 | # Prepare plots # 390 | ############################################################################################### 391 | 392 | ##Movie 393 | movieCertificates <- movieHistory 394 | movieCertificates$dummy <- 1 395 | movieCertificates <- aggregate(movieCertificates$dummy, by=list(Category=movieCertificates$Certificate), FUN = sum) 396 | movieCertificates$group <- "Rating (Movie)" 397 | levels(movieCertificates$Category)<- ordered(c("Unknown",levels(movieCertificates$Category))) 398 | movieCertificates$Category[movieCertificates$Category == "null"] <- as.factor("Unknown") 399 | #movieCertificates 400 | 401 | graphCountByCertificate <- ggplot(data = movieCertificates, aes(x = Category, y = x)) + 402 | geom_bar(stat = "identity", fill = primaryColor) + coord_polar() + xlab("Rating") + ylab("") 403 | graphCountByCertificate <- graphCountByCertificate + kobe_theme2() 404 | #graphCountByCertificate 405 | 406 | ##Show 407 | showCertificates <- showHistory 408 | showCertificates$dummy <- 1 409 | showCertificates <- aggregate(showCertificates$dummy, by=list(Category=showCertificates$Certificate), FUN = sum) 410 | showCertificates$group <- "Rating (Movie)" 411 | levels(showCertificates$Category)<- ordered(c("Unknown",levels(showCertificates$Category))) 412 | showCertificates$Category[showCertificates$Category == "null"] <- as.factor("Unknown") 413 | #showCertificates 414 | 415 | #Runtime 416 | #Calculate frequency bins hist(x, breaks=br, include.lowest=TRUE, plot=FALSE) We never use it but maybe 417 | # still usefull in the future? 418 | frequencies <- hist(movieHistory$Runtime, breaks=6, include.lowest=TRUE, plot=FALSE) 419 | ##TODO actually print breaks lower limit to limt before 420 | movieRuntimeFrequencies <- data.frame(frequencies$mids,frequencies$counts) 421 | colnames(movieRuntimeFrequencies) <- c("Category","x") 422 | movieRuntimeFrequencies$group <- "Runtime" 423 | 424 | 425 | ##Runtime by weekday 426 | runtime.ByWeekDay <-runtime.ByDay 427 | runtime.ByWeekDay$weekDay <- as.POSIXlt(runtime.ByWeekDay$Date)$wday 428 | 429 | runtime.ByWeekDay <- aggregate(runtime.ByWeekDay$Runtime, by=list(Category=runtime.ByWeekDay$weekDay), FUN = sum) 430 | runtime.ByWeekDay$Category[runtime.ByWeekDay$Category==0] <- 7 431 | runtime.ByWeekDay$Category <- factor(runtime.ByWeekDay$Category,levels=1:7,labels=c("Mon","Tue","Wed","Thu","Fri","Sat","Sun"),ordered=TRUE) 432 | 433 | graphRuntimeByDay <- ggplot(data = runtime.ByWeekDay, aes(x = Category, y = x)) + 434 | geom_bar(stat = "identity", fill = primaryColor) + coord_polar() + xlab("min") + ylab("") 435 | graphRuntimeByDay <- graphRuntimeByDay + kobe_theme2() 436 | 437 | #Runtime by month 438 | runtime.ByMonth <- runtime.ByDay 439 | runtime.ByMonth$month <- as.POSIXlt(runtime.ByMonth$Date)$mon + 1 440 | runtime.ByMonth <- aggregate(runtime.ByMonth$Runtime, by=list(Category=runtime.ByMonth$month), FUN = sum) 441 | runtime.ByMonth$Category <- factor(runtime.ByMonth$Category,levels=as.character(1:12),labels=c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"),ordered=TRUE) 442 | graphRuntimeByMonth <- ggplot(data = runtime.ByMonth, aes(x = Category, y = x)) + xlab("min") + ylab("") + 443 | geom_bar(stat = "identity", fill = primaryColor) + coord_polar() + kobe_theme2() 444 | 445 | ##Movie Genre 446 | barGenre <- ggplot(data = genre, aes(x = Genre, y = Count)) + geom_bar(stat = "identity", fill = primaryColor) + 447 | coord_flip() + ylab("Network") + kobe_theme2()+ ylab("Y LABEL") + xlab("X LABEL") # 448 | 449 | 450 | #Barplot 451 | mostWatchedSeries <- runtime.BySeries[order(runtime.BySeries$Runtime,decreasing = TRUE),][1:10,] 452 | 453 | mostEpisodeGraph <- ggplot(data = mostWatchedSeries, aes(x = Series, y = Runtime)) + geom_bar(stat = "identity", fill = primaryColor) + 454 | coord_flip() +xlab("")+ kobe_theme() + ylab("Runtime (min)") 455 | 456 | networkGraph <- ggplot(data = showHistoryNetworkCount, aes(x = Category, y = x)) + geom_bar(stat = "identity", fill = primaryColor) + 457 | coord_flip() +xlab("")+ kobe_theme() + ylab("Episodes") 458 | 459 | genreGraph <- ggplot(data = genre, aes(x = Genre, y = Count)) + geom_bar(stat = "identity", fill = primaryColor) + 460 | coord_flip() +xlab("")+ kobe_theme() + ylab("Episodes & Movies") 461 | 462 | 463 | ##Create timline chart 464 | 465 | tenFavoriteSeries <- runtime.BySeries[order(runtime.BySeries$Runtime,decreasing = TRUE),][1:10,1] 466 | episodesOfFavoriteSeries <- showHistory[showHistory$Series %in% tenFavoriteSeries,] 467 | 468 | 469 | #Long format 470 | epStartEndDateLong <- rbind( 471 | aggregate(episodesOfFavoriteSeries$Date, by = list(episodesOfFavoriteSeries$Series), min), 472 | aggregate(episodesOfFavoriteSeries$Date, by = list(episodesOfFavoriteSeries$Series), max) 473 | ) 474 | 475 | 476 | #Short format 477 | epStartEndDate <- merge( 478 | aggregate(episodesOfFavoriteSeries$Date, by = list(episodesOfFavoriteSeries$Series), min), 479 | aggregate(episodesOfFavoriteSeries$Date, by = list(episodesOfFavoriteSeries$Series), max), 480 | by="Group.1" 481 | ) 482 | 483 | colnames(epStartEndDate) <- c("Series","Begin","End") 484 | colnames(epStartEndDateLong) <- c("Series","Date") 485 | 486 | seriesTimeline <- ggplot(epStartEndDateLong,aes(Series,Date)) + coord_flip() + kobe_theme2() + scale_y_date(date_breaks="10 days",labels=date_format("%b ‘%y"))+ 487 | geom_line(size=6,color = primaryColor) + geom_point(data=episodesOfFavoriteSeries,aes(Series,Date),color=primaryColorBright, alpha = 5/10) + 488 | theme(axis.text.x=element_text(angle=45, hjust=1), plot.margin = margin(5.5,5.5,30,5.5)) + ggtitle("Series - Time ") 489 | 490 | rm(tenFavoriteSeries,episodesOfFavoriteSeries,epStartEndDate) 491 | 492 | ############################################################################################### 493 | # Construct Graphics # 494 | ############################################################################################### 495 | 496 | ySummaryTitle <- unit(0.890, "npc") 497 | ySummaryContent <- ySummaryTitle - unit(0.07, "npc") 498 | xSummaryTitle <- unit(0.01, "npc") 499 | xPaddingSummaryContent <- unit(0.2, "npc") 500 | xPaddingSummayTitle <- unit(0.8, "npc") 501 | 502 | 503 | png(outputPath, width = 10, height = 25, units = "in", res = 500, type = "cairo") 504 | grid.newpage() 505 | pushViewport(viewport(layout = grid.layout(5, 3))) 506 | 507 | #Background 508 | grid.rect(gp = gpar(fill = backgroundColor, col = backgroundColor)) 509 | #Upper banner 510 | grid.rect(gp = gpar(fill = secondaryColor, col = secondaryColor), x = unit(0.5, "npc"), y = unit(0.85, "npc"), width = unit(1, "npc"), height = unit(0.10, "npc")) 511 | 512 | grid.text("INFOGRAPHIC", y = unit(1, "npc"), x = unit(0.5, "npc"), vjust = 1, hjust = .5, gp = gpar(fontfamily = "Impact", col = infoColor, cex = 12, alpha = 0.3)) 513 | grid.text("Netflix Viewing Statistics", y = unit(0.94, "npc"), gp = gpar(fontfamily = "Impact", col = secondaryColor, cex = 5.8)) 514 | 515 | # Date span watched 516 | grid.text(paste(format(min(dates), format("%d.%m.%y")), 517 | "-", 518 | format(max(dates), format("%d.%m.%y"))), vjust = 0, hjust = 0, x = unit(0.01, "npc"), y = unit(0.905, "npc"), gp = gpar(fontfamily = "Impact", col = primaryColor, cex = 1.2)) 519 | 520 | grid.text("SUMMARY", y = unit(0.85, "npc"), x = unit(0.5, "npc"), vjust = .5, hjust = .5, gp = gpar(fontfamily = "Impact", col = summaryColor, cex = 13, alpha = 0.3)) 521 | 522 | #####Section 523 | 524 | ## Show 525 | grid.text("SHOWS", vjust = 0, hjust = 0, x = xSummaryTitle, y = ySummaryTitle, gp = gpar(fontfamily = "Impact", col = headingColor, cex = 1.5)) 526 | grid.raster(hashtagImage, x = unit(0.035, "npc"), y = unit(0.866, "npc"), width = unit(0.06, "npc")) 527 | grid.text(paste(length(unique(showHistory$Series))," Shows","\n",paste(sum(episodeCountBySeries$`Episode Count`)," Episodes")), 528 | vjust = 1, hjust = 0, x = unit(0.08, "npc"), y = unit(0.875, "npc"), gp = gpar(fontfamily = "Impact", col = primaryColor, cex = 1.1)) 529 | 530 | grid.raster(starImage, x = unit(0.035, "npc"), y = unit(0.822, "npc"), width = unit(0.06, "npc")) 531 | favoriteSeriesRuntime <- runtime.BySeries[order(runtime.BySeries$Runtime,decreasing = TRUE),][1,] 532 | favoriteSeriesEpisode <- episodeCountBySeries[order(episodeCountBySeries$`Episode Count`,decreasing = TRUE),][1,] 533 | 534 | grid.text( paste(favoriteSeriesRuntime$Series," (",favoriteSeriesRuntime$Runtime," min)","\n", 535 | favoriteSeriesEpisode$Series," (",favoriteSeriesEpisode$`Episode Count`," Episodes)"), 536 | vjust = 1, hjust = 0, x = unit(0.08, "npc"), y = unit(0.828, "npc"), gp = gpar(fontfamily = "Impact", col = primaryColor, cex = 1.1)) 537 | 538 | rm(favoriteSeriesEpisode,favoriteSeriesRuntime) 539 | 540 | ## Records 541 | grid.text("MISCELLANEOUS", vjust = 0, hjust = 0.5, x = unit(0.5,"npc"), y = ySummaryTitle, gp = gpar(fontfamily = "Impact", col = headingColor, cex = 1.5)) 542 | grid.raster(clockImage, x = unit(0.45, "npc"), y = unit(0.87, "npc"), width = unit(0.06, "npc")) 543 | grid.text(paste(seconds_to_period(sum(runtime.Combined$Runtime)*60)), vjust = 0, hjust = 0, x = unit(0.5, "npc"), y = unit(0.87, "npc"), gp = gpar(fontfamily = "Impact", col = primaryColor, cex = 1)) 544 | 545 | grid.raster(heartImage, x = unit(0.45, "npc"), y = unit(0.84, "npc"), width = unit(0.06, "npc")) 546 | grid.text(capitalize(genre[1,1]), vjust = 0, hjust = 0, x = unit(0.5, "npc"), y = unit(0.84, "npc"), gp = gpar(fontfamily = "Impact", col = primaryColor, cex = 1)) 547 | 548 | grid.raster(marathonImage, x = unit(0.45, "npc"), y = unit(0.815, "npc"), width = unit(0.06, "npc")) 549 | grid.text(paste( 550 | seconds_to_period(60*runtime.ByDay[order(runtime.ByDay$Runtime,decreasing = TRUE),2][1]), 551 | "\n", 552 | runtime.ByDay[order(runtime.ByDay$Runtime,decreasing = TRUE),1][1]), just = "center", x = unit(0.535, "npc"), y = unit(0.815, "npc"), gp = gpar(fontfamily = "Impact", col = primaryColor, cex = 1)) 553 | 554 | 555 | ## Movies 556 | grid.text("MOVIES", vjust = 0, hjust = 0, x = unit(0.91,"npc"), y = ySummaryTitle, gp = gpar(fontfamily = "Impact", col = headingColor, cex = 1.5)) 557 | 558 | grid.raster(hashtagImage, x = unit(1, "npc") - unit(0.035, "npc"), y = unit(0.866, "npc"), width = unit(0.06, "npc")) 559 | grid.text(paste(length(unique(movieHistory$Title))," Movies"), 560 | vjust = 1, hjust = 1, x = unit(0.91, "npc"), y = unit(0.87, "npc"), gp = gpar(fontfamily = "Impact", col = primaryColor, cex = 1.1)) 561 | 562 | grid.raster(starImage, x = unit(1, "npc") - unit(0.035, "npc"), y = unit(0.822, "npc"), width = unit(0.06, "npc")) 563 | 564 | longestMovie <- max(movieHistory$Runtime) 565 | longestMovie <- movieHistory[movieHistory$Runtime == longestMovie,] 566 | grid.text( paste(longestMovie$Title," (",longestMovie$Runtime," min)","\n", 567 | "Total ",seconds_to_period(sum(movieHistory$Runtime)*60)), 568 | vjust = 1, hjust = 1, x = unit(0.91, "npc"), y = unit(0.828, "npc"), gp = gpar(fontfamily = "Impact", col = primaryColor, cex = 1.1)) 569 | 570 | ### Heatmap 571 | print(heatmap,vp = vplayout(2,1:3)) 572 | 573 | 574 | ####### After heatmap section 575 | 576 | grid.raster(cashImage, x = unit(0.75, "npc"), y = unit(0.635,"npc"), width = unit(0.06, "npc")) 577 | 578 | gridTextMulticolor(unit(0.8,"npc"), 579 | unit(0.635,"npc"), 580 | c(costPerHour," ",currency,"/hour"), 581 | c(secondaryColor,secondaryColor,primaryColor,primaryColor), 582 | fontSize = 1.2) 583 | 584 | grid.raster(ticketImage, x = unit(0.75, "npc"), y = unit(0.6,"npc"), width = unit(0.06, "npc")) 585 | 586 | gridTextMulticolor(unit(0.8,"npc"), 587 | unit(0.6,"npc"), 588 | c(cinemaVisits," x cinema visits"), 589 | c(secondaryColor,primaryColor), 590 | fontSize = 1.2) 591 | 592 | #Oldest movie 593 | grid.raster(grandpaImage, x = unit(0.28, "npc"), y = unit(0.635,"npc"), width = unit(0.06, "npc"), 594 | gp = gpar(fill="black")) 595 | 596 | oldest <- movieHistory[order(movieHistory$Released, decreasing = FALSE)[1],] 597 | 598 | text <- c("Old: ", as.character(oldest$Title),"\n",as.character(oldest$Released)) 599 | 600 | #grid.text(paste("Old: ",,), vjust = 0.5, hjust = 1, x = unit(0.23,"npc"), y = unit(0.63,"npc"), gp = gpar(fontfamily = "Impact", col = primaryColor, cex = 1.3)) 601 | gridTextMulticolor(unit(0.23,"npc"), 602 | unit(0.64,"npc"), 603 | text, 604 | c(secondaryColor,primaryColor,primaryColor), 605 | fontSize = 1.2,rightAlign = TRUE) 606 | 607 | rm(oldest) 608 | 609 | grid.raster(numberOne, x = unit(0.28, "npc"), y = unit(0.6,"npc"), width = unit(0.06, "npc"), 610 | gp = gpar(fill="black")) 611 | 612 | #Determine the first ever watched item 613 | 614 | eMovie <- min(movieHistory$Date) 615 | eShow <- min(showHistory$Date) 616 | eUnknown <- min(unknownHistory$Date) 617 | 618 | if(eMovie <= eShow && eMovie <= eUnknown){ 619 | earliest <- movieHistory[movieHistory$Date == eMovie,][1,]$Title 620 | }else if(eShow <= eMovie && eShow <= eUnknown){ 621 | temp <- showHistory[showHistory$Date == eShow,][1,] 622 | earliest <- paste(temp$Series,"\n",temp$Title) 623 | rm(temp) 624 | }else{ 625 | earliest <- unknownHistory[unknownHistory$Date == eUnknown,][1,]$Title 626 | } 627 | 628 | #Here we have multiple values. Just pick the first one 629 | gridTextMulticolor(unit(0.23,"npc"), 630 | unit(0.605,"npc"), 631 | c("First: ",earliest), 632 | c(secondaryColor,primaryColor,primaryColor), 633 | fontSize = 1.2, rightAlign = TRUE) 634 | 635 | 636 | 637 | rm(eMovie,eShow,eUnknown,earliest) 638 | 639 | ## START PLOTS 640 | 641 | grid.rect(gp = gpar(fill = secondaryColor, col = secondaryColor),x = unit(0.19,"npc"), y = unit(0.57,"npc"),width = unit(0.31,"npc"), height = unit(0.01,"npc")) 642 | grid.rect(gp = gpar(fill = secondaryColor, col = secondaryColor),x = unit(0.515,"npc"), y = unit(0.57,"npc"),width = unit(0.31,"npc"), height = unit(0.01,"npc")) 643 | grid.rect(gp = gpar(fill = secondaryColor, col = secondaryColor),x = unit(0.84,"npc"), y = unit(0.57,"npc"),width = unit(0.31,"npc"), height = unit(0.01,"npc")) 644 | 645 | grid.text("Movie Rating", vjust = 0.5, hjust = 0.5, x = unit(0.19,"npc"), y = unit(0.57,"npc"), gp = gpar(fontfamily = "Impact", col = headingColor, cex = 1)) 646 | grid.text("Time Spent Day Of Week", vjust = 0.5, hjust = 0.5, x = unit(0.515,"npc"), y = unit(0.57,"npc"), gp = gpar(fontfamily = "Impact", col = headingColor, cex = 1)) 647 | grid.text("Time Spent Month Of Year", vjust = 0.5, hjust = 0.5, x = unit(0.84,"npc"), y = unit(0.57,"npc"), gp = gpar(fontfamily = "Impact", col = headingColor, cex = 1)) 648 | 649 | 650 | print(graphCountByCertificate, vp = vplayout(3, 1)) 651 | print(graphRuntimeByDay, vp = vplayout(3, 2)) 652 | print(graphRuntimeByMonth, vp = vplayout(3, 3)) 653 | 654 | print(genreGraph, vp = vplayout(4, 1)) 655 | print(mostEpisodeGraph, vp = vplayout(4, 2)) 656 | print(networkGraph, vp = vplayout(4, 3)) 657 | 658 | grid.rect(gp = gpar(fill = secondaryColor, col = secondaryColor),x = unit(0.19,"npc"), y = unit(0.4015,"npc"),width = unit(0.31,"npc"), height = unit(0.01,"npc")) 659 | grid.rect(gp = gpar(fill = secondaryColor, col = secondaryColor),x = unit(0.515,"npc"), y = unit(0.4015,"npc"),width = unit(0.31,"npc"), height = unit(0.01,"npc")) 660 | grid.rect(gp = gpar(fill = secondaryColor, col = secondaryColor),x = unit(0.84,"npc"), y = unit(0.4015,"npc"),width = unit(0.31,"npc"), height = unit(0.01,"npc")) 661 | 662 | grid.text("Genres", vjust = 0.5, hjust = 0.5, x = unit(0.19,"npc"), y = unit(0.4015,"npc"), gp = gpar(fontfamily = "Impact", col = headingColor, cex = 1)) 663 | grid.text("Most Watched Series", vjust = 0.5, hjust = 0.5, x = unit(0.515,"npc"), y = unit(0.4015,"npc"), gp = gpar(fontfamily = "Impact", col = headingColor, cex = 1)) 664 | grid.text("Network", vjust = 0.5, hjust = 0.5, x = unit(0.84,"npc"), y = unit(0.4015,"npc"), gp = gpar(fontfamily = "Impact", col = headingColor, cex = 1)) 665 | 666 | 667 | print(seriesTimeline,vp = vplayout(5,1:3)) 668 | 669 | 670 | footerText <- paste("Generate your own graphics: http://www.github.com/kilianB/ - Image licenses available @github","\n","Restrictions due to data provided by Netflix:","Runtime overestimation: every episode/movie started will be counted as fully seen","\n", 671 | "Runtime underestimation: Duplicate episodes/movies are not counted twice. The oldest entry will be purged from the data", " Viewing activity only contains the last 12 months of data.") 672 | 673 | grid.rect(x = unit(0.5,"npc"),y=unit(0,"npc"),width = unit(1,"npc"),height = unit(0.05,"npc"),gp = gpar(fill = secondaryColor, col = secondaryColor)) 674 | grid.text(footerText, x = unit(0.01,"npc"), y = unit(0.015,"npc"),gp = gpar(col = footerColor, cex = 0.7), just = "left") 675 | 676 | dev.off() 677 | 678 | 679 | -------------------------------------------------------------------------------- /src/main/R/images/calendar.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KilianB/NetflixViewingActivityVisualizer/dab2c81b2a43f8d049380fb66820d5d7e4ce3964/src/main/R/images/calendar.png -------------------------------------------------------------------------------- /src/main/R/images/cash.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KilianB/NetflixViewingActivityVisualizer/dab2c81b2a43f8d049380fb66820d5d7e4ce3964/src/main/R/images/cash.png -------------------------------------------------------------------------------- /src/main/R/images/clock.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KilianB/NetflixViewingActivityVisualizer/dab2c81b2a43f8d049380fb66820d5d7e4ce3964/src/main/R/images/clock.png -------------------------------------------------------------------------------- /src/main/R/images/grandpa.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KilianB/NetflixViewingActivityVisualizer/dab2c81b2a43f8d049380fb66820d5d7e4ce3964/src/main/R/images/grandpa.png -------------------------------------------------------------------------------- /src/main/R/images/hashtag.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KilianB/NetflixViewingActivityVisualizer/dab2c81b2a43f8d049380fb66820d5d7e4ce3964/src/main/R/images/hashtag.png -------------------------------------------------------------------------------- /src/main/R/images/like.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KilianB/NetflixViewingActivityVisualizer/dab2c81b2a43f8d049380fb66820d5d7e4ce3964/src/main/R/images/like.png -------------------------------------------------------------------------------- /src/main/R/images/numberOne.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KilianB/NetflixViewingActivityVisualizer/dab2c81b2a43f8d049380fb66820d5d7e4ce3964/src/main/R/images/numberOne.png -------------------------------------------------------------------------------- /src/main/R/images/running.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KilianB/NetflixViewingActivityVisualizer/dab2c81b2a43f8d049380fb66820d5d7e4ce3964/src/main/R/images/running.png -------------------------------------------------------------------------------- /src/main/R/images/star.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KilianB/NetflixViewingActivityVisualizer/dab2c81b2a43f8d049380fb66820d5d7e4ce3964/src/main/R/images/star.png -------------------------------------------------------------------------------- /src/main/R/images/ticket.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KilianB/NetflixViewingActivityVisualizer/dab2c81b2a43f8d049380fb66820d5d7e4ce3964/src/main/R/images/ticket.png -------------------------------------------------------------------------------- /src/main/R/images/time.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KilianB/NetflixViewingActivityVisualizer/dab2c81b2a43f8d049380fb66820d5d7e4ce3964/src/main/R/images/time.png -------------------------------------------------------------------------------- /src/main/java/com/github/kilianB/fileHandling/in/NetflixParser.java: -------------------------------------------------------------------------------- 1 | package com.github.kilianB.fileHandling.in; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.BufferedWriter; 5 | import java.io.File; 6 | import java.io.FileReader; 7 | import java.io.FileWriter; 8 | import java.io.IOException; 9 | import java.util.ArrayList; 10 | import java.util.Objects; 11 | import java.util.logging.Logger; 12 | import java.util.regex.Matcher; 13 | import java.util.regex.Pattern; 14 | 15 | import com.github.kilianB.model.netflix.NetflixMovie; 16 | import com.github.kilianB.model.netflix.NetflixShowEpisode; 17 | import com.github.kilianB.model.netflix.ViewItem; 18 | 19 | /** 20 | * Attempt to extract the names of series and episode information of netflix titles. 21 | * Sadly the syntax isn't consistent. e.g. double quotes ... The current pattern might 22 | * fail if colons are present in the episode title. 23 | * 24 | * Sample of shows 25 | * "Star Trek: Discovery: Season 1: The Vulcan Hello" 26 | * "Breaking Bad: Season 1: Pilot" 27 | * "PussyTerror TV: Staffel 2: PussyTerror TV vom 16.04.2016" 28 | * "Haus des Geldes: Part 1: Episode 1" 29 | * 30 | * @author Kilian 31 | * 32 | */ 33 | public class NetflixParser { 34 | 35 | /** 36 | * Use the default logger for now 37 | */ 38 | private static final Logger LOGGER = Logger.getLogger(NetflixParser.class.getName()); 39 | 40 | /** 41 | * Input delimiter used in the CSV file 42 | */ 43 | private static final String INPUT_DELIMITER = ","; 44 | 45 | /** 46 | * We can't simply split line after line of the csv by delimiter since movie titles may also include commas. 47 | * Sample : 48 | * "Narcos: Season 3: MRO","05/08/2018" And 49 | * "13 Reasons Why: Season 1: Tape 7, Side A","18/05/2018" 50 | */ 51 | private final static Pattern splitLine = Pattern.compile("\"(?<Title>.*)\""+INPUT_DELIMITER+"\"(?<Date>.*)\""); 52 | 53 | /** 54 | * If we have a show try to separate the series, season and episode title 55 | */ 56 | private final static Pattern showPattern = Pattern.compile( 57 | "(?<series>.*(?:(?:Season|Staffel|Part) [0-9]+)(?=:)): (?<epTitle>.*)", 58 | java.util.regex.Pattern.UNICODE_CHARACTER_CLASS); 59 | 60 | /** 61 | * Once we get the season extract the season number 62 | * TODO greater 10 + instead of *? But what if season does not include a number? 63 | */ 64 | private final static Pattern seasonPattern = Pattern.compile( 65 | "(?<series>.*(?=:)): (?<seasonText>[^0-9]*)(?<season>[0-9]*)", 66 | java.util.regex.Pattern.UNICODE_CHARACTER_CLASS); 67 | 68 | 69 | /** 70 | * Hide default constructor 71 | * 72 | * @param filePath 73 | */ 74 | @SuppressWarnings("unused") 75 | private NetflixParser(String filePath) {} 76 | 77 | public static ArrayList<ViewItem> parseHistoryFile(String filePath) throws IOException { 78 | 79 | Objects.requireNonNull(filePath); 80 | 81 | File viewFile = new File(filePath); 82 | 83 | if (!viewFile.exists()) { 84 | throw new IllegalArgumentException("Abort: Can not read Netflix view history file."); 85 | } 86 | 87 | var viewHistory = new ArrayList<ViewItem>(); 88 | 89 | try (BufferedReader br = new BufferedReader(new FileReader(viewFile))) { 90 | 91 | // Skip csv header 92 | String line = br.readLine(); 93 | 94 | // Maybe read everything into memory to work with stream api? 95 | while ((line = br.readLine()) != null) { 96 | //Tokenize 97 | Matcher m = splitLine.matcher(line); 98 | if(m.find()) { 99 | 100 | var parsedEntry = parseEntry(m.group("Title"),m.group("Date")); 101 | viewHistory.add(parsedEntry); 102 | }else { 103 | LOGGER.warning("Line in the csv file can not be tokenized. Skipping line: " + line); 104 | } 105 | } 106 | return viewHistory; 107 | } 108 | } 109 | 110 | /** 111 | * Keep it package private so we can unit test it 112 | * 113 | * @return 114 | */ 115 | static ViewItem parseEntry(String title,String date) { 116 | 117 | Matcher m = showPattern.matcher(title); 118 | 119 | /* 120 | * Input: "Star Trek: Discovery: Season 1: The Vulcan Hello" 121 | * Capturing group 122 | * series: Star Trek: Discovery: Season 1 123 | * epTitle: The Vulcan Hello 124 | */ 125 | 126 | boolean matchFound = m.find(); 127 | if (matchFound) { 128 | 129 | String seriesRaw = m.group("series"); 130 | String episodeTitle = m.group("epTitle"); 131 | 132 | Matcher titleMatcher = seasonPattern.matcher(seriesRaw); 133 | /* 134 | * Input: Star Trek: Discovery: Season 1" 135 | * Capturing group 136 | * series: Star Trek: Discovery 137 | * seasonText: Season 138 | * season: 1 139 | */ 140 | 141 | if (titleMatcher.find()) { 142 | 143 | String series = titleMatcher.group("series"); 144 | 145 | /*Numerical number of the season. 146 | * If season is not populated this will contain the series name. e.g. if series 147 | * are not numbered. 148 | * TODO since show patterns quantifier was changed to + instead of * regarding the season number 149 | * seasonText should never be the only thing populated and therefore gets discarded */ 150 | //String season = titleMatcher.group("season") != null ? titleMatcher.group("season") : titleMatcher.group("seasonText"); 151 | 152 | int season = Integer.parseInt(titleMatcher.group("season")); 153 | 154 | //System.out.println("Show:" + tokens[0] + " Token " + tokens[1]); 155 | 156 | return new NetflixShowEpisode(episodeTitle, date, season, series); 157 | } else { 158 | 159 | // Most likely a movie with a colon in the title 160 | return new NetflixMovie(title, date); 161 | } 162 | } else { 163 | // Most likely a movie 164 | return new NetflixMovie(title, date); 165 | } 166 | } 167 | 168 | public NetflixParser(String fileName, String delimiter) throws IOException { 169 | 170 | File csvFile = new File(fileName); 171 | 172 | try(BufferedWriter bw = new BufferedWriter(new FileWriter(csvFile))){ 173 | 174 | } 175 | 176 | } 177 | 178 | 179 | 180 | } 181 | -------------------------------------------------------------------------------- /src/main/java/com/github/kilianB/fileHandling/in/NetflixViewingActivityDownloader.java: -------------------------------------------------------------------------------- 1 | package com.github.kilianB.fileHandling.in; 2 | 3 | 4 | //import org.openqa.selenium.By; 5 | //import org.openqa.selenium.NoSuchElementException; 6 | //import org.openqa.selenium.TimeoutException; 7 | //import org.openqa.selenium.WebDriver; 8 | //import org.openqa.selenium.WebElement; 9 | //import org.openqa.selenium.chrome.ChromeDriver; 10 | //import org.openqa.selenium.support.ui.ExpectedConditions; 11 | //import org.openqa.selenium.support.ui.WebDriverWait; 12 | 13 | /** 14 | * 15 | * Download the Netflix viewing history file from the server. This requires a Netflix session. We 16 | * could achieve this nicely by asking the user for their credentials or session hijacking by extracting 17 | * their cookies. 18 | * 19 | * As it's bothersome to configure selenimum drivers for such a small gain don't bother. 20 | * Maybe later as nice assignment. 21 | * 22 | * 23 | * @author Kilian 24 | * Instead we could directly send the correct packages to netflix instead of relying on htmlunit? 25 | * Maybe try out selenium? 26 | * How about jaunt ? http://jaunt-api.com/ 27 | */ 28 | @Deprecated 29 | @SuppressWarnings("unused") 30 | public class NetflixViewingActivityDownloader { 31 | 32 | private static final String INITIAL_URL = "https://www.netflix.com/browse"; 33 | private static final String VIEWING_ACTIVITY_URL = "https://www.netflix.com/viewingactivity"; 34 | 35 | public static void main(String[] args) { 36 | downloadNetflixViewingActivity("Kilian.Brachtendorf@t-online.de","DuVogel","Kili"); 37 | } 38 | 39 | /** 40 | * Hide default constructor 41 | */ 42 | private NetflixViewingActivityDownloader() {} 43 | 44 | /** 45 | * 46 | * @param loginUsername 47 | * @param loginPassword 48 | * @param netflixUsername 49 | * @return true if the file was sucessfully downloaded. False otherwise 50 | */ 51 | @Deprecated 52 | public static boolean downloadNetflixViewingActivity(String loginUsername, String loginPassword, 53 | String netflixUsername) { 54 | return false; 55 | } 56 | 57 | private boolean downloadUsingSelenium() { 58 | return false; 59 | // //Selenium 60 | // System.setProperty("webdriver.chrome.driver", ""); 61 | // 62 | // WebDriver driver = new ChromeDriver(); 63 | // driver.get(INITIAL_URL); 64 | // 65 | // 66 | // try { 67 | // WebElement form = driver.findElement(By.className("login-form")); 68 | // WebElement usernameField = driver.findElement(By.name("userLoginId")); 69 | // WebElement passwordField = driver.findElement(By.name("password")); 70 | // 71 | // //execute 72 | // usernameField.sendKeys(loginUsername); 73 | // passwordField.sendKeys(loginPassword); 74 | // form.submit(); 75 | // 76 | // //do everything else 77 | // WebDriverWait waitUntilResponse = new WebDriverWait(driver,10); 78 | // 79 | // try { 80 | // WebElement response = waitUntilResponse.until(ExpectedConditions.presenceOfElementLocated(By.className("profile-gate-label"))); 81 | // 82 | // System.out.println("Login to netflix sucessful"); 83 | // 84 | // }catch(TimeoutException timeout) { 85 | // System.out.println("Login wasn't sucessfull"); 86 | // timeout.printStackTrace(); 87 | // return false; 88 | // } 89 | // 90 | // return true; 91 | // }catch (NoSuchElementException exception) { 92 | // exception.printStackTrace(); 93 | // return false; 94 | // } 95 | // 96 | 97 | //Wait until next page has loaded. 98 | 99 | } 100 | 101 | @Deprecated 102 | private boolean downloadUsingHTMLUnit() { 103 | return false; 104 | // try (final WebClient webClient = new WebClient()) { 105 | // 106 | // //Mute and ignore javascript errors 107 | // java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF); 108 | // webClient.getOptions().setJavaScriptEnabled(true); 109 | // webClient.getOptions().setThrowExceptionOnScriptError(false); 110 | // 111 | // 112 | // // Get the first page 113 | // final HtmlPage netflixLandingPage = webClient.getPage(INITIAL_URL); 114 | // 115 | // 116 | // File html = new File("Hrmlpage"+Math.random()+".html"); 117 | // netflixLandingPage.save(html); 118 | // 119 | // // Get the form that we are dealing with and within that form, 120 | // // find the submit button and the field that we want to change. 121 | // var forms = netflixLandingPage.getForms(); 122 | // 123 | // Optional<HtmlForm> oForm = forms.stream().filter(form -> form.getAttribute("class").equals("login-form")) 124 | // .findFirst(); 125 | // 126 | // //Alternative .. netflixLandingPage.getDocumentElement().getElementsByAttribute("form", "class", "login-form").get(0) 127 | // if (oForm.isPresent()) { 128 | // 129 | // final HtmlForm signinForm = oForm.get(); 130 | // 131 | // 132 | // System.out.println("Form: " ); 133 | // System.out.println(signinForm.asXml()); 134 | // 135 | // //Sometimes works sometimes it doesn't? 136 | // final HtmlButton button = (HtmlButton) signinForm.getElementsByAttribute("button", "type", "submit").get(0); 137 | // final HtmlTextInput username = signinForm.getInputByName("userLoginId"); 138 | // //OR !final HtmlTextInput username = signinForm.getInputByName("email"); 139 | // final HtmlPasswordInput passwordField = signinForm.getInputByName("password"); 140 | // 141 | // //Fill out the form 142 | // username.type(loginUsername); 143 | // passwordField.type(loginPassword); 144 | // 145 | // HtmlPage referencePage = button.click(); 146 | // 147 | // 148 | // 149 | // //Do we need to wait for javascript to finish loading? 150 | // 151 | // System.out.println(referencePage.asXml()); 152 | // 153 | //// 154 | //// // Change the value of the text field 155 | //// textField.type("root"); 156 | //// 157 | //// // Now submit the form by clicking the button and get back the second page. 158 | //// final HtmlPage page2 = button.click(); 159 | //// 160 | //// 161 | // 162 | // } else { 163 | // System.err.println( 164 | // "Fatal: Could not find netflix signin form. Maybe the site layout changed. Please download the viewing activity file manually. Abort"); 165 | // return false; 166 | // } 167 | // 168 | // 169 | // } catch (FailingHttpStatusCodeException | IOException e) { 170 | // e.printStackTrace(); 171 | // return false; 172 | // } 173 | } 174 | 175 | } 176 | -------------------------------------------------------------------------------- /src/main/java/com/github/kilianB/fileHandling/out/CSVMovieWriter.java: -------------------------------------------------------------------------------- 1 | package com.github.kilianB.fileHandling.out; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.util.Arrays; 6 | 7 | import com.github.kilianB.model.netflix.NetflixMovie; 8 | import com.uwetrottmann.trakt5.entities.Movie; 9 | 10 | /** 11 | * Rudimentary synchronized CSV writer accepting movie objects to be written to a CSV file 12 | * 13 | * @author Kilian 14 | */ 15 | public class CSVMovieWriter extends CSVWriter{ 16 | 17 | public CSVMovieWriter(File csvOutPath, String delimiter) throws IOException { 18 | super(csvOutPath, delimiter,"Date","Title","Runtime","Certificate","Released","Genres"); 19 | } 20 | 21 | /** 22 | * Append the data to the end of the csv file in a synchronized manner. 23 | * @param movie Movie object retrieved from Trakt 24 | * @param netflixObj matching movie item parsed from the viewinghistory file 25 | * @throws IOException if an IOError occurs 26 | */ 27 | public void push(Movie movie, NetflixMovie netflixObj) throws IOException { 28 | 29 | String genres = ""; 30 | if(movie.genres != null) { 31 | genres = Arrays.toString(movie.genres.toArray(new String[movie.genres.size()])); 32 | } 33 | 34 | writeLine(netflixObj.getViewDate(), 35 | movie.title, 36 | movie.runtime, 37 | movie.certification, 38 | movie.released, 39 | genres 40 | ); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/github/kilianB/fileHandling/out/CSVShowWriter.java: -------------------------------------------------------------------------------- 1 | package com.github.kilianB.fileHandling.out; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import org.threeten.bp.format.DateTimeFormatter; 6 | import java.util.Arrays; 7 | 8 | import com.github.kilianB.model.netflix.NetflixShowEpisode; 9 | import com.uwetrottmann.trakt5.entities.Show; 10 | 11 | /** 12 | * Rudimentary synchronized CSV writer accepting Show objects to be written to a CSV file 13 | * 14 | * @author Kilian 15 | */ 16 | public class CSVShowWriter extends CSVWriter{ 17 | 18 | public CSVShowWriter(File csvOutPath, String delimiter) throws IOException { 19 | super(csvOutPath, delimiter,"Date","Series","Title","Season","Runtime","Certificate","FirstAired","Network","Genres"); 20 | } 21 | 22 | /** 23 | * Output date format of the first aired date 24 | */ 25 | private static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd.MM.yyyy"); 26 | 27 | /** 28 | * Append the data to the end of the csv file in a synchronized manner. 29 | * @param show A show object received by trakt 30 | * @param netflixShow A matching object parsed from the viewfile.csv 31 | * @param runtime The runtime of the episode 32 | * @throws IOException if an IO Error occurs 33 | */ 34 | public void push(Show show, NetflixShowEpisode netflixShow, int runtime) throws IOException { 35 | 36 | String genres = ""; 37 | if(show.genres != null) { 38 | genres = Arrays.toString(show.genres.toArray(new String[show.genres.size()])); 39 | } 40 | 41 | try { 42 | dtf.format(show.first_aired); 43 | }catch(IllegalArgumentException e) { 44 | System.out.println("First aired: " + show.first_aired); 45 | } 46 | 47 | writeLine(netflixShow.getViewDate(), 48 | netflixShow.getSeries(), 49 | netflixShow.getTitle(), 50 | netflixShow.getSeason(), 51 | runtime, 52 | show.certification, 53 | show.first_aired.format(dtf), 54 | show.network, 55 | genres); 56 | } 57 | 58 | 59 | 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/github/kilianB/fileHandling/out/CSVWriter.java: -------------------------------------------------------------------------------- 1 | package com.github.kilianB.fileHandling.out; 2 | 3 | import java.io.BufferedWriter; 4 | import java.io.File; 5 | import java.io.FileWriter; 6 | import java.io.IOException; 7 | import java.util.Arrays; 8 | import java.util.Iterator; 9 | import java.util.concurrent.locks.ReentrantLock; 10 | import java.util.logging.Logger; 11 | 12 | /** 13 | * Rudimentary synchronized csv writer 14 | * @author Kilian 15 | * 16 | */ 17 | public class CSVWriter implements AutoCloseable { 18 | 19 | private static final Logger LOGGER = Logger.getLogger(CSVWriter.class.getName()); 20 | 21 | /** 22 | * Writer used to write to the file 23 | */ 24 | protected final BufferedWriter bw; 25 | 26 | /** 27 | * Delimiter used to seperate values 28 | */ 29 | protected String delimiter = ";"; 30 | 31 | /** 32 | * Lock to keep write access synchronized 33 | */ 34 | protected ReentrantLock writeLock = new ReentrantLock(); 35 | 36 | /** 37 | * Count of headers. R requires consistent header and data length 38 | */ 39 | private int headerLength = 0; 40 | 41 | public CSVWriter(File csvOutPath, String delimiter,String... headers) throws IOException { 42 | this.bw = new BufferedWriter(new FileWriter(csvOutPath)); 43 | this.delimiter = delimiter; 44 | writeHeader(headers); 45 | } 46 | 47 | /** 48 | * Write a header row at the beginning of a field 49 | * @param headers The header title fields 50 | * @throws IOException if an IO error occurs 51 | */ 52 | private void writeHeader(String... headers) throws IOException { 53 | 54 | headerLength = headers.length; 55 | 56 | StringBuilder haederBuilder = new StringBuilder(); 57 | 58 | Iterator<String> iter = Arrays.asList(headers).iterator(); 59 | 60 | while (iter.hasNext()) { 61 | haederBuilder.append(iter.next()); 62 | if (iter.hasNext()) 63 | haederBuilder.append(delimiter); 64 | } 65 | haederBuilder.append(System.lineSeparator()); 66 | 67 | lockedWrite(haederBuilder.toString()); 68 | 69 | } 70 | 71 | /** 72 | * Append the supplied content to the file. 73 | * This method synchronized write actions. 74 | * @param content 75 | * @throws IOException 76 | */ 77 | protected void lockedWrite(String content) throws IOException{ 78 | writeLock.lock(); 79 | try { 80 | bw.write(content); 81 | }catch(IOException io) { 82 | //Retrow 83 | throw io; 84 | }finally { 85 | writeLock.unlock(); 86 | } 87 | } 88 | 89 | 90 | /** 91 | * Append the objects to the end of the file. Each object 92 | * will be treated as a new value seperated by a delimiter. 93 | * 94 | * This action is synchronized 95 | * @param entries entries to be appended to the file 96 | * @throws IOException 97 | */ 98 | public void writeLine(Object...entries) throws IOException { 99 | 100 | if(entries.length > headerLength) { 101 | LOGGER.warning("More entries added than header fields written"); 102 | } 103 | 104 | StringBuilder sb = new StringBuilder(); 105 | 106 | for(int i = 0; i < entries.length; i++) { 107 | sb.append(entries[i]); 108 | if(i < entries.length -1) { 109 | sb.append(delimiter); 110 | } 111 | } 112 | 113 | sb.append(System.lineSeparator()); 114 | lockedWrite(sb.toString()); 115 | } 116 | 117 | 118 | @Override 119 | public void close(){ 120 | try { 121 | bw.close(); 122 | }catch(IOException io) { 123 | io.printStackTrace(); 124 | } 125 | } 126 | } 127 | 128 | 129 | 130 | -------------------------------------------------------------------------------- /src/main/java/com/github/kilianB/launcher/NetflixAnalyzer.java: -------------------------------------------------------------------------------- 1 | package com.github.kilianB.launcher; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.lang.Thread.UncaughtExceptionHandler; 6 | import java.util.ArrayList; 7 | import java.util.HashMap; 8 | import java.util.HashSet; 9 | import java.util.List; 10 | import java.util.Map; 11 | import java.util.Optional; 12 | import java.util.PriorityQueue; 13 | import java.util.Set; 14 | import java.util.concurrent.ExecutorService; 15 | import java.util.concurrent.Executors; 16 | import java.util.concurrent.Future; 17 | import java.util.concurrent.TimeUnit; 18 | import java.util.concurrent.atomic.AtomicInteger; 19 | import java.util.function.Function; 20 | import java.util.function.Predicate; 21 | import java.util.logging.Logger; 22 | import java.util.stream.Collectors; 23 | 24 | import org.apache.commons.text.similarity.EditDistance; 25 | import org.apache.commons.text.similarity.LevenshteinDistance; 26 | 27 | import com.github.kilianB.fileHandling.in.NetflixParser; 28 | import com.github.kilianB.fileHandling.out.CSVMovieWriter; 29 | import com.github.kilianB.fileHandling.out.CSVShowWriter; 30 | import com.github.kilianB.fileHandling.out.CSVWriter; 31 | import com.github.kilianB.model.BaseEntityWrapper; 32 | import com.github.kilianB.model.netflix.NetflixMovie; 33 | import com.github.kilianB.model.netflix.NetflixShowEpisode; 34 | import com.github.kilianB.model.netflix.ViewItem; 35 | import com.uwetrottmann.trakt5.entities.Episode; 36 | import com.uwetrottmann.trakt5.entities.Movie; 37 | import com.uwetrottmann.trakt5.entities.Season; 38 | import com.uwetrottmann.trakt5.entities.Show; 39 | import com.uwetrottmann.trakt5.enums.Type; 40 | 41 | import trakt.TraktHelper; 42 | 43 | /** 44 | * Download and append detailed information to a Netflix viewing history file e.g. runtime 45 | * and genre for further evaluation. 46 | * <p> 47 | * 48 | * The code is in no way optimized but rather a practice project focuses on utilizing some of Java 8-10 49 | * features. 50 | * 51 | * JAVA 8 Method reference :: Predicates 52 | * JAVA 9 streams + lambda 53 | * JAVA 10: local * type inference 54 | * 55 | * The input csv file will be parsed and individual items will either be classified as an 56 | * episode (show), a movie or of type unknown. For each type a separate csv file with additional 57 | * information will be produced 58 | * 59 | * @usage -> java -jar NetflixAnalyzer InputFilePath.csv TraktApiKey 60 | * -> java -jar NetflixAnalyzer TraktApiKey 61 | * 62 | * @author Kilian 63 | * 64 | */ 65 | public class NetflixAnalyzer { 66 | 67 | private static final Logger LOGGER = Logger.getLogger(NetflixParser.class.getName()); 68 | 69 | // Settings 70 | 71 | /** 72 | * Print additional debug information 73 | */ 74 | private final boolean verbose = false; 75 | 76 | /** 77 | * Output path of csv file containing all items classified as movie 78 | */ 79 | private final String movieCsv = "MovieViewingHistory.csv"; 80 | 81 | /** 82 | * Output path of csv file containing all items classified as episode 83 | */ 84 | private final String showCsv = "ShowViewingHistory.csv"; 85 | 86 | /** 87 | * Output path of csv file containing all items which could not be resolved 88 | */ 89 | private final String unknownCsv = "UnknownViewingHistory.csv"; 90 | 91 | 92 | //Fields 93 | 94 | /** 95 | * Trakt client used to query the movie database 96 | */ 97 | private TraktHelper trakt; 98 | 99 | /** 100 | * Key : -> Series name as found in the netflix viewing history file 101 | * Value: -> Show object returned by trakt (Overview: Genre, rating, ids) 102 | */ 103 | private Map<String, Show> traktShows; 104 | 105 | /** 106 | * Key : -> Movie name as found in the netflix viewing history file 107 | * Value: -> Movie object returned by trakt 108 | */ 109 | private Map<NetflixMovie, Movie> traktMovies; 110 | 111 | /** 112 | * 1. Parse the Netflix viewing csv file -> (Title,Date) 113 | * 2. Query trakt API to attach id's to the movie/series title. 114 | * a) Movies are done. more work for episodes are required 115 | * 3. Download summary of the series to get the episode id's 116 | * 4. Use the episode ids and download granular information for each item 117 | * 5. Match trakt and netflix titles using levenshtein distance 118 | * 6. Output results to csv 119 | * 120 | * @param viewFilePath 121 | * @param traktToken 122 | */ 123 | public NetflixAnalyzer(String viewFilePath, String traktToken) { 124 | 125 | /* 126 | * Initialize trakt api movie database 127 | */ 128 | trakt = new TraktHelper(traktToken); 129 | 130 | //@formatter:off 131 | try { 132 | 133 | //1. Import viewing history and attempt to classify movies and shows 134 | List<ViewItem> parsedHistory = NetflixParser.parseHistoryFile(viewFilePath); 135 | 136 | //Retrieve a single NetflixShow for every show watched 137 | HashSet<NetflixShowEpisode> distinctSeries = parsedHistory.stream() 138 | .filter(item -> item.isShow()) 139 | .filter(distinctObjects(item -> ((NetflixShowEpisode) item).getSeries())) 140 | .map(show -> (NetflixShowEpisode) show) 141 | .collect(Collectors.toCollection(HashSet::new)); 142 | 143 | //Retrieve unique movies e.g. if we have watched a movie twice we only should hit the api once 144 | var distinctMovies = parsedHistory.stream() 145 | .filter(i -> !i.isShow()) 146 | .filter(distinctObjects(item -> ((NetflixMovie) item).getTitle())) 147 | .map(show -> (NetflixMovie) show) 148 | .collect(Collectors.toCollection(HashSet::new)); 149 | //@formatter:on 150 | 151 | // Debug print 152 | System.out.println("Series: " + distinctSeries.size() + " " + distinctSeries.stream() 153 | .map(series -> series.getSeries()).collect(Collectors.joining(" , ", "Series [", "] parsed"))); 154 | System.out.println("Movies: " + distinctMovies.size() + " " + distinctMovies.stream() 155 | .map(movie -> movie.getTitle()).collect(Collectors.joining(" , ", "Movies [", "] parsed"))); 156 | 157 | if (verbose) { 158 | for (var item : parsedHistory) { 159 | if (item instanceof NetflixShowEpisode) { 160 | NetflixShowEpisode show = (NetflixShowEpisode) item; 161 | System.out.println(show); 162 | } 163 | } 164 | } 165 | 166 | /* 167 | * We are not allowed to search for episode given a specified series. Only 168 | * searching for the episode title will give false reports therefore download 169 | * episode info for all series we have watched and search within the returned 170 | * results. This approach isn't really easy on the trakt API therefore we are 171 | * nice and save the returned information in an SQL database to only need to 172 | * query the API once. 173 | */ 174 | 175 | //@formatter:off 176 | 177 | //2. Extract trakt id for every series 178 | traktShows = distinctSeries.parallelStream() 179 | .map(trakt::searchShow) 180 | .flatMap(Optional<BaseEntityWrapper<NetflixShowEpisode,Show>>::stream) 181 | .collect(Collectors.toMap( 182 | s -> s.netflixViewItem.getSeries(), //Key by string 183 | s -> s.getEntity())); //Function.identity(); if not wrapped 184 | 185 | // 2. Extract trakt id for every movie 186 | traktMovies = distinctMovies.parallelStream() 187 | .map(trakt::searchMovie) 188 | .flatMap(Optional<BaseEntityWrapper<NetflixMovie,Movie>>::stream) 189 | .collect(Collectors.toMap( 190 | s -> s.netflixViewItem, 191 | s -> s.getEntity())); 192 | //@formatter:on 193 | 194 | if (verbose) { 195 | trakt.printNotFoundItems(); 196 | } 197 | 198 | /** 199 | * Key : -> Movie name as found in the netflix viewing history file Value: -> 200 | * Movie object returned by trakt 201 | */ 202 | HashMap<Show, List<Season>> seasonList = trakt.downloadSeriesInfo(traktShows); 203 | 204 | Map<Type, Set<String>> notFoundOnTrakt = trakt.getNotFoundItems(); 205 | 206 | /* 207 | * Generate 3 output files 1. 2. 3. 208 | */ 209 | CSVShowWriter showWriter = new CSVShowWriter(new File(showCsv), ";"); 210 | CSVMovieWriter movieWriter = new CSVMovieWriter(new File(movieCsv), ";"); 211 | CSVWriter unknowWriter = new CSVWriter(new File(unknownCsv), ";", "Date", "Type", "Title", "Series"); 212 | 213 | var notFoundShows = notFoundOnTrakt.get(Type.SHOW); 214 | var notFoundMovies = notFoundOnTrakt.get(Type.MOVIE); 215 | 216 | trakt.printNotFoundItems(); 217 | /* 218 | * Multithread calls or we will wait forever (Do we need small delays to not get 219 | * blacklisted at trakt? 220 | * 221 | */ 222 | ExecutorService executor = Executors.newFixedThreadPool(15, 223 | (Runnable r)->{ 224 | Thread t = new Thread(r); 225 | t.setName("T-Pool:"); 226 | t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { 227 | @Override 228 | public void uncaughtException(Thread t, Throwable e) { 229 | System.out.println("Uncaught exception: " + t + " " + e.toString()); 230 | } 231 | 232 | }); 233 | return new Thread(r); 234 | } 235 | ); 236 | 237 | System.out.println("Retrieve runtime for shows. This may take a few seconds..."); 238 | 239 | var futures = new ArrayList<Future<?>>(); 240 | 241 | /* 242 | * Variables modified in runnables have to be effective final. Circumvent this issue 243 | * by encapsulating the int in an object. Atomic integers also give us thread safety 244 | * for free. 245 | */ 246 | AtomicInteger knownEpisodeCount = new AtomicInteger(0); 247 | AtomicInteger unknownCount = new AtomicInteger(0); 248 | 249 | /* 250 | * Construct the tasks of writing the individual data to a csv file. 251 | * For shows runtime data still has to be downloaded on a per episode basis 252 | */ 253 | for (var viewItem : parsedHistory) { 254 | //Not the nicest use of anonymous classes but keep it for now... 255 | var future = executor.submit(new Runnable() { 256 | ViewItem viewItem; 257 | 258 | @Override 259 | public void run() { 260 | try { 261 | if (viewItem.isShow()) { 262 | 263 | NetflixShowEpisode netflixShow = (NetflixShowEpisode) viewItem; 264 | 265 | if (notFoundShows.contains(netflixShow.getSeries())) { 266 | LOGGER.fine("Non resolved show: " + netflixShow.getTitle()); 267 | unknowWriter.writeLine(netflixShow.getViewDate(), Type.SHOW, netflixShow.getTitle(), 268 | netflixShow.getSeries()); 269 | unknownCount.incrementAndGet(); 270 | } else { 271 | // Special case. While the show object contains a runtime 272 | // It is not specific for an episode but more or less the average of a show. 273 | // Query the episode list and look again 274 | Show show = traktShows.get(netflixShow.getSeries()); 275 | int runtime = getRuntimeForEpisode(netflixShow, seasonList); 276 | showWriter.push(show, netflixShow, runtime); 277 | knownEpisodeCount.incrementAndGet(); 278 | } 279 | 280 | // Output to csv 281 | } else { 282 | // Movie 283 | NetflixMovie netflixMovie = (NetflixMovie) viewItem; 284 | 285 | if (notFoundMovies.contains(netflixMovie.getTitle())) { 286 | unknowWriter.writeLine(netflixMovie.getViewDate(), Type.MOVIE, 287 | netflixMovie.getTitle()); 288 | unknownCount.incrementAndGet(); 289 | } else { 290 | movieWriter.push(traktMovies.get(netflixMovie), netflixMovie); 291 | } 292 | } 293 | } catch (IOException e) { 294 | LOGGER.severe("Error during output file creation: " + e.getMessage()); 295 | } 296 | } 297 | 298 | //Inject value into anonymous class ... 299 | public Runnable setViewItem(ViewItem viewItem) { 300 | this.viewItem = viewItem; 301 | return this; 302 | } 303 | 304 | }.setViewItem(viewItem)); 305 | 306 | futures.add(future); 307 | } 308 | 309 | //Wait for all threads to return 310 | // for(var future : futures) { 311 | // try { 312 | // future.get(); 313 | // } catch (InterruptedException | ExecutionException e) { 314 | // e.printStackTrace(); 315 | // } 316 | // } 317 | 318 | try { 319 | executor.shutdown(); 320 | executor.awaitTermination(30, TimeUnit.SECONDS); 321 | } catch (InterruptedException e) { 322 | e.printStackTrace(); 323 | } 324 | //Close writer //TODO move in finally? 325 | showWriter.close(); 326 | movieWriter.close(); 327 | unknowWriter.close(); 328 | 329 | //dumpActiveNonDeamonThreads("After Shutdown"); 330 | 331 | //Print some information 332 | 333 | int charLength = (int)Math.log10(parsedHistory.size())+1; 334 | 335 | System.out.printf( 336 | "%nFinished:%n-----------------------------------------%n" 337 | + "%14s %"+charLength+"d%n%14s %"+charLength+"d%n%14s %"+charLength+"d%n" 338 | + "%14s %"+charLength+"d%n%14s %"+charLength+"d%n", 339 | "Items parsed:",parsedHistory.size(),"Unique shows:", traktShows.size(), 340 | "Episodes:", knownEpisodeCount.get(),"Movies:", traktMovies.size(), 341 | "Unknown:",unknownCount.get()); 342 | } catch (IOException e) { 343 | e.printStackTrace(); 344 | } 345 | 346 | //Print some 347 | 348 | 349 | /*The trakt2 api depends on okttp which releases it's ressources after some idle time. 350 | * We don't want to wait so long and trakt doesn't expose the client therefore force 351 | * all threads to shut down at this point 352 | */ 353 | System.exit(0); 354 | 355 | 356 | } 357 | 358 | /** 359 | * A predicate used to retrieve unique values present in a collection based on an arbitrary 360 | * filter value 361 | * 362 | * @param func function executed to retrieve the filter key from the object 363 | * @return a map containing all elements which are present in the collection without duplicates 364 | */ 365 | public Predicate<ViewItem> distinctObjects(Function<? super ViewItem, Object> func) { 366 | var map = new HashSet<Object>(); 367 | return t -> map.add(func.apply((ViewItem) t)); 368 | } 369 | 370 | /** 371 | * Return the runtime for an individual episode 372 | * 373 | * @param show 374 | * @param seasonList 375 | * @return 376 | */ 377 | private int getRuntimeForEpisode(NetflixShowEpisode show, HashMap<Show, List<Season>> seasonList) { 378 | 379 | // TODO returns null! 380 | 381 | String episodeTitle = show.getTitle(); 382 | String seriesName = show.getSeries(); 383 | int seasonNumber = show.getSeason(); 384 | 385 | // Get the Show object as retrieved by trakt 386 | Show traktShow = traktShows.get(seriesName); 387 | 388 | // Retrieve the episode number query the 389 | 390 | List<Season> seasons = seasonList.get(traktShow); 391 | 392 | // System.out.println("Netflix Show: " + show + "\nTrakt: " + traktShow + "\nSeasons: " + seasons 393 | // + "\nSeasonNumber: " + seasonNumber); 394 | 395 | // Get the correct Season 396 | Optional<Season> seasonTemp = seasons.stream().filter(s -> s.number == seasonNumber).findAny(); 397 | 398 | 399 | if (!seasonTemp.isPresent()) { 400 | LOGGER.warning("Could not find season of " + seriesName + "(" + seasonNumber + "). Fallback to " 401 | + "defaul show runtime"); 402 | return traktShow.runtime; 403 | } 404 | 405 | Season correctSeason = seasonTemp.get(); 406 | 407 | // Now choose the correct episodes 408 | List<Episode> episodes = correctSeason.episodes; 409 | 410 | // Choose the episode depending on the title. 411 | EditDistance<Integer> levDistance = new LevenshteinDistance(); 412 | var potentialEpisodes = new PriorityQueue<EpisodeTitleSearchResult>(); 413 | for (var e : episodes) { 414 | // Calculate the similarity between the title we want and the title we get since 415 | // trakt and netflix titles may not be 100% identical 416 | int distance = levDistance.apply(episodeTitle, e.title); 417 | potentialEpisodes.add(new EpisodeTitleSearchResult(e, distance)); 418 | } 419 | 420 | // Get the closest match 421 | 422 | EpisodeTitleSearchResult closestMatch = potentialEpisodes.poll(); 423 | 424 | // Download the summary for the episode 425 | 426 | int editDistance = closestMatch.editDistance; 427 | if (editDistance < 5) { 428 | 429 | // Episodes downloaded via season summary don't contain the runtime. 430 | try { 431 | int runtime = trakt.getEpisodeRuntime(Integer.toString(closestMatch.episode.ids.trakt)); 432 | 433 | if (editDistance > 0) { 434 | // Close enough match 435 | LOGGER.warning("No exact match for episode found. Going with closest match: Query:" + episodeTitle 436 | + " Target: " + closestMatch.episode.title); 437 | } 438 | return runtime; 439 | 440 | } catch (IOException e1) { 441 | LOGGER.severe("Error while downloading runtime. Fallback to average show runtime"); 442 | e1.printStackTrace(); 443 | return traktShow.runtime; 444 | } 445 | } else { 446 | LOGGER.warning("Could not find episode of " + seriesName + "(" + episodeTitle + "). Fallback to " 447 | + "average show runtime"); 448 | return traktShow.runtime; 449 | } 450 | } 451 | 452 | /* 453 | * 454 | * Helper classes 455 | * 456 | */ 457 | 458 | /** 459 | * Title of episodes returned by trakt might not exactly match the titles 460 | * provided by netflix. Therefore allow search through all episode titles of a 461 | * season and pick the closest candidate. 462 | * 463 | * @author Kilian 464 | * 465 | */ 466 | class EpisodeTitleSearchResult implements Comparable<EpisodeTitleSearchResult> { 467 | int editDistance; 468 | Episode episode; 469 | 470 | public EpisodeTitleSearchResult(Episode e, int distance) { 471 | this.episode = e; 472 | this.editDistance = distance; 473 | } 474 | 475 | @Override 476 | public int compareTo(EpisodeTitleSearchResult o) { 477 | return Integer.compare(editDistance, o.editDistance); 478 | } 479 | 480 | } 481 | 482 | public static void main(String[] args) { 483 | 484 | //Set logging format 485 | System.setProperty("Djava.util.logging.SimpleFormatter.format", 486 | "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$-6s %2$s %5$s%6$s%n"); 487 | 488 | // Input validation 489 | if (args.length >= 2 && args[0].endsWith(".csv") && args[1].length() == 64) { 490 | // Trakt token is sha 256 encrypted? -> 64 characters 491 | new NetflixAnalyzer(args[0], args[1]); 492 | } else if(args.length == 1){ 493 | if(args[0].length() == 64) { 494 | System.err.println("No input file path specified. Falback to default " 495 | + "NetflixViewingHistory.csv in current directory"); 496 | new NetflixAnalyzer("NetflixViewingHistory.csv", args[0]); 497 | }else { 498 | System.err.println("The supplied trakt key does not have the correct length to be " 499 | + "a valid key"); 500 | System.err.println("Aborting"); 501 | } 502 | 503 | }else { 504 | System.err.println("Usage:\n" 505 | + "\tjava -jar NetflixAnalyzer PATH_TO_VIEWHISTORYFILE.csv traktClientID\n" 506 | + "\tjava -jar NetflixAnalyzer traktClientID"); 507 | System.err.println("Aborting"); 508 | } 509 | } 510 | 511 | 512 | 513 | /** 514 | * Debug function used to check which threads prevent the jvm from exiting 515 | * In production we would not use strack traces as these are rather expensive 516 | * @param message 517 | */ 518 | @SuppressWarnings("unused") 519 | private void dumpActiveNonDeamonThreads(String message) { 520 | System.out.println(message); 521 | Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); 522 | for(Thread t : threadSet) { 523 | if(!t.isDaemon()) 524 | System.out.println(t); 525 | } 526 | } 527 | 528 | } 529 | -------------------------------------------------------------------------------- /src/main/java/com/github/kilianB/model/BaseEntityWrapper.java: -------------------------------------------------------------------------------- 1 | package com.github.kilianB.model; 2 | 3 | import com.github.kilianB.model.netflix.ViewItem; 4 | import com.uwetrottmann.trakt5.entities.BaseEntity; 5 | 6 | /** 7 | * Bundle a ViewItem directly parsed from the viewing history 8 | * file with a metadataentity downloaded from trakt 9 | * @author Kilian 10 | * 11 | * @param <T> Either NetflixMovie or NetflixShowEpisode 12 | * @param <K> The matching TraktDTO class 13 | */ 14 | public class BaseEntityWrapper<T extends ViewItem,K extends BaseEntity> { 15 | 16 | /** 17 | * Netflix.csv object 18 | */ 19 | public T netflixViewItem; 20 | /** 21 | * Trakt object 22 | */ 23 | public K entity; 24 | 25 | public BaseEntityWrapper(T netflixTitle, K entity) { 26 | this.netflixViewItem = netflixTitle; 27 | this.entity = entity; 28 | } 29 | 30 | public T getTitle() { 31 | return netflixViewItem; 32 | } 33 | 34 | public K getEntity() { 35 | return entity; 36 | } 37 | } -------------------------------------------------------------------------------- /src/main/java/com/github/kilianB/model/netflix/NetflixMovie.java: -------------------------------------------------------------------------------- 1 | package com.github.kilianB.model.netflix; 2 | 3 | /** 4 | * Representing a single line found in the Netflix activity csv file 5 | * most likely representing a movie. 6 | * @author Kilian 7 | * 8 | */ 9 | public class NetflixMovie extends ViewItem{ 10 | 11 | public NetflixMovie(String title, String viewDate) { 12 | super(title, viewDate); 13 | } 14 | 15 | @Override 16 | public boolean isShow() { 17 | return false; 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/github/kilianB/model/netflix/NetflixShowEpisode.java: -------------------------------------------------------------------------------- 1 | package com.github.kilianB.model.netflix; 2 | 3 | /** 4 | * Representing a single line found in the Netflix activity csv file 5 | * most likely representing an episode of a show. 6 | * @author Kilian 7 | * 8 | */ 9 | public class NetflixShowEpisode extends ViewItem{ 10 | 11 | /** 12 | * Season of this episode 13 | */ 14 | private int season; //int 15 | 16 | /** 17 | * Title of the series 18 | */ 19 | private String series; //Title of the show 20 | 21 | 22 | public NetflixShowEpisode(String title, String viewDate, int season, String series) { 23 | super(title, viewDate); 24 | this.season = season; 25 | this.series = series; 26 | } 27 | 28 | @Override 29 | public boolean isShow() { 30 | return true; 31 | } 32 | 33 | @Override 34 | public String toString() { 35 | return "NetflixShow [season=" + season + ", series=" + series + ", title=" + title + ", viewDate=" + viewDate + "]"; 36 | } 37 | 38 | /** 39 | * @return The season number as parsed from the viewing history file 40 | * <p> Example: 1 41 | */ 42 | public int getSeason() { 43 | return season; 44 | } 45 | 46 | public void setSeason(int season) { 47 | this.season = season; 48 | } 49 | 50 | /** 51 | * @return The name of the series as parsed from the viewing history file. 52 | * <p> Example: (Game of Thrones) 53 | * 54 | */ 55 | public String getSeries() { 56 | return series; 57 | } 58 | 59 | public void setSeries(String series) { 60 | this.series = series; 61 | } 62 | 63 | 64 | 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/github/kilianB/model/netflix/ViewItem.java: -------------------------------------------------------------------------------- 1 | package com.github.kilianB.model.netflix; 2 | 3 | /** 4 | * Basic Item representing a single line found in the Netflix activity csv file 5 | * @author Kilian 6 | * 7 | */ 8 | public abstract class ViewItem { 9 | 10 | //Data read by parsing the input file. 11 | 12 | /** 13 | * Title of the movie or show 14 | */ 15 | protected String title; 16 | /** 17 | * Date the episode/movie was watched on netflix. Hence no data manipulation takes place in java 18 | * no reason to cast it into an actual date object 19 | */ 20 | protected String viewDate; 21 | 22 | 23 | public ViewItem(String title, String viewDate) { 24 | this.title = title; 25 | this.viewDate = viewDate; 26 | } 27 | 28 | /** 29 | * Return true if this object represents a netflix show/episode. 30 | * Return false if it is a movie. 31 | * TODO bad OOP style. ... instanceof could be used as well. Anyways 32 | * go with it for now. 33 | * @return 34 | */ 35 | public abstract boolean isShow(); 36 | 37 | /** 38 | * @return The title of the movie or show as parsed directly from the netflix.csv file 39 | * <p> Example: "The winter is coming" 40 | */ 41 | public String getTitle() { 42 | return title; 43 | } 44 | 45 | public void setTitle(String title) { 46 | this.title = title; 47 | } 48 | 49 | public String getViewDate() { 50 | return viewDate; 51 | } 52 | 53 | public void setViewDate(String viewDate) { 54 | this.viewDate = viewDate; 55 | } 56 | 57 | @Override 58 | public String toString() { 59 | return "ViewItem [title=" + title + ", viewDate=" + viewDate+"]"; 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/trakt/TraktHelper.java: -------------------------------------------------------------------------------- 1 | package trakt; 2 | 3 | import java.io.IOException; 4 | import java.util.Arrays; 5 | import java.util.HashMap; 6 | import java.util.List; 7 | import java.util.Map; 8 | import java.util.Map.Entry; 9 | import java.util.Optional; 10 | import java.util.Set; 11 | import java.util.concurrent.ConcurrentHashMap; 12 | import java.util.logging.Logger; 13 | 14 | import com.github.kilianB.model.BaseEntityWrapper; 15 | import com.github.kilianB.model.netflix.NetflixMovie; 16 | import com.github.kilianB.model.netflix.NetflixShowEpisode; 17 | import com.uwetrottmann.trakt5.TraktV2; 18 | import com.uwetrottmann.trakt5.entities.BaseEntity; 19 | import com.uwetrottmann.trakt5.entities.Movie; 20 | import com.uwetrottmann.trakt5.entities.SearchResult; 21 | import com.uwetrottmann.trakt5.entities.Season; 22 | import com.uwetrottmann.trakt5.entities.Show; 23 | import com.uwetrottmann.trakt5.enums.Extended; 24 | import com.uwetrottmann.trakt5.enums.IdType; 25 | import com.uwetrottmann.trakt5.enums.Type; 26 | import com.uwetrottmann.trakt5.services.Episodes; 27 | import com.uwetrottmann.trakt5.services.Search; 28 | import com.uwetrottmann.trakt5.services.Seasons; 29 | 30 | import retrofit2.Response; 31 | 32 | public class TraktHelper { 33 | 34 | private static final Logger LOGGER = Logger.getLogger(TraktHelper.class.getName()); 35 | 36 | private final String clientId; 37 | 38 | /** 39 | * 40 | * Trakt API to access movie and show metadata 41 | * 42 | * @see https://trakt.tv/ 43 | */ 44 | private TraktV2 trakt; 45 | 46 | /** 47 | * Keep track of series and movies we could not find by querying the trakt 48 | * database 49 | */ 50 | private Map<Type, Set<String>> notFoundOnTrakt = new HashMap<>(); 51 | 52 | // Cache end points 53 | private Search searchEndpoint; 54 | private Seasons seasonEndpoint; 55 | private Episodes episodeEndpoint; 56 | 57 | public TraktHelper(String clientId) { 58 | this.clientId = clientId; 59 | setup(); 60 | } 61 | 62 | private void setup() { 63 | trakt = new TraktV2(clientId); 64 | searchEndpoint = trakt.search(); 65 | seasonEndpoint = trakt.seasons(); 66 | episodeEndpoint = trakt.episodes(); 67 | 68 | // Setup hashsets 69 | notFoundOnTrakt.put(Type.SHOW, ConcurrentHashMap.newKeySet()); 70 | notFoundOnTrakt.put(Type.MOVIE, ConcurrentHashMap.newKeySet()); 71 | 72 | 73 | } 74 | 75 | @SuppressWarnings("unchecked") 76 | /** 77 | * Wraps the optional show with the original showName used to search the title 78 | * as the title delivered by netflix might not be identical with the title used 79 | * by trakt. This might be unnecessary but prevents annoying cornver cases. 80 | * 81 | * @param showName 82 | * @return 83 | */ 84 | public Optional<BaseEntityWrapper<NetflixShowEpisode, Show>> searchShow(NetflixShowEpisode netflixShow) { 85 | Optional<Show> show = (Optional<Show>) queryTraktAPI(netflixShow.getSeries(), Type.SHOW); 86 | if (show.isPresent()) { 87 | 88 | //System.out.println("Show acquired: Size Genres" + show.get().genres.size() + " Certificate:" + show.get().certification.length()); 89 | 90 | return Optional.of(new BaseEntityWrapper<NetflixShowEpisode, Show>(netflixShow, show.get())); 91 | } else { 92 | return Optional.empty(); 93 | } 94 | } 95 | 96 | @SuppressWarnings("unchecked") 97 | public Optional<BaseEntityWrapper<NetflixMovie, Movie>> searchMovie(NetflixMovie netflixMovie) { 98 | Optional<Movie> movie = (Optional<Movie>) queryTraktAPI(netflixMovie.getTitle(), Type.MOVIE); 99 | if (movie.isPresent()) { 100 | return Optional.of(new BaseEntityWrapper<NetflixMovie, Movie>(netflixMovie, movie.get())); 101 | } else { 102 | return Optional.empty(); 103 | } 104 | } 105 | 106 | /* 107 | * Duplicate code following. Maybe use a functional interface or simply a 108 | * util.Function and pass it along ? .apply 109 | */ 110 | 111 | private Optional<? extends BaseEntity> queryTraktAPI(String title, Type showOrMovie) { 112 | 113 | // TODO remove on "production" 114 | assert (showOrMovie.equals(Type.SHOW) || showOrMovie.equals(Type.MOVIE)); 115 | 116 | try { 117 | LOGGER.config("Search for: " + title); 118 | 119 | Response<List<SearchResult>> results = searchEndpoint 120 | .textQuery(showOrMovie, title, null, null, null, null, null, null, Extended.FULL, 1, 1).execute(); 121 | if (results.isSuccessful()) { 122 | 123 | if (results.body().size() == 0) { 124 | notFoundOnTrakt.get(showOrMovie).add(title); 125 | LOGGER.warning( 126 | "Could not find : " + (showOrMovie.equals(Type.SHOW) ? "series " : "movie ") + title); 127 | return Optional.empty(); 128 | } else { 129 | 130 | var result = results.body().get(0); 131 | 132 | if (result.score < 1000) { 133 | LOGGER.warning(title + " matched with a low similarity score of " + result.score + " :" 134 | + (showOrMovie.equals(Type.SHOW) ? result.show.title : result.movie.title)); 135 | 136 | } 137 | 138 | if (showOrMovie.equals(Type.SHOW)) { 139 | return Optional.of(result.show); 140 | } else if (showOrMovie.equals(Type.MOVIE)) { 141 | return Optional.of(result.movie); 142 | } else { 143 | LOGGER.severe( 144 | "queryTraktAPI does not handle types of type:" + showOrMovie + " Aborted: " + title); 145 | return Optional.empty(); 146 | } 147 | } 148 | } else { 149 | LOGGER.severe("Search request for - " + showOrMovie + " was not successfull. Please try again later"); 150 | return Optional.empty(); 151 | } 152 | } catch (IOException e) { 153 | e.printStackTrace(); 154 | return Optional.empty(); 155 | } 156 | } 157 | 158 | /** 159 | * Download detailed information about every season for a series 160 | * 161 | * @return 162 | * @throws IOException 163 | */ 164 | public HashMap<Show, List<Season>> downloadSeriesInfo(Map<String, Show> traktShows) throws IOException{ 165 | var seasonList = new HashMap<Show, List<Season>>(); 166 | 167 | for (Entry<String, Show> entry : traktShows.entrySet()) { 168 | Show show = entry.getValue(); 169 | var response = seasonEndpoint.summary(show.ids.slug, Extended.EPISODES).execute(); 170 | 171 | if (response.isSuccessful()) { 172 | List<Season> seasons = response.body(); 173 | seasonList.put(show, seasons); 174 | }else { 175 | System.out.println("Download Season info not sucessfull"); 176 | } 177 | } 178 | 179 | return seasonList; 180 | } 181 | 182 | 183 | public int getEpisodeRuntime(String traktId) throws IOException { 184 | 185 | Response<List<SearchResult>> result = searchEndpoint.idLookup(IdType.TRAKT, traktId, Type.EPISODE, Extended.FULL, 1, 1).execute(); 186 | if(result.isSuccessful()) { 187 | SearchResult res = result.body().get(0); 188 | return res.episode.runtime; 189 | }else { 190 | return -1; 191 | } 192 | } 193 | 194 | 195 | public Map<Type, Set<String>> getNotFoundItems() { 196 | return notFoundOnTrakt; 197 | } 198 | 199 | public void printNotFoundItems() { 200 | System.out.println("Not found shows: " + Arrays.toString(notFoundOnTrakt.get(Type.SHOW).toArray())); 201 | System.out.println("Not found movies: " + Arrays.toString(notFoundOnTrakt.get(Type.MOVIE).toArray())); 202 | } 203 | 204 | } 205 | -------------------------------------------------------------------------------- /src/test/java/fileHandling/in/TestNetflixParser.java: -------------------------------------------------------------------------------- 1 | package fileHandling.in; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertAll; 4 | import static org.junit.jupiter.api.Assertions.assertEquals; 5 | import static org.junit.jupiter.api.Assertions.assertFalse; 6 | import static org.junit.jupiter.api.Assertions.assertTrue; 7 | 8 | import java.lang.reflect.Method; 9 | import java.util.Optional; 10 | 11 | import org.junit.jupiter.api.AfterAll; 12 | import org.junit.jupiter.api.BeforeAll; 13 | import org.junit.jupiter.api.Disabled; 14 | import org.junit.jupiter.api.DisplayName; 15 | import org.junit.jupiter.api.Nested; 16 | import org.junit.jupiter.api.Test; 17 | import org.junit.platform.commons.support.ReflectionSupport; 18 | 19 | import com.github.kilianB.fileHandling.in.NetflixParser; 20 | import com.github.kilianB.model.netflix.NetflixMovie; 21 | import com.github.kilianB.model.netflix.NetflixShowEpisode; 22 | import com.github.kilianB.model.netflix.ViewItem; 23 | 24 | /** 25 | * 26 | * @author Kilian 27 | * TODO we don't have fail test cases. 28 | */ 29 | class TestNetflixParser { 30 | 31 | static Method parseMethod; 32 | 33 | @BeforeAll 34 | static void setUpBeforeClass() throws Exception { 35 | 36 | // Cache reflection method 37 | Optional<Method> parseCandidate = ReflectionSupport.findMethod(NetflixParser.class, "parseEntry", String.class,String.class); 38 | 39 | if (parseCandidate.isPresent()) { 40 | parseMethod = parseCandidate.get(); 41 | } else { 42 | throw new NoSuchMethodException("Could not find parseEntry method in CSVHelper.class"); 43 | } 44 | 45 | } 46 | 47 | @AfterAll 48 | static void tearDownAfterClass() throws Exception { 49 | } 50 | 51 | @Nested 52 | @DisplayName("Test Parsing Methods") 53 | class TestCSVParser { 54 | 55 | @Nested 56 | class TestSeries { 57 | 58 | @Test 59 | void basicSeries() { 60 | String title = "Title"; 61 | int season = 1; 62 | String series = "TestSeries"; 63 | 64 | NetflixShowEpisode show = new NetflixShowEpisode(title, "1.1.2018",season,series); 65 | validateEntry(show, title, season,series); 66 | } 67 | 68 | @Test 69 | void defaultSeriesName() { 70 | String inputString = "Lie to Me: Season 3: In the Red"; 71 | ViewItem parsedShow = (ViewItem) ReflectionSupport.invokeMethod(parseMethod, null,inputString,"1.1.2018"); 72 | validateEntry(parsedShow, "In the Red", 3,"Lie to Me"); 73 | } 74 | 75 | @Test 76 | void numericalSeriesName() { 77 | String inputString = "Touch: Season 1: 1 + 1 = 3"; 78 | ViewItem parsedShow = (ViewItem) ReflectionSupport.invokeMethod(parseMethod, null,inputString,"1.1.2018"); 79 | validateEntry(parsedShow, "1 + 1 = 3", 1,"Touch"); 80 | } 81 | 82 | @Test 83 | void colonsInSeriesName() { 84 | String inputString = "Star Trek: Discovery: Season 1: Context is for Kings"; 85 | ViewItem parsedShow = (ViewItem) ReflectionSupport.invokeMethod(parseMethod, null,inputString,"1.1.2018"); 86 | validateEntry(parsedShow, "Context is for Kings", 1,"Star Trek: Discovery"); 87 | } 88 | 89 | @Test 90 | void colonsInEpisodeName() { 91 | String inputString = "The Fresh Prince of Bel-Air: Season 1: Someday Your Prince Will Be in Effect: Part 2"; 92 | ViewItem parsedShow = (ViewItem) ReflectionSupport.invokeMethod(parseMethod, null,inputString,"1.1.2018"); 93 | validateEntry(parsedShow, "Someday Your Prince Will Be in Effect: Part 2", 1,"The Fresh Prince of Bel-Air"); 94 | } 95 | 96 | 97 | void validateEntry(ViewItem data, String title,int season,String series) { 98 | TestCSVParser.this.validateEntry(NetflixShowEpisode.class, data, title, season,series); 99 | } 100 | 101 | } 102 | 103 | @Nested 104 | class TestMovies { 105 | 106 | @Test 107 | void movieWithoutColon() { 108 | String movieTitle = "The Legend of Tarzan"; 109 | ViewItem parsedMovie = (ViewItem) ReflectionSupport.invokeMethod(parseMethod, null, 110 | movieTitle,"ViewDate"); 111 | validateEntry(parsedMovie, movieTitle); 112 | } 113 | 114 | @Test 115 | void movieWithColon() { 116 | String movieTitle = "Underworld: Awakening"; 117 | ViewItem parsedMovie = (ViewItem) ReflectionSupport.invokeMethod(parseMethod, null, 118 | movieTitle,"ViewDate"); 119 | validateEntry(parsedMovie, movieTitle); 120 | } 121 | 122 | //As expected this will assert to be a show. 123 | @Test 124 | @Disabled 125 | void movieWithTwoColons() { 126 | String movieTitle = "\"Underworld: Awakening : Hello\""; 127 | ViewItem parsedMovie = (ViewItem) ReflectionSupport.invokeMethod(parseMethod, null, 128 | wrapMovieTitle(movieTitle)); 129 | validateEntry(parsedMovie, movieTitle); 130 | } 131 | 132 | 133 | void validateEntry(ViewItem data, String title) { 134 | TestCSVParser.this.validateEntry(NetflixMovie.class, data, title, Integer.MIN_VALUE,null); 135 | } 136 | } 137 | 138 | /** 139 | * Helper method to assert if the supplied view item contains the information expected 140 | * @param clazz 141 | * @param data 142 | * @param title 143 | * @param episode 144 | */ 145 | void validateEntry(Class clazz, ViewItem data, String title, int season, String series) { 146 | 147 | assertEquals(clazz,data.getClass()); 148 | 149 | //Assert movie 150 | if(data.getClass().equals(NetflixMovie.class)) { 151 | 152 | //@formatter:off 153 | assertAll( 154 | () -> assertFalse(data.isShow()), 155 | () -> assertEquals(title,data.getTitle()), 156 | () -> assertEquals("ViewDate",data.getViewDate()) 157 | ); 158 | //@formatter:on 159 | 160 | }else { 161 | 162 | NetflixShowEpisode show = (NetflixShowEpisode) data; 163 | assertAll( 164 | () -> assertTrue(show.isShow()), 165 | () -> assertEquals(title,show.getTitle()), 166 | () -> assertEquals("1.1.2018",show.getViewDate()), 167 | () -> assertEquals(season,show.getSeason()), 168 | () -> assertEquals(series,show.getSeries()) 169 | ); 170 | } 171 | 172 | 173 | } 174 | 175 | /** 176 | * Wrap the movie title into an object the reflection method can work with 177 | * 178 | * @param movieTitle 179 | */ 180 | Object[] wrapMovieTitle(String movieTitle) { 181 | return new Object[] { new String[] { movieTitle, "ViewDate" } }; 182 | } 183 | } 184 | 185 | 186 | } 187 | --------------------------------------------------------------------------------