├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── dependabot.yml └── workflows │ ├── build.yml │ ├── lint.yml │ └── release.yml ├── .gitignore ├── .goreleaser.yml ├── LICENSE ├── README.md ├── go.mod ├── go.sum ├── internal ├── cmd │ ├── cmd.go │ ├── registry.go │ └── registry_unix.go ├── config │ ├── config.go │ └── default-config.toml ├── creds │ ├── creds.go │ └── creds_darwin.go ├── github │ └── update.go ├── proxy │ └── proxy.go ├── ui │ ├── live.go │ ├── logger.go │ ├── node.go │ ├── nodeV2.go │ ├── node_test.go │ ├── state.go │ └── theme.go └── util │ ├── logger.go │ ├── util.go │ └── util_test.go ├── main.go └── pkg └── f1tv └── v2 ├── api.go └── models.go /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: "[BUG]" 5 | labels: bug 6 | assignees: SoMuchForSubtlety 7 | 8 | --- 9 | 10 | Please check the [FAQ](https://github.com/SoMuchForSubtlety/f1viewer#Faq) and search [existing issues](https://github.com/SoMuchForSubtlety/f1viewer/issues?q=is%3Aissue) before you submit a new one! 11 | 12 | **Describe the bug** 13 | A clear and concise description of what the bug is. 14 | 15 | **To Reproduce** 16 | Steps to reproduce the behavior: 17 | 1. Go to... 18 | 2. Try to play... 19 | 3. See error 20 | 21 | **Expected behaviour** 22 | A clear and concise description of what you expected to happen. 23 | 24 | **Screenshots** 25 | If applicable, add screenshots to help explain your problem. 26 | 27 | **F1TV account plan** 28 | Do you have a free, access or pro account? Are you using a VPN / proxy? 29 | 30 | **Desktop (please complete the following information):** 31 | - OS 32 | - installation method 33 | - Version [`f1viewer -v` output] 34 | 35 | **Logs** 36 | If applicable please provide the relevant portion of your logs. You can find them by running `f1viewer -logs`. 37 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '[FEATURE]' 5 | labels: 'enhancement' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: gomod 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: "04:00" 8 | open-pull-requests-limit: 10 9 | ignore: 10 | - dependency-name: github.com/atotto/clipboard 11 | versions: 12 | - 0.1.4 13 | - dependency-name: github.com/stretchr/testify 14 | versions: 15 | - 1.7.0 16 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | branches: 4 | - master 5 | pull_request: 6 | name: Test 7 | jobs: 8 | test: 9 | strategy: 10 | matrix: 11 | os: [ubuntu-latest, macos-latest, windows-latest] 12 | runs-on: ${{ matrix.os }} 13 | steps: 14 | - name: Install Go 15 | uses: actions/setup-go@v2 16 | with: 17 | go-version: 1.18.x 18 | - name: Checkout code 19 | uses: actions/checkout@v2 20 | - name: Test 21 | run: go test ./... 22 | build: 23 | strategy: 24 | matrix: 25 | goos: [linux, windows, darwin] 26 | goarch: [amd64, arm64] 27 | runs-on: ubuntu-latest 28 | steps: 29 | - name: Install Go 30 | uses: actions/setup-go@v2 31 | with: 32 | go-version: 1.18.x 33 | - name: Checkout code 34 | uses: actions/checkout@v2 35 | - name: Build 36 | env: 37 | GOOS: ${{ matrix.goos }} 38 | GOARCH: ${{ matrix.goarch }} 39 | run: go build -v -o f1viewer-${{ matrix.goos }}-${{ matrix.goarch }} . 40 | - uses: actions/upload-artifact@v2 41 | with: 42 | name: ${{ matrix.goos }}-${{ matrix.goarch }} 43 | path: f1viewer-${{ matrix.goos }}-${{ matrix.goarch }} 44 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: lint 2 | on: 3 | push: 4 | branches: 5 | - master 6 | pull_request: 7 | jobs: 8 | golangci: 9 | name: lint 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - name: golangci-lint 14 | uses: golangci/golangci-lint-action@v2 15 | with: 16 | # Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version. 17 | version: v1.45 18 | args: --enable="gofumpt,gocritic,dupl" 19 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: release 2 | 3 | on: 4 | push: 5 | tags: 6 | - "*" 7 | 8 | jobs: 9 | goreleaser: 10 | # needs to run on macOS or keychain access on mac breaks 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Checkout 14 | uses: actions/checkout@v2 15 | - name: Unshallow 16 | run: git fetch --prune --unshallow 17 | - name: Set up Go 18 | uses: actions/setup-go@v2 19 | with: 20 | go-version: 1.18.x 21 | - name: Run GoReleaser 22 | uses: goreleaser/goreleaser-action@v2 23 | with: 24 | version: latest 25 | args: release --rm-dist 26 | env: 27 | GITHUB_TOKEN: ${{ secrets.GORELEASER }} 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | result.json 2 | *.exe 3 | config.json 4 | *.m3u8 5 | goreleaser.exe 6 | .backup.yml 7 | dist/ 8 | *.exe~ 9 | .vscode/ 10 | .idea/ 11 | downloads/ 12 | *.txt 13 | F1viewer 14 | *.log 15 | f1viewer 16 | -------------------------------------------------------------------------------- /.goreleaser.yml: -------------------------------------------------------------------------------- 1 | project_name: f1viewer 2 | builds: 3 | - id: windows 4 | goos: 5 | - windows 6 | goarch: 7 | - amd64 8 | - id: linux 9 | goos: 10 | - linux 11 | goarch: 12 | - amd64 13 | - arm 14 | - arm64 15 | - id: mac 16 | goos: 17 | - darwin 18 | goarch: 19 | - amd64 20 | - arm64 21 | archives: 22 | - replacements: 23 | darwin: macOS 24 | format_overrides: 25 | - goos: windows 26 | format: zip 27 | universal_binaries: 28 | - replace: true 29 | id: mac 30 | checksum: 31 | name_template: "checksums.txt" 32 | snapshot: 33 | name_template: "{{ .Tag }}-next" 34 | changelog: 35 | skip: true 36 | nfpms: 37 | - description: TUI client for F1TV 38 | license: GPL-3.0-only 39 | homepage: https://github.com/SoMuchForSubtlety/f1viewer/ 40 | maintainer: SoMuchForSubtlety 41 | formats: 42 | - deb 43 | - rpm 44 | recommends: 45 | - xclip 46 | - mpv 47 | - vlc 48 | brews: 49 | - description: TUI client for F1TV 50 | homepage: https://github.com/SoMuchForSubtlety/f1viewer/ 51 | folder: Formula 52 | tap: 53 | owner: SoMuchForSubtlety 54 | name: homebrew-tap 55 | commit_author: 56 | name: goreleaserbot 57 | email: goreleaser@carlosbecker.com 58 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Go Report Card](https://goreportcard.com/badge/github.com/SoMuchForSubtlety/f1viewer)](https://goreportcard.com/report/github.com/SoMuchForSubtlety/f1viewer) 2 | ![](https://github.com/SoMuchForSubtlety/f1viewer/workflows/Test/badge.svg) 3 | 4 | # f1viewer 5 | 6 | ![preview image](https://user-images.githubusercontent.com/15961647/107859733-c6a8a900-6e3b-11eb-82b8-5b1ee0a16297.png) 7 | 8 | ## Table of Contents 9 | 10 | * [Installation](#Installation) 11 | * [Login](#Login) 12 | * [FAQ](#Faq) 13 | * [Config](#Config) 14 | * [Custom Commands](#Custom-commands) 15 | * [Multi Commands](#Multi-commands) 16 | * [Live Session Hooks](#Live-session-hooks) 17 | * [Key Bindings](#Key-bindings) 18 | * [Logs](#Logs) 19 | * [Credentials](#Credentials) 20 | 21 | ## Installation 22 | 23 | **Note:** You also need a compatible player installed, you can find a list [here](https://github.com/SoMuchForSubtlety/f1viewer/wiki/Players-Supported-by-Default). 24 | 25 | ## compile form source 26 | Install the go compiler, then run the following commands 27 | ```bash 28 | git clone https://github.com/SoMuchForSubtlety/f1viewer && cd f1viewer 29 | go build . 30 | ``` 31 | 32 | ### Windows 33 | * Download [the latest release directly](https://github.com/SoMuchForSubtlety/f1viewer/releases/latest) 34 | * Or install with [chocolatey](https://chocolatey.org/packages/f1viewer/) 35 | 36 | ### macOS 37 | * You can install f1viewer with Homebrew (recommended) 38 | ```bash 39 | brew tap SoMuchForSubtlety/tap 40 | brew install SoMuchForSubtlety/tap/f1viewer 41 | ``` 42 | * Or [download the binary directly](https://github.com/SoMuchForSubtlety/f1viewer/releases/latest) 43 | 44 | ### Debian and Ubuntu 45 | Download the latest release `.deb` [file](https://github.com/SoMuchForSubtlety/f1viewer/releases/latest) 46 | 47 | ### Fedora, openSUSE, CentOS 48 | * Install from the f1viewer [copr repo](https://copr.fedorainfracloud.org/coprs/somuchforsubtlety/f1viewer/) 49 | 50 | ```bash 51 | sudo dnf install dnf-plugins-core 52 | sudo dnf copr enable somuchforsubtlety/f1viewer 53 | sudo dnf install f1viewer 54 | ``` 55 | 56 | * Or download the latest release `.rpm` [file](https://github.com/SoMuchForSubtlety/f1viewer/releases/latest) 57 | 58 | ### Arch 59 | Install the f1viewer [AUR package](https://aur.archlinux.org/packages/f1viewer/). 60 | 61 | ### Any other Linux distribution 62 | * Download the binary [directly](https://github.com/SoMuchForSubtlety/f1viewer/releases/latest) 63 | * Or install it with [Homebrew](https://docs.brew.sh/Homebrew-on-Linux) as described in the [macOS](#macOS) section. 64 | 65 | ## Login 66 | Login via email and password is currently broken dues to anti-bot measures from F1TV. Follow [these steps](https://github.com/SoMuchForSubtlety/f1viewer/wiki/Getting-your-subscription-token) to log in with your subscription token. 67 | 68 | ## FAQ 69 | #### why is there a login, what credentials should I use 70 | You need an F1TV account created with an IP in a country that has F1TV pro. Use your F1TV account email and password to log in. You can use the tab key to navigate the login form. 71 | #### when I try to play something I get a 4xx error 72 | You need to be logged in and in a country that has F1TV pro. If you get the error but think your account should be able to play the selected content please open an issue. 73 | #### f1viewer is not showing a live session / loading very slowly 74 | This can happen if the F1TV servers are overloaded. There is nothing I can do to fix this. 75 | Start your stream as soon as possible at the start of the session and you can usually avoid this. 76 | #### The player starts but then has some issue / error 77 | Please make sure you are using the latest version of the player. If you use Windows please download MPV from [here](https://sourceforge.net/projects/mpv-player-windows/files/). Generally once an external program is started f1viewer is done and you should consult the external program's documentation for troubleshooting. 78 | #### No players are detected 79 | Players need to be in your PATH environment variable to be detected by f1viewer. 80 | 81 | ## Config 82 | When you first start f1viewer a boilerplate config is automatically generated. On Widows systems it's located in `%AppData%\Roaming\f1viewer`, on macOS in `$HOME/Library/Application Support/f1viewer` and on Linux in `$XDG_CONFIG_HOME/f1viewer` or `$HOME/.config/f1viewer`. You can access it quickly by running `f1viewer -config`. 83 | 84 | ## Custom Commands 85 | You can execute custom commands, for example to launch a different player. These are set in the config under `custom_playback_options` in the config file. You can add as many as you want. 86 | ```toml 87 | [[custom_playback_options]] 88 | command = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-i", "$url", "-c", "copy", "-f", "mp4", "$title.mp4"] 89 | proxy = true 90 | title = "Download as mp4" 91 | ``` 92 | 93 | `title` is the title. It will appear next to the standard `Play with MPV` and `Copy URL to clipboard`. 94 | 95 | `command` is where your command goes. It is saved as a list of args like in the examples above. Every argument should be a separate string! The following would be incorrect! `["ffmpeg", "-i $url", "-c copy", "$title.mp4"]` 96 | 97 | `proxy` sends http requests through a proxy if they require cookies. This is useful for commands that use ffmpeg (and by extension mpv). 98 | 99 | There are several placeholder variables you can use that will be replaced by f1viewer. 100 | 101 | - `$url`: the content's URL 102 | - `$category`: the content's category (eg. "Documentary") 103 | - `$season`: the season's year (eg. "2021") 104 | - `$event`: the event (eg. "Belgian Grand Prix") 105 | - `$session`: the session (eg. "F1 Practice 3") 106 | - `$perspective`: the perspective (eg. "F1 Live", "Kimi Räikkönen", etc.) 107 | - `$title`: the conten's title as reported by F1TV 108 | - `$filename`: the same as title, but with illegal characters removed 109 | - `$series`: "Formula 1", "Formula 2", etc. 110 | - `$country`: the country an event is held in 111 | - `$circuit`: the circuirt and event is held at 112 | - `$time`: the time of the session in RFC3339 format (`$year`, `$month`, `$day`, `$hour` and `$minute` are also available) 113 | - `$date`: the date of the session in ISO 8601 format 114 | - `$ordinal`: the ordinal numer of the event 115 | - `$episodenumber`: the episode number as reported by F1TV 116 | - `$json`: all metadata fields and the full source metadata from F1TV 117 | - `$lang`: the preferred languages as a comma separated list 118 | 119 | If you have ideas for more variables feel free to open an issue. 120 | 121 | **Tip**: To get Windows commands like `echo`, `dir`, etc. to work, you'll need to prepend them with `"cmd", "/C"`, so for example `["echo", "hello"]` turns into `["cmd", "/C", "echo", "hello"]` 122 | 123 | ## Multi Commands 124 | To make it easy to load the same feeds with the same commands every time, you can map multiple commands to one action. The `match_title` variable will be used to match the session feeds (it also allows regex). For example, if `match_title` is `Lando Norris`, it will load any feed with that name, with the given command. 125 | You can specify commands directly with `command`, or reference one of your [custom commands](#custom-command) titles with `command_key`. 126 | 127 | For an explanation on the `command` variable, see [Custom Commands](#custom-commands) 128 | 129 | ```toml 130 | [[multi_commands]] 131 | title = "Open F1 Live and HAM onboard" 132 | 133 | [[multi_commands.targets]] 134 | command = ["mpv", "$url", "--alang=$lang"] # define a command to execute 135 | match_title = "F1 Live" 136 | 137 | [[multi_commands.targets]] 138 | command_key = "custom mpv" # you can also reference previously defined custom commands 139 | match_title = "Lewis [a-zA-Z]+" # regex is also supported 140 | ``` 141 | 142 | ## Live Session Hooks 143 | Live session hooks work like multi commands, but they are automatically started when a new live session is detected. 144 | 145 | ```toml 146 | [[live_session_hooks]] 147 | title = "Open Pit Lane and Data Channel" 148 | 149 | [[live_session_hooks.targets]] 150 | command = ["mpv", "$url", "--alang=$lang", "--quiet"] # define a command to execute 151 | match_title = "Pit Lane" 152 | 153 | [[live_session_hooks.targets]] 154 | command_key = "custom mpv" # you can also reference previously defined custom commands 155 | match_title = "Data Channel" 156 | ``` 157 | 158 | ## Key Bindings 159 | * arrow keys or `h`, `j`, `k`, `l`. 160 | * `tab` to cycle through the login form fields 161 | * enter to select / confirm 162 | * `q` to quit 163 | 164 | ## Logs 165 | By default f1viewer saves all info and error messages to log files. Under Windows and macOS they are save in the same directory as the config file, on Linux they are saved to `$HOME/.local/share/f1viewer/`. You can access them quickly by running `f1viewer -logs`. 166 | Saving logs can also be turned off in the config. 167 | 168 | ## Credentials 169 | Your login credentials for F1TV are not saved in the config file. On macOS they are stored in the keychain and on Windows the credential store is used. If you're using Linux, where they are saved depends on your distro. Generally [Pass](https://www.passwordstore.org/), [Secret Service](https://specifications.freedesktop.org/secret-service/latest/) / [GNOME Keyring](https://wiki.gnome.org/Projects/GnomeKeyring) and KWallet are supported. 170 | If it does not work on your distro or you encounter any problems please open an issue. -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/SoMuchForSubtlety/f1viewer/v2 2 | 3 | go 1.17 4 | 5 | replace github.com/rivo/tview => github.com/SoMuchForSubtlety/tview v0.0.0-20210731202536-88987c7f5054 6 | 7 | require ( 8 | github.com/99designs/keyring v1.2.1 9 | github.com/BurntSushi/toml v1.0.0 10 | github.com/atotto/clipboard v0.1.4 11 | github.com/gdamore/tcell/v2 v2.4.0 12 | github.com/mattn/go-runewidth v0.0.13 // indirect 13 | github.com/rivo/tview v0.0.0-20210624165335-29d673af0ce2 14 | github.com/stretchr/testify v1.7.0 15 | github.com/zalando/go-keyring v0.2.1 16 | golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a 17 | golang.org/x/text v0.3.7 // indirect 18 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect 19 | ) 20 | 21 | require ( 22 | github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect 23 | github.com/alessio/shellescape v1.4.1 // indirect 24 | github.com/danieljoos/wincred v1.1.2 // indirect 25 | github.com/davecgh/go-spew v1.1.1 // indirect 26 | github.com/dvsekhvalnov/jose2go v1.5.0 // indirect 27 | github.com/gdamore/encoding v1.0.0 // indirect 28 | github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect 29 | github.com/godbus/dbus/v5 v5.0.6 // indirect 30 | github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect 31 | github.com/lucasb-eyer/go-colorful v1.2.0 // indirect 32 | github.com/mtibben/percent v0.2.1 // indirect 33 | github.com/pmezard/go-difflib v1.0.0 // indirect 34 | github.com/rivo/uniseg v0.2.0 // indirect 35 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 // indirect 36 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect 37 | ) 38 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:/vQbFIOMbk2FiG/kXiLl8BRyzTWDw7gX/Hz7Dd5eDMs= 2 | github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4/go.mod h1:hN7oaIRCjzsZ2dE+yG5k+rsdt3qcwykqK6HVGcKwsw4= 3 | github.com/99designs/keyring v1.2.1 h1:tYLp1ULvO7i3fI5vE21ReQuj99QFSs7lGm0xWyJo87o= 4 | github.com/99designs/keyring v1.2.1/go.mod h1:fc+wB5KTk9wQ9sDx0kFXB3A0MaeGHM9AwRStKOQ5vOA= 5 | github.com/BurntSushi/toml v1.0.0 h1:dtDWrepsVPfW9H/4y7dDgFc2MBUSeJhlaDtK13CxFlU= 6 | github.com/BurntSushi/toml v1.0.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= 7 | github.com/SoMuchForSubtlety/tview v0.0.0-20210731202536-88987c7f5054 h1:Za8ACAZcd/bHAvQpFROAi0hJ4gyMJMD6N06s9L8olQs= 8 | github.com/SoMuchForSubtlety/tview v0.0.0-20210731202536-88987c7f5054/go.mod h1:IxQujbYMAh4trWr0Dwa8jfciForjVmxyHpskZX6aydQ= 9 | github.com/alessio/shellescape v1.4.1 h1:V7yhSDDn8LP4lc4jS8pFkt0zCnzVJlG5JXy9BVKJUX0= 10 | github.com/alessio/shellescape v1.4.1/go.mod h1:PZAiSCk0LJaZkiCSkPv8qIobYglO3FPpyFjDCtHLS30= 11 | github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= 12 | github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= 13 | github.com/danieljoos/wincred v1.1.0/go.mod h1:XYlo+eRTsVA9aHGp7NGjFkPla4m+DCL7hqDjlFjiygg= 14 | github.com/danieljoos/wincred v1.1.2 h1:QLdCxFs1/Yl4zduvBdcHB8goaYk9RARS2SgLLRuAyr0= 15 | github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnGqR5Vl2tAx0= 16 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 17 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 18 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 19 | github.com/dvsekhvalnov/jose2go v1.5.0 h1:3j8ya4Z4kMCwT5nXIKFSV84YS+HdqSSO0VsTQxaLAeM= 20 | github.com/dvsekhvalnov/jose2go v1.5.0/go.mod h1:QsHjhyTlD/lAVqn/NSbVZmSCGeDehTB/mPZadG+mhXU= 21 | github.com/gdamore/encoding v1.0.0 h1:+7OoQ1Bc6eTm5niUzBa0Ctsh6JbMW6Ra+YNuAtDBdko= 22 | github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg= 23 | github.com/gdamore/tcell/v2 v2.3.3/go.mod h1:cTTuF84Dlj/RqmaCIV5p4w8uG1zWdk0SF6oBpwHp4fU= 24 | github.com/gdamore/tcell/v2 v2.4.0 h1:W6dxJEmaxYvhICFoTY3WrLLEXsQ11SaFnKGVEXW57KM= 25 | github.com/gdamore/tcell/v2 v2.4.0/go.mod h1:cTTuF84Dlj/RqmaCIV5p4w8uG1zWdk0SF6oBpwHp4fU= 26 | github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 h1:ZpnhV/YsD2/4cESfV5+Hoeu/iUR3ruzNvZ+yQfO03a0= 27 | github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2/go.mod h1:bBOAhwG1umN6/6ZUMtDFBMQR8jRg9O75tm9K00oMsK4= 28 | github.com/godbus/dbus/v5 v5.0.6 h1:mkgN1ofwASrYnJ5W6U/BxG15eXXXjirgZc7CLqkcaro= 29 | github.com/godbus/dbus/v5 v5.0.6/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= 30 | github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU= 31 | github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0= 32 | github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI= 33 | github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= 34 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 35 | github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= 36 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 37 | github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= 38 | github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= 39 | github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= 40 | github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= 41 | github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU= 42 | github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= 43 | github.com/mtibben/percent v0.2.1 h1:5gssi8Nqo8QU/r2pynCm+hBQHpkB/uNK7BJCFogWdzs= 44 | github.com/mtibben/percent v0.2.1/go.mod h1:KG9uO+SZkUp+VkRHsCdYQV3XSZrrSpR3O9ibNBTZrns= 45 | github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= 46 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 47 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 48 | github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= 49 | github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= 50 | github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= 51 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 52 | github.com/stretchr/objx v0.3.0 h1:NGXK3lHquSN08v5vWalVI/L8XU9hdzE/G6xsrze47As= 53 | github.com/stretchr/objx v0.3.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= 54 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 55 | github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= 56 | github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= 57 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 58 | github.com/zalando/go-keyring v0.2.1 h1:MBRN/Z8H4U5wEKXiD67YbDAr5cj/DOStmSga70/2qKc= 59 | github.com/zalando/go-keyring v0.2.1/go.mod h1:g63M2PPn0w5vjmEbwAX3ib5I+41zdm4esSETOn9Y6Dw= 60 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 61 | golang.org/x/sys v0.0.0-20210309074719-68d13333faf2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 62 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 63 | golang.org/x/sys v0.0.0-20210819135213-f52c844e1c1c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 64 | golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a h1:ppl5mZgokTT8uPkmYOyEUmPTr3ypaKkg5eFOGrAmxxE= 65 | golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 66 | golang.org/x/term v0.0.0-20201210144234-2321bbc49cbf/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 67 | golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 68 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY= 69 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 70 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 71 | golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 72 | golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= 73 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= 74 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 75 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 76 | gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 77 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= 78 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= 79 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 80 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= 81 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 82 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= 83 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 84 | -------------------------------------------------------------------------------- /internal/cmd/cmd.go: -------------------------------------------------------------------------------- 1 | package cmd 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "os" 9 | "os/exec" 10 | "os/user" 11 | "path/filepath" 12 | "regexp" 13 | "runtime" 14 | "strconv" 15 | "strings" 16 | "time" 17 | 18 | "github.com/SoMuchForSubtlety/f1viewer/v2/internal/proxy" 19 | "github.com/SoMuchForSubtlety/f1viewer/v2/internal/util" 20 | "github.com/gdamore/tcell/v2" 21 | ) 22 | 23 | type Store struct { 24 | Commands []Command 25 | MultiCommads []MultiCommand 26 | logger util.Logger 27 | lang []string 28 | accentColor tcell.Color 29 | } 30 | 31 | type commandAndArgs []string 32 | 33 | type Command struct { 34 | Title string `json:"title" toml:"title"` 35 | Command commandAndArgs `json:"command" toml:"command"` 36 | Proxy bool `json:"proxy" toml:"proxy"` 37 | registry string 38 | registry32 string 39 | flatpakAppID string 40 | } 41 | 42 | type MultiCommand struct { 43 | Title string `json:"title,omitempty" toml:"title,omitempty"` 44 | Targets []ChannelMatcher `json:"targets,omitempty" toml:"targets,omitempty"` 45 | } 46 | 47 | type ChannelMatcher struct { 48 | MatchTitle string `json:"match_title,omitempty" toml:"match_title,omitempty"` 49 | Command commandAndArgs `json:"command,omitempty" toml:"command,omitempty"` 50 | CommandKey string `json:"command_key,omitempty" toml:"command_key,omitempty"` 51 | Proxy bool `json:"proxy" toml:"proxy"` 52 | } 53 | 54 | type CommandContext struct { 55 | CustomOptions Command 56 | MetaData MetaData 57 | URL func() (string, error) 58 | } 59 | 60 | // MetaData contains title metadata 61 | type MetaData struct { 62 | PerspectiveTitle string 63 | Event string 64 | Category string 65 | Title string 66 | Session string 67 | Date time.Time 68 | Year string 69 | Country string 70 | Series string 71 | EpisodeNumber int64 72 | OrdinalNumber int64 73 | Circuit string 74 | 75 | Source interface{} 76 | } 77 | 78 | func NewStore(customCommands []Command, multiCommands []MultiCommand, lang []string, logger util.Logger, accentColor tcell.Color) *Store { 79 | store := Store{ 80 | logger: logger, 81 | lang: lang, 82 | accentColor: accentColor, 83 | MultiCommads: multiCommands, 84 | } 85 | 86 | commands := []Command{ 87 | { 88 | Title: "Play with MPV", 89 | Command: []string{"mpv", "$url", "--alang=" + strings.Join(lang, ","), "--quiet", "--title=$title"}, 90 | Proxy: true, 91 | flatpakAppID: "io.mpv.Mpv", 92 | }, 93 | { 94 | Title: "Play with VLC", 95 | registry: "SOFTWARE\\WOW6432Node\\VideoLAN\\VLC", 96 | registry32: "SOFTWARE\\VideoLAN\\VLC", 97 | Command: []string{"vlc", "$url", "--meta-title=$title", "--audio-language=" + strings.Join(lang, ",")}, 98 | flatpakAppID: "org.videolan.VLC", 99 | }, 100 | { 101 | Title: "Play with IINA", 102 | Command: []string{"iina", "--no-stdin", "--keep-running", "$url"}, 103 | Proxy: true, 104 | }, 105 | } 106 | 107 | for _, c := range commands { 108 | _, err := exec.LookPath(c.Command[0]) 109 | if err == nil { 110 | store.Commands = append(store.Commands, c) 111 | } else if c, found := checkRegistry(c); found { 112 | store.Commands = append(store.Commands, c) 113 | } else if c, found := checkFlatpak(c); found { 114 | store.Commands = append(store.Commands, c) 115 | } 116 | } 117 | 118 | if runtime.GOOS == "darwin" { 119 | store.Commands = append(store.Commands, Command{ 120 | Title: "Play with QuickTime Player", 121 | Command: []string{"open", "-a", "quicktime player", "$url"}, 122 | }) 123 | } 124 | 125 | if len(store.Commands) == 0 { 126 | store.logger.Error("No compatible players found, make sure they are in your PATH environmen variable") 127 | } 128 | 129 | store.Commands = append(store.Commands, customCommands...) 130 | 131 | return &store 132 | } 133 | 134 | func (s *Store) GetCommand(multi ChannelMatcher) Command { 135 | if multi.CommandKey != "" { 136 | for _, c := range s.Commands { 137 | if strings.EqualFold(multi.CommandKey, c.Title) { 138 | return c 139 | } 140 | } 141 | } 142 | 143 | return Command{ 144 | Title: "matcher for " + multi.MatchTitle, 145 | Command: multi.Command, 146 | Proxy: multi.Proxy, 147 | } 148 | } 149 | 150 | func (s *Store) RunCommand(cc CommandContext) error { 151 | url, err := cc.URL() 152 | if err != nil { 153 | return fmt.Errorf("could not get video URL: %w", err) 154 | } 155 | 156 | var proxyEnabled bool 157 | ctx, cancel := context.WithCancel(context.Background()) 158 | if cc.CustomOptions.Proxy { 159 | prxy, err := proxy.NewProxyServer(url, s.logger) 160 | switch { 161 | case err != nil && !errors.Is(err, proxy.ErrNotRequired): 162 | cancel() 163 | return err 164 | case err == nil: 165 | tmpUrl, err := prxy.Listen(ctx) 166 | if err != nil { 167 | s.logger.Errorf("failed to start proxy: %s", err) 168 | } else { 169 | s.logger.Info("proxy started") 170 | url = tmpUrl 171 | proxyEnabled = true 172 | } 173 | default: 174 | cancel() 175 | s.logger.Info("proxy not required") 176 | } 177 | } 178 | 179 | // replace variables 180 | tmpCommand := make([]string, len(cc.CustomOptions.Command)) 181 | copy(tmpCommand, cc.CustomOptions.Command) 182 | metadataJson, err := json.MarshalIndent(cc.MetaData, "", "\t") 183 | if err != nil { 184 | s.logger.Error("failed to convert metadata to JSON:", err) 185 | } 186 | for i := range tmpCommand { 187 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$url", url) 188 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$json", string(metadataJson)) 189 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$session", cc.MetaData.Session) 190 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$event", cc.MetaData.Event) 191 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$perspective", cc.MetaData.PerspectiveTitle) 192 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$category", cc.MetaData.Category) 193 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$episodenumber", strconv.FormatInt(cc.MetaData.EpisodeNumber, 10)) 194 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$season", cc.MetaData.Year) 195 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$title", cc.MetaData.Title) 196 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$filename", sanitizeFileName(cc.MetaData.Title)) 197 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$series", cc.MetaData.Series) 198 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$country", cc.MetaData.Country) 199 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$circuit", cc.MetaData.Circuit) 200 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$ordinal", strconv.FormatInt(cc.MetaData.OrdinalNumber, 10)) 201 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$time", cc.MetaData.Date.Format(time.RFC3339)) 202 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$date", cc.MetaData.Date.Format("2006-01-02")) 203 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$year", cc.MetaData.Year) 204 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$month", cc.MetaData.Date.Format("01")) 205 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$day", cc.MetaData.Date.Format("02")) 206 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$hour", cc.MetaData.Date.Format("15")) 207 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$minute", cc.MetaData.Date.Format("04")) 208 | tmpCommand[i] = strings.ReplaceAll(tmpCommand[i], "$lang", strings.Join(s.lang, ",")) 209 | } 210 | 211 | if len(tmpCommand) < 2 { 212 | cancel() 213 | return fmt.Errorf("invalid command %v", tmpCommand) 214 | } 215 | return s.runCmd(exec.Command(tmpCommand[0], tmpCommand[1:]...), proxyEnabled, cancel) 216 | } 217 | 218 | func (s *Store) runCmd(cmd *exec.Cmd, proxy bool, cancel func()) error { 219 | wdir, err := os.Getwd() 220 | if err != nil { 221 | // session.logError("unable to get working directory: ", err) 222 | wdir = "?" 223 | } 224 | user, err := user.Current() 225 | if err == nil { 226 | if wdir == user.HomeDir { 227 | wdir = "~" 228 | } else { 229 | wdir = filepath.Base(wdir) 230 | } 231 | } 232 | 233 | accentColorString := util.ColortoHexString(s.accentColor) 234 | fmt.Fprintf(s.logger, "[%s::b][[-]%s[%s]]$[-::-] %s\n", accentColorString, wdir, accentColorString, strings.Join(cmd.Args, " ")) 235 | 236 | cmd.Stdout = s.logger 237 | cmd.Stderr = s.logger 238 | 239 | err = cmd.Start() 240 | if err != nil { 241 | cancel() 242 | return err 243 | } 244 | if !proxy { 245 | cancel() 246 | return cmd.Process.Release() 247 | } else { 248 | go func() { 249 | _, err := cmd.Process.Wait() 250 | if err != nil { 251 | s.logger.Error("process exited with error: %s", err) 252 | } 253 | cancel() 254 | }() 255 | return nil 256 | } 257 | } 258 | 259 | func sanitizeFileName(s string) string { 260 | whitespace := regexp.MustCompile(`\s+`) 261 | var illegal *regexp.Regexp 262 | if runtime.GOOS == "windows" { 263 | illegal = regexp.MustCompile(`[<>:"/\\|?*]`) 264 | } else { 265 | illegal = regexp.MustCompile(`/`) 266 | } 267 | s = illegal.ReplaceAllString(s, " ") 268 | s = whitespace.ReplaceAllString(s, " ") 269 | s = strings.TrimSpace(s) 270 | return s 271 | } 272 | -------------------------------------------------------------------------------- /internal/cmd/registry.go: -------------------------------------------------------------------------------- 1 | //go:build windows 2 | // +build windows 3 | 4 | package cmd 5 | 6 | import ( 7 | "runtime" 8 | 9 | "golang.org/x/sys/windows/registry" 10 | ) 11 | 12 | func checkRegistry(c Command) (Command, bool) { 13 | regPath := c.registry 14 | if runtime.GOARCH == "386" { 15 | regPath = c.registry32 16 | } 17 | 18 | if regPath == "" { 19 | return c, false 20 | } 21 | 22 | result, err := registry.OpenKey(registry.LOCAL_MACHINE, regPath, registry.QUERY_VALUE) 23 | if err != nil { 24 | return c, false 25 | } 26 | 27 | path, _, err := result.GetStringValue("InstallDir") 28 | if err != nil { 29 | return c, false 30 | } 31 | c.Command[0] = path + "\\" + c.Command[0] 32 | 33 | return c, true 34 | } 35 | 36 | func checkFlatpak(c Command) (Command, bool) { 37 | return c, false 38 | } 39 | -------------------------------------------------------------------------------- /internal/cmd/registry_unix.go: -------------------------------------------------------------------------------- 1 | //go:build !windows 2 | // +build !windows 3 | 4 | package cmd 5 | 6 | import "os/exec" 7 | 8 | func checkRegistry(c Command) (Command, bool) { 9 | _ = c.registry 10 | _ = c.registry32 11 | return c, false 12 | } 13 | 14 | func checkFlatpak(c Command) (Command, bool) { 15 | if c.flatpakAppID == "" { 16 | // command is not flatpak 17 | return c, false 18 | } 19 | 20 | _, err := exec.LookPath("flatpak") 21 | if err != nil { 22 | // flatpak not installed 23 | return c, false 24 | } 25 | 26 | err = exec.Command("flatpak", "info", c.flatpakAppID).Run() 27 | if err != nil { 28 | // package not installed 29 | return c, false 30 | } 31 | 32 | c.Command[0] = c.flatpakAppID 33 | c.Command = append([]string{"flatpak", "run"}, c.Command...) 34 | 35 | return c, true 36 | } 37 | -------------------------------------------------------------------------------- /internal/config/config.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "bytes" 5 | _ "embed" 6 | "encoding/json" 7 | "fmt" 8 | "io/fs" 9 | "io/ioutil" 10 | "log" 11 | "os" 12 | "path" 13 | "path/filepath" 14 | "runtime" 15 | "time" 16 | 17 | "github.com/BurntSushi/toml" 18 | "github.com/SoMuchForSubtlety/f1viewer/v2/internal/cmd" 19 | ) 20 | 21 | type Config struct { 22 | LiveRetryTimeout int `toml:"live_retry_timeout,omitempty"` 23 | Lang []string `toml:"preferred_languages,omitempty"` 24 | CheckUpdate bool `toml:"check_updates,omitempty"` 25 | SaveLogs bool `toml:"save_logs,omitempty,omitempty"` 26 | LogLocation string `toml:"log_location,omitempty"` 27 | CustomPlaybackOptions []cmd.Command `json:"custom_playback_options" toml:"custom_playback_options,omitempty"` 28 | LiveSessionHooks []cmd.MultiCommand `toml:"live_session_hooks,omitempty"` 29 | MultiCommand []cmd.MultiCommand `json:"multi_commands" toml:"multi_commands,omitempty"` 30 | HorizontalLayout bool `toml:"horizontal_layout,omitempty"` 31 | Theme Theme `toml:"theme,omitempty"` 32 | TreeRatio int `toml:"tree_ratio,omitempty"` 33 | OutputRatio int `toml:"output_ratio,omitempty"` 34 | TerminalWrap bool `toml:"terminal_wrap,omitempty"` 35 | DisableTeamColors bool `toml:"disable_team_colors,omitempty"` 36 | EnableMouse bool `toml:"enable_mouse,omitempty"` 37 | } 38 | 39 | type ConversionConfig struct { 40 | CustomPlaybackOptions []cmd.Command `toml:"custom_playback_options,omitempty"` 41 | MultiCommand []cmd.MultiCommand `toml:"multi_commands,omitempty"` 42 | } 43 | 44 | type Theme struct { 45 | BackgroundColor string `toml:"background_color"` 46 | BorderColor string `toml:"border_color"` 47 | CategoryNodeColor string `toml:"category_node_color"` 48 | FolderNodeColor string `toml:"folder_node_color"` 49 | ItemNodeColor string `toml:"item_node_color"` 50 | ActionNodeColor string `toml:"action_node_color"` 51 | LoadingColor string `toml:"loading_color"` 52 | LiveColor string `toml:"live_color"` 53 | UpdateColor string `toml:"update_color"` 54 | NoContentColor string `toml:"no_content_color"` 55 | InfoColor string `toml:"info_color"` 56 | ErrorColor string `toml:"error_color"` 57 | TerminalAccentColor string `toml:"terminal_accent_color"` 58 | TerminalTextColor string `toml:"terminal_text_color"` 59 | MultiCommandColor string `toml:"multi_command_color"` 60 | } 61 | 62 | //go:embed default-config.toml 63 | var defaultConfig []byte 64 | 65 | const ( 66 | configName = "config.toml" 67 | ) 68 | 69 | // Old configs (e.g. the old default config) may be using ISO 639-1 2-letter 70 | // codes. We remap those codes to ISO 639-2 3-letter codes to prevent those 71 | // configs from breaking. 72 | // https://www.iso.org/iso-639-language-codes.html 73 | var languageCodeRemapping = map[string]string{ 74 | "de": "deu", 75 | "fr": "fra", 76 | "es": "spa", 77 | "nl": "nld", 78 | "pt": "por", 79 | "en": "eng", 80 | } 81 | 82 | func customOptsAsToml(path string) ([]byte, error) { 83 | oldCfg, err := os.ReadFile(filepath.Join(path, "config.json")) 84 | if err != nil { 85 | return nil, fmt.Errorf("could not open old config file: %w", err) 86 | } 87 | var tmpCfg Config 88 | err = json.Unmarshal(oldCfg, &tmpCfg) 89 | if err != nil { 90 | return nil, fmt.Errorf("invalid old config: %w", err) 91 | } 92 | tmpCfg2 := ConversionConfig{ 93 | CustomPlaybackOptions: tmpCfg.CustomPlaybackOptions, 94 | MultiCommand: tmpCfg.MultiCommand, 95 | } 96 | var data bytes.Buffer 97 | err = toml.NewEncoder(&data).Encode(tmpCfg2) 98 | if err != nil { 99 | return nil, fmt.Errorf("could not encode old config as toml: %w", err) 100 | } 101 | 102 | return data.Bytes(), nil 103 | } 104 | 105 | func LoadConfig() (Config, error) { 106 | var cfg Config 107 | p, err := GetConfigPath() 108 | if err != nil { 109 | return cfg, err 110 | } 111 | 112 | if _, err = os.Stat(path.Join(p, configName)); os.IsNotExist(err) { 113 | cfgData := defaultConfig 114 | customOptsToml, err := customOptsAsToml(p) 115 | if err == nil { 116 | cfgData = append(cfgData, 0x0A) // newline 117 | cfgData = append(cfgData, customOptsToml...) // add existing custom opts 118 | } 119 | err = os.WriteFile(path.Join(p, configName), cfgData, fs.ModePerm) 120 | if err != nil { 121 | return cfg, err 122 | } 123 | } 124 | 125 | data, err := ioutil.ReadFile(path.Join(p, configName)) 126 | if err != nil { 127 | return cfg, err 128 | } 129 | err = toml.Unmarshal(data, &cfg) 130 | if err != nil { 131 | return cfg, err 132 | } 133 | 134 | if cfg.TreeRatio < 1 { 135 | cfg.TreeRatio = 1 136 | } 137 | if cfg.OutputRatio < 1 { 138 | cfg.OutputRatio = 1 139 | } 140 | 141 | // Remap 2-letter code to 3-letter code 142 | for i, lang := range cfg.Lang { 143 | if val, ok := languageCodeRemapping[lang]; ok { 144 | cfg.Lang[i] = val 145 | } 146 | } 147 | 148 | // TODO: move? 149 | _, err = configureLogging(cfg) 150 | return cfg, err 151 | } 152 | 153 | func GetConfigPath() (string, error) { 154 | p, err := os.UserConfigDir() 155 | if err != nil { 156 | return "", err 157 | } 158 | p = path.Join(p, "f1viewer") 159 | 160 | _, err = os.Stat(p) 161 | if os.IsNotExist(err) { 162 | err = os.MkdirAll(p, os.ModePerm) 163 | } 164 | return p, err 165 | } 166 | 167 | func GetLogPath() (string, error) { 168 | var p string 169 | 170 | // windows, macos 171 | switch runtime.GOOS { 172 | case "windows", "darwin": 173 | configPath, err := GetConfigPath() 174 | if err != nil { 175 | return "", err 176 | } 177 | p = path.Join(configPath, "logs") 178 | default: 179 | // linux, etc. 180 | home, err := os.UserHomeDir() 181 | if err != nil { 182 | return "", err 183 | } 184 | p = path.Join(home, "/.local/share/f1viewer/") 185 | } 186 | 187 | _, err := os.Stat(p) 188 | if os.IsNotExist(err) { 189 | err = os.MkdirAll(p, os.ModePerm) 190 | } 191 | return p, err 192 | } 193 | 194 | func configureLogging(cfg Config) (*os.File, error) { 195 | if !cfg.SaveLogs { 196 | log.SetOutput(ioutil.Discard) 197 | return nil, nil 198 | } 199 | logPath, err := GetLogPath() 200 | if err != nil { 201 | return nil, fmt.Errorf("Could not get log path: %w", err) 202 | } 203 | completePath := path.Join(logPath, time.Now().Format("2006-01-02")+".log") 204 | logFile, err := os.OpenFile(completePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o666) 205 | if err != nil { 206 | return nil, fmt.Errorf("Could not open log file: %w", err) 207 | } 208 | log.SetOutput(logFile) 209 | return logFile, nil 210 | } 211 | -------------------------------------------------------------------------------- /internal/config/default-config.toml: -------------------------------------------------------------------------------- 1 | # notify about new releases 2 | check_updates = true 3 | # don't show driver names in their team's colour 4 | disable_team_colors = false 5 | # show the output at the bottom 6 | horizontal_layout = false 7 | # check for a live F1TV stream every x seconds 8 | live_retry_timeout = 60 9 | # change the size ratio of differen parts 10 | output_ratio = 1 11 | tree_ratio = 1 12 | # set to false to disable mouse input 13 | enable_mouse = true 14 | 15 | # F1TV has not been consistent with the code for their audio tracks, these vaules have been observed in the past 16 | # "deu" -> german 17 | # "fra" -> french 18 | # "spa" -> spanish 19 | # "nld" -> dutch 20 | # "por" -> portugese 21 | # "eng" -> english 22 | # "fx" -> no commentary 23 | # "cfx" -> no commentary 24 | # onboards only: 25 | # "teamradio" -> team radio 26 | # "obc" -> team radio 27 | # list them according to your preference 28 | preferred_languages = ["teamradio", "obc", "eng"] 29 | save_logs = true 30 | # wrap the output of executed commands or cut it off 31 | terminal_wrap = true 32 | 33 | # custom playback options can be used to execute any command, this example uses ffmpeg to donload the video 34 | # [[custom_playback_options]] 35 | # command = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-i", "$url", "-c", "copy", "-f", "mp4", "$title.mp4"] 36 | # proxy = true 37 | # title = "Download as mp4" 38 | 39 | # mult commands can be used to start multiple streams at once, this example starts the F1 Live an the onboard for the GOAT ;) 40 | # [[multi_commands]] 41 | # title = "Open F1 Live and HAM onboard" 42 | # [[multi_commands.targets]] 43 | # command = ["mpv", "$url", "--alang=$lang", "--quiet"] # define a command to execute 44 | # match_title = "F1 Live" 45 | # [[multi_commands.targets]] 46 | # command_key = "custom mpv" # you can also reference previously defined custom commands 47 | # match_title = "Lewis [a-zA-Z]+" # regex is also supported 48 | 49 | # live session hooks are like custom multi commands, but they are automatically started if a new live session is detected 50 | # [[live_session_hooks]] 51 | # title = "Open Pit Lane and Data Channel" 52 | # [[live_session_hooks.targets]] 53 | # command = ["mpv", "$url", "--alang=$lang", "--quiet"] # define a command to execute 54 | # match_title = "Pit Lane" 55 | # [[live_session_hooks.targets]] 56 | # command_key = "custom mpv" # you can also reference previously defined custom commands 57 | # match_title = "Data Channel" 58 | 59 | # you can override the default colours by providing new values in hex format (#RRGGBB) 60 | [theme] 61 | action_node_color = "#008B8B" 62 | background_color = "" 63 | border_color = "#FFFFFF" 64 | category_node_color = "#FF4500" 65 | error_color = "#FF0000" 66 | folder_node_color = "#FFFFFF" 67 | info_color = "#008000" 68 | item_node_color = "#90EE90" 69 | live_color = "#FF0000" 70 | loading_color = "" 71 | multi_command_color = "#7FFFD4" 72 | no_content_color = "#FF4500" 73 | terminal_accent_color = "#008000" 74 | terminal_text_color = "#FFFFFF" 75 | update_color = "#8B0000" 76 | -------------------------------------------------------------------------------- /internal/creds/creds.go: -------------------------------------------------------------------------------- 1 | //go:build !darwin 2 | // +build !darwin 3 | 4 | package creds 5 | 6 | import ( 7 | "fmt" 8 | 9 | "github.com/99designs/keyring" 10 | ) 11 | 12 | const serviceName = "f1viewer" 13 | 14 | func LoadCredentials() (string, string, string, error) { 15 | ring, err := openRing() 16 | if err != nil { 17 | return "", "", "", fmt.Errorf("failed to open secret store: %w", err) 18 | } 19 | 20 | username, err := ring.Get("username") 21 | if err != nil { 22 | return "", "", "", fmt.Errorf("Could not get username: %w", err) 23 | } 24 | 25 | password, err := ring.Get("password") 26 | if err != nil { 27 | return "", "", "", fmt.Errorf("Could not get password: %w", err) 28 | } 29 | 30 | token, err := ring.Get("token") 31 | if err != nil { 32 | return string(username.Data), string(password.Data), "", nil 33 | } 34 | return string(username.Data), string(password.Data), string(token.Data), nil 35 | } 36 | 37 | func SaveCredentials(username, password, token string) error { 38 | ring, err := openRing() 39 | if err != nil { 40 | return fmt.Errorf("failed to open secret store: %w", err) 41 | } 42 | 43 | err = ring.Set(keyring.Item{ 44 | Description: "F1TV username", 45 | Key: "username", 46 | Data: []byte(username), 47 | }) 48 | if err != nil { 49 | return fmt.Errorf("could not save username %w", err) 50 | } 51 | 52 | err = ring.Set(keyring.Item{ 53 | Description: "F1TV password", 54 | Key: "password", 55 | Data: []byte(password), 56 | }) 57 | if err != nil { 58 | return fmt.Errorf("could not save password %w", err) 59 | } 60 | 61 | err = ring.Set(keyring.Item{ 62 | Description: "F1TV subscription token", 63 | Key: "token", 64 | Data: []byte(token), 65 | }) 66 | if err != nil { 67 | return fmt.Errorf("could not save token %w", err) 68 | } 69 | return nil 70 | } 71 | 72 | func RemoveCredentials() error { 73 | ring, err := openRing() 74 | if err != nil { 75 | return fmt.Errorf("failed to open secret store: %w", err) 76 | } 77 | 78 | err = ring.Remove("username") 79 | if err != nil { 80 | return fmt.Errorf("Could not remove username: %w", err) 81 | } 82 | 83 | err = ring.Remove("password") 84 | if err != nil { 85 | return fmt.Errorf("Could not remove password: %w", err) 86 | } 87 | 88 | return nil 89 | } 90 | 91 | func openRing() (keyring.Keyring, error) { 92 | return keyring.Open(keyring.Config{ 93 | ServiceName: serviceName, 94 | AllowedBackends: []keyring.BackendType{ 95 | keyring.PassBackend, 96 | keyring.SecretServiceBackend, 97 | keyring.KWalletBackend, 98 | keyring.WinCredBackend, 99 | }, 100 | }) 101 | } 102 | -------------------------------------------------------------------------------- /internal/creds/creds_darwin.go: -------------------------------------------------------------------------------- 1 | //go:build darwin 2 | // +build darwin 3 | 4 | package creds 5 | 6 | import ( 7 | "fmt" 8 | 9 | "github.com/zalando/go-keyring" 10 | ) 11 | 12 | const ( 13 | serviceName = "f1viewer" 14 | userKey = "username" 15 | passKey = "password" 16 | tokenKey = "token" 17 | ) 18 | 19 | func LoadCredentials() (string, string, string, error) { 20 | username, err := keyring.Get(serviceName, userKey) 21 | if err != nil { 22 | return "", "", "", fmt.Errorf("failed to get username: %w", err) 23 | } 24 | password, err := keyring.Get(serviceName, passKey) 25 | if err != nil { 26 | return "", "", "", fmt.Errorf("failed to get password: %w", err) 27 | } 28 | token, err := keyring.Get(serviceName, tokenKey) 29 | if err != nil { 30 | return username, password, "", nil 31 | } 32 | return username, password, token, nil 33 | } 34 | 35 | func SaveCredentials(username, password, token string) error { 36 | err := keyring.Set(serviceName, userKey, username) 37 | if err != nil { 38 | return fmt.Errorf("failed to save username: %w", err) 39 | } 40 | keyring.Set(serviceName, passKey, password) 41 | if err != nil { 42 | return fmt.Errorf("failed to save password: %w", err) 43 | } 44 | keyring.Set(serviceName, tokenKey, token) 45 | if err != nil { 46 | return fmt.Errorf("failed to save token: %w", err) 47 | } 48 | return nil 49 | } 50 | 51 | func RemoveCredentials() error { 52 | if err := keyring.Delete(serviceName, userKey); err != nil { 53 | return fmt.Errorf("failed to delete username: %w", err) 54 | } 55 | if err := keyring.Delete(serviceName, passKey); err != nil { 56 | return fmt.Errorf("failed to delete password: %w", err) 57 | } 58 | if err := keyring.Delete(serviceName, tokenKey); err != nil { 59 | return fmt.Errorf("failed to delete token: %w", err) 60 | } 61 | return nil 62 | } 63 | -------------------------------------------------------------------------------- /internal/github/update.go: -------------------------------------------------------------------------------- 1 | package github 2 | 3 | import ( 4 | "encoding/json" 5 | "net/http" 6 | ) 7 | 8 | const githubURL = "https://api.github.com/repos/SoMuchForSubtlety/F1viewer/releases/latest" 9 | 10 | type Release struct { 11 | TagName string `json:"tag_name"` 12 | Name string `json:"name"` 13 | Draft bool `json:"draft"` 14 | Prerelease bool `json:"prerelease"` 15 | Body string `json:"body"` 16 | } 17 | 18 | func CheckUpdate(version string) (Release, bool, error) { 19 | resp, err := http.Get(githubURL) 20 | if err != nil { 21 | return Release{}, false, err 22 | } 23 | 24 | var release Release 25 | err = json.NewDecoder(resp.Body).Decode(&release) 26 | if err != nil { 27 | return Release{}, false, err 28 | } 29 | 30 | new := release.TagName != version && 31 | release.TagName != "v"+version && 32 | version != "dev" 33 | 34 | return release, new, nil 35 | } 36 | -------------------------------------------------------------------------------- /internal/proxy/proxy.go: -------------------------------------------------------------------------------- 1 | package proxy 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "errors" 7 | "fmt" 8 | "io" 9 | "math/rand" 10 | "net" 11 | "net/http" 12 | "net/http/cookiejar" 13 | "net/url" 14 | "time" 15 | 16 | "github.com/SoMuchForSubtlety/f1viewer/v2/internal/util" 17 | ) 18 | 19 | const ( 20 | proxyMaxRetries = 10 21 | proxyRetryDelay = 50 * time.Millisecond 22 | ErrNotRequired = ProxyError("domain does not use cookies") 23 | ) 24 | 25 | type ProxyError string 26 | 27 | func (e ProxyError) Error() string { 28 | return string(e) 29 | } 30 | 31 | func init() { 32 | rand.Seed(time.Now().UnixNano()) 33 | } 34 | 35 | func NewProxyServer(streamURL string, logger util.Logger) (*ProxyServer, error) { 36 | proxy, err := newProxy(streamURL, logger) 37 | if err != nil { 38 | return nil, err 39 | } 40 | srv := &ProxyServer{ 41 | srv: http.Server{Handler: proxy}, 42 | log: logger, 43 | path: proxy.url.Path, 44 | } 45 | 46 | return srv, nil 47 | } 48 | 49 | type ProxyServer struct { 50 | srv http.Server 51 | log util.Logger 52 | path string 53 | } 54 | 55 | func (s *ProxyServer) Listen(ctx context.Context) (string, error) { 56 | listener, err := net.Listen("tcp", "127.0.0.1:0") 57 | if err != nil { 58 | return "", fmt.Errorf("failed to start proxy: %w", err) 59 | } 60 | go func() { 61 | err := s.srv.Serve(listener) 62 | if !errors.Is(err, http.ErrServerClosed) { 63 | s.log.Error(err) 64 | } else { 65 | s.log.Info("stopped proxy") 66 | } 67 | }() 68 | 69 | go func() { 70 | <-ctx.Done() 71 | s.log.Info("closing proxy") 72 | if err := s.srv.Close(); err != nil { 73 | s.log.Errorf("failed to stop proxy: %v", err) 74 | } 75 | }() 76 | s.log.Infof("proxy listening at: %s", listener.Addr()) 77 | 78 | return "http://" + listener.Addr().String() + s.path, nil 79 | } 80 | 81 | func newProxy(streamURL string, logger util.Logger) (*proxy, error) { 82 | u, err := url.Parse(streamURL) 83 | if err != nil { 84 | return nil, err 85 | } 86 | 87 | j, _ := cookiejar.New(nil) 88 | c := &http.Client{ 89 | Jar: j, 90 | } 91 | 92 | res, err := c.Get(streamURL) 93 | if err != nil { 94 | return nil, err 95 | } 96 | b, err := io.ReadAll(res.Body) 97 | if err != nil { 98 | return nil, err 99 | } 100 | 101 | if len(j.Cookies(u)) == 0 { 102 | return nil, ErrNotRequired 103 | } 104 | 105 | return &proxy{u, b, c, logger}, nil 106 | } 107 | 108 | type proxy struct { 109 | url *url.URL 110 | playlist []byte 111 | client *http.Client 112 | util.Logger 113 | } 114 | 115 | func (t *proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) { 116 | switch r.URL.Path { 117 | case "/index.m3u8": 118 | http.Redirect(w, r, t.url.Path, http.StatusMovedPermanently) 119 | return 120 | case t.url.Path: 121 | _, err := w.Write(t.playlist) 122 | if err != nil { 123 | t.Errorf("failed to write http response: %v", err) 124 | } 125 | return 126 | } 127 | 128 | u := *r.URL 129 | u.Scheme = t.url.Scheme 130 | u.Host = t.url.Host 131 | 132 | for i := 0; i < proxyMaxRetries; i++ { 133 | res, err := t.client.Get(u.String()) 134 | if err != nil { 135 | t.Errorf("upstream proxy request: %v", err) 136 | time.Sleep(proxyRetryDelay) 137 | continue 138 | } 139 | 140 | if res.StatusCode != http.StatusOK { 141 | t.Errorf("received non 200 response code: %d, %s", res.StatusCode, u.String()) 142 | time.Sleep(proxyRetryDelay) 143 | continue 144 | } 145 | 146 | b := &bytes.Buffer{} 147 | if _, err := io.Copy(b, res.Body); err != nil { 148 | t.Errorf("loading upstream proxy response: %v", err) 149 | time.Sleep(proxyRetryDelay) 150 | continue 151 | } 152 | 153 | if _, err := io.Copy(w, b); err != nil { 154 | t.Errorf("delivering proxy response: %v", err) 155 | http.Error(w, err.Error(), http.StatusInternalServerError) 156 | return 157 | } 158 | return 159 | } 160 | 161 | t.Errorf(`proxy request failed: "%s"`, r.URL) 162 | http.Error(w, "max retries", http.StatusBadGateway) 163 | } 164 | -------------------------------------------------------------------------------- /internal/ui/live.go: -------------------------------------------------------------------------------- 1 | package ui 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/SoMuchForSubtlety/f1viewer/v2/internal/cmd" 7 | "github.com/SoMuchForSubtlety/f1viewer/v2/pkg/f1tv/v2" 8 | ) 9 | 10 | func (s *UIState) checkLive() { 11 | for { 12 | s.logger.Info("checking for live session") 13 | isLive, liveNode, newSessions, err := s.getLiveNode() 14 | switch { 15 | case err != nil: 16 | s.logger.Error("error looking for live session: ", err) 17 | if s.cfg.LiveRetryTimeout <= 0 { 18 | return 19 | } 20 | case isLive: 21 | if len(newSessions) == 0 { 22 | break 23 | } 24 | s.addLiveNode(liveNode) 25 | s.logger.Info("found live event") 26 | 27 | for _, session := range newSessions { 28 | meta := s.extractMetadata(session.Metadata, session.Properties) 29 | details, err := s.v2.ContentDetails(session.Metadata.ContentID) 30 | if err != nil { 31 | s.logger.Errorf("failed to load details for session %s: %v", meta.Title, err) 32 | continue 33 | } 34 | for _, liveHook := range s.cfg.LiveSessionHooks { 35 | s.runLiveHook(liveHook, session, details.Metadata.AdditionalStreams, meta) 36 | } 37 | } 38 | case s.cfg.LiveRetryTimeout <= 0: 39 | s.logger.Info("no live session found") 40 | return 41 | default: 42 | s.addLiveNode(nil) // remove live node 43 | s.logger.Info("no live session found") 44 | } 45 | time.Sleep(time.Second * time.Duration(s.cfg.LiveRetryTimeout)) 46 | } 47 | } 48 | 49 | func (s *UIState) runLiveHook(hook cmd.MultiCommand, mainStream f1tv.ContentContainer, perspectives []f1tv.AdditionalStream, meta cmd.MetaData) { 50 | commands := s.extractCommands(hook, perspectives, mainStream) 51 | // If no streams are matched, continue 52 | if len(commands) == 0 { 53 | return 54 | } 55 | 56 | for _, context := range commands { 57 | err := s.cmd.RunCommand(context) 58 | if err != nil { 59 | s.logger.Error(err) 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /internal/ui/logger.go: -------------------------------------------------------------------------------- 1 | package ui 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | 7 | "github.com/SoMuchForSubtlety/f1viewer/v2/internal/util" 8 | "github.com/rivo/tview" 9 | ) 10 | 11 | type tviewLogger struct { 12 | *tview.TextView 13 | } 14 | 15 | func (s *UIState) Logger() *tviewLogger { 16 | return &tviewLogger{s.textWindow} 17 | } 18 | 19 | func (l *tviewLogger) Errorf(format string, v ...interface{}) { 20 | l.Error(fmt.Sprintf(format, v...)) 21 | } 22 | 23 | func (l *tviewLogger) Error(v ...interface{}) { 24 | fmt.Fprintln(l.TextView, fmt.Sprintf("[%s::b]ERROR:[-::-]", util.ColortoHexString(activeTheme.ErrorColor)), fmt.Sprint(v...)) 25 | log.Println("[ERROR]", fmt.Sprint(v...)) 26 | l.ScrollToEnd() 27 | } 28 | 29 | func (l *tviewLogger) Infof(format string, v ...interface{}) { 30 | l.Info(fmt.Sprintf(format, v...)) 31 | } 32 | 33 | func (l *tviewLogger) Info(v ...interface{}) { 34 | fmt.Fprintln(l.TextView, fmt.Sprintf("[%s::b]INFO:[-::-]", util.ColortoHexString(activeTheme.InfoColor)), fmt.Sprint(v...)) 35 | log.Println("[INFO]", fmt.Sprint(v...)) 36 | l.ScrollToEnd() 37 | } 38 | -------------------------------------------------------------------------------- /internal/ui/node.go: -------------------------------------------------------------------------------- 1 | package ui 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "sync" 7 | 8 | "github.com/SoMuchForSubtlety/f1viewer/v2/internal/cmd" 9 | "github.com/SoMuchForSubtlety/f1viewer/v2/internal/util" 10 | "github.com/SoMuchForSubtlety/f1viewer/v2/pkg/f1tv/v2" 11 | "github.com/atotto/clipboard" 12 | "github.com/gdamore/tcell/v2" 13 | "github.com/rivo/tview" 14 | ) 15 | 16 | // NodeMetadata is used for treenode references and holds metadata about a node 17 | type NodeMetadata struct { 18 | nodeType NodeType 19 | id string 20 | metadata cmd.MetaData 21 | sync.Mutex 22 | } 23 | 24 | // NodeType indicates a treeview node's type 25 | type NodeType int 26 | 27 | // Node types for Metadata 28 | const ( 29 | CategoryNode NodeType = iota 30 | EventNode 31 | PlayableNode 32 | StreamNode 33 | ActionNode 34 | MiscNode 35 | CollectionNode 36 | ) 37 | 38 | func (s *UIState) TreeInputHanlder(keyEvent *tcell.EventKey) *tcell.EventKey { 39 | // only listen for 'r' key 40 | if keyEvent.Key() != tcell.KeyRune || (keyEvent.Rune() != 'r' && keyEvent.Rune() != 'q') { 41 | return keyEvent 42 | } 43 | 44 | if keyEvent.Rune() == 'q' { 45 | s.app.Stop() 46 | return nil 47 | } 48 | 49 | node := s.treeView.GetCurrentNode() 50 | metadata, err := getMetadata(node) 51 | if err != nil { 52 | s.logger.Error(err) 53 | } 54 | 55 | switch metadata.nodeType { 56 | case EventNode: 57 | // TODO: implement refreshing again 58 | return nil 59 | default: 60 | return keyEvent 61 | } 62 | } 63 | 64 | func getMetadata(node *tview.TreeNode) (*NodeMetadata, error) { 65 | if node == nil { 66 | return &NodeMetadata{}, errors.New("node is nil") 67 | } 68 | switch v := node.GetReference().(type) { 69 | case *NodeMetadata: 70 | return v, nil 71 | default: 72 | return &NodeMetadata{}, fmt.Errorf("Node has reference of unexpected type %T", v) 73 | } 74 | } 75 | 76 | func (s *UIState) getPlaybackNodes(sessionTitles cmd.MetaData, getURL func() (string, error)) []*tview.TreeNode { 77 | nodes := make([]*tview.TreeNode, 0) 78 | 79 | for _, c := range s.cmd.Commands { 80 | nodes = append(nodes, s.createCommandNode(sessionTitles, getURL, c)) 81 | } 82 | 83 | // for _, c := range s.cmd.MultiCommads { 84 | // nodes = append(nodes, s.createCommandNode(sessionTitles, getURL, c)) 85 | // } 86 | 87 | clipboardNode := tview.NewTreeNode("Copy URL to clipboard"). 88 | SetColor(activeTheme.ActionNodeColor). 89 | SetReference(&NodeMetadata{nodeType: ActionNode, metadata: sessionTitles}) 90 | clipboardNode.SetSelectedFunc(func() { 91 | url, err := getURL() 92 | if err != nil { 93 | s.logger.Error(err) 94 | return 95 | } 96 | err = clipboard.WriteAll(url) 97 | if err != nil { 98 | s.logger.Error(err) 99 | return 100 | } 101 | s.logger.Info("URL copied to clipboard") 102 | }) 103 | nodes = append(nodes, clipboardNode) 104 | return nodes 105 | } 106 | 107 | func (s *UIState) createCommandNode(t cmd.MetaData, getURL func() (string, error), c cmd.Command) *tview.TreeNode { 108 | context := cmd.CommandContext{ 109 | MetaData: t, 110 | CustomOptions: c, 111 | URL: getURL, 112 | } 113 | node := tview.NewTreeNode(c.Title). 114 | SetColor(activeTheme.ActionNodeColor). 115 | SetReference(&NodeMetadata{nodeType: ActionNode, metadata: t}) 116 | node.SetSelectedFunc(func() { 117 | go func() { 118 | err := s.cmd.RunCommand(context) 119 | if err != nil { 120 | s.logger.Error(err) 121 | } 122 | }() 123 | }) 124 | 125 | return node 126 | } 127 | 128 | func (s *UIState) getLiveNode() (bool, *tview.TreeNode, []f1tv.ContentContainer, error) { 129 | liveVideos, err := s.v2.GetLiveVideoContainers() 130 | if err != nil || len(liveVideos) == 0 { 131 | return false, nil, nil, err 132 | } 133 | 134 | newLiveSessions := make(map[string]struct{}) 135 | var newLiveVideos []f1tv.ContentContainer 136 | for _, v := range liveVideos { 137 | _, ok := s.liveSessions[v.ID] 138 | newLiveSessions[v.ID] = struct{}{} 139 | if !ok { 140 | newLiveVideos = append(newLiveVideos, v) 141 | } 142 | } 143 | s.liveSessions = newLiveSessions 144 | 145 | var nodes []*tview.TreeNode 146 | for _, v := range liveVideos { 147 | streamNode := s.v2ContentNode(v) 148 | streamNode.SetText(v.Metadata.Title + " - LIVE").SetColor(activeTheme.LiveColor) 149 | nodes = append(nodes, streamNode) 150 | } 151 | 152 | if len(nodes) > 1 { 153 | allLive := tview.NewTreeNode("LIVE"). 154 | SetColor(activeTheme.LiveColor). 155 | SetExpanded(false) 156 | appendNodes(allLive, nodes...) 157 | return true, allLive, newLiveVideos, nil 158 | } else { 159 | return true, nodes[0], newLiveVideos, nil 160 | } 161 | } 162 | 163 | func (s *UIState) getPageNodes(id f1tv.PageID) []*tview.TreeNode { 164 | s.logger.Infof("loading page %d", id) 165 | headings, bundles, err := s.v2.GetPageContent(id) 166 | if err != nil { 167 | s.logger.Error(err) 168 | return nil 169 | } 170 | 171 | seenIDs := make(map[f1tv.PageID]struct{}) 172 | 173 | var headingNodes []*tview.TreeNode 174 | for _, h := range headings { 175 | h := h 176 | title := util.FirstNonEmptyString(h.Metadata.Label, h.Metadata.Title, h.RetrieveItems.ResultObj.MeetingName) 177 | 178 | if title == "" { 179 | for _, v := range h.RetrieveItems.ResultObj.Containers { 180 | headingNodes = append(headingNodes, s.v2ContentNode(v)) 181 | } 182 | } else { 183 | headingNode := tview.NewTreeNode(title). 184 | SetColor(activeTheme.CategoryNodeColor). 185 | SetReference(&NodeMetadata{nodeType: CategoryNode}). 186 | SetExpanded(false) 187 | 188 | for _, v := range h.RetrieveItems.ResultObj.Containers { 189 | headingNode.AddChild(s.v2ContentNode(v)) 190 | } 191 | headingNodes = append(headingNodes, headingNode) 192 | } 193 | } 194 | for _, b := range bundles { 195 | b := b 196 | // don't show the same page 197 | _, ok := seenIDs[b.ID] 198 | if !ok { 199 | seenIDs[b.ID] = struct{}{} 200 | } else { 201 | continue 202 | } 203 | headingNode := tview.NewTreeNode(b.Title). 204 | SetColor(activeTheme.FolderNodeColor). 205 | SetReference(&NodeMetadata{nodeType: CategoryNode}). 206 | SetExpanded(false) 207 | 208 | headingNode.SetSelectedFunc(s.withBlink(headingNode, func() { 209 | headingNode.SetSelectedFunc(nil) 210 | appendNodes(headingNode, s.getPageNodes(b.ID)...) 211 | headingNode.SetExpanded(true) 212 | }, nil)) 213 | headingNodes = append(headingNodes, headingNode) 214 | } 215 | 216 | return headingNodes 217 | } 218 | 219 | func appendNodes(parent *tview.TreeNode, children ...*tview.TreeNode) { 220 | for _, node := range children { 221 | if node != nil { 222 | parent.AddChild(node) 223 | } 224 | } 225 | } 226 | 227 | func insertNodeAtTop(parentNode *tview.TreeNode, childNode *tview.TreeNode) { 228 | children := parentNode.GetChildren() 229 | children = append([]*tview.TreeNode{childNode}, children...) 230 | parentNode.SetChildren(children) 231 | } 232 | 233 | func (s *UIState) toggleVisibility(node *tview.TreeNode) { 234 | if len(node.GetChildren()) > 0 { 235 | node.SetExpanded(!node.IsExpanded()) 236 | } 237 | } 238 | -------------------------------------------------------------------------------- /internal/ui/nodeV2.go: -------------------------------------------------------------------------------- 1 | package ui 2 | 3 | import ( 4 | "fmt" 5 | "regexp" 6 | "sort" 7 | "time" 8 | 9 | "github.com/SoMuchForSubtlety/f1viewer/v2/internal/cmd" 10 | "github.com/SoMuchForSubtlety/f1viewer/v2/internal/util" 11 | "github.com/SoMuchForSubtlety/f1viewer/v2/pkg/f1tv/v2" 12 | "github.com/gdamore/tcell/v2" 13 | 14 | "github.com/rivo/tview" 15 | ) 16 | 17 | func (s *UIState) extractMetadata(metadata f1tv.Metadata, properties []f1tv.Properties) cmd.MetaData { 18 | meta := cmd.MetaData{ 19 | Event: util.FirstNonEmptyString(metadata.EmfAttributes.MeetingName, metadata.EmfAttributes.GlobalMeetingName), 20 | Title: util.FirstNonEmptyString(metadata.Title, metadata.EmfAttributes.GlobalTitle, metadata.TitleBrief), 21 | Circuit: util.FirstNonEmptyString(metadata.EmfAttributes.CircuitShortName, metadata.EmfAttributes.CircuitOfficialName), 22 | Year: metadata.Year, 23 | EpisodeNumber: metadata.EpisodeNumber, 24 | Country: util.FirstNonEmptyString(metadata.EmfAttributes.GlobalMeetingCountryName, metadata.EmfAttributes.MeetingCountryName, metadata.Country), 25 | Series: metadata.EmfAttributes.Series, 26 | Session: metadata.TitleBrief, 27 | Source: map[string]interface{}{"metadata": metadata, "properties": properties}, 28 | } 29 | if len(metadata.Genres) > 0 { 30 | meta.Category = metadata.Genres[0] 31 | } 32 | if len(properties) > 0 { 33 | meta.Date = time.Unix(properties[0].SessionStartDate/1000, properties[0].SessionStartDate%1000*1000000) 34 | meta.OrdinalNumber = properties[0].MeetingNumber 35 | } 36 | 37 | return meta 38 | } 39 | 40 | func (s *UIState) v2ContentNode(v f1tv.ContentContainer) *tview.TreeNode { 41 | streamNode := tview.NewTreeNode(util.FirstNonEmptyString( 42 | v.Metadata.Title, 43 | v.Metadata.TitleBrief, 44 | v.Metadata.EmfAttributes.GlobalTitle, 45 | v.Metadata.ShortDescription, 46 | v.Metadata.LongDescription, 47 | )).SetColor(activeTheme.ItemNodeColor). 48 | SetReference(&NodeMetadata{nodeType: StreamNode, id: v.Metadata.ContentID.String(), metadata: s.extractMetadata(v.Metadata, v.Properties)}) 49 | streamNode.SetSelectedFunc(func() { 50 | streamNode.SetSelectedFunc(nil) 51 | 52 | perspectives := s.v2PerspectiveNodes(v) 53 | appendNodes(streamNode, perspectives...) 54 | }) 55 | 56 | return streamNode 57 | } 58 | 59 | func (s *UIState) v2PerspectiveNodes(v f1tv.ContentContainer) []*tview.TreeNode { 60 | meta := s.extractMetadata(v.Metadata, v.Properties) 61 | s.logger.Infof("loading details for %s (%d)", meta.Title, v.Metadata.ContentID) 62 | details, err := s.v2.ContentDetails(v.Metadata.ContentID) 63 | if err != nil { 64 | s.logger.Errorf("could not get content details for '%d': %v", v.Metadata.ContentID, err) 65 | } else { 66 | meta = s.extractMetadata(details.Metadata, details.Properties) 67 | } 68 | 69 | // fall back to just the main stream if there was an error getting details 70 | // or there are no more streams 71 | if err != nil || len(details.Metadata.AdditionalStreams) == 0 { 72 | nodes := s.getPlaybackNodes(meta, func() (string, error) { return s.v2.GetPlaybackURL(f1tv.BIG_SCREEN_HLS, v.Metadata.ContentID, nil) }) 73 | return nodes 74 | } 75 | 76 | streams := details.Metadata.AdditionalStreams 77 | var perspectives []*tview.TreeNode 78 | 79 | sort.Slice(streams, func(i, j int) bool { 80 | if streams[i].TeamName != "" && streams[j].TeamName != "" { 81 | return streams[i].TeamName < streams[j].TeamName 82 | } 83 | if streams[i].TeamName == "" && streams[j].TeamName == "" { 84 | return streams[i].Title < streams[j].Title 85 | } 86 | return streams[i].TeamName == "" 87 | }) 88 | 89 | perspectives = append(perspectives, s.buildPerspectiveNode(meta, activeTheme.ItemNodeColor, "Default", details.ContentID, nil)) 90 | for _, p := range streams { 91 | p := p 92 | color := util.HexStringToColor(p.Hex) 93 | if p.Hex == "" || s.cfg.DisableTeamColors { 94 | color = activeTheme.ItemNodeColor 95 | } 96 | 97 | perspectives = append(perspectives, s.buildPerspectiveNode(meta, color, p.PrettyName(), details.ContentID, &p.ChannelID)) 98 | } 99 | 100 | multicommands := s.v2MultiCommandNodes(streams, v) 101 | return append(multicommands, perspectives...) 102 | } 103 | 104 | func (s *UIState) buildPerspectiveNode(meta cmd.MetaData, color tcell.Color, name string, contentID f1tv.ContentID, channelID *f1tv.ChannelID) *tview.TreeNode { 105 | meta.PerspectiveTitle = name 106 | node := tview.NewTreeNode(name). 107 | SetColor(color). 108 | SetReference(&NodeMetadata{nodeType: PlayableNode, metadata: meta}) 109 | 110 | node.SetSelectedFunc(func() { 111 | node.SetSelectedFunc(nil) 112 | playbackNodes := s.getPlaybackNodes(meta, func() (string, error) { 113 | return s.v2.GetPlaybackURL(f1tv.BIG_SCREEN_HLS, contentID, channelID) 114 | }) 115 | appendNodes(node, playbackNodes...) 116 | }) 117 | 118 | return node 119 | } 120 | 121 | func (s *UIState) v2MultiCommandNodes(perspectives []f1tv.AdditionalStream, mainStream f1tv.ContentContainer) []*tview.TreeNode { 122 | s.logger.Info("checking for multi commands") 123 | if len(s.cfg.MultiCommand) == 0 { 124 | return nil 125 | } 126 | 127 | var nodes []*tview.TreeNode 128 | 129 | for _, multi := range s.cmd.MultiCommads { 130 | s.logger.Infof("checking %q", multi.Title) 131 | commands := s.extractCommands(multi, perspectives, mainStream) 132 | 133 | // If no streams are matched, continue 134 | if len(commands) == 0 { 135 | continue 136 | } 137 | 138 | multiNode := tview.NewTreeNode(multi.Title). 139 | SetColor(activeTheme.MultiCommandColor). 140 | SetReference(&NodeMetadata{nodeType: ActionNode}) 141 | multiNode.SetSelectedFunc(s.withBlink(multiNode, func() { 142 | multiNode.SetSelectedFunc(nil) 143 | for _, context := range commands { 144 | err := s.cmd.RunCommand(context) 145 | if err != nil { 146 | s.logger.Error(err) 147 | } 148 | } 149 | }, nil)) 150 | nodes = append(nodes, multiNode) 151 | } 152 | 153 | return nodes 154 | } 155 | 156 | func (s *UIState) extractCommands(multi cmd.MultiCommand, perspectives []f1tv.AdditionalStream, content f1tv.ContentContainer) []cmd.CommandContext { 157 | var commands []cmd.CommandContext 158 | for _, target := range multi.Targets { 159 | perspective, err := findPerspectiveByName(target.MatchTitle, perspectives, content) 160 | if err != nil { 161 | s.logger.Errorf("could not find streaming matching '%s'", target.MatchTitle) 162 | continue 163 | } 164 | 165 | urlFunc := func() (string, error) { 166 | return s.v2.GetPlaybackURL(f1tv.BIG_SCREEN_HLS, content.Metadata.ContentID, &perspective.ChannelID) 167 | } 168 | 169 | targetCmd := s.cmd.GetCommand(target) 170 | if len(targetCmd.Command) == 0 { 171 | s.logger.Errorf("could not determine command for %q - %q", multi.Title, target.MatchTitle) 172 | continue 173 | } 174 | 175 | meta := s.extractMetadata(content.Metadata, content.Properties) 176 | if perspective != nil { 177 | meta.PerspectiveTitle = perspective.PrettyName() 178 | } 179 | // If we have a match, run the given command! 180 | context := cmd.CommandContext{ 181 | MetaData: meta, 182 | CustomOptions: targetCmd, 183 | URL: urlFunc, 184 | } 185 | commands = append(commands, context) 186 | } 187 | return commands 188 | } 189 | 190 | func findPerspectiveByName(name string, perspectives []f1tv.AdditionalStream, content f1tv.ContentContainer) (*f1tv.AdditionalStream, error) { 191 | notFound := fmt.Errorf("found no perspective matching '%s'", name) 192 | for _, perspective := range perspectives { 193 | if perspective.PrettyName() == name { 194 | return &perspective, nil 195 | } 196 | // if the string doesn't match try regex 197 | r, err := regexp.Compile(name) 198 | if err != nil { 199 | continue 200 | } 201 | if r.MatchString(perspective.PrettyName()) { 202 | return &perspective, nil 203 | } 204 | } 205 | return nil, notFound 206 | } 207 | -------------------------------------------------------------------------------- /internal/ui/node_test.go: -------------------------------------------------------------------------------- 1 | package ui 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/rivo/tview" 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func TestMetadata(t *testing.T) { 11 | node := tview.NewTreeNode("Testing").SetReference(&NodeMetadata{nodeType: MiscNode}) 12 | metadata, err := getMetadata(node) 13 | assert.NoError(t, err) 14 | assert.Equal(t, MiscNode, metadata.nodeType) 15 | 16 | _, err = getMetadata(nil) 17 | assert.EqualError(t, err, "node is nil") 18 | 19 | _, err = getMetadata(tview.NewTreeNode("Testing")) 20 | assert.EqualError(t, err, "Node has reference of unexpected type ") 21 | 22 | _, err = getMetadata(tview.NewTreeNode("Testing").SetReference(123)) 23 | assert.EqualError(t, err, "Node has reference of unexpected type int") 24 | } 25 | -------------------------------------------------------------------------------- /internal/ui/state.go: -------------------------------------------------------------------------------- 1 | package ui 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "strings" 8 | "time" 9 | 10 | "github.com/SoMuchForSubtlety/f1viewer/v2/internal/cmd" 11 | "github.com/SoMuchForSubtlety/f1viewer/v2/internal/config" 12 | "github.com/SoMuchForSubtlety/f1viewer/v2/internal/creds" 13 | "github.com/SoMuchForSubtlety/f1viewer/v2/internal/github" 14 | "github.com/SoMuchForSubtlety/f1viewer/v2/internal/util" 15 | "github.com/SoMuchForSubtlety/f1viewer/v2/pkg/f1tv/v2" 16 | "github.com/gdamore/tcell/v2" 17 | "github.com/rivo/tview" 18 | "github.com/zalando/go-keyring" 19 | ) 20 | 21 | // TODO: rework 22 | var activeTheme = struct { 23 | CategoryNodeColor tcell.Color 24 | FolderNodeColor tcell.Color 25 | ItemNodeColor tcell.Color 26 | ActionNodeColor tcell.Color 27 | LoadingColor tcell.Color 28 | LiveColor tcell.Color 29 | MultiCommandColor tcell.Color 30 | UpdateColor tcell.Color 31 | NoContentColor tcell.Color 32 | InfoColor tcell.Color 33 | ErrorColor tcell.Color 34 | TerminalAccentColor tcell.Color 35 | TerminalTextColor tcell.Color 36 | }{ 37 | CategoryNodeColor: tcell.ColorOrange, 38 | FolderNodeColor: tcell.ColorWhite, 39 | ItemNodeColor: tcell.ColorLightGreen, 40 | ActionNodeColor: tcell.ColorDarkCyan, 41 | LoadingColor: tcell.ColorDarkCyan, 42 | LiveColor: tcell.ColorRed, 43 | MultiCommandColor: tcell.ColorAquaMarine, 44 | UpdateColor: tcell.ColorDarkRed, 45 | NoContentColor: tcell.ColorOrangeRed, 46 | InfoColor: tcell.ColorGreen, 47 | ErrorColor: tcell.ColorRed, 48 | TerminalAccentColor: tcell.ColorGreen, 49 | TerminalTextColor: tview.Styles.PrimaryTextColor, 50 | } 51 | 52 | type UIState struct { 53 | version string 54 | cfg config.Config 55 | 56 | app *tview.Application 57 | 58 | textWindow *tview.TextView 59 | treeView *tview.TreeView 60 | 61 | LiveNode *tview.TreeNode 62 | 63 | logger util.Logger 64 | 65 | // TODO: replace activeTheme 66 | // theme config.Theme 67 | 68 | v2 *f1tv.F1TV 69 | 70 | cmd *cmd.Store 71 | 72 | liveSessions map[string]struct{} 73 | } 74 | 75 | func NewUI(cfg config.Config, version string) *UIState { 76 | ui := UIState{ 77 | version: version, 78 | cfg: cfg, 79 | v2: f1tv.NewF1TV(version), 80 | liveSessions: make(map[string]struct{}), 81 | } 82 | ui.applyTheme(cfg.Theme) 83 | 84 | ui.app = tview.NewApplication() 85 | ui.app.EnableMouse(cfg.EnableMouse) 86 | 87 | root := tview.NewTreeNode("Categories").SetSelectable(false) 88 | 89 | ui.treeView = tview.NewTreeView(). 90 | SetRoot(root). 91 | SetCurrentNode(root). 92 | SetTopLevel(1) 93 | 94 | // refresh supported nodes on 'r' key press or quit on 'q' 95 | ui.treeView.SetInputCapture(ui.TreeInputHanlder) 96 | 97 | ui.textWindow = tview.NewTextView(). 98 | SetWordWrap(false). 99 | SetWrap(cfg.TerminalWrap). 100 | SetDynamicColors(true). 101 | SetChangedFunc(func() { ui.app.Draw() }) 102 | ui.textWindow.SetBorder(true) 103 | 104 | ui.treeView.SetSelectedFunc(ui.toggleVisibility) 105 | 106 | ui.logger = ui.Logger() 107 | 108 | ui.cmd = cmd.NewStore(cfg.CustomPlaybackOptions, cfg.MultiCommand, cfg.Lang, ui.logger, activeTheme.TerminalAccentColor) 109 | 110 | err := ui.loginWithStoredCredentials() 111 | if err != nil { 112 | if !errors.Is(err, keyring.ErrNotFound) { 113 | ui.logger.Errorf("could not get credentials: %s", err.Error()) 114 | } 115 | ui.initUIWithForm() 116 | } else { 117 | ui.logger.Info("logged in!") 118 | ui.initUI() 119 | } 120 | 121 | homepageContent := tview.NewTreeNode("homepage"). 122 | SetColor(activeTheme.CategoryNodeColor). 123 | SetReference(&NodeMetadata{nodeType: CategoryNode, metadata: cmd.MetaData{}}). 124 | SetExpanded(true) 125 | homepageContent.SetSelectedFunc(ui.withBlink(homepageContent, func() { 126 | homepageContent.SetSelectedFunc(nil) 127 | appendNodes(homepageContent, ui.getPageNodes(f1tv.PAGE_HOMEPAGE)...) 128 | }, nil)) 129 | 130 | appendNodes(root, 131 | ui.pageNode(f1tv.PAGE_HOMEPAGE, "Homepage"), 132 | ui.pageNode(f1tv.PAGE_SEASON_2022, "2022 Season"), 133 | ui.pageNode(f1tv.PAGE_ARCHIVE, "Archive"), 134 | ui.pageNode(f1tv.PAGE_DOCUMENTARIES, "Documentaries"), 135 | ui.pageNode(f1tv.PAGE_SHOWS, "Shows"), 136 | ) 137 | 138 | return &ui 139 | } 140 | 141 | func (ui *UIState) pageNode(id f1tv.PageID, title string) *tview.TreeNode { 142 | node := tview.NewTreeNode(title). 143 | SetColor(activeTheme.FolderNodeColor). 144 | SetReference(&NodeMetadata{nodeType: CategoryNode, metadata: cmd.MetaData{}}). 145 | SetExpanded(true) 146 | node.SetSelectedFunc(ui.withBlink(node, func() { 147 | node.SetSelectedFunc(nil) 148 | appendNodes(node, ui.getPageNodes(id)...) 149 | }, nil)) 150 | 151 | return node 152 | } 153 | 154 | func (ui *UIState) Stop() { 155 | ui.app.Stop() 156 | } 157 | 158 | func (ui *UIState) Run() error { 159 | done := make(chan error) 160 | go func() { 161 | done <- ui.app.Run() 162 | }() 163 | 164 | go ui.checkLive() 165 | go ui.loadUpdate() 166 | 167 | logOutNode := tview.NewTreeNode("Log Out"). 168 | SetReference(&NodeMetadata{nodeType: ActionNode}). 169 | SetColor(activeTheme.ActionNodeColor) 170 | logOutNode.SetSelectedFunc(ui.logout) 171 | 172 | ui.treeView.GetRoot().AddChild(logOutNode) 173 | 174 | return <-done 175 | } 176 | 177 | func (s *UIState) logout() { 178 | if err := creds.RemoveCredentials(); err != nil { 179 | s.logger.Error(err) 180 | } 181 | s.initUIWithForm() 182 | } 183 | 184 | func (s *UIState) loginWithStoredCredentials() error { 185 | username, password, token, err := creds.LoadCredentials() 186 | if err != nil { 187 | return err 188 | } 189 | return s.login(username, password, token) 190 | } 191 | 192 | func (s *UIState) login(username, pw, token string) error { 193 | var err error 194 | if token != "" { 195 | token, err = unpackToken(token) 196 | if err != nil { 197 | return err 198 | } 199 | err = s.v2.SetToken(token) 200 | if err == nil { 201 | s.logger.Info("token is valid") 202 | return nil 203 | } 204 | } 205 | err = s.v2.Authenticate(username, pw, s.logger) 206 | return err 207 | } 208 | 209 | func unpackToken(input string) (string, error) { 210 | if !strings.HasPrefix(input, "{") { 211 | return input, nil 212 | } 213 | 214 | var auth f1tv.AuthResp 215 | err := json.Unmarshal([]byte(input), &auth) 216 | if err != nil { 217 | return input, fmt.Errorf("invalid token json: %w", err) 218 | } 219 | 220 | return auth.Data.SubscriptionToken, nil 221 | } 222 | 223 | func (s *UIState) initUIWithForm() { 224 | username, _, _, _ := creds.LoadCredentials() 225 | pw := "" 226 | token := "" 227 | form := tview.NewForm(). 228 | AddInputField("email", username, 30, nil, func(text string) { username = text }). 229 | AddPasswordField("password", "", 30, '*', func(text string) { pw = text }). 230 | AddInputField("token", "", 100, nil, func(text string) { token = text }). 231 | AddButton("test", func() { 232 | err := s.login(username, pw, token) 233 | if err == nil { 234 | s.logger.Info("credentials accepted") 235 | } else { 236 | s.logger.Error(err) 237 | } 238 | }). 239 | AddButton("save", func() { s.closeForm(username, pw, token) }) 240 | 241 | formTreeFlex := tview.NewFlex() 242 | if !s.cfg.HorizontalLayout { 243 | formTreeFlex.SetDirection(tview.FlexRow) 244 | } 245 | 246 | if s.cfg.HorizontalLayout { 247 | formTreeFlex. 248 | AddItem(form, 50, 0, true). 249 | AddItem(s.treeView, 0, 1, false) 250 | } else { 251 | formTreeFlex. 252 | AddItem(form, 9, 0, true). 253 | AddItem(s.treeView, 0, 1, false) 254 | } 255 | 256 | masterFlex := tview.NewFlex() 257 | if s.cfg.HorizontalLayout { 258 | masterFlex.SetDirection(tview.FlexRow) 259 | } 260 | 261 | masterFlex. 262 | AddItem(formTreeFlex, 0, s.cfg.TreeRatio, true). 263 | AddItem(s.textWindow, 0, s.cfg.OutputRatio, false) 264 | 265 | s.app.SetRoot(masterFlex, true) 266 | } 267 | 268 | func (s *UIState) initUI() { 269 | flex := tview.NewFlex(). 270 | AddItem(s.treeView, 0, s.cfg.TreeRatio, true). 271 | AddItem(s.textWindow, 0, s.cfg.OutputRatio, false) 272 | 273 | if s.cfg.HorizontalLayout { 274 | flex.SetDirection(tview.FlexRow) 275 | } 276 | 277 | s.app.SetRoot(flex, true) 278 | } 279 | 280 | func (s *UIState) closeForm(username, pw, token string) { 281 | token, _ = unpackToken(token) 282 | if err := s.login(username, pw, token); err != nil { 283 | s.logger.Error(err) 284 | } 285 | if err := creds.SaveCredentials(username, pw, token); err != nil { 286 | s.logger.Error(err) 287 | } 288 | s.initUI() 289 | } 290 | 291 | func (s *UIState) withBlink(node *tview.TreeNode, fn func(), after func()) func() { 292 | return func() { 293 | done := make(chan struct{}) 294 | go func() { 295 | fn() 296 | done <- struct{}{} 297 | }() 298 | go func() { 299 | s.blinkNode(node, done) 300 | if after != nil { 301 | after() 302 | } 303 | }() 304 | } 305 | } 306 | 307 | func (s *UIState) blinkNode(node *tview.TreeNode, done chan struct{}) { 308 | originalText := node.GetText() 309 | originalColor := node.GetColor() 310 | color1 := originalColor 311 | color2 := activeTheme.LoadingColor 312 | node.SetText("loading...") 313 | 314 | ticker := time.NewTicker(200 * time.Millisecond) 315 | for { 316 | select { 317 | case <-done: 318 | node.SetText(originalText) 319 | node.SetColor(originalColor) 320 | s.app.Draw() 321 | return 322 | case <-ticker.C: 323 | node.SetColor(color2) 324 | s.app.Draw() 325 | color1, color2 = color2, color1 326 | } 327 | } 328 | } 329 | 330 | func (ui *UIState) addLiveNode(newNode *tview.TreeNode) { 331 | if ui.LiveNode != nil { 332 | ui.treeView.GetRoot().RemoveChild(ui.LiveNode) 333 | } 334 | 335 | // newNode if nil if the previous session is no longer live and there is no new live session 336 | if newNode != nil { 337 | ui.LiveNode = newNode 338 | insertNodeAtTop(ui.treeView.GetRoot(), newNode) 339 | } 340 | ui.app.Draw() 341 | } 342 | 343 | func (ui *UIState) loadUpdate() { 344 | release, new, err := github.CheckUpdate(ui.version) 345 | if err != nil { 346 | ui.logger.Error("failed to check for update: ", err) 347 | } 348 | if !new { 349 | return 350 | } 351 | 352 | ui.logger.Info("New version found!") 353 | ui.logger.Info(release.TagName) 354 | fmt.Fprintln(ui.logger, "\n[blue::bu]"+release.Name+"[-::-]") 355 | fmt.Fprintln(ui.logger, release.Body+"\n") 356 | 357 | updateNode := tview.NewTreeNode("UPDATE AVAILABLE"). 358 | SetColor(activeTheme.UpdateColor). 359 | SetExpanded(false) 360 | getUpdateNode := tview.NewTreeNode("download update"). 361 | SetColor(activeTheme.ActionNodeColor). 362 | SetSelectedFunc(func() { 363 | err := util.Open("https://github.com/SoMuchForSubtlety/f1viewer/releases/latest") 364 | if err != nil { 365 | ui.logger.Error(err) 366 | } 367 | }) 368 | 369 | appendNodes(updateNode, getUpdateNode) 370 | insertNodeAtTop(ui.treeView.GetRoot(), updateNode) 371 | } 372 | -------------------------------------------------------------------------------- /internal/ui/theme.go: -------------------------------------------------------------------------------- 1 | package ui 2 | 3 | import ( 4 | "github.com/SoMuchForSubtlety/f1viewer/v2/internal/config" 5 | "github.com/SoMuchForSubtlety/f1viewer/v2/internal/util" 6 | "github.com/gdamore/tcell/v2" 7 | "github.com/rivo/tview" 8 | ) 9 | 10 | // TODO: replace with non global 11 | func (ui *UIState) applyTheme(t config.Theme) { 12 | if t.TerminalTextColor != "" { 13 | tview.Styles.PrimaryTextColor = util.HexStringToColor(t.TerminalTextColor) 14 | } 15 | if t.CategoryNodeColor != "" { 16 | activeTheme.CategoryNodeColor = util.HexStringToColor(t.CategoryNodeColor) 17 | } 18 | if t.FolderNodeColor != "" { 19 | activeTheme.FolderNodeColor = util.HexStringToColor(t.FolderNodeColor) 20 | } 21 | if t.ItemNodeColor != "" { 22 | activeTheme.ItemNodeColor = util.HexStringToColor(t.ItemNodeColor) 23 | } 24 | if t.ActionNodeColor != "" { 25 | activeTheme.ActionNodeColor = util.HexStringToColor(t.ActionNodeColor) 26 | } 27 | if t.BackgroundColor != "" { 28 | tview.Styles.PrimitiveBackgroundColor = util.HexStringToColor(t.BackgroundColor) 29 | } else { 30 | tview.Styles.PrimitiveBackgroundColor = tcell.ColorDefault 31 | } 32 | if t.BorderColor != "" { 33 | tview.Styles.BorderColor = util.HexStringToColor(t.BorderColor) 34 | } 35 | if t.NoContentColor != "" { 36 | activeTheme.NoContentColor = util.HexStringToColor(t.NoContentColor) 37 | } 38 | if t.LoadingColor != "" { 39 | activeTheme.LoadingColor = util.HexStringToColor(t.LoadingColor) 40 | } 41 | if t.LiveColor != "" { 42 | activeTheme.LiveColor = util.HexStringToColor(t.LiveColor) 43 | } 44 | if t.UpdateColor != "" { 45 | activeTheme.UpdateColor = util.HexStringToColor(t.UpdateColor) 46 | } 47 | if t.TerminalAccentColor != "" { 48 | activeTheme.TerminalAccentColor = util.HexStringToColor(t.TerminalAccentColor) 49 | } 50 | if t.TerminalTextColor != "" { 51 | activeTheme.TerminalTextColor = util.HexStringToColor(t.TerminalTextColor) 52 | } 53 | if t.InfoColor != "" { 54 | activeTheme.InfoColor = util.HexStringToColor(t.InfoColor) 55 | } 56 | if t.ErrorColor != "" { 57 | activeTheme.ErrorColor = util.HexStringToColor(t.ErrorColor) 58 | } 59 | if t.MultiCommandColor != "" { 60 | activeTheme.MultiCommandColor = util.HexStringToColor(t.MultiCommandColor) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /internal/util/logger.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import "io" 4 | 5 | type Logger interface { 6 | io.Writer 7 | Infof(msg string, args ...interface{}) 8 | Info(args ...interface{}) 9 | Errorf(msg string, args ...interface{}) 10 | Error(args ...interface{}) 11 | } 12 | -------------------------------------------------------------------------------- /internal/util/util.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "os/exec" 7 | "runtime" 8 | "strconv" 9 | "strings" 10 | 11 | "github.com/gdamore/tcell/v2" 12 | ) 13 | 14 | func Open(url string) error { 15 | var err error 16 | switch runtime.GOOS { 17 | case "linux": 18 | err = exec.Command("xdg-open", url).Start() 19 | case "windows": 20 | err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start() 21 | case "darwin": 22 | err = exec.Command("open", url).Start() 23 | default: 24 | err = fmt.Errorf("unsupported platform") 25 | } 26 | if err != nil { 27 | return err 28 | } 29 | return nil 30 | } 31 | 32 | func HexStringToColor(hex string) tcell.Color { 33 | hex = strings.ReplaceAll(hex, "#", "") 34 | color, _ := strconv.ParseInt(hex, 16, 32) 35 | return tcell.NewHexColor(int32(color)) 36 | } 37 | 38 | func ColortoHexString(color tcell.Color) string { 39 | return fmt.Sprintf("#%06x", color.Hex()) 40 | } 41 | 42 | // takes year/race ID and returns full year and race nuber as strings 43 | func GetYearAndRace(input string) (string, string, error) { 44 | var fullYear string 45 | var raceNumber string 46 | if len(input) < 4 { 47 | return fullYear, raceNumber, errors.New("not long enough") 48 | } 49 | _, err := strconv.Atoi(input[:4]) 50 | if err != nil { 51 | return fullYear, raceNumber, errors.New("not a valid YearRaceID") 52 | } 53 | if input[:4] == "2018" || input[:4] == "2019" { 54 | return input[:4], "0", nil 55 | } 56 | year := input[:2] 57 | intYear, _ := strconv.Atoi(year) 58 | if intYear < 30 { 59 | fullYear = "20" + year 60 | } else { 61 | fullYear = "19" + year 62 | } 63 | raceNumber = input[2:4] 64 | return fullYear, raceNumber, nil 65 | } 66 | 67 | func FirstNonEmptyString(strs ...string) string { 68 | for _, str := range strs { 69 | if str != "" { 70 | return str 71 | } 72 | } 73 | return "" 74 | } 75 | -------------------------------------------------------------------------------- /internal/util/util_test.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | // func TestSanitizeFileName(t *testing.T) { 4 | // t.Parallel() 5 | // title := `file name: "with" \/characters|` 6 | // var target string 7 | // title = sanitizeFileName(title) 8 | // if runtime.GOOS == "windows" { 9 | // target = `file name with illegal characters` 10 | // } else { 11 | // target = `file name: "with" \ characters|` 12 | // } 13 | 14 | // assert.Equal(t, target, title) 15 | // } 16 | 17 | // var colorPairs = []struct { 18 | // hex string 19 | // name string 20 | // }{ 21 | // {hex: "#bc8f8f", name: "rosybrown"}, 22 | // {hex: "#fff5ee", name: "seashell"}, 23 | // {hex: "#00ff7f", name: "springgreen"}, 24 | // {hex: "#ffe4c4", name: "bisque"}, 25 | // {hex: "#2f4f4f", name: "darkslategrey"}, 26 | // {hex: "#b8860b", name: "darkgoldenrod"}, 27 | // {hex: "#e0ffff", name: "lightcyan"}, 28 | // {hex: "#66cdaa", name: "mediumaquamarine"}, 29 | // {hex: "#ffdab9", name: "peachpuff"}, 30 | // {hex: "#f4a460", name: "sandybrown"}, 31 | // {hex: "#d8bfd8", name: "thistle"}, 32 | // {hex: "#d3d3d3", name: "lightgrey"}, 33 | // {hex: "#808080", name: "gray"}, 34 | // {hex: "#a52a2a", name: "brown"}, 35 | // {hex: "#e9967a", name: "darksalmon"}, 36 | // {hex: "#dda0dd", name: "plum"}, 37 | // {hex: "#708090", name: "slategray"}, 38 | // {hex: "#ffffff", name: "white"}, 39 | // } 40 | 41 | // func TestColorToHexString(t *testing.T) { 42 | // t.Parallel() 43 | // for _, s := range colorPairs { 44 | // hex := colortoHexString(tcell.GetColor(s.name)) 45 | // assert.Equal(t, s.hex, hex) 46 | // } 47 | // } 48 | 49 | // func TestHexStringToColor(t *testing.T) { 50 | // t.Parallel() 51 | // for _, s := range colorPairs { 52 | // t.Run(s.name, func(t *testing.T) { 53 | // t.Parallel() 54 | // color := hexStringToColor(s.hex) 55 | // assert.Equal(t, color.Hex(), tcell.GetColor(s.name).Hex()) 56 | // }) 57 | // } 58 | // } 59 | 60 | // func TestWithBlink(t *testing.T) { 61 | // t.Parallel() 62 | // // TODO add check for colors 63 | // originalScreen := ` 64 | // node title┌────────┐ 65 | // │ │ 66 | // │ │ 67 | // │ │ 68 | // └────────┘` 69 | 70 | // loadingScreen := ` 71 | // loading...┌────────┐ 72 | // │ │ 73 | // │ │ 74 | // │ │ 75 | // └────────┘` 76 | 77 | // originalText := "node title" 78 | // originalColor := tcell.ColorViolet 79 | // node := tview.NewTreeNode(originalText) 80 | // node.SetColor(originalColor) 81 | 82 | // simScreen, s := newTestApp(t, 20, 5) 83 | // s.tree.GetRoot().AddChild(node) 84 | // go func() { 85 | // err := s.app.Run() 86 | // assert.NoError(t, err) 87 | // }() 88 | 89 | // go s.withBlink(node, func() { 90 | // time.Sleep(time.Millisecond * 200) 91 | // }, nil)() 92 | 93 | // time.Sleep(time.Millisecond * 100) 94 | // assert.Equal(t, loadingScreen, toTextScreen(simScreen)) 95 | 96 | // time.Sleep(time.Millisecond * 200) 97 | 98 | // assert.Equal(t, originalScreen, toTextScreen(simScreen)) 99 | // assert.Equal(t, originalColor, node.GetColor()) 100 | // assert.Equal(t, originalText, node.GetText()) 101 | 102 | // var wg sync.WaitGroup 103 | // wg.Add(1) 104 | 105 | // go s.withBlink(node, 106 | // func() {}, 107 | // // after function should be executed after the node is restored 108 | // func() { 109 | // assert.Equal(t, originalScreen, toTextScreen(simScreen)) 110 | // assert.Equal(t, originalColor, node.GetColor()) 111 | // assert.Equal(t, originalText, node.GetText()) 112 | // wg.Done() 113 | // })() 114 | // wg.Wait() 115 | // } 116 | 117 | // // func TestGetYearAndRace(t *testing.T) { 118 | // // t.Parallel() 119 | // // // TODO add checks for post 2020 events 120 | // // year, race, err := getYearAndRace("1914_ITA_FP2_F1TV") 121 | // // assert.Nil(t, err) 122 | // // assert.Equal(t, "2019", year) 123 | // // assert.Equal(t, "14", race) 124 | 125 | // // year, race, err = getYearAndRace("9414_ABC") 126 | // // assert.Nil(t, err) 127 | // // assert.Equal(t, "1994", year) 128 | // // assert.Equal(t, "14", race) 129 | 130 | // // year, race, err = getYearAndRace("2018_TEST") 131 | // // assert.Nil(t, err) 132 | // // assert.Equal(t, "2018", year) 133 | // // assert.Equal(t, "0", race) 134 | 135 | // // _, _, err = getYearAndRace("abcde") 136 | // // assert.EqualError(t, err, "not a valid YearRaceID") 137 | 138 | // // _, _, err = getYearAndRace("123") 139 | // // assert.EqualError(t, err, "not long enough") 140 | // // } 141 | 142 | // func TestLog(t *testing.T) { 143 | // t.Parallel() 144 | // expectedInfo := ` 145 | // ┌─────────────┐ 146 | // │INFO: info │ 147 | // │ │ 148 | // │ │ 149 | // └─────────────┘` 150 | 151 | // expectedError := ` 152 | // ┌─────────────┐ 153 | // │INFO: info │ 154 | // │ERROR: test │ 155 | // │ │ 156 | // └─────────────┘` 157 | 158 | // simScreen, s := newTestApp(t, 30, 5) 159 | // go func() { 160 | // err := s.app.Run() 161 | // assert.NoError(t, err) 162 | // }() 163 | // s.logInfo("info") 164 | // time.Sleep(time.Millisecond * 100) 165 | // assert.Equal(t, expectedInfo, toTextScreen(simScreen)) 166 | // s.logError(errors.New("test")) 167 | // time.Sleep(time.Millisecond * 100) 168 | // assert.Equal(t, expectedError, toTextScreen(simScreen)) 169 | // } 170 | 171 | // func toTextScreen(screen tcell.SimulationScreen) string { 172 | // content := "\n" 173 | // contents, width, _ := screen.GetContents() 174 | // var cursor int 175 | // for _, cell := range contents { 176 | // if cursor >= width { 177 | // content += "\n" 178 | // cursor = 0 179 | // } 180 | // content += string(cell.Bytes) 181 | // cursor++ 182 | // } 183 | // return content 184 | // } 185 | 186 | // func newTestApp(t *testing.T, x, y int) (tcell.SimulationScreen, viewerSession) { 187 | // simScreen := tcell.NewSimulationScreen("UTF-8") 188 | // err := simScreen.Init() 189 | // assert.NoError(t, err) 190 | // simScreen.SetSize(x, y) 191 | 192 | // app := tview.NewApplication() 193 | // app.SetScreen(simScreen) 194 | 195 | // text := tview.NewTextView(). 196 | // SetWordWrap(false). 197 | // SetWrap(false). 198 | // SetDynamicColors(true). 199 | // SetChangedFunc(func() { 200 | // app.Draw() 201 | // }) 202 | 203 | // text.SetBorder(true) 204 | 205 | // tree := tview.NewTreeView(). 206 | // SetRoot(tview.NewTreeNode("root")). 207 | // SetTopLevel(1) 208 | 209 | // flex := tview.NewFlex() 210 | // flex.AddItem(tree, 0, 1, true) 211 | // flex.AddItem(text, 0, 1, false) 212 | 213 | // app.SetRoot(flex, true) 214 | 215 | // return simScreen, viewerSession{tree: tree, app: app, textWindow: text} 216 | // } 217 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "os" 7 | "os/signal" 8 | "path" 9 | "syscall" 10 | 11 | "github.com/SoMuchForSubtlety/f1viewer/v2/internal/config" 12 | "github.com/SoMuchForSubtlety/f1viewer/v2/internal/ui" 13 | "github.com/SoMuchForSubtlety/f1viewer/v2/internal/util" 14 | ) 15 | 16 | var ( 17 | version = "dev" 18 | commit = "" 19 | date = "" 20 | ) 21 | 22 | func main() { 23 | var showVersion bool 24 | var openConfig bool 25 | var openLogs bool 26 | flag.BoolVar(&showVersion, "v", showVersion, "show version information") 27 | flag.BoolVar(&showVersion, "version", showVersion, "show version information") 28 | flag.BoolVar(&openConfig, "config", openConfig, "open config file") 29 | flag.BoolVar(&openLogs, "logs", openLogs, "open logs directory") 30 | flag.Parse() 31 | if showVersion { 32 | fmt.Println(buildVersion()) 33 | return 34 | } 35 | cfg, err := config.LoadConfig() 36 | if err != nil { 37 | fmt.Printf("Could not open config: %v\n", err) 38 | os.Exit(1) 39 | } 40 | if openConfig { 41 | cfgPath, err := config.GetConfigPath() 42 | if err != nil { 43 | fmt.Println(err) 44 | os.Exit(1) 45 | } 46 | err = util.Open(path.Join(cfgPath, "config.toml")) 47 | if err != nil { 48 | fmt.Println(err) 49 | os.Exit(1) 50 | } 51 | return 52 | } 53 | if openLogs { 54 | logPath, err := config.GetLogPath() 55 | if err != nil { 56 | fmt.Println(err) 57 | os.Exit(1) 58 | } 59 | err = util.Open(logPath) 60 | if err != nil { 61 | fmt.Println(err) 62 | os.Exit(1) 63 | } 64 | return 65 | } 66 | 67 | ui := ui.NewUI(cfg, version) 68 | go func() { 69 | if err := ui.Run(); err != nil { 70 | fmt.Println(err) 71 | os.Exit(1) 72 | } 73 | os.Exit(0) 74 | }() 75 | 76 | c := make(chan os.Signal, 1) 77 | signal.Notify(c, os.Interrupt, syscall.SIGTERM) 78 | 79 | <-c 80 | 81 | ui.Stop() 82 | } 83 | 84 | func buildVersion() string { 85 | result := fmt.Sprintf("Version: %s", version) 86 | if commit != "" { 87 | result += fmt.Sprintf("\nGit commit: %s", commit) 88 | } 89 | if date != "" { 90 | result += fmt.Sprintf("\nBuilt: %s", date) 91 | } 92 | return result 93 | } 94 | -------------------------------------------------------------------------------- /pkg/f1tv/v2/api.go: -------------------------------------------------------------------------------- 1 | package f1tv 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "net/http" 9 | "net/url" 10 | "runtime" 11 | "sort" 12 | "strconv" 13 | "strings" 14 | 15 | "github.com/SoMuchForSubtlety/f1viewer/v2/internal/util" 16 | ) 17 | 18 | const ( 19 | baseURL = "https://f1tv.formula1.com" 20 | authURL = "https://api.formula1.com/v2/account/subscriber/authenticate/by-password" 21 | 22 | playbackRequestPath = "/2.0/R/ENG/%v/ALL/CONTENT/PLAY" 23 | contentDetailsPath = "/3.0/R/ENG/%v/ALL/CONTENT/VIDEO/%d/F1_TV_Pro_Annual/14" 24 | categoryPagePath = "/2.0/R/ENG/%v/ALL/PAGE/%v/F1_TV_Pro_Annual/14" 25 | 26 | apiKey = "fCUCjWrKPu9ylJwRAv8BpGLEgiAuThx7" 27 | 28 | BIG_SCREEN_HLS StreamType = "BIG_SCREEN_HLS" 29 | WEB_HLS StreamType = "WEB_HLS" 30 | TABLET_HLS StreamType = "TABLET_HLS" 31 | MOBILE_HLS StreamType = "MOBILE_HLS" 32 | BIG_SCREEN_DASH StreamType = "BIG_SCREEN_DASH" 33 | WEB_DASH StreamType = "WEB_DASH" 34 | MOBILE_DASH StreamType = "MOBILE_DASH" 35 | TABLET_DASH StreamType = "TABLET_DASH" 36 | 37 | PAGE_HOMEPAGE PageID = 395 38 | PAGE_ARCHIVE PageID = 493 39 | PAGE_SHOWS PageID = 410 40 | PAGE_DOCUMENTARIES PageID = 413 41 | PAGE_SEASON_2022 PageID = 4319 42 | 43 | VIDEO ContentType = "VIDEO" 44 | BUNDLE ContentType = "BUNDLE" 45 | LAUNCHER ContentType = "LAUNCHER" 46 | 47 | LIVE ContentSubType = "LIVE" 48 | REPLAY ContentSubType = "REPLAY" 49 | ) 50 | 51 | type ( 52 | ContentType string 53 | ContentSubType string 54 | StreamType string 55 | 56 | PageID int64 57 | ContentID int64 58 | ChannelID int64 59 | ) 60 | 61 | func (c ContentID) String() string { 62 | return strconv.FormatInt(int64(c), 10) 63 | } 64 | 65 | func (c ChannelID) String() string { 66 | return strconv.FormatInt(int64(c), 10) 67 | } 68 | 69 | func assembleURL(urlPath string, format StreamType, args ...interface{}) (*url.URL, error) { 70 | args = append([]interface{}{format}, args...) 71 | return url.Parse(baseURL + fmt.Sprintf(urlPath, args...)) 72 | } 73 | 74 | type F1TV struct { 75 | SubscriptionToken string 76 | userAgent string 77 | Client *http.Client 78 | } 79 | 80 | func NewF1TV(version string) *F1TV { 81 | return &F1TV{ 82 | userAgent: fmt.Sprintf("f1viewer/%s (%s)", version, runtime.GOOS), 83 | Client: http.DefaultClient, 84 | } 85 | } 86 | 87 | func (f *F1TV) SetToken(token string) error { 88 | f.SubscriptionToken = token 89 | _, err := f.GetPlaybackURL(BIG_SCREEN_HLS, 1000003967, nil) 90 | if err != nil { 91 | return fmt.Errorf("invalid token: %w", err) 92 | } 93 | return nil 94 | } 95 | 96 | type AuthResp struct { 97 | Data struct { 98 | SubscriptionStatus string `json:"subscriptionStatus"` 99 | SubscriptionToken string `json:"subscriptionToken"` 100 | } `json:"data"` 101 | } 102 | 103 | func (f *F1TV) Authenticate(username, password string, logger util.Logger) error { 104 | type request struct { 105 | Login string `json:"Login"` 106 | Password string `json:"Password"` 107 | } 108 | 109 | payloadBuf := new(bytes.Buffer) 110 | err := json.NewEncoder(payloadBuf).Encode(request{Login: username, Password: password}) 111 | if err != nil { 112 | return err 113 | } 114 | req, err := http.NewRequest(http.MethodPost, authURL, payloadBuf) 115 | req.Header.Set("apiKey", apiKey) 116 | req.Header.Set("User-Agent", "RaceControl f1viewer") 117 | if err != nil { 118 | return err 119 | } 120 | 121 | resp, err := f.Client.Do(req) 122 | if err != nil { 123 | return err 124 | } 125 | var auth AuthResp 126 | 127 | err = json.NewDecoder(resp.Body).Decode(&auth) 128 | logger.Infof("subscription status: %s", auth.Data.SubscriptionStatus) 129 | if auth.Data.SubscriptionToken == "" { 130 | return errors.New("could not get subscription token") 131 | } 132 | f.SubscriptionToken = auth.Data.SubscriptionToken 133 | return err 134 | } 135 | 136 | func (f *F1TV) GetContent(format StreamType, category PageID, v interface{}) error { 137 | reqURL, err := assembleURL(categoryPagePath, format, category) 138 | if err != nil { 139 | return err 140 | } 141 | req, err := http.NewRequest(http.MethodGet, reqURL.String(), nil) 142 | if err != nil { 143 | return err 144 | } 145 | resp, err := f.Client.Do(req) 146 | if err != nil { 147 | return fmt.Errorf("error during request: %w", err) 148 | } 149 | 150 | return json.NewDecoder(resp.Body).Decode(v) 151 | } 152 | 153 | type RemoteContent struct { 154 | ID PageID 155 | Title string 156 | Ordinal string 157 | } 158 | 159 | func (f *F1TV) GetPageContent(id PageID) ([]TopContainer, []RemoteContent, error) { 160 | var resp APIResponse 161 | err := f.GetContent(WEB_DASH, id, &resp) 162 | if err != nil { 163 | return nil, nil, err 164 | } 165 | 166 | var content []TopContainer 167 | var bundles []RemoteContent 168 | for _, container := range resp.ResultObj.Containers { 169 | var videoContainers []ContentContainer 170 | for _, contentContainer := range container.RetrieveItems.ResultObj.Containers { 171 | switch contentContainer.Metadata.ContentType { 172 | case VIDEO: 173 | videoContainers = append(videoContainers, contentContainer) 174 | case BUNDLE: 175 | if contentContainer.Metadata.EmfAttributes.PageID == id { 176 | // we don't need recusion 177 | continue 178 | } 179 | title := util.FirstNonEmptyString( 180 | contentContainer.Metadata.EmfAttributes.MeetingName, 181 | contentContainer.Metadata.EmfAttributes.GlobalMeetingName, 182 | contentContainer.Metadata.EmfAttributes.GlobalTitle, 183 | contentContainer.Metadata.EmfAttributes.MeetingOfficialName, 184 | contentContainer.Metadata.Label, 185 | contentContainer.Metadata.Title, 186 | ) 187 | 188 | bundles = append(bundles, RemoteContent{ 189 | ID: contentContainer.Metadata.EmfAttributes.PageID, 190 | Title: title, 191 | Ordinal: fmt.Sprintf("%5s", contentContainer.Metadata.EmfAttributes.ChampionshipMeetingOrdinal), 192 | }) 193 | case LAUNCHER: 194 | if len(contentContainer.Actions) == 0 || contentContainer.Actions[0].HREF == "" { 195 | continue 196 | } 197 | title := util.FirstNonEmptyString( 198 | contentContainer.Metadata.EmfAttributes.MeetingName, 199 | contentContainer.Metadata.EmfAttributes.GlobalMeetingName, 200 | contentContainer.Metadata.EmfAttributes.GlobalTitle, 201 | contentContainer.Metadata.EmfAttributes.MeetingOfficialName, 202 | contentContainer.Metadata.Label, 203 | contentContainer.Metadata.Title, 204 | ) 205 | idString := strings.Split(contentContainer.Actions[0].HREF, "/")[2] 206 | id, err := strconv.ParseInt(idString, 10, 64) 207 | if err != nil { 208 | continue 209 | } 210 | bundles = append(bundles, RemoteContent{ 211 | ID: PageID(id), 212 | Title: title, 213 | Ordinal: fmt.Sprintf("%5s", contentContainer.Metadata.EmfAttributes.ChampionshipMeetingOrdinal), 214 | }) 215 | } 216 | } 217 | container.RetrieveItems.ResultObj.Containers = videoContainers 218 | if len(videoContainers) > 0 { 219 | content = append(content, container) 220 | } 221 | sort.Slice(bundles, func(i, j int) bool { 222 | switch { 223 | case bundles[i].Ordinal == " " && bundles[j].Ordinal == " ": 224 | return bundles[i].Title > bundles[j].Title 225 | case bundles[i].Ordinal == " ": 226 | return true 227 | case bundles[j].Ordinal == " ": 228 | return false 229 | default: 230 | return bundles[i].Ordinal < bundles[j].Ordinal 231 | } 232 | }) 233 | } 234 | 235 | return content, bundles, err 236 | } 237 | 238 | func (s AdditionalStream) PrettyName() string { 239 | switch s.Title { 240 | case "F1 LIVE": 241 | return "F1 Live" 242 | case "TRACKER": 243 | return "Driver Tracker" 244 | case "DATA": 245 | return "Data Channel" 246 | case "INTERNATIONAL": 247 | return "International" 248 | case "PIT LANE": 249 | return "Pit Lane" 250 | default: 251 | if s.DriverFirstName == "" && s.DriverLastName == "" { 252 | return s.Title 253 | } 254 | return fmt.Sprintf("%s %s", s.DriverFirstName, s.DriverLastName) 255 | } 256 | } 257 | 258 | func (f *F1TV) GetLiveVideoContainers() ([]ContentContainer, error) { 259 | topContainers, _, err := f.GetPageContent(PAGE_HOMEPAGE) 260 | if err != nil { 261 | return nil, err 262 | } 263 | var live []ContentContainer 264 | ids := make(map[ContentID]struct{}) 265 | for _, vidContainers := range topContainers { 266 | for _, v := range vidContainers.RetrieveItems.ResultObj.Containers { 267 | _, ok := ids[v.Metadata.ContentID] 268 | if !ok && v.Metadata.ContentSubtype == LIVE { 269 | ids[v.Metadata.ContentID] = struct{}{} 270 | live = append(live, v) 271 | } 272 | } 273 | } 274 | 275 | return live, nil 276 | } 277 | 278 | func (f *F1TV) ContentDetails(contentID ContentID) (TopContainer, error) { 279 | reqURL, err := assembleURL(contentDetailsPath, BIG_SCREEN_HLS, contentID) 280 | if err != nil { 281 | return TopContainer{}, err 282 | } 283 | req, err := http.NewRequest(http.MethodGet, reqURL.String(), nil) 284 | if err != nil { 285 | return TopContainer{}, err 286 | } 287 | 288 | resp, err := f.Client.Do(req) 289 | if err != nil { 290 | return TopContainer{}, err 291 | } 292 | defer resp.Body.Close() 293 | 294 | var details APIResponse 295 | err = json.NewDecoder(resp.Body).Decode(&details) 296 | 297 | if resp.StatusCode < 200 || resp.StatusCode >= 300 { 298 | return TopContainer{}, fmt.Errorf("got status code %d: %s", resp.StatusCode, details.Message) 299 | } 300 | 301 | if len(details.ResultObj.Containers) == 0 { 302 | return TopContainer{}, fmt.Errorf("no content details for %d", contentID) 303 | } 304 | return details.ResultObj.Containers[0], err 305 | } 306 | 307 | func (f *F1TV) GetPlaybackURL(format StreamType, contentID ContentID, channelID *ChannelID) (string, error) { 308 | reqURL, err := assembleURL(playbackRequestPath, format) 309 | if err != nil { 310 | return "", nil 311 | } 312 | query := reqURL.Query() 313 | query.Add("contentId", contentID.String()) 314 | if channelID != nil { 315 | query.Add("channelId", channelID.String()) 316 | } 317 | reqURL.RawQuery = query.Encode() 318 | 319 | return f.playbackURL(reqURL.String()) 320 | } 321 | 322 | func (f *F1TV) playbackURL(reqURL string) (string, error) { 323 | req, err := http.NewRequest(http.MethodGet, reqURL, nil) 324 | if err != nil { 325 | return "", nil 326 | } 327 | 328 | req.Header.Set("ascendontoken", f.SubscriptionToken) 329 | httpResp, err := http.DefaultClient.Do(req) 330 | if err != nil { 331 | return "", err 332 | } 333 | 334 | var resp struct { 335 | ResultCode string `json:"resultCode"` 336 | Message string `json:"message"` 337 | ErrorDescription string `json:"errorDescription"` 338 | ResultObj struct { 339 | EntitlementToken string `json:"entitlementToken"` 340 | URL string `json:"url"` 341 | StreamType string `json:"streamType"` 342 | } `json:"resultObj"` 343 | SystemTime int64 `json:"systemTime"` 344 | } 345 | 346 | err = json.NewDecoder(httpResp.Body).Decode(&resp) 347 | if err != nil { 348 | return "", err 349 | } 350 | 351 | if httpResp.StatusCode < 200 || httpResp.StatusCode >= 300 { 352 | err = errors.New(resp.Message) 353 | } else if resp.ResultObj.URL == "" { 354 | err = fmt.Errorf("API returned empty URL: %s", resp.Message) 355 | } 356 | 357 | return resp.ResultObj.URL, err 358 | } 359 | -------------------------------------------------------------------------------- /pkg/f1tv/v2/models.go: -------------------------------------------------------------------------------- 1 | package f1tv 2 | 3 | type APIResponse struct { 4 | ResultCode string `json:"resultCode,omitempty"` 5 | Message string `json:"message,omitempty"` 6 | ErrorDescription string `json:"errorDescription,omitempty"` 7 | ResultObj ResultObj `json:"resultObj,omitempty"` 8 | SystemTime int64 `json:"systemTime,omitempty"` 9 | Source string `json:"source,omitempty"` 10 | } 11 | 12 | type Category struct { 13 | ExternalPathIds []string `json:"externalPathIds,omitempty"` 14 | StartDate int64 `json:"startDate,omitempty"` 15 | CategoryID int `json:"categoryId,omitempty"` 16 | EndDate int64 `json:"endDate,omitempty"` 17 | CategoryPathIds []int `json:"categoryPathIds,omitempty"` 18 | OrderID int `json:"orderId,omitempty"` 19 | IsPrimary bool `json:"isPrimary,omitempty"` 20 | CategoryName string `json:"categoryName,omitempty"` 21 | } 22 | 23 | type Bundles struct { 24 | BundleID int `json:"bundleId,omitempty"` 25 | BundleType string `json:"bundleType,omitempty"` 26 | BundleSubtype string `json:"bundleSubtype,omitempty"` 27 | IsParent bool `json:"isParent,omitempty"` 28 | OrderID int `json:"orderId,omitempty"` 29 | } 30 | 31 | type TechnicalPackage struct { 32 | PackageID int `json:"packageId,omitempty"` 33 | PackageName string `json:"packageName,omitempty"` 34 | PackageType string `json:"packageType,omitempty"` 35 | } 36 | 37 | type PlatformVariants struct { 38 | SubtitlesLanguages []interface{} `json:"subtitlesLanguages,omitempty"` 39 | AudioLanguages []interface{} `json:"audioLanguages,omitempty"` 40 | TechnicalPackages []TechnicalPackage `json:"technicalPackages,omitempty"` 41 | CpID int `json:"cpId,omitempty"` 42 | VideoType string `json:"videoType,omitempty"` 43 | PictureURL string `json:"pictureUrl,omitempty"` 44 | TrailerURL string `json:"trailerUrl,omitempty"` 45 | HasTrailer bool `json:"hasTrailer,omitempty"` 46 | } 47 | 48 | type Properties struct { 49 | MeetingNumber int64 `json:"meeting_Number,omitempty"` 50 | SessionEndTime int64 `json:"sessionEndTime,omitempty"` 51 | Series string `json:"series,omitempty"` 52 | LastUpdatedDate int64 `json:"lastUpdatedDate,omitempty"` 53 | SeasonMeetingOrdinal int64 `json:"season_Meeting_Ordinal,omitempty"` 54 | MeetingStartDate int64 `json:"meeting_Start_Date,omitempty"` 55 | MeetingEndDate int64 `json:"meeting_End_Date,omitempty"` 56 | Season int64 `json:"season,omitempty"` 57 | SessionIndex int64 `json:"session_index,omitempty"` 58 | SessionStartDate int64 `json:"sessionStartDate,omitempty"` 59 | MeetingSessionKey int64 `json:"meetingSessionKey,omitempty"` 60 | SessionEndDate int64 `json:"sessionEndDate,omitempty"` 61 | } 62 | 63 | type EmfAttributes struct { 64 | VideoType string `json:"VideoType,omitempty"` 65 | MeetingKey string `json:"MeetingKey,omitempty"` 66 | MeetingSessionKey string `json:"MeetingSessionKey,omitempty"` 67 | MeetingName string `json:"Meeting_Name,omitempty"` 68 | MeetingNumber string `json:"Meeting_Number,omitempty"` 69 | CircuitShortName string `json:"Circuit_Short_Name,omitempty"` 70 | MeetingCode string `json:"Meeting_Code,omitempty"` 71 | MeetingCountryKey string `json:"MeetingCountryKey,omitempty"` 72 | CircuitKey string `json:"CircuitKey,omitempty"` 73 | MeetingLocation string `json:"Meeting_Location,omitempty"` 74 | Series string `json:"Series,omitempty"` 75 | OBC bool `json:"OBC,omitempty"` 76 | State string `json:"state,omitempty"` 77 | TimetableKey string `json:"TimetableKey,omitempty"` 78 | SessionKey string `json:"SessionKey,omitempty"` 79 | SessionPeriod string `json:"SessionPeriod,omitempty"` 80 | CircuitOfficialName string `json:"Circuit_Official_Name,omitempty"` 81 | ActivityDescription string `json:"ActivityDescription,omitempty"` 82 | SeriesMeetingSessionIdentifier string `json:"SeriesMeetingSessionIdentifier,omitempty"` 83 | SessionEndTime string `json:"sessionEndTime,omitempty"` 84 | MeetingStartDate string `json:"Meeting_Start_Date,omitempty"` 85 | MeetingEndDate string `json:"Meeting_End_Date,omitempty"` 86 | TrackLength string `json:"Track_Length,omitempty"` 87 | ScheduledLapCount string `json:"Scheduled_Lap_Count,omitempty"` 88 | ScheduledDistance string `json:"Scheduled_Distance,omitempty"` 89 | CircuitLocation string `json:"Circuit_Location,omitempty"` 90 | MeetingSponsor string `json:"Meeting_Sponsor,omitempty"` 91 | IsTestEvent string `json:"IsTestEvent,omitempty"` 92 | ChampionshipMeetingOrdinal string `json:"Championship_Meeting_Ordinal,omitempty"` 93 | MeetingOfficialName string `json:"Meeting_Official_Name,omitempty"` 94 | MeetingDisplayDate string `json:"Meeting_Display_Date,omitempty"` 95 | PageID PageID `json:"PageID,omitempty"` 96 | MeetingCountryName string `json:"Meeting_Country_Name,omitempty"` 97 | GlobalTitle string `json:"Global_Title,omitempty"` 98 | GlobalMeetingCountryName string `json:"Global_Meeting_Country_Name,omitempty"` 99 | GlobalMeetingName string `json:"Global_Meeting_Name,omitempty"` 100 | DriversID string `json:"Drivers_ID,omitempty"` 101 | Year string `json:"Year,omitempty"` 102 | TeamsID string `json:"Teams_ID,omitempty"` 103 | // inconsistent types 104 | // SeasonMeetingOrdinal int64 `json:"Season_Meeting_Ordinal,omitempty"` 105 | // SessionStartDate int64 `json:"sessionStartDate,omitempty"` 106 | // SessionEndDate int64 `json:"sessionEndDate,omitempty"` 107 | // SessionIndex int64 `json:"session_index,omitempty"` 108 | } 109 | 110 | type Language []struct { 111 | LanguageCode string `json:"languageCode,omitempty"` 112 | LanguageName string `json:"languageName,omitempty"` 113 | } 114 | 115 | type Metadata struct { 116 | EmfAttributes EmfAttributes `json:"emfAttributes,omitempty"` 117 | LongDescription string `json:"longDescription,omitempty"` 118 | Country string `json:"country,omitempty"` 119 | Year string `json:"year,omitempty"` 120 | ContractStartDate int64 `json:"contractStartDate,omitempty"` 121 | EpisodeNumber int64 `json:"episodeNumber,omitempty"` 122 | ContractEndDate int64 `json:"contractEndDate,omitempty"` 123 | ExternalID string `json:"externalId,omitempty"` 124 | Title string `json:"title,omitempty"` 125 | TitleBrief string `json:"titleBrief,omitempty"` 126 | ObjectType string `json:"objectType,omitempty"` 127 | Duration int64 `json:"duration,omitempty"` 128 | Genres []string `json:"genres,omitempty"` 129 | ContentSubtype ContentSubType `json:"contentSubtype,omitempty"` 130 | PcLevel int `json:"pcLevel,omitempty"` 131 | ContentID ContentID `json:"contentId,omitempty"` 132 | StarRating int `json:"starRating,omitempty"` 133 | PictureURL string `json:"pictureUrl,omitempty"` 134 | ContentType ContentType `json:"contentType,omitempty"` 135 | Language string `json:"language,omitempty"` 136 | Season int `json:"season,omitempty"` 137 | UIDuration string `json:"uiDuration,omitempty"` 138 | Entitlement string `json:"entitlement,omitempty"` 139 | Locked bool `json:"locked,omitempty"` 140 | Label string `json:"label,omitempty"` 141 | ImageURL string `json:"imageUrl,omitempty"` 142 | ID string `json:"id,omitempty"` 143 | MetaDescription string `json:"meta-description,omitempty"` 144 | IsADVAllowed bool `json:"isADVAllowed,omitempty"` 145 | ContentProvider string `json:"contentProvider,omitempty"` 146 | IsLatest bool `json:"isLatest,omitempty"` 147 | IsOnAir bool `json:"isOnAir,omitempty"` 148 | IsEncrypted bool `json:"isEncrypted,omitempty"` 149 | ObjectSubtype string `json:"objectSubtype,omitempty"` 150 | MetadataLanguage string `json:"metadataLanguage,omitempty"` 151 | PcLevelVod string `json:"pcLevelVod,omitempty"` 152 | IsParent bool `json:"isParent,omitempty"` 153 | AvailableLanguages []AvailableLanguages `json:"availableLanguages,omitempty"` 154 | AdvTags string `json:"advTags,omitempty"` 155 | ShortDescription string `json:"shortDescription,omitempty"` 156 | LeavingSoon bool `json:"leavingSoon,omitempty"` 157 | AvailableAlso []string `json:"availableAlso,omitempty"` 158 | PcVodLabel string `json:"pcVodLabel,omitempty"` 159 | IsGeoBlocked bool `json:"isGeoBlocked,omitempty"` 160 | Filter string `json:"filter,omitempty"` 161 | ComingSoon bool `json:"comingSoon,omitempty"` 162 | IsPopularEpisode bool `json:"isPopularEpisode,omitempty"` 163 | PrimaryCategoryID int `json:"primaryCategoryId,omitempty"` 164 | MeetingKey string `json:"meetingKey,omitempty"` 165 | VideoType string `json:"videoType,omitempty"` 166 | ParentalAdvisory string `json:"parentalAdvisory,omitempty"` 167 | AdditionalStreams []AdditionalStream `json:"additionalStreams,omitempty"` 168 | } 169 | 170 | type Container struct { 171 | ID string `json:"id,omitempty"` 172 | Layout string `json:"layout,omitempty"` 173 | Actions []Actions `json:"actions,omitempty"` 174 | PlatformVariants []PlatformVariants `json:"platformVariants,omitempty"` 175 | Properties []Properties `json:"properties,omitempty"` 176 | Metadata Metadata `json:"metadata,omitempty"` 177 | RetrieveItems RetrieveItems `json:"retrieveItems,omitempty"` 178 | Translations Translations `json:"translations,omitempty"` 179 | Categories []Category `json:"categories,omitempty"` 180 | Bundles []Bundles `json:"bundles,omitempty"` 181 | } 182 | 183 | type ContentContainer struct { 184 | ID string `json:"id,omitempty"` 185 | Layout string `json:"layout,omitempty"` 186 | Actions []Actions `json:"actions,omitempty"` 187 | PlatformVariants []PlatformVariants `json:"platformVariants,omitempty"` 188 | Properties []Properties `json:"properties,omitempty"` 189 | Metadata Metadata `json:"metadata,omitempty"` 190 | Containers struct { 191 | Categories []Category `json:"categories,omitempty"` 192 | Bundles []Bundles `json:"bundles,omitempty"` 193 | } `json:"containers,omitempty"` 194 | } 195 | 196 | type ContentDetailsContainer struct{} 197 | 198 | type TopContainer struct { 199 | // inconsistent type 200 | // ID string `json:"id,omitempty"` 201 | Layout string `json:"layout,omitempty"` 202 | Actions []Actions `json:"actions,omitempty"` 203 | Metadata Metadata `json:"metadata,omitempty"` 204 | RetrieveItems RetrieveItems `json:"retrieveItems,omitempty"` 205 | Translations Translations `json:"translations,omitempty"` 206 | 207 | // only in content details 208 | PlatformVariants []PlatformVariants `json:"platformVariants,omitempty"` 209 | ContentID ContentID `json:"contentId,omitempty"` 210 | Containers struct { 211 | Bundles []Bundles `json:"bundles,omitempty"` 212 | Categories []Categories `json:"categories,omitempty"` 213 | } `json:"containers,omitempty"` 214 | Suggest Suggest `json:"suggest,omitempty"` 215 | PlatformName string `json:"platformName,omitempty"` 216 | Properties []Properties `json:"properties,omitempty"` 217 | } 218 | 219 | type ResultObj struct { 220 | Total int `json:"total,omitempty"` 221 | Containers []TopContainer `json:"containers,omitempty"` 222 | MeetingName string `json:"meetingName,omitempty"` 223 | Metadata Metadata `json:"metadata,omitempty"` 224 | } 225 | 226 | type ContainerResultObj struct { 227 | Total int `json:"total,omitempty"` 228 | Containers []ContentContainer `json:"containers,omitempty"` 229 | MeetingName string `json:"meetingName,omitempty"` 230 | Metadata Metadata `json:"metadata,omitempty"` 231 | } 232 | 233 | type RetrieveItems struct { 234 | ResultObj ContainerResultObj `json:"resultObj,omitempty"` 235 | URIOriginal string `json:"uriOriginal,omitempty"` 236 | TypeOriginal string `json:"typeOriginal,omitempty"` 237 | } 238 | 239 | type Actions struct { 240 | Key string `json:"key,omitempty"` 241 | URI string `json:"uri,omitempty"` 242 | TargetType string `json:"targetType,omitempty"` 243 | Type string `json:"type,omitempty"` 244 | Layout string `json:"layout,omitempty"` 245 | HREF string `json:"href,omitempty"` 246 | } 247 | 248 | type MetadataLabel struct { 249 | NLD string `json:"NLD,omitempty"` 250 | FRA string `json:"FRA,omitempty"` 251 | DEU string `json:"DEU,omitempty"` 252 | POR string `json:"POR,omitempty"` 253 | SPA string `json:"SPA,omitempty"` 254 | } 255 | 256 | type Translations struct { 257 | MetadataLabel MetadataLabel `json:"metadata.label,omitempty"` 258 | } 259 | 260 | type AvailableLanguages struct { 261 | LanguageCode string `json:"languageCode,omitempty"` 262 | LanguageName string `json:"languageName,omitempty"` 263 | } 264 | 265 | type AdditionalStream struct { 266 | RacingNumber int `json:"racingNumber"` 267 | TeamName string `json:"teamName"` 268 | Type string `json:"type"` 269 | PlaybackURL string `json:"playbackUrl"` 270 | DriverImg string `json:"driverImg"` 271 | TeamImg string `json:"teamImg"` 272 | ChannelID ChannelID `json:"channelId"` 273 | Title string `json:"title"` 274 | ReportingName string `json:"reportingName"` 275 | Default bool `json:"default"` 276 | DriverFirstName string `json:"driverFirstName,omitempty"` 277 | DriverLastName string `json:"driverLastName,omitempty"` 278 | ConstructorName string `json:"constructorName,omitempty"` 279 | Hex string `json:"hex,omitempty"` 280 | } 281 | 282 | type AudioLanguages struct { 283 | AudioLanguageName string `json:"audioLanguageName,omitempty"` 284 | AudioID string `json:"audioId,omitempty"` 285 | IsPreferred bool `json:"isPreferred,omitempty"` 286 | } 287 | 288 | type TechnicalPackages struct { 289 | PackageID int `json:"packageId,omitempty"` 290 | PackageName string `json:"packageName,omitempty"` 291 | PackageType string `json:"packageType,omitempty"` 292 | } 293 | 294 | type Categories struct { 295 | CategoryPathIds []int `json:"categoryPathIds,omitempty"` 296 | ExternalPathIds []string `json:"externalPathIds,omitempty"` 297 | EndDate int64 `json:"endDate,omitempty"` 298 | OrderID int `json:"orderId,omitempty"` 299 | IsPrimary bool `json:"isPrimary,omitempty"` 300 | CategoryName string `json:"categoryName,omitempty"` 301 | CategoryID int `json:"categoryId,omitempty"` 302 | StartDate int64 `json:"startDate,omitempty"` 303 | } 304 | 305 | type Containers struct{} 306 | 307 | type Suggest struct { 308 | Input []string `json:"input,omitempty"` 309 | Payload struct { 310 | ObjectSubtype string `json:"objectSubtype,omitempty"` 311 | ContentID string `json:"contentId,omitempty"` 312 | Title string `json:"title,omitempty"` 313 | ObjectType string `json:"objectType,omitempty"` 314 | } `json:"payload,omitempty"` 315 | } 316 | --------------------------------------------------------------------------------