Skip to content

A Plex client for Samsung TVs that doesn't suck.

JavaScript

push to remote

rfaile3138ea8d72df90d
diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000..fc1a88a
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,26 @@
+# Copy to .env and fill in. .env is gitignored.
+
+# Samsung TV on your LAN (Settings > Connection > Network > Network Status > IP Settings)
+TV_IP=192.168.1.100
+TV_SDB_PORT=26101
+
+# Tizen Studio install location
+TIZEN_STUDIO=$HOME/tizen-studio
+
+# Name of the Samsung signing profile in Tizen's Certificate Manager
+# (certs themselves live outside this repo, e.g. ~/SamsungCertificate)
+TIZEN_SIGN_PROFILE=samsucks
+
+# Plex server (optional during dev; the app will do PIN login on-device)
+PLEX_SERVER_URL=http://192.168.1.10:32400
+PLEX_TOKEN=
+
+# Password for the Tizen author cert (tizen certificate -a samsucks -p <pw> -f samsucks)
+TIZEN_CERT_PASSWORD=
+
+# Dev builds send logs/perf to tools/devserver.mjs on this host:port
+DEV_HOST=192.168.1.20:8790
+
+# Dev builds only: skip plex.tv sign-in and use PLEX_SERVER_URL directly
+# (works when the server allows unauthenticated LAN access)
+DEV_SKIP_LOGIN=0
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..ae4dcac
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,43 @@
+# Local, personal config — never commit
+.env
+.env.*
+!.env.example
+
+# Signing certificates / keystores / profiles
+*.p12
+*.pfx
+*.pem
+*.key
+*.crt
+*.cer
+*.csr
+author.xml
+distributor.xml
+profiles.xml
+SamsungCertificate/
+certs/
+
+# Build output
+*.wgt
+build/
+dist/
+.buildResult/
+.sign/
+.tproject
+
+# Tizen Studio / IDE workspace junk
+.metadata/
+.settings/
+.project
+.vscode/
+.idea/
+
+# Node
+node_modules/
+npm-debug.log*
+
+# OS
+.DS_Store
+
+# Promo material (videos, graphics, drafts); final README media goes in docs/media/
+marketing/
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<https://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<https://www.gnu.org/licenses/why-not-lgpl.html>.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..02a436e
--- /dev/null
+++ b/README.md
@@ -0,0 +1,228 @@
+<p align="center">
+ <picture>
+ <source media="(prefers-color-scheme: light)" srcset="assets/brand/lockup-horizontal-dark-1920x640.png">
+ <img src="assets/brand/lockup-horizontal-light-1920x640.png" alt="SamSUCKS" width="560">
+ </picture>
+</p>
+
+<p align="center">
+ <b>A Plex client for Samsung TVs that doesn't suck.</b><br>
+ Smooth scrolling, hardware playback, zero dependencies.
+</p>
+
+<p align="center">
+ <img src="assets/readme/home.png" alt="SamSUCKS home screen" width="880">
+</p>
+
+The official Plex app on Samsung TVs is painfully slow. The same library flies on a
+Fire TV or an Apple TV, so the TV isn't the problem; the app is.
+
+On my 75" Samsung Q60B (2022, Tizen 6.5):
+
+| | Official Plex app | SamSUCKS |
+| --- | --- | --- |
+| Opening the app | about a minute | about a second |
+| Typing in search | every letter lags | instant |
+| Search results | take forever | appear as you type |
+
+The Plex server answers a search in 30–150 ms, so the server was never the bottleneck.
+
+SamSUCKS is a from-scratch Plex client for Samsung's Tizen TVs, built for speed:
+
+- **Smooth.** About 50 fps while scrolling, with a 17 ms median frame, measured on a 2022 Samsung Q60B.
+- **Hardware playback.** It plays files directly through Samsung's video decoder.
+ On a real 3,952-item library, 98.7% plays without any transcoding.
+- **Quick to start.** Home appears in under a second, and video starts about a second after you press play.
+- **Tiny.** Plain JavaScript, no framework, no npm, no build step.
+
+## Install
+
+You need:
+- a Samsung smart TV (tested on a 2022 Q60B; 2020 or newer should work),
+- a Mac or Linux computer on the same network as the TV,
+- a Plex Media Server.
+
+**1. Download SamSUCKS**
+
+```sh
+git clone https://github.com/rfaile313/samsucks.git
+cd samsucks
+```
+
+**2. Run setup**
+
+```sh
+./scripts/setup.sh
+```
+
+This installs Samsung's command-line tools (about 270 MB), finds your TV on the
+network, and creates a signing certificate. If Developer Mode isn't turned on yet,
+it stops and tells you exactly what to do, including your computer's IP address.
+The steps are also below. Run it again afterwards, and it picks up where it left off.
+
+**3. Install it on the TV**
+
+```sh
+./scripts/deploy.sh
+```
+
+SamSUCKS opens on the TV. Go to **[plex.tv/link](https://plex.tv/link)** on your phone
+or computer and type the code it shows, or scan the QR code. That's it.
+
+<details>
+<summary><b>Turning on Developer Mode</b></summary>
+
+1. Press **Home** on the remote and open **Apps**.
+2. On the Apps screen, type **1 2 3 4 5** on the remote.
+ - No number keys? Press the **123** button to bring up the on-screen keypad.
+ - Nothing happened? Try again, typing a bit faster.
+3. Switch **Developer mode** to **On**, and enter your computer's IP address
+ (`./scripts/setup.sh` prints it).
+4. Choose **OK**, then restart the TV: hold the **Power** button until it turns off and back on.
+
+When it's on, the Apps screen shows **Develop mode** at the top.
+</details>
+
+### Opening it later
+
+Press **Home** → **Apps** and scroll to the bottom, where your installed apps are.
+To pin it to the home bar, highlight **SamSUCKS**, open its options (hold **OK**) and
+choose **Add to Home**.
+
+### Troubleshooting
+
+| Problem | Fix |
+| --- | --- |
+| Typing 12345 does nothing | Make sure you're on the **Apps** screen. Use the on-screen keypad (**123** button) if your remote has no number keys, and type quickly. |
+| Setup says "No Samsung TV found" | Turn the TV on and make sure it's on the same network (Wi-Fi or Ethernet) as your computer. |
+| Setup says Developer Mode points at another IP | Re-enter your computer's IP in the Developer Mode popup, then restart the TV. |
+| "Can't reach the TV" when deploying | Restart the TV, then run `./scripts/setup.sh` again. Your computer's IP may have changed. |
+| The app disappeared | TV firmware updates can remove sideloaded apps. Run `./scripts/deploy.sh` again. |
+| The sign-in code expired | Press **OK** on the sign-in screen for a new code. |
+
+## Using it
+
+| Remote | What it does |
+| --- | --- |
+| Arrows / OK | Move around / select |
+| Play/Pause | Play whatever is focused, or pause and resume |
+| Back | Go back (while watching, the first press hides the controls) |
+| ▼ while watching | Audio and subtitle tracks |
+| ◀ ▶ while watching | Seek; hold to go faster |
+| Yellow | Change the sort order in a library |
+| CH ▲ / CH ▼ | Jump by letter in a library |
+
+What's in it: home rows (Continue Watching, On Deck, Recently Added…), full library
+grids, search with the TV keyboard, movie and show pages with seasons and episodes,
+resume and mark watched, audio and subtitle picker (including external `.srt` files),
+up-next autoplay, and watch progress synced back to Plex.
+
+## Why it's fast
+
+Samsung TVs only run web apps, but there's nothing slow about the web engine
+if you treat it like a game engine:
+
+- Every animation is a GPU transform or fade. Nothing big is ever repainted.
+- Lists reuse a fixed set of tiles instead of creating new ones as you scroll.
+- The focus ring never moves. The content slides under it.
+- A held-down key can never queue up work: input is applied at most once per frame.
+- Plex resizes every image to exactly the pixels on screen before it's sent.
+- Video goes straight to Samsung's hardware decoder. Only what the TV can't decode
+ (mostly DTS audio) is converted by Plex, and the video itself is never re-encoded.
+
+The biggest win was one line of CSS:
+
+<p align="center">
+ <img src="assets/readme/frame-trace.png" alt="Frame times for the same 12 button presses: the old renderer froze for about 2 seconds on every press and took 24.4 s; SamSUCKS finished in 3.7 s and never went above 66 ms" width="760">
+</p>
+
+A full-screen CSS gradient behind the UI took **almost two seconds** to repaint on the
+TV's CPU. Now the background is a 2×2-pixel WebGL texture that the GPU stretches to
+fill the screen: it looks the same and costs nothing. Want to see the difference?
+**Settings → Demo: original slow renderer** brings the old one back, and
+**Settings → Performance overlay** shows the frame rate.
+
+## For developers
+
+<details>
+<summary><b>Dev loop: logs, remote control and benchmarks on the real TV</b></summary>
+
+Chrome DevTools can't attach to a retail TV, so dev builds talk to a small server on
+your computer instead. Put your computer's `host:port` in `.env` as `DEV_HOST`, then:
+
+```sh
+node tools/devserver.mjs # receives logs and perf samples from the TV (build/tv.log)
+./scripts/deploy.sh --dev # dev build: performance overlay, logging, remote control
+
+curl 'localhost:8790/send?keys=down,right,right,enter' # press buttons
+tools/tveval.sh 'document.title' # run JS on the TV, print the result
+tools/tveval.sh '__bench(["right","right","left","left"], 250)' # frame stats while replaying keys
+tools/tveval.sh "__css('.hero-art{display:none}')" # A/B test a CSS change live
+```
+
+With `DEV_SKIP_LOGIN=1` and `PLEX_SERVER_URL` in `.env`, dev builds skip sign-in and
+use a server that allows unauthenticated local-network access.
+
+The UI also runs in desktop Chrome: `./scripts/deploy.sh --build-only`, then serve
+`build/app/` with any static server. It uses a `<video>` element instead of AVPlay there.
+</details>
+
+<details>
+<summary><b>How the code is laid out</b></summary>
+
+```
+app/ the whole TV app; deploy.sh copies it to build/app and packages it
+ js/screens/ home, library, detail, player, search, settings, login
+ js/ui/ rows, grids, tiles, image loader, backdrop, perf overlay
+ js/plex/ plex.tv sign-in and Plex Media Server API
+ js/platform/ Tizen keys and device info, AVPlay / <video> player
+scripts/ setup.sh (one-time) and deploy.sh (build + install)
+tools/ dev server, TV eval, network remote
+```
+
+There's no bundler. The TV's browser (Chromium 69+ on Tizen 5.5+) runs ES modules
+natively, and `deploy.sh` adds `<link rel="modulepreload">` tags so every module loads
+in parallel (about 0.9 s cold start, versus 0.8 s for a minified bundle).
+</details>
+
+<details>
+<summary><b>Performance notes</b> (measured on a 2022 Q60B, Tizen 6.5, Chromium 85)</summary>
+
+| Background renderer | fps while navigating | worst frame |
+| --- | --- | --- |
+| Full-screen CSS `radial-gradient` | 11 | 1,928 ms |
+| 2×2 2D canvas, stretched by CSS | 20 | 207 ms |
+| 2×2 WebGL canvas, stretched by the compositor | 49–50 | 80 ms (17 ms median) |
+
+Ruled out by A/B testing on the TV: hero image masks, the focus ring's shadow,
+poster fade-ins, row opacity changes, and per-tile compositor layers. None made a
+measurable difference.
+</details>
+
+<details>
+<summary><b>Plex server quirks</b></summary>
+
+- Plex Media Server 1.42 returns `400` for `start.m3u8` unless
+ `/video/:/transcode/universal/decision` was called for the same session first.
+- `X-Plex-Platform=Tizen` selects the server's built-in profile for the official app,
+ which rejects these transcode requests, so SamSUCKS identifies itself as `Samsung`.
+- Samsung TVs from 2018 on can't decode DTS. For those files Plex copies the video
+ and converts only the audio, to AC3 5.1.
+</details>
+
+## Credits
+
+Inspired by [plx-native](https://github.com/GLinnik21/plx-native), a native Plex client
+for LG TVs. Fonts: [Inter](https://rsms.me/inter/) and
+[Barlow Condensed](https://fonts.google.com/specimen/Barlow+Condensed) (SIL Open Font
+License). QR codes: [qrcode-generator](https://github.com/kazuhikoarase/qrcode-generator)
+by Kazuhiko Arase (MIT).
+
+SamSUCKS is an independent project, not affiliated with Plex or Samsung.
+
+## License
+
+Copyright © 2026 rfaile313. SamSUCKS is free software, released under the
+[GNU General Public License v3.0](LICENSE): you can use, study, change and share it,
+and anything you distribute that's built on it must stay open source under the same
+license.
diff --git a/app/config.xml b/app/config.xml
new file mode 100644
index 0000000..f7c792a
--- /dev/null
+++ b/app/config.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<widget xmlns="http://www.w3.org/ns/widgets" xmlns:tizen="http://tizen.org/ns/widgets" id="http://github.com/samsucks/samsucks" version="0.1.0" viewmodes="maximized">
+ <tizen:application id="SamSucks01.samsucks" package="SamSucks01" required_version="6.5"/>
+ <content src="index.html"/>
+ <icon src="icon.png"/>
+ <name>SamSUCKS - Better Plex</name>
+ <description>A fast Plex client for Samsung TVs</description>
+ <feature name="http://tizen.org/feature/screen.size.all"/>
+ <tizen:profile name="tv-samsung"/>
+ <tizen:privilege name="http://tizen.org/privilege/internet"/>
+ <tizen:privilege name="http://tizen.org/privilege/tv.inputdevice"/>
+ <tizen:privilege name="http://developer.samsung.com/privilege/avplay"/>
+ <tizen:privilege name="http://developer.samsung.com/privilege/productinfo"/>
+ <access origin="*" subdomains="true"/>
+ <tizen:setting screen-orientation="landscape" context-menu="disable" background-support="disable" encryption="disable" install-location="auto" hwkey-event="enable"/>
+</widget>
diff --git a/app/css/app.css b/app/css/app.css
new file mode 100644
index 0000000..91c3a5d
--- /dev/null
+++ b/app/css/app.css
@@ -0,0 +1,432 @@
+@font-face { font-family: 'Inter'; font-weight: 400; font-display: swap; src: url(../fonts/inter-latin-400-normal.woff2) format('woff2'); }
+@font-face { font-family: 'Inter'; font-weight: 500; font-display: swap; src: url(../fonts/inter-latin-500-normal.woff2) format('woff2'); }
+@font-face { font-family: 'Inter'; font-weight: 600; font-display: swap; src: url(../fonts/inter-latin-600-normal.woff2) format('woff2'); }
+@font-face { font-family: 'Inter'; font-weight: 700; font-display: swap; src: url(../fonts/inter-latin-700-normal.woff2) format('woff2'); }
+@font-face { font-family: 'Barlow Condensed'; font-weight: 600; font-display: swap; src: url(../fonts/barlow-condensed-latin-600-normal.woff2) format('woff2'); }
+@font-face { font-family: 'Barlow Condensed'; font-weight: 700; font-display: swap; src: url(../fonts/barlow-condensed-latin-700-normal.woff2) format('woff2'); }
+
+/*
+ * Performance rules for this file:
+ * - anything that animates only animates transform or opacity, on an element
+ * that already has its own layer (will-change), so the GPU does it without
+ * repainting;
+ * - no blur filters, backdrop-filter or animated box-shadows;
+ * - fixed sizes everywhere, so recycling a tile never triggers layout.
+ */
+
+:root {
+ --bg: #0B0D12;
+ --raised: #181B23;
+ --coral: #FF4C42;
+ --cream: #FFF7E6;
+ --dim: rgba(255, 247, 230, 0.62);
+ --faint: rgba(255, 247, 230, 0.10);
+ --ease: cubic-bezier(0.2, 0.8, 0.2, 1);
+ --display: 'Barlow Condensed', 'SamsungOneUI', sans-serif;
+ --body: 'Inter', 'SamsungOneUI', sans-serif;
+}
+
+* { margin: 0; padding: 0; box-sizing: border-box; }
+
+html, body {
+ width: 1920px;
+ height: 1080px;
+ overflow: hidden;
+ background: var(--bg);
+ color: var(--cream);
+ font-family: var(--body);
+ -webkit-font-smoothing: antialiased;
+ -webkit-user-select: none;
+ user-select: none;
+}
+
+#app { position: absolute; top: 0; left: 0; width: 1920px; height: 1080px; }
+
+/* Video plays on a plane beneath the web layer, so everything must be see-through. */
+html.playing, html.playing body, html.playing #app { background: transparent; }
+html.playing .ambience { display: none; }
+
+.hidden { display: none !important; }
+
+#splash {
+ position: absolute; top: 0; left: 0; width: 1920px; height: 1080px;
+ z-index: 50; background: var(--bg);
+ transition: opacity 350ms ease;
+ will-change: opacity;
+}
+#splash img { width: 1920px; height: 1080px; display: block; }
+#splash.gone { opacity: 0; }
+
+.screen { position: absolute; top: 0; left: 0; width: 1920px; height: 1080px; overflow: hidden; }
+
+/* ---------- ambience + hero art ---------- */
+
+.ambience { position: absolute; top: 0; left: 0; width: 1920px; height: 1080px; background: var(--bg); }
+/* A 2x2 WebGL canvas stretched by the compositor; see ui/backdrop.js. */
+.amb-layer { position: absolute; top: 0; left: 0; width: 1920px; height: 1080px; will-change: opacity; }
+.amb-layer { opacity: 0; transition: opacity 700ms ease; }
+.amb-layer.on { opacity: 1; }
+.ambience.legacy .amb-layer { display: none; }
+
+.hero-art { position: absolute; overflow: hidden; }
+.hero-img {
+ position: absolute; top: 0; left: 0; width: 100%; height: 100%;
+ object-fit: cover; opacity: 0;
+ transition: opacity 600ms ease; will-change: opacity;
+}
+.hero-img.on { opacity: 1; }
+.hero-fade { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
+
+.home-art {
+ left: 576px; top: 0; width: 1344px; height: 756px;
+ -webkit-mask-image: linear-gradient(to right, transparent 0%, #000 42%), linear-gradient(to top, transparent 0%, #000 45%);
+ -webkit-mask-composite: source-in;
+}
+.home-art .hero-fade { background: linear-gradient(180deg, rgba(11, 13, 18, 0.55) 0%, transparent 22%), linear-gradient(90deg, rgba(11, 13, 18, 0.5) 0%, transparent 40%); }
+
+.detail-art {
+ left: 0; top: 0; width: 1920px; height: 1080px;
+ -webkit-mask-image: linear-gradient(to right, rgba(0, 0, 0, 0.18) 0%, #000 62%), linear-gradient(to top, rgba(0, 0, 0, 0.1) 0%, #000 55%);
+ -webkit-mask-composite: source-in;
+ transition: opacity 400ms ease; will-change: opacity;
+}
+.detail-art .hero-fade {
+ background: linear-gradient(90deg, rgba(11, 13, 18, 0.82) 0%, rgba(11, 13, 18, 0.55) 38%, transparent 70%),
+ linear-gradient(0deg, rgba(11, 13, 18, 0.7) 0%, transparent 40%);
+}
+.detail.shifted .detail-art { opacity: 0.35; }
+
+/* ---------- top bar / nav ---------- */
+
+.topbar {
+ position: absolute; top: 40px; left: 96px; right: 96px; height: 88px;
+ display: flex; align-items: center;
+}
+.brand { display: flex; align-items: center; flex-shrink: 0; }
+.brand-mark { width: 81px; height: 84px; display: block; }
+.brand-text { margin-left: 16px; }
+.brand-wordmark { width: 206px; height: 44px; display: block; }
+.brand-by {
+ margin-top: 6px; padding-left: 2px;
+ font: 500 17px/1 var(--body); letter-spacing: 0.06em; color: rgba(255, 255, 255, 0.86);
+}
+
+.nav { display: flex; align-items: center; margin-left: 72px; }
+.nav-item {
+ position: relative; display: flex; align-items: center; justify-content: center;
+ height: 52px; padding: 0 24px; margin-right: 6px; border-radius: 26px;
+ font: 600 26px/1 var(--body); color: var(--dim); white-space: nowrap;
+}
+.nav-item span { display: block; padding-top: 1px; }
+.nav-item.current { color: var(--cream); }
+/* Current section: small coral dot under the label. */
+.nav-item.current::after {
+ content: ''; position: absolute; left: 50%; bottom: -10px; width: 6px; height: 6px;
+ margin-left: -3px; border-radius: 3px; background: var(--coral);
+}
+.nav-item.focus { background: var(--cream); color: var(--bg); }
+.nav-item.focus::after { display: none; }
+.nav-icon { width: 52px; padding: 0; }
+.nav-icon svg { width: 28px; height: 28px; display: block; }
+.nav-sep { width: 2px; height: 28px; margin: 0 14px 0 8px; border-radius: 1px; background: rgba(255, 247, 230, 0.18); }
+.topbar-who { margin-left: auto; font: 500 22px var(--body); color: var(--dim); white-space: nowrap; }
+
+/* ---------- home ---------- */
+
+.hero-info { position: absolute; left: 96px; top: 190px; width: 880px; }
+.hero-logo { display: block; max-width: 560px; max-height: 170px; object-fit: contain; object-position: left bottom; }
+.hero-title {
+ font: 700 96px/0.95 var(--display); letter-spacing: 0.005em;
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
+}
+.hero-meta { margin-top: 18px; font: 500 26px var(--body); color: var(--dim); white-space: nowrap; }
+.hero-summary {
+ margin-top: 16px; font: 400 25px/1.45 var(--body); color: rgba(255, 247, 230, 0.8);
+ display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden;
+ max-height: 109px;
+}
+.home.in-nav .hero-info { opacity: 0.5; }
+.home-rows { position: absolute; left: 0; width: 1920px; bottom: 0; overflow: hidden; }
+.home-empty { position: absolute; left: 96px; top: 660px; font: 500 28px var(--body); color: var(--dim); }
+
+.rows-track {
+ position: absolute; top: 0; left: 0; width: 1920px;
+ will-change: transform; transition: transform 300ms var(--ease);
+}
+
+/* ---------- rows + tiles ---------- */
+
+.row {
+ position: absolute; top: 0; left: 0; width: 1920px;
+ will-change: transform, opacity;
+ transition: opacity 250ms ease;
+}
+.row:not(.active) { opacity: 0.5; }
+.row.above { opacity: 0; }
+.row-title {
+ height: 52px; margin-left: 96px;
+ font: 600 34px/52px var(--display); letter-spacing: 0.02em; color: var(--cream);
+}
+.row-clip { position: relative; width: 1920px; }
+.row-track {
+ position: absolute; top: 12px; left: 96px;
+ will-change: transform; transition: transform 260ms var(--ease);
+}
+
+.ring {
+ position: absolute; top: 4px; left: 0;
+ border: 5px solid var(--coral); border-radius: 16px;
+ box-shadow: 0 0 36px rgba(255, 76, 66, 0.45);
+ opacity: 0; pointer-events: none;
+ will-change: transform, opacity;
+ transition: opacity 200ms ease, transform 220ms var(--ease);
+}
+.row.active .ring, .ring.on { opacity: 1; }
+
+.tile { position: absolute; top: 0; left: 0; }
+.tile-frame { position: relative; border-radius: 10px; overflow: hidden; background: var(--raised); }
+.tile-ph {
+ position: absolute; top: 0; left: 0; right: 0; bottom: 0;
+ display: flex; align-items: flex-end; padding: 18px;
+ font: 600 28px/1.05 var(--display); color: var(--dim);
+}
+.tile-img {
+ position: absolute; top: 0; left: 0; width: 100%; height: 100%;
+ object-fit: cover; opacity: 0; transition: opacity 220ms ease;
+}
+.tile-img.in { opacity: 1; }
+.tile-img.in + .tile-ph { visibility: hidden; }
+.tile-img.now, html.fast .tile-img { transition: none; }
+.tile-bar {
+ position: absolute; left: 12px; right: 12px; bottom: 12px; height: 6px;
+ border-radius: 3px; background: rgba(0, 0, 0, 0.6); overflow: hidden;
+}
+.tile-bar i { display: block; height: 100%; background: var(--coral); transform-origin: 0 0; }
+.tile-badge {
+ position: absolute; top: 10px; right: 10px; min-width: 36px; height: 36px; padding: 0 10px;
+ border-radius: 18px; background: var(--coral); color: #fff;
+ font: 700 20px/36px var(--body); text-align: center;
+}
+.tile-badge.done { background: rgba(11, 13, 18, 0.78); color: var(--cream); }
+.tile-cap {
+ margin-top: 14px; font: 600 22px var(--body); color: var(--cream);
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
+}
+.tile-sub {
+ margin-top: 4px; font: 400 19px var(--body); color: var(--dim);
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
+}
+
+html.fast .row-track, html.fast .rows-track, html.fast .grid-track, html.fast .ring {
+ transition-duration: 110ms;
+}
+
+/* ---------- library grid ---------- */
+
+.lib-head { position: absolute; top: 52px; left: 96px; right: 96px; display: flex; align-items: baseline; }
+.lib-title { font: 700 76px/1 var(--display); }
+.lib-count { margin-left: 24px; font: 500 26px var(--body); color: var(--dim); }
+.lib-sort { margin-left: auto; font: 500 24px var(--body); color: var(--dim); }
+.lib-focus {
+ position: absolute; top: 146px; left: 96px; width: 1300px;
+ font: 500 26px var(--body); color: var(--cream);
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
+}
+.lib-hint { position: absolute; top: 150px; right: 96px; font: 500 22px var(--body); color: var(--dim); }
+.key-yellow { display: inline-block; width: 18px; height: 18px; border-radius: 4px; background: #F5C518; vertical-align: -2px; }
+
+.grid { position: absolute; left: 88px; width: 1776px; overflow: hidden; }
+.grid-track {
+ position: absolute; top: 12px; left: 8px;
+ will-change: transform; transition: transform 260ms var(--ease);
+}
+.grid-row { position: absolute; top: 0; left: 0; will-change: transform; }
+
+/* ---------- detail ---------- */
+
+.detail-body {
+ position: absolute; left: 96px; top: 140px; width: 1728px;
+ will-change: transform; transition: transform 380ms var(--ease);
+}
+.detail-logo { display: block; max-width: 640px; max-height: 210px; object-fit: contain; object-position: left bottom; }
+.detail-title { font: 700 108px/0.95 var(--display); max-width: 1150px; }
+.detail-sub { margin-top: 18px; font: 600 30px var(--body); min-height: 36px; }
+.detail-meta { margin-top: 12px; font: 500 26px var(--body); color: var(--dim); }
+.detail-tags { margin-top: 10px; font: 400 22px var(--body); color: var(--dim); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 1100px; }
+.detail-summary {
+ margin-top: 22px; max-width: 980px; height: 156px;
+ font: 400 26px/1.5 var(--body); color: rgba(255, 247, 230, 0.82);
+ display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical; overflow: hidden;
+}
+.detail-buttons { margin-top: 34px; height: 80px; white-space: nowrap; }
+
+.btn {
+ display: inline-flex; align-items: center; vertical-align: top;
+ height: 72px; padding: 0 34px; margin-right: 18px; border-radius: 36px;
+ background: rgba(255, 247, 230, 0.12); color: var(--cream);
+ font: 600 26px var(--body); white-space: nowrap;
+}
+.btn svg { width: 28px; height: 28px; margin-right: 14px; }
+.btn.focus { background: var(--cream); color: var(--bg); }
+
+.detail-seasons { margin-top: 60px; height: 56px; white-space: nowrap; }
+.pill {
+ display: inline-block; height: 56px; line-height: 56px; padding: 0 28px; margin-right: 12px;
+ border-radius: 28px; font: 600 24px/56px var(--body); color: var(--dim);
+}
+.pill.current { color: var(--cream); background: var(--faint); }
+.pill.focus { background: var(--cream); color: var(--bg); }
+.detail-episodes { position: relative; margin: 24px 0 0 -96px; width: 1920px; height: 330px; }
+
+/* ---------- player ---------- */
+
+.player { background: transparent; }
+.player-stage, .av-object { position: absolute; top: 0; left: 0; width: 1920px; height: 1080px; }
+
+.osd { position: absolute; top: 0; left: 0; width: 1920px; height: 1080px; opacity: 0; transition: opacity 250ms ease; will-change: opacity; }
+.osd-on .osd { opacity: 1; }
+.osd-top {
+ position: absolute; top: 0; left: 0; width: 1920px; height: 280px; padding: 64px 96px 0;
+ background: linear-gradient(180deg, rgba(0, 0, 0, 0.78), transparent);
+}
+.osd-title { font: 700 64px/1 var(--display); }
+.osd-sub { margin-top: 12px; font: 500 28px var(--body); color: var(--dim); }
+.osd-bottom {
+ position: absolute; bottom: 0; left: 0; width: 1920px; height: 320px;
+ background: linear-gradient(0deg, rgba(0, 0, 0, 0.85), transparent);
+}
+.osd-bar { position: absolute; left: 96px; width: 1728px; bottom: 150px; height: 8px; border-radius: 4px; background: rgba(255, 247, 230, 0.25); }
+.osd-fill {
+ position: absolute; top: 0; left: 0; width: 100%; height: 100%;
+ border-radius: 4px; background: var(--coral); transform-origin: 0 0; will-change: transform;
+}
+.osd-knob {
+ position: absolute; left: -12px; top: -8px; width: 24px; height: 24px; border-radius: 12px;
+ background: var(--cream); box-shadow: 0 2px 10px rgba(0, 0, 0, 0.5); will-change: transform;
+}
+.osd-seek {
+ display: none; position: absolute; bottom: 40px; left: 12px;
+ transform: translateX(-50%); padding: 8px 16px; border-radius: 10px;
+ background: var(--cream); color: var(--bg); font: 700 28px var(--body); white-space: nowrap;
+}
+.seeking .osd-seek { display: block; }
+.osd-times {
+ position: absolute; left: 96px; width: 1728px; bottom: 90px;
+ display: flex; justify-content: space-between; font: 500 26px var(--body);
+}
+.osd-info { color: var(--dim); }
+.osd-hint { position: absolute; left: 96px; bottom: 40px; font: 500 20px var(--body); color: var(--dim); }
+
+.pause-big {
+ position: absolute; left: 880px; top: 380px; width: 160px; height: 160px; padding: 36px;
+ border-radius: 80px; background: rgba(11, 13, 18, 0.6); color: var(--cream);
+ opacity: 0; transition: opacity 200ms ease; will-change: opacity;
+}
+.pause-big svg { width: 88px; height: 88px; display: block; }
+.paused .pause-big { opacity: 1; }
+
+.spinner {
+ display: none; position: absolute; left: 912px; top: 492px; width: 96px; height: 96px;
+ border-radius: 50%; border: 6px solid rgba(255, 247, 230, 0.18); border-top-color: var(--coral);
+ animation: spin 0.9s linear infinite; will-change: transform;
+}
+.spinner.on { display: block; }
+@keyframes spin { to { transform: rotate(360deg); } }
+
+.subs {
+ position: absolute; left: 160px; right: 160px; bottom: 90px;
+ text-align: center; white-space: pre-line;
+ font: 600 46px/1.25 var(--body); color: #fff;
+ text-shadow: 0 2px 6px #000, 0 0 3px #000, 0 0 3px #000;
+}
+.osd-on .subs { bottom: 340px; }
+
+.tracks {
+ position: absolute; right: 0; top: 0; width: 960px; height: 1080px;
+ padding: 110px 72px; display: flex;
+ background: rgba(11, 13, 18, 0.94);
+}
+.tracks-col { flex: 1; margin-right: 32px; overflow: hidden; }
+.tracks-head { display: flex; align-items: center; margin-bottom: 24px; font: 600 24px var(--body); color: var(--dim); letter-spacing: 0.08em; text-transform: uppercase; }
+.tracks-head svg { width: 30px; height: 30px; margin-right: 12px; }
+.tracks-opt {
+ padding: 16px 22px; margin-bottom: 6px; border-radius: 14px;
+ font: 500 25px var(--body); color: rgba(255, 247, 230, 0.75);
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
+}
+.tracks-opt.on { color: var(--cream); }
+.tracks-opt.on::before { content: '✓ '; color: var(--coral); }
+.tracks-opt.focus { background: var(--cream); color: var(--bg); }
+
+.upnext {
+ position: absolute; right: 96px; bottom: 120px; width: 660px; padding: 34px 40px;
+ border-radius: 22px; background: var(--raised); box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6);
+}
+.upnext-label { font: 700 22px var(--body); color: var(--coral); letter-spacing: 0.08em; text-transform: uppercase; }
+.upnext-title { margin: 12px 0; font: 600 42px/1.1 var(--display); }
+.upnext-hint { font: 500 20px var(--body); color: var(--dim); }
+
+.player-error {
+ position: absolute; left: 360px; right: 360px; top: 470px; padding: 40px;
+ border-radius: 22px; background: var(--raised); text-align: center; font: 500 30px var(--body);
+}
+
+/* ---------- login / picker / settings ---------- */
+
+.login-art { position: absolute; left: 140px; top: 230px; }
+.login-art img { width: 560px; height: 560px; display: block; }
+.login-panel { position: absolute; left: 840px; top: 170px; width: 940px; }
+.login-title { font: 700 96px/1 var(--display); }
+.login-steps { margin-top: 28px; padding-left: 36px; font: 500 30px/1.7 var(--body); color: var(--dim); }
+.login-steps b { color: var(--cream); }
+.login-code { margin: 14px 0 36px; font: 700 160px/1 var(--display); letter-spacing: 0.16em; color: var(--coral); height: 160px; }
+.login-qr { display: flex; align-items: center; }
+.login-qr-box { width: 200px; height: 200px; padding: 14px; border-radius: 16px; background: #fff; }
+.login-qr-box svg { width: 100%; height: 100%; display: block; }
+.login-qr-label { margin-left: 28px; font: 500 26px var(--body); color: var(--dim); }
+.login-status { margin-top: 34px; font: 500 26px var(--body); color: var(--dim); min-height: 32px; }
+
+.picker-title, .settings-title { position: absolute; left: 160px; top: 110px; font: 700 80px/1 var(--display); }
+.picker-list, .settings-list { position: absolute; left: 160px; top: 260px; width: 1100px; }
+.picker .login-status { position: absolute; left: 160px; bottom: 120px; }
+.btn-wide {
+ display: flex; flex-direction: column; align-items: flex-start; justify-content: center;
+ width: 100%; height: 112px; margin-bottom: 16px; padding: 0 36px; border-radius: 20px;
+}
+.btn-wide span { font: 600 32px var(--body); }
+.btn-wide small { margin-top: 6px; font: 500 22px var(--body); color: var(--dim); }
+.btn-wide.focus small { color: rgba(11, 13, 18, 0.65); }
+
+.setting {
+ display: flex; justify-content: space-between; align-items: center;
+ height: 96px; padding: 0 36px; margin-bottom: 14px; border-radius: 20px;
+ background: rgba(255, 247, 230, 0.06); font: 600 28px var(--body);
+}
+.setting-value { color: var(--dim); font-weight: 500; }
+.setting.focus { background: var(--cream); color: var(--bg); }
+.setting.focus .setting-value { color: rgba(11, 13, 18, 0.65); }
+.settings-foot { position: absolute; left: 160px; bottom: 64px; font: 500 20px var(--body); color: var(--dim); }
+
+/* ---------- search ---------- */
+
+.search-bar {
+ position: absolute; top: 64px; left: 96px; right: 96px; height: 96px; padding: 0 36px;
+ border-radius: 48px; background: rgba(255, 247, 230, 0.08);
+ display: flex; align-items: center;
+}
+.search.in-input .search-bar { box-shadow: 0 0 0 4px var(--coral); }
+.search-icon svg { width: 40px; height: 40px; display: block; color: var(--dim); }
+.search-input {
+ flex: 1; margin-left: 22px; border: 0; outline: 0; background: transparent;
+ color: var(--cream); font: 500 38px var(--body);
+}
+.search-input::placeholder { color: rgba(255, 247, 230, 0.4); }
+.search-status { position: absolute; top: 196px; left: 96px; font: 500 26px var(--body); color: var(--dim); }
+.search-rows { position: absolute; top: 230px; left: 0; width: 1920px; bottom: 0; overflow: hidden; }
+
+/* ---------- dev ---------- */
+
+.hud {
+ position: absolute; top: 10px; right: 14px; z-index: 100; padding: 4px 12px; border-radius: 8px;
+ background: rgba(0, 0, 0, 0.65); color: #9f9; font: 18px monospace; pointer-events: none;
+}
diff --git a/app/fonts/LICENSE-BarlowCondensed.txt b/app/fonts/LICENSE-BarlowCondensed.txt
new file mode 100644
index 0000000..d2f2fc5
--- /dev/null
+++ b/app/fonts/LICENSE-BarlowCondensed.txt
@@ -0,0 +1,93 @@
+Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow) BarlowCondensed-ThinItalic.ttf: Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow) BarlowCondensed-ExtraLight.ttf: Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow) BarlowCondensed-ExtraLightItalic.ttf: Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow) BarlowCondensed-Light.ttf: Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow) BarlowCondensed-LightItalic.ttf: Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow) BarlowCondensed-Regular.ttf: Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow) BarlowCondensed-Italic.ttf: Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow) BarlowCondensed-Medium.ttf: Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow) BarlowCondensed-MediumItalic.ttf: Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow) BarlowCondensed-SemiBold.ttf: Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow) BarlowCondensed-SemiBoldItalic.ttf: Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow) BarlowCondensed-Bold.ttf: Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow) BarlowCondensed-BoldItalic.ttf: Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow) BarlowCondensed-ExtraBold.ttf: Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow) BarlowCondensed-ExtraBoldItalic.ttf: Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow) BarlowCondensed-Black.ttf: Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow) BarlowCondensed-BlackItalic.ttf: Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/app/fonts/LICENSE-Inter.txt b/app/fonts/LICENSE-Inter.txt
new file mode 100644
index 0000000..40589da
--- /dev/null
+++ b/app/fonts/LICENSE-Inter.txt
@@ -0,0 +1,93 @@
+Copyright 2016 The Inter Project Authors (https://github.com/rsms/inter) Inter-Italic[opsz,wght].ttf: Copyright 2016 The Inter Project Authors (https://github.com/rsms/inter)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/app/fonts/barlow-condensed-latin-600-normal.woff2 b/app/fonts/barlow-condensed-latin-600-normal.woff2
new file mode 100644
index 0000000..da60c9a
Binary files /dev/null and b/app/fonts/barlow-condensed-latin-600-normal.woff2 differ
diff --git a/app/fonts/barlow-condensed-latin-700-normal.woff2 b/app/fonts/barlow-condensed-latin-700-normal.woff2
new file mode 100644
index 0000000..3726e9d
Binary files /dev/null and b/app/fonts/barlow-condensed-latin-700-normal.woff2 differ
diff --git a/app/fonts/inter-latin-400-normal.woff2 b/app/fonts/inter-latin-400-normal.woff2
new file mode 100644
index 0000000..f15b025
Binary files /dev/null and b/app/fonts/inter-latin-400-normal.woff2 differ
diff --git a/app/fonts/inter-latin-500-normal.woff2 b/app/fonts/inter-latin-500-normal.woff2
new file mode 100644
index 0000000..54f0a59
Binary files /dev/null and b/app/fonts/inter-latin-500-normal.woff2 differ
diff --git a/app/fonts/inter-latin-600-normal.woff2 b/app/fonts/inter-latin-600-normal.woff2
new file mode 100644
index 0000000..d189794
Binary files /dev/null and b/app/fonts/inter-latin-600-normal.woff2 differ
diff --git a/app/fonts/inter-latin-700-normal.woff2 b/app/fonts/inter-latin-700-normal.woff2
new file mode 100644
index 0000000..a68fb10
Binary files /dev/null and b/app/fonts/inter-latin-700-normal.woff2 differ
diff --git a/app/icon.png b/app/icon.png
new file mode 100644
index 0000000..1605167
Binary files /dev/null and b/app/icon.png differ
diff --git a/app/img/mascot-512.png b/app/img/mascot-512.png
new file mode 100644
index 0000000..a46c21f
Binary files /dev/null and b/app/img/mascot-512.png differ
diff --git a/app/img/mascot.png b/app/img/mascot.png
new file mode 100644
index 0000000..507f148
Binary files /dev/null and b/app/img/mascot.png differ
diff --git a/app/img/splash.png b/app/img/splash.png
new file mode 100644
index 0000000..224b3ba
Binary files /dev/null and b/app/img/splash.png differ
diff --git a/app/img/wordmark.png b/app/img/wordmark.png
new file mode 100644
index 0000000..f3084db
Binary files /dev/null and b/app/img/wordmark.png differ
diff --git a/app/index.html b/app/index.html
new file mode 100644
index 0000000..b34ea68
--- /dev/null
+++ b/app/index.html
@@ -0,0 +1,15 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=1920, height=1080">
+<title>SamSUCKS</title>
+<link rel="stylesheet" href="css/app.css">
+<script src="$WEBAPIS/webapis/webapis.js"></script>
+</head>
+<body>
+<div id="app"></div>
+<div id="splash"><img src="img/splash.png" alt=""></div>
+<script type="module" src="js/main.js"></script>
+</body>
+</html>
diff --git a/app/js/app.js b/app/js/app.js
new file mode 100644
index 0000000..4095d52
--- /dev/null
+++ b/app/js/app.js
@@ -0,0 +1,74 @@
+// Boot: restore the session and go straight to Home when we can; otherwise sign in.
+import { DEV, DEV_HOST, DEV_PLEX_URL, VERSION } from './config.js';
+import * as router from './router.js';
+import { registerKeys } from './platform/tizen.js';
+import { session, reconnect, signOut } from './session.js';
+import { HomeScreen } from './screens/home.js';
+import { LoginScreen } from './screens/login.js';
+import { initHud } from './ui/hud.js';
+import { log, warn } from './util/log.js';
+import * as nav from './nav.js';
+import * as store from './util/store.js';
+
+function goHome() {
+ router.reset(HomeScreen());
+}
+
+function goLogin() {
+ router.reset(LoginScreen({ onDone: goHome }));
+}
+
+async function verify() {
+ // Home already painted from cache; make sure the saved connection still works.
+ try {
+ await session.server.get('/identity');
+ } catch (e) {
+ if (e.status === 401) { signOut(); goLogin(); return; }
+ warn('saved server unreachable, re-resolving', e.message);
+ try {
+ await reconnect();
+ goHome();
+ } catch (err) {
+ if (err.status === 401) { signOut(); goLogin(); }
+ }
+ }
+}
+
+function start() {
+ // A release build installed over a dev build must not inherit its LAN shortcut.
+ if (!DEV && session.token === 'lan-dev') {
+ signOut();
+ store.set('hud', undefined);
+ }
+ if (DEV && DEV_PLEX_URL && !session.token) {
+ // Dev shortcut for servers that allow unauthenticated LAN access.
+ store.set('token', 'lan-dev');
+ store.set('user', { title: 'LAN (dev)' });
+ store.set('server', { uri: DEV_PLEX_URL, token: '', name: 'Plex (LAN dev)', id: 'lan-dev' });
+ location.reload();
+ return;
+ }
+ if (session.token && session.server) {
+ goHome();
+ verify();
+ } else {
+ goLogin();
+ }
+}
+
+export function boot() {
+ if (DEV) window.__ss = { router, session, nav };
+ log('boot', VERSION, navigator.userAgent);
+ registerKeys();
+ router.init(document.getElementById('app'));
+ initHud(() => (router.top() && router.top().name) || '');
+ window.addEventListener('samsucks:restart', start);
+ // Dev builds only; release builds don't ship js/dev/.
+ if (DEV && DEV_HOST) import('./dev/remote.js').then(m => m.startDevRemote());
+ start();
+ const splash = document.getElementById('splash');
+ setTimeout(() => {
+ splash.classList.add('gone');
+ setTimeout(() => splash.parentNode && splash.parentNode.removeChild(splash), 400);
+ }, 500);
+}
diff --git a/app/js/config.js b/app/js/config.js
new file mode 100644
index 0000000..0ca37de
--- /dev/null
+++ b/app/js/config.js
@@ -0,0 +1,5 @@
+// Build settings. `scripts/deploy.sh --dev` rewrites this file in build/app only.
+export const DEV = false;
+export const DEV_HOST = ''; // host:port of tools/devserver.mjs
+export const DEV_PLEX_URL = ''; // dev only: skip sign-in and use this server directly
+export const VERSION = '0.1.0';
diff --git a/app/js/dev/remote.js b/app/js/dev/remote.js
new file mode 100644
index 0000000..c05d49b
--- /dev/null
+++ b/app/js/dev/remote.js
@@ -0,0 +1,61 @@
+// Dev builds only: long-poll the devserver for key presses / snippets to run,
+// so the app can be driven and inspected from the Mac.
+import { DEV_HOST } from '../config.js';
+import { inject } from '../input.js';
+import { log, error } from '../util/log.js';
+
+const sleep = ms => new Promise(r => setTimeout(r, ms));
+
+async function run(cmd) {
+ if (cmd.keys) {
+ for (const k of cmd.keys) {
+ inject(k);
+ await sleep(cmd.gap || 150);
+ }
+ }
+ if (cmd.eval) {
+ try {
+ let result = (0, eval)(cmd.eval);
+ if (result && typeof result.then === 'function') result = await result;
+ log('eval →', result);
+ } catch (e) {
+ error('eval failed', e);
+ }
+ }
+}
+
+export async function startDevRemote() {
+ for (;;) {
+ try {
+ const res = await fetch('http://' + DEV_HOST + '/cmd');
+ const cmds = await res.json();
+ for (const c of cmds) await run(c);
+ } catch (e) {
+ await sleep(3000);
+ }
+ }
+}
+
+// __bench(['right', ...], gapMs) → frame stats while those keys are replayed.
+window.__bench = async function (keys, gap) {
+ const deltas = [];
+ let last = performance.now();
+ let running = true;
+ const tick = now => { deltas.push(now - last); last = now; if (running) requestAnimationFrame(tick); };
+ requestAnimationFrame(tick);
+ for (const k of keys) { inject(k); await sleep(gap || 200); }
+ await sleep(600);
+ running = false;
+ const total = deltas.reduce((a, b) => a + b, 0);
+ deltas.sort((a, b) => a - b);
+ return 'fps=' + Math.round(deltas.length * 1000 / total) + ' p50=' + deltas[deltas.length >> 1].toFixed(0) +
+ ' p95=' + deltas[Math.floor(deltas.length * 0.95)].toFixed(0) + ' max=' + deltas[deltas.length - 1].toFixed(0);
+};
+
+// __css('selector { ... }') injects a style override for A/B experiments.
+window.__css = function (text) {
+ let el = document.getElementById('dev-css');
+ if (!el) { el = document.createElement('style'); el.id = 'dev-css'; document.head.appendChild(el); }
+ el.textContent = text;
+ return 'css set';
+};
diff --git a/app/js/input.js b/app/js/input.js
new file mode 100644
index 0000000..6e3fe90
--- /dev/null
+++ b/app/js/input.js
@@ -0,0 +1,86 @@
+// Remote input. Navigation keys are applied at most once per animation frame
+// (extra presses of the same key in one frame collapse), so holding a direction
+// can never queue up work and the UI stops the instant the key is released.
+// While a key is held, <html> gets .fast which shortens transitions.
+import { actionFor } from './platform/tizen.js';
+
+const NAV = { left: 1, right: 1, up: 1, down: 1 };
+
+let handler = null;
+let pending = null;
+let scheduled = false;
+let fastTimer = 0;
+let lastNavAt = 0;
+const root = document.documentElement;
+
+export const stats = { keyAt: 0, latency: 0 };
+
+export function setHandler(fn) {
+ handler = fn;
+}
+
+function setFast(on) {
+ if (root.classList.contains('fast') !== on) root.classList.toggle('fast', on);
+}
+
+function flush() {
+ if (!scheduled) return;
+ scheduled = false;
+ const action = pending;
+ pending = null;
+ if (action && handler) handler(action);
+}
+
+document.addEventListener('keydown', e => {
+ const action = actionFor(e);
+ if (!action) return;
+ // Let text inputs (search) handle their own keys except navigation out.
+ const tag = document.activeElement && document.activeElement.tagName;
+ if (tag === 'INPUT' && action !== 'back' && action !== 'down' && action !== 'up' && action !== 'enter') return;
+ e.preventDefault();
+ stats.keyAt = performance.now();
+
+ if (NAV[action]) {
+ const now = performance.now();
+ const held = e.repeat || now - lastNavAt < 140;
+ lastNavAt = now;
+ if (held) {
+ setFast(true);
+ clearTimeout(fastTimer);
+ fastTimer = setTimeout(() => setFast(false), 220);
+ }
+ pending = action;
+ if (!scheduled) {
+ scheduled = true;
+ requestAnimationFrame(flush);
+ // rAF pauses when the page is occluded; never let input stall on it.
+ setTimeout(flush, 50);
+ }
+ return;
+ }
+ if (handler) handler(action);
+}, true);
+
+// Feed an action through the same path as a real key press (dev remote).
+export function inject(action) {
+ stats.keyAt = performance.now();
+ if (NAV[action]) {
+ pending = action;
+ if (!scheduled) {
+ scheduled = true;
+ requestAnimationFrame(flush);
+ setTimeout(flush, 50);
+ }
+ return;
+ }
+ if (handler) handler(action);
+}
+
+document.addEventListener('keyup', () => {
+ clearTimeout(fastTimer);
+ fastTimer = setTimeout(() => setFast(false), 60);
+});
+
+export function isFast() {
+ return root.classList.contains('fast');
+}
diff --git a/app/js/main.js b/app/js/main.js
new file mode 100644
index 0000000..52a734c
--- /dev/null
+++ b/app/js/main.js
@@ -0,0 +1,3 @@
+import { boot } from './app.js';
+
+boot();
diff --git a/app/js/nav.js b/app/js/nav.js
new file mode 100644
index 0000000..2a0b649
--- /dev/null
+++ b/app/js/nav.js
@@ -0,0 +1,33 @@
+// Where selecting things goes. Kept in one place so screens don't import each other.
+import * as router from './router.js';
+import { DetailScreen } from './screens/detail.js';
+import { LibraryScreen } from './screens/library.js';
+import { PlayerScreen } from './screens/player.js';
+import { SearchScreen } from './screens/search.js';
+import { SettingsScreen } from './screens/settings.js';
+
+export function openItem(item) {
+ if (item.type === 'clip') { playItem(item); return; }
+ router.push(DetailScreen(item));
+}
+
+export function playItem(item, opts) {
+ if (item.type === 'show' || item.type === 'season') {
+ // Play on a show means "the next episode"; the detail screen resolves it.
+ router.push(DetailScreen(item, { autoplay: true }));
+ return;
+ }
+ router.push(PlayerScreen(item, opts || {}));
+}
+
+export function openLibrary(section) {
+ router.push(LibraryScreen(section));
+}
+
+export function openSearch() {
+ router.push(SearchScreen());
+}
+
+export function openSettings() {
+ router.push(SettingsScreen());
+}
diff --git a/app/js/platform/player.js b/app/js/platform/player.js
new file mode 100644
index 0000000..54fe28d
--- /dev/null
+++ b/app/js/platform/player.js
@@ -0,0 +1,121 @@
+// Video backend: Samsung AVPlay (hardware decode, plays straight to the video
+// plane under the web layer) on the TV, <video> in a desktop browser.
+//
+// listener: { onTime(ms), onBuffering(bool), onEnd(), onError(msg), onSubtitle(text, durationMs) }
+
+function avplayBackend(container, listener) {
+ const av = webapis.avplay;
+ const obj = document.createElement('object');
+ obj.type = 'application/avplayer';
+ obj.className = 'av-object';
+ container.appendChild(obj);
+ let opened = false;
+
+ const api = {
+ open(url, { uhd = false } = {}) {
+ api.close();
+ av.open(url);
+ opened = true;
+ av.setDisplayRect(0, 0, 1920, 1080);
+ av.setDisplayMethod('PLAYER_DISPLAY_MODE_LETTER_BOX');
+ if (uhd) {
+ try { av.setStreamingProperty('SET_MODE_4K', 'TRUE'); } catch (e) { /* not a UHD panel */ }
+ }
+ av.setListener({
+ onbufferingstart: () => listener.onBuffering(true),
+ onbufferingprogress: () => {},
+ onbufferingcomplete: () => listener.onBuffering(false),
+ oncurrentplaytime: ms => listener.onTime(ms),
+ onstreamcompleted: () => listener.onEnd(),
+ onerror: e => listener.onError(String(e)),
+ onevent: () => {},
+ onsubtitlechange: (duration, text) => listener.onSubtitle(text, Number(duration)),
+ ondrmevent: () => {},
+ });
+ },
+ prepare() {
+ return new Promise((resolve, reject) => av.prepareAsync(resolve, e => reject(new Error(String(e && e.name || e)))));
+ },
+ play() { av.play(); },
+ pause() { av.pause(); },
+ seek(ms) {
+ return new Promise((resolve, reject) => av.seekTo(Math.max(0, Math.floor(ms)), resolve, e => reject(new Error(String(e && e.name || e)))));
+ },
+ time() {
+ try { return av.getCurrentTime(); } catch (e) { return 0; }
+ },
+ state() {
+ try { return av.getState(); } catch (e) { return 'NONE'; }
+ },
+ tracks() {
+ let info = [];
+ try { info = av.getTotalTrackInfo() || []; } catch (e) {}
+ return {
+ audio: info.filter(t => t.type === 'AUDIO').map(t => t.index),
+ text: info.filter(t => t.type === 'TEXT').map(t => t.index),
+ };
+ },
+ selectAudio(avIndex) {
+ try { av.setSelectTrack('AUDIO', avIndex); return true; } catch (e) { return false; }
+ },
+ selectText(avIndex) {
+ try {
+ if (avIndex == null) { av.setSilentSubtitle(true); return true; }
+ av.setSelectTrack('TEXT', avIndex);
+ av.setSilentSubtitle(false);
+ return true;
+ } catch (e) { return false; }
+ },
+ suspend() { try { av.suspend(); } catch (e) {} },
+ restore() { try { av.restore(); } catch (e) {} },
+ close() {
+ if (!opened) return;
+ opened = false;
+ try { av.stop(); } catch (e) {}
+ try { av.close(); } catch (e) {}
+ },
+ destroy() {
+ api.close();
+ if (obj.parentNode) obj.parentNode.removeChild(obj);
+ },
+ };
+ return api;
+}
+
+function videoBackend(container, listener) {
+ const v = document.createElement('video');
+ v.className = 'av-object';
+ container.appendChild(v);
+ v.addEventListener('timeupdate', () => listener.onTime(v.currentTime * 1000));
+ v.addEventListener('waiting', () => listener.onBuffering(true));
+ v.addEventListener('playing', () => listener.onBuffering(false));
+ v.addEventListener('ended', () => listener.onEnd());
+ v.addEventListener('error', () => listener.onError('video error ' + (v.error && v.error.code)));
+ return {
+ open(url) { v.src = url; },
+ prepare() {
+ return new Promise((resolve, reject) => {
+ v.addEventListener('loadedmetadata', resolve, { once: true });
+ v.addEventListener('error', () => reject(new Error('load failed')), { once: true });
+ v.load();
+ });
+ },
+ play() { v.play(); },
+ pause() { v.pause(); },
+ seek(ms) { v.currentTime = ms / 1000; return Promise.resolve(); },
+ time() { return v.currentTime * 1000; },
+ state() { return v.paused ? 'PAUSED' : 'PLAYING'; },
+ tracks() { return { audio: [], text: [] }; },
+ selectAudio() { return false; },
+ selectText() { return false; },
+ suspend() {},
+ restore() {},
+ close() { v.removeAttribute('src'); v.load(); },
+ destroy() { v.removeAttribute('src'); if (v.parentNode) v.parentNode.removeChild(v); },
+ };
+}
+
+export function createPlayer(container, listener) {
+ if (typeof webapis !== 'undefined' && webapis.avplay) return avplayBackend(container, listener);
+ return videoBackend(container, listener);
+}
diff --git a/app/js/platform/tizen.js b/app/js/platform/tizen.js
new file mode 100644
index 0000000..222c886
--- /dev/null
+++ b/app/js/platform/tizen.js
@@ -0,0 +1,55 @@
+// Thin wrapper over the Tizen / Samsung web APIs, with desktop-browser fallbacks
+// so the UI can also be developed in Chrome.
+import { warn } from '../util/log.js';
+
+export const isTizen = typeof window.tizen !== 'undefined';
+
+// keyCode → action. Desktop keys mirror the remote for development in a browser.
+const KEYMAP = {
+ 37: 'left', 38: 'up', 39: 'right', 40: 'down', 13: 'enter',
+ 10009: 'back', 8: 'back', 27: 'back',
+ 10252: 'playpause', 32: 'playpause', 415: 'play', 19: 'pause', 413: 'stop',
+ 417: 'ff', 412: 'rw', 427: 'pageup', 428: 'pagedown', 33: 'pageup', 34: 'pagedown',
+ 403: 'red', 404: 'green', 405: 'yellow', 406: 'blue', 457: 'info', 10073: 'info',
+};
+
+export function actionFor(e) {
+ return KEYMAP[e.keyCode] || null;
+}
+
+export function registerKeys() {
+ if (!isTizen) return;
+ const keys = ['MediaPlayPause', 'MediaPlay', 'MediaPause', 'MediaStop', 'MediaFastForward',
+ 'MediaRewind', 'ChannelUp', 'ChannelDown', 'ColorF0Red', 'ColorF1Green', 'ColorF2Yellow',
+ 'ColorF3Blue', 'Info'];
+ for (const k of keys) {
+ try { tizen.tvinputdevice.registerKey(k); } catch (e) { warn('registerKey failed', k); }
+ }
+}
+
+export function exitApp() {
+ try { tizen.application.getCurrentApplication().exit(); } catch (e) { window.close(); }
+}
+
+export function deviceInfo() {
+ let model = 'Browser';
+ let name = 'SamSUCKS';
+ try { model = webapis.productinfo.getRealModel() || webapis.productinfo.getModel(); } catch (e) {}
+ try { name = 'Samsung ' + (webapis.productinfo.getModel() || 'TV'); } catch (e) {}
+ // PMS has a built-in "Tizen" profile (the official app) that rejects our
+ // transcode requests with 400; "Samsung" gets the generic profile plus our
+ // own X-Plex-Client-Profile-Extra.
+ return { model, name, platform: isTizen ? 'Samsung' : 'Web' };
+}
+
+export function supports4K() {
+ try { return webapis.productinfo.isUdPanelSupported(); } catch (e) { return false; }
+}
+
+// Keep the screen saver from kicking in during playback.
+export function setScreenSaver(on) {
+ try {
+ webapis.appcommon.setScreenSaver(on ? webapis.appcommon.AppCommonScreenSaverState.SCREEN_SAVER_ON
+ : webapis.appcommon.AppCommonScreenSaverState.SCREEN_SAVER_OFF);
+ } catch (e) {}
+}
diff --git a/app/js/player/subtitles.js b/app/js/player/subtitles.js
new file mode 100644
index 0000000..725ed46
--- /dev/null
+++ b/app/js/player/subtitles.js
@@ -0,0 +1,93 @@
+// Sidecar (external) text subtitles, rendered by us over a direct-played video,
+// so an .srt next to the file never forces the server to transcode.
+
+function ms(h, m, s, frac) {
+ return ((+h * 60 + +m) * 60 + +s) * 1000 + Math.round(+('0.' + (frac || '0')) * 1000);
+}
+
+function clean(text) {
+ return text
+ .replace(/\{\\[^}]*\}/g, '')
+ .replace(/<[^>]+>/g, '')
+ .replace(/\\N/gi, '\n')
+ .trim();
+}
+
+function parseSrtOrVtt(text) {
+ const cues = [];
+ const re = /(\d+):(\d{2}):(\d{2})[,.](\d{1,3})\s*-->\s*(\d+):(\d{2}):(\d{2})[,.](\d{1,3})[^\n]*\n([\s\S]*?)(?:\n\s*\n|$)/g;
+ let m;
+ while ((m = re.exec(text))) {
+ cues.push({ start: ms(m[1], m[2], m[3], m[4]), end: ms(m[5], m[6], m[7], m[8]), text: clean(m[9]) });
+ }
+ // WebVTT allows mm:ss.ttt without hours.
+ if (!cues.length) {
+ const short = /(\d{2}):(\d{2})\.(\d{3})\s*-->\s*(\d{2}):(\d{2})\.(\d{3})[^\n]*\n([\s\S]*?)(?:\n\s*\n|$)/g;
+ while ((m = short.exec(text))) {
+ cues.push({ start: ms(0, m[1], m[2], m[3]), end: ms(0, m[4], m[5], m[6]), text: clean(m[7]) });
+ }
+ }
+ return cues;
+}
+
+function parseAss(text) {
+ const cues = [];
+ const lines = text.split(/\r?\n/);
+ let textIndex = 9;
+ for (const line of lines) {
+ if (/^Format:/i.test(line) && /Text/i.test(line)) {
+ const fields = line.slice(7).split(',').map(f => f.trim().toLowerCase());
+ textIndex = fields.indexOf('text');
+ }
+ if (!/^Dialogue:/i.test(line)) continue;
+ const parts = line.slice(9).split(',');
+ const t = s => s.trim().match(/(\d+):(\d{2}):(\d{2})\.(\d{1,3})/);
+ const a = t(parts[1]);
+ const b = t(parts[2]);
+ if (!a || !b) continue;
+ cues.push({ start: ms(a[1], a[2], a[3], a[4]), end: ms(b[1], b[2], b[3], b[4]), text: clean(parts.slice(textIndex).join(',')) });
+ }
+ return cues.sort((x, y) => x.start - y.start);
+}
+
+export function parseSubtitles(text, codec) {
+ text = text.replace(/\r\n/g, '\n').replace(/^/, '');
+ if (codec === 'ass' || codec === 'ssa' || /^\[Script Info\]/m.test(text)) return parseAss(text);
+ return parseSrtOrVtt(text);
+}
+
+// Finds the active cue for a playback position; cheap for monotonic playback,
+// binary search after jumps.
+export class CueTrack {
+ constructor(cues) {
+ this.cues = cues;
+ this.i = 0;
+ }
+
+ at(t) {
+ const cues = this.cues;
+ if (!cues.length) return '';
+ let i = this.i;
+ if (i >= cues.length || cues[i].start > t || (i + 1 < cues.length && cues[i + 1].start <= t && t - cues[i].start > 30000)) {
+ let lo = 0;
+ let hi = cues.length - 1;
+ while (lo < hi) {
+ const mid = (lo + hi + 1) >> 1;
+ if (cues[mid].start <= t) lo = mid; else hi = mid - 1;
+ }
+ i = lo;
+ }
+ while (i + 1 < cues.length && cues[i + 1].start <= t) i++;
+ this.i = i;
+ const c = cues[i];
+ if (c.start <= t && t < c.end) {
+ // Overlapping cues (common in ASS) are shown together.
+ let text = c.text;
+ for (let j = i - 1; j >= 0 && j >= i - 3; j--) {
+ if (cues[j].end > t && cues[j].text !== text) text = cues[j].text + '\n' + text;
+ }
+ return text;
+ }
+ return '';
+ }
+}
diff --git a/app/js/plex/auth.js b/app/js/plex/auth.js
new file mode 100644
index 0000000..4ee5e24
--- /dev/null
+++ b/app/js/plex/auth.js
@@ -0,0 +1,79 @@
+// plex.tv sign-in (PIN / plex.tv/link) and server discovery.
+import { request, clientId, PRODUCT, query } from './client.js';
+import { log, warn } from '../util/log.js';
+
+const TV = 'https://plex.tv/api/v2';
+
+export async function createPin() {
+ // Non-strong PINs are the 4-character codes plex.tv/link accepts.
+ return request(TV + '/pins', { method: 'POST', params: { strong: 'false' } });
+}
+
+export async function checkPin(id) {
+ const pin = await request(TV + '/pins/' + id);
+ return pin.authToken || null;
+}
+
+// Link that signs this device in from a phone, encoded in the login QR code.
+export function authAppUrl(code) {
+ return 'https://app.plex.tv/auth#?' + query({
+ clientID: clientId,
+ code,
+ 'context[device][product]': PRODUCT,
+ });
+}
+
+export async function getUser(token) {
+ return request(TV + '/user', { token });
+}
+
+export async function getServers(token) {
+ const resources = await request(TV + '/resources', {
+ token, params: { includeHttps: 1, includeRelay: 1, includeIPv6: 0 },
+ });
+ return resources.filter(r => (r.provides || '').indexOf('server') !== -1);
+}
+
+function probe(uri, token, timeout) {
+ const started = Date.now();
+ return request(uri + '/identity', { token, timeout }).then(() => ({ uri, ms: Date.now() - started }));
+}
+
+// Plain HTTP on the LAN is the fastest path on a TV CPU (no TLS), so try that
+// first, then the plex.direct HTTPS URLs, then remote, then relay.
+export function candidateUris(resource) {
+ const conns = resource.connections || [];
+ const local = conns.filter(c => c.local && !c.relay);
+ const remote = conns.filter(c => !c.local && !c.relay);
+ const relay = conns.filter(c => c.relay);
+ const tiers = [];
+ if (resource.httpsRequired !== true) {
+ tiers.push(local.map(c => 'http://' + c.address + ':' + c.port));
+ }
+ tiers.push(local.map(c => c.uri));
+ tiers.push(remote.map(c => c.uri));
+ tiers.push(relay.map(c => c.uri));
+ return tiers.filter(t => t.length);
+}
+
+function firstSuccess(promises) {
+ return new Promise((resolve, reject) => {
+ let pending = promises.length;
+ if (!pending) reject(new Error('no candidates'));
+ promises.forEach(p => p.then(resolve, () => { if (--pending === 0) reject(new Error('all failed')); }));
+ });
+}
+
+export async function connect(resource) {
+ const token = resource.accessToken;
+ for (const tier of candidateUris(resource)) {
+ try {
+ const hit = await firstSuccess(tier.map(uri => probe(uri, token, 4000)));
+ log('connected to', resource.name, 'via', hit.uri, hit.ms + 'ms');
+ return hit.uri;
+ } catch (e) {
+ warn('connection tier failed', tier.join(', '));
+ }
+ }
+ throw new Error('Could not reach ' + resource.name);
+}
diff --git a/app/js/plex/client.js b/app/js/plex/client.js
new file mode 100644
index 0000000..f7da95f
--- /dev/null
+++ b/app/js/plex/client.js
@@ -0,0 +1,71 @@
+// Shared request plumbing for plex.tv and Plex Media Server.
+import { VERSION } from '../config.js';
+import { deviceInfo } from '../platform/tizen.js';
+import * as store from '../util/store.js';
+import { uuid } from '../util/format.js';
+
+export const PRODUCT = 'SamSUCKS';
+
+let clientId = store.get('clientId');
+if (!clientId) {
+ clientId = uuid();
+ store.set('clientId', clientId);
+}
+export { clientId };
+
+const device = deviceInfo();
+
+// Identity params, also needed as query params on URLs we hand to AVPlay
+// (which can't send headers).
+export function identity() {
+ return {
+ 'X-Plex-Product': PRODUCT,
+ 'X-Plex-Version': VERSION,
+ 'X-Plex-Client-Identifier': clientId,
+ 'X-Plex-Platform': device.platform,
+ 'X-Plex-Platform-Version': '6.5',
+ 'X-Plex-Device': device.model,
+ 'X-Plex-Device-Name': device.name,
+ 'X-Plex-Model': device.model,
+ };
+}
+
+export function query(params) {
+ const parts = [];
+ for (const k in params) {
+ const v = params[k];
+ if (v === undefined || v === null || v === '') continue;
+ parts.push(encodeURIComponent(k) + '=' + encodeURIComponent(v));
+ }
+ return parts.join('&');
+}
+
+export function withQuery(url, params) {
+ const q = query(params);
+ if (!q) return url;
+ return url + (url.indexOf('?') === -1 ? '?' : '&') + q;
+}
+
+export class HttpError extends Error {
+ constructor(status, url) {
+ super('HTTP ' + status + ' from ' + url.split('?')[0].replace(/^https?:\/\/[^/]+/, ''));
+ this.status = status;
+ }
+}
+
+export async function request(url, { method = 'GET', token, params, timeout = 15000, body, raw } = {}) {
+ const headers = Object.assign({ Accept: 'application/json' }, identity());
+ if (token) headers['X-Plex-Token'] = token;
+ const ctrl = typeof AbortController !== 'undefined' ? new AbortController() : null;
+ const timer = ctrl ? setTimeout(() => ctrl.abort(), timeout) : 0;
+ const full = withQuery(url, params);
+ try {
+ const res = await fetch(full, { method, headers, body, signal: ctrl ? ctrl.signal : undefined });
+ if (!res.ok) throw new HttpError(res.status, full);
+ if (raw) return res;
+ const text = await res.text();
+ return text ? JSON.parse(text) : {};
+ } finally {
+ clearTimeout(timer);
+ }
+}
diff --git a/app/js/plex/server.js b/app/js/plex/server.js
new file mode 100644
index 0000000..8ef4292
--- /dev/null
+++ b/app/js/plex/server.js
@@ -0,0 +1,138 @@
+// Plex Media Server API, scoped to the features this client uses.
+import { request, withQuery, identity } from './client.js';
+
+const SUPPORTED_HUB_TYPES = { movie: 1, show: 1, episode: 1, season: 1, mixed: 1, clip: 1 };
+
+export class Server {
+ constructor({ uri, token, name, id }) {
+ this.uri = uri;
+ this.token = token;
+ this.name = name;
+ this.id = id;
+ this.cache = new Map();
+ }
+
+ async get(path, params, { maxAge = 0 } = {}) {
+ const key = withQuery(path, params);
+ if (maxAge) {
+ const hit = this.cache.get(key);
+ if (hit && Date.now() - hit.t < maxAge) return hit.data;
+ }
+ const json = await request(this.uri + path, { token: this.token, params });
+ const data = json.MediaContainer || json;
+ if (maxAge) this.cache.set(key, { t: Date.now(), data });
+ return data;
+ }
+
+ invalidate() {
+ this.cache.clear();
+ }
+
+ // Posters/backdrops resized (and optionally blurred) by the server, so the TV
+ // only ever downloads and decodes pixels it actually shows.
+ image(path, width, height, { blur = 0, quality = 85, format = 'jpeg' } = {}) {
+ if (!path) return '';
+ return withQuery(this.uri + '/photo/:/transcode', {
+ width, height, minSize: 1, upscale: 1, blur: blur || undefined,
+ quality, format, url: path, 'X-Plex-Token': this.token,
+ });
+ }
+
+ url(path, params) {
+ return withQuery(this.uri + path, Object.assign({ 'X-Plex-Token': this.token }, params));
+ }
+
+ async sections() {
+ const mc = await this.get('/library/sections', null, { maxAge: 300000 });
+ return (mc.Directory || []).filter(d => d.type === 'movie' || d.type === 'show');
+ }
+
+ async hubs() {
+ const mc = await this.get('/hubs', { count: 24, includeExternalMedia: 0 });
+ return (mc.Hub || []).filter(h => h.size > 0 && SUPPORTED_HUB_TYPES[h.type] && h.Metadata);
+ }
+
+ async sectionHubs(sectionId) {
+ const mc = await this.get('/hubs/sections/' + sectionId, { count: 24 });
+ return (mc.Hub || []).filter(h => h.size > 0 && SUPPORTED_HUB_TYPES[h.type] && h.Metadata);
+ }
+
+ async items(sectionId, start, size, { sort = 'titleSort', type } = {}) {
+ const mc = await this.get('/library/sections/' + sectionId + '/all', {
+ sort, type,
+ 'X-Plex-Container-Start': start,
+ 'X-Plex-Container-Size': size,
+ excludeFields: 'summary,tagline',
+ });
+ return { total: mc.totalSize != null ? mc.totalSize : mc.size, items: mc.Metadata || [] };
+ }
+
+ async metadata(ratingKey) {
+ const mc = await this.get('/library/metadata/' + ratingKey, { includeOnDeck: 1, includeExtras: 0 });
+ const item = (mc.Metadata || [])[0];
+ if (item && mc.OnDeck && mc.OnDeck.Metadata) item.onDeck = mc.OnDeck.Metadata[0];
+ return item;
+ }
+
+ async children(ratingKey) {
+ const mc = await this.get('/library/metadata/' + ratingKey + '/children', { excludeAllLeaves: 1 });
+ return mc.Metadata || [];
+ }
+
+ async search(q) {
+ const mc = await this.get('/hubs/search', { query: q, limit: 30, includeCollections: 0 });
+ return (mc.Hub || []).filter(h => h.size > 0 && SUPPORTED_HUB_TYPES[h.type] && h.Metadata);
+ }
+
+ timeline(params) {
+ return request(this.uri + '/:/timeline', { token: this.token, params, timeout: 8000 }).catch(() => {});
+ }
+
+ scrobble(ratingKey) {
+ return request(this.uri + '/:/scrobble', {
+ token: this.token, params: { identifier: 'com.plexapp.plugins.library', key: ratingKey },
+ });
+ }
+
+ unscrobble(ratingKey) {
+ return request(this.uri + '/:/unscrobble', {
+ token: this.token, params: { identifier: 'com.plexapp.plugins.library', key: ratingKey },
+ });
+ }
+
+ // HLS URL for content the TV can't direct play. Video is passed through when
+ // possible; only the audio (e.g. DTS) or container gets converted.
+ transcodeUrl(item, { session, offsetMs = 0, mediaIndex = 0, maxBitrate = 40000, resolution = '3840x2160', audioStreamID, subtitleStreamID } = {}) {
+ const extra = [
+ 'add-transcode-target(type=videoProfile&context=streaming&protocol=hls&container=mpegts&videoCodec=h264,hevc&audioCodec=aac,ac3,eac3)',
+ 'add-direct-play-profile(type=videoProfile&container=mp4,mkv&videoCodec=h264,hevc&audioCodec=aac,ac3,eac3)',
+ ].join('+');
+ return withQuery(this.uri + '/video/:/transcode/universal/start.m3u8', Object.assign({}, identity(), {
+ path: '/library/metadata/' + item.ratingKey,
+ mediaIndex, partIndex: 0,
+ protocol: 'hls', fastSeek: 1,
+ directPlay: 0, directStream: 1, directStreamAudio: 1,
+ offset: Math.floor(offsetMs / 1000),
+ videoQuality: 100, videoResolution: resolution, maxVideoBitrate: maxBitrate,
+ subtitles: subtitleStreamID ? 'burn' : 'none', subtitleSize: 100,
+ audioBoost: 100, location: 'lan', copyts: 1,
+ session, 'X-Plex-Session-Identifier': session,
+ 'X-Plex-Client-Profile-Extra': extra,
+ 'X-Plex-Token': this.token,
+ }));
+ }
+
+ // Selected audio/subtitle streams are stored per part on the server.
+ selectStreams(partId, { audioStreamID, subtitleStreamID }) {
+ return request(this.uri + '/library/parts/' + partId, {
+ method: 'PUT', token: this.token,
+ params: { audioStreamID, subtitleStreamID, allParts: 1 },
+ }).catch(() => {});
+ }
+
+ stopTranscode(session) {
+ return request(this.uri + '/video/:/transcode/universal/stop', {
+ token: this.token, params: { session }, timeout: 5000,
+ }).catch(() => {});
+ }
+}
diff --git a/app/js/router.js b/app/js/router.js
new file mode 100644
index 0000000..952ceec
--- /dev/null
+++ b/app/js/router.js
@@ -0,0 +1,70 @@
+// Screen stack. Screens below the top stay in the DOM but hidden, so going
+// back is instant and keeps its scroll/focus state.
+//
+// A screen is { el, onKey(action) -> bool?, onShow?(), onHide?(), destroy?() }.
+import { setHandler } from './input.js';
+import { exitApp } from './platform/tizen.js';
+
+const stack = [];
+let root = null;
+let globalKey = null;
+
+export function init(container, onGlobalKey) {
+ root = container;
+ globalKey = onGlobalKey;
+ setHandler(action => {
+ const top = stack[stack.length - 1];
+ if (top && top.onKey && top.onKey(action) === true) return;
+ if (globalKey && globalKey(action) === true) return;
+ if (action === 'back') back();
+ });
+}
+
+function hide(screen) {
+ screen.el.classList.add('hidden');
+ if (screen.onHide) screen.onHide();
+}
+
+function reveal(screen) {
+ screen.el.classList.remove('hidden');
+ if (screen.onShow) screen.onShow();
+}
+
+export function push(screen) {
+ const top = stack[stack.length - 1];
+ if (top) hide(top);
+ stack.push(screen);
+ root.appendChild(screen.el);
+ reveal(screen);
+}
+
+export function replace(screen) {
+ const top = stack.pop();
+ if (top) destroy(top);
+ push(screen);
+}
+
+// Clear everything and start over from one screen (sign in/out, server switch).
+export function reset(screen) {
+ while (stack.length) destroy(stack.pop());
+ push(screen);
+}
+
+function destroy(screen) {
+ if (screen.onHide) screen.onHide();
+ if (screen.destroy) screen.destroy();
+ if (screen.el.parentNode) screen.el.parentNode.removeChild(screen.el);
+}
+
+export function back() {
+ if (stack.length <= 1) {
+ exitApp();
+ return;
+ }
+ destroy(stack.pop());
+ reveal(stack[stack.length - 1]);
+}
+
+export function top() {
+ return stack[stack.length - 1];
+}
diff --git a/app/js/screens/detail.js b/app/js/screens/detail.js
new file mode 100644
index 0000000..15ffc6b
--- /dev/null
+++ b/app/js/screens/detail.js
@@ -0,0 +1,244 @@
+// Detail page for a movie, show, season (opens its show) or episode.
+import { h, setText, setTransform, toggleClass } from '../util/dom.js';
+import { useAmbience, HeroArt } from '../ui/backdrop.js';
+import { Row } from '../ui/row.js';
+import { session } from '../session.js';
+import { metaLine, clock, episodeLabel } from '../util/format.js';
+import { clearLogo } from './home.js';
+import * as icons from '../ui/icons.js';
+import * as router from '../router.js';
+import { playItem } from '../nav.js';
+import { error } from '../util/log.js';
+
+const SHIFT = 400; // how far the body slides up to reveal seasons/episodes
+
+export function DetailScreen(initial, { autoplay = false } = {}) {
+ const el = h('div', 'screen detail');
+ const ambience = useAmbience(initial.UltraBlurColors);
+ const art = new HeroArt(el, 'hero-art detail-art');
+ const body = h('div', 'detail-body', el);
+ const logo = h('img', 'detail-logo', body);
+ const title = h('h1', 'detail-title', body);
+ const sub = h('div', 'detail-sub', body);
+ const meta = h('div', 'detail-meta', body);
+ const tags = h('div', 'detail-tags', body);
+ const summary = h('p', 'detail-summary', body);
+ const buttonsEl = h('div', 'detail-buttons', body);
+ const seasonsEl = h('div', 'detail-seasons', body);
+ const episodesWrap = h('div', 'detail-episodes', body);
+
+ let item = initial;
+ let buttons = [];
+ let buttonIndex = 0;
+ let seasons = [];
+ let seasonIndex = 0;
+ let episodes = null;
+ let zone = 'buttons';
+ let alive = true;
+ let shown = false;
+
+ const isShowLike = () => item.type === 'show';
+
+ function renderHeader() {
+ const server = session.server;
+ const logoPath = clearLogo(item);
+ const showTitle = item.type === 'episode' ? item.grandparentTitle : item.title;
+ if (logoPath) {
+ logo.src = server.image(logoPath, 720, 240, { format: 'png' });
+ logo.style.display = '';
+ title.style.display = 'none';
+ } else {
+ logo.style.display = 'none';
+ title.style.display = '';
+ setText(title, showTitle);
+ }
+ setText(sub, item.type === 'episode' ? episodeLabel(item) + ' ' + item.title : (item.tagline || ''));
+ setText(meta, metaLine(item));
+ const genres = (item.Genre || []).slice(0, 3).map(g => g.tag);
+ const people = (item.Director || []).slice(0, 1).map(d => 'Directed by ' + d.tag)
+ .concat((item.Role || []).length ? ['Starring ' + item.Role.slice(0, 3).map(r => r.tag).join(', ')] : []);
+ setText(tags, genres.concat(people).join(' · '));
+ setText(summary, item.summary || '');
+ ambience.set(item.UltraBlurColors);
+ const artPath = item.type === 'episode' ? (item.grandparentArt || item.art) : item.art;
+ art.set(server.image(artPath, 1920, 1080));
+ }
+
+ function target() {
+ // What Play acts on: the item itself, or for a show the next episode.
+ if (!isShowLike()) return item;
+ if (item.onDeck) return item.onDeck;
+ if (!episodes) return null;
+ const eps = episodes.items;
+ return eps.find(e => e.viewOffset) || eps.find(e => !e.viewCount) || eps[0] || null;
+ }
+
+ function renderButtons() {
+ buttonsEl.innerHTML = '';
+ buttons = [];
+ const t = target();
+ const add = (icon, label, run) => {
+ const b = h('div', 'btn', buttonsEl);
+ b.innerHTML = icon;
+ h('span', '', b).textContent = label;
+ buttons.push({ el: b, run });
+ };
+ if (t) {
+ const prefix = isShowLike() ? episodeLabel(t) + ' ' : '';
+ if (t.viewOffset) {
+ add(icons.play, prefix + 'Resume ' + clock(t.viewOffset), () => playItem(t, { offset: t.viewOffset }));
+ add(icons.restart, 'From the start', () => playItem(t, { offset: 0 }));
+ } else {
+ add(icons.play, isShowLike() ? 'Play ' + prefix : 'Play', () => playItem(t, { offset: 0 }));
+ }
+ }
+ const watched = isShowLike() ? item.viewedLeafCount >= item.leafCount : !!item.viewCount;
+ add(watched ? icons.check : icons.uncheck, watched ? 'Watched' : 'Mark watched', toggleWatched);
+ if (item.type === 'episode' && item.grandparentRatingKey) {
+ add(icons.tv, 'Go to show', () => router.push(DetailScreen({ ratingKey: item.grandparentRatingKey, type: 'show', title: item.grandparentTitle })));
+ }
+ buttonIndex = Math.min(buttonIndex, buttons.length - 1);
+ renderFocus();
+ }
+
+ function renderSeasons() {
+ seasonsEl.innerHTML = '';
+ seasons.forEach(s => { s.el = h('div', 'pill', seasonsEl); s.el.textContent = s.title; });
+ renderFocus();
+ }
+
+ function renderFocus() {
+ buttons.forEach((b, i) => toggleClass(b.el, 'focus', zone === 'buttons' && i === buttonIndex));
+ seasons.forEach((s, i) => {
+ toggleClass(s.el, 'focus', zone === 'seasons' && i === seasonIndex);
+ toggleClass(s.el, 'current', i === seasonIndex);
+ });
+ if (episodes) episodes.row.setActive(zone === 'episodes');
+ setTransform(body, zone === 'buttons' ? 'translateY(0)' : 'translateY(' + (-SHIFT) + 'px)');
+ toggleClass(el, 'shifted', zone !== 'buttons');
+ }
+
+ async function loadEpisodes(season) {
+ const kids = await session.server.children(season.ratingKey);
+ if (!alive) return;
+ if (!episodes) {
+ const row = new Row({
+ kind: 'episode', caption: true, items: kids,
+ onSelect: ep => playItem(ep, { offset: ep.viewOffset || 0 }),
+ });
+ episodesWrap.appendChild(row.el);
+ episodes = { row, items: kids };
+ } else {
+ episodes.items = kids;
+ episodes.row.setItems(kids);
+ }
+ // Land on the first unwatched episode.
+ const next = kids.findIndex(k => !k.viewCount || k.viewOffset);
+ episodes.row.focusIndex(next >= 0 ? next : 0);
+ renderFocus();
+ }
+
+ async function load() {
+ try {
+ let key = item.ratingKey;
+ let preferSeason = null;
+ if (item.type === 'season') { preferSeason = item.ratingKey; key = item.parentRatingKey; }
+ const full = await session.server.metadata(key);
+ if (!alive || !full) return;
+ item = full;
+ renderHeader();
+ if (isShowLike()) {
+ seasons = (await session.server.children(item.ratingKey)).filter(s => s.type === 'season');
+ if (!alive) return;
+ const deckSeason = item.onDeck ? seasons.findIndex(s => s.ratingKey === item.onDeck.parentRatingKey) : -1;
+ const pref = preferSeason ? seasons.findIndex(s => s.ratingKey === preferSeason) : -1;
+ seasonIndex = pref >= 0 ? pref : (deckSeason >= 0 ? deckSeason : 0);
+ renderSeasons();
+ if (seasons[seasonIndex]) await loadEpisodes(seasons[seasonIndex]);
+ }
+ renderButtons();
+ if (autoplay) {
+ autoplay = false;
+ const t = target();
+ if (t) playItem(t, { offset: t.viewOffset || 0 });
+ }
+ } catch (e) {
+ error('detail load failed', e);
+ setText(summary, 'Couldn\'t load details.');
+ }
+ }
+
+ async function toggleWatched() {
+ const server = session.server;
+ const watched = isShowLike() ? item.viewedLeafCount >= item.leafCount : !!item.viewCount;
+ try {
+ if (watched) await server.unscrobble(item.ratingKey);
+ else await server.scrobble(item.ratingKey);
+ server.invalidate();
+ await load();
+ } catch (e) {
+ error('toggle watched failed', e);
+ }
+ }
+
+ if (item.title) renderHeader();
+ renderButtons();
+ load();
+
+ function moveZone(dir) {
+ const order = ['buttons'];
+ if (seasons.length > 1) order.push('seasons');
+ if (episodes) order.push('episodes');
+ const i = order.indexOf(zone) + dir;
+ if (i < 0 || i >= order.length) return;
+ zone = order[i];
+ renderFocus();
+ }
+
+ return {
+ el,
+ name: 'detail',
+ onShow() {
+ ambience.restore();
+ // Back from the player: refresh resume points and watched state.
+ if (shown) {
+ session.server.invalidate();
+ load();
+ }
+ shown = true;
+ },
+ onKey(action) {
+ if (action === 'up') { moveZone(-1); return true; }
+ if (action === 'down') { moveZone(1); return true; }
+ if (action === 'play' || action === 'playpause') {
+ const t = zone === 'episodes' ? episodes.row.current() : target();
+ if (t) playItem(t, { offset: t.viewOffset || 0 });
+ return true;
+ }
+ if (zone === 'buttons') {
+ if (action === 'left') { buttonIndex = Math.max(0, buttonIndex - 1); renderFocus(); return true; }
+ if (action === 'right') { buttonIndex = Math.min(buttons.length - 1, buttonIndex + 1); renderFocus(); return true; }
+ if (action === 'enter' && buttons[buttonIndex]) { buttons[buttonIndex].run(); return true; }
+ } else if (zone === 'seasons') {
+ if (action === 'left' || action === 'right') {
+ const next = seasonIndex + (action === 'right' ? 1 : -1);
+ if (next >= 0 && next < seasons.length) {
+ seasonIndex = next;
+ renderFocus();
+ loadEpisodes(seasons[seasonIndex]).catch(e => error('episodes failed', e));
+ }
+ return true;
+ }
+ if (action === 'enter') { moveZone(1); return true; }
+ } else if (zone === 'episodes') {
+ if (action === 'left') { episodes.row.move(-1); return true; }
+ if (action === 'right') { episodes.row.move(1); return true; }
+ if (action === 'enter') { episodes.row.select(); return true; }
+ if (action === 'info') { router.push(DetailScreen(episodes.row.current())); return true; }
+ }
+ if (action === 'back' && zone !== 'buttons') { zone = 'buttons'; renderFocus(); return true; }
+ return false;
+ },
+ destroy() { alive = false; },
+ };
+}
diff --git a/app/js/screens/home.js b/app/js/screens/home.js
new file mode 100644
index 0000000..3898ec9
--- /dev/null
+++ b/app/js/screens/home.js
@@ -0,0 +1,250 @@
+// Home: hero for the focused item, nav bar, and Plex's home hubs as rows.
+// The last hub payload is cached so a cold start paints instantly.
+import { h, setText, setTransform, toggleClass } from '../util/dom.js';
+import { Row } from '../ui/row.js';
+import { useAmbience, HeroArt } from '../ui/backdrop.js';
+import { session } from '../session.js';
+import { metaLine } from '../util/format.js';
+import { isFast } from '../input.js';
+import * as store from '../util/store.js';
+import * as icons from '../ui/icons.js';
+import { openItem, playItem, openLibrary, openSearch, openSettings } from '../nav.js';
+import { error, log } from '../util/log.js';
+
+const ROWS_TOP = 600;
+
+function slimHub(hub) {
+ // Keep the cache small: only fields the home screen renders.
+ const keep = ['ratingKey', 'key', 'type', 'title', 'grandparentTitle', 'parentTitle', 'year', 'thumb', 'art',
+ 'grandparentThumb', 'grandparentArt', 'parentThumb', 'index', 'parentIndex', 'duration', 'viewOffset',
+ 'viewCount', 'leafCount', 'viewedLeafCount', 'childCount', 'contentRating', 'audienceRating', 'summary',
+ 'originallyAvailableAt', 'UltraBlurColors', 'grandparentRatingKey', 'parentRatingKey', 'Image'];
+ return {
+ hubIdentifier: hub.hubIdentifier, title: hub.title, type: hub.type,
+ Metadata: hub.Metadata.map(m => {
+ const o = {};
+ for (const k of keep) if (m[k] !== undefined) o[k] = m[k];
+ return o;
+ }),
+ };
+}
+
+export function heroArtPath(item) {
+ if (item.type === 'episode' || item.type === 'season') return item.grandparentArt || item.art;
+ return item.art;
+}
+
+export function clearLogo(item) {
+ const img = (item.Image || []).find(i => i.type === 'clearLogo');
+ return img ? img.url : '';
+}
+
+export function HomeScreen() {
+ const el = h('div', 'screen home');
+ const ambience = useAmbience();
+ const hero = new HeroArt(el, 'hero-art home-art');
+
+ const top = h('header', 'topbar', el);
+ const brand = h('div', 'brand', top);
+ h('img', 'brand-mark', brand).src = 'img/mascot.png';
+ const brandText = h('div', 'brand-text', brand);
+ h('img', 'brand-wordmark', brandText).src = 'img/wordmark.png';
+ h('div', 'brand-by', brandText).textContent = 'by rfaile313';
+ const navEl = h('nav', 'nav', top);
+ const who = h('div', 'topbar-who', top);
+ setText(who, session.server ? session.server.name : '');
+
+ const info = h('div', 'hero-info', el);
+ const heroLogo = h('img', 'hero-logo', info);
+ const heroTitle = h('h1', 'hero-title', info);
+ const heroMeta = h('div', 'hero-meta', info);
+ const heroSummary = h('p', 'hero-summary', info);
+
+ const rowsClip = h('div', 'home-rows', el);
+ rowsClip.style.top = ROWS_TOP + 'px';
+ const track = h('div', 'rows-track', rowsClip);
+ const empty = h('div', 'home-empty', el);
+
+ let rows = [];
+ let offsets = [];
+ let rowIndex = 0;
+ let zone = 'rows';
+ let navItems = [];
+ let navIndex = 0;
+ let loadedAt = 0;
+ let heroTimer = 0;
+ let artTimer = 0;
+ let reportedPaint = false;
+
+ function buildNav(sections) {
+ navEl.innerHTML = '';
+ navItems = [{ label: 'Home', id: 'home' }]
+ .concat(sections.map(s => ({ label: s.title, id: 'section', section: s })))
+ .concat([{ label: 'Search', id: 'search', icon: icons.search }, { label: 'Settings', id: 'settings', icon: icons.gear }]);
+ navItems.forEach((n, i) => {
+ if (n.icon && !navItems[i - 1].icon) h('i', 'nav-sep', navEl);
+ n.el = h('div', 'nav-item' + (n.icon ? ' nav-icon' : ''), navEl);
+ if (n.icon) n.el.innerHTML = n.icon;
+ else h('span', '', n.el).textContent = n.label;
+ });
+ renderNav();
+ }
+
+ function renderNav() {
+ navItems.forEach((n, i) => {
+ toggleClass(n.el, 'focus', zone === 'nav' && i === navIndex);
+ toggleClass(n.el, 'current', n.id === 'home');
+ });
+ toggleClass(el, 'in-nav', zone === 'nav');
+ }
+
+ function showHero(item) {
+ if (!item) return;
+ const logoPath = clearLogo(item);
+ const server = session.server;
+ if (logoPath && item.type !== 'episode') {
+ heroLogo.src = server.image(logoPath, 640, 200, { format: 'png' });
+ heroLogo.style.display = '';
+ heroTitle.style.display = 'none';
+ } else {
+ heroLogo.style.display = 'none';
+ heroTitle.style.display = '';
+ setText(heroTitle, item.type === 'episode' ? item.grandparentTitle : item.title);
+ }
+ setText(heroMeta, (item.type === 'episode' ? item.title + ' · ' : '') + metaLine(item));
+ setText(heroSummary, item.summary || '');
+ ambience.set(item.UltraBlurColors);
+ clearTimeout(artTimer);
+ artTimer = setTimeout(() => hero.set(server.image(heroArtPath(item), 1344, 756)), isFast() ? 350 : 120);
+ }
+
+ function onFocusItem(item) {
+ clearTimeout(heroTimer);
+ // While a key is held, skip the text repaint until the user settles.
+ if (isFast()) heroTimer = setTimeout(() => showHero(item), 160);
+ else showHero(item);
+ }
+
+ function layoutRows() {
+ offsets = [];
+ let y = 0;
+ rows.forEach(r => {
+ offsets.push(y);
+ setTransform(r.el, 'translateY(' + y + 'px)');
+ y += r.height;
+ });
+ }
+
+ function renderRows() {
+ rows.forEach((r, i) => {
+ r.setActive(zone === 'rows' && i === rowIndex);
+ toggleClass(r.el, 'above', i < rowIndex);
+ });
+ setTransform(track, 'translateY(' + (-(offsets[rowIndex] || 0)) + 'px)');
+ }
+
+ function setHubs(hubs) {
+ const sameShape = hubs.length === rows.length && hubs.every((hb, i) => rows[i].hubId === hb.hubIdentifier);
+ const focusedKey = rows[rowIndex] && rows[rowIndex].current() && rows[rowIndex].current().ratingKey;
+ if (sameShape) {
+ hubs.forEach((hb, i) => rows[i].setItems(hb.Metadata, i === rowIndex ? focusedKey : null));
+ } else {
+ track.innerHTML = '';
+ rows = hubs.map(hb => {
+ const wide = /continue|ondeck/i.test(hb.hubIdentifier);
+ const row = new Row({
+ title: hb.title, kind: wide ? 'wide' : 'poster', items: hb.Metadata,
+ onFocus: onFocusItem, onSelect: item => openItem(item),
+ });
+ row.hubId = hb.hubIdentifier;
+ track.appendChild(row.el);
+ return row;
+ });
+ rowIndex = Math.min(rowIndex, Math.max(0, rows.length - 1));
+ layoutRows();
+ }
+ renderRows();
+ setText(empty, rows.length ? '' : 'Nothing here yet. Add some media to your Plex server.');
+ const cur = rows[rowIndex] && rows[rowIndex].current();
+ if (cur) showHero(cur);
+ if (!reportedPaint && rows.length) {
+ reportedPaint = true;
+ log('home rows ready at ' + Math.round(performance.now()) + 'ms after page start');
+ }
+ }
+
+ async function load() {
+ const server = session.server;
+ loadedAt = Date.now();
+ try {
+ const [sections, hubs] = await Promise.all([server.sections(), server.hubs()]);
+ buildNav(sections);
+ setHubs(hubs);
+ store.set('homeCache', { server: server.id, sections, hubs: hubs.map(slimHub) });
+ } catch (e) {
+ error('home load failed', e);
+ if (!rows.length) setText(empty, 'Couldn\'t load from ' + server.name + '. Press OK to retry.');
+ }
+ }
+
+ const cached = store.get('homeCache');
+ if (cached && session.server && cached.server === session.server.id) {
+ buildNav(cached.sections || []);
+ setHubs(cached.hubs || []);
+ } else {
+ buildNav([]);
+ }
+ load();
+
+ function activateNav(n) {
+ if (n.id === 'section') openLibrary(n.section);
+ else if (n.id === 'search') openSearch();
+ else if (n.id === 'settings') openSettings();
+ }
+
+ return {
+ el,
+ name: 'home',
+ onShow() {
+ ambience.restore();
+ // Coming back from playback: progress and Continue Watching changed.
+ if (Date.now() - loadedAt > 5000) load();
+ },
+ onKey(action) {
+ if (zone === 'nav') {
+ if (action === 'left') { navIndex = Math.max(0, navIndex - 1); renderNav(); return true; }
+ if (action === 'right') { navIndex = Math.min(navItems.length - 1, navIndex + 1); renderNav(); return true; }
+ if (action === 'down' && rows.length) { zone = 'rows'; renderNav(); renderRows(); return true; }
+ if (action === 'enter') { activateNav(navItems[navIndex]); return true; }
+ if (action === 'back') return false;
+ return true;
+ }
+ const row = rows[rowIndex];
+ if (!row) {
+ if (action === 'up') { zone = 'nav'; renderNav(); return true; }
+ if (action === 'enter') { load(); return true; }
+ return false;
+ }
+ switch (action) {
+ case 'left': row.move(-1); return true;
+ case 'right': row.move(1); return true;
+ case 'up':
+ if (rowIndex === 0) { zone = 'nav'; renderNav(); renderRows(); return true; }
+ rowIndex--; renderRows(); onFocusItem(rows[rowIndex].current()); return true;
+ case 'down':
+ if (rowIndex < rows.length - 1) { rowIndex++; renderRows(); onFocusItem(rows[rowIndex].current()); }
+ return true;
+ case 'enter': row.select(); return true;
+ case 'play': case 'playpause': if (row.current()) playItem(row.current()); return true;
+ case 'back':
+ // Back from deep in the rows returns to the top first.
+ if (rowIndex > 0 || row.index > 0) {
+ rowIndex = 0; rows.forEach(r => r.focusIndex(0)); renderRows(); onFocusItem(rows[0].current());
+ return true;
+ }
+ return false;
+ }
+ return false;
+ },
+ };
+}
diff --git a/app/js/screens/library.js b/app/js/screens/library.js
new file mode 100644
index 0000000..ec6c5ef
--- /dev/null
+++ b/app/js/screens/library.js
@@ -0,0 +1,146 @@
+// A whole library as a virtualized poster grid, loaded page by page.
+// Yellow cycles the sort; CH▲/CH▼ jump by letter (title sort) or by page.
+import { h, setText } from '../util/dom.js';
+import { Grid } from '../ui/grid.js';
+import { useAmbience } from '../ui/backdrop.js';
+import { session } from '../session.js';
+import { prefetch } from '../ui/images.js';
+import { isFast } from '../input.js';
+import { openItem, playItem } from '../nav.js';
+import { error } from '../util/log.js';
+import { metaLine } from '../util/format.js';
+
+const PAGE = 140;
+const SORTS = [
+ { id: 'titleSort', label: 'A–Z' },
+ { id: 'addedAt:desc', label: 'Recently added' },
+ { id: 'originallyAvailableAt:desc', label: 'Release date' },
+ { id: 'audienceRating:desc', label: 'Rating' },
+];
+
+export function LibraryScreen(section) {
+ const el = h('div', 'screen library');
+ const ambience = useAmbience();
+ const head = h('header', 'lib-head', el);
+ h('h1', 'lib-title', head).textContent = section.title;
+ const count = h('div', 'lib-count', head);
+ const sortEl = h('div', 'lib-sort', head);
+ const focusInfo = h('div', 'lib-focus', el);
+ const hint = h('div', 'lib-hint', el);
+ hint.innerHTML = '<i class="key-yellow"></i> Sort &nbsp;&nbsp; CH ▲▼ Jump';
+
+ let sortIndex = 0;
+ let pages = new Map(); // page -> 'loading' | true
+ let items = [];
+ let letters = []; // [{ title: 'A', start: 0 }]
+ let generation = 0;
+
+ const type = section.type === 'show' ? 2 : 1;
+
+ const grid = new Grid({
+ top: 200, height: 880, total: 0,
+ getItem: i => items[i],
+ onFocus: (item, index) => {
+ // Warm posters for the row just past the recycled pool.
+ if (!isFast()) {
+ const start = (Math.floor(index / grid.cols) + grid.poolRows - 1) * grid.cols;
+ for (let i = start; i < start + grid.cols; i++) {
+ if (items[i]) prefetch(session.server.image(items[i].thumb, 216, 324));
+ }
+ }
+ if (!item) { setText(focusInfo, ''); return; }
+ setText(focusInfo, item.title + ' ' + metaLine(item));
+ ambience.set(item.UltraBlurColors);
+ },
+ onSelect: item => openItem(item),
+ onNeed: (start, end) => {
+ for (let p = Math.floor(start / PAGE); p <= Math.floor(end / PAGE); p++) loadPage(p);
+ },
+ });
+ el.appendChild(grid.el);
+
+ async function loadPage(p) {
+ if (pages.has(p)) return;
+ if (grid.total && p * PAGE >= grid.total) return;
+ pages.set(p, 'loading');
+ const gen = generation;
+ try {
+ const res = await session.server.items(section.key, p * PAGE, PAGE, { sort: SORTS[sortIndex].id, type });
+ if (gen !== generation) return;
+ res.items.forEach((it, i) => { items[p * PAGE + i] = it; });
+ pages.set(p, true);
+ if (grid.total !== res.total) {
+ grid.setTotal(res.total);
+ setText(count, res.total + (section.type === 'show' ? ' shows' : ' movies'));
+ } else {
+ grid.refresh();
+ }
+ if (p === 0 && res.items[0]) grid.onFocus(grid.current());
+ } catch (e) {
+ pages.delete(p);
+ error('library page failed', section.title, p, e);
+ }
+ }
+
+ async function loadLetters() {
+ letters = [];
+ if (SORTS[sortIndex].id !== 'titleSort') return;
+ try {
+ const mc = await session.server.get('/library/sections/' + section.key + '/firstCharacter', { type });
+ let start = 0;
+ letters = (mc.Directory || []).map(d => {
+ const l = { title: d.title, start };
+ start += d.size;
+ return l;
+ });
+ } catch (e) { /* letter jump just won't work */ }
+ }
+
+ function reload() {
+ generation++;
+ pages = new Map();
+ items = [];
+ setText(sortEl, 'Sorted by ' + SORTS[sortIndex].label);
+ grid.total = 0;
+ grid.index = 0;
+ grid.refresh();
+ loadPage(0);
+ loadLetters();
+ }
+ reload();
+
+ function jump(dir) {
+ if (letters.length) {
+ const i = grid.index;
+ let li = letters.findIndex((l, k) => i >= l.start && (k === letters.length - 1 || i < letters[k + 1].start));
+ li = Math.max(0, Math.min(letters.length - 1, li + dir));
+ grid.focusIndex(letters[li].start);
+ setText(focusInfo, letters[li].title);
+ } else {
+ grid.focusIndex(grid.index + dir * grid.cols * 3);
+ }
+ }
+
+ return {
+ el,
+ name: 'library',
+ onShow() { ambience.restore(); },
+ onKey(action) {
+ switch (action) {
+ case 'left': grid.move(-1, 0); return true;
+ case 'right': grid.move(1, 0); return true;
+ case 'up': grid.move(0, -1); return true;
+ case 'down': grid.move(0, 1); return true;
+ case 'pageup': jump(-1); return true;
+ case 'pagedown': jump(1); return true;
+ case 'enter': grid.select(); return true;
+ case 'play': case 'playpause': if (grid.current()) playItem(grid.current()); return true;
+ case 'yellow': sortIndex = (sortIndex + 1) % SORTS.length; reload(); return true;
+ case 'back':
+ if (grid.index > grid.cols * 2) { grid.focusIndex(0); return true; }
+ return false;
+ }
+ return false;
+ },
+ };
+}
diff --git a/app/js/screens/login.js b/app/js/screens/login.js
new file mode 100644
index 0000000..9184a43
--- /dev/null
+++ b/app/js/screens/login.js
@@ -0,0 +1,134 @@
+// Sign in with a plex.tv/link code (or by scanning the QR code with a phone),
+// then pick a server.
+import qrcode from '../vendor/qrcode.js';
+import { h, setText } from '../util/dom.js';
+import { createPin, checkPin, authAppUrl, getUser, getServers, connect } from '../plex/auth.js';
+import { signIn, useServer, session } from '../session.js';
+import * as router from '../router.js';
+import { error, log } from '../util/log.js';
+import { useAmbience } from '../ui/backdrop.js';
+
+export function LoginScreen({ onDone }) {
+ const el = h('div', 'screen login');
+ const ambience = useAmbience({ topLeft: '3a1518', topRight: '161922', bottomLeft: '1b1f2b', bottomRight: '2a1012' });
+ const left = h('div', 'login-art', el);
+ const art = h('img', '', left);
+ art.src = 'img/mascot-512.png';
+ const panel = h('div', 'login-panel', el);
+ h('h1', 'login-title', panel).textContent = 'Sign in to Plex';
+ const steps = h('ol', 'login-steps', panel);
+ h('li', '', steps).innerHTML = 'On your phone or computer, go to <b>plex.tv/link</b>';
+ h('li', '', steps).textContent = 'Enter this code:';
+ const code = h('div', 'login-code', panel);
+ const qrWrap = h('div', 'login-qr', panel);
+ const qrBox = h('div', 'login-qr-box', qrWrap);
+ h('div', 'login-qr-label', qrWrap).textContent = 'or scan to sign in';
+ const status = h('div', 'login-status', panel);
+
+ let timer = 0;
+ let alive = true;
+
+ async function start() {
+ clearTimeout(timer);
+ try {
+ setText(status, '');
+ const pin = await createPin();
+ if (!alive) return;
+ setText(code, pin.code);
+ const qr = qrcode(0, 'M');
+ qr.addData(authAppUrl(pin.code));
+ qr.make();
+ qrBox.innerHTML = qr.createSvgTag({ cellSize: 6, margin: 0, scalable: true });
+ const expires = Date.now() + (pin.expiresIn || 900) * 1000 - 5000;
+ const poll = async () => {
+ if (!alive) return;
+ if (Date.now() > expires) { start(); return; }
+ try {
+ const token = await checkPin(pin.id);
+ if (token) { await finish(token); return; }
+ } catch (e) {
+ error('pin poll failed', e);
+ }
+ timer = setTimeout(poll, 2000);
+ };
+ timer = setTimeout(poll, 2000);
+ } catch (e) {
+ error('createPin failed', e);
+ setText(status, 'Can\'t reach plex.tv. Retrying…');
+ timer = setTimeout(start, 4000);
+ }
+ }
+
+ async function finish(token) {
+ setText(status, 'Signed in. Finding your servers…');
+ const user = await getUser(token);
+ signIn(token, user);
+ log('signed in as', session.user.title);
+ const servers = await getServers(token);
+ if (!servers.length) {
+ setText(status, 'No Plex Media Servers on this account.');
+ return;
+ }
+ if (servers.length === 1) {
+ setText(status, 'Connecting to ' + servers[0].name + '…');
+ const uri = await connect(servers[0]);
+ useServer(servers[0], uri);
+ onDone();
+ return;
+ }
+ router.replace(ServerPicker({ servers, onDone }));
+ }
+
+ start();
+
+ return {
+ el,
+ name: 'login',
+ onShow() { ambience.restore(); },
+ onKey(action) {
+ if (action === 'enter') { start(); return true; }
+ return false;
+ },
+ destroy() {
+ alive = false;
+ clearTimeout(timer);
+ },
+ };
+}
+
+export function ServerPicker({ servers, onDone }) {
+ const el = h('div', 'screen picker');
+ const ambience = useAmbience();
+ h('h1', 'picker-title', el).textContent = 'Choose a server';
+ const list = h('div', 'picker-list', el);
+ const status = h('div', 'login-status', el);
+ const buttons = servers.map(s => {
+ const b = h('div', 'btn btn-wide', list);
+ h('span', '', b).textContent = s.name;
+ h('small', '', b).textContent = s.owned ? 'Your server' : 'Shared by ' + (s.sourceTitle || 'a friend');
+ return b;
+ });
+ let index = 0;
+ const render = () => buttons.forEach((b, i) => b.classList.toggle('focus', i === index));
+ render();
+
+ return {
+ el,
+ name: 'picker',
+ onShow() { ambience.restore(); },
+ onKey(action) {
+ if (action === 'up' || action === 'down') {
+ index = Math.max(0, Math.min(servers.length - 1, index + (action === 'down' ? 1 : -1)));
+ render();
+ return true;
+ }
+ if (action === 'enter') {
+ const s = servers[index];
+ setText(status, 'Connecting to ' + s.name + '…');
+ connect(s).then(uri => { useServer(s, uri); onDone(); }, e => setText(status, e.message));
+ return true;
+ }
+ return false;
+ },
+ };
+}
diff --git a/app/js/screens/player.js b/app/js/screens/player.js
new file mode 100644
index 0000000..e890187
--- /dev/null
+++ b/app/js/screens/player.js
@@ -0,0 +1,564 @@
+// Playback. Direct play whenever the TV can decode the file (hardware, zero
+// server load); otherwise ask Plex for HLS with the video passed through and
+// only the audio/container converted. Seeking previews locally and only
+// commits once the user stops pressing, because AVPlay seeks are slow.
+import { DEV } from '../config.js';
+import { h, setText, setTransform, toggleClass } from '../util/dom.js';
+import { createPlayer } from '../platform/player.js';
+import { setScreenSaver, supports4K } from '../platform/tizen.js';
+import { session } from '../session.js';
+import { clock, episodeLabel, uuid } from '../util/format.js';
+import * as icons from '../ui/icons.js';
+import * as router from '../router.js';
+import { log, warn, error } from '../util/log.js';
+import { request } from '../plex/client.js';
+import { parseSubtitles, CueTrack } from '../player/subtitles.js';
+
+// What a 2022 Samsung (Tizen 6.5) decodes natively. No DTS on 2018+ models.
+const DIRECT = {
+ container: { mp4: 1, m4v: 1, mov: 1, mkv: 1, webm: 1, ts: 1, mpegts: 1, avi: 1 },
+ video: { h264: 1, hevc: 1, vp9: 1, av1: 1, mpeg4: 1, mpeg2video: 1, vc1: 1 },
+ audio: { aac: 1, ac3: 1, eac3: 1, mp3: 1, mp2: 1, flac: 1, opus: 1, vorbis: 1, pcm: 1 },
+};
+const TEXT_SUBS = { srt: 1, subrip: 1, ass: 1, ssa: 1, mov_text: 1, vtt: 1, webvtt: 1, smi: 1 };
+
+const OSD_HIDE_MS = 4000;
+const SEEK_COMMIT_MS = 900;
+const TIMELINE_MS = 10000;
+
+function streamsOf(part, type) {
+ return (part && part.Stream || []).filter(s => s.streamType === type);
+}
+
+function isEmbeddedText(sub) {
+ return !!sub && sub.index != null && !sub.key && !!TEXT_SUBS[sub.codec];
+}
+
+// External .srt/.ass/.vtt files: we fetch and draw these ourselves.
+function isSidecarText(sub) {
+ return !!sub && !!sub.key && !!TEXT_SUBS[sub.codec];
+}
+
+function subtitleLabel(s) {
+ const title = s.displayTitle && s.displayTitle !== 'Unknown' ? s.displayTitle : (s.language || '');
+ const kind = (s.codec || '').toUpperCase() + (s.key ? ' · external' : '');
+ return title ? title + (s.key ? ' · external' : '') : kind || 'Subtitle';
+}
+
+function cleanSubtitle(text) {
+ return String(text || '')
+ .replace(/\{\\[^}]*\}/g, '') // ASS override tags
+ .replace(/<[^>]+>/g, '') // <i>, <font> ...
+ .replace(/\\N/g, '\n');
+}
+
+export function PlayerScreen(initial, { offset = null } = {}) {
+ const el = h('div', 'screen player');
+ const stage = h('div', 'player-stage', el);
+ const subs = h('div', 'subs', el);
+ const spinner = h('div', 'spinner', el);
+ const pauseBig = h('div', 'pause-big', el);
+ pauseBig.innerHTML = icons.pause;
+
+ const osd = h('div', 'osd', el);
+ const osdTop = h('div', 'osd-top', osd);
+ const osdTitle = h('div', 'osd-title', osdTop);
+ const osdSub = h('div', 'osd-sub', osdTop);
+ const osdBottom = h('div', 'osd-bottom', osd);
+ const bar = h('div', 'osd-bar', osdBottom);
+ const barFill = h('div', 'osd-fill', bar);
+ const knob = h('div', 'osd-knob', bar);
+ const seekLabel = h('div', 'osd-seek', knob);
+ const times = h('div', 'osd-times', osdBottom);
+ const tNow = h('span', 'osd-now', times);
+ const tInfo = h('span', 'osd-info', times);
+ const tLeft = h('span', 'osd-left', times);
+ const hintEl = h('div', 'osd-hint', osdBottom);
+ hintEl.innerHTML = '▼ Audio &amp; subtitles';
+
+ const panel = h('div', 'tracks hidden', el);
+ const upnext = h('div', 'upnext hidden', el);
+ const errorEl = h('div', 'player-error hidden', el);
+
+ let item = initial;
+ let media = null;
+ let part = null;
+ let mode = 'direct';
+ let triedFallback = false;
+ let base = 0; // HLS restarts at an offset; AVPlay time is relative to it
+ let position = offset || 0;
+ let duration = initial.duration || 0;
+ let paused = false;
+ let started = false;
+ let alive = true;
+ let audioStream = null;
+ let subStream = null;
+ let seekTarget = null;
+ let seekCount = 0;
+ let lastSeekAt = 0;
+ let seekTimer = 0;
+ let osdTimer = 0;
+ let timelineTimer = 0;
+ let subTimer = 0;
+ let lastText = 0;
+ let upnextTimer = 0;
+ let nextItem = null;
+ let cueTrack = null;
+ let cueTimer = 0;
+ let cueFor = null;
+ const playSession = uuid();
+
+ const player = createPlayer(stage, {
+ onTime(ms) {
+ if (!started) return;
+ position = base + ms;
+ if (seekTarget == null) renderProgress(position);
+ },
+ onBuffering(on) { toggleClass(spinner, 'on', on); },
+ onEnd() { finished(); },
+ onError(msg) { failed(msg); },
+ onSubtitle(text, ms) {
+ clearTimeout(subTimer);
+ setText(subs, cleanSubtitle(text));
+ if (ms > 0) subTimer = setTimeout(() => setText(subs, ''), ms);
+ },
+ });
+
+ // --- OSD --------------------------------------------------------------
+
+ function renderProgress(ms) {
+ const p = duration ? Math.max(0, Math.min(1, ms / duration)) : 0;
+ setTransform(barFill, 'scaleX(' + p.toFixed(4) + ')');
+ setTransform(knob, 'translateX(' + Math.round(p * 1728) + 'px)');
+ const now = Date.now();
+ if (now - lastText > 900 || seekTarget != null) {
+ lastText = now;
+ setText(tNow, clock(ms));
+ setText(tLeft, '−' + clock(duration - ms));
+ const ends = new Date(now + (duration - ms));
+ let hh = ends.getHours();
+ const ampm = hh >= 12 ? 'PM' : 'AM';
+ hh = hh % 12 || 12;
+ const mm = ends.getMinutes();
+ setText(tInfo, 'Ends at ' + hh + ':' + (mm < 10 ? '0' : '') + mm + ' ' + ampm);
+ }
+ }
+
+ function showOsd(sticky) {
+ toggleClass(el, 'osd-on', true);
+ clearTimeout(osdTimer);
+ if (!sticky && !paused) osdTimer = setTimeout(() => toggleClass(el, 'osd-on', false), OSD_HIDE_MS);
+ }
+
+ function hideOsd() {
+ clearTimeout(osdTimer);
+ toggleClass(el, 'osd-on', false);
+ }
+
+ function renderTitles() {
+ if (item.type === 'episode') {
+ setText(osdTitle, item.grandparentTitle);
+ setText(osdSub, episodeLabel(item) + ' ' + item.title);
+ } else {
+ setText(osdTitle, item.title);
+ setText(osdSub, item.year || '');
+ }
+ }
+
+ // --- Timeline ---------------------------------------------------------
+
+ function report(state) {
+ if (!item.ratingKey) return;
+ if (DEV && window.__ss && window.__ss.muteTimeline) return;
+ session.server.timeline({
+ ratingKey: item.ratingKey,
+ key: '/library/metadata/' + item.ratingKey,
+ state,
+ time: Math.floor(position),
+ duration: Math.floor(duration),
+ 'X-Plex-Session-Identifier': playSession,
+ });
+ }
+
+ function startTimeline() {
+ clearInterval(timelineTimer);
+ timelineTimer = setInterval(() => report(paused ? 'paused' : 'playing'), TIMELINE_MS);
+ }
+
+ // --- Opening ----------------------------------------------------------
+
+ function decideMode() {
+ const directOk = DIRECT.container[media.container] && DIRECT.video[media.videoCodec] &&
+ (!audioStream || DIRECT.audio[audioStream.codec]);
+ const subsOk = !subStream || isEmbeddedText(subStream) || isSidecarText(subStream);
+ return directOk && subsOk ? 'direct' : 'hls';
+ }
+
+ async function open(atMs) {
+ const server = session.server;
+ const t0 = Date.now();
+ started = false;
+ toggleClass(spinner, 'on', true);
+ let url;
+ if (mode === 'direct') {
+ base = 0;
+ url = server.url(part.key);
+ } else {
+ base = atMs;
+ // Burn in only what we can't draw ourselves (image subs, embedded text).
+ const burn = subStream && !isSidecarText(subStream);
+ url = server.transcodeUrl(item, {
+ session: playSession, offsetMs: atMs,
+ audioStreamID: audioStream && audioStream.id,
+ subtitleStreamID: burn ? subStream.id : undefined,
+ });
+ // PMS 1.42+ rejects start.m3u8 unless a decision was made for the session first.
+ const decision = await request(url.replace('/start.m3u8', '/decision'));
+ const mc = decision.MediaContainer || {};
+ if (mc.generalDecisionCode && mc.generalDecisionCode >= 2000) throw new Error(mc.generalDecisionText || 'Server refused to convert this file');
+ }
+ log('play', mode, item.title, media.container + '/' + media.videoCodec + '/' + (audioStream && audioStream.codec), 'at', clock(atMs));
+ player.open(url, { uhd: media.videoResolution === '4k' && supports4K() });
+ await player.prepare();
+ if (!alive) return;
+ if (mode === 'direct') {
+ applyTracks();
+ if (atMs > 0) await player.seek(atMs);
+ }
+ syncSidecar();
+ player.play();
+ paused = false;
+ started = true;
+ position = atMs;
+ toggleClass(el, 'paused', false);
+ toggleClass(spinner, 'on', false);
+ log('playing after ' + (Date.now() - t0) + 'ms (' + mode + ')');
+ report('playing');
+ startTimeline();
+ }
+
+ // Map Plex's chosen streams onto AVPlay's track list (same file order).
+ function applyTracks() {
+ const t = player.tracks();
+ if (audioStream && t.audio.length > 1) {
+ const pos = streamsOf(part, 2).indexOf(audioStream);
+ if (pos >= 0 && t.audio[pos] != null) player.selectAudio(t.audio[pos]);
+ }
+ if (isEmbeddedText(subStream)) {
+ const pos = streamsOf(part, 3).filter(isEmbeddedText).indexOf(subStream);
+ if (pos >= 0 && t.text[pos] != null) player.selectText(t.text[pos]);
+ } else {
+ player.selectText(null);
+ setText(subs, '');
+ }
+ }
+
+ // Start/stop drawing an external subtitle file for the current selection.
+ function syncSidecar() {
+ if (!isSidecarText(subStream)) {
+ cueTrack = null;
+ cueFor = null;
+ clearInterval(cueTimer);
+ if (!isEmbeddedText(subStream)) setText(subs, '');
+ return;
+ }
+ if (cueFor === subStream) return;
+ cueFor = subStream;
+ const stream = subStream;
+ cueTrack = null;
+ fetch(session.server.url(stream.key, { encoding: 'utf-8' }))
+ .then(r => r.text())
+ .then(text => {
+ if (cueFor !== stream || !alive) return;
+ cueTrack = new CueTrack(parseSubtitles(text, stream.codec));
+ log('subtitles loaded', stream.displayTitle, cueTrack.cues.length + ' cues');
+ })
+ .catch(e => warn('subtitle fetch failed', e.message));
+ clearInterval(cueTimer);
+ cueTimer = setInterval(() => {
+ if (cueTrack && started) setText(subs, cueTrack.at(base + player.time()));
+ }, 120);
+ }
+
+ async function start() {
+ try {
+ const full = await session.server.metadata(item.ratingKey);
+ if (!alive) return;
+ item = full;
+ duration = item.duration || duration;
+ media = (item.Media || [])[0];
+ part = media && media.Part && media.Part[0];
+ if (!part) throw new Error('No playable media');
+ const audios = streamsOf(part, 2);
+ audioStream = audios.find(s => s.selected) || audios[0] || null;
+ subStream = streamsOf(part, 3).find(s => s.selected) || null;
+ renderTitles();
+ mode = decideMode();
+ if (offset == null) offset = item.viewOffset || 0;
+ position = offset;
+ renderProgress(position);
+ showOsd();
+ await open(offset);
+ } catch (e) {
+ failed(e.message || String(e));
+ }
+ }
+
+ function failed(msg) {
+ if (!alive) return;
+ if (mode === 'direct' && !triedFallback && media) {
+ // The file looked direct-playable but the TV choked: let Plex convert it.
+ warn('direct play failed (' + msg + '), falling back to HLS');
+ triedFallback = true;
+ mode = 'hls';
+ open(position).catch(e => failed(e.message));
+ return;
+ }
+ error('playback failed', msg);
+ toggleClass(spinner, 'on', false);
+ errorEl.classList.remove('hidden');
+ setText(errorEl, 'Playback failed: ' + msg);
+ }
+
+ // --- Controls ---------------------------------------------------------
+
+ function togglePause() {
+ if (!started) return;
+ if (paused) {
+ player.play();
+ paused = false;
+ showOsd();
+ } else {
+ player.pause();
+ paused = true;
+ showOsd(true);
+ }
+ toggleClass(el, 'paused', paused);
+ report(paused ? 'paused' : 'playing');
+ }
+
+ function seekBy(dir) {
+ if (!started) return;
+ const now = Date.now();
+ seekCount = now - lastSeekAt < 700 ? seekCount + 1 : 0;
+ lastSeekAt = now;
+ const step = seekCount < 3 ? 10000 : seekCount < 8 ? 30000 : seekCount < 16 ? 60000 : 180000;
+ const from = seekTarget == null ? position : seekTarget;
+ seekTarget = Math.max(0, Math.min(duration - 3000, from + dir * step));
+ toggleClass(el, 'seeking', true);
+ setText(seekLabel, clock(seekTarget));
+ renderProgress(seekTarget);
+ showOsd(true);
+ clearTimeout(seekTimer);
+ seekTimer = setTimeout(commitSeek, SEEK_COMMIT_MS);
+ }
+
+ async function commitSeek() {
+ clearTimeout(seekTimer);
+ if (seekTarget == null) return;
+ const target = seekTarget;
+ seekTarget = null;
+ toggleClass(el, 'seeking', false);
+ showOsd();
+ position = target;
+ try {
+ if (mode === 'direct') {
+ toggleClass(spinner, 'on', true);
+ await player.seek(target);
+ toggleClass(spinner, 'on', false);
+ if (paused) togglePause();
+ } else {
+ await open(target);
+ }
+ } catch (e) {
+ warn('seek failed, reopening', e.message);
+ open(target).catch(err => failed(err.message));
+ }
+ }
+
+ // --- Audio / subtitle picker ------------------------------------------
+
+ let panelCol = 0;
+ let panelIndex = [0, 0];
+ let panelLists = [[], []];
+
+ function openPanel() {
+ const audios = streamsOf(part, 2);
+ const texts = streamsOf(part, 3);
+ panelLists = [
+ audios.map(s => ({ label: s.displayTitle || s.language || 'Track', stream: s, on: s === audioStream })),
+ [{ label: 'Off', stream: null, on: !subStream }].concat(texts.map(s => ({ label: subtitleLabel(s), stream: s, on: s === subStream }))),
+ ];
+ panelIndex = panelLists.map(l => Math.max(0, l.findIndex(x => x.on)));
+ panelCol = 0;
+ renderPanel();
+ panel.classList.remove('hidden');
+ hideOsd();
+ }
+
+ function renderPanel() {
+ panel.innerHTML = '';
+ ['Audio', 'Subtitles'].forEach((name, c) => {
+ const col = h('div', 'tracks-col', panel);
+ const head = h('div', 'tracks-head', col);
+ head.innerHTML = c === 0 ? icons.audio : icons.subtitles;
+ h('span', '', head).textContent = name;
+ panelLists[c].forEach((opt, i) => {
+ const row = h('div', 'tracks-opt', col);
+ row.textContent = opt.label;
+ toggleClass(row, 'on', opt.on);
+ toggleClass(row, 'focus', c === panelCol && i === panelIndex[c]);
+ });
+ });
+ }
+
+ async function choose(col, opt) {
+ const server = session.server;
+ if (col === 0) audioStream = opt.stream;
+ else subStream = opt.stream;
+ server.selectStreams(part.id, {
+ audioStreamID: audioStream ? audioStream.id : undefined,
+ subtitleStreamID: subStream ? subStream.id : 0,
+ });
+ panel.classList.add('hidden');
+ const wanted = decideMode();
+ if (wanted === 'direct' && mode === 'direct') {
+ applyTracks();
+ syncSidecar();
+ } else if (mode === 'hls' && wanted === 'hls' && col === 1 && isSidecarText(subStream)) {
+ syncSidecar();
+ } else {
+ mode = wanted;
+ triedFallback = false;
+ await open(position).catch(e => failed(e.message));
+ }
+ }
+
+ function panelKey(action) {
+ if (action === 'back' || action === 'up' && panelIndex[panelCol] === 0) { panel.classList.add('hidden'); return true; }
+ if (action === 'left' || action === 'right') panelCol = action === 'left' ? 0 : 1;
+ if (action === 'up') panelIndex[panelCol]--;
+ if (action === 'down') panelIndex[panelCol] = Math.min(panelLists[panelCol].length - 1, panelIndex[panelCol] + 1);
+ if (action === 'enter') {
+ const opt = panelLists[panelCol][panelIndex[panelCol]];
+ if (opt) choose(panelCol, opt);
+ return true;
+ }
+ renderPanel();
+ return true;
+ }
+
+ // --- Ending -----------------------------------------------------------
+
+ async function nextEpisode() {
+ const server = session.server;
+ const eps = await server.children(item.parentRatingKey);
+ const i = eps.findIndex(e => e.ratingKey === item.ratingKey);
+ if (i >= 0 && i < eps.length - 1) return eps[i + 1];
+ const seasons = (await server.children(item.grandparentRatingKey)).filter(s => s.type === 'season');
+ const si = seasons.findIndex(s => s.ratingKey === item.parentRatingKey);
+ if (si >= 0 && si < seasons.length - 1) return (await server.children(seasons[si + 1].ratingKey))[0] || null;
+ return null;
+ }
+
+ async function finished() {
+ position = duration;
+ report('stopped');
+ clearInterval(timelineTimer);
+ player.close();
+ if (item.type !== 'episode') { exit(); return; }
+ try { nextItem = await nextEpisode(); } catch (e) { nextItem = null; }
+ if (!alive) return;
+ if (!nextItem) { exit(); return; }
+ let left = 10;
+ upnext.classList.remove('hidden');
+ const render = () => {
+ upnext.innerHTML = '';
+ h('div', 'upnext-label', upnext).textContent = 'Up next in ' + left;
+ h('div', 'upnext-title', upnext).textContent = episodeLabel(nextItem) + ' ' + nextItem.title;
+ h('div', 'upnext-hint', upnext).textContent = 'OK to play now · Back to stop';
+ };
+ render();
+ upnextTimer = setInterval(() => {
+ left--;
+ if (left <= 0) playNext();
+ else render();
+ }, 1000);
+ }
+
+ function playNext() {
+ clearInterval(upnextTimer);
+ router.replace(PlayerScreen(nextItem, { offset: 0 }));
+ }
+
+ function exit() {
+ router.back();
+ }
+
+ function teardown() {
+ if (!alive) return;
+ alive = false;
+ if (started && position < duration) report('stopped');
+ [seekTimer, osdTimer, subTimer].forEach(clearTimeout);
+ clearInterval(timelineTimer);
+ clearInterval(upnextTimer);
+ clearInterval(cueTimer);
+ player.destroy();
+ if (mode === 'hls') session.server.stopTranscode(playSession);
+ document.documentElement.classList.remove('playing');
+ setScreenSaver(true);
+ document.removeEventListener('visibilitychange', onVisibility);
+ }
+
+ function onVisibility() {
+ if (document.hidden) {
+ if (started && !paused) togglePause();
+ player.suspend();
+ } else {
+ player.restore();
+ }
+ }
+
+ return {
+ el,
+ name: 'player',
+ onShow() {
+ document.documentElement.classList.add('playing');
+ setScreenSaver(false);
+ document.addEventListener('visibilitychange', onVisibility);
+ renderTitles();
+ if (!started) start();
+ },
+ onKey(action) {
+ if (!upnext.classList.contains('hidden')) {
+ if (action === 'enter') { playNext(); return true; }
+ if (action === 'back' || action === 'stop') { exit(); return true; }
+ return true;
+ }
+ if (!panel.classList.contains('hidden')) return panelKey(action);
+ switch (action) {
+ case 'enter':
+ if (seekTarget != null) commitSeek();
+ else if (el.classList.contains('osd-on') || paused) togglePause();
+ else showOsd();
+ return true;
+ case 'playpause': if (seekTarget != null) commitSeek(); else togglePause(); return true;
+ case 'play': if (paused) togglePause(); return true;
+ case 'pause': if (!paused) togglePause(); return true;
+ case 'left': case 'rw': seekBy(-1); return true;
+ case 'right': case 'ff': seekBy(1); return true;
+ case 'up': case 'info': showOsd(); return true;
+ case 'down': if (part) openPanel(); return true;
+ case 'stop': exit(); return true;
+ case 'back':
+ if (seekTarget != null) { seekTarget = null; toggleClass(el, 'seeking', false); renderProgress(position); showOsd(); return true; }
+ if (el.classList.contains('osd-on') && !paused) { hideOsd(); return true; }
+ exit();
+ return true;
+ }
+ return true;
+ },
+ onHide() {},
+ destroy: teardown,
+ };
+}
diff --git a/app/js/screens/search.js b/app/js/screens/search.js
new file mode 100644
index 0000000..f31da01
--- /dev/null
+++ b/app/js/screens/search.js
@@ -0,0 +1,124 @@
+// Search across the server. Focusing the input brings up Samsung's on-screen
+// keyboard; results update as you type.
+import { h, setText, setTransform } from '../util/dom.js';
+import { Row } from '../ui/row.js';
+import { session } from '../session.js';
+import { openItem, playItem } from '../nav.js';
+import { error } from '../util/log.js';
+import * as icons from '../ui/icons.js';
+import { useAmbience } from '../ui/backdrop.js';
+
+const IME_DONE = 65376;
+const IME_CANCEL = 65385;
+
+export function SearchScreen() {
+ const el = h('div', 'screen search');
+ const ambience = useAmbience();
+ const bar = h('div', 'search-bar', el);
+ const icon = h('div', 'search-icon', bar);
+ icon.innerHTML = icons.search;
+ const input = h('input', 'search-input', bar);
+ input.type = 'text';
+ input.placeholder = 'Search movies and shows';
+ input.setAttribute('autocomplete', 'off');
+ const status = h('div', 'search-status', el);
+ const clip = h('div', 'search-rows', el);
+ const track = h('div', 'rows-track', clip);
+
+ let rows = [];
+ let rowIndex = -1; // -1 = input
+ let timer = 0;
+ let query = '';
+ let generation = 0;
+
+ async function run(q) {
+ query = q;
+ const gen = ++generation;
+ if (q.length < 2) { setRows([]); setText(status, ''); return; }
+ setText(status, 'Searching…');
+ try {
+ const hubs = await session.server.search(q);
+ if (gen !== generation) return;
+ setRows(hubs);
+ setText(status, hubs.length ? '' : 'Nothing found for “' + q + '”');
+ } catch (e) {
+ error('search failed', e);
+ setText(status, 'Search failed');
+ }
+ }
+
+ function setRows(hubs) {
+ track.innerHTML = '';
+ let y = 0;
+ rows = hubs.map(hub => {
+ const row = new Row({
+ title: hub.title, kind: hub.type === 'episode' ? 'episode' : 'poster',
+ caption: true, items: hub.Metadata, onSelect: item => openItem(item),
+ });
+ setTransform(row.el, 'translateY(' + y + 'px)');
+ row.y = y;
+ y += row.height;
+ track.appendChild(row.el);
+ return row;
+ });
+ if (rowIndex >= rows.length) rowIndex = rows.length - 1;
+ render();
+ }
+
+ function render() {
+ rows.forEach((r, i) => r.setActive(i === rowIndex));
+ el.classList.toggle('in-input', rowIndex < 0);
+ const y = rowIndex > 0 ? rows[rowIndex].y : 0;
+ setTransform(track, 'translateY(' + (-y) + 'px)');
+ }
+
+ function focusInput() {
+ rowIndex = -1;
+ render();
+ input.focus();
+ }
+
+ input.addEventListener('input', () => {
+ clearTimeout(timer);
+ timer = setTimeout(() => run(input.value.trim()), 350);
+ });
+ input.addEventListener('keydown', e => {
+ if (e.keyCode === IME_DONE || e.keyCode === 13) {
+ input.blur();
+ run(input.value.trim());
+ if (rows.length) { rowIndex = 0; render(); }
+ } else if (e.keyCode === IME_CANCEL) {
+ input.blur();
+ }
+ });
+
+ return {
+ el,
+ name: 'search',
+ onShow() {
+ ambience.restore();
+ if (rowIndex < 0) setTimeout(focusInput, 50);
+ },
+ onHide() { input.blur(); },
+ onKey(action) {
+ if (rowIndex < 0) {
+ if (action === 'down' && rows.length) { input.blur(); rowIndex = 0; render(); return true; }
+ if (action === 'enter') { input.focus(); return true; }
+ if (action === 'back') { input.blur(); return false; }
+ return true;
+ }
+ const row = rows[rowIndex];
+ switch (action) {
+ case 'left': row.move(-1); return true;
+ case 'right': row.move(1); return true;
+ case 'up': if (rowIndex === 0) focusInput(); else { rowIndex--; render(); } return true;
+ case 'down': if (rowIndex < rows.length - 1) { rowIndex++; render(); } return true;
+ case 'enter': row.select(); return true;
+ case 'play': case 'playpause': if (row.current()) playItem(row.current()); return true;
+ case 'back': focusInput(); return true;
+ }
+ return false;
+ },
+ destroy() { clearTimeout(timer); generation++; },
+ };
+}
diff --git a/app/js/screens/settings.js b/app/js/screens/settings.js
new file mode 100644
index 0000000..d418237
--- /dev/null
+++ b/app/js/screens/settings.js
@@ -0,0 +1,82 @@
+// Account, server and diagnostics.
+import { DEV, VERSION } from '../config.js';
+import { h, toggleClass } from '../util/dom.js';
+import { session, signOut, useServer } from '../session.js';
+import { getServers, connect } from '../plex/auth.js';
+import { setHud, hudEnabled } from '../ui/hud.js';
+import * as router from '../router.js';
+import { ServerPicker } from './login.js';
+import { error } from '../util/log.js';
+import { useAmbience, setLegacyGradients, legacyGradients } from '../ui/backdrop.js';
+
+export function SettingsScreen() {
+ const el = h('div', 'screen settings');
+ const ambience = useAmbience();
+ h('h1', 'settings-title', el).textContent = 'Settings';
+ const list = h('div', 'settings-list', el);
+ const foot = h('div', 'settings-foot', el);
+ foot.textContent = 'SamSUCKS ' + VERSION + (DEV ? ' (dev)' : '') + ' · ' + (session.server ? session.server.uri.replace(/X-Plex-Token=.*/, '') : '');
+
+ let index = 0;
+ let items = [];
+
+ function build() {
+ list.innerHTML = '';
+ items = [
+ { label: 'Server', value: session.server ? session.server.name : '—', run: switchServer },
+ { label: 'Signed in as', value: session.user ? session.user.title : '—', run: doSignOut, action: 'Sign out' },
+ { label: 'Performance overlay', value: hudEnabled() ? 'On' : 'Off', run: () => { setHud(!hudEnabled()); build(); } },
+ // For before/after recordings: brings back the full-screen gradients that took ~2s per repaint.
+ { label: 'Demo: original slow renderer', value: legacyGradients() ? 'On' : 'Off', run: () => { setLegacyGradients(!legacyGradients()); build(); } },
+ ];
+ items.forEach(it => {
+ it.el = h('div', 'setting', list);
+ h('span', 'setting-label', it.el).textContent = it.label;
+ h('span', 'setting-value', it.el).textContent = it.value + (it.action ? ' · ' + it.action : '');
+ });
+ render();
+ }
+
+ function render() {
+ items.forEach((it, i) => toggleClass(it.el, 'focus', i === index));
+ }
+
+ async function switchServer() {
+ try {
+ const servers = await getServers(session.token);
+ if (servers.length === 1) {
+ const uri = await connect(servers[0]);
+ useServer(servers[0], uri);
+ restart();
+ return;
+ }
+ router.push(ServerPicker({ servers, onDone: restart }));
+ } catch (e) {
+ error('server list failed', e);
+ }
+ }
+
+ function doSignOut() {
+ signOut();
+ restart();
+ }
+
+ function restart() {
+ // Rebuild from scratch: app.js decides between login and home.
+ window.dispatchEvent(new Event('samsucks:restart'));
+ }
+
+ build();
+
+ return {
+ el,
+ name: 'settings',
+ onShow() { ambience.restore(); },
+ onKey(action) {
+ if (action === 'up') { index = Math.max(0, index - 1); render(); return true; }
+ if (action === 'down') { index = Math.min(items.length - 1, index + 1); render(); return true; }
+ if (action === 'enter') { items[index].run(); return true; }
+ return false;
+ },
+ };
+}
diff --git a/app/js/session.js b/app/js/session.js
new file mode 100644
index 0000000..5ccadf1
--- /dev/null
+++ b/app/js/session.js
@@ -0,0 +1,49 @@
+// Who is signed in and which server we're talking to. Persisted so a restart
+// goes straight to the home screen.
+import * as store from './util/store.js';
+import { Server } from './plex/server.js';
+import { getServers, connect } from './plex/auth.js';
+import { log } from './util/log.js';
+
+export const session = {
+ token: store.get('token'),
+ user: store.get('user'),
+ server: null,
+};
+
+const saved = store.get('server');
+if (saved) session.server = new Server(saved);
+
+export function signIn(token, user) {
+ session.token = token;
+ session.user = { title: user.title || user.username, thumb: user.thumb, uuid: user.uuid };
+ store.set('token', token);
+ store.set('user', session.user);
+}
+
+export function useServer(resource, uri) {
+ session.server = new Server({ uri, token: resource.accessToken, name: resource.name, id: resource.clientIdentifier });
+ store.set('server', { uri, token: resource.accessToken, name: resource.name, id: resource.clientIdentifier });
+}
+
+export function signOut() {
+ session.token = null;
+ session.user = null;
+ session.server = null;
+ store.set('token', undefined);
+ store.set('user', undefined);
+ store.set('server', undefined);
+ store.set('homeCache', undefined);
+}
+
+// The saved URI can go stale (DHCP, remote vs. home). Re-resolve it from plex.tv.
+export async function reconnect() {
+ const servers = await getServers(session.token);
+ const current = session.server && servers.find(s => s.clientIdentifier === session.server.id);
+ const resource = current || servers[0];
+ if (!resource) throw new Error('No Plex servers on this account');
+ const uri = await connect(resource);
+ useServer(resource, uri);
+ log('reconnected', resource.name, uri);
+ return session.server;
+}
diff --git a/app/js/ui/backdrop.js b/app/js/ui/backdrop.js
new file mode 100644
index 0000000..1f7ed1d
--- /dev/null
+++ b/app/js/ui/backdrop.js
@@ -0,0 +1,141 @@
+// Full-screen ambience from Plex's UltraBlur corner colors, plus a hero image.
+//
+// Painting a full-screen CSS gradient takes ~2s on a 2022 TV CPU, and even a
+// software canvas stretched to full screen costs ~100ms per change. Instead the
+// ambience is a 2x2-pixel WebGL canvas (one pixel per corner color): WebGL
+// output always lives on the GPU, so the compositor just stretches a 2x2
+// texture over the screen and bilinear filtering produces the smooth blend.
+// One shared instance sits behind every screen; two layers cross-fade.
+import { h } from '../util/dom.js';
+
+const FALLBACK = { topLeft: '1b1f2b', topRight: '0f1118', bottomLeft: '2a1414', bottomRight: '0b0d12' };
+const DIM = 0.78; // keep text readable on bright posters
+
+function rgb(hex) {
+ const n = parseInt(hex || '0b0d12', 16);
+ return [(n >> 16 & 255) * DIM, (n >> 8 & 255) * DIM, (n & 255) * DIM];
+}
+
+function createLayer(parent, className) {
+ const canvas = h('canvas', className, parent);
+ canvas.width = 2;
+ canvas.height = 2;
+ const opts = { preserveDrawingBuffer: true, antialias: false, alpha: false, depth: false, stencil: false };
+ canvas._gl = canvas.getContext('webgl', opts) || canvas.getContext('experimental-webgl', opts);
+ if (!canvas._gl) canvas._ctx = canvas.getContext('2d');
+ return canvas;
+}
+
+function paint(canvas, colors) {
+ const c = colors || FALLBACK;
+ const px = [c.topLeft, c.topRight, c.bottomLeft, c.bottomRight].map(rgb);
+ const gl = canvas._gl;
+ if (gl) {
+ gl.enable(gl.SCISSOR_TEST);
+ px.forEach(([r, g, b], i) => {
+ // GL's origin is bottom-left.
+ gl.scissor(i % 2, i < 2 ? 1 : 0, 1, 1);
+ gl.clearColor(r / 255, g / 255, b / 255, 1);
+ gl.clear(gl.COLOR_BUFFER_BIT);
+ });
+ return;
+ }
+ const img = canvas._ctx.createImageData(2, 2);
+ px.forEach(([r, g, b], i) => { img.data.set([r, g, b, 255], i * 4); });
+ canvas._ctx.putImageData(img, 0, 0);
+}
+
+// The renderer this replaced, kept as a Settings demo for before/after videos:
+// four full-screen CSS radial gradients, repainted on every focus change.
+let legacy = false;
+
+function legacyGradient(colors) {
+ const c = colors || FALLBACK;
+ return ['topLeft 0% 0%', 'topRight 100% 0%', 'bottomLeft 0% 100%', 'bottomRight 100% 100%']
+ .map(s => { const [k, x, y] = s.split(' '); return 'radial-gradient(ellipse at ' + x + ' ' + y + ', #' + c[k] + ' 0%, transparent 70%)'; })
+ .join(',') + ',#0B0D12';
+}
+
+class Ambience {
+ constructor(parent) {
+ this.el = h('div', 'ambience', parent);
+ this.layers = [createLayer(this.el, 'amb-layer on'), createLayer(this.el, 'amb-layer')];
+ paint(this.layers[0], null);
+ this.front = 0;
+ this.key = '';
+ }
+
+ set(colors) {
+ const key = colors ? colors.topLeft + colors.topRight + colors.bottomLeft + colors.bottomRight : '';
+ if (key === this.key) return;
+ this.key = key;
+ this.colors = colors;
+ if (legacy) {
+ this.el.style.background = legacyGradient(colors);
+ return;
+ }
+ const back = 1 - this.front;
+ paint(this.layers[back], colors);
+ this.layers[back].classList.add('on');
+ this.layers[this.front].classList.remove('on');
+ this.front = back;
+ }
+}
+
+let shared = null;
+
+export function setLegacyGradients(on) {
+ legacy = on;
+ if (!shared) return;
+ shared.el.classList.toggle('legacy', on);
+ shared.el.style.background = on ? legacyGradient(shared.colors) : '';
+ if (!on) { const c = shared.colors; shared.key = null; shared.set(c); }
+}
+
+export function legacyGradients() {
+ return legacy;
+}
+
+// Per-screen handle on the shared ambience: remembers the screen's colors so
+// they can be restored when the screen comes back to the top.
+export function useAmbience(initial) {
+ if (!shared) shared = new Ambience(document.body.insertBefore(document.createElement('div'), document.body.firstChild));
+ let colors = initial || null;
+ return {
+ set(c) { colors = c || null; shared.set(colors); },
+ restore() { shared.set(colors); },
+ };
+}
+
+export class HeroArt {
+ constructor(parent, className) {
+ this.el = h('div', className || 'hero-art', parent);
+ this.imgs = [h('img', 'hero-img', this.el), h('img', 'hero-img', this.el)];
+ this.front = 0;
+ this.url = '';
+ this.token = 0;
+ h('div', 'hero-fade', this.el);
+ }
+
+ set(url) {
+ if (url === this.url) return;
+ this.url = url;
+ const token = ++this.token;
+ if (!url) {
+ this.imgs.forEach(i => i.classList.remove('on'));
+ return;
+ }
+ const back = this.imgs[1 - this.front];
+ const loader = new Image();
+ loader.src = url;
+ const swap = () => {
+ if (token !== this.token) return;
+ back.src = url;
+ back.classList.add('on');
+ this.imgs[this.front].classList.remove('on');
+ this.front = 1 - this.front;
+ };
+ if (loader.decode) loader.decode().then(swap, () => {});
+ else loader.onload = swap;
+ }
+}
diff --git a/app/js/ui/grid.js b/app/js/ui/grid.js
new file mode 100644
index 0000000..3bccb25
--- /dev/null
+++ b/app/js/ui/grid.js
@@ -0,0 +1,132 @@
+// Vertical, virtualized poster grid for whole libraries.
+// Each row is its own compositor layer, so scrolling only re-rasterizes the one
+// row that gets recycled with new posters. The track moves by transform; the
+// focus ring moves horizontally on its own layer.
+import { h, setTransform } from '../util/dom.js';
+import { createTile, fillTile, KINDS } from './tile.js';
+
+export class Grid {
+ constructor({ cols = 7, kind = 'grid', gapX = 41, gapY = 28, captionH = 70, top = 0, height = 1080, getItem, total = 0, onFocus, onSelect, onNeed }) {
+ this.cols = cols;
+ this.size = KINDS[kind];
+ this.stepX = this.size.w + gapX;
+ this.stepY = this.size.h + captionH + gapY;
+ this.getItem = getItem;
+ this.total = total;
+ this.onFocus = onFocus;
+ this.onSelect = onSelect;
+ this.onNeed = onNeed;
+ this.index = 0;
+ this.scrollRow = 0;
+
+ this.el = h('div', 'grid');
+ this.el.style.top = top + 'px';
+ this.el.style.height = height + 'px';
+ this.track = h('div', 'grid-track', this.el);
+ this.ring = h('div', 'ring on', this.track);
+ this.ring.style.width = (this.size.w + 16) + 'px';
+ this.ring.style.height = (this.size.h + 16) + 'px';
+
+ this.visibleRows = Math.ceil(height / this.stepY) + 1;
+ this.poolRows = this.visibleRows + 2;
+ this.rows = [];
+ for (let r = 0; r < this.poolRows; r++) {
+ const rowEl = h('div', 'grid-row', this.track);
+ const tiles = [];
+ for (let c = 0; c < cols; c++) {
+ const tile = createTile(kind, { caption: true });
+ setTransform(tile.el, 'translateX(' + c * this.stepX + 'px)');
+ rowEl.appendChild(tile.el);
+ tiles.push(tile);
+ }
+ this.rows.push({ el: rowEl, tiles, row: -1 });
+ }
+ this.render();
+ }
+
+ get rowCount() {
+ return Math.ceil(this.total / this.cols);
+ }
+
+ setTotal(total) {
+ this.total = total;
+ this.refresh();
+ }
+
+ current() {
+ return this.getItem(this.index);
+ }
+
+ // Data for some rows arrived: re-fill whatever is on screen.
+ refresh() {
+ for (const r of this.rows) r.row = -1;
+ this.render();
+ }
+
+ move(dx, dy) {
+ const col = this.index % this.cols;
+ let next = this.index;
+ if (dx) {
+ if (col + dx < 0 || col + dx >= this.cols) return false;
+ next += dx;
+ }
+ if (dy) next += dy * this.cols;
+ if (next < 0) return false;
+ if (next >= this.total) {
+ // Moving down into a short last row lands on its last item.
+ if (dy > 0 && Math.floor(next / this.cols) < this.rowCount) next = this.total - 1;
+ else return false;
+ }
+ if (next === this.index) return false;
+ this.focusIndex(next);
+ return true;
+ }
+
+ focusIndex(i) {
+ this.index = Math.max(0, Math.min(this.total - 1, i));
+ this.render();
+ if (this.onFocus) this.onFocus(this.current(), this.index);
+ }
+
+ select() {
+ const item = this.current();
+ if (item && this.onSelect) this.onSelect(item, this.index);
+ }
+
+ render() {
+ const focusRow = Math.floor(this.index / this.cols);
+ // Keep the focused row second from the top (first row at the very top).
+ this.scrollRow = Math.max(0, focusRow - 1);
+ const firstRow = Math.max(0, this.scrollRow - 1);
+ const lastRow = Math.min(this.rowCount, firstRow + this.poolRows);
+
+ for (let r = firstRow; r < lastRow; r++) {
+ const slot = this.rows[r % this.poolRows];
+ if (slot.row === r) continue;
+ slot.row = r;
+ slot.el.style.visibility = '';
+ setTransform(slot.el, 'translateY(' + r * this.stepY + 'px)');
+ for (let c = 0; c < this.cols; c++) {
+ const i = r * this.cols + c;
+ const tile = slot.tiles[c];
+ if (i < this.total) {
+ tile.el.style.visibility = '';
+ fillTile(tile, this.getItem(i) || null);
+ } else {
+ tile.el.style.visibility = 'hidden';
+ }
+ }
+ }
+ for (const slot of this.rows) {
+ if (slot.row < firstRow || slot.row >= lastRow) {
+ slot.row = -1;
+ slot.el.style.visibility = 'hidden';
+ }
+ }
+ if (this.onNeed) this.onNeed(firstRow * this.cols, lastRow * this.cols + this.cols * 4);
+
+ setTransform(this.track, 'translateY(' + (-this.scrollRow * this.stepY) + 'px)');
+ const col = this.index % this.cols;
+ setTransform(this.ring, 'translate(' + (col * this.stepX - 8) + 'px,' + (focusRow * this.stepY - 8) + 'px)');
+ }
+}
diff --git a/app/js/ui/hud.js b/app/js/ui/hud.js
new file mode 100644
index 0000000..5598226
--- /dev/null
+++ b/app/js/ui/hud.js
@@ -0,0 +1,63 @@
+// Perf overlay: fps, worst frame and key-to-frame latency. On in dev builds
+// (and reported to the devserver), toggleable from Settings in release builds.
+import { DEV } from '../config.js';
+import { h, setText } from '../util/dom.js';
+import { stats } from '../input.js';
+import { perf } from '../util/log.js';
+import * as store from '../util/store.js';
+
+let el = null;
+let running = false;
+let frames = 0;
+let worst = 0;
+let last = 0;
+let windowStart = 0;
+let maxLatency = 0;
+let longFrames = 0;
+let screenName = () => '';
+
+function tick(now) {
+ if (!running) return;
+ const dt = now - last;
+ last = now;
+ frames++;
+ if (dt > worst) worst = dt;
+ if (dt > 50) longFrames++;
+ if (stats.keyAt) {
+ stats.latency = now - stats.keyAt;
+ if (stats.latency > maxLatency) maxLatency = stats.latency;
+ stats.keyAt = 0;
+ }
+ if (now - windowStart >= 1000) {
+ const fps = Math.round(frames * 1000 / (now - windowStart));
+ setText(el, fps + ' fps · worst ' + worst.toFixed(0) + 'ms · key ' + stats.latency.toFixed(0) + 'ms');
+ // Only report windows where something happened, so idle doesn't drown the log.
+ if (maxLatency || fps < 55) {
+ perf('screen=' + screenName() + ' fps=' + fps + ' worst=' + worst.toFixed(0) + ' long=' + longFrames + ' keyMax=' + maxLatency.toFixed(0));
+ }
+ frames = 0; worst = 0; longFrames = 0; maxLatency = 0; windowStart = now;
+ }
+ requestAnimationFrame(tick);
+}
+
+// Only an explicit choice in Settings is remembered; dev builds default to on.
+export function setHud(on, remember = true) {
+ if (remember) store.set('hud', on);
+ if (on === running) return;
+ running = on;
+ if (!el) el = h('div', 'hud', document.body);
+ el.style.display = on ? '' : 'none';
+ if (on) {
+ last = windowStart = performance.now();
+ requestAnimationFrame(tick);
+ }
+}
+
+export function hudEnabled() {
+ return running;
+}
+
+export function initHud(getScreenName) {
+ screenName = getScreenName;
+ setHud(store.get('hud', DEV), false);
+}
diff --git a/app/js/ui/icons.js b/app/js/ui/icons.js
new file mode 100644
index 0000000..c052f39
--- /dev/null
+++ b/app/js/ui/icons.js
@@ -0,0 +1,11 @@
+// Inline SVG icons (stroke/fill use currentColor).
+export const play = '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M7 4.5v15a1 1 0 0 0 1.5.86l12.5-7.5a1 1 0 0 0 0-1.72L8.5 3.64A1 1 0 0 0 7 4.5z"/></svg>';
+export const pause = '<svg viewBox="0 0 24 24"><rect fill="currentColor" x="5" y="4" width="5" height="16" rx="1.2"/><rect fill="currentColor" x="14" y="4" width="5" height="16" rx="1.2"/></svg>';
+export const restart = '<svg viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" d="M4 12a8 8 0 1 0 2.4-5.7M4 4v4.5h4.5"/></svg>';
+export const check = '<svg viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-width="2.8" stroke-linecap="round" stroke-linejoin="round" d="M5 12.5l4.5 4.5L19 7.5"/></svg>';
+export const uncheck = '<svg viewBox="0 0 24 24"><circle fill="none" stroke="currentColor" stroke-width="2.4" cx="12" cy="12" r="8"/></svg>';
+export const tv = '<svg viewBox="0 0 24 24"><rect fill="none" stroke="currentColor" stroke-width="2.2" x="3" y="6" width="18" height="13" rx="2.5"/><path fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" d="M8.5 2.5L12 6l3.5-3.5"/></svg>';
+export const search = '<svg viewBox="0 0 24 24"><circle fill="none" stroke="currentColor" stroke-width="2.6" cx="10.5" cy="10.5" r="6.5"/><path stroke="currentColor" stroke-width="2.6" stroke-linecap="round" d="M15.5 15.5L20 20"/></svg>';
+export const gear = '<svg viewBox="0 0 24 24"><circle fill="none" stroke="currentColor" stroke-width="2.4" cx="12" cy="12" r="3.2"/><path fill="none" stroke="currentColor" stroke-width="2.2" stroke-linejoin="round" d="M12 2.8l1.6 2.4 2.8-.7.7 2.8 2.4 1.6-1.2 2.6 1.2 2.6-2.4 1.6-.7 2.8-2.8-.7L12 21.2l-1.6-2.4-2.8.7-.7-2.8-2.4-1.6L5.7 12 4.5 9.4l2.4-1.6.7-2.8 2.8.7z"/></svg>';
+export const subtitles = '<svg viewBox="0 0 24 24"><rect fill="none" stroke="currentColor" stroke-width="2.2" x="2.5" y="5" width="19" height="14" rx="2.5"/><path stroke="currentColor" stroke-width="2.2" stroke-linecap="round" d="M6.5 15h4M13 15h4.5M6.5 11.5h7M15.5 11.5h2"/></svg>';
+export const audio = '<svg viewBox="0 0 24 24"><path fill="currentColor" d="M4 9.5h3.5L12 5v14l-4.5-4.5H4z"/><path fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" d="M15.5 9a4 4 0 0 1 0 6M18 6.5a7.5 7.5 0 0 1 0 11"/></svg>';
diff --git a/app/js/ui/images.js b/app/js/ui/images.js
new file mode 100644
index 0000000..c5a6133
--- /dev/null
+++ b/app/js/ui/images.js
@@ -0,0 +1,75 @@
+// Image loading tuned for a slow TV CPU:
+// - a few downloads at a time, newest request first (what's on screen now
+// matters more than what scrolled past),
+// - requests for nodes that were recycled before loading are dropped,
+// - decode() runs off the main thread before the image is attached, so
+// attaching never stalls a frame.
+const MAX_ACTIVE = 6;
+const LOADED_MAX = 800;
+
+const queue = [];
+let active = 0;
+const loaded = new Map(); // url -> true, in insertion order for LRU trimming
+
+function remember(url) {
+ loaded.delete(url);
+ loaded.set(url, true);
+ if (loaded.size > LOADED_MAX) loaded.delete(loaded.keys().next().value);
+}
+
+function attach(img, url, instant) {
+ img.src = url;
+ if (instant) {
+ img.classList.add('in', 'now');
+ } else {
+ img.classList.remove('now');
+ img.classList.add('in');
+ }
+}
+
+function pump() {
+ while (active < MAX_ACTIVE && queue.length) {
+ const job = queue.pop();
+ if (job.img._want !== job.url) continue;
+ active++;
+ const loader = new Image();
+ loader.src = job.url;
+ const done = ok => {
+ active--;
+ if (ok) {
+ remember(job.url);
+ if (job.img._want === job.url) attach(job.img, job.url, false);
+ }
+ pump();
+ };
+ if (loader.decode) loader.decode().then(() => done(true), () => done(false));
+ else { loader.onload = () => done(true); loader.onerror = () => done(false); }
+ }
+}
+
+// Point an <img> at a URL. Empty url clears it.
+export function load(img, url) {
+ if (img._want === url) return;
+ img._want = url;
+ if (!url) {
+ img.classList.remove('in');
+ img.removeAttribute('src');
+ return;
+ }
+ if (loaded.has(url)) {
+ attach(img, url, true);
+ return;
+ }
+ img.classList.remove('in');
+ queue.push({ img, url });
+ if (queue.length > 200) queue.splice(0, queue.length - 200);
+ pump();
+}
+
+// Warm the cache without a target element (e.g. the next page of a grid).
+export function prefetch(url) {
+ if (!url || loaded.has(url)) return;
+ const sink = { _want: url, classList: { add() {}, remove() {} } };
+ queue.unshift({ img: sink, url });
+ pump();
+}
diff --git a/app/js/ui/row.js b/app/js/ui/row.js
new file mode 100644
index 0000000..58de17e
--- /dev/null
+++ b/app/js/ui/row.js
@@ -0,0 +1,116 @@
+// Horizontal, virtualized row. Focus is anchored at the left edge: the track
+// slides under a stationary focus ring, so every move is one compositor-only
+// transform and the ring never repaints.
+import { h, setText, setTransform, toggleClass } from '../util/dom.js';
+import { createTile, fillTile, KINDS } from './tile.js';
+
+const GAP = 28;
+const LEFT = 96;
+const BEHIND = 2; // tiles kept to the left of focus (one is peeking on screen)
+
+export class Row {
+ constructor({ title, kind = 'poster', items = [], caption = false, onFocus, onSelect }) {
+ this.kind = kind;
+ this.size = KINDS[kind];
+ this.step = this.size.w + GAP;
+ this.items = items;
+ this.index = 0;
+ this.active = false;
+ this.onFocus = onFocus;
+ this.onSelect = onSelect;
+
+ this.el = h('section', 'row');
+ this.titleEl = h('h2', 'row-title', this.el);
+ setText(this.titleEl, title || '');
+ const clip = h('div', 'row-clip', this.el);
+ this.track = h('div', 'row-track', clip);
+ this.track.style.left = LEFT + 'px';
+ this.ring = h('div', 'ring', clip);
+ this.ring.style.left = (LEFT - 8) + 'px';
+ this.ring.style.width = (this.size.w + 16) + 'px';
+ this.ring.style.height = (this.size.h + 16) + 'px';
+
+ this.captionH = caption ? 70 : 0;
+ clip.style.height = (this.size.h + this.captionH + 24) + 'px';
+ this.height = (title ? 64 : 0) + this.size.h + this.captionH + 24;
+
+ const visible = Math.ceil((1920 - LEFT) / this.step);
+ this.poolSize = visible + BEHIND + 2;
+ this.pool = [];
+ for (let i = 0; i < this.poolSize; i++) {
+ const tile = createTile(kind, { caption });
+ tile.index = -1;
+ this.track.appendChild(tile.el);
+ this.pool.push(tile);
+ }
+ this.render();
+ }
+
+ setItems(items, keepKey) {
+ this.items = items;
+ if (keepKey) {
+ const i = items.findIndex(it => it.ratingKey === keepKey);
+ this.index = i >= 0 ? i : Math.min(this.index, items.length - 1);
+ } else {
+ this.index = Math.min(this.index, Math.max(0, items.length - 1));
+ }
+ for (const t of this.pool) { t.index = -1; t.item = undefined; }
+ this.render();
+ }
+
+ setTitle(title) {
+ setText(this.titleEl, title);
+ }
+
+ current() {
+ return this.items[this.index];
+ }
+
+ setActive(on) {
+ this.active = on;
+ toggleClass(this.el, 'active', on);
+ }
+
+ focusIndex(i) {
+ if (!this.items.length) return;
+ this.index = Math.max(0, Math.min(this.items.length - 1, i));
+ this.render();
+ if (this.onFocus) this.onFocus(this.current(), this);
+ }
+
+ // Returns false at the edges so the parent can decide what to do.
+ move(dx) {
+ const next = this.index + dx;
+ if (next < 0 || next >= this.items.length) return false;
+ this.index = next;
+ this.render();
+ if (this.onFocus) this.onFocus(this.current(), this);
+ return true;
+ }
+
+ select() {
+ if (this.onSelect && this.current()) this.onSelect(this.current(), this);
+ }
+
+ render() {
+ const first = Math.max(0, this.index - BEHIND);
+ const last = Math.min(this.items.length, first + this.poolSize);
+ for (let i = first; i < last; i++) {
+ const tile = this.pool[i % this.poolSize];
+ if (tile.index !== i) {
+ tile.index = i;
+ setTransform(tile.el, 'translateX(' + i * this.step + 'px)');
+ tile.el.style.visibility = '';
+ }
+ fillTile(tile, this.items[i]);
+ }
+ // Slots not covering any item this frame.
+ for (const tile of this.pool) {
+ if (tile.index < first || tile.index >= last) {
+ tile.index = -1;
+ tile.el.style.visibility = 'hidden';
+ }
+ }
+ setTransform(this.track, 'translateX(' + (-this.index * this.step) + 'px)');
+ }
+}
diff --git a/app/js/ui/tile.js b/app/js/ui/tile.js
new file mode 100644
index 0000000..a63edae
--- /dev/null
+++ b/app/js/ui/tile.js
@@ -0,0 +1,100 @@
+// Poster / landscape tiles. A tile node is created once and re-filled as it is
+// recycled; fill() only touches the DOM for fields that changed.
+import { h, setText, show, setTransform, toggleClass } from '../util/dom.js';
+import { load } from './images.js';
+import { session } from '../session.js';
+import { progress, episodeLabel } from '../util/format.js';
+
+export const KINDS = {
+ poster: { w: 220, h: 330 },
+ wide: { w: 400, h: 225 },
+ grid: { w: 216, h: 324 },
+ episode: { w: 384, h: 216 },
+};
+
+export function createTile(kind, { caption = false } = {}) {
+ const size = KINDS[kind];
+ const el = h('div', 'tile tile-' + kind);
+ const frame = h('div', 'tile-frame', el);
+ frame.style.width = size.w + 'px';
+ frame.style.height = size.h + 'px';
+ const img = h('img', 'tile-img', frame);
+ const ph = h('div', 'tile-ph', frame);
+ img.alt = '';
+ const badge = h('div', 'tile-badge', frame);
+ const bar = h('div', 'tile-bar', frame);
+ const fill = h('i', '', bar);
+ let cap = null;
+ let sub = null;
+ if (caption) {
+ cap = h('div', 'tile-cap', el);
+ cap.style.width = size.w + 'px';
+ sub = h('div', 'tile-sub', el);
+ sub.style.width = size.w + 'px';
+ }
+ return { el, img, ph, badge, bar, fill, cap, sub, kind, size, item: null };
+}
+
+function artFor(item, kind) {
+ if (kind === 'wide' || kind === 'episode') {
+ if (item.type === 'episode') return item.thumb || item.art;
+ return item.art || item.thumb;
+ }
+ if (item.type === 'episode') return item.grandparentThumb || item.parentThumb || item.thumb;
+ if (item.type === 'season') return item.thumb || item.parentThumb;
+ return item.thumb;
+}
+
+function titleFor(item, kind) {
+ if (item.type === 'episode' && kind !== 'episode') return item.grandparentTitle || item.title;
+ return item.title;
+}
+
+function subFor(item, kind) {
+ if (item.type === 'episode') {
+ return kind === 'episode' ? episodeLabel(item).replace(' · ', '') + ' ' + item.title
+ : episodeLabel(item) + ' ' + item.title;
+ }
+ if (item.type === 'season') return item.leafCount ? item.leafCount + ' episodes' : '';
+ return item.year || '';
+}
+
+export function fillTile(tile, item) {
+ if (tile.item === item) return;
+ tile.item = item;
+ if (!item) {
+ load(tile.img, '');
+ setText(tile.ph, '');
+ show(tile.bar, false);
+ show(tile.badge, false);
+ if (tile.cap) { setText(tile.cap, ''); setText(tile.sub, ''); }
+ return;
+ }
+ const kind = tile.kind;
+ const server = session.server;
+ const path = artFor(item, kind);
+ // The web layer is 1920x1080, so tile size is exactly the pixels we need.
+ load(tile.img, server ? server.image(path, tile.size.w, tile.size.h) : '');
+ setText(tile.ph, titleFor(item, kind));
+
+ const p = progress(item);
+ show(tile.bar, p > 0.01);
+ if (p > 0.01) setTransform(tile.fill, 'scaleX(' + p.toFixed(3) + ')');
+
+ // Unwatched episode count on shows/seasons, check on watched items.
+ let badge = '';
+ if ((item.type === 'show' || item.type === 'season') && item.leafCount) {
+ const left = item.leafCount - (item.viewedLeafCount || 0);
+ badge = left > 0 ? String(left) : '✓';
+ } else if (item.viewCount && !item.viewOffset && item.type !== 'show') {
+ badge = '✓';
+ }
+ show(tile.badge, !!badge);
+ setText(tile.badge, badge);
+ toggleClass(tile.badge, 'done', badge === '✓');
+
+ if (tile.cap) {
+ setText(tile.cap, kind === 'episode' ? item.title : titleFor(item, kind));
+ setText(tile.sub, kind === 'episode' ? episodeLabel(item) + (item.duration ? ' · ' + Math.round(item.duration / 60000) + 'm' : '') : subFor(item, kind));
+ }
+}
diff --git a/app/js/util/dom.js b/app/js/util/dom.js
new file mode 100644
index 0000000..d3f6773
--- /dev/null
+++ b/app/js/util/dom.js
@@ -0,0 +1,35 @@
+export function h(tag, className, parent) {
+ const el = document.createElement(tag);
+ if (className) el.className = className;
+ if (parent) parent.appendChild(el);
+ return el;
+}
+
+// Skip DOM writes when nothing changed; text and style writes are what
+// invalidate paint on recycled nodes.
+export function setText(el, value) {
+ value = value == null ? '' : String(value);
+ if (el._text !== value) {
+ el._text = value;
+ el.textContent = value;
+ }
+}
+
+export function setTransform(el, value) {
+ if (el._tf !== value) {
+ el._tf = value;
+ el.style.transform = value;
+ }
+}
+
+export function show(el, visible) {
+ const v = visible ? '' : 'none';
+ if (el._disp !== v) {
+ el._disp = v;
+ el.style.display = v;
+ }
+}
+
+export function toggleClass(el, name, on) {
+ if (el.classList.contains(name) !== !!on) el.classList.toggle(name, !!on);
+}
diff --git a/app/js/util/format.js b/app/js/util/format.js
new file mode 100644
index 0000000..cc86c93
--- /dev/null
+++ b/app/js/util/format.js
@@ -0,0 +1,48 @@
+export function duration(ms) {
+ if (!ms) return '';
+ const min = Math.round(ms / 60000);
+ if (min < 60) return min + 'm';
+ return Math.floor(min / 60) + 'h ' + (min % 60) + 'm';
+}
+
+export function clock(ms) {
+ const s = Math.max(0, Math.floor(ms / 1000));
+ const hh = Math.floor(s / 3600);
+ const mm = Math.floor((s % 3600) / 60);
+ const ss = s % 60;
+ const pad = n => (n < 10 ? '0' : '') + n;
+ return (hh ? hh + ':' + pad(mm) : mm) + ':' + pad(ss);
+}
+
+export function episodeLabel(item) {
+ if (item.type !== 'episode') return '';
+ return 'S' + (item.parentIndex || 0) + ' · E' + (item.index || 0);
+}
+
+// The line under a title: "2019 · PG-13 · 2h 4m" style.
+export function metaLine(item) {
+ const parts = [];
+ if (item.type === 'episode') {
+ parts.push(episodeLabel(item));
+ if (item.originallyAvailableAt) parts.push(item.originallyAvailableAt.slice(0, 4));
+ } else if (item.year) {
+ parts.push(item.year);
+ }
+ if (item.contentRating) parts.push(item.contentRating);
+ if (item.type === 'show' && item.childCount) parts.push(item.childCount + (item.childCount === 1 ? ' season' : ' seasons'));
+ else if (item.duration) parts.push(duration(item.duration));
+ if (item.audienceRating) parts.push('★ ' + Number(item.audienceRating).toFixed(1));
+ return parts.join(' · ');
+}
+
+export function progress(item) {
+ if (!item.viewOffset || !item.duration) return 0;
+ return Math.min(1, item.viewOffset / item.duration);
+}
+
+export function uuid() {
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
+ const r = Math.random() * 16 | 0;
+ return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
+ });
+}
diff --git a/app/js/util/log.js b/app/js/util/log.js
new file mode 100644
index 0000000..3757f87
--- /dev/null
+++ b/app/js/util/log.js
@@ -0,0 +1,38 @@
+import { DEV, DEV_HOST } from '../config.js';
+// Logging. In dev builds every line is also batched to the devserver on the Mac,
+// since the TV gives us no usable console.
+const queue = [];
+let timer = 0;
+
+function stringify(args) {
+ return args.map(a => {
+ if (a instanceof Error) return a.stack || a.message;
+ if (typeof a === 'object') { try { return JSON.stringify(a); } catch (e) { return String(a); } }
+ return String(a);
+ }).join(' ');
+}
+
+function flush() {
+ timer = 0;
+ if (!queue.length) return;
+ const body = JSON.stringify(queue.splice(0));
+ try {
+ fetch('http://' + DEV_HOST + '/log', { method: 'POST', body, headers: { 'Content-Type': 'text/plain' } }).catch(() => {});
+ } catch (e) { /* devserver not running */ }
+}
+
+function emit(level, args) {
+ if (!DEV || !DEV_HOST) return;
+ queue.push({ t: Date.now(), level, msg: stringify(args) });
+ if (!timer) timer = setTimeout(flush, 400);
+}
+
+export const log = (...a) => { console.log(...a); emit('log', a); };
+export const warn = (...a) => { console.warn(...a); emit('warn', a); };
+export const error = (...a) => { console.error(...a); emit('error', a); };
+export const perf = (...a) => emit('perf', a);
+
+if (DEV) {
+ window.addEventListener('error', e => error('uncaught', e.message, (e.filename || '') + ':' + e.lineno, e.error || ''));
+ window.addEventListener('unhandledrejection', e => error('unhandled rejection', e.reason));
+}
diff --git a/app/js/util/store.js b/app/js/util/store.js
new file mode 100644
index 0000000..a1bcfde
--- /dev/null
+++ b/app/js/util/store.js
@@ -0,0 +1,18 @@
+// localStorage wrapper. Tizen keeps it across app restarts; it can throw when full.
+const PREFIX = 'ss.';
+
+export function get(key, fallback) {
+ try {
+ const raw = localStorage.getItem(PREFIX + key);
+ return raw == null ? fallback : JSON.parse(raw);
+ } catch (e) {
+ return fallback;
+ }
+}
+
+export function set(key, value) {
+ try {
+ if (value === undefined) localStorage.removeItem(PREFIX + key);
+ else localStorage.setItem(PREFIX + key, JSON.stringify(value));
+ } catch (e) { /* quota */ }
+}
diff --git a/app/js/vendor/qrcode.js b/app/js/vendor/qrcode.js
new file mode 100644
index 0000000..4445225
--- /dev/null
+++ b/app/js/vendor/qrcode.js
@@ -0,0 +1,2237 @@
+//---------------------------------------------------------------------
+//
+// QR Code Generator for JavaScript
+//
+// Copyright (c) 2009 Kazuhiko Arase
+//
+// URL: http://www.d-project.com/
+//
+// Licensed under the MIT license:
+// http://www.opensource.org/licenses/mit-license.php
+//
+// The word 'QR Code' is registered trademark of
+// DENSO WAVE INCORPORATED
+// http://www.denso-wave.com/qrcode/faqpatent-e.html
+//
+//---------------------------------------------------------------------
+
+//---------------------------------------------------------------------
+// qrcode
+//---------------------------------------------------------------------
+
+/**
+ * qrcode
+ * @param typeNumber 1 to 40
+ * @param errorCorrectionLevel 'L','M','Q','H'
+ */
+export const qrcode = function(typeNumber, errorCorrectionLevel) {
+
+ const PAD0 = 0xEC;
+ const PAD1 = 0x11;
+
+ let _typeNumber = typeNumber;
+ const _errorCorrectionLevel = QRErrorCorrectionLevel[errorCorrectionLevel];
+ let _modules = null;
+ let _moduleCount = 0;
+ let _dataCache = null;
+ const _dataList = [];
+
+ const _this = {};
+
+ const makeImpl = function(test, maskPattern) {
+
+ _moduleCount = _typeNumber * 4 + 17;
+ _modules = function(moduleCount) {
+ const modules = new Array(moduleCount);
+ for (let row = 0; row < moduleCount; row += 1) {
+ modules[row] = new Array(moduleCount);
+ for (let col = 0; col < moduleCount; col += 1) {
+ modules[row][col] = null;
+ }
+ }
+ return modules;
+ }(_moduleCount);
+
+ setupPositionProbePattern(0, 0);
+ setupPositionProbePattern(_moduleCount - 7, 0);
+ setupPositionProbePattern(0, _moduleCount - 7);
+ setupPositionAdjustPattern();
+ setupTimingPattern();
+ setupTypeInfo(test, maskPattern);
+
+ if (_typeNumber >= 7) {
+ setupTypeNumber(test);
+ }
+
+ if (_dataCache == null) {
+ _dataCache = createData(_typeNumber, _errorCorrectionLevel, _dataList);
+ }
+
+ mapData(_dataCache, maskPattern);
+ };
+
+ const setupPositionProbePattern = function(row, col) {
+
+ for (let r = -1; r <= 7; r += 1) {
+
+ if (row + r <= -1 || _moduleCount <= row + r) continue;
+
+ for (let c = -1; c <= 7; c += 1) {
+
+ if (col + c <= -1 || _moduleCount <= col + c) continue;
+
+ if ( (0 <= r && r <= 6 && (c == 0 || c == 6) )
+ || (0 <= c && c <= 6 && (r == 0 || r == 6) )
+ || (2 <= r && r <= 4 && 2 <= c && c <= 4) ) {
+ _modules[row + r][col + c] = true;
+ } else {
+ _modules[row + r][col + c] = false;
+ }
+ }
+ }
+ };
+
+ const getBestMaskPattern = function() {
+
+ let minLostPoint = 0;
+ let pattern = 0;
+
+ for (let i = 0; i < 8; i += 1) {
+
+ makeImpl(true, i);
+
+ const lostPoint = QRUtil.getLostPoint(_this);
+
+ if (i == 0 || minLostPoint > lostPoint) {
+ minLostPoint = lostPoint;
+ pattern = i;
+ }
+ }
+
+ return pattern;
+ };
+
+ const setupTimingPattern = function() {
+
+ for (let r = 8; r < _moduleCount - 8; r += 1) {
+ if (_modules[r][6] != null) {
+ continue;
+ }
+ _modules[r][6] = (r % 2 == 0);
+ }
+
+ for (let c = 8; c < _moduleCount - 8; c += 1) {
+ if (_modules[6][c] != null) {
+ continue;
+ }
+ _modules[6][c] = (c % 2 == 0);
+ }
+ };
+
+ const setupPositionAdjustPattern = function() {
+
+ const pos = QRUtil.getPatternPosition(_typeNumber);
+
+ for (let i = 0; i < pos.length; i += 1) {
+
+ for (let j = 0; j < pos.length; j += 1) {
+
+ const row = pos[i];
+ const col = pos[j];
+
+ if (_modules[row][col] != null) {
+ continue;
+ }
+
+ for (let r = -2; r <= 2; r += 1) {
+
+ for (let c = -2; c <= 2; c += 1) {
+
+ if (r == -2 || r == 2 || c == -2 || c == 2
+ || (r == 0 && c == 0) ) {
+ _modules[row + r][col + c] = true;
+ } else {
+ _modules[row + r][col + c] = false;
+ }
+ }
+ }
+ }
+ }
+ };
+
+ const setupTypeNumber = function(test) {
+
+ const bits = QRUtil.getBCHTypeNumber(_typeNumber);
+
+ for (let i = 0; i < 18; i += 1) {
+ const mod = (!test && ( (bits >> i) & 1) == 1);
+ _modules[Math.floor(i / 3)][i % 3 + _moduleCount - 8 - 3] = mod;
+ }
+
+ for (let i = 0; i < 18; i += 1) {
+ const mod = (!test && ( (bits >> i) & 1) == 1);
+ _modules[i % 3 + _moduleCount - 8 - 3][Math.floor(i / 3)] = mod;
+ }
+ };
+
+ const setupTypeInfo = function(test, maskPattern) {
+
+ const data = (_errorCorrectionLevel << 3) | maskPattern;
+ const bits = QRUtil.getBCHTypeInfo(data);
+
+ // vertical
+ for (let i = 0; i < 15; i += 1) {
+
+ const mod = (!test && ( (bits >> i) & 1) == 1);
+
+ if (i < 6) {
+ _modules[i][8] = mod;
+ } else if (i < 8) {
+ _modules[i + 1][8] = mod;
+ } else {
+ _modules[_moduleCount - 15 + i][8] = mod;
+ }
+ }
+
+ // horizontal
+ for (let i = 0; i < 15; i += 1) {
+
+ const mod = (!test && ( (bits >> i) & 1) == 1);
+
+ if (i < 8) {
+ _modules[8][_moduleCount - i - 1] = mod;
+ } else if (i < 9) {
+ _modules[8][15 - i - 1 + 1] = mod;
+ } else {
+ _modules[8][15 - i - 1] = mod;
+ }
+ }
+
+ // fixed module
+ _modules[_moduleCount - 8][8] = (!test);
+ };
+
+ const mapData = function(data, maskPattern) {
+
+ let inc = -1;
+ let row = _moduleCount - 1;
+ let bitIndex = 7;
+ let byteIndex = 0;
+ const maskFunc = QRUtil.getMaskFunction(maskPattern);
+
+ for (let col = _moduleCount - 1; col > 0; col -= 2) {
+
+ if (col == 6) col -= 1;
+
+ while (true) {
+
+ for (let c = 0; c < 2; c += 1) {
+
+ if (_modules[row][col - c] == null) {
+
+ let dark = false;
+
+ if (byteIndex < data.length) {
+ dark = ( ( (data[byteIndex] >>> bitIndex) & 1) == 1);
+ }
+
+ const mask = maskFunc(row, col - c);
+
+ if (mask) {
+ dark = !dark;
+ }
+
+ _modules[row][col - c] = dark;
+ bitIndex -= 1;
+
+ if (bitIndex == -1) {
+ byteIndex += 1;
+ bitIndex = 7;
+ }
+ }
+ }
+
+ row += inc;
+
+ if (row < 0 || _moduleCount <= row) {
+ row -= inc;
+ inc = -inc;
+ break;
+ }
+ }
+ }
+ };
+
+ const createBytes = function(buffer, rsBlocks) {
+
+ let offset = 0;
+
+ let maxDcCount = 0;
+ let maxEcCount = 0;
+
+ const dcdata = new Array(rsBlocks.length);
+ const ecdata = new Array(rsBlocks.length);
+
+ for (let r = 0; r < rsBlocks.length; r += 1) {
+
+ const dcCount = rsBlocks[r].dataCount;
+ const ecCount = rsBlocks[r].totalCount - dcCount;
+
+ maxDcCount = Math.max(maxDcCount, dcCount);
+ maxEcCount = Math.max(maxEcCount, ecCount);
+
+ dcdata[r] = new Array(dcCount);
+
+ for (let i = 0; i < dcdata[r].length; i += 1) {
+ dcdata[r][i] = 0xff & buffer.getBuffer()[i + offset];
+ }
+ offset += dcCount;
+
+ const rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount);
+ const rawPoly = qrPolynomial(dcdata[r], rsPoly.getLength() - 1);
+
+ const modPoly = rawPoly.mod(rsPoly);
+ ecdata[r] = new Array(rsPoly.getLength() - 1);
+ for (let i = 0; i < ecdata[r].length; i += 1) {
+ const modIndex = i + modPoly.getLength() - ecdata[r].length;
+ ecdata[r][i] = (modIndex >= 0)? modPoly.getAt(modIndex) : 0;
+ }
+ }
+
+ let totalCodeCount = 0;
+ for (let i = 0; i < rsBlocks.length; i += 1) {
+ totalCodeCount += rsBlocks[i].totalCount;
+ }
+
+ const data = new Array(totalCodeCount);
+ let index = 0;
+
+ for (let i = 0; i < maxDcCount; i += 1) {
+ for (let r = 0; r < rsBlocks.length; r += 1) {
+ if (i < dcdata[r].length) {
+ data[index] = dcdata[r][i];
+ index += 1;
+ }
+ }
+ }
+
+ for (let i = 0; i < maxEcCount; i += 1) {
+ for (let r = 0; r < rsBlocks.length; r += 1) {
+ if (i < ecdata[r].length) {
+ data[index] = ecdata[r][i];
+ index += 1;
+ }
+ }
+ }
+
+ return data;
+ };
+
+ const createData = function(typeNumber, errorCorrectionLevel, dataList) {
+
+ const rsBlocks = QRRSBlock.getRSBlocks(typeNumber, errorCorrectionLevel);
+
+ const buffer = qrBitBuffer();
+
+ for (let i = 0; i < dataList.length; i += 1) {
+ const data = dataList[i];
+ buffer.put(data.getMode(), 4);
+ buffer.put(data.getLength(), QRUtil.getLengthInBits(data.getMode(), typeNumber) );
+ data.write(buffer);
+ }
+
+ // calc num max data.
+ let totalDataCount = 0;
+ for (let i = 0; i < rsBlocks.length; i += 1) {
+ totalDataCount += rsBlocks[i].dataCount;
+ }
+
+ if (buffer.getLengthInBits() > totalDataCount * 8) {
+ throw 'code length overflow. ('
+ + buffer.getLengthInBits()
+ + '>'
+ + totalDataCount * 8
+ + ')';
+ }
+
+ // end code
+ if (buffer.getLengthInBits() + 4 <= totalDataCount * 8) {
+ buffer.put(0, 4);
+ }
+
+ // padding
+ while (buffer.getLengthInBits() % 8 != 0) {
+ buffer.putBit(false);
+ }
+
+ // padding
+ while (true) {
+
+ if (buffer.getLengthInBits() >= totalDataCount * 8) {
+ break;
+ }
+ buffer.put(PAD0, 8);
+
+ if (buffer.getLengthInBits() >= totalDataCount * 8) {
+ break;
+ }
+ buffer.put(PAD1, 8);
+ }
+
+ return createBytes(buffer, rsBlocks);
+ };
+
+ _this.addData = function(data, mode) {
+
+ mode = mode || 'Byte';
+
+ let newData = null;
+
+ switch(mode) {
+ case 'Numeric' :
+ newData = qrNumber(data);
+ break;
+ case 'Alphanumeric' :
+ newData = qrAlphaNum(data);
+ break;
+ case 'Byte' :
+ newData = qr8BitByte(data);
+ break;
+ case 'Kanji' :
+ newData = qrKanji(data);
+ break;
+ default :
+ throw 'mode:' + mode;
+ }
+
+ _dataList.push(newData);
+ _dataCache = null;
+ };
+
+ _this.isDark = function(row, col) {
+ if (row < 0 || _moduleCount <= row || col < 0 || _moduleCount <= col) {
+ throw row + ',' + col;
+ }
+ return _modules[row][col];
+ };
+
+ _this.getModuleCount = function() {
+ return _moduleCount;
+ };
+
+ _this.make = function() {
+ if (_typeNumber < 1) {
+ let typeNumber = 1;
+
+ for (; typeNumber < 40; typeNumber++) {
+ const rsBlocks = QRRSBlock.getRSBlocks(typeNumber, _errorCorrectionLevel);
+ const buffer = qrBitBuffer();
+
+ for (let i = 0; i < _dataList.length; i++) {
+ const data = _dataList[i];
+ buffer.put(data.getMode(), 4);
+ buffer.put(data.getLength(), QRUtil.getLengthInBits(data.getMode(), typeNumber) );
+ data.write(buffer);
+ }
+
+ let totalDataCount = 0;
+ for (let i = 0; i < rsBlocks.length; i++) {
+ totalDataCount += rsBlocks[i].dataCount;
+ }
+
+ if (buffer.getLengthInBits() <= totalDataCount * 8) {
+ break;
+ }
+ }
+
+ _typeNumber = typeNumber;
+ }
+
+ makeImpl(false, getBestMaskPattern() );
+ };
+
+ _this.createTableTag = function(cellSize, margin) {
+
+ cellSize = cellSize || 2;
+ margin = (typeof margin == 'undefined')? cellSize * 4 : margin;
+
+ let qrHtml = '';
+
+ qrHtml += '<table style="';
+ qrHtml += ' border-width: 0px; border-style: none;';
+ qrHtml += ' border-collapse: collapse;';
+ qrHtml += ' padding: 0px; margin: ' + margin + 'px;';
+ qrHtml += '">';
+ qrHtml += '<tbody>';
+
+ for (let r = 0; r < _this.getModuleCount(); r += 1) {
+
+ qrHtml += '<tr>';
+
+ for (let c = 0; c < _this.getModuleCount(); c += 1) {
+ qrHtml += '<td style="';
+ qrHtml += ' border-width: 0px; border-style: none;';
+ qrHtml += ' border-collapse: collapse;';
+ qrHtml += ' padding: 0px; margin: 0px;';
+ qrHtml += ' width: ' + cellSize + 'px;';
+ qrHtml += ' height: ' + cellSize + 'px;';
+ qrHtml += ' background-color: ';
+ qrHtml += _this.isDark(r, c)? '#000000' : '#ffffff';
+ qrHtml += ';';
+ qrHtml += '"/>';
+ }
+
+ qrHtml += '</tr>';
+ }
+
+ qrHtml += '</tbody>';
+ qrHtml += '</table>';
+
+ return qrHtml;
+ };
+
+ _this.createSvgTag = function(cellSize, margin, alt, title) {
+
+ let opts = {};
+ if (typeof arguments[0] == 'object') {
+ // Called by options.
+ opts = arguments[0];
+ // overwrite cellSize and margin.
+ cellSize = opts.cellSize;
+ margin = opts.margin;
+ alt = opts.alt;
+ title = opts.title;
+ }
+
+ cellSize = cellSize || 2;
+ margin = (typeof margin == 'undefined')? cellSize * 4 : margin;
+
+ // Compose alt property surrogate
+ alt = (typeof alt === 'string') ? {text: alt} : alt || {};
+ alt.text = alt.text || null;
+ alt.id = (alt.text) ? alt.id || 'qrcode-description' : null;
+
+ // Compose title property surrogate
+ title = (typeof title === 'string') ? {text: title} : title || {};
+ title.text = title.text || null;
+ title.id = (title.text) ? title.id || 'qrcode-title' : null;
+
+ const size = _this.getModuleCount() * cellSize + margin * 2;
+ let c, mc, r, mr, qrSvg='', rect;
+
+ rect = 'l' + cellSize + ',0 0,' + cellSize +
+ ' -' + cellSize + ',0 0,-' + cellSize + 'z ';
+
+ qrSvg += '<svg version="1.1" xmlns="http://www.w3.org/2000/svg"';
+ qrSvg += !opts.scalable ? ' width="' + size + 'px" height="' + size + 'px"' : '';
+ qrSvg += ' viewBox="0 0 ' + size + ' ' + size + '" ';
+ qrSvg += ' preserveAspectRatio="xMinYMin meet"';
+ qrSvg += (title.text || alt.text) ? ' role="img" aria-labelledby="' +
+ escapeXml([title.id, alt.id].join(' ').trim() ) + '"' : '';
+ qrSvg += '>';
+ qrSvg += (title.text) ? '<title id="' + escapeXml(title.id) + '">' +
+ escapeXml(title.text) + '</title>' : '';
+ qrSvg += (alt.text) ? '<description id="' + escapeXml(alt.id) + '">' +
+ escapeXml(alt.text) + '</description>' : '';
+ qrSvg += '<rect width="100%" height="100%" fill="white" cx="0" cy="0"/>';
+ qrSvg += '<path d="';
+
+ for (r = 0; r < _this.getModuleCount(); r += 1) {
+ mr = r * cellSize + margin;
+ for (c = 0; c < _this.getModuleCount(); c += 1) {
+ if (_this.isDark(r, c) ) {
+ mc = c*cellSize+margin;
+ qrSvg += 'M' + mc + ',' + mr + rect;
+ }
+ }
+ }
+
+ qrSvg += '" stroke="transparent" fill="black"/>';
+ qrSvg += '</svg>';
+
+ return qrSvg;
+ };
+
+ _this.createDataURL = function(cellSize, margin) {
+
+ cellSize = cellSize || 2;
+ margin = (typeof margin == 'undefined')? cellSize * 4 : margin;
+
+ const size = _this.getModuleCount() * cellSize + margin * 2;
+ const min = margin;
+ const max = size - margin;
+
+ return createDataURL(size, size, function(x, y) {
+ if (min <= x && x < max && min <= y && y < max) {
+ const c = Math.floor( (x - min) / cellSize);
+ const r = Math.floor( (y - min) / cellSize);
+ return _this.isDark(r, c)? 0 : 1;
+ } else {
+ return 1;
+ }
+ } );
+ };
+
+ _this.createImgTag = function(cellSize, margin, alt) {
+
+ cellSize = cellSize || 2;
+ margin = (typeof margin == 'undefined')? cellSize * 4 : margin;
+
+ const size = _this.getModuleCount() * cellSize + margin * 2;
+
+ let img = '';
+ img += '<img';
+ img += '\u0020src="';
+ img += _this.createDataURL(cellSize, margin);
+ img += '"';
+ img += '\u0020width="';
+ img += size;
+ img += '"';
+ img += '\u0020height="';
+ img += size;
+ img += '"';
+ if (alt) {
+ img += '\u0020alt="';
+ img += escapeXml(alt);
+ img += '"';
+ }
+ img += '/>';
+
+ return img;
+ };
+
+ const escapeXml = function(s) {
+ let escaped = '';
+ for (let i = 0; i < s.length; i += 1) {
+ const c = s.charAt(i);
+ switch(c) {
+ case '<': escaped += '&lt;'; break;
+ case '>': escaped += '&gt;'; break;
+ case '&': escaped += '&amp;'; break;
+ case '"': escaped += '&quot;'; break;
+ default : escaped += c; break;
+ }
+ }
+ return escaped;
+ };
+
+ const _createHalfASCII = function(margin) {
+ const cellSize = 1;
+ margin = (typeof margin == 'undefined')? cellSize * 2 : margin;
+
+ const size = _this.getModuleCount() * cellSize + margin * 2;
+ const min = margin;
+ const max = size - margin;
+
+ let y, x, r1, r2, p;
+
+ const blocks = {
+ '██': '█',
+ '█ ': '▀',
+ ' █': '▄',
+ ' ': ' '
+ };
+
+ const blocksLastLineNoMargin = {
+ '██': '▀',
+ '█ ': '▀',
+ ' █': ' ',
+ ' ': ' '
+ };
+
+ let ascii = '';
+ for (y = 0; y < size; y += 2) {
+ r1 = Math.floor((y - min) / cellSize);
+ r2 = Math.floor((y + 1 - min) / cellSize);
+ for (x = 0; x < size; x += 1) {
+ p = '█';
+
+ if (min <= x && x < max && min <= y && y < max && _this.isDark(r1, Math.floor((x - min) / cellSize))) {
+ p = ' ';
+ }
+
+ if (min <= x && x < max && min <= y+1 && y+1 < max && _this.isDark(r2, Math.floor((x - min) / cellSize))) {
+ p += ' ';
+ }
+ else {
+ p += '█';
+ }
+
+ // Output 2 characters per pixel, to create full square. 1 character per pixels gives only half width of square.
+ ascii += (margin < 1 && y+1 >= max) ? blocksLastLineNoMargin[p] : blocks[p];
+ }
+
+ ascii += '\n';
+ }
+
+ if (size % 2 && margin > 0) {
+ return ascii.substring(0, ascii.length - size - 1) + Array(size+1).join('▀');
+ }
+
+ return ascii.substring(0, ascii.length-1);
+ };
+
+ _this.createASCII = function(cellSize, margin) {
+ cellSize = cellSize || 1;
+
+ if (cellSize < 2) {
+ return _createHalfASCII(margin);
+ }
+
+ cellSize -= 1;
+ margin = (typeof margin == 'undefined')? cellSize * 2 : margin;
+
+ const size = _this.getModuleCount() * cellSize + margin * 2;
+ const min = margin;
+ const max = size - margin;
+
+ let y, x, r, p;
+
+ const white = Array(cellSize+1).join('██');
+ const black = Array(cellSize+1).join(' ');
+
+ let ascii = '';
+ let line = '';
+ for (y = 0; y < size; y += 1) {
+ r = Math.floor( (y - min) / cellSize);
+ line = '';
+ for (x = 0; x < size; x += 1) {
+ p = 1;
+
+ if (min <= x && x < max && min <= y && y < max && _this.isDark(r, Math.floor((x - min) / cellSize))) {
+ p = 0;
+ }
+
+ // Output 2 characters per pixel, to create full square. 1 character per pixels gives only half width of square.
+ line += p ? white : black;
+ }
+
+ for (r = 0; r < cellSize; r += 1) {
+ ascii += line + '\n';
+ }
+ }
+
+ return ascii.substring(0, ascii.length-1);
+ };
+
+ _this.renderTo2dContext = function(context, cellSize) {
+ cellSize = cellSize || 2;
+ const length = _this.getModuleCount();
+ for (let row = 0; row < length; row++) {
+ for (let col = 0; col < length; col++) {
+ context.fillStyle = _this.isDark(row, col) ? 'black' : 'white';
+ context.fillRect(col * cellSize, row * cellSize, cellSize, cellSize);
+ }
+ }
+ }
+
+ return _this;
+};
+
+//---------------------------------------------------------------------
+// qrcode.stringToBytes
+//---------------------------------------------------------------------
+
+qrcode.stringToBytes = function(s) {
+ const bytes = [];
+ for (let i = 0; i < s.length; i += 1) {
+ const c = s.charCodeAt(i);
+ bytes.push(c & 0xff);
+ }
+ return bytes;
+};
+
+//---------------------------------------------------------------------
+// qrcode.createStringToBytes
+//---------------------------------------------------------------------
+
+/**
+ * @param unicodeData base64 string of byte array.
+ * [16bit Unicode],[16bit Bytes], ...
+ * @param numChars
+ */
+qrcode.createStringToBytes = function(unicodeData, numChars) {
+
+ // create conversion map.
+
+ const unicodeMap = function() {
+
+ const bin = base64DecodeInputStream(unicodeData);
+ const read = function() {
+ const b = bin.read();
+ if (b == -1) throw 'eof';
+ return b;
+ };
+
+ let count = 0;
+ const unicodeMap = {};
+ while (true) {
+ const b0 = bin.read();
+ if (b0 == -1) break;
+ const b1 = read();
+ const b2 = read();
+ const b3 = read();
+ const k = String.fromCharCode( (b0 << 8) | b1);
+ const v = (b2 << 8) | b3;
+ unicodeMap[k] = v;
+ count += 1;
+ }
+ if (count != numChars) {
+ throw count + ' != ' + numChars;
+ }
+
+ return unicodeMap;
+ }();
+
+ const unknownChar = '?'.charCodeAt(0);
+
+ return function(s) {
+ const bytes = [];
+ for (let i = 0; i < s.length; i += 1) {
+ const c = s.charCodeAt(i);
+ if (c < 128) {
+ bytes.push(c);
+ } else {
+ const b = unicodeMap[s.charAt(i)];
+ if (typeof b == 'number') {
+ if ( (b & 0xff) == b) {
+ // 1byte
+ bytes.push(b);
+ } else {
+ // 2bytes
+ bytes.push(b >>> 8);
+ bytes.push(b & 0xff);
+ }
+ } else {
+ bytes.push(unknownChar);
+ }
+ }
+ }
+ return bytes;
+ };
+};
+
+//---------------------------------------------------------------------
+// QRMode
+//---------------------------------------------------------------------
+
+const QRMode = {
+ MODE_NUMBER : 1 << 0,
+ MODE_ALPHA_NUM : 1 << 1,
+ MODE_8BIT_BYTE : 1 << 2,
+ MODE_KANJI : 1 << 3
+};
+
+//---------------------------------------------------------------------
+// QRErrorCorrectionLevel
+//---------------------------------------------------------------------
+
+const QRErrorCorrectionLevel = {
+ L : 1,
+ M : 0,
+ Q : 3,
+ H : 2
+};
+
+//---------------------------------------------------------------------
+// QRMaskPattern
+//---------------------------------------------------------------------
+
+const QRMaskPattern = {
+ PATTERN000 : 0,
+ PATTERN001 : 1,
+ PATTERN010 : 2,
+ PATTERN011 : 3,
+ PATTERN100 : 4,
+ PATTERN101 : 5,
+ PATTERN110 : 6,
+ PATTERN111 : 7
+};
+
+//---------------------------------------------------------------------
+// QRUtil
+//---------------------------------------------------------------------
+
+const QRUtil = function() {
+
+ const PATTERN_POSITION_TABLE = [
+ [],
+ [6, 18],
+ [6, 22],
+ [6, 26],
+ [6, 30],
+ [6, 34],
+ [6, 22, 38],
+ [6, 24, 42],
+ [6, 26, 46],
+ [6, 28, 50],
+ [6, 30, 54],
+ [6, 32, 58],
+ [6, 34, 62],
+ [6, 26, 46, 66],
+ [6, 26, 48, 70],
+ [6, 26, 50, 74],
+ [6, 30, 54, 78],
+ [6, 30, 56, 82],
+ [6, 30, 58, 86],
+ [6, 34, 62, 90],
+ [6, 28, 50, 72, 94],
+ [6, 26, 50, 74, 98],
+ [6, 30, 54, 78, 102],
+ [6, 28, 54, 80, 106],
+ [6, 32, 58, 84, 110],
+ [6, 30, 58, 86, 114],
+ [6, 34, 62, 90, 118],
+ [6, 26, 50, 74, 98, 122],
+ [6, 30, 54, 78, 102, 126],
+ [6, 26, 52, 78, 104, 130],
+ [6, 30, 56, 82, 108, 134],
+ [6, 34, 60, 86, 112, 138],
+ [6, 30, 58, 86, 114, 142],
+ [6, 34, 62, 90, 118, 146],
+ [6, 30, 54, 78, 102, 126, 150],
+ [6, 24, 50, 76, 102, 128, 154],
+ [6, 28, 54, 80, 106, 132, 158],
+ [6, 32, 58, 84, 110, 136, 162],
+ [6, 26, 54, 82, 110, 138, 166],
+ [6, 30, 58, 86, 114, 142, 170]
+ ];
+ const G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0);
+ const G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0);
+ const G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1);
+
+ const _this = {};
+
+ const getBCHDigit = function(data) {
+ let digit = 0;
+ while (data != 0) {
+ digit += 1;
+ data >>>= 1;
+ }
+ return digit;
+ };
+
+ _this.getBCHTypeInfo = function(data) {
+ let d = data << 10;
+ while (getBCHDigit(d) - getBCHDigit(G15) >= 0) {
+ d ^= (G15 << (getBCHDigit(d) - getBCHDigit(G15) ) );
+ }
+ return ( (data << 10) | d) ^ G15_MASK;
+ };
+
+ _this.getBCHTypeNumber = function(data) {
+ let d = data << 12;
+ while (getBCHDigit(d) - getBCHDigit(G18) >= 0) {
+ d ^= (G18 << (getBCHDigit(d) - getBCHDigit(G18) ) );
+ }
+ return (data << 12) | d;
+ };
+
+ _this.getPatternPosition = function(typeNumber) {
+ return PATTERN_POSITION_TABLE[typeNumber - 1];
+ };
+
+ _this.getMaskFunction = function(maskPattern) {
+
+ switch (maskPattern) {
+
+ case QRMaskPattern.PATTERN000 :
+ return function(i, j) { return (i + j) % 2 == 0; };
+ case QRMaskPattern.PATTERN001 :
+ return function(i, j) { return i % 2 == 0; };
+ case QRMaskPattern.PATTERN010 :
+ return function(i, j) { return j % 3 == 0; };
+ case QRMaskPattern.PATTERN011 :
+ return function(i, j) { return (i + j) % 3 == 0; };
+ case QRMaskPattern.PATTERN100 :
+ return function(i, j) { return (Math.floor(i / 2) + Math.floor(j / 3) ) % 2 == 0; };
+ case QRMaskPattern.PATTERN101 :
+ return function(i, j) { return (i * j) % 2 + (i * j) % 3 == 0; };
+ case QRMaskPattern.PATTERN110 :
+ return function(i, j) { return ( (i * j) % 2 + (i * j) % 3) % 2 == 0; };
+ case QRMaskPattern.PATTERN111 :
+ return function(i, j) { return ( (i * j) % 3 + (i + j) % 2) % 2 == 0; };
+
+ default :
+ throw 'bad maskPattern:' + maskPattern;
+ }
+ };
+
+ _this.getErrorCorrectPolynomial = function(errorCorrectLength) {
+ let a = qrPolynomial([1], 0);
+ for (let i = 0; i < errorCorrectLength; i += 1) {
+ a = a.multiply(qrPolynomial([1, QRMath.gexp(i)], 0) );
+ }
+ return a;
+ };
+
+ _this.getLengthInBits = function(mode, type) {
+
+ if (1 <= type && type < 10) {
+
+ // 1 - 9
+
+ switch(mode) {
+ case QRMode.MODE_NUMBER : return 10;
+ case QRMode.MODE_ALPHA_NUM : return 9;
+ case QRMode.MODE_8BIT_BYTE : return 8;
+ case QRMode.MODE_KANJI : return 8;
+ default :
+ throw 'mode:' + mode;
+ }
+
+ } else if (type < 27) {
+
+ // 10 - 26
+
+ switch(mode) {
+ case QRMode.MODE_NUMBER : return 12;
+ case QRMode.MODE_ALPHA_NUM : return 11;
+ case QRMode.MODE_8BIT_BYTE : return 16;
+ case QRMode.MODE_KANJI : return 10;
+ default :
+ throw 'mode:' + mode;
+ }
+
+ } else if (type < 41) {
+
+ // 27 - 40
+
+ switch(mode) {
+ case QRMode.MODE_NUMBER : return 14;
+ case QRMode.MODE_ALPHA_NUM : return 13;
+ case QRMode.MODE_8BIT_BYTE : return 16;
+ case QRMode.MODE_KANJI : return 12;
+ default :
+ throw 'mode:' + mode;
+ }
+
+ } else {
+ throw 'type:' + type;
+ }
+ };
+
+ _this.getLostPoint = function(qrcode) {
+
+ const moduleCount = qrcode.getModuleCount();
+
+ let lostPoint = 0;
+
+ // LEVEL1
+
+ for (let row = 0; row < moduleCount; row += 1) {
+ for (let col = 0; col < moduleCount; col += 1) {
+
+ let sameCount = 0;
+ const dark = qrcode.isDark(row, col);
+
+ for (let r = -1; r <= 1; r += 1) {
+
+ if (row + r < 0 || moduleCount <= row + r) {
+ continue;
+ }
+
+ for (let c = -1; c <= 1; c += 1) {
+
+ if (col + c < 0 || moduleCount <= col + c) {
+ continue;
+ }
+
+ if (r == 0 && c == 0) {
+ continue;
+ }
+
+ if (dark == qrcode.isDark(row + r, col + c) ) {
+ sameCount += 1;
+ }
+ }
+ }
+
+ if (sameCount > 5) {
+ lostPoint += (3 + sameCount - 5);
+ }
+ }
+ };
+
+ // LEVEL2
+
+ for (let row = 0; row < moduleCount - 1; row += 1) {
+ for (let col = 0; col < moduleCount - 1; col += 1) {
+ let count = 0;
+ if (qrcode.isDark(row, col) ) count += 1;
+ if (qrcode.isDark(row + 1, col) ) count += 1;
+ if (qrcode.isDark(row, col + 1) ) count += 1;
+ if (qrcode.isDark(row + 1, col + 1) ) count += 1;
+ if (count == 0 || count == 4) {
+ lostPoint += 3;
+ }
+ }
+ }
+
+ // LEVEL3
+
+ for (let row = 0; row < moduleCount; row += 1) {
+ for (let col = 0; col < moduleCount - 6; col += 1) {
+ if (qrcode.isDark(row, col)
+ && !qrcode.isDark(row, col + 1)
+ && qrcode.isDark(row, col + 2)
+ && qrcode.isDark(row, col + 3)
+ && qrcode.isDark(row, col + 4)
+ && !qrcode.isDark(row, col + 5)
+ && qrcode.isDark(row, col + 6) ) {
+ lostPoint += 40;
+ }
+ }
+ }
+
+ for (let col = 0; col < moduleCount; col += 1) {
+ for (let row = 0; row < moduleCount - 6; row += 1) {
+ if (qrcode.isDark(row, col)
+ && !qrcode.isDark(row + 1, col)
+ && qrcode.isDark(row + 2, col)
+ && qrcode.isDark(row + 3, col)
+ && qrcode.isDark(row + 4, col)
+ && !qrcode.isDark(row + 5, col)
+ && qrcode.isDark(row + 6, col) ) {
+ lostPoint += 40;
+ }
+ }
+ }
+
+ // LEVEL4
+
+ let darkCount = 0;
+
+ for (let col = 0; col < moduleCount; col += 1) {
+ for (let row = 0; row < moduleCount; row += 1) {
+ if (qrcode.isDark(row, col) ) {
+ darkCount += 1;
+ }
+ }
+ }
+
+ const ratio = Math.abs(100 * darkCount / moduleCount / moduleCount - 50) / 5;
+ lostPoint += ratio * 10;
+
+ return lostPoint;
+ };
+
+ return _this;
+}();
+
+//---------------------------------------------------------------------
+// QRMath
+//---------------------------------------------------------------------
+
+const QRMath = function() {
+
+ const EXP_TABLE = new Array(256);
+ const LOG_TABLE = new Array(256);
+
+ // initialize tables
+ for (let i = 0; i < 8; i += 1) {
+ EXP_TABLE[i] = 1 << i;
+ }
+ for (let i = 8; i < 256; i += 1) {
+ EXP_TABLE[i] = EXP_TABLE[i - 4]
+ ^ EXP_TABLE[i - 5]
+ ^ EXP_TABLE[i - 6]
+ ^ EXP_TABLE[i - 8];
+ }
+ for (let i = 0; i < 255; i += 1) {
+ LOG_TABLE[EXP_TABLE[i] ] = i;
+ }
+
+ const _this = {};
+
+ _this.glog = function(n) {
+
+ if (n < 1) {
+ throw 'glog(' + n + ')';
+ }
+
+ return LOG_TABLE[n];
+ };
+
+ _this.gexp = function(n) {
+
+ while (n < 0) {
+ n += 255;
+ }
+
+ while (n >= 256) {
+ n -= 255;
+ }
+
+ return EXP_TABLE[n];
+ };
+
+ return _this;
+}();
+
+//---------------------------------------------------------------------
+// qrPolynomial
+//---------------------------------------------------------------------
+
+const qrPolynomial = function(num, shift) {
+
+ if (typeof num.length == 'undefined') {
+ throw num.length + '/' + shift;
+ }
+
+ const _num = function() {
+ let offset = 0;
+ while (offset < num.length && num[offset] == 0) {
+ offset += 1;
+ }
+ const _num = new Array(num.length - offset + shift);
+ for (let i = 0; i < num.length - offset; i += 1) {
+ _num[i] = num[i + offset];
+ }
+ return _num;
+ }();
+
+ const _this = {};
+
+ _this.getAt = function(index) {
+ return _num[index];
+ };
+
+ _this.getLength = function() {
+ return _num.length;
+ };
+
+ _this.multiply = function(e) {
+
+ const num = new Array(_this.getLength() + e.getLength() - 1);
+
+ for (let i = 0; i < _this.getLength(); i += 1) {
+ for (let j = 0; j < e.getLength(); j += 1) {
+ num[i + j] ^= QRMath.gexp(QRMath.glog(_this.getAt(i) ) + QRMath.glog(e.getAt(j) ) );
+ }
+ }
+
+ return qrPolynomial(num, 0);
+ };
+
+ _this.mod = function(e) {
+
+ if (_this.getLength() - e.getLength() < 0) {
+ return _this;
+ }
+
+ const ratio = QRMath.glog(_this.getAt(0) ) - QRMath.glog(e.getAt(0) );
+
+ const num = new Array(_this.getLength() );
+ for (let i = 0; i < _this.getLength(); i += 1) {
+ num[i] = _this.getAt(i);
+ }
+
+ for (let i = 0; i < e.getLength(); i += 1) {
+ num[i] ^= QRMath.gexp(QRMath.glog(e.getAt(i) ) + ratio);
+ }
+
+ // recursive call
+ return qrPolynomial(num, 0).mod(e);
+ };
+
+ return _this;
+};
+
+//---------------------------------------------------------------------
+// QRRSBlock
+//---------------------------------------------------------------------
+
+const QRRSBlock = function() {
+
+ const RS_BLOCK_TABLE = [
+
+ // L
+ // M
+ // Q
+ // H
+
+ // 1
+ [1, 26, 19],
+ [1, 26, 16],
+ [1, 26, 13],
+ [1, 26, 9],
+
+ // 2
+ [1, 44, 34],
+ [1, 44, 28],
+ [1, 44, 22],
+ [1, 44, 16],
+
+ // 3
+ [1, 70, 55],
+ [1, 70, 44],
+ [2, 35, 17],
+ [2, 35, 13],
+
+ // 4
+ [1, 100, 80],
+ [2, 50, 32],
+ [2, 50, 24],
+ [4, 25, 9],
+
+ // 5
+ [1, 134, 108],
+ [2, 67, 43],
+ [2, 33, 15, 2, 34, 16],
+ [2, 33, 11, 2, 34, 12],
+
+ // 6
+ [2, 86, 68],
+ [4, 43, 27],
+ [4, 43, 19],
+ [4, 43, 15],
+
+ // 7
+ [2, 98, 78],
+ [4, 49, 31],
+ [2, 32, 14, 4, 33, 15],
+ [4, 39, 13, 1, 40, 14],
+
+ // 8
+ [2, 121, 97],
+ [2, 60, 38, 2, 61, 39],
+ [4, 40, 18, 2, 41, 19],
+ [4, 40, 14, 2, 41, 15],
+
+ // 9
+ [2, 146, 116],
+ [3, 58, 36, 2, 59, 37],
+ [4, 36, 16, 4, 37, 17],
+ [4, 36, 12, 4, 37, 13],
+
+ // 10
+ [2, 86, 68, 2, 87, 69],
+ [4, 69, 43, 1, 70, 44],
+ [6, 43, 19, 2, 44, 20],
+ [6, 43, 15, 2, 44, 16],
+
+ // 11
+ [4, 101, 81],
+ [1, 80, 50, 4, 81, 51],
+ [4, 50, 22, 4, 51, 23],
+ [3, 36, 12, 8, 37, 13],
+
+ // 12
+ [2, 116, 92, 2, 117, 93],
+ [6, 58, 36, 2, 59, 37],
+ [4, 46, 20, 6, 47, 21],
+ [7, 42, 14, 4, 43, 15],
+
+ // 13
+ [4, 133, 107],
+ [8, 59, 37, 1, 60, 38],
+ [8, 44, 20, 4, 45, 21],
+ [12, 33, 11, 4, 34, 12],
+
+ // 14
+ [3, 145, 115, 1, 146, 116],
+ [4, 64, 40, 5, 65, 41],
+ [11, 36, 16, 5, 37, 17],
+ [11, 36, 12, 5, 37, 13],
+
+ // 15
+ [5, 109, 87, 1, 110, 88],
+ [5, 65, 41, 5, 66, 42],
+ [5, 54, 24, 7, 55, 25],
+ [11, 36, 12, 7, 37, 13],
+
+ // 16
+ [5, 122, 98, 1, 123, 99],
+ [7, 73, 45, 3, 74, 46],
+ [15, 43, 19, 2, 44, 20],
+ [3, 45, 15, 13, 46, 16],
+
+ // 17
+ [1, 135, 107, 5, 136, 108],
+ [10, 74, 46, 1, 75, 47],
+ [1, 50, 22, 15, 51, 23],
+ [2, 42, 14, 17, 43, 15],
+
+ // 18
+ [5, 150, 120, 1, 151, 121],
+ [9, 69, 43, 4, 70, 44],
+ [17, 50, 22, 1, 51, 23],
+ [2, 42, 14, 19, 43, 15],
+
+ // 19
+ [3, 141, 113, 4, 142, 114],
+ [3, 70, 44, 11, 71, 45],
+ [17, 47, 21, 4, 48, 22],
+ [9, 39, 13, 16, 40, 14],
+
+ // 20
+ [3, 135, 107, 5, 136, 108],
+ [3, 67, 41, 13, 68, 42],
+ [15, 54, 24, 5, 55, 25],
+ [15, 43, 15, 10, 44, 16],
+
+ // 21
+ [4, 144, 116, 4, 145, 117],
+ [17, 68, 42],
+ [17, 50, 22, 6, 51, 23],
+ [19, 46, 16, 6, 47, 17],
+
+ // 22
+ [2, 139, 111, 7, 140, 112],
+ [17, 74, 46],
+ [7, 54, 24, 16, 55, 25],
+ [34, 37, 13],
+
+ // 23
+ [4, 151, 121, 5, 152, 122],
+ [4, 75, 47, 14, 76, 48],
+ [11, 54, 24, 14, 55, 25],
+ [16, 45, 15, 14, 46, 16],
+
+ // 24
+ [6, 147, 117, 4, 148, 118],
+ [6, 73, 45, 14, 74, 46],
+ [11, 54, 24, 16, 55, 25],
+ [30, 46, 16, 2, 47, 17],
+
+ // 25
+ [8, 132, 106, 4, 133, 107],
+ [8, 75, 47, 13, 76, 48],
+ [7, 54, 24, 22, 55, 25],
+ [22, 45, 15, 13, 46, 16],
+
+ // 26
+ [10, 142, 114, 2, 143, 115],
+ [19, 74, 46, 4, 75, 47],
+ [28, 50, 22, 6, 51, 23],
+ [33, 46, 16, 4, 47, 17],
+
+ // 27
+ [8, 152, 122, 4, 153, 123],
+ [22, 73, 45, 3, 74, 46],
+ [8, 53, 23, 26, 54, 24],
+ [12, 45, 15, 28, 46, 16],
+
+ // 28
+ [3, 147, 117, 10, 148, 118],
+ [3, 73, 45, 23, 74, 46],
+ [4, 54, 24, 31, 55, 25],
+ [11, 45, 15, 31, 46, 16],
+
+ // 29
+ [7, 146, 116, 7, 147, 117],
+ [21, 73, 45, 7, 74, 46],
+ [1, 53, 23, 37, 54, 24],
+ [19, 45, 15, 26, 46, 16],
+
+ // 30
+ [5, 145, 115, 10, 146, 116],
+ [19, 75, 47, 10, 76, 48],
+ [15, 54, 24, 25, 55, 25],
+ [23, 45, 15, 25, 46, 16],
+
+ // 31
+ [13, 145, 115, 3, 146, 116],
+ [2, 74, 46, 29, 75, 47],
+ [42, 54, 24, 1, 55, 25],
+ [23, 45, 15, 28, 46, 16],
+
+ // 32
+ [17, 145, 115],
+ [10, 74, 46, 23, 75, 47],
+ [10, 54, 24, 35, 55, 25],
+ [19, 45, 15, 35, 46, 16],
+
+ // 33
+ [17, 145, 115, 1, 146, 116],
+ [14, 74, 46, 21, 75, 47],
+ [29, 54, 24, 19, 55, 25],
+ [11, 45, 15, 46, 46, 16],
+
+ // 34
+ [13, 145, 115, 6, 146, 116],
+ [14, 74, 46, 23, 75, 47],
+ [44, 54, 24, 7, 55, 25],
+ [59, 46, 16, 1, 47, 17],
+
+ // 35
+ [12, 151, 121, 7, 152, 122],
+ [12, 75, 47, 26, 76, 48],
+ [39, 54, 24, 14, 55, 25],
+ [22, 45, 15, 41, 46, 16],
+
+ // 36
+ [6, 151, 121, 14, 152, 122],
+ [6, 75, 47, 34, 76, 48],
+ [46, 54, 24, 10, 55, 25],
+ [2, 45, 15, 64, 46, 16],
+
+ // 37
+ [17, 152, 122, 4, 153, 123],
+ [29, 74, 46, 14, 75, 47],
+ [49, 54, 24, 10, 55, 25],
+ [24, 45, 15, 46, 46, 16],
+
+ // 38
+ [4, 152, 122, 18, 153, 123],
+ [13, 74, 46, 32, 75, 47],
+ [48, 54, 24, 14, 55, 25],
+ [42, 45, 15, 32, 46, 16],
+
+ // 39
+ [20, 147, 117, 4, 148, 118],
+ [40, 75, 47, 7, 76, 48],
+ [43, 54, 24, 22, 55, 25],
+ [10, 45, 15, 67, 46, 16],
+
+ // 40
+ [19, 148, 118, 6, 149, 119],
+ [18, 75, 47, 31, 76, 48],
+ [34, 54, 24, 34, 55, 25],
+ [20, 45, 15, 61, 46, 16]
+ ];
+
+ const qrRSBlock = function(totalCount, dataCount) {
+ const _this = {};
+ _this.totalCount = totalCount;
+ _this.dataCount = dataCount;
+ return _this;
+ };
+
+ const _this = {};
+
+ const getRsBlockTable = function(typeNumber, errorCorrectionLevel) {
+
+ switch(errorCorrectionLevel) {
+ case QRErrorCorrectionLevel.L :
+ return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 0];
+ case QRErrorCorrectionLevel.M :
+ return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 1];
+ case QRErrorCorrectionLevel.Q :
+ return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 2];
+ case QRErrorCorrectionLevel.H :
+ return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 3];
+ default :
+ return undefined;
+ }
+ };
+
+ _this.getRSBlocks = function(typeNumber, errorCorrectionLevel) {
+
+ const rsBlock = getRsBlockTable(typeNumber, errorCorrectionLevel);
+
+ if (typeof rsBlock == 'undefined') {
+ throw 'bad rs block @ typeNumber:' + typeNumber +
+ '/errorCorrectionLevel:' + errorCorrectionLevel;
+ }
+
+ const length = rsBlock.length / 3;
+
+ const list = [];
+
+ for (let i = 0; i < length; i += 1) {
+
+ const count = rsBlock[i * 3 + 0];
+ const totalCount = rsBlock[i * 3 + 1];
+ const dataCount = rsBlock[i * 3 + 2];
+
+ for (let j = 0; j < count; j += 1) {
+ list.push(qrRSBlock(totalCount, dataCount) );
+ }
+ }
+
+ return list;
+ };
+
+ return _this;
+}();
+
+//---------------------------------------------------------------------
+// qrBitBuffer
+//---------------------------------------------------------------------
+
+const qrBitBuffer = function() {
+
+ const _buffer = [];
+ let _length = 0;
+
+ const _this = {};
+
+ _this.getBuffer = function() {
+ return _buffer;
+ };
+
+ _this.getAt = function(index) {
+ const bufIndex = Math.floor(index / 8);
+ return ( (_buffer[bufIndex] >>> (7 - index % 8) ) & 1) == 1;
+ };
+
+ _this.put = function(num, length) {
+ for (let i = 0; i < length; i += 1) {
+ _this.putBit( ( (num >>> (length - i - 1) ) & 1) == 1);
+ }
+ };
+
+ _this.getLengthInBits = function() {
+ return _length;
+ };
+
+ _this.putBit = function(bit) {
+
+ const bufIndex = Math.floor(_length / 8);
+ if (_buffer.length <= bufIndex) {
+ _buffer.push(0);
+ }
+
+ if (bit) {
+ _buffer[bufIndex] |= (0x80 >>> (_length % 8) );
+ }
+
+ _length += 1;
+ };
+
+ return _this;
+};
+
+//---------------------------------------------------------------------
+// qrNumber
+//---------------------------------------------------------------------
+
+const qrNumber = function(data) {
+
+ const _mode = QRMode.MODE_NUMBER;
+ const _data = data;
+
+ const _this = {};
+
+ _this.getMode = function() {
+ return _mode;
+ };
+
+ _this.getLength = function(buffer) {
+ return _data.length;
+ };
+
+ _this.write = function(buffer) {
+
+ const data = _data;
+
+ let i = 0;
+
+ while (i + 2 < data.length) {
+ buffer.put(strToNum(data.substring(i, i + 3) ), 10);
+ i += 3;
+ }
+
+ if (i < data.length) {
+ if (data.length - i == 1) {
+ buffer.put(strToNum(data.substring(i, i + 1) ), 4);
+ } else if (data.length - i == 2) {
+ buffer.put(strToNum(data.substring(i, i + 2) ), 7);
+ }
+ }
+ };
+
+ const strToNum = function(s) {
+ let num = 0;
+ for (let i = 0; i < s.length; i += 1) {
+ num = num * 10 + chatToNum(s.charAt(i) );
+ }
+ return num;
+ };
+
+ const chatToNum = function(c) {
+ if ('0' <= c && c <= '9') {
+ return c.charCodeAt(0) - '0'.charCodeAt(0);
+ }
+ throw 'illegal char :' + c;
+ };
+
+ return _this;
+};
+
+//---------------------------------------------------------------------
+// qrAlphaNum
+//---------------------------------------------------------------------
+
+const qrAlphaNum = function(data) {
+
+ const _mode = QRMode.MODE_ALPHA_NUM;
+ const _data = data;
+
+ const _this = {};
+
+ _this.getMode = function() {
+ return _mode;
+ };
+
+ _this.getLength = function(buffer) {
+ return _data.length;
+ };
+
+ _this.write = function(buffer) {
+
+ const s = _data;
+
+ let i = 0;
+
+ while (i + 1 < s.length) {
+ buffer.put(
+ getCode(s.charAt(i) ) * 45 +
+ getCode(s.charAt(i + 1) ), 11);
+ i += 2;
+ }
+
+ if (i < s.length) {
+ buffer.put(getCode(s.charAt(i) ), 6);
+ }
+ };
+
+ const getCode = function(c) {
+
+ if ('0' <= c && c <= '9') {
+ return c.charCodeAt(0) - '0'.charCodeAt(0);
+ } else if ('A' <= c && c <= 'Z') {
+ return c.charCodeAt(0) - 'A'.charCodeAt(0) + 10;
+ } else {
+ switch (c) {
+ case '\u0020' : return 36;
+ case '$' : return 37;
+ case '%' : return 38;
+ case '*' : return 39;
+ case '+' : return 40;
+ case '-' : return 41;
+ case '.' : return 42;
+ case '/' : return 43;
+ case ':' : return 44;
+ default :
+ throw 'illegal char :' + c;
+ }
+ }
+ };
+
+ return _this;
+};
+
+//---------------------------------------------------------------------
+// qr8BitByte
+//---------------------------------------------------------------------
+
+const qr8BitByte = function(data) {
+
+ const _mode = QRMode.MODE_8BIT_BYTE;
+ const _data = data;
+ const _bytes = qrcode.stringToBytes(data);
+
+ const _this = {};
+
+ _this.getMode = function() {
+ return _mode;
+ };
+
+ _this.getLength = function(buffer) {
+ return _bytes.length;
+ };
+
+ _this.write = function(buffer) {
+ for (let i = 0; i < _bytes.length; i += 1) {
+ buffer.put(_bytes[i], 8);
+ }
+ };
+
+ return _this;
+};
+
+//---------------------------------------------------------------------
+// qrKanji
+//---------------------------------------------------------------------
+
+const qrKanji = function(data) {
+
+ const _mode = QRMode.MODE_KANJI;
+ const _data = data;
+
+ const stringToBytes = qrcode.stringToBytes;
+ !function(c, code) {
+ // self test for sjis support.
+ const test = stringToBytes(c);
+ if (test.length != 2 || ( (test[0] << 8) | test[1]) != code) {
+ throw 'sjis not supported.';
+ }
+ }('\u53cb', 0x9746);
+
+ const _bytes = stringToBytes(data);
+
+ const _this = {};
+
+ _this.getMode = function() {
+ return _mode;
+ };
+
+ _this.getLength = function(buffer) {
+ return ~~(_bytes.length / 2);
+ };
+
+ _this.write = function(buffer) {
+
+ const data = _bytes;
+
+ let i = 0;
+
+ while (i + 1 < data.length) {
+
+ let c = ( (0xff & data[i]) << 8) | (0xff & data[i + 1]);
+
+ if (0x8140 <= c && c <= 0x9FFC) {
+ c -= 0x8140;
+ } else if (0xE040 <= c && c <= 0xEBBF) {
+ c -= 0xC140;
+ } else {
+ throw 'illegal char at ' + (i + 1) + '/' + c;
+ }
+
+ c = ( (c >>> 8) & 0xff) * 0xC0 + (c & 0xff);
+
+ buffer.put(c, 13);
+
+ i += 2;
+ }
+
+ if (i < data.length) {
+ throw 'illegal char at ' + (i + 1);
+ }
+ };
+
+ return _this;
+};
+
+//=====================================================================
+// GIF Support etc.
+//
+
+//---------------------------------------------------------------------
+// byteArrayOutputStream
+//---------------------------------------------------------------------
+
+const byteArrayOutputStream = function() {
+
+ const _bytes = [];
+
+ const _this = {};
+
+ _this.writeByte = function(b) {
+ _bytes.push(b & 0xff);
+ };
+
+ _this.writeShort = function(i) {
+ _this.writeByte(i);
+ _this.writeByte(i >>> 8);
+ };
+
+ _this.writeBytes = function(b, off, len) {
+ off = off || 0;
+ len = len || b.length;
+ for (let i = 0; i < len; i += 1) {
+ _this.writeByte(b[i + off]);
+ }
+ };
+
+ _this.writeString = function(s) {
+ for (let i = 0; i < s.length; i += 1) {
+ _this.writeByte(s.charCodeAt(i) );
+ }
+ };
+
+ _this.toByteArray = function() {
+ return _bytes;
+ };
+
+ _this.toString = function() {
+ let s = '';
+ s += '[';
+ for (let i = 0; i < _bytes.length; i += 1) {
+ if (i > 0) {
+ s += ',';
+ }
+ s += _bytes[i];
+ }
+ s += ']';
+ return s;
+ };
+
+ return _this;
+};
+
+//---------------------------------------------------------------------
+// base64EncodeOutputStream
+//---------------------------------------------------------------------
+
+const base64EncodeOutputStream = function() {
+
+ let _buffer = 0;
+ let _buflen = 0;
+ let _length = 0;
+ let _base64 = '';
+
+ const _this = {};
+
+ const writeEncoded = function(b) {
+ _base64 += String.fromCharCode(encode(b & 0x3f) );
+ };
+
+ const encode = function(n) {
+ if (n < 0) {
+ throw 'n:' + n;
+ } else if (n < 26) {
+ return 0x41 + n;
+ } else if (n < 52) {
+ return 0x61 + (n - 26);
+ } else if (n < 62) {
+ return 0x30 + (n - 52);
+ } else if (n == 62) {
+ return 0x2b;
+ } else if (n == 63) {
+ return 0x2f;
+ } else {
+ throw 'n:' + n;
+ }
+ };
+
+ _this.writeByte = function(n) {
+
+ _buffer = (_buffer << 8) | (n & 0xff);
+ _buflen += 8;
+ _length += 1;
+
+ while (_buflen >= 6) {
+ writeEncoded(_buffer >>> (_buflen - 6) );
+ _buflen -= 6;
+ }
+ };
+
+ _this.flush = function() {
+
+ if (_buflen > 0) {
+ writeEncoded(_buffer << (6 - _buflen) );
+ _buffer = 0;
+ _buflen = 0;
+ }
+
+ if (_length % 3 != 0) {
+ // padding
+ const padlen = 3 - _length % 3;
+ for (let i = 0; i < padlen; i += 1) {
+ _base64 += '=';
+ }
+ }
+ };
+
+ _this.toString = function() {
+ return _base64;
+ };
+
+ return _this;
+};
+
+//---------------------------------------------------------------------
+// base64DecodeInputStream
+//---------------------------------------------------------------------
+
+const base64DecodeInputStream = function(str) {
+
+ const _str = str;
+ let _pos = 0;
+ let _buffer = 0;
+ let _buflen = 0;
+
+ const _this = {};
+
+ _this.read = function() {
+
+ while (_buflen < 8) {
+
+ if (_pos >= _str.length) {
+ if (_buflen == 0) {
+ return -1;
+ }
+ throw 'unexpected end of file./' + _buflen;
+ }
+
+ const c = _str.charAt(_pos);
+ _pos += 1;
+
+ if (c == '=') {
+ _buflen = 0;
+ return -1;
+ } else if (c.match(/^\s$/) ) {
+ // ignore if whitespace.
+ continue;
+ }
+
+ _buffer = (_buffer << 6) | decode(c.charCodeAt(0) );
+ _buflen += 6;
+ }
+
+ const n = (_buffer >>> (_buflen - 8) ) & 0xff;
+ _buflen -= 8;
+ return n;
+ };
+
+ const decode = function(c) {
+ if (0x41 <= c && c <= 0x5a) {
+ return c - 0x41;
+ } else if (0x61 <= c && c <= 0x7a) {
+ return c - 0x61 + 26;
+ } else if (0x30 <= c && c <= 0x39) {
+ return c - 0x30 + 52;
+ } else if (c == 0x2b) {
+ return 62;
+ } else if (c == 0x2f) {
+ return 63;
+ } else {
+ throw 'c:' + c;
+ }
+ };
+
+ return _this;
+};
+
+//---------------------------------------------------------------------
+// gifImage (B/W)
+//---------------------------------------------------------------------
+
+const gifImage = function(width, height) {
+
+ const _width = width;
+ const _height = height;
+ const _data = new Array(width * height);
+
+ const _this = {};
+
+ _this.setPixel = function(x, y, pixel) {
+ _data[y * _width + x] = pixel;
+ };
+
+ _this.write = function(out) {
+
+ //---------------------------------
+ // GIF Signature
+
+ out.writeString('GIF87a');
+
+ //---------------------------------
+ // Screen Descriptor
+
+ out.writeShort(_width);
+ out.writeShort(_height);
+
+ out.writeByte(0x80); // 2bit
+ out.writeByte(0);
+ out.writeByte(0);
+
+ //---------------------------------
+ // Global Color Map
+
+ // black
+ out.writeByte(0x00);
+ out.writeByte(0x00);
+ out.writeByte(0x00);
+
+ // white
+ out.writeByte(0xff);
+ out.writeByte(0xff);
+ out.writeByte(0xff);
+
+ //---------------------------------
+ // Image Descriptor
+
+ out.writeString(',');
+ out.writeShort(0);
+ out.writeShort(0);
+ out.writeShort(_width);
+ out.writeShort(_height);
+ out.writeByte(0);
+
+ //---------------------------------
+ // Local Color Map
+
+ //---------------------------------
+ // Raster Data
+
+ const lzwMinCodeSize = 2;
+ const raster = getLZWRaster(lzwMinCodeSize);
+
+ out.writeByte(lzwMinCodeSize);
+
+ let offset = 0;
+
+ while (raster.length - offset > 255) {
+ out.writeByte(255);
+ out.writeBytes(raster, offset, 255);
+ offset += 255;
+ }
+
+ out.writeByte(raster.length - offset);
+ out.writeBytes(raster, offset, raster.length - offset);
+ out.writeByte(0x00);
+
+ //---------------------------------
+ // GIF Terminator
+ out.writeString(';');
+ };
+
+ const bitOutputStream = function(out) {
+
+ const _out = out;
+ let _bitLength = 0;
+ let _bitBuffer = 0;
+
+ const _this = {};
+
+ _this.write = function(data, length) {
+
+ if ( (data >>> length) != 0) {
+ throw 'length over';
+ }
+
+ while (_bitLength + length >= 8) {
+ _out.writeByte(0xff & ( (data << _bitLength) | _bitBuffer) );
+ length -= (8 - _bitLength);
+ data >>>= (8 - _bitLength);
+ _bitBuffer = 0;
+ _bitLength = 0;
+ }
+
+ _bitBuffer = (data << _bitLength) | _bitBuffer;
+ _bitLength = _bitLength + length;
+ };
+
+ _this.flush = function() {
+ if (_bitLength > 0) {
+ _out.writeByte(_bitBuffer);
+ }
+ };
+
+ return _this;
+ };
+
+ const getLZWRaster = function(lzwMinCodeSize) {
+
+ const clearCode = 1 << lzwMinCodeSize;
+ const endCode = (1 << lzwMinCodeSize) + 1;
+ let bitLength = lzwMinCodeSize + 1;
+
+ // Setup LZWTable
+ const table = lzwTable();
+
+ for (let i = 0; i < clearCode; i += 1) {
+ table.add(String.fromCharCode(i) );
+ }
+ table.add(String.fromCharCode(clearCode) );
+ table.add(String.fromCharCode(endCode) );
+
+ const byteOut = byteArrayOutputStream();
+ const bitOut = bitOutputStream(byteOut);
+
+ // clear code
+ bitOut.write(clearCode, bitLength);
+
+ let dataIndex = 0;
+
+ let s = String.fromCharCode(_data[dataIndex]);
+ dataIndex += 1;
+
+ while (dataIndex < _data.length) {
+
+ const c = String.fromCharCode(_data[dataIndex]);
+ dataIndex += 1;
+
+ if (table.contains(s + c) ) {
+
+ s = s + c;
+
+ } else {
+
+ bitOut.write(table.indexOf(s), bitLength);
+
+ if (table.size() < 0xfff) {
+
+ if (table.size() == (1 << bitLength) ) {
+ bitLength += 1;
+ }
+
+ table.add(s + c);
+ }
+
+ s = c;
+ }
+ }
+
+ bitOut.write(table.indexOf(s), bitLength);
+
+ // end code
+ bitOut.write(endCode, bitLength);
+
+ bitOut.flush();
+
+ return byteOut.toByteArray();
+ };
+
+ const lzwTable = function() {
+
+ const _map = {};
+ let _size = 0;
+
+ const _this = {};
+
+ _this.add = function(key) {
+ if (_this.contains(key) ) {
+ throw 'dup key:' + key;
+ }
+ _map[key] = _size;
+ _size += 1;
+ };
+
+ _this.size = function() {
+ return _size;
+ };
+
+ _this.indexOf = function(key) {
+ return _map[key];
+ };
+
+ _this.contains = function(key) {
+ return typeof _map[key] != 'undefined';
+ };
+
+ return _this;
+ };
+
+ return _this;
+};
+
+const createDataURL = function(width, height, getPixel) {
+ const gif = gifImage(width, height);
+ for (let y = 0; y < height; y += 1) {
+ for (let x = 0; x < width; x += 1) {
+ gif.setPixel(x, y, getPixel(x, y) );
+ }
+ }
+
+ const b = byteArrayOutputStream();
+ gif.write(b);
+
+ const base64 = base64EncodeOutputStream();
+ const bytes = b.toByteArray();
+ for (let i = 0; i < bytes.length; i += 1) {
+ base64.writeByte(bytes[i]);
+ }
+ base64.flush();
+
+ return 'data:image/gif;base64,' + base64;
+};
+
+export default qrcode;
+
+export const stringToBytes = qrcode.stringToBytes;
diff --git a/assets/README.md b/assets/README.md
new file mode 100644
index 0000000..b9ef5e8
--- /dev/null
+++ b/assets/README.md
@@ -0,0 +1,69 @@
+# SamSUCKS branding assets
+
+Production-ready PNG branding for the SamSUCKS Samsung Tizen TV app. The visual system uses a charcoal television mascot, angry face, coral pirate eye patch, warm cream highlights, and a condensed `SamSUCKS` wordmark.
+
+## Start here
+
+- `tizen/icon-dev-117x117.png` — development/package icon used while testing a TV app in Tizen Studio.
+- `tizen/seller-logo-layer-1920x1080.png` — transparent RGBA logo layer for Samsung Seller Office.
+- `tizen/seller-background-1920x1080.jpg` — separate RGB background for the 1920×1080 Seller Office icon.
+- `tizen/seller-icon-512x423.png` — flattened RGB store icon.
+- `tizen/seller-combined-preview-1920x1080.png` — preview only; shows the logo layer over the background.
+- `splash/splash-1920x1080.png` — recommended full-HD in-app splash artwork.
+- `preview/asset-preview.png` — quick visual index of the set.
+
+## Verified Samsung TV requirements
+
+Checked against Samsung Developer documentation on October 10, 2026:
+
+| Purpose | Samsung requirement | Included file |
+| --- | --- | --- |
+| Tizen Studio testing icon | 117×117 PNG | `tizen/icon-dev-117x117.png` |
+| Seller Office logo layer | 1920×1080, 32-bit PNG (RGBA), under 300 KB | `tizen/seller-logo-layer-1920x1080.png` |
+| Seller Office background | 1920×1080, 24-bit PNG (RGB) or JPG, under 300 KB | `tizen/seller-background-1920x1080.jpg` |
+| Seller Office alternate icon | 512×423, 24-bit PNG (RGB), under 300 KB | `tizen/seller-icon-512x423.png` |
+
+Samsung also recommends designing TV application screens at 1920×1080 in a 16:9 aspect ratio. The 1280×720 splash is supplied as a convenience for FHD testing.
+
+Official references:
+
+- https://developer.samsung.com/smarttv/design/app-icons-and-screenshots.html
+- https://developer.samsung.com/smarttv/design/smart-tv-application-design-qa.html
+- https://developer.samsung.com/smarttv/develop/guides/fundamentals/managing-screen-resolution.html
+- https://developer.samsung.com/smarttv/develop/guides/fundamentals/configuring-tv-applications.html
+
+## Directory map
+
+```text
+SamSUCKS/
+├── brand/ Transparent mascot, wordmark, and horizontal lockups
+├── icons/ General-purpose square RGB app icons
+├── preview/ Contact sheet for visual review
+├── source/ Original generated mascot and normalized transparent master
+├── splash/ 16:9 splash screens and wide banners
+└── tizen/ Samsung/Tizen-specific deliverables
+```
+
+## Using the development icon
+
+Copy `tizen/icon-dev-117x117.png` into the root of the Tizen web project as `icon.png`, then point `config.xml` to it:
+
+```xml
+<icon src="icon.png" />
+```
+
+The 117×117 icon is for development/testing. For a published TV app, upload the separate Seller Office assets listed above.
+
+## Brand usage
+
+- Primary background: `#0B0D12`
+- Raised charcoal: `#181B23`
+- Coral accent: `#FF4C42`
+- Warm cream: `#FFF7E6`
+- Keep the mascot fully visible with breathing room; do not crop the antenna tips or eye patch.
+- Use the light wordmark on dark backgrounds and the dark wordmark on light backgrounds.
+- The splash and banner files are application artwork, not mandatory Seller Office submission images.
+
+## Notes
+
+All PNG dimensions and color modes were validated after export. The Seller Office assets are under Samsung's 300 KB file-size ceiling. The mascot is original project artwork generated for SamSUCKS; the wordmark is rasterized into the PNG files.
diff --git a/assets/brand/lockup-horizontal-dark-1920x640.png b/assets/brand/lockup-horizontal-dark-1920x640.png
new file mode 100644
index 0000000..82a6352
Binary files /dev/null and b/assets/brand/lockup-horizontal-dark-1920x640.png differ
diff --git a/assets/brand/lockup-horizontal-light-1920x640.png b/assets/brand/lockup-horizontal-light-1920x640.png
new file mode 100644
index 0000000..23926cf
Binary files /dev/null and b/assets/brand/lockup-horizontal-light-1920x640.png differ
diff --git a/assets/brand/mascot-transparent-1024.png b/assets/brand/mascot-transparent-1024.png
new file mode 100644
index 0000000..824cf86
Binary files /dev/null and b/assets/brand/mascot-transparent-1024.png differ
diff --git a/assets/brand/mascot-transparent-117.png b/assets/brand/mascot-transparent-117.png
new file mode 100644
index 0000000..98d7029
Binary files /dev/null and b/assets/brand/mascot-transparent-117.png differ
diff --git a/assets/brand/mascot-transparent-256.png b/assets/brand/mascot-transparent-256.png
new file mode 100644
index 0000000..1313cd2
Binary files /dev/null and b/assets/brand/mascot-transparent-256.png differ
diff --git a/assets/brand/mascot-transparent-512.png b/assets/brand/mascot-transparent-512.png
new file mode 100644
index 0000000..a46c21f
Binary files /dev/null and b/assets/brand/mascot-transparent-512.png differ
diff --git a/assets/brand/wordmark-dark-1600x400.png b/assets/brand/wordmark-dark-1600x400.png
new file mode 100644
index 0000000..23d1893
Binary files /dev/null and b/assets/brand/wordmark-dark-1600x400.png differ
diff --git a/assets/brand/wordmark-light-1600x400.png b/assets/brand/wordmark-light-1600x400.png
new file mode 100644
index 0000000..c559bee
Binary files /dev/null and b/assets/brand/wordmark-light-1600x400.png differ
diff --git a/assets/icons/app-icon-1024.png b/assets/icons/app-icon-1024.png
new file mode 100644
index 0000000..dc87256
Binary files /dev/null and b/assets/icons/app-icon-1024.png differ
diff --git a/assets/icons/app-icon-117.png b/assets/icons/app-icon-117.png
new file mode 100644
index 0000000..1605167
Binary files /dev/null and b/assets/icons/app-icon-117.png differ
diff --git a/assets/icons/app-icon-128.png b/assets/icons/app-icon-128.png
new file mode 100644
index 0000000..f444cce
Binary files /dev/null and b/assets/icons/app-icon-128.png differ
diff --git a/assets/icons/app-icon-256.png b/assets/icons/app-icon-256.png
new file mode 100644
index 0000000..3bb862e
Binary files /dev/null and b/assets/icons/app-icon-256.png differ
diff --git a/assets/icons/app-icon-512.png b/assets/icons/app-icon-512.png
new file mode 100644
index 0000000..ec642c6
Binary files /dev/null and b/assets/icons/app-icon-512.png differ
diff --git a/assets/preview/asset-preview.png b/assets/preview/asset-preview.png
new file mode 100644
index 0000000..2fbf498
Binary files /dev/null and b/assets/preview/asset-preview.png differ
diff --git a/assets/readme/frame-trace.png b/assets/readme/frame-trace.png
new file mode 100644
index 0000000..75cbc29
Binary files /dev/null and b/assets/readme/frame-trace.png differ
diff --git a/assets/readme/home.png b/assets/readme/home.png
new file mode 100644
index 0000000..e059440
Binary files /dev/null and b/assets/readme/home.png differ
diff --git a/assets/source/mascot-master-generated.png b/assets/source/mascot-master-generated.png
new file mode 100644
index 0000000..8cc84d4
Binary files /dev/null and b/assets/source/mascot-master-generated.png differ
diff --git a/assets/source/mascot-master-transparent.png b/assets/source/mascot-master-transparent.png
new file mode 100644
index 0000000..92a06cc
Binary files /dev/null and b/assets/source/mascot-master-transparent.png differ
diff --git a/assets/splash/banner-1280x320.png b/assets/splash/banner-1280x320.png
new file mode 100644
index 0000000..8347129
Binary files /dev/null and b/assets/splash/banner-1280x320.png differ
diff --git a/assets/splash/banner-1920x480.png b/assets/splash/banner-1920x480.png
new file mode 100644
index 0000000..f42dc3a
Binary files /dev/null and b/assets/splash/banner-1920x480.png differ
diff --git a/assets/splash/splash-1280x720.png b/assets/splash/splash-1280x720.png
new file mode 100644
index 0000000..5a45f91
Binary files /dev/null and b/assets/splash/splash-1280x720.png differ
diff --git a/assets/splash/splash-1920x1080.png b/assets/splash/splash-1920x1080.png
new file mode 100644
index 0000000..224b3ba
Binary files /dev/null and b/assets/splash/splash-1920x1080.png differ
diff --git a/assets/tizen/icon-dev-117x117.png b/assets/tizen/icon-dev-117x117.png
new file mode 100644
index 0000000..1605167
Binary files /dev/null and b/assets/tizen/icon-dev-117x117.png differ
diff --git a/assets/tizen/seller-background-1920x1080.jpg b/assets/tizen/seller-background-1920x1080.jpg
new file mode 100644
index 0000000..9a9106e
Binary files /dev/null and b/assets/tizen/seller-background-1920x1080.jpg differ
diff --git a/assets/tizen/seller-combined-preview-1920x1080.png b/assets/tizen/seller-combined-preview-1920x1080.png
new file mode 100644
index 0000000..2dc66c6
Binary files /dev/null and b/assets/tizen/seller-combined-preview-1920x1080.png differ
diff --git a/assets/tizen/seller-icon-512x423.png b/assets/tizen/seller-icon-512x423.png
new file mode 100644
index 0000000..b24c303
Binary files /dev/null and b/assets/tizen/seller-icon-512x423.png differ
diff --git a/assets/tizen/seller-logo-layer-1920x1080.png b/assets/tizen/seller-logo-layer-1920x1080.png
new file mode 100644
index 0000000..5d532f6
Binary files /dev/null and b/assets/tizen/seller-logo-layer-1920x1080.png differ
diff --git a/scripts/deploy.sh b/scripts/deploy.sh
new file mode 100755
index 0000000..7d8e7c2
--- /dev/null
+++ b/scripts/deploy.sh
@@ -0,0 +1,64 @@
+#!/usr/bin/env bash
+# Build, sign, install and launch the app on the TV configured in .env.
+# ./scripts/deploy.sh release build
+# ./scripts/deploy.sh --dev dev build: perf overlay, logs + remote control via tools/devserver.mjs
+# ./scripts/deploy.sh --build-only just produce build/app (no TV needed)
+# ./scripts/deploy.sh --no-run install but don't launch
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+[ -f "$ROOT/.env" ] || { echo "No .env yet. Run ./scripts/setup.sh first." >&2; exit 1; }
+set -a; source "$ROOT/.env"; set +a
+
+DEV=0; RUN=1; INSTALL=1
+for arg in "$@"; do
+ case "$arg" in
+ --dev) DEV=1 ;;
+ --no-run) RUN=0 ;;
+ --build-only) INSTALL=0 ;;
+ esac
+done
+
+# --- build: the app is plain JS modules, so building is a copy ---------------
+OUT="$ROOT/build/app"
+rm -rf "$OUT" && mkdir -p "$ROOT/build"
+cp -R "$ROOT/app" "$OUT"
+VERSION=$(sed -n 's/.*widget.* version="\([^"]*\)".*/\1/p' "$ROOT/app/config.xml")
+if [ "$DEV" = 1 ]; then
+ PLEX_URL=""; [ "${DEV_SKIP_LOGIN:-0}" = 1 ] && PLEX_URL="${PLEX_SERVER_URL:-}"
+ cat > "$OUT/js/config.js" <<EOF
+export const DEV = true;
+export const DEV_HOST = '${DEV_HOST:-}';
+export const DEV_PLEX_URL = '$PLEX_URL';
+export const VERSION = '$VERSION';
+EOF
+else
+ rm -rf "$OUT/js/dev"
+ sed -i.bak "s/^export const VERSION = .*/export const VERSION = '$VERSION';/" "$OUT/js/config.js" && rm "$OUT/js/config.js.bak"
+fi
+# Preload every module up front so the TV fetches them in parallel instead of
+# discovering the import graph one level at a time.
+PRELOADS=$(cd "$OUT" && find js -name '*.js' | sort | sed 's|.*|<link rel="modulepreload" href="&">|' | tr '\n' ' ')
+sed -i.bak "s|</head>|$PRELOADS</head>|" "$OUT/index.html" && rm "$OUT/index.html.bak"
+echo "built $([ "$DEV" = 1 ] && echo dev || echo release) $VERSION → build/app"
+[ "$INSTALL" = 1 ] || exit 0
+
+# --- package, sign, install, launch -------------------------------------------
+TIZEN_STUDIO="${TIZEN_STUDIO:-$HOME/tizen-studio}"
+SDB="$TIZEN_STUDIO/tools/sdb"
+TIZEN="$TIZEN_STUDIO/tools/ide/bin/tizen"
+TARGET="$TV_IP:${TV_SDB_PORT:-26101}"
+APP_ID=$(sed -n 's/.*tizen:application id="\([^"]*\)".*/\1/p' "$ROOT/app/config.xml")
+
+rm -f "$ROOT"/build/*.wgt
+"$TIZEN" package -t wgt -s "${TIZEN_SIGN_PROFILE:-samsucks}" -o "$ROOT/build" -- "$OUT" >/dev/null
+# The package is named after the app ("SamSUCKS - Better Plex.wgt"); the installer chokes on spaces.
+WGT="$ROOT/build/samsucks.wgt"
+mv "$(ls "$ROOT"/build/*.wgt | head -1)" "$WGT"
+
+"$SDB" connect "$TARGET" >/dev/null
+DEVICE=$("$SDB" devices | awk -v t="$TARGET" '$1 == t { print $3 }')
+[ -n "$DEVICE" ] || { echo "Can't reach the TV at $TARGET. Is it on, with Developer Mode pointing at this computer?" >&2; exit 1; }
+
+"$TIZEN" install -n "$WGT" -t "$DEVICE" | grep -E 'install completed|Installed|error|fail' || true
+if [ "$RUN" = 1 ]; then "$TIZEN" run -p "$APP_ID" -t "$DEVICE" | tail -1; fi
diff --git a/scripts/make-brand.py b/scripts/make-brand.py
new file mode 100644
index 0000000..d3a9f94
--- /dev/null
+++ b/scripts/make-brand.py
@@ -0,0 +1,18 @@
+"""Trimmed, display-sized brand images for the app header (run with python3 -I)."""
+from pathlib import Path
+from PIL import Image
+
+root = Path(__file__).resolve().parent.parent
+out = root / 'app' / 'img'
+
+
+def trim(src, height, dest):
+ im = Image.open(root / src).convert('RGBA')
+ im = im.crop(im.getchannel('A').getbbox())
+ w = round(im.width * height / im.height)
+ im.resize((w, height), Image.LANCZOS).save(out / dest, optimize=True)
+ print(dest, (w, height))
+
+
+trim('assets/brand/wordmark-light-1600x400.png', 96, 'wordmark.png')
+trim('assets/brand/mascot-transparent-256.png', 168, 'mascot.png')
diff --git a/scripts/setup.sh b/scripts/setup.sh
new file mode 100755
index 0000000..ebba6e1
--- /dev/null
+++ b/scripts/setup.sh
@@ -0,0 +1,141 @@
+#!/usr/bin/env bash
+# One-time setup: installs Samsung's command-line tools, finds your TV, creates a
+# signing certificate and writes .env. Safe to run again; finished steps are skipped.
+# ./scripts/setup.sh
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+ENV="$ROOT/.env"
+TIZEN_VERSION=6.1
+
+bold() { printf '\n\033[1m%s\033[0m\n' "$*"; }
+ok() { printf ' \033[32m✓\033[0m %s\n' "$*"; }
+fail() { printf '\n \033[31m✗ %s\033[0m\n\n' "$*" >&2; exit 1; }
+
+get_env() { [ -f "$ENV" ] && sed -n "s/^$1=//p" "$ENV" | tail -1 || true; }
+set_env() {
+ if grep -q "^$1=" "$ENV"; then KEY="$1" VAL="$2" perl -pi -e 's/^\Q$ENV{KEY}\E=.*/$ENV{KEY}=$ENV{VAL}/' "$ENV"
+ else printf '%s=%s\n' "$1" "$2" >> "$ENV"; fi
+}
+
+# --- 1. Tizen command-line tools ----------------------------------------------
+bold "1/4 Samsung Tizen tools"
+case "$(uname -s)" in
+ Darwin) INSTALLER="web-cli_Tizen_Studio_${TIZEN_VERSION}_macos-64.bin" ;;
+ Linux) INSTALLER="web-cli_Tizen_Studio_${TIZEN_VERSION}_ubuntu-64.bin" ;;
+ *) fail "Only macOS and Linux are supported (on Windows, use WSL)." ;;
+esac
+[ -f "$ENV" ] || cp "$ROOT/.env.example" "$ENV"
+TIZEN_STUDIO="$(get_env TIZEN_STUDIO)"; TIZEN_STUDIO="${TIZEN_STUDIO/\$HOME/$HOME}"; TIZEN_STUDIO="${TIZEN_STUDIO:-$HOME/tizen-studio}"
+TIZEN="$TIZEN_STUDIO/tools/ide/bin/tizen"
+SDB="$TIZEN_STUDIO/tools/sdb"
+PM="$TIZEN_STUDIO/package-manager/package-manager-cli.bin"
+
+if [ -x "$TIZEN" ]; then
+ ok "already installed in $TIZEN_STUDIO"
+else
+ echo " Downloading $INSTALLER (~270 MB)…"
+ TMP="$(mktemp -d)"
+ curl -fL --progress-bar -o "$TMP/$INSTALLER" "https://download.tizen.org/sdk/Installer/tizen-studio_${TIZEN_VERSION}/$INSTALLER"
+ chmod +x "$TMP/$INSTALLER"
+ "$TMP/$INSTALLER" --accept-license "$TIZEN_STUDIO" >/dev/null
+ rm -rf "$TMP"
+ ok "installed in $TIZEN_STUDIO"
+fi
+
+PACKAGES="cert-add-on TV-SAMSUNG-Public-WebAppDevelopment TV-SAMSUNG-Extension-Tools Certificate-Manager"
+INSTALLED=$("$PM" show-pkgs 2>/dev/null | awk '$1 == "i" { print $2 }')
+MISSING=""
+for p in $PACKAGES; do echo "$INSTALLED" | grep -qx "$p" || MISSING="$MISSING $p"; done
+if [ -n "$MISSING" ]; then
+ echo " Installing Samsung TV extensions (a few minutes)…"
+ "$PM" install --accept-license $MISSING >/dev/null
+fi
+ok "Samsung TV extensions"
+
+# --- 2. Find the TV -------------------------------------------------------------
+bold "2/4 Finding your TV"
+if [ "$(uname -s)" = Darwin ]; then
+ IFACE=$(route -n get default 2>/dev/null | awk '/interface:/ { print $2 }')
+ MY_IP=$(ipconfig getifaddr "${IFACE:-en0}" 2>/dev/null || true)
+else
+ MY_IP=$(ip -4 route get 1.1.1.1 2>/dev/null | sed -n 's/.* src \([0-9.]*\).*/\1/p')
+fi
+[ -n "$MY_IP" ] || fail "Couldn't work out this computer's IP address. Are you on Wi-Fi or Ethernet?"
+ok "this computer is $MY_IP"
+
+tv_info() { curl -s -m 2 "http://$1:8001/api/v2/" 2>/dev/null || true; }
+field() { sed -n "s/.*\"$1\" *: *\"\([^\"]*\)\".*/\1/p" <<<"$2" | head -1; }
+
+TV_IP="$(get_env TV_IP)"
+INFO=""
+[ -n "$TV_IP" ] && INFO=$(tv_info "$TV_IP")
+if [ -z "$INFO" ]; then
+ echo " Scanning ${MY_IP%.*}.0/24 for Samsung TVs (make sure the TV is on)…"
+ FOUND=()
+ TMP="$(mktemp -d)"
+ for i in $(seq 1 254); do
+ ( r=$(tv_info "${MY_IP%.*}.$i"); grep -q '"type" *: *"Samsung SmartTV"' <<<"$r" && echo "$r" > "$TMP/${MY_IP%.*}.$i" ) &
+ done
+ wait
+ for f in "$TMP"/*; do [ -e "$f" ] && FOUND+=("$(basename "$f")"); done
+ [ ${#FOUND[@]} -gt 0 ] || { rm -rf "$TMP"; fail "No Samsung TV found on your network. Is it on, and on the same network as this computer?"; }
+ if [ ${#FOUND[@]} -eq 1 ]; then
+ TV_IP="${FOUND[0]}"
+ else
+ echo " Found ${#FOUND[@]} TVs:"
+ for n in "${!FOUND[@]}"; do echo " $((n + 1))) ${FOUND[$n]} $(field name "$(cat "$TMP/${FOUND[$n]}")")"; done
+ read -rp " Which one? [1] " PICK
+ TV_IP="${FOUND[$(( ${PICK:-1} - 1 ))]}"
+ fi
+ INFO=$(cat "$TMP/$TV_IP")
+ rm -rf "$TMP"
+fi
+TV_NAME=$(field name "$INFO"); TV_MODEL=$(field modelName "$INFO")
+ok "$TV_NAME ($TV_MODEL) at $TV_IP"
+set_env TV_IP "$TV_IP"
+set_env TV_MODEL "$TV_MODEL"
+
+DEV_MODE=$(field developerMode "$INFO"); DEV_IP=$(field developerIP "$INFO")
+if [ "$DEV_MODE" != 1 ] || [ "$DEV_IP" != "$MY_IP" ]; then
+ if [ "$DEV_MODE" = 1 ]; then echo " Developer Mode is on, but it points at $DEV_IP instead of this computer."
+ else echo " Developer Mode is off."; fi
+ cat <<EOF
+
+ On the TV:
+ 1. Press Home and open Apps.
+ 2. On the Apps screen, type 1 2 3 4 5 on the remote.
+ (No number keys? Press the 123 button for the on-screen keypad.
+ Nothing happened? Try again a little faster.)
+ 3. Turn Developer mode On, and enter this computer's IP: $MY_IP
+ 4. Choose OK, then restart the TV: hold the Power button until it turns off and back on.
+
+ Then run ./scripts/setup.sh again.
+EOF
+ exit 1
+fi
+ok "Developer Mode is on and points at this computer"
+
+# --- 3. Signing certificate -----------------------------------------------------
+bold "3/4 Signing certificate"
+PROFILE="$(get_env TIZEN_SIGN_PROFILE)"; PROFILE="${PROFILE:-samsucks}"
+set_env TIZEN_SIGN_PROFILE "$PROFILE"
+if "$TIZEN" security-profiles list 2>/dev/null | grep -q "^$PROFILE "; then
+ ok "profile '$PROFILE' already exists"
+else
+ PW="$(get_env TIZEN_CERT_PASSWORD)"
+ [ -n "$PW" ] || PW=$(LC_ALL=C tr -dc 'a-z0-9' < /dev/urandom | head -c 24)
+ set_env TIZEN_CERT_PASSWORD "$PW"
+ "$TIZEN" certificate -a "$PROFILE" -p "$PW" -f "$PROFILE" >/dev/null
+ "$TIZEN" security-profiles add -n "$PROFILE" -a "$HOME/tizen-studio-data/keystore/author/$PROFILE.p12" -p "$PW" >/dev/null
+ ok "created profile '$PROFILE' (password saved in .env)"
+fi
+"$TIZEN" cli-config "profiles.path=$HOME/tizen-studio-data/profile/profiles.xml" >/dev/null
+
+# --- 4. Connect -------------------------------------------------------------------
+bold "4/4 Connecting to the TV"
+"$SDB" connect "$TV_IP:26101" >/dev/null 2>&1 || true
+"$SDB" devices | grep -q "^$TV_IP:26101" || fail "The TV didn't accept the connection. Restart the TV and run this again."
+ok "connected"
+
+printf '\n\033[1mAll set.\033[0m Install SamSUCKS on your TV with:\n\n ./scripts/deploy.sh\n\n'
diff --git a/tools/devserver.mjs b/tools/devserver.mjs
new file mode 100644
index 0000000..4f3b781
--- /dev/null
+++ b/tools/devserver.mjs
@@ -0,0 +1,68 @@
+// Dev companion for builds made with --dev:
+// - receives logs and perf samples from the TV (POST /log) and appends them to build/tv.log
+// - queues commands for the app, which long-polls GET /cmd
+// curl 'localhost:8790/send?keys=down,down,right,enter'
+// curl 'localhost:8790/send?eval=document.title' (result comes back in the log)
+import { createServer } from 'node:http';
+import { appendFileSync, mkdirSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const logFile = path.join(root, 'build', 'tv.log');
+mkdirSync(path.dirname(logFile), { recursive: true });
+const port = Number(process.env.PORT || 8790);
+
+const queue = [];
+let waiting = null;
+
+function deliver() {
+ if (!waiting || !queue.length) return;
+ const res = waiting;
+ waiting = null;
+ clearTimeout(res.timer);
+ res.end(JSON.stringify(queue.splice(0)));
+}
+
+createServer((req, res) => {
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
+ const url = new URL(req.url, 'http://x');
+
+ if (req.method === 'GET' && url.pathname === '/cmd') {
+ if (waiting) { clearTimeout(waiting.timer); waiting.end('[]'); }
+ waiting = res;
+ res.timer = setTimeout(() => { if (waiting === res) { waiting = null; res.end('[]'); } }, 20000);
+ deliver();
+ return;
+ }
+
+ if (req.method === 'GET' && url.pathname === '/send') {
+ const connected = !!waiting;
+ const keys = url.searchParams.get('keys');
+ const gap = Number(url.searchParams.get('gap') || 150);
+ if (keys) queue.push({ keys: keys.split(','), gap });
+ const code = url.searchParams.get('eval');
+ if (code) queue.push({ eval: code });
+ deliver();
+ res.end(connected ? 'sent\n' : 'queued (app not connected yet)\n');
+ return;
+ }
+
+ if (req.method !== 'POST') { res.end('ok'); return; }
+ let body = '';
+ req.on('data', c => { body += c; });
+ req.on('end', () => {
+ try {
+ for (const entry of JSON.parse(body)) {
+ const t = new Date(entry.t).toISOString().slice(11, 23);
+ const line = `${t} ${entry.level.padEnd(5)} ${entry.msg}`;
+ console.log(line);
+ appendFileSync(logFile, line + '\n');
+ }
+ } catch (e) {
+ console.error('bad payload', e.message);
+ }
+ res.end('ok');
+ });
+}).listen(port, '0.0.0.0', () => console.log(`devserver on :${port}, logging to ${path.relative(root, logFile)}`));
diff --git a/tools/remote.mjs b/tools/remote.mjs
new file mode 100644
index 0000000..1b8f1ec
--- /dev/null
+++ b/tools/remote.mjs
@@ -0,0 +1,46 @@
+// Send remote-control keys to a Samsung TV over its LAN websocket API.
+// Usage: node tools/remote.mjs KEY_DOWN KEY_DOWN:10 KEY_ENTER ...
+// KEY:N repeats N times; "wait:ms" pauses. Token is cached in .env as TV_REMOTE_TOKEN.
+import { readFileSync, writeFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import path from 'node:path';
+
+process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; // TV uses a self-signed cert
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const envPath = path.join(root, '.env');
+const env = Object.fromEntries(readFileSync(envPath, 'utf8').split('\n')
+ .filter(l => l.includes('=')).map(l => [l.slice(0, l.indexOf('=')), l.slice(l.indexOf('=') + 1)]));
+
+const name = Buffer.from('samsucks-dev').toString('base64');
+const token = env.TV_REMOTE_TOKEN ? `&token=${env.TV_REMOTE_TOKEN}` : '';
+const url = `wss://${env.TV_IP}:8002/api/v2/channels/samsung.remote.control?name=${name}${token}`;
+const gap = Number(process.env.GAP || 120);
+
+const steps = process.argv.slice(2).flatMap(a => {
+ if (a.startsWith('wait:')) return [{ wait: Number(a.slice(5)) }];
+ const [key, n] = a.split(':');
+ return Array.from({ length: Number(n || 1) }, () => ({ key }));
+});
+
+const sleep = ms => new Promise(r => setTimeout(r, ms));
+const ws = new WebSocket(url);
+ws.onmessage = async ev => {
+ const msg = JSON.parse(ev.data);
+ if (msg.event !== 'ms.channel.connect') return;
+ const t = msg.data && msg.data.token;
+ if (t && t !== env.TV_REMOTE_TOKEN) {
+ const text = readFileSync(envPath, 'utf8').replace(/^TV_REMOTE_TOKEN=.*\n?/m, '');
+ writeFileSync(envPath, text.replace(/\n?$/, '\n') + `TV_REMOTE_TOKEN=${t}\n`);
+ }
+ for (const s of steps) {
+ if (s.wait) { await sleep(s.wait); continue; }
+ ws.send(JSON.stringify({ method: 'ms.remote.control', params: {
+ Cmd: 'Click', DataOfCmd: s.key, Option: 'false', TypeOfRemote: 'SendRemoteKey' } }));
+ await sleep(gap);
+ }
+ await sleep(200);
+ ws.close();
+};
+ws.onerror = e => { console.error('remote error:', e.message || e); process.exit(1); };
+ws.onclose = () => process.exit(0);
+setTimeout(() => { console.error('timed out (accept the prompt on the TV?)'); process.exit(1); }, 30000);
diff --git a/tools/tveval.sh b/tools/tveval.sh
new file mode 100755
index 0000000..8a7a043
--- /dev/null
+++ b/tools/tveval.sh
@@ -0,0 +1,12 @@
+#!/usr/bin/env bash
+# Run JS in the dev build on the TV and print the result.
+# tools/tveval.sh '__bench(["right","right"], 200)' [timeout-seconds]
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+LOG="$ROOT/build/tv.log"
+n=$(wc -l < "$LOG")
+curl -s --get --data-urlencode "eval=$1" "localhost:${PORT:-8790}/send" >/dev/null
+for _ in $(seq 1 $(( ${2:-30} * 4 ))); do
+ sleep 0.25
+ tail -n +$((n + 1)) "$LOG" | grep -m1 -E 'eval (→|failed)' && exit 0
+done
+echo "timeout"; exit 1