├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── addon.xml ├── bin └── tv_grab_zap2epg ├── changelog.txt ├── default.py ├── genre.py ├── logger.py ├── resources ├── icon.png ├── img │ ├── antenna.png │ ├── channel.png │ ├── minus.png │ ├── plus.png │ ├── run.png │ ├── screenshot001.png │ ├── screenshot002.png │ ├── screenshot003.png │ ├── screenshot004.png │ ├── screenshot005.png │ ├── screenshot006.png │ ├── settings.png │ └── tv.png ├── language │ └── resource.language.en_gb │ │ └── strings.po └── settings.xml ├── settings.xml ├── tvh.py ├── tvlistings.py └── zap2epg.py /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /cache 2 | *.pyo 3 | *.log 4 | xmltv.xml 5 | settings.xml 6 | zap2epg.log 7 | *.json 8 | .venv 9 | __pycache__ -------------------------------------------------------------------------------- /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 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) 2017 {name of author} 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 | script.module.zap2epg Copyright (C) 2017 edit4ever 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 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # zap2epg - Kodi addon (script.module.zap2epg) 2 | 3 | zap2epg will generate an xmltv.xml file for USA/Canada TV lineups.* 4 | 5 | zap2epg is originally designed to be easily setup in Kodi for use as a grabber for tvheadend. It includes the ability to setup your channel list to reduce the amount of data downloaded and speed up the grab. It has an option for downloading extra detail information for programs. (Note: this option will generate an extra http request per episode) It also has an option to append the extra detail information to the description (plot) field, which makes displaying this information in the Kodi EPG easier on many skins. 6 | 7 | Setup: 8 | 1. Install the zap2epg addon in Kodi 9 | 2. Run the addon and setup your lineup 10 | 3. Configure your channel list (add channels to be downloaded) 11 | 4. You can run the program from the addon as a test - not necessary 12 | 5. Setup the zap2epg grabber in tvheadend 13 | 6. Enjoy your new EPG! 14 | 15 | Language identification is accomplished through a python module 'LangId'. This module does not have to be installed inside the Kodi interpreter but must be installed in on the device machine. 16 | For debian based machines 17 | 1. sudo apt-get update 18 | 2. sudo apt-get install pip (if not already installed) 19 | 3. sudo apt-get install python3-numpy 20 | 4. pip install langid 21 | 22 | If you try to install langid befoure installing numpy, you may get an error as the langid tries to install it but cannot find the required files. 23 | 24 | The setting "Use Hex values for genre type instead of textual name" will use the hex values from http://www.etsi.org/deliver/etsi_en/300400_300499/300468/01.11.01_60/en_300468v011101p.pdf 25 | Both Kodi and TVH use those categories as their genre groups. Kodi understands and stores the genre information as a hex value. As of now, I can't figure out how to get TVH to recognize the genre hex values. 26 | 27 | 28 | * Note that zap2epg is a proof of concept and is for personal experimentation only. It is not meant to be used in a commercial product and its use is your own responsibiility. 29 | -------------------------------------------------------------------------------- /addon.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | executable 10 | 11 | 12 | zap2epg will generate an xmltv.xml file for USA/Canada TV lineups 13 | zap2epg is originally designed to be easily setup in Kodi for use as a grabber for tvheadend. It includes the ability to setup your custom channel list to reduce the amount of data downloaded and speed up the grab. It has an option for downloading extra detail information for programs. (Note: this option will generate an extra http request per series) It also has an option to append the extra detail information to the description (plot) field, which makes displaying this information in the Kodi EPG easier on many skins. 14 | 15 | Setup: 16 | 1. Install the zap2epg addon in Kodi 17 | 2. Run the addon and setup your lineup 18 | 3. Configure your channel list (add channels to be downloaded) 19 | 4. You can run the program from the addon as a test (not necessary) 20 | 5. Setup the zap2epg grabber in tvheadend 21 | 6. Enjoy your new EPG! 22 | 23 | 24 | all 25 | GNU GENERAL PUBLIC LICENSE. Version 3, June 2007 26 | 27 | 28 | 29 | 30 | 31 | v2.2.1 - update for gracenote api call. Fixed spelling errors in genres. (2025-07-21) 32 | v2.2.0 - update for gracenote. Added separate files for EPG and TVH connections and new logger system (2025-07-14) 33 | v2.0.4 - Update for Kodi 20+. Updated EPG Genre linking and language detection. 34 | v2.0.3 - fix channel configuration error (2021-05-23) 35 | v2.0.2 - fix Tvheadend username and password option (2021-03-29) 36 | v2.0.1 - Kodi 19 dialog fix (2021-02-25) 37 | v2.0.0 - Python 3 update (2020-10-27) 38 | v1.3.0 - fix server issues for lineups (2019-04-12) 39 | v1.2.0 - add option to refresh download cache days (2019-03-04) 40 | v1.1.0 - added ability to refresh TBA episodes (2018-11-20) 41 | v1.0.0 - official stable release (2018-07-12) 42 | 43 | 44 | resources/icon.png 45 | 46 | resources/img/screenshot001.png 47 | resources/img/screenshot002.png 48 | resources/img/screenshot003.png 49 | resources/img/screenshot004.png 50 | resources/img/screenshot005.png 51 | resources/img/screenshot006.png 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /bin/tv_grab_zap2epg: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # zap2epg tv schedule grabber for kodi 3 | ################################################################################ 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License for more details. 13 | # 14 | # You should have received a copy of the GNU General Public License 15 | # along with this program. If not, see . 16 | ################################################################################ 17 | 18 | . /etc/profile 19 | 20 | ADDON_HOME="$HOME/.kodi/userdata/addon_data/script.module.zap2epg" 21 | ADDON_DIR="$HOME/.kodi/addons/script.module.zap2epg" 22 | XMLTV_OUTPUT="$ADDON_HOME/xmltv.xml" 23 | 24 | if [ $# -lt 1 ] 25 | then 26 | CD=`pwd` 27 | cd $ADDON_HOME 28 | python $ADDON_DIR/zap2epg.py 29 | cat $XMLTV_OUTPUT 30 | cd $CD 31 | exit 0 32 | fi 33 | 34 | while [ $# -gt 0 ] 35 | do case "$1" in 36 | -d | --description ) 37 | printf "tv_grab_zap2epg is a simple grabber for USA-Canada\n" 38 | ;; 39 | 40 | -v | --version ) 41 | printf "2.2.1\n" 42 | ;; 43 | 44 | -c | --capabilities ) 45 | printf "baseline\n" 46 | ;; 47 | 48 | -* ) 49 | printf "unknown option: %s\n" "$1" 50 | printf "Usage: %s: [--description] [--version] [--capabilities]\n" ${0##*/} 51 | exit 2 52 | ;; 53 | 54 | esac; shift 55 | done 56 | 57 | exit 0 58 | -------------------------------------------------------------------------------- /changelog.txt: -------------------------------------------------------------------------------- 1 | v2.2.1 (2025-07-21) 2 | - Fixed api call to gracenote missing a few parameters 3 | - Fixed spelling in genres 4 | - Fixed whitespace in parts of code for better reading and consistancy 5 | 6 | v2.2.0 (2025-07-14) 7 | - Updated EPG website to the current website. 8 | - Updated the code to connect to TVH. Using request (instead of requests) framework so LibreElec users can use the addon. 9 | - Added HTTP digest authentication (still a small bug in code) 10 | - Added logger python script to log from all python scripts instead of just the main script. 11 | - Added back NEW / LIVE / PREMIERE tags in the EPG description. 12 | 13 | v1.3.1 (2020-10-29) 14 | - remove doctype error for TVH on OSMC 15 | 16 | v1.3.0 (2019-04-12) 17 | - fix server issues for lineups 18 | 19 | v1.2.0 (2019-03-04) 20 | - add option to refresh download cache days 21 | 22 | v1.1.0 (2018-11-20) 23 | - added ability to refresh TBA episode information 24 | 25 | v1.0.0 (2018-07-12) 26 | - official stable release 27 | 28 | v0.7.4 (2018-01-20) 29 | - fix for channel configuration with digital cable lineups 30 | 31 | v0.7.3 (2018-01-19) 32 | - fixes issue with channel configuration when not using Tvheadend 33 | 34 | v0.7.2 (2018-01-18) 35 | - fixes issue with certain digital lineups 36 | 37 | v0.7.1 (2018-01-15) 38 | - fixes issue with program id number (series recording error) 39 | 40 | v0.7.0 (2018-01-09) 41 | - adds option to disable Tvheadend functions 42 | 43 | v0.6.3 (2017-12-18) 44 | - fixes Tvh service name issue with username-password 45 | 46 | v0.6.2 (2017-12-13) 47 | - Only match Tvheadend channels that are enabled 48 | - Add option for original genre categories 49 | - various fixes for extra description listings 50 | 51 | v0.6.1 (2017-12-8) 52 | - OTA Tvheadend channels pre-selected in channels list 53 | 54 | v0.6.0 (2017-12-7) 55 | - add Kodi 18 (LE9) compatibility and fix TVH username-password 56 | 57 | v0.5.4 (2017-11-28) 58 | - fix for movie cast info 59 | 60 | v0.5.3 (2017-11-26) 61 | - fix for TVH username-password 62 | 63 | v0.5.2 (2017-11-22) 64 | - fix for channel names with ampersand 65 | 66 | v0.5.0 (2017-11-19) 67 | - add tvheadend subchannel and match option 68 | 69 | v0.4.1 (2017-11-16) 70 | - adds option to adjust genre information 71 | 72 | v0.3.5 (2017-11-14) 73 | - fixes missing episodes 74 | 75 | v0.3.2 (2017-11-12) 76 | - fixes url change for location 77 | 78 | v0.3.0 (2017-11-07) 79 | - adds generic timezone lineups and station/channels icons | removes old episode data from cache 80 | 81 | v0.2.1 (2017-11-02) 82 | - fix for location name and JSON file errors 83 | 84 | v0.2.0 (2017-10-27) 85 | - modified for new zap2it guide data 86 | 87 | v0.1.0 (2017-10-24) 88 | - initial test release 89 | -------------------------------------------------------------------------------- /default.py: -------------------------------------------------------------------------------- 1 | # zap2epg tv schedule grabber for kodi 2 | ################################################################################ 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program. If not, see . 15 | ################################################################################ 16 | import xbmc, xbmcaddon, xbmcvfs, xbmcgui 17 | import os 18 | from logger import createLogger, logger 19 | from tvh import tvh_connect, tvh_getData 20 | from tvlistings import create_opener, fetch_url 21 | from xbmcswift2 import Plugin 22 | import re 23 | import zap2epg 24 | import urllib.request, urllib.error, urllib.parse 25 | import json 26 | from collections import OrderedDict 27 | import time 28 | import datetime 29 | 30 | userdata = xbmcvfs.translatePath(xbmcaddon.Addon().getAddonInfo('profile')) 31 | tvhoff = True if xbmcaddon.Addon().getSetting('tvhoff') == 'true' else False 32 | if not os.path.exists(userdata): 33 | os.mkdir(userdata) 34 | Clist = os.path.join(userdata, 'channels.json') 35 | tvhList = os.path.join(userdata, 'TVHchannels.json') 36 | cacheDir = os.path.join(userdata, 'cache') 37 | plugin = Plugin() 38 | dialog = xbmcgui.Dialog() 39 | gridtime = (int(time.mktime(time.strptime(str(datetime.datetime.now().replace(microsecond=0,second=0,minute=0)), '%Y-%m-%d %H:%M:%S')))) 40 | connection = None 41 | create_opener #create the connection to the EPG website 42 | 43 | def connectTVH(updateSetting = False): 44 | #import web_pdb; web_pdb.set_trace() 45 | global tvhoff, connection, tvh_url 46 | if tvhoff is True: 47 | tvh_url = xbmcaddon.Addon().getSetting('tvhurl') 48 | tvh_port = xbmcaddon.Addon().getSetting('tvhport') 49 | tvh_usern = xbmcaddon.Addon().getSetting('usern') 50 | tvh_passw = xbmcaddon.Addon().getSetting('passw') 51 | tvh_digest = True if xbmcaddon.Addon().getSetting('digest') == 'true' else False 52 | 53 | connection = tvh_connect(tvh_url, tvh_port, tvh_usern, tvh_passw, tvh_digest) 54 | tvhoff = connection 55 | if tvhoff is False: 56 | dialog.ok("TVHeadend Server", f'The TVH server {tvh_url} was not found or username / password was incorrect. Please check TVH settings') 57 | if updateSetting: 58 | connection = None 59 | tvhoff = False 60 | xbmcaddon.Addon().setSetting(id='tvhoff', value='false') 61 | 62 | def getTVHChannels(): 63 | #import web_pdb; web_pdb.set_trace() 64 | global tvhoff, connection 65 | if connection is None: 66 | connectTVH() 67 | if connection is not None: 68 | channels = tvh_getData('allchannels') #returns a JSON string 69 | try: 70 | logger.info('Accessing Tvheadend channel list from: %s', tvh_url) 71 | #channels = response.json() 72 | with open(tvhList,"w") as f: 73 | json.dump(channels,f) 74 | except Exception as e: 75 | logger.warning(f"Error Type: {type(e).__name__}: {e}") 76 | tvhoff = False 77 | 78 | def get_icon_path(icon_name): 79 | #import web_pdb; web_pdb.set_trace() 80 | addon_path = xbmcaddon.Addon().getAddonInfo("path") 81 | return os.path.join(addon_path, 'resources', 'img', icon_name+".png") 82 | 83 | def create_cList(): #channel listings 84 | #import web_pdb; web_pdb.set_trace() 85 | tvhClist = [] 86 | if tvhoff is True and not os.path.isfile(tvhList): 87 | getTVHChannels() 88 | if tvhoff is True: 89 | with open(tvhList) as tvhData: 90 | tvhDict = json.load(tvhData) 91 | for ch in tvhDict['entries']: 92 | channelEnabled = ch['enabled'] 93 | if channelEnabled == True: 94 | tvhClist.append(ch['number']) 95 | lineupcode = xbmcaddon.Addon().getSetting('lineupcode') 96 | #url = 'http://tvlistings.gracenote.com/api/grid?lineupId=×pan=3&headendId=' + lineupcode + '&country=' + country + '&device=' + device + '&postalCode=' + zipcode + '&time=' + str(gridtime) + '&pref=-&userId=-' 97 | options = {'lineupcode': lineupcode, 'country': country, 'device': device, 'zipcode': zipcode, 'gridtime': str(gridtime)} 98 | #content = urllib.request.urlopen(url).read() 99 | content = fetch_url('lineup', options) 100 | contentDict = json.loads(content) 101 | stationDict = {} 102 | if 'channels' in contentDict: 103 | for channel in contentDict['channels']: 104 | skey = channel.get('channelId') 105 | stationDict[skey] = {} 106 | stationDict[skey]['name'] = channel.get('callSign') 107 | stationDict[skey]['num'] = channel.get('channelNo') 108 | if channel.get('channelNo') in tvhClist: 109 | stationDict[skey]['include'] = 'True' 110 | else: 111 | stationDict[skey]['include'] = 'False' 112 | stationDictSort = OrderedDict(sorted(iter(stationDict.items()), key=lambda i: (float(i[1]['num'])))) 113 | 114 | #Search the stations for duplicate channel numbers. Get rid of the non 'DT' channel(s) if so. 115 | for station in stationDictSort: 116 | myStations = {k: v for k, v in stationDictSort.items() if v['num'] == stationDictSort[station]['num']} 117 | if len(myStations) > 1: 118 | for st in myStations: 119 | if myStations[st]['name'].find('DT') < 0: 120 | stationDictSort[st]['include'] = 'False' 121 | 122 | with open(Clist,"w") as f: 123 | json.dump(stationDictSort,f) 124 | 125 | @plugin.route('/channels') #Menu item Configure Channel List 126 | def channels(): 127 | # import web_pdb; web_pdb.set_trace() 128 | lineupcode = xbmcaddon.Addon().getSetting('lineupcode') 129 | if lineup is None or zipcode is None: 130 | dialog.ok('Location not configured!', 'Please setup your location before configuring channels.') 131 | if not os.path.isfile(Clist): 132 | create_cList() 133 | else: 134 | newList = dialog.yesno('Existing Channel List Found', 'Would you like to download a new channel list or review your current list?', 'Review', 'Download') 135 | if newList: 136 | os.remove(Clist) 137 | create_cList() 138 | with open(Clist) as data: 139 | stationDict = json.load(data) 140 | stationDict = OrderedDict(sorted(iter(stationDict.items()), key=lambda i: (float(i[1]['num'])))) 141 | stationCode = [] 142 | stationListName = [] 143 | stationListNum = [] 144 | stationListInclude = [] 145 | for station in stationDict: 146 | stationCode.append(station) 147 | stationListName.append(stationDict[station]['name']) 148 | stationListNum.append(stationDict[station]['num']) 149 | stationListInclude.append(stationDict[station]['include']) 150 | stationPre = [i for i, x in enumerate(stationListInclude) if x == 'True'] 151 | stationListFull = list(zip(stationListNum, stationListName)) 152 | stationList = ["%s %s" % x for x in stationListFull] 153 | selCh = dialog.multiselect('Click to Select Channels to Include', stationList, preselect=stationPre) 154 | for station in stationDict: 155 | stationDict[station]['include'] = 'False' 156 | stationListCodes = [] 157 | if selCh: 158 | for channel in selCh: 159 | skey = stationCode[channel] 160 | stationDict[skey]['include'] = 'True' 161 | stationListCodes.append(skey) 162 | with open(Clist,"w") as f: 163 | json.dump(stationDict,f) 164 | xbmcaddon.Addon().setSetting(id='slist', value=','.join(stationListCodes)) 165 | 166 | @plugin.route('/location') #Menu item: Change Current Location 167 | def location(): 168 | #import web_pdb; web_pdb.set_trace() 169 | global country 170 | countryPick = ['USA', 'CAN'] 171 | countryNew = dialog.select('Select your country', list=countryPick) 172 | if countryNew == 0: 173 | zipcodeNew = dialog.input('Enter your zipcode', defaultt=zipcode, type=xbmcgui.INPUT_NUMERIC) 174 | if countryNew == 1: 175 | zipcodeNew = dialog.input('Enter your zipcode', defaultt=zipcode, type=xbmcgui.INPUT_ALPHANUM) 176 | if not 'zipcodeNew' in vars() or 'zipcodeNew' in globals(): 177 | return 178 | zipcodeNew = re.sub(' ', '', zipcodeNew) 179 | zipcodeNew = zipcodeNew.upper() 180 | xbmcaddon.Addon().setSetting(id='zipcode', value=zipcodeNew) 181 | 182 | if countryNew == 0: 183 | options = {'country': 'USA', 'zipcodeNew': zipcodeNew} 184 | #url = 'https://tvlistings.gracenote.com/gapzap_webapi/api/Providers/getPostalCodeProviders/USA/' + zipcodeNew + '/gapzap/en' 185 | lineupsN = ['AVAILABLE LINEUPS', 'TIMEZONE - Eastern', 'TIMEZONE - Central', 'TIMEZONE - Mountain', 'TIMEZONE - Pacific', 'TIMEZONE - Alaskan', 'TIMEZONE - Hawaiian'] 186 | lineupsC = ['NONE', 'DFLTE', 'DFLTC', 'DFLTM', 'DFLTP', 'DFLTA', 'DFLTH'] 187 | deviceX = ['-', '-', '-', '-', '-', '-', '-'] 188 | if countryNew == 1: 189 | options = {'country': 'CAN', 'zipcodeNew': zipcodeNew} 190 | #url = 'https://tvlistings.gracenote.com/gapzap_webapi/api/Providers/getPostalCodeProviders/CAN/' + zipcodeNew + '/gapzap/en' 191 | lineupsN = ['AVAILABLE LINEUPS', 'TIMEZONE - Eastern', 'TIMEZONE - Central', 'TIMEZONE - Mountain', 'TIMEZONE - Pacific'] 192 | lineupsC = ['NONE', 'DFLTEC', 'DFLTCC', 'DFLTMC', 'DFLTPC'] 193 | deviceX = ['-', '-', '-', '-', '-'] 194 | content = fetch_url('postal', options) 195 | if content is not None: 196 | lineupDict = json.loads(content) 197 | if 'Providers' in lineupDict: 198 | for provider in lineupDict['Providers']: 199 | lineupName = provider.get('name') 200 | lineupLocation = provider.get('location') 201 | if lineupLocation != '': 202 | lineupCombo = lineupName + ' (' + lineupLocation + ')' 203 | lineupsN.append(lineupCombo) 204 | else: 205 | lineupsN.append(lineupName) 206 | lineupsC.append(provider.get('headendId')) 207 | deviceGet = provider.get('device') 208 | if deviceGet == '' or deviceGet == ' ': 209 | deviceGet = '-' 210 | deviceX.append(deviceGet) 211 | 212 | else: 213 | dialog.ok('Error - No Providers!', 'No providers were found - please check zipcode and try again.') 214 | return 215 | lineupSel = dialog.select('Select a lineup', list=lineupsN) 216 | if lineupSel: 217 | lineupSelCode = lineupsC[lineupSel] 218 | lineupSelName = lineupsN[lineupSel] 219 | deviceSel = deviceX[lineupSel] 220 | xbmcaddon.Addon().setSetting(id='lineupcode', value=lineupSelCode) 221 | xbmcaddon.Addon().setSetting(id='lineup', value=lineupSelName) 222 | xbmcaddon.Addon().setSetting(id='device', value=deviceSel) 223 | if os.path.exists(cacheDir): 224 | entries = os.listdir(cacheDir) 225 | for entry in entries: 226 | oldfile = entry.split('.')[0] 227 | if oldfile.isdigit(): 228 | fn = os.path.join(cacheDir, entry) 229 | try: 230 | os.remove(fn) 231 | except: 232 | pass 233 | xbmc.executebuiltin('Container.Refresh') 234 | else: 235 | xbmc.executebuiltin('Container.Refresh') 236 | return 237 | else: 238 | return 239 | 240 | @plugin.route('/run') #Menu item: Run zap2epg and Update Guide Data 241 | def run(): 242 | #import web_pdb; web_pdb.set_trace() 243 | status = zap2epg.mainRun(userdata) 244 | dialog.ok('zap2epg Finished!', 'zap2epg completed in ' + str(status[0]) + ' seconds.\n' + str(status[1]) + ' Stations and ' + str(status[2]) + ' Episodes written to xmltv.xml file.') 245 | 246 | @plugin.route('/open_settings') #Menu item Configure Settings and Options 247 | def open_settings(): 248 | #import web_pdb; web_pdb.set_trace() 249 | plugin.open_settings() 250 | global tvhoff, connection 251 | # Test the connection to TVH if tvhoff is true 252 | tvhoff = True if xbmcaddon.Addon().getSetting('tvhoff') == 'true' else False 253 | if tvhoff is True: 254 | connectTVH(True) 255 | try: 256 | os.remove(tvhList) 257 | except: 258 | pass 259 | if connection is not None: 260 | getTVHChannels() 261 | else: 262 | tvhoff = False 263 | xbmcaddon.Addon().setSetting(id='tvhoff', value='false') 264 | 265 | @plugin.route('/') 266 | def index(): 267 | items = [] 268 | items.append( 269 | { 270 | 'label': 'Run zap2epg and Update Guide Data', 271 | 'path': plugin.url_for('run'), 272 | 'thumbnail':get_icon_path('run'), 273 | }) 274 | items.append( 275 | { 276 | 'label': 'Change Current Location | Zipcode: ' + zipcode + ' & Lineup: ' + lineup, 277 | 'path': plugin.url_for('location'), 278 | 'thumbnail':get_icon_path('antenna'), 279 | }) 280 | items.append( 281 | { 282 | 'label': 'Configure Channel List', 283 | 'path': plugin.url_for('channels'), 284 | 'thumbnail':get_icon_path('channel'), 285 | }) 286 | items.append( 287 | { 288 | 'label': 'Configure Settings and Options', 289 | 'path': plugin.url_for('open_settings'), 290 | 'thumbnail':get_icon_path('settings'), 291 | }) 292 | return items 293 | 294 | 295 | if __name__ == '__main__': 296 | log = os.path.join(userdata, 'zap2epg.log') 297 | createLogger(log) 298 | logger.info("We have connected to the logging program!") 299 | try: 300 | zipcode = xbmcaddon.Addon().getSetting('zipcode') 301 | if zipcode.isdigit(): 302 | country = 'USA' 303 | else: 304 | country = 'CAN' 305 | lineup = xbmcaddon.Addon().getSetting('lineup') 306 | device = xbmcaddon.Addon().getSetting('device') 307 | if zipcode == '' or lineup == '': 308 | zipConfig = dialog.yesno('No Lineup Configured!', 'You need to configure your lineup location before running zap2epg.\n\nWould you like to setup your lineup?') 309 | if zipConfig: 310 | location() 311 | xbmc.executebuiltin('Container.Refresh') 312 | except: 313 | dialog.ok('No Lineup Configured!', '', 'Please configure your zipcode and lineup under Change Current Location.') 314 | plugin.run() -------------------------------------------------------------------------------- /genre.py: -------------------------------------------------------------------------------- 1 | # genre Mapping of tv shows found in zap2it website 2 | ################################################################################ 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program. If not, see . 15 | ################################################################################ 16 | genreCount = [] 17 | 18 | def countGenres(): 19 | global genreCount 20 | return genreCount 21 | 22 | def genreSort(edict, userSelectedGenre, useHex): 23 | global genreCount 24 | genreList = [] 25 | updatedgenreList = [] 26 | EPgenre = edict['epgenres'] 27 | 28 | if userSelectedGenre == '1': #User selected 'Simple' 29 | for g in EPgenre: 30 | if g != "Comedy": 31 | genreList.append(g) 32 | if not set(['movie','Movie','Movies','movies']).isdisjoint(genreList): 33 | genreList.insert(0, "Movie / Drama") 34 | if not set(['News']).isdisjoint(genreList): 35 | genreList.insert(0, "News / Current Affairs") 36 | if not set(['Game show']).isdisjoint(genreList): 37 | genreList.insert(0, "Game show / Quiz / Contest") 38 | if not set(['Law']).isdisjoint(genreList): 39 | genreList.insert(0, "Show / Game show") 40 | if not set(['Art','Culture']).isdisjoint(genreList): 41 | genreList.insert(0, "Arts / Culture (without music)") 42 | if not set(['Entertainment']).isdisjoint(genreList): 43 | genreList.insert(0, "Popular culture / Traditional Arts") 44 | if not set(['Politics','Social','Public affairs']).isdisjoint(genreList): 45 | genreList.insert(0, "Social / Political issues / Economics") 46 | if not set(['Education','Science']).isdisjoint(genreList): 47 | genreList.insert(0, "Education / Science / Factual topics") 48 | if not set(['How-to']).isdisjoint(genreList): 49 | genreList.insert(0, "Leisure hobbies") 50 | if not set(['Travel']).isdisjoint(genreList): 51 | genreList.insert(0, "Tourism / Travel") 52 | if not set(['Sitcom']).isdisjoint(genreList): 53 | genreList.insert(0, "Variety show") 54 | if not set(['Talk']).isdisjoint(genreList): 55 | genreList.insert(0, "Talk show") 56 | if not set(['Children']).isdisjoint(genreList): 57 | genreList.insert(0, "Children's / Youth programs") 58 | if not set(['Animated']).isdisjoint(genreList): 59 | genreList.insert(0, "Cartoons / Puppets") 60 | if not set(['Music']).isdisjoint(genreList): 61 | genreList.insert(0, "Music / Ballet / Dance") 62 | 63 | return genreList 64 | 65 | if userSelectedGenre == '2': #User selected 'FULL' epg 66 | 67 | for g in EPgenre: 68 | genreList.append(g) 69 | 70 | #make each element lowercase, romve all spaces and any 's' at the end 71 | genreList = list(map(lambda x: x.lower().replace(" ", ""), genreList)) 72 | if (len(genreList) > 0 and genreList[0] != ''): 73 | genreList = list(map(lambda x: x[0:-1] if x and x[-1] == 's' else x, genreList)) 74 | desc = f'{edict["epdesc"]} {edict["eptitle"]} {edict["epshow"]} {edict["epdesc"]}' 75 | desc = desc.lower() 76 | 77 | #Movies 78 | # TVHeadend Docs: https://github.com/tvheadend/tvheadend/blob/master/src/epg.c#L1775 line 1775 79 | # Kodi Docs: https://github.com/xbmc/xbmc/blob/cda8e8c37190881fab4ea972d0d17cb54d5618d8/xbmc/addons/kodi-dev-kit/include/kodi/c-api/addon-instance/pvr/pvr_epg.h#L63 line 63 80 | # Look in the strings.po for the language selected to determine the text that will be displayed inside KODi for each code 81 | if not set(['movie']).isdisjoint(genreList): 82 | if not set(['adultsonly','erotic','gay/lesbian','lgbtq']).isdisjoint(genreList): 83 | updatedgenreList.append(["Adult movie","0x18"][useHex]) #Adult movie 0x18 84 | genreCount.append("Adult movie") 85 | elif not set(['detective','thriller','crime','crimedrama','mystery']).isdisjoint(genreList): 86 | updatedgenreList.append(["Detective/Thriller","0x11"][useHex]) #Detectivc/Thriller 0x11 87 | genreCount.append("Detective/Thriller") 88 | elif not set(['sciencefiction','fantasy','horror','paranormal']).isdisjoint(genreList): 89 | updatedgenreList.append(["Science fiction/Fantasy/Horror","0x13"][useHex]) #Science Fiction/Fantasy/Horror 0x13 90 | genreCount.append("Science fiction/Fantasy/Horror") 91 | elif not set(['comedy','comedydrama','darkcomedy']).isdisjoint(genreList): 92 | updatedgenreList.append(["Comedy","0x14"][useHex]) #Comedy 0x14 93 | genreCount.append("Comedy") 94 | elif not set(['western','war','military']).isdisjoint(genreList): 95 | updatedgenreList.append(["Adventure/Western/War","0x12"][useHex]) #Adventure/Western/War 0x12 96 | genreCount.append("Adventure/Western/War") 97 | elif not set(['soap','melodrama','folkloric','music','musical','musicalcomedy']).isdisjoint(genreList): 98 | updatedgenreList.append(["Soap/Melodrama/Folkloric","0x15"][useHex]) #Soap/Melodrama/Folkloric 0x15 99 | genreCount.append("Soap/Melodrama/Folkloric") 100 | elif not set(['romance','romanticcomedy']).isdisjoint(genreList): 101 | updatedgenreList.append(["Romance","0x16"][useHex]) #Romance 0x16 102 | genreCount.append("Romance") 103 | elif not set(['serious','classical','religious','historicaldrama','biography','documentary','docudrama']).isdisjoint(genreList): 104 | updatedgenreList.append(["Serious/Classical/Religious/Historical movie/Drama","0x17"][useHex]) #Serious/Classical/Religious/Historical Movie/Drama 0x17 105 | genreCount.append("Serious/Classical/Religious/Historical movie/Drama") 106 | elif not set(['adventure']).isdisjoint(genreList): 107 | updatedgenreList.append(["Adventure/Western/War","0x12"][useHex]) #Adventure/Western/War 0x12 108 | genreCount.append("Adventure/Western/War") 109 | else: 110 | updatedgenreList.append(["Movie / drama","0x10"][useHex]) #Movie/Drana 0x10 111 | genreCount.append("Movie / drama") 112 | 113 | #Adult TV Shows 114 | elif not set(['adultsonly','erotic','Gay/lesbian','LGBTQ']).isdisjoint(genreList): 115 | updatedgenreList.append(["Adult movie","0xF8"][useHex]) #Adult Show 0xF8 116 | genreCount.append("Adult movie") 117 | 118 | #Children Programming 119 | elif not set(['children','youth']).isdisjoint(genreList): 120 | if edict['eprating'] == 'TV-Y': 121 | updatedgenreList.append(["Pre-school children's programs","0x51"][useHex]) #Pre-school Children's Programmes 0x51 122 | genreCount.append("Pre-school children's programs") 123 | elif edict['eprating'] == 'TV-Y7': 124 | updatedgenreList.append(["Entertainment programs for 6 to 14","0x52"][useHex]) #Entertainment Programmes for 6 to 14 0x52 125 | genreCount.append("Entertainment programs for 6 to 14") 126 | elif edict['eprating'] == 'TV-G': 127 | updatedgenreList.append(["Entertainment programs for 10 to 16","0x53"][useHex]) #Entertainment Programmes for 10 to 16 0x53 128 | genreCount.append("Entertainment programs for 10 to 16") 129 | elif not set(['informational','educational','science','technology']).isdisjoint(genreList): 130 | updatedgenreList.append(["Informational/Educational/School programs","0x54"][useHex]) #Informational/Educational/School Programme 0x54 131 | genreCount.append("Informational/Educational/School programs") 132 | elif not set(['anime','animated']).isdisjoint(genreList): 133 | updatedgenreList.append(["Cartoons/Puppets","0x55"][useHex]) #Cartoons/Puppets 0x55 134 | genreCount.append("Cartoons/Puppets") 135 | else: 136 | updatedgenreList.append(["Children's / Youth programs","0x50"][useHex]) #Children's/Youth Programs 0x50 137 | genreCount.append("Children's / Youth programs") 138 | 139 | #MLeisure/Hobbies 140 | elif not set(['advertisement','archery','auto','bodybuilding','consumer','cooking','exercise','fishing','fitness', 141 | 'fitness&health','gardening','handicraft','health','hobby','homeimprovement','house/garden','how-to','hunting', 142 | 'motoring','outdoor','selfimprovement','shopping','tourism','travel']).isdisjoint(genreList): 143 | 144 | if not set(['tourism','travel']).isdisjoint(genreList): 145 | updatedgenreList.append(["Tourism / Travel","0xA1"][useHex]) #Tourism/Travel 0xA1 146 | genreCount.append("Tourism / Travel") 147 | elif not set(['handicraft','homeimprovement','house/garden','how-to']).isdisjoint(genreList): 148 | updatedgenreList.append(["Handicraft","0xA2"][useHex]) #Handicraft 0xA2 149 | genreCount.append("Handicraft") 150 | elif not set(['motoring','auto']).isdisjoint(genreList): 151 | updatedgenreList.append(["Motoring","0xA3"][useHex]) #Motoring 0xA3 152 | genreCount.append("Motoring") 153 | elif not set(['fitnes','health','fitness&health','selfimprovement','bodybuilding','exercise']).isdisjoint(genreList): 154 | updatedgenreList.append(["Fitness and health","0xA4"][useHex]) #Fitness & Health 0xA4 155 | genreCount.append("Fitness and health") 156 | elif not set(['cooking']).isdisjoint(genreList): 157 | updatedgenreList.append(["Cooking","0xA5"][useHex]) #Cooking 0xA5 158 | genreCount.append("Cooking") 159 | elif not set(['advertisement','shopping','consumer']).isdisjoint(genreList): 160 | updatedgenreList.append(["Advertisement / Shopping","0xA6"][useHex]) #Advertisement/Shopping 0xA6 161 | genreCount.append("Advertisement / Shopping") 162 | elif not set(['gardening']).isdisjoint(genreList): 163 | updatedgenreList.append(["Gardening","0xA7"][useHex]) #Gardening 0xA7 164 | genreCount.append("Gardening") 165 | else: 166 | updatedgenreList.append(["Leisure hobbies","0xA0"][useHex]) #Leisure/Hobbies 0xA0 167 | genreCount.append("Leisure hobbies") 168 | 169 | #News 170 | elif not set(['currentaffair','documentary','interview','news','newsmagazine']).isdisjoint(genreList): 171 | 172 | if not set(['weather']).isdisjoint(genreList): 173 | updatedgenreList.append(["News/Weather report","0x21"][useHex]) #News/Weather Report 0x21 174 | genreCount.append("News/Weather report") 175 | elif not set(['newsmagazine']).isdisjoint(genreList): 176 | updatedgenreList.append(["News magazine","0x22"][useHex]) #News Magazine 0x22 177 | genreCount.append("News magazine") 178 | elif not set(['documentary']).isdisjoint(genreList): 179 | updatedgenreList.append(["Documentary","0x23"][useHex]) #Documentary 0x23 180 | genreCount.append("Documentary") 181 | elif not set(['discussion','interview','debate']).isdisjoint(genreList): 182 | updatedgenreList.append(["Discussion/Interview/Debate","0x24"][useHex]) #Discussion/Interview/Debate 0x24 183 | genreCount.append("Discussion/Interview/Debate") 184 | else: 185 | updatedgenreList.append(["News/Current Affairs","0x20"][useHex]) #News/Current Affair 0x20 186 | genreCount.append("News/Current Affairs") 187 | 188 | #Sports 189 | elif not set(['actionsport','australianrulesfootball','autoracing','baseball','basketball','beachvolleyball','billiard','bmxracing', 190 | 'boatracing','bobsled','bowling','boxing','bullriding','cheerleading','cricket','cycling','diving','dragracing','equestrian', 191 | 'esport','fencing','fieldhockey','figureskating','fishing','football','footvolley','golf','gymnastic','hockey','horse','horseracing', 192 | 'karate','lacrosse','martialart','mixedmartialart','motorcycle','motorcycleracing','motorsport','multisportevent','olympic', 193 | 'paralympic','pickleball','prowrestling','racing','rodeo','rugby','rugbyleague','running','sailing','skating','skiing', 194 | 'snowboarding','soccer','softball','squash','superbowl','surfing','swimming','tabletennis','tennis','track/field','volleyball', 195 | 'waterpolo','watersport','weightlifting','wintersport','worldcup','wrestling']).isdisjoint(genreList): 196 | if not set(['documentary','sportstalk']).isdisjoint(genreList): 197 | updatedgenreList.append(["Sports magazines","0x42"][useHex]) #Sports magazines 0x42 198 | genreCount.append("Sports magazines") 199 | elif not set(['final','superbowl','worldcup','olympic','paralympic']).isdisjoint(genreList): 200 | updatedgenreList.append(["Special events (Olympic Games, World Cup, etc.)","0x41"][useHex]) #Special events (Olympic Games, World Cup, etc.) 0x41 201 | genreCount.append("Special events (Olympic Games, World Cup, etc.") 202 | elif not set(['football','soccer','australianrulesfootball']).isdisjoint(genreList): 203 | updatedgenreList.append(["Football/Soccer","0x43"][useHex]) #Football/Soccer 0x43 204 | genreCount.append("Football/Soccer") 205 | elif not set(['tabletennis','tennis','squash']).isdisjoint(genreList): 206 | updatedgenreList.append(["Tennis/Squash","0x44"][useHex]) #Tennis/Squash 0x44 207 | genreCount.append("Tennis/Squash") 208 | elif not set(['basketball','hockey','baseball','softball','gymnastics','volleyball','track/field','fieldhockey', 209 | 'lacrosse','rugby','cricket','fieldhockey']).isdisjoint(genreList): 210 | updatedgenreList.append(["Team sports (excluding football)","0x45"][useHex]) #Team sports (excluding football) 0x45 211 | genreCount.append("Team sports (excluding football)") 212 | elif not set(['running','snowboarding','wrestling','cycling']).isdisjoint(genreList): 213 | updatedgenreList.append(["Athletics","0x46"][useHex]) #Athletics 0x46 214 | genreCount.append("Athletics") 215 | elif not set(['autoracing','dragracing','motorcycle','motorcycleracing','motorsport']).isdisjoint(genreList): 216 | updatedgenreList.append(["Motor sport","0x47"][useHex]) #Motor sports 0x47 217 | genreCount.append("Motor sport") 218 | elif not set(['bmxracing','boatracing','diving','fishing','sailing','surfing','swimming','waterpolo','watersport']).isdisjoint(genreList): 219 | updatedgenreList.append(["Water sport","0x48"][useHex]) #Water sport 0x48 220 | genreCount.append("Water sport") 221 | elif not set(['wintersport','skiing','bobsled','figureskating','skating','snowboarding']).isdisjoint(genreList): 222 | updatedgenreList.append(["Winter sports","0x49"][useHex]) #Winter sports 0x49 223 | genreCount.append("Winter sports") 224 | elif not set(['horse','equestrian','horseracing','rodeo','bullriding']).isdisjoint(genreList): 225 | updatedgenreList.append(["Equestrian","0x4A"][useHex]) #Equestrian 0x4A 226 | genreCount.append("Equestrian") 227 | elif not set(['martialart','mixedmartialart','karate']).isdisjoint(genreList): 228 | updatedgenreList.append(["Martial sports","0x4B"][useHex]) #Martial sports 0x4B 229 | genreCount.append("Martial sports") 230 | else: 231 | updatedgenreList.append(["Sports","0x40"][useHex]) #Sports 0x40 232 | genreCount.append("Sports") 233 | 234 | #Show 235 | elif not set(['competition','competitionreality','contest','gameshow','quiz','reality','talk','talkshow','variety', 236 | 'varietyshow']).isdisjoint(genreList): 237 | if not set(['gameshow','quiz','contest']).isdisjoint(genreList): 238 | updatedgenreList.append(["Game show/Quiz/Contest","0x31"][useHex]) #Game show/Quiz/Contest 0x31 239 | genreCount.append("Game show/Quiz/Contest") 240 | elif not set(['variety','varietyshow','competition','competitionreality','reality']).isdisjoint(genreList): 241 | updatedgenreList.append(["Variety show","0x32"][useHex]) #Variety Show 0x32 242 | genreCount.append("Variety show") 243 | elif not set(['talk','talkshow']).isdisjoint(genreList): 244 | updatedgenreList.append(["Talk show","0x33"][useHex]) #Talk Show 0x33 245 | genreCount.append("Talk show") 246 | else: 247 | updatedgenreList.append(["Show / Game show","0x30"][useHex]) #Show/Game Show 0x30 248 | genreCount.append("Show / Game show") 249 | 250 | #Music/Ballet/Dance 251 | elif not set(['ballet','classicalmusic','dance','folk','jazz','music','musical','opera','pop','rock','traditionalmusic']).isdisjoint(genreList): 252 | if not set(['rock','pop']).isdisjoint(genreList): 253 | updatedgenreList.append(["Rock/Pop","0x61"][useHex]) #Rock/Pop 0x61 254 | genreCount.append("Rock/Pop") 255 | elif not set(['serious','classicalmusic']).isdisjoint(genreList): 256 | updatedgenreList.append(["Serious music/Classical music","0x62"][useHex]) #Seriouis/Classical Music 0x62 257 | genreCount.append("Serious music/Classical music") 258 | elif not set(['folk','traditionalmusic']).isdisjoint(genreList): 259 | updatedgenreList.append(["Folk/Traditional music","0x63"][useHex]) #Folk/Traditional Music 0x63 260 | genreCount.append("Folk/Traditional music") 261 | elif not set(['jazz']).isdisjoint(genreList): 262 | updatedgenreList.append(["Jazz","0x64"][useHex]) #Jazz 0x64 263 | genreCount.append("Jazz") 264 | elif not set(['musical','opera']).isdisjoint(genreList): 265 | updatedgenreList.append(["Musical/Opera","0x65"][useHex]) #Musical/Opera 0x65 266 | genreCount.append("Musical/Opera") 267 | elif not set(['ballet']).isdisjoint(genreList): 268 | updatedgenreList.append(["Ballet","0x66"][useHex]) #Ballet 0x66 269 | genreCount.append("Ballet") 270 | else: 271 | updatedgenreList.append(["Music / Ballet / Dance","0x60"][useHex]) #Music/Ballet/Dance 0x60 272 | genreCount.append("Music / Ballet / Dance") 273 | 274 | #Arts/Culture 275 | elif not set(['art','arts/craft','artsmagazine','broadcasting','cinema','culture','culturemagazine','experimentalfilm','fashion','film', 276 | 'fineart','literature','newmedia','performingart','popularculture','pres','religion','religious','traditionalart','video']).isdisjoint(genreList): 277 | 278 | if not set(['performingart']).isdisjoint(genreList): 279 | updatedgenreList.append(["Performing arts","0x71"][useHex]) #Performing Arts 0x71 280 | genreCount.append("Performing arts") 281 | elif not set(['fineart']).isdisjoint(genreList): 282 | updatedgenreList.append(["Fine arts","0x72"][useHex]) #Fine Arts 0x72 283 | genreCount.append("Fine arts") 284 | elif not set(['religion','religious']).isdisjoint(genreList): 285 | updatedgenreList.append(["Religion","0x73"][useHex]) #Religion 0x73 286 | genreCount.append("Religion") 287 | elif not set(['popculture','traditionalart']).isdisjoint(genreList): 288 | updatedgenreList.append(["Popular culture/Traditional arts","0x74"][useHex]) #Pop Culture/Traditional Arts 0x74 289 | genreCount.append("Popular culture/Traditional arts") 290 | elif not set(['literature']).isdisjoint(genreList): 291 | updatedgenreList.append(["Literature","0x75"][useHex]) #Literature 0x75 292 | genreCount.append("Literature") 293 | elif not set(['film','cinema']).isdisjoint(genreList): 294 | updatedgenreList.append(["Film/Cinema","0x76"][useHex]) #Film/Cinema 0x76 295 | genreCount.append("Film/Cinema") 296 | elif not set(['experimentalfilm','video']).isdisjoint(genreList): 297 | updatedgenreList.append(["Experimental film/Video","0x77"][useHex]) #Experimental Film/Video 0x77 298 | genreCount.append("Experimental film/Video") 299 | elif not set(['broadcasting','pres']).isdisjoint(genreList): 300 | updatedgenreList.append(["Broadcasting/Press","0x78"][useHex]) #Broadcasting/Press 0x78 301 | genreCount.append("Broadcasting/Press") 302 | elif not set(['newmedia']).isdisjoint(genreList): 303 | updatedgenreList.append(["New media","0x79"][useHex]) #New Media 0x79 304 | genreCount.append("New media") 305 | elif not set(['artmagazine','culturemagazine','magazine']).isdisjoint(genreList): 306 | updatedgenreList.append(["Arts magazines/Culture magazines","0x7A"][useHex]) #Arts/Culture Magazine 0x7A 307 | genreCount.append("Arts magazines/Culture magazines") 308 | elif not set(['fashion']).isdisjoint(genreList): 309 | updatedgenreList.append(["Fashion","0x7B"][useHex]) #Fashion 0x7B 310 | genreCount.append("Fashion") 311 | else: 312 | updatedgenreList.append(["Arts / Culture (without music)","0x70"][useHex]) #Arts/Culture 0x70 313 | genreCount.append("Arts / Culture (without music)") 314 | 315 | #Social/Politics/Economics 316 | elif not set(['community','documentary','economic','magazine','politic','political','publicaffair', 317 | 'remarkablepeople','report','social','socialadvisory']).isdisjoint(genreList): 318 | 319 | if not set(['magazine','report','documentary']).isdisjoint(genreList): 320 | updatedgenreList.append(["Magazines/Reports/Documentary","0x81"][useHex]) #Magazines/Reports/Documentary 0x81 321 | genreCount.append("Magazines/Reports/Documentary") 322 | elif not set(['economic','socialadvisory']).isdisjoint(genreList): 323 | updatedgenreList.append(["Economics/Social advisory","0x82"][useHex]) #Economics/Social Advisory 0x82 324 | genreCount.append("Economics/Social advisory") 325 | elif not set(['remarkablepeople']).isdisjoint(genreList): 326 | updatedgenreList.append(["Remarkable people","0x83"][useHex]) #Remarkable People 0x83 327 | genreCount.append("Remarkable people") 328 | else: 329 | updatedgenreList.append(["Social/Political issues/Economics","0x80"][useHex]) #Social/Political/Economics 0x80 330 | genreCount.append("Social/Political issues/Economics") 331 | 332 | #MEducational/Science 333 | elif not set(['adulteducation','animal','dogshow','education','educational','environment','expedition','factual','foreigncountrie', 334 | 'furthereducation','health','language','medical','medicine','naturalscience','nature','outdoor','physiology','psychology', 335 | 'science','social','spiritualscience','technology']).isdisjoint(genreList): 336 | 337 | if not set(['nature','animal','environment','outdoor','dogshow']).isdisjoint(genreList): 338 | updatedgenreList.append(["Nature/Animals/Environment","0x91"][useHex]) #Nature/Animals/Environment 0x91 339 | genreCount.append("Nature/Animals/Environment") 340 | elif not set(['technology','naturalscience']).isdisjoint(genreList): 341 | updatedgenreList.append(["Technology/Natural sciences","0x92"][useHex]) #Technology/Natural Sciences 0x92 342 | genreCount.append("Technology/Natural sciences") 343 | elif not set(['medicine','physiology','psychology','health','medical']).isdisjoint(genreList): 344 | updatedgenreList.append(["Medicine/Physiology/Psychology","0x93"][useHex]) #Medicine/Physiology/Psychology 0x93 345 | genreCount.append("Medicine/Physiology/Psychology") 346 | elif not set(['foreigncountrie','expedition']).isdisjoint(genreList): 347 | updatedgenreList.append(["Foreign countries/Expeditions","0x94"][useHex]) #Foreign Countries/Expeditions 0x94 348 | genreCount.append("Foreign countries/Expeditions") 349 | elif not set(['social','spiritualscience']).isdisjoint(genreList): 350 | updatedgenreList.append(["Social/Spiritual sciences","0x95"][useHex]) #Social/Spiritual Sciences 0x95 351 | genreCount.append("Social/Spiritual sciences") 352 | elif not set(['furthereducation','adulteducation']).isdisjoint(genreList): 353 | updatedgenreList.append(["Further education","0x96"][useHex]) #Further Education 0x96 354 | genreCount.append("Further education") 355 | elif not set(['language']).isdisjoint(genreList): 356 | updatedgenreList.append(["Languages","0x97"][useHex]) #Languages 0x97 357 | genreCount.append("Languages") 358 | else: 359 | updatedgenreList.append(["Education / Science / Factual topics","0x90"][useHex]) #Education/Science 0x90 360 | genreCount.append("Education / Science / Factual topics") 361 | 362 | # TVHeadend does not recognize the non-movie genres below. 0xF# are user defined genres per the specification and TVH 363 | # does not use them. Kodi does use these user defined values. I could not figure out a way to pass the hex code to TVH 364 | # instead of the string to be recoginzed correctly. When TVH is modified to accept a hex value for the genre we can then 365 | # use these codes to get correct EPG colored grids. One color for movies with it's separate color and one for TV shows. 366 | 367 | elif not set(['crime','crimedrama','detective','mystery','thriller']).isdisjoint(genreList): 368 | updatedgenreList.append(["Detective/Thriller","0xF1"][useHex]) #Detective/Thriller 0xF1 369 | genreCount.append("Detective/Thriller") 370 | 371 | elif not set(['fantasy','horror','paranormal','sciencefiction']).isdisjoint(genreList): 372 | updatedgenreList.append(["Science fiction/Fantasy/Horror","0xF3"][useHex]) #Science Fiction/Fantasy/Horror 0xF3 373 | genreCount.append("Science fiction/Fantasy/Horror") 374 | 375 | elif not set(['western','war','military']).isdisjoint(genreList): 376 | updatedgenreList.append(["Adventure/Western/War","0xF2"][useHex]) #Adventure/Western/War 0xF2 377 | genreCount.append("Adventure/Western/War") 378 | 379 | elif not set(['comedy','comedydrama','darkcomedy','sitcom']).isdisjoint(genreList): 380 | updatedgenreList.append(["Comedy","0xF4"][useHex]) #Comedy 0xF4 381 | genreCount.append("Comedy") 382 | 383 | elif not set(['folk','folkloric','melodrama','music','musical','musicalcomedy','soap']).isdisjoint(genreList): 384 | updatedgenreList.append(["Soap/Melodrama/Folkloric","0xF5"][useHex]) #Soap/Melodrama/Folkloric 0xF5 385 | genreCount.append("Soap/Melodrama/Folkloric") 386 | 387 | elif not set(['romance','romanticcomedy']).isdisjoint(genreList): 388 | updatedgenreList.append(["Romance","0xF6"][useHex]) #Romance 0xF6 389 | genreCount.append("Romance") 390 | 391 | elif not set(['biography','classical','classicalreligion','docudrama','historical','historicaldrama','religion','serious']).isdisjoint(genreList): 392 | updatedgenreList.append(["Serious/Classical/Religious/Historical movie/Drama","0xF7"][useHex]) #Serious/Classical/Religion/Historical 0xF7 393 | genreCount.append("Serious/Classical/Religious/Historical movie/Drama") 394 | 395 | elif not set(['adventure']).isdisjoint(genreList): 396 | updatedgenreList.append(["Adventure/Western/War","0xF2"][useHex]) #Adventure/Western/War 0xF2 397 | genreCount.append("Adventure/Western/War") 398 | 399 | elif not set(['drama']).isdisjoint(genreList): 400 | updatedgenreList.append(["Movie / Drama","0xF0"][useHex]) #Drama 0xF0 401 | genreCount.append("Movie / Drama") 402 | 403 | return updatedgenreList 404 | 405 | if userSelectedGenre == '3': #User selected 'original' epg tag 406 | for g in EPgenre: 407 | genreList.append(g) 408 | return genreList 409 | -------------------------------------------------------------------------------- /logger.py: -------------------------------------------------------------------------------- 1 | ################################################################################ 2 | # This program is free software: you can redistribute it and/or modify 3 | # it under the terms of the GNU General Public License as published by 4 | # the Free Software Foundation, either version 3 of the License, or 5 | # (at your option) any later version. 6 | # 7 | # This program is distributed in the hope that it will be useful, 8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 | # GNU General Public License for more details. 11 | # 12 | # You should have received a copy of the GNU General Public License 13 | # along with this program. If not, see . 14 | ################################################################################ 15 | 16 | import logging 17 | import os 18 | import shutil 19 | 20 | #create a place holder so earlier function calls will still work before the logger is initialized. 21 | logger = logging.getLogger("zap2epg") 22 | 23 | def createLogger(log): 24 | global logger 25 | # Create a logger object 26 | try: 27 | if logger.hashandlers(): 28 | return logger 29 | except: 30 | name, ext = os.path.splitext(log) 31 | old_file = f'{name}_old{ext}' 32 | if os.path.exists(log): 33 | if os.path.exists(old_file): 34 | os.remove(old_file) 35 | shutil.move(log, old_file) 36 | 37 | logger = logging.getLogger('zap2epg') 38 | logger.setLevel(logging.DEBUG) 39 | 40 | # Create a handler that writes to Kodi's log 41 | handler = logging.FileHandler(log, mode='w') 42 | formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y/%m/%d %H:%M:%S') 43 | handler.setFormatter(formatter) 44 | 45 | # Avoid adding multiple handlers if already configured 46 | if not logger.hasHandlers(): 47 | logger.addHandler(handler) 48 | 49 | logger.info("Logging started for zap2epg") 50 | 51 | return logger 52 | -------------------------------------------------------------------------------- /resources/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/edit4ever/script.module.zap2epg/b3555cb205c1df3c08e871858c9692e7446b8362/resources/icon.png -------------------------------------------------------------------------------- /resources/img/antenna.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/edit4ever/script.module.zap2epg/b3555cb205c1df3c08e871858c9692e7446b8362/resources/img/antenna.png -------------------------------------------------------------------------------- /resources/img/channel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/edit4ever/script.module.zap2epg/b3555cb205c1df3c08e871858c9692e7446b8362/resources/img/channel.png -------------------------------------------------------------------------------- /resources/img/minus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/edit4ever/script.module.zap2epg/b3555cb205c1df3c08e871858c9692e7446b8362/resources/img/minus.png -------------------------------------------------------------------------------- /resources/img/plus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/edit4ever/script.module.zap2epg/b3555cb205c1df3c08e871858c9692e7446b8362/resources/img/plus.png -------------------------------------------------------------------------------- /resources/img/run.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/edit4ever/script.module.zap2epg/b3555cb205c1df3c08e871858c9692e7446b8362/resources/img/run.png -------------------------------------------------------------------------------- /resources/img/screenshot001.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/edit4ever/script.module.zap2epg/b3555cb205c1df3c08e871858c9692e7446b8362/resources/img/screenshot001.png -------------------------------------------------------------------------------- /resources/img/screenshot002.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/edit4ever/script.module.zap2epg/b3555cb205c1df3c08e871858c9692e7446b8362/resources/img/screenshot002.png -------------------------------------------------------------------------------- /resources/img/screenshot003.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/edit4ever/script.module.zap2epg/b3555cb205c1df3c08e871858c9692e7446b8362/resources/img/screenshot003.png -------------------------------------------------------------------------------- /resources/img/screenshot004.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/edit4ever/script.module.zap2epg/b3555cb205c1df3c08e871858c9692e7446b8362/resources/img/screenshot004.png -------------------------------------------------------------------------------- /resources/img/screenshot005.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/edit4ever/script.module.zap2epg/b3555cb205c1df3c08e871858c9692e7446b8362/resources/img/screenshot005.png -------------------------------------------------------------------------------- /resources/img/screenshot006.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/edit4ever/script.module.zap2epg/b3555cb205c1df3c08e871858c9692e7446b8362/resources/img/screenshot006.png -------------------------------------------------------------------------------- /resources/img/settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/edit4ever/script.module.zap2epg/b3555cb205c1df3c08e871858c9692e7446b8362/resources/img/settings.png -------------------------------------------------------------------------------- /resources/img/tv.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/edit4ever/script.module.zap2epg/b3555cb205c1df3c08e871858c9692e7446b8362/resources/img/tv.png -------------------------------------------------------------------------------- /resources/language/resource.language.en_gb/strings.po: -------------------------------------------------------------------------------- 1 | # Kodi Media Center language file 2 | # Addon Name: zap2epg 3 | # Addon id: script.module.zap2epg 4 | # Addon Provider: edit4ever 5 | 6 | msgid "" 7 | msgstr "" 8 | 9 | msgctxt "#32001" 10 | msgid "Location" 11 | msgstr "" 12 | 13 | msgctxt "#32002" 14 | msgid "Zipcode" 15 | msgstr "" 16 | 17 | msgctxt "#32003" 18 | msgid "Lineup" 19 | msgstr "" 20 | 21 | msgctxt "#32004" 22 | msgid "Lineup Code" 23 | msgstr "" 24 | 25 | msgctxt "#32005" 26 | msgid "Station List" 27 | msgstr "" 28 | 29 | msgctxt "#32006" 30 | msgid "Device" 31 | msgstr "" 32 | 33 | # 32007-32009 blank 34 | 35 | msgctxt "#32010" 36 | msgid "Data Handling" 37 | msgstr "" 38 | 39 | msgctxt "#32011" 40 | msgid "Options" 41 | msgstr "" 42 | 43 | msgctxt "#32012" 44 | msgid "Number of Days to Download" 45 | msgstr "" 46 | 47 | msgctxt "#32013" 48 | msgid "Download Extra Details" 49 | msgstr "" 50 | 51 | msgctxt "#32014" 52 | msgid "Append Extra Details to Description" 53 | msgstr "" 54 | 55 | msgctxt "#32015" 56 | msgid "Number of Days to Delete Cache (re-download)" 57 | msgstr "" 58 | 59 | msgctxt "#32016" 60 | msgid "Remove unsafe Windows® characters from Show Titles" 61 | msgstr "" 62 | 63 | msgctxt "#32017" 64 | msgid "Remove unsafe Windows® characters from Episode Titles" 65 | msgstr "" 66 | 67 | msgctxt "#32018" 68 | msgid "Replace unsafe characters with: " 69 | msgstr "" 70 | 71 | msgctxt "#32019" 72 | msgid "Default language:" 73 | 74 | msgctxt "#32020" 75 | msgid "Include Episode Thumbnail" 76 | msgstr "" 77 | 78 | msgctxt "#32021" 79 | msgid "None" 80 | msgstr "" 81 | 82 | msgctxt "#32022" 83 | msgid "Series Image" 84 | msgstr "" 85 | 86 | msgctxt "#32023" 87 | msgid "Episode Image" 88 | msgstr "" 89 | 90 | msgctxt "#32024" 91 | msgid "Use Language Identification (requires langid module)" 92 | msgstr "" 93 | 94 | msgctxt "#32025" 95 | msgid "English" 96 | msgstr "" 97 | 98 | msgctxt "#32026" 99 | msgid "Spanish" 100 | msgstr "" 101 | 102 | msgctxt "#32027" 103 | msgid "French" 104 | msgstr "" 105 | 106 | 107 | # 32028 blank 108 | 109 | msgctxt "#32029" 110 | msgid "Use hex values for genre type instead of textual name" 111 | msgstr "" 112 | 113 | msgctxt "#32030" 114 | msgid "Include Episode Genres (colored EPG grid)" 115 | msgstr "" 116 | 117 | msgctxt "#32031" 118 | msgid "None" 119 | msgstr "" 120 | 121 | msgctxt "#32032" 122 | msgid "Simple" 123 | msgstr "" 124 | 125 | msgctxt "#32033" 126 | msgid "Full" 127 | msgstr "" 128 | 129 | msgctxt "#32034" 130 | msgid "Original" 131 | msgstr "" 132 | 133 | # 32035-32039 blank 134 | 135 | msgctxt "#32040" 136 | msgid "Tvheadend" 137 | msgstr "" 138 | 139 | msgctxt "#32041" 140 | msgid "Tvheadend Username" 141 | msgstr "" 142 | 143 | msgctxt "#32042" 144 | msgid "Tvheadend Password" 145 | msgstr "" 146 | 147 | msgctxt "#32043" 148 | msgid "Append Subchannel Number for OTA" 149 | msgstr "" 150 | 151 | msgctxt "#32044" 152 | msgid "Append Tvheadend Service Name" 153 | msgstr "" 154 | 155 | msgctxt "#32045" 156 | msgid "Tvheadend URL" 157 | msgstr "" 158 | 159 | msgctxt "#32046" 160 | msgid "Tvheadend Port" 161 | msgstr "" 162 | 163 | msgctxt "#32047" 164 | msgid "Use DIGEST authentication (more secure - requires TVH server setting change)" 165 | msgstr "" 166 | 167 | # 32048 blank 168 | 169 | msgctxt "#32049" 170 | msgid "Tvheadend Options Enabled" 171 | msgstr "" 172 | 173 | # 32050-32199 blank 174 | 175 | msgctxt "#32200" 176 | msgid "X-Details Order" 177 | msgstr "" 178 | 179 | msgctxt "#32201" 180 | msgid "Extra Details Will Be Appended to Program Description in the Order Set Below" 181 | msgstr "" 182 | 183 | msgctxt "#32202" 184 | msgid "Seperator" 185 | msgstr "" 186 | 187 | msgctxt "#32210" 188 | msgid "1" 189 | msgstr "" 190 | 191 | msgctxt "#32211" 192 | msgid "2" 193 | msgstr "" 194 | 195 | msgctxt "#32212" 196 | msgid "3" 197 | msgstr "" 198 | 199 | msgctxt "#32213" 200 | msgid "4" 201 | msgstr "" 202 | 203 | msgctxt "#32214" 204 | msgid "5" 205 | msgstr "" 206 | 207 | msgctxt "#32215" 208 | msgid "6" 209 | msgstr "" 210 | 211 | msgctxt "#32216" 212 | msgid "7" 213 | msgstr "" 214 | 215 | msgctxt "#32217" 216 | msgid "8" 217 | msgstr "" 218 | 219 | msgctxt "#32218" 220 | msgid "9" 221 | msgstr "" 222 | 223 | msgctxt "#32219" 224 | msgid "10" 225 | msgstr "" 226 | 227 | msgctxt "#32220" 228 | msgid "11" 229 | msgstr "" 230 | 231 | msgctxt "#32221" 232 | msgid "12" 233 | msgstr "" 234 | 235 | msgctxt "#32222" 236 | msgid "13" 237 | msgstr "" 238 | 239 | msgctxt "#32223" 240 | msgid "14" 241 | msgstr "" 242 | 243 | msgctxt "#32224" 244 | msgid "15" 245 | msgstr "" 246 | 247 | msgctxt "#32225" 248 | msgid "16" 249 | msgstr "" 250 | 251 | msgctxt "#32226" 252 | msgid "17" 253 | msgstr "" 254 | 255 | msgctxt "#32227" 256 | msgid "18" 257 | msgstr "" 258 | 259 | msgctxt "#32228" 260 | msgid "19" 261 | msgstr "" 262 | 263 | msgctxt "#32229" 264 | msgid "20" 265 | msgstr "" 266 | 267 | msgctxt "#32230" 268 | msgid "21" 269 | msgstr "" 270 | 271 | msgctxt "#32231" 272 | msgid "22" 273 | msgstr "" 274 | 275 | # 32232-32299 blank 276 | 277 | msgctxt "#32300" 278 | msgid "None" 279 | msgstr "" 280 | 281 | msgctxt "#32301" 282 | msgid "BULLET" 283 | msgstr "" 284 | 285 | msgctxt "#32302" 286 | msgid "HYPHEN" 287 | msgstr "" 288 | 289 | msgctxt "#32303" 290 | msgid "Plot Description" 291 | msgstr "" 292 | 293 | msgctxt "#32304" 294 | msgid "New/Live/Premiere Indicator" 295 | msgstr "" 296 | 297 | msgctxt "#32305" 298 | msgid "HD Indicator" 299 | msgstr "" 300 | 301 | msgctxt "#32306" 302 | msgid "STEREO/CC/DVS Indicator" 303 | msgstr "" 304 | 305 | msgctxt "#32307" 306 | msgid "Season/Episode Number" 307 | msgstr "" 308 | 309 | msgctxt "#32308" 310 | msgid "TV Rating" 311 | msgstr "" 312 | 313 | msgctxt "#32309" 314 | msgid "Original Air Date" 315 | msgstr "" 316 | 317 | msgctxt "#32310" 318 | msgid "Program Title" 319 | msgstr "" 320 | 321 | msgctxt "#32311" 322 | msgid "Episode Title" 323 | msgstr "" 324 | 325 | msgctxt "#32312" 326 | msgid "Episode Title in Quotes" 327 | msgstr "" 328 | 329 | msgctxt "#32313" 330 | msgid "Cast" 331 | msgstr "" 332 | 333 | msgctxt "#32314" 334 | msgid "Movie Release Year" 335 | msgstr "" 336 | 337 | msgctxt "#32315" 338 | msgid "Genres" 339 | msgstr "" 340 | 341 | msgctxt "#32316" 342 | msgid "Determined Language" 343 | msgstr "" 344 | 345 | msgctxt "#32320" 346 | msgid "LINE BREAK" 347 | msgstr "" 348 | 349 | msgctxt "#32321" 350 | msgid "SPACE" 351 | msgstr "" 352 | 353 | msgctxt "#32322" 354 | msgid "COLON" 355 | msgstr "" 356 | 357 | msgctxt "#32323" 358 | msgid "VERTICAL BAR" 359 | msgstr "" 360 | 361 | msgctxt "#32324" 362 | msgid "SLASH" 363 | msgstr "" 364 | 365 | msgctxt "#32325" 366 | msgid "COMMA" 367 | msgstr "" 368 | -------------------------------------------------------------------------------- /resources/settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 1 3 | 1 4 | true 5 | true 6 | 1 7 | 2 8 | false 9 | false 10 | false 11 | _ 12 | 0 13 | true 14 | 10 15 | 1 16 | 16 17 | 1 18 | 17 19 | 13 20 | 15 21 | 2 22 | 11 23 | 1 24 | 12 25 | 1 26 | 22 27 | 1 28 | 21 29 | 14 30 | 2 31 | 9 32 | 2 33 | 20 34 | 8 35 | 19 36 | true 37 | 127.0.0.1 38 | 9981 39 | 40 | 41 | false 42 | true 43 | true 44 | 92101 45 | Local Over the Air Broadcast 46 | lineupId 47 | - 48 | 49 | 50 | -------------------------------------------------------------------------------- /tvh.py: -------------------------------------------------------------------------------- 1 | # TVH is a connection and grabber tool for TVH servers 2 | ################################################################################ 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program. If not, see . 15 | ################################################################################ 16 | 17 | import urllib.request 18 | from urllib.request import HTTPDigestAuthHandler, build_opener 19 | from urllib.error import URLError, HTTPError 20 | import base64 21 | from logger import logger 22 | import json 23 | 24 | isConnectedtoTVH = False 25 | hostname = '' 26 | port = '' 27 | username = '' 28 | password = '' 29 | useDigest = False 30 | 31 | 32 | def tvh_connect(ipaddress, portNumber, usern, passw, userDigest=False, tvh=None ): 33 | 34 | #save the connection info to the global variables 35 | global hostname, port, username, password, useDigest, isConnectedtoTVH 36 | hostname = ipaddress 37 | port = portNumber 38 | username = usern 39 | password = passw 40 | useDigest = userDigest 41 | 42 | #make an initial attempt to connect to the server wiht line 49 43 | def check_connection(): 44 | response = tvh_getData('connection') 45 | if response is not None: 46 | return response 47 | else: 48 | return None 49 | 50 | response = check_connection() 51 | 52 | #read the response and respond 53 | if response is not None: 54 | isConnectedtoTVH = True 55 | logger.info("Connected to TVH server") 56 | return True 57 | else: 58 | isConnectedtoTVH = False 59 | logger.info('Nothing returned!') 60 | return False 61 | 62 | def tvh_getData(string): 63 | global isConnectedtoTVH 64 | def digest(url): #newer encryption style 65 | #header = [ ("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:115.0) Gecko/20100101 Firefox/115.0"), 66 | # ("Accept", "application/json"), 67 | # ("Accept-Language", "en-US,en;q=0.9") ] 68 | headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:115.0) Gecko/20100101 Firefox/115.0", 69 | "Accept": "application/json", 70 | "Accept-Language": "en-US,en;q=0.9"} 71 | 72 | password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm() 73 | password_mgr.add_password(None, url, username, password) 74 | digest_auth_handler = HTTPDigestAuthHandler(password_mgr) 75 | #opener = build_opener(digest_auth_handler) 76 | #opener.addheaders = headers 77 | 78 | opener = urllib.request.build_opener(digest_auth_handler) 79 | request = urllib.request.Request(url, headers=headers) 80 | 81 | 82 | try: 83 | with opener.open(request, timeout=10) as response: 84 | raw = response.read().decode('utf-8') 85 | return json.loads(raw) 86 | except HTTPError as e: 87 | logger.info(f'Error: HTTP Error {e.code}: {e.reason}') 88 | if (e.reason == 401 or e.reason == 403): 89 | #dialog.ok("Tvheadend Access Error!",f"{e.reasone}: {url}\nAuthorization Denied\n\nPlease check your username/password in settings.") 90 | return None 91 | except URLError as e: 92 | logger.info(f'Error: URL Error: {e.reason}') 93 | if (e.reason != 200): 94 | #dialog.ok("Tvheadend Access Error!", f"{e.reason}: {url}\nCould not connect to Tvheadend server.\nPlease check your Tvheadend server is running or check the IP and port configuration in the settings.") 95 | return None 96 | except json.JSONDecodeError as e: 97 | logger.info(f'Error: JSON Decode Error: {e.msg}') 98 | return None 99 | except Exception as e: 100 | logger.warning("Exception in digest authentication - %s", e) 101 | 102 | def basicAuth(url): #Older encryption style 103 | credentials = f"{username}:{password}" 104 | userpass_enc = base64.b64encode(credentials.encode('utf-8')).decode('utf-8') 105 | headers_basic = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:115.0) Gecko/20100101 Firefox/115.0", 106 | "Accept": "application/json", 107 | "Accept-Language": "en-US,en;q=0.9", 108 | "Authorization": f"Basic {userpass_enc}"} 109 | 110 | request = urllib.request.Request(url, headers=headers_basic) 111 | 112 | try: 113 | with urllib.request.urlopen(request, timeout=10) as response: 114 | raw = response.read().decode('utf-8') 115 | return json.loads(raw) 116 | except HTTPError as e: 117 | logger.info(f'Error: HTTP Error {e.code}: {e.reason}') 118 | if (e.reason == 401 or e.reason == 403): 119 | #dialog.ok("Tvheadend Access Error!",f"{e.reasone}: {url}\nAuthorization Denied\n\nPlease check your username/password in settings.") 120 | return None 121 | except URLError as e: 122 | logger.info(f'Error: URL Error: {e.reason}') 123 | if (e.reason != 200): 124 | #dialog.ok("Tvheadend Access Error!", f"{e.reason}: {url}\nCould not connect to Tvheadend server.\nPlease check your Tvheadend server is running or check the IP and port configuration in the settings.") 125 | return None 126 | except json.JSONDecodeError as e: 127 | logger.info(f'Error: JSON Decode Error: {e.msg}') 128 | return None 129 | except Exception as e: 130 | logger.warning("Exception in basic authentication - %s", e) 131 | 132 | #Strings used to connect to TVH and pull station listings 133 | if string == 'connection': #this py line 42 134 | isConnectedtoTVH = True 135 | substring = '/api/status/connections' 136 | if string == 'channels': #default.ph line 97 137 | substring = '/api/channel/grid?all=1&limit=999999999&sort=name&filter=[{"type":"boolean","value":true,"field":"enabled"}]' 138 | if string == 'allchannels': 139 | substring = '/api/channel/grid?all=1&limit=999999999&sort=name' 140 | 141 | if isConnectedtoTVH: 142 | url = f'http://{hostname}:{port}{substring}' 143 | if useDigest: 144 | data = digest(url) 145 | else: 146 | data = basicAuth(url) 147 | return data 148 | else: 149 | return None -------------------------------------------------------------------------------- /tvlistings.py: -------------------------------------------------------------------------------- 1 | # TVtvlistings is a connection and grabber tool for gracenote servers 2 | ################################################################################ 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program. If not, see . 15 | ################################################################################ 16 | 17 | import urllib.request, urllib.error, urllib.parse 18 | from urllib.request import HTTPDigestAuthHandler, build_opener 19 | import base64 20 | from logger import logger 21 | import time 22 | 23 | url = "" 24 | opener = "" 25 | isActivated = False 26 | def create_opener(urlsite='https://tvlistings.gracenote.com'): 27 | global isActivated 28 | #Create the headers and other info to connect to the tvlistings.gracenote.com website 29 | headers = [ ("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:115.0) Gecko/20100101 Firefox/115.0"), 30 | ("Accept", "application/json"), 31 | ("Accept-Language", "en-US,en;q=0.9") ] 32 | global url, opener 33 | url = urlsite 34 | opener = urllib.request.build_opener() 35 | opener.addheaders = headers 36 | isActivated = True 37 | 38 | def fetch_url(string, options): 39 | data = None #initialize variable 40 | if string == 'postal': #default.py line 201 41 | substring = f"/gapzap_webapi/api/Providers/getPostalCodeProviders/{options['country']}/{options['zipcodeNew']}/gapzap/en" 42 | if string == 'lineup': #default.py line 113, zap2epg.py line 768 43 | substring = f"/api/grid?aid=orbebb&TMSID=&AffiliateID=lat&FromPage=TV%20Grid&lineupId=×pan=3&headendId={options['lineupcode']}&country={options['country']}&device={options['device']}&postalCode={options['zipcode']}&time={options['gridtime']}&isOverride=true&pref=-&userId=-" 44 | if string == 'programDetails': #zap2epg line 566 45 | substring = '/api/program/overviewDetails' 46 | data = options['data_encode'] 47 | 48 | if not isActivated: 49 | create_opener() 50 | 51 | if isActivated: 52 | try: 53 | combinedURL = url + substring 54 | 55 | if data is not None: 56 | if isinstance(data, str): 57 | data = data.encode('utf-8') # encode string to bytes 58 | with opener.open(combinedURL, data) as response: 59 | return response.read() 60 | else: 61 | with opener.open(combinedURL) as response: 62 | return response.read() 63 | 64 | except urllib.error.HTTPError as e: 65 | logger.warning(f"HTTP Error: {e.code} - {e.reason}") 66 | if e.code == 429: #Too Many Requests 67 | time.sleep(2) 68 | except urllib.error.URLError as e: 69 | logger.warning(f"URL Error: {e.reason}") 70 | except Exception as e: 71 | logger.warning(f"Error Type: {type(e).__name__}: {e}") 72 | 73 | def returnSite(): 74 | global url 75 | return url 76 | -------------------------------------------------------------------------------- /zap2epg.py: -------------------------------------------------------------------------------- 1 | # zap2epg tv schedule grabber for kodi 2 | ################################################################################ 3 | # This program is free software: you can redistribute it and/or modify 4 | # it under the terms of the GNU General Public License as published by 5 | # the Free Software Foundation, either version 3 of the License, or 6 | # (at your option) any later version. 7 | # 8 | # This program is distributed in the hope that it will be useful, 9 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | # GNU General Public License for more details. 12 | # 13 | # You should have received a copy of the GNU General Public License 14 | # along with this program. If not, see . 15 | ################################################################################ 16 | 17 | import urllib.request, urllib.error, urllib.parse 18 | import os 19 | from logger import createLogger, logger 20 | from tvh import tvh_connect, tvh_getData 21 | from genre import genreSort, countGenres 22 | from tvlistings import create_opener, fetch_url, returnSite 23 | import codecs 24 | import time 25 | import datetime 26 | import calendar 27 | import gzip 28 | import re 29 | import json 30 | import xml.etree.ElementTree as ET 31 | from collections import OrderedDict 32 | import html 33 | from collections import Counter 34 | 35 | try: 36 | import langid #Determine if the langid module has been installed and set a flag if it has been. 37 | from langid.langid import LanguageIdentifier, model 38 | LanguageID = LanguageIdentifier.from_modelstring(model, norm_probs=True) 39 | useLangid = True #Used in the parse episodes function 40 | except: 41 | useLangid = False 42 | 43 | def mainRun(userdata): 44 | settingsFile = os.path.join(userdata, 'settings.xml') 45 | settings = ET.parse(settingsFile) 46 | root = settings.getroot() 47 | settingsDict = {} 48 | xdescOrderDict = {} 49 | kodiVersion = root.attrib.get('version') 50 | logger.info('Kodi settings version is: %s', kodiVersion) 51 | for setting in root.findall('setting'): 52 | if kodiVersion == '2': 53 | settingStr = setting.text 54 | else: 55 | settingStr = setting.get('value') 56 | if settingStr == '': 57 | settingStr = None 58 | settingID = setting.get('id') 59 | settingsDict[settingID] = settingStr 60 | 61 | #Setup default values in case the settings XML does not have everything. 62 | stationList = "" 63 | zipcode = "" 64 | lineup="lineup" 65 | device = "" 66 | days = 1 67 | redays = 0 68 | xdetails = False 69 | xdesc = False 70 | epicon = 0 71 | epgenre = 0 72 | tvhoff = False 73 | tvhurl = "127.0.0.1" 74 | tvhport = "9981" 75 | usern = "" 76 | passw = "" 77 | digest = False 78 | chmatch = False 79 | tvhmatch = False 80 | safetitle = False 81 | safeepisode = False 82 | escapeChar = "_" 83 | userLangid = False 84 | useLang = False 85 | useHex = 0 86 | 87 | for setting in settingsDict: 88 | if setting == 'slist': #station list from gracenote website i.e. 100105 89 | stationList = settingsDict[setting] 90 | if setting == 'zipcode': #zipcode 91 | zipcode = settingsDict[setting] 92 | if setting == 'lineup': #Type of lineup to receive from the given zipcode. i.e. cable or OTA 93 | lineup = settingsDict[setting] 94 | if setting == 'lineupcode': #Lineup Code [string default==lineupid] 95 | lineupcode = settingsDict[setting] 96 | if setting == 'device': #Device name to be sent to gracenote website 97 | device = settingsDict[setting] 98 | if setting == 'days': #Number of days to download data (1 to 14) 99 | days = settingsDict[setting] 100 | if setting == 'redays': #Number of Days to Delete Cache (re-download) for TBA listings (1 to 7) 101 | redays = settingsDict[setting] 102 | if setting == 'xdetails': #Add extra details from shows and movie listing 103 | xdetails = settingsDict[setting] 104 | if setting == 'xdesc': #Append Extra Details to Description 105 | xdesc = settingsDict[setting] 106 | if setting == 'epicon': #Include Episode Thumbnail [0: None, 1: Series Image, 2: Episode Image] 107 | epicon = settingsDict[setting] 108 | if setting == 'epgenre': #Include Episode Genres (colored EPG grid) [0: None, 1: Simple, 2: Full, 3: Original] 109 | epgenre = settingsDict[setting] 110 | if setting == 'tvhoff': #Tvheadend Options Enabled [True, False] 111 | tvhoff = settingsDict[setting] 112 | if setting == 'tvhurl': #TV Headend URL [http://] 113 | tvhurl = settingsDict[setting] 114 | if setting == 'tvhport': #TV Headend Port [9981] 115 | tvhport = settingsDict[setting] 116 | if setting == 'usern': #TV Headend Username (string) 117 | usern = settingsDict[setting] 118 | if setting == 'passw': #TV Headend password (string) 119 | passw = settingsDict[setting] 120 | if setting == 'digest': #TV Headend digest authentication or plain text for TVH (string) 121 | digest = True if settingsDict[setting] == 'true' else False 122 | if setting == 'chmatch': #Append Subchannel Number for OTA" [True, False] 123 | chmatch = settingsDict[setting] 124 | if setting == 'tvhmatch': #Append Tvheadend Service Name [True, False] 125 | tvhmatch = settingsDict[setting] 126 | if setting == 'safetitle': #Remove unsafe Windows characters from Show Titles [True, False] 127 | safetitle = settingsDict[setting] 128 | if setting == 'safeepisode': #Remove unsafe Windows characters from Episode Titles [True, False] 129 | safeepisode = settingsDict[setting] 130 | if setting == 'escapechar': #Replace unsafe characters with: [string] 131 | escapeChar = settingsDict[setting] 132 | if escapeChar is None: escapeChar = '_' 133 | if setting == 'langid': #Use module LangID to identify language based on the description field [True, False] 134 | userLangid = settingsDict[setting] 135 | userLangid = {'0': 'en', '1': 'es', '2': 'fr'}.get(userLangid) 136 | if userLangid is None: userLangid = 'en' 137 | if setting == 'useLang': #Language to use if LangID is not used or can't determine language [em, es, fr, de, etc...] 138 | useLang = settingsDict[setting] 139 | if setting == 'useHex': #0: Returns a string respresentation of the genre text 1: Returns a hex value for the genre 140 | useHex = 1 if settingsDict[setting] == 'true' else 0 141 | if setting.startswith('desc'): #The array of options for extra details desc01 thru desc20 142 | xdescOrderDict[setting] = (settingsDict[setting]) 143 | xdescOrder = [value for (key, value) in sorted(xdescOrderDict.items())] 144 | if lineupcode != 'lineupId': 145 | chmatch = 'false' 146 | tvhmatch = 'false' 147 | if zipcode.isdigit(): 148 | country = 'USA' 149 | else: 150 | country = 'CAN' 151 | logger.info('Running zap2epg-2.2.1 for zipcode: %s and lineup: %s', zipcode, lineup) 152 | logger.info(f'langid installed: {useLangid}') 153 | pythonStartTime = time.time() 154 | cacheDir = os.path.join(userdata, 'cache') 155 | dayHours = int(days) * 8 # set back to 8 when done testing 156 | gridtimeStart = (int(time.mktime(time.strptime(str(datetime.datetime.now().replace(microsecond=0,second=0,minute=0)), '%Y-%m-%d %H:%M:%S')))) 157 | schedule = {} 158 | tvhMatchDict = {} 159 | 160 | def getLang(desc: str, show: str, title: str) -> str: 161 | text = "" 162 | if desc is not None: #Concatenate show, title and description into one string to send to the langudage detection module 163 | text = text + " " + desc 164 | if show is not None: 165 | text = text + " " + show 166 | if title is not None: 167 | text = text + " " + title 168 | try: 169 | if useLangid and useLang and text is not None: #Is the language module installed and did the user want to use it 170 | result = LanguageID.classify(text) 171 | if result[0] in (['en', 'es', 'fr']) and result[1] > .998: #USA and Canada only broadcast in English, Spanish and French 172 | return result[0] 173 | else: 174 | return userLangid #If the language module returns a random language, return the default language 175 | else: 176 | return userLangid # should be the default selected by the user 177 | except: 178 | return userLangid #If there is an error, return the default language 179 | 180 | def tvhMatchGet(): #Routine will match the EPG station name to TVH station name or channel number 181 | if isConnectedtoTVH == True: 182 | response = tvh_getData('channels') #returns a json file 183 | if response is not None: 184 | logger.info(f'Accessing Tvheadend channel list from: {tvhurl}') 185 | try: 186 | channels = response 187 | for ch in channels['entries']: 188 | channelName = ch['name'] 189 | channelNum = ch['number'] 190 | tvhMatchDict[channelNum] = channelName 191 | logger.info(f'{str(len(tvhMatchDict))} Tvheadend channels found.') 192 | except: 193 | logger.exception('Exception: tvhMatch - %s', f'Error parsing JSON response') 194 | else: 195 | logger.exception('Exception: tvhMatch - %s', f'tvh returned no channels') 196 | pass 197 | 198 | def deleteOldCache(gridtimeStart): 199 | logger.info('Checking for old cache files...') 200 | try: 201 | if os.path.exists(cacheDir): 202 | entries = os.listdir(cacheDir) 203 | for entry in entries: 204 | oldfile = entry.split('.')[0] 205 | if oldfile.isdigit(): 206 | fn = os.path.join(cacheDir, entry) 207 | if (int(oldfile)) < (gridtimeStart + (int(redays) * 86400)): 208 | try: 209 | os.remove(fn) 210 | logger.info('Deleting old cache: %s', entry) 211 | except OSError as e: 212 | logger.warning('Error Deleting: %s - %s.' % (e.filename, e.strerror)) 213 | except Exception as e: 214 | logger.exception('Exception: deleteOldCache - %s', e.strerror) 215 | 216 | def deleteOldShowCache(showList): 217 | logger.info('Checking for old show cache files...') 218 | try: 219 | if os.path.exists(cacheDir): 220 | entries = os.listdir(cacheDir) 221 | for entry in entries: 222 | oldfile = entry.split('.')[0] 223 | if not oldfile.isdigit(): 224 | fn = os.path.join(cacheDir, entry) 225 | if oldfile not in showList: 226 | try: 227 | os.remove(fn) 228 | logger.info('Deleting old show cache: %s', entry) 229 | except OSError as e: 230 | logger.warning('Error Deleting: %s - %s.' % (e.filename, e.strerror)) 231 | except Exception as e: 232 | logger.exception('Exception: deleteOldshowCache - %s', e.strerror) 233 | 234 | def convTime(t): 235 | return time.strftime("%Y%m%d%H%M%S",time.localtime(int(t))) 236 | 237 | def savepage(fn, data): 238 | if not os.path.exists(cacheDir): 239 | os.mkdir(cacheDir) 240 | fileDir = os.path.join(cacheDir, fn) 241 | with gzip.open(fileDir,"wb+") as f: 242 | f.write(data) 243 | f.close() 244 | 245 | def printHeader(fh, enc): #This is the header for the XMLTV file 246 | logger.info('Creating xmltv.xml file...') 247 | fh.write(f'\n') 248 | #fh.write("\n\n") 249 | fh.write(f'\n') 250 | 251 | def printFooter(fh): #This is the footer for the XMLTV file 252 | fh.write("") 253 | 254 | def printStations(fh): #Take the data collected in edict variable and parse it, to writhe the XMLTV file 255 | global stationCount 256 | stationCount = 0 257 | try: 258 | logger.info('Writing Stations to xmltv.xml file...') 259 | try: 260 | scheduleSort = OrderedDict(sorted(iter(schedule.items()), key=lambda x: x[1]['chnum'])) 261 | except: 262 | scheduleSort = OrderedDict(sorted(iter(schedule.items()), key=lambda x: x[1]['chfcc'])) 263 | for station in scheduleSort: 264 | fh.write(f'\t\n') 265 | if 'chtvh' in scheduleSort[station] and scheduleSort[station]['chtvh'] is not None: 266 | xchtvh = html.escape(scheduleSort[station]['chtvh'], quote=True) 267 | fh.write(f'\t\t{xchtvh}\n') 268 | if 'chnum' in scheduleSort[station] and 'chfcc' in scheduleSort[station]: 269 | xchnum = scheduleSort[station]['chnum'] 270 | xchfcc = scheduleSort[station]['chfcc'] 271 | xchfcc = html.escape(xchfcc, quote=True) 272 | fh.write(f'\t\t{xchnum} {xchfcc}\n') 273 | fh.write(f'\t\t{xchfcc}\n') 274 | fh.write(f'\t\t{xchnum}\n') 275 | elif 'chfcc' in scheduleSort[station]: 276 | xchnum = scheduleSort[station]['chfcc'] 277 | xcfcc = html.escape(xcfcc, quote=True) 278 | fh.write(f'\t\t{xcfcc}\n') 279 | elif 'chnum' in scheduleSort[station]: 280 | xchnum = scheduleSort[station]['chnum'] 281 | fh.write(f'\t\t{xchnum}\n') 282 | if 'chicon' in scheduleSort[station]: 283 | fh.write(f'\t\t\n') 284 | fh.write("\t\n") 285 | stationCount += 1 286 | except Exception as e: 287 | logger.exception('Exception: printStations') 288 | 289 | def printEpisodes(fh): #Take the data collected in edict variable and parse it, to write the XMLTV file 290 | global episodeCount 291 | episodeCount = 0 292 | try: 293 | logger.info('Writing Episodes to xmltv.xml file...') 294 | if xdesc is True: 295 | logger.info('Appending Xdetails to description for xmltv.xml file...') 296 | for station in schedule: 297 | sdict = schedule[station] 298 | for episode in sdict: 299 | if not episode.startswith("ch"): 300 | try: 301 | edict = sdict[episode] 302 | if 'epstart' in edict: 303 | lang = getLang(edict['epdesc'], edict['epshow'], edict['eptitle']) 304 | edict['lang'] = lang 305 | startTime = convTime(edict['epstart']) 306 | is_dst = time.daylight and time.localtime().tm_isdst > 0 307 | TZoffset = "%.2d%.2d" %(- (time.altzone if is_dst else time.timezone)/3600, 0) 308 | stopTime = convTime(edict['epend']) 309 | fh.write(f'\t\n') 310 | dd_progid = edict['epid'] 311 | fh.write(f'\t\t{dd_progid[:-4]}.{dd_progid[-4:]}\n') 312 | if edict['epshow'] is not None: 313 | titleShow = edict['epshow'] 314 | if safetitle == "true": 315 | titleShow = re.sub('[\\/*?:"<>|]', escapeChar, titleShow) 316 | titleShow = html.escape(titleShow, quote=True) 317 | titleShow = f'\t\t{titleShow}\n' 318 | fh.write(titleShow) 319 | if edict['eptitle'] is not None: 320 | titleEpisode = edict['eptitle'] 321 | if safeepisode == "true": 322 | titleEpisode = re.sub('[\\/*?:"<>|]', escapeChar, titleEpisode) 323 | titleEpisode = html.escape(titleEpisode, quote=True) 324 | titleEpisode = f'\t\t{titleEpisode}\n' 325 | fh.write(titleEpisode) 326 | 327 | if xdesc == 'true': 328 | xdescSort = addXDetails(edict) 329 | xdescSort = html.escape(xdescSort, quote=True) 330 | fh.write(f'\t\t{xdescSort}\n') 331 | if xdesc == 'false': 332 | if edict['epdesc'] is not None: 333 | epdesc = html.escape(f"{edict['epdesc']}\nLang: {lang}", quote=True) 334 | fh.write(f'\t\t{epdesc}\n') 335 | if edict['eplength'] is not None: 336 | fh.write('\t\t' + edict['eplength'] + '\n') 337 | if edict['epsn'] is not None and edict['epen'] is not None: 338 | fh.write(f'\t\tS{edict["epsn"].zfill(2)}E{edict["epen"].zfill(2)}\n') 339 | fh.write(f'\t\t{str(int(edict["epsn"])-1)}.{str(int(edict["epen"])-1)}.\n') 340 | if edict['epyear'] is not None: 341 | fh.write(f'\t\t{edict["epyear"]}\n') 342 | if not episode.startswith("MV"): 343 | if epicon == '1': 344 | if edict['epimage'] is not None and edict['epimage'] != '': 345 | fh.write(f'\t\t\n') 346 | else: 347 | if edict['epthumb'] is not None and edict['epthumb'] != '': 348 | fh.write(f'\t\t\n') 349 | if epicon == '2': 350 | if edict['epthumb'] is not None and edict['epthumb'] != '': 351 | fh.write(f'\t\t\n') 352 | if episode.startswith("MV"): 353 | if edict['epthumb'] is not None and edict['epthumb'] != '': 354 | fh.write(f'\t\t\n') 355 | if not any(i in ['New', 'Live'] for i in edict['epflag']): 356 | fh.write("\t\t 0: 358 | fh.write(f'start=\"{convTime(edict["epoad"])} {TZoffset}\" ') 359 | fh.write("/>\n") 360 | if edict['epflag'] is not None: 361 | if 'Finale' in edict['epflag']: 362 | fh.write("\t\t\n") 363 | if 'Live' in edict['epflag']: 364 | fh.write("\t\t\n") 365 | if 'New' in edict['epflag']: 366 | fh.write("\t\t\n") 367 | if 'Premiere' in edict['epflag']: 368 | fh.write("\t\t\n") 369 | if edict['eprating'] is not None: 370 | fh.write(f'\t\t\n\t\t\t{edict["eprating"]}\n\t\t\n') 371 | if edict['epstar'] is not None: 372 | fh.write(f'\t\t\n\t\t\t{edict["epstar"]}/4\n\t\t\n') 373 | if edict['epcredits'] is not None: 374 | fh.write("\t\t\n") 375 | for c in edict['epcredits']: 376 | if c['assetId'] is not None and c['assetId'] != '': 377 | fh.write('\t\t\t<' + c['role'].lower() + ' role="' + html.escape(c['characterName'], quote=True) + '" src="https://zap2it.tmsimg.com/assets/' + c['assetId'] + '.jpg">' + html.escape(c['name'], quote=True) + '\n') 378 | else: 379 | fh.write('\t\t\t<' + c['role'].lower() + ' role="' + html.escape(c['characterName'], quote=True) + '">' + html.escape(c['name'], quote=True) + '\n') 380 | fh.write("\t\t\n") 381 | if edict['eptags'] is not None: 382 | if 'CC' in edict['eptags']: 383 | fh.write('\t\t\n') 384 | if epgenre != '0': 385 | if edict['epfilter'] is not None and edict['epgenres'] is not None: 386 | genreNewList = genreSort(edict, epgenre, useHex) 387 | elif edict['epfilter'] is not None: 388 | genreNewList = edict['epfilter'] 389 | if genreNewList is not None and genreNewList != '': 390 | for genre in genreNewList: 391 | genre = html.escape(genre.replace('filter-', ''), quote=True) 392 | fh.write(f'\t\t{genre}\n') 393 | fh.write("\t\n") 394 | episodeCount += 1 395 | except Exception as e: 396 | logger.exception('No data for episode %s:', episode) 397 | #fn = os.path.join(cacheDir, episode + '.json') 398 | #os.remove(fn) 399 | #logger.info('Deleting episode %s:', episode) 400 | except Exception as e: 401 | logger.exception('Exception: printEpisodes') 402 | 403 | def xmltv(): # Routine called after the data has been collected from gracenote website 404 | try: 405 | enc = 'UTF-8' 406 | outFile = os.path.join(userdata, 'xmltv.xml') 407 | fh = codecs.open(outFile, 'w+b', encoding=enc) 408 | printHeader(fh, enc) 409 | printStations(fh) 410 | printEpisodes(fh) 411 | printFooter(fh) 412 | fh.close() 413 | except Exception as e: 414 | logger.exception('Exception: xmltv') 415 | 416 | def parseStations(content): #Routine downloads the necessary files from gracenote website. 417 | try: 418 | ch_guide = json.loads(content) 419 | for station in ch_guide['channels']: 420 | skey = station.get('channelId') 421 | if stationList is not None: 422 | if skey in stationList: 423 | schedule[skey] = {} 424 | chName = station.get('callSign') 425 | schedule[skey]['chfcc'] = chName 426 | schedule[skey]['chicon'] = station.get('thumbnail').split('?')[0] 427 | chnumStart = station.get('channelNo') 428 | if '.' not in chnumStart and chmatch == 'true' and chName is not None: 429 | chsub = re.search(r'(\d+)$', chName) 430 | if chsub is not None: 431 | chnumUpdate = chnumStart + '.' + chsub.group(0) 432 | else: 433 | chnumUpdate = chnumStart + '.1' 434 | else: 435 | chnumUpdate = chnumStart 436 | schedule[skey]['chnum'] = chnumUpdate 437 | if tvhmatch == 'true' and '.' in chnumUpdate: 438 | if chnumUpdate in tvhMatchDict: 439 | schedule[skey]['chtvh'] = tvhMatchDict[chnumUpdate] 440 | else: 441 | schedule[skey]['chtvh'] = None 442 | else: 443 | schedule[skey] = {} 444 | chName = station.get('callSign') 445 | schedule[skey]['chfcc'] = chName 446 | schedule[skey]['chicon'] = station.get('thumbnail').split('?')[0] 447 | chnumStart = station.get('channelNo') 448 | if '.' not in chnumStart and chmatch == 'true' and chName is not None: 449 | chsub = re.search(r'(\d+)$', chName) 450 | if chsub is not None: 451 | chnumUpdate = chnumStart + '.' + chsub.group(0) 452 | else: 453 | chnumUpdate = chnumStart + '.1' 454 | else: 455 | chnumUpdate = chnumStart 456 | schedule[skey]['chnum'] = chnumUpdate 457 | if tvhmatch == 'true' and '.' in chnumUpdate: 458 | if chnumUpdate in tvhMatchDict: 459 | schedule[skey]['chtvh'] = tvhMatchDict[chnumUpdate] 460 | else: 461 | schedule[skey]['chtvh'] = None 462 | except Exception as e: 463 | logger.exception('Exception: parseStations') 464 | 465 | def parseEpisodes(content): 466 | CheckTBA = "Safe" 467 | try: 468 | ch_guide = json.loads(content) 469 | for station in ch_guide['channels']: 470 | skey = station.get('channelId') 471 | if stationList is not None: 472 | if skey in stationList: 473 | episodes = station.get('events') 474 | for episode in episodes: 475 | epkey = str(calendar.timegm(time.strptime(episode.get('startTime'), '%Y-%m-%dT%H:%M:%SZ'))) 476 | schedule[skey][epkey] = {} 477 | schedule[skey][epkey]['epid'] = episode['program'].get('tmsId') 478 | schedule[skey][epkey]['epstart'] = str(calendar.timegm(time.strptime(episode.get('startTime'), '%Y-%m-%dT%H:%M:%SZ'))) 479 | schedule[skey][epkey]['epend'] = str(calendar.timegm(time.strptime(episode.get('endTime'), '%Y-%m-%dT%H:%M:%SZ'))) 480 | schedule[skey][epkey]['eplength'] = episode.get('duration') 481 | schedule[skey][epkey]['epshow'] = episode['program'].get('title') 482 | schedule[skey][epkey]['eptitle'] = episode['program'].get('episodeTitle') 483 | schedule[skey][epkey]['epdesc'] = episode['program'].get('shortDesc') 484 | schedule[skey][epkey]['epyear'] = episode['program'].get('releaseYear') 485 | schedule[skey][epkey]['eprating'] = episode.get('rating') 486 | schedule[skey][epkey]['epflag'] = episode.get('flag') 487 | schedule[skey][epkey]['eptags'] = episode.get('tags') 488 | schedule[skey][epkey]['epsn'] = episode['program'].get('season') 489 | schedule[skey][epkey]['epen'] = episode['program'].get('episode') 490 | schedule[skey][epkey]['epthumb'] = episode.get('thumbnail') 491 | schedule[skey][epkey]['epoad'] = None 492 | schedule[skey][epkey]['epstar'] = None 493 | schedule[skey][epkey]['epfilter'] = episode.get('filter') 494 | schedule[skey][epkey]['epgenres'] = None 495 | schedule[skey][epkey]['epcredits'] = None 496 | schedule[skey][epkey]['epxdesc'] = None 497 | schedule[skey][epkey]['epseries'] = episode.get('seriesId') 498 | schedule[skey][epkey]['epimage'] = None 499 | schedule[skey][epkey]['epfan'] = None 500 | if "TBA" in schedule[skey][epkey]['epshow']: 501 | CheckTBA = "Unsafe" 502 | elif schedule[skey][epkey]['eptitle']: 503 | if "TBA" in schedule[skey][epkey]['eptitle']: 504 | CheckTBA = "Unsafe" 505 | else: 506 | episodes = station.get('events') 507 | for episode in episodes: 508 | epkey = str(calendar.timegm(time.strptime(episode.get('startTime'), '%Y-%m-%dT%H:%M:%SZ'))) 509 | schedule[skey][epkey] = {} 510 | schedule[skey][epkey]['epid'] = episode['program'].get('tmsId') 511 | schedule[skey][epkey]['epstart'] = str(calendar.timegm(time.strptime(episode.get('startTime'), '%Y-%m-%dT%H:%M:%SZ'))) 512 | schedule[skey][epkey]['epend'] = str(calendar.timegm(time.strptime(episode.get('endTime'), '%Y-%m-%dT%H:%M:%SZ'))) 513 | schedule[skey][epkey]['eplength'] = episode.get('duration') 514 | schedule[skey][epkey]['epshow'] = episode['program'].get('title') 515 | schedule[skey][epkey]['eptitle'] = episode['program'].get('episodeTitle') 516 | schedule[skey][epkey]['epdesc'] = episode['program'].get('shortDesc') 517 | schedule[skey][epkey]['epyear'] = episode['program'].get('releaseYear') 518 | schedule[skey][epkey]['eprating'] = episode.get('rating') 519 | schedule[skey][epkey]['epflag'] = episode.get('flag') 520 | schedule[skey][epkey]['eptags'] = episode.get('tags') 521 | schedule[skey][epkey]['epsn'] = episode['program'].get('season') 522 | schedule[skey][epkey]['epen'] = episode['program'].get('episode') 523 | schedule[skey][epkey]['epthumb'] = episode.get('thumbnail') 524 | schedule[skey][epkey]['epoad'] = None 525 | schedule[skey][epkey]['epstar'] = None 526 | schedule[skey][epkey]['epfilter'] = episode.get('filter') 527 | schedule[skey][epkey]['epgenres'] = None 528 | schedule[skey][epkey]['epcredits'] = None 529 | schedule[skey][epkey]['epxdesc'] = None 530 | schedule[skey][epkey]['epseries'] = episode.get('seriesId') 531 | schedule[skey][epkey]['epimage'] = None 532 | schedule[skey][epkey]['epfan'] = None 533 | if "TBA" in schedule[skey][epkey]['epshow']: 534 | CheckTBA = "Unsafe" 535 | elif schedule[skey][epkey]['eptitle']: 536 | if "TBA" in schedule[skey][epkey]['eptitle']: 537 | CheckTBA = "Unsafe" 538 | except Exception as e: 539 | logger.exception('Exception: parseEpisodes') 540 | return CheckTBA 541 | 542 | def parseXdetails(): 543 | showList = [] 544 | failList = [] 545 | try: 546 | for station in schedule: 547 | sdict = schedule[station] 548 | for episode in sdict: 549 | if not episode.startswith("ch"): 550 | edict = sdict[episode] 551 | EPseries = edict['epseries'] 552 | showList.append(edict['epseries']) 553 | filename = EPseries + '.json' 554 | fileDir = os.path.join(cacheDir, filename) 555 | try: 556 | if not os.path.exists(fileDir) and EPseries not in failList: 557 | retry = 3 558 | while retry > 0: 559 | logger.info('Downloading details data for: %s', EPseries) 560 | #url = 'https://tvlistings.gracenote.com/api/program/overviewDetails' 561 | data = 'programSeriesID=' + EPseries 562 | data_encode = data.encode('utf-8') 563 | try: 564 | #URLcontent = urllib.request.Request(url, data=data_encode) 565 | URLcontent = fetch_url('programDetails', {'data_encode': data_encode}) 566 | JSONcontent = json.dumps(json.loads(URLcontent)).encode('utf-8') 567 | if JSONcontent: 568 | with open(fileDir,"wb+") as f: 569 | f.write(JSONcontent) 570 | f.close() 571 | retry = 0 572 | else: 573 | time.sleep(1) 574 | retry -= 1 575 | logger.warning('Retry downloading missing details data for: %s', EPseries) 576 | except Exception as e: 577 | time.sleep(1) 578 | retry -= 1 579 | logger.warning('Retry downloading details data for: %s - %s', EPseries, e) 580 | if os.path.exists(fileDir): 581 | fileSize = os.path.getsize(fileDir) 582 | if fileSize > 0: 583 | with open(fileDir, 'rb') as f: 584 | EPdetails = json.loads(f.read()) 585 | f.close() 586 | logger.info('Parsing %s', filename) 587 | edict['epimage'] = EPdetails.get('seriesImage') 588 | edict['epfan'] = EPdetails.get('backgroundImage') 589 | EPgenres = EPdetails.get('seriesGenres') 590 | if filename.startswith("MV"): 591 | edict['epcredits'] = EPdetails['overviewTab'].get('cast') 592 | EPgenres = 'Movie|' + EPgenres 593 | edict['epgenres'] = EPgenres.split('|') 594 | #edict['epstar'] = EPdetails.get('starRating') 595 | EPlist = EPdetails['upcomingEpisodeTab'] 596 | EPid = edict['epid'] 597 | for airing in EPlist: 598 | if EPid.lower() == airing['tmsID'].lower(): 599 | if not episode.startswith("MV"): 600 | try: 601 | origDate = airing.get('originalAirDate') 602 | if origDate != '': 603 | EPoad = re.sub('Z', ':00Z', airing.get('originalAirDate')) 604 | edict['epoad'] = str(calendar.timegm(time.strptime(EPoad, '%Y-%m-%dT%H:%M:%SZ'))) 605 | except Exception as e: 606 | logger.exception('Could not parse oad for: %s - %s', episode, e) 607 | try: 608 | TBAcheck = airing.get('episodeTitle') 609 | if TBAcheck != '': 610 | if "TBA" in TBAcheck: 611 | try: 612 | os.remove(fileDir) 613 | logger.info('Deleting %s due to TBA listings', filename) 614 | showList.remove(edict['epseries']) 615 | except OSError as e: 616 | logger.warning('Error Deleting: %s - %s.' % (e.filename, e.strerror)) 617 | except Exception as e: 618 | logger.exception('Could not parse TBAcheck for: %s - %s', episode, e) 619 | else: 620 | logger.warning('Could not parse data for: %s - deleting file', filename) 621 | os.remove(fileDir) 622 | else: 623 | logger.warning('Could not download details data for: %s - skipping episode', episode) 624 | failList.append(EPseries) 625 | except Exception as e: 626 | logger.exception('Could not parse data for: %s - deleting file - %s', episode, e) 627 | #os.remove(fileDir) 628 | except Exception as e: 629 | logger.exception('Exception: parseXdetails') 630 | return showList 631 | 632 | def addXDetails(edict): 633 | try: 634 | ratings = "" 635 | date = "" 636 | myear = "" 637 | new = "" 638 | live = "" 639 | hd = "" 640 | cc = "" 641 | cast = "" 642 | season = "" 643 | epis = "" 644 | episqts = "" 645 | prog = "" 646 | plot= "" 647 | descsort = "" 648 | genre = "" 649 | lang = "" 650 | bullet = "\u2022 " 651 | hyphen = "\u2013 " 652 | newLine = "\n" 653 | space = " " 654 | colon = "\u003A " 655 | vbar = "\u007C " 656 | slash = "\u2215 " 657 | comma = "\u002C " 658 | 659 | def getSortName(opt): 660 | return { 661 | 1: bullet, 2: newLine, 3: hyphen, 4: space, 662 | 5: colon, 6: vbar, 7: slash, 8: comma, 663 | 9: plot, 10: new, 11: hd, 12: cc, 664 | 13: season, 14: ratings, 15: date, 16: prog, 665 | 17: epis, 18: episqts, 19: cast, 20: myear, 666 | 21: genre, 22: lang 667 | }.get(opt, None) 668 | 669 | def cleanSortList(optList): 670 | cleanList=[] 671 | optLen = len(optList) 672 | for opt in optList: 673 | thisOption = getSortName(int(opt)) 674 | if thisOption: 675 | cleanList.append(int(opt)) 676 | for _ in reversed(cleanList): 677 | if cleanList[-1] <= 8: 678 | del cleanList[-1] 679 | return cleanList 680 | 681 | def makeDescsortList(optList): 682 | sortOrderList =[] 683 | lastOption = 1 684 | cleanedList = cleanSortList(optList) 685 | for opt in cleanedList: 686 | thisOption = getSortName(int(opt)) 687 | if int(opt) <= 8 and lastOption <= 8: 688 | if int(opt) == 2 and len(sortOrderList) > 1: 689 | del sortOrderList[-1] 690 | sortOrderList.append(thisOption) 691 | lastOption = int(opt) 692 | elif thisOption and lastOption: 693 | sortOrderList.append(thisOption) 694 | lastOption = int(opt) 695 | elif thisOption: 696 | lastOption = int(opt) 697 | return sortOrderList 698 | 699 | if edict['epoad'] is not None and int(edict['epoad']) > 0: 700 | is_dst = time.daylight and time.localtime().tm_isdst > 0 701 | TZoffset = (time.altzone if is_dst else time.timezone) 702 | origDate = int(edict['epoad']) + TZoffset 703 | finalDate = datetime.datetime.fromtimestamp(origDate).strftime('%B %d%% %Y') 704 | finalDate = re.sub('%', ',', finalDate) 705 | date = "First aired: " + finalDate + space 706 | if edict['epyear'] is not None: 707 | myear = "Released: " + edict['epyear'] + space 708 | if edict['eprating'] is not None: 709 | ratings = edict['eprating'] + space 710 | if edict['eptags'] != []: 711 | tagsList = edict['eptags'] 712 | cc = ' '.join(tagsList).upper() + space 713 | #if edict['ephd'] is not None: 714 | #hd = edict['ephd'] + space 715 | if edict['epflag'] != []: 716 | flagList = edict['epflag'] 717 | new = ' '.join(flagList).upper() + space 718 | if edict['epsn'] is not None and edict['epen'] is not None: 719 | s = re.sub('S', '', edict['epsn']) 720 | sf = "Season " + str(int(s)) 721 | e = re.sub('E', '', edict['epen']) 722 | ef = "Episode " + str(int(e)) 723 | season = sf + " - " + ef + space 724 | if edict['epshow'] is not None: 725 | prog = edict['epshow'] + space 726 | if edict['eptitle'] is not None: 727 | epis = edict['eptitle'] + space 728 | episqts = '\"' + edict['eptitle'] + '\"' + space 729 | if edict['epdesc'] is not None: 730 | plot = edict['epdesc'] + space 731 | if edict['epgenres'] is not None: 732 | genre = ", ".join(edict["epgenres"]) + space 733 | if edict['lang'] is not None: 734 | langdict = {'en': 'English', 'es': 'Español', 'fr': 'Français'} 735 | lang = langdict.get(edict["lang"]) + space 736 | 737 | # todo - handle star ratings 738 | 739 | descsort = "".join(makeDescsortList(xdescOrder)) 740 | return descsort 741 | except Exception as e: 742 | logger.exception('Exception: addXdetails to description') 743 | 744 | isConnectedtoTVH = tvh_connect(tvhurl, tvhport, usern, passw, digest) 745 | 746 | try: 747 | if not os.path.exists(cacheDir): 748 | os.mkdir(cacheDir) 749 | count = 0 750 | gridtime = gridtimeStart 751 | if stationList is None: 752 | logger.info('No channel list found - adding all stations!') 753 | if tvhoff == 'true' and tvhmatch == 'true': 754 | tvhMatchGet() 755 | deleteOldCache(gridtimeStart) 756 | while count < dayHours: 757 | filename = str(gridtime) + '.json.gz' 758 | fileDir = os.path.join(cacheDir, filename) 759 | if not os.path.exists(fileDir): 760 | try: 761 | logger.info('Downloading guide data for: %s', str(gridtime)) 762 | #url = f"https://tvlistings.gracenote.com/api/grid?aid=orbebb&TMSID=&AffiliateID=lat&FromPage=TV%20Grid&lineupId=×pan=3&headendId={lineupcode}&country={country}&device={device}&postalCode={zipcode}&time={str(gridtime)}&isOverride=true&pref=-&userId=-" 763 | options = {'lineupcode': lineupcode, 'country': country, 'device': device, 'zipcode': zipcode, 'gridtime': str(gridtime)} 764 | saveContent = fetch_url('lineup', options) 765 | #saveContent = urllib.request.urlopen(url).read() 766 | savepage(fileDir, saveContent) 767 | except: 768 | logger.warning('Could not download guide data for: %s', str(gridtime)) 769 | logger.warning('URL: %s', options) 770 | if os.path.exists(fileDir): 771 | try: 772 | with gzip.open(fileDir, 'rb') as f: 773 | content = f.read() 774 | f.close() 775 | logger.info('Parsing %s', filename) 776 | if count == 0: 777 | parseStations(content) 778 | TBAcheck = parseEpisodes(content) 779 | if TBAcheck == "Unsafe": 780 | try: 781 | os.remove(fileDir) 782 | logger.info('Deleting %s due to TBA listings', filename) 783 | except OSError as e: 784 | logger.warning('Error Deleting: %s - %s.' % (e.filename, e.strerror)) 785 | except: 786 | logger.warning('JSON file error for: %s - deleting file', filename) 787 | os.remove(fileDir) 788 | count += 1 789 | gridtime = gridtime + 10800 790 | if xdetails == 'true': 791 | showList = parseXdetails() 792 | else: 793 | showList = [] 794 | xmltv() 795 | deleteOldShowCache(showList) 796 | timeRun = round((time.time() - pythonStartTime),2) 797 | logger.info('zap2epg completed in %s seconds. ', timeRun) 798 | logger.info('%s Stations and %s Episodes written to xmltv.xml file.', str(stationCount), str(episodeCount)) 799 | counter = dict(sorted(Counter(countGenres()).items())) 800 | for cnt in counter: 801 | logger.info(cnt + ": " + str(counter[cnt])) 802 | return timeRun, stationCount, episodeCount 803 | except Exception as e: 804 | logger.exception('Exception: main - %s',e) 805 | 806 | if __name__ == '__main__': 807 | userdata = os.getcwd() 808 | log = os.path.join(userdata, 'zap2epg.log') 809 | createLogger(log) 810 | logger.info("zap2epg.py is started executing") 811 | create_opener() #create the connection to the website for EPG data 812 | mainRun(userdata) 813 | --------------------------------------------------------------------------------