Compare commits
18 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6584136cb0 | ||
|
|
2c93afce9e | ||
|
|
b911eefe72 | ||
|
|
76ebe9e40c | ||
|
|
4803323087 | ||
|
|
63b99ef88e | ||
|
|
de504fbcb4 | ||
|
|
69dc6b8fac | ||
|
|
291f4950e8 | ||
|
|
9a65f42f51 | ||
|
|
a3e4fa4ec7 | ||
|
|
897f2ec0c2 | ||
|
|
e24b448c6c | ||
|
|
4e9a1fd038 | ||
|
|
31f59ba4a2 | ||
|
|
b848154942 | ||
|
|
79db6adf45 | ||
|
|
a06e473e85 |
661
LICENSE
Normal file
661
LICENSE
Normal file
@@ -0,0 +1,661 @@
|
|||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are 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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
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 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 work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero 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 Affero 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 Affero 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 Affero 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) 2026 Michael Borak <michael.borak@isuit.ch>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
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 AGPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
129
README.md
129
README.md
@@ -1,95 +1,94 @@
|
|||||||
# Hearbit AI 🦉🎙️
|
# Hearbit AI 🦉🎙️
|
||||||
|
|
||||||
**Hearbit AI** is your professional meeting assistant for macOS. It records both your microphone and system audio (e.g., Teams, Zoom), transcribes it with high precision using Infomaniak's Whisper API, and generates intelligent, structured summaries.
|
**Hearbit AI** is your professional meeting assistant for macOS. It records both your microphone and system audio (e.g., Teams, Zoom, 3CX, Talk), transcribes it with high precision using Infomaniak's Whisper API, and generates intelligent, structured summaries.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
## ✨ Features
|
## ✨ New in v1.2.x
|
||||||
|
|
||||||
* **🎙️ Dual-Channel Recording**: seamlessly capture your voice and meeting audio from apps like Microsoft Teams, Zoom, or Google Meet.
|
### v1.2.3: App Blocking & Selective Recording 🚫🎧
|
||||||
* **📅 Microsoft 365 Integration**:
|
* **🔇 App Blocking (Selective Recording)**: You can now exclude specific applications from being captured by the system audio recording.
|
||||||
* **Upcoming Meetings**: View your daily schedule and join with **one click**.
|
* **🧠 Smart Matching**: Uses prefix-based matching (e.g., `com.apple.Safari`) to reliably block main apps AND their background/helper processes (e.g., "Safari Web Content").
|
||||||
* **Meeting Details**: View full agenda and **invited attendee status** (Accepted/Declined).
|
* **🚀 Quick Select Presets**: Quickly block common background apps like **Spotify, Apple Music, VLC, Safari, or Chrome** with one click.
|
||||||
* **💾 Persistent History**: Automatically saves all transcripts and summaries to disk. Search and review past meetings anytime.
|
* **🔍 Live App List**: Filter any currently running application directly from the new **Apps** tab in Settings.
|
||||||
* **✉️ Email Summaries**: Send professional, formatted HTML summaries (with preview) directly to attendees via your own SMTP server.
|
* **🔄 Robust Auto-Refresh**: The capture filter automatically updates every 5 seconds to account for newly opened browsers or media players.
|
||||||
* **🧠 Powered by Infomaniak AI**:
|
|
||||||
* **Precision Transcription**: Standard-compliant formatting with **second-by-second timestamps**.
|
|
||||||
* **Smart Summaries**: Uses **Smart Templates** to automatically select the best format (Business Protocol vs. 1:1) based on meeting content.
|
|
||||||
* **🔇 Smart VAD**: Automatically filters out silence and stops recording when you stop talking.
|
|
||||||
* **🔒 Privacy-First**: Data is processed securely via your own Infomaniak API keys.
|
|
||||||
|
|
||||||
---
|
### v1.2.0: Native Audio & Auto-Loop 🦉
|
||||||
|
* **🎧 Native System Audio**: No more BlackHole driver needed! Captures Teams, Zoom, 3CX, and Talk audio directly via macOS ScreenCaptureKit.
|
||||||
|
* **🔁 Auto-Loop (Standby Mode)**: Automatically "re-arms" after a call finishes.
|
||||||
|
* **⚡ Smart VAD & Pre-Roll**: 3-second pre-roll and noise filtering.
|
||||||
|
* **🛡️ Empty Audio Guard**: Automatically discards silent recordings.
|
||||||
|
* **💾 Daily Security Backups**: Automatic JSON history backups every 24 hours.
|
||||||
|
|
||||||
## 🚀 Getting Started
|
## 🚀 Key Features
|
||||||
|
|
||||||
### 1. Prerequisites
|
* **🎙️ Dual-Channel Recording**: Seamlessly capture your voice and meeting audio.
|
||||||
* **macOS** (Apple Silicon or Intel).
|
* **📁 Import Audio Files**: Upload existing recordings (MP3, WAV, M4A, etc.).
|
||||||
* **Infomaniak AI Account**: You need an API Key and Product ID from the [Infomaniak Developer Portal](https://manager.infomaniak.com/).
|
* **⏱️ Long Meeting Support**: Handles meetings 2+ hours with automatic chunking.
|
||||||
|
* **📅 Microsoft 365 Integration**: View upcoming meetings and join with one click.
|
||||||
### 2. Installation
|
* **💾 Persistent History**: Automatically saves all transcripts and summaries locally.
|
||||||
1. Download the latest `.dmg` file from the [Releases page](#).
|
* **✉️ Email Summaries**: Send formatted HTML summaries via your own SMTP server.
|
||||||
2. Open the `.dmg` and drag **Hearbit AI** to your Applications folder.
|
* **🎨 White-Labeling**: Upload your custom company logo.
|
||||||
3. Launch the app.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 🎧 Recording System Audio (Teams, Zoom, etc.)
|
|
||||||
|
|
||||||
We've made this easy! Hearbit AI includes a built-in helper to set up your audio devices.
|
|
||||||
|
|
||||||
1. **Open Audio MIDI Setup**: Click the "Open Audio MIDI Setup" button in the recorder view.
|
|
||||||
2. **Create "Hearbit Audio" Device**:
|
|
||||||
* If you don't have a virtual device, click **"🪄 Create Hearbit Audio Device"** in the app (appears in Meeting mode if no device is found).
|
|
||||||
* This will automatically configure a Multi-Output Device so you can record and hear at the same time.
|
|
||||||
3. **Select "Hearbit Audio" in Teams/Zoom**:
|
|
||||||
* In your meeting app settings (Teams/Zoom), set your **Speaker** to **Hearbit Audio**.
|
|
||||||
* In Hearbit AI, select **Hearbit Audio** (or BlackHole) as your input.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🛠️ Usage Guide
|
## 🛠️ Usage Guide
|
||||||
|
|
||||||
1. **Configuration**:
|
### 1. Installation
|
||||||
* Click the **Settings** (gear icon).
|
1. Download the latest `.dmg` file from the [Releases page](#).
|
||||||
* Enter your **Infomaniak API Key** and **Product ID**.
|
2. Open the `.dmg` and drag **Hearbit AI** to your Applications folder.
|
||||||
|
3. **Permission Check**: On first launch, grant "Screen Recording" permission (required for capturing System Audio).
|
||||||
|
|
||||||
2. **Connect M365 (Optional)**:
|
### 2. Configuration
|
||||||
* Copy the **Application (client) ID**.
|
1. Click **Settings** (gear icon).
|
||||||
* Click the **Meetings** tab.
|
2. Enter your **Infomaniak API Key** and **Product ID**.
|
||||||
* Enter your **Client ID** and click "Connect".
|
3. (Optional) Configure **SMTP** for email sending and **Microsoft 365** for calendar integration.
|
||||||
* Proceed with MS login.
|
|
||||||
* View your upcoming meetings.
|
|
||||||
|
|
||||||
3. **Recording**:
|
### 3. Recording a Meeting
|
||||||
* Choose your **Template** (e.g., "Meeting Protocol").
|
1. **Select Mode**: Choose "Meeting" (captures Mic + System) or "Voice Memo" (Mic only).
|
||||||
* Select your **Input Device**.
|
2. **Auto-Start Logic**:
|
||||||
* Click **Start Recording**.
|
- **Meeting Mode**: Triggers only when the call actually starts (system audio detected).
|
||||||
|
- **Voice Memo**: Triggers immediately when you start speaking.
|
||||||
|
3. **Standby**: Click "Standby (Auto-Start)". The app waits silently.
|
||||||
|
4. **Join Call**: Join your Teams/Zoom call.
|
||||||
|
5. **Trigger**: Hearbit starts recording automatically based on the selected mode.
|
||||||
|
6. **Finish**: When the call ends (silence > 25s), Hearbit stops, transcribes, summarizes, and **goes back to Standby** for the next call.
|
||||||
|
|
||||||
4. **Processing**:
|
### 4. Optimal Setup (MS Teams / Zoom / 3CX)
|
||||||
* Click **Stop** when finished.
|
For the best experience without changing any software settings:
|
||||||
* The app will transcribe the audio (with timestamps!) and generate a summary based on your selected template.
|
* **Hearbit App**: Select your **real microphone** (e.g., "MacBook Mic" or Headset).
|
||||||
* You will be automatically taken to the **Transcription** tab to review the results.
|
* **Meeting Software**: Use your standard output (Speakers/Headset).
|
||||||
|
* *How it works*: Hearbit captures your voice via mic and the other side via macOS System Audio Capture automatically.
|
||||||
|
|
||||||
|
*Note: If you choose "Hearbit Audio" (Aggregate Device) in the app, you MUST set your Teams/Zoom/3CX speaker output to "Hearbit Audio" as well.*
|
||||||
|
|
||||||
|
### 5. Customizing Prompts
|
||||||
|
You can create custom AI templates in Settings -> Prompts. Example:
|
||||||
|
* **"Sales Call"**: Focus on budget, timeline, and decision makers.
|
||||||
|
* **"Daily Standup"**: Extract blockers and next steps.
|
||||||
|
* **"General Protocol"**: Standard meeting minutes.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## ❓ Troubleshooting
|
## ❓ Troubleshooting
|
||||||
|
|
||||||
### "Hearbit AI is damaged and can't be opened"
|
### "Hearbit AI is damaged and can't be opened"
|
||||||
This is a standard macOS warning for apps not signed with an Apple Developer Certificate. To fix it:
|
If macOS blocks the app because it's not notarized:
|
||||||
|
|
||||||
1. Open **Terminal**.
|
1. Open **Terminal**.
|
||||||
2. Run the following command:
|
2. Run: `sudo xattr -cr /Applications/Hearbit\ AI.app`
|
||||||
```bash
|
3. Enter your password and try again.
|
||||||
sudo xattr -cr /Applications/Hearbit\ AI.app
|
|
||||||
```
|
### Audio cuts off at the start?
|
||||||
3. Enter your password.
|
v1.2.0 includes a **3-second buffer**. The Meeting mode now uses a more sensitive trigger (0.005 energy) to catch even quiet participants.
|
||||||
4. Open the app again.
|
|
||||||
|
### "Batch processing failed"
|
||||||
|
This means the audio was empty or too short. Check the **Logs** tab for detailed error messages from Infomaniak. The most common cause is selecting the wrong input device or a lack of Screen Recording permissions.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 👨💻 Development
|
## 👨💻 Development
|
||||||
|
|
||||||
Built with **Tauri**, **React**, and **TypeScript**.
|
Built with **Tauri v2**, **React**, and **TypeScript**.
|
||||||
|
|
||||||
### Setup
|
### Setup
|
||||||
```bash
|
```bash
|
||||||
@@ -105,9 +104,9 @@ npm run tauri dev
|
|||||||
```bash
|
```bash
|
||||||
npm run tauri build
|
npm run tauri build
|
||||||
```
|
```
|
||||||
*The build artifact will be located in `src-tauri/target/release/bundle/dmg/*`*
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📄 License
|
## 📄 License
|
||||||
Property of Livtec. All rights reserved.
|
|
||||||
|
This project is licensed under the **GNU Affero General Public License v3.0 (AGPLv3)**. See the [LICENSE](LICENSE) file for details.
|
||||||
|
|||||||
81
RELEASE_NOTES_1.1.0.md
Normal file
81
RELEASE_NOTES_1.1.0.md
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
# Release Notes - Version 1.1.0
|
||||||
|
|
||||||
|
**Release Date**: January 21, 2026
|
||||||
|
|
||||||
|
## 🎉 What's New
|
||||||
|
|
||||||
|
### Import Audio Files Feature
|
||||||
|
|
||||||
|
We've added a powerful new **Import** tab that allows you to upload and process existing audio/video files!
|
||||||
|
|
||||||
|
**Key Features:**
|
||||||
|
- **Drag-and-Drop Upload**: Simply drag your audio files into the app
|
||||||
|
- **8 Format Support**: MP3, MP4, WAV, M4A, FLAC, OGG, AAC, WMA
|
||||||
|
- **Smart Metadata Display**: See file duration, size, and format before processing
|
||||||
|
- **Editable Meeting Titles**: Customize the name (defaults to filename)
|
||||||
|
- **Progress Tracking**: Visual indicators for each stage (Validating → Transcribing → Summarizing)
|
||||||
|
- **Same AI Power**: Uses the same AI templates and Smart Select as live recordings
|
||||||
|
- **Auto-Navigation**: Seamlessly transition to Transcription view when complete
|
||||||
|
|
||||||
|
**Use Cases:**
|
||||||
|
- Process pre-recorded meetings you forgot to record live
|
||||||
|
- Batch process voice memos
|
||||||
|
- Import recordings from other devices
|
||||||
|
- Archive and transcribe old meeting recordings
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📝 Documentation Updates
|
||||||
|
|
||||||
|
### README Enhancements
|
||||||
|
- Added mandatory **BlackHole 2ch Driver** requirement to Prerequisites
|
||||||
|
- Clarified **Teams/Zoom configuration** (Speaker vs. Microphone settings)
|
||||||
|
- Added detailed setup instructions for meeting audio capture
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔧 Technical Improvements
|
||||||
|
|
||||||
|
- Added `get_audio_metadata` Rust command for file metadata extraction
|
||||||
|
- Improved tab navigation with new Import tab
|
||||||
|
- Enhanced error handling for file validation
|
||||||
|
- Code optimizations and cleanup
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📦 Installation
|
||||||
|
|
||||||
|
Download the DMG file:
|
||||||
|
```
|
||||||
|
Hearbit_AI_1.1.0_aarch64.dmg
|
||||||
|
```
|
||||||
|
|
||||||
|
**Location**: `src-tauri/target/release/bundle/dmg/`
|
||||||
|
|
||||||
|
### First-time Installation
|
||||||
|
If you see "Hearbit AI is damaged and can't be opened":
|
||||||
|
```bash
|
||||||
|
sudo xattr -cr /Applications/Hearbit\ AI.app
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🐛 Known Issues
|
||||||
|
|
||||||
|
None reported for this release.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🙏 Credits
|
||||||
|
|
||||||
|
Built with ❤️ by the Livtec team using Tauri, React, and TypeScript.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What's Next?
|
||||||
|
|
||||||
|
Potential future enhancements:
|
||||||
|
- Meeting auto-stop when meeting ends (via M365 API)
|
||||||
|
- Batch file import
|
||||||
|
- Audio preview player
|
||||||
|
- More audio format conversions
|
||||||
22
RELEASE_NOTES_1.2.0.md
Normal file
22
RELEASE_NOTES_1.2.0.md
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
# Release Notes - Hearbit AI v1.2.0
|
||||||
|
|
||||||
|
## 🚀 Neuheiten
|
||||||
|
|
||||||
|
### Native System Audio (ScreenCaptureKit)
|
||||||
|
Wir haben die Audio-Engine komplett erneuert!
|
||||||
|
- **Keine Treiber mehr:** Sie müssen BlackHole nicht mehr installieren.
|
||||||
|
- **Funktioniert überall:** Egal ob Teams, Zoom, Webex, Nextcloud Talk oder 3CX – die App hört jetzt nativ mit.
|
||||||
|
- **Berechtigung:** Die App fragt beim ersten Start nach der "Bildschirmaufnahme"-Berechtigung. Dies ist der moderne Apple-Standard für Audio-Capture.
|
||||||
|
|
||||||
|
### Smart VAD (Intelligente Spracherkennung)
|
||||||
|
- **Ignoriert Musik:** Die App unterscheidet jetzt präzise zwischen menschlicher Sprache und Musik.
|
||||||
|
- **Wartebereich-Filter:** Musik im Teams-Wartebereich wird nicht mehr aufgenommen. Die Aufnahme startet erst, wenn wirklich gesprochen wird.
|
||||||
|
|
||||||
|
### UI Verbesserungen
|
||||||
|
- **Neuer Setup-Flow:** Das komplizierte Audio-Setup wurde entfernt.
|
||||||
|
- **Freie Wahl:** Nutzen Sie jedes Mikrofon, das Sie möchten.
|
||||||
|
|
||||||
|
## 🛠️ Technische Änderungen
|
||||||
|
- Update auf `screencapturekit` Framework (macOS 12.3+ erforderlich).
|
||||||
|
- BlackHole-Abhängigkeit entfernt.
|
||||||
|
- Audio-Mixing direkt in der App.
|
||||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "hearbit-ai",
|
"name": "hearbit-ai",
|
||||||
"version": "0.1.0",
|
"version": "1.2.2",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "hearbit-ai",
|
"name": "hearbit-ai",
|
||||||
"version": "0.1.0",
|
"version": "1.2.2",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@tailwindcss/postcss": "^4.1.18",
|
"@tailwindcss/postcss": "^4.1.18",
|
||||||
"@tauri-apps/api": "^2",
|
"@tauri-apps/api": "^2",
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "hearbit-ai",
|
"name": "hearbit-ai",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "1.1.0",
|
"version": "1.2.3",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
178
src-tauri/Cargo.lock
generated
178
src-tauri/Cargo.lock
generated
@@ -347,6 +347,12 @@ dependencies = [
|
|||||||
"wyz",
|
"wyz",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "block"
|
||||||
|
version = "0.1.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "block-buffer"
|
name = "block-buffer"
|
||||||
version = "0.10.4"
|
version = "0.10.4"
|
||||||
@@ -623,6 +629,35 @@ dependencies = [
|
|||||||
"stacker",
|
"stacker",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cocoa"
|
||||||
|
version = "0.26.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ad36507aeb7e16159dfe68db81ccc27571c3ccd4b76fb2fb72fc59e7a4b1b64c"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.10.0",
|
||||||
|
"block",
|
||||||
|
"cocoa-foundation",
|
||||||
|
"core-foundation 0.10.1",
|
||||||
|
"core-graphics",
|
||||||
|
"foreign-types 0.5.0",
|
||||||
|
"libc",
|
||||||
|
"objc",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cocoa-foundation"
|
||||||
|
version = "0.2.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "81411967c50ee9a1fc11365f8c585f863a22a9697c89239c452292c40ba79b0d"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.10.0",
|
||||||
|
"block",
|
||||||
|
"core-foundation 0.10.1",
|
||||||
|
"core-graphics-types",
|
||||||
|
"objc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "combine"
|
name = "combine"
|
||||||
version = "4.6.7"
|
version = "4.6.7"
|
||||||
@@ -1739,15 +1774,21 @@ checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "hearbit-ai"
|
name = "hearbit-ai"
|
||||||
version = "1.1.0"
|
version = "1.2.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"base64 0.22.1",
|
||||||
"chrono",
|
"chrono",
|
||||||
|
"cocoa",
|
||||||
|
"core-foundation 0.10.1",
|
||||||
"cpal",
|
"cpal",
|
||||||
"hound",
|
"hound",
|
||||||
"lettre",
|
"lettre",
|
||||||
"oauth2",
|
"oauth2",
|
||||||
|
"objc",
|
||||||
"reqwest 0.11.27",
|
"reqwest 0.11.27",
|
||||||
"rubato",
|
"rubato",
|
||||||
|
"screencapturekit",
|
||||||
|
"screencapturekit-sys",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"tauri",
|
"tauri",
|
||||||
@@ -1757,6 +1798,7 @@ dependencies = [
|
|||||||
"tauri-plugin-log",
|
"tauri-plugin-log",
|
||||||
"tauri-plugin-oauth",
|
"tauri-plugin-oauth",
|
||||||
"tauri-plugin-opener",
|
"tauri-plugin-opener",
|
||||||
|
"tauri-plugin-shell",
|
||||||
"tokio",
|
"tokio",
|
||||||
"url",
|
"url",
|
||||||
"voice_activity_detector",
|
"voice_activity_detector",
|
||||||
@@ -2423,6 +2465,15 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "malloc_buf"
|
||||||
|
version = "0.0.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "markup5ever"
|
name = "markup5ever"
|
||||||
version = "0.14.1"
|
version = "0.14.1"
|
||||||
@@ -2715,6 +2766,27 @@ dependencies = [
|
|||||||
"url",
|
"url",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "objc"
|
||||||
|
version = "0.2.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1"
|
||||||
|
dependencies = [
|
||||||
|
"malloc_buf",
|
||||||
|
"objc_exception",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "objc-foundation"
|
||||||
|
version = "0.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1add1b659e36c9607c7aab864a76c7a4c2760cd0cd2e120f3fb8b952c7e22bf9"
|
||||||
|
dependencies = [
|
||||||
|
"block",
|
||||||
|
"objc",
|
||||||
|
"objc_id",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "objc2"
|
name = "objc2"
|
||||||
version = "0.6.3"
|
version = "0.6.3"
|
||||||
@@ -2977,6 +3049,24 @@ dependencies = [
|
|||||||
"objc2-security",
|
"objc2-security",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "objc_exception"
|
||||||
|
version = "0.1.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ad970fb455818ad6cba4c122ad012fae53ae8b4795f86378bce65e4f6bab2ca4"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "objc_id"
|
||||||
|
version = "0.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c92d4ddb4bd7b50d730c215ff871754d0da6b2178849f8a2a2ab69712d0c073b"
|
||||||
|
dependencies = [
|
||||||
|
"objc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "object"
|
name = "object"
|
||||||
version = "0.32.2"
|
version = "0.32.2"
|
||||||
@@ -3089,6 +3179,16 @@ dependencies = [
|
|||||||
"ureq",
|
"ureq",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "os_pipe"
|
||||||
|
version = "1.2.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"windows-sys 0.61.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pango"
|
name = "pango"
|
||||||
version = "0.18.3"
|
version = "0.18.3"
|
||||||
@@ -4102,6 +4202,29 @@ version = "1.2.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "screencapturekit"
|
||||||
|
version = "0.2.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1a5eeeb57ac94960cfe5ff4c402be6585ae4c8d29a2cf41b276048c2e849d64e"
|
||||||
|
dependencies = [
|
||||||
|
"screencapturekit-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "screencapturekit-sys"
|
||||||
|
version = "0.2.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "22411b57f7d49e7fe08025198813ee6fd65e1ee5eff4ebc7880c12c82bde4c60"
|
||||||
|
dependencies = [
|
||||||
|
"block",
|
||||||
|
"dispatch",
|
||||||
|
"objc",
|
||||||
|
"objc-foundation",
|
||||||
|
"objc_id",
|
||||||
|
"once_cell",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sct"
|
name = "sct"
|
||||||
version = "0.7.1"
|
version = "0.7.1"
|
||||||
@@ -4361,12 +4484,44 @@ dependencies = [
|
|||||||
"digest",
|
"digest",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "shared_child"
|
||||||
|
version = "1.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1e362d9935bc50f019969e2f9ecd66786612daae13e8f277be7bfb66e8bed3f7"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"sigchld",
|
||||||
|
"windows-sys 0.60.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "shlex"
|
name = "shlex"
|
||||||
version = "1.3.0"
|
version = "1.3.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
|
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "sigchld"
|
||||||
|
version = "0.2.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "47106eded3c154e70176fc83df9737335c94ce22f821c32d17ed1db1f83badb1"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"os_pipe",
|
||||||
|
"signal-hook",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "signal-hook"
|
||||||
|
version = "0.3.18"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"signal-hook-registry",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "signal-hook-registry"
|
name = "signal-hook-registry"
|
||||||
version = "1.4.8"
|
version = "1.4.8"
|
||||||
@@ -4951,6 +5106,27 @@ dependencies = [
|
|||||||
"zbus",
|
"zbus",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tauri-plugin-shell"
|
||||||
|
version = "2.3.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "39b76f884a3937e04b631ffdc3be506088fa979369d25147361352f2f352e5ed"
|
||||||
|
dependencies = [
|
||||||
|
"encoding_rs",
|
||||||
|
"log",
|
||||||
|
"open",
|
||||||
|
"os_pipe",
|
||||||
|
"regex",
|
||||||
|
"schemars 0.8.22",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"shared_child",
|
||||||
|
"tauri",
|
||||||
|
"tauri-plugin",
|
||||||
|
"thiserror 2.0.18",
|
||||||
|
"tokio",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tauri-runtime"
|
name = "tauri-runtime"
|
||||||
version = "2.9.2"
|
version = "2.9.2"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "hearbit-ai"
|
name = "hearbit-ai"
|
||||||
version = "1.1.0"
|
version = "1.2.1"
|
||||||
description = "A Tauri App"
|
description = "A Tauri App"
|
||||||
authors = ["you"]
|
authors = ["you"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
@@ -18,7 +18,7 @@ crate-type = ["staticlib", "cdylib", "rlib"]
|
|||||||
tauri-build = { version = "2", features = [] }
|
tauri-build = { version = "2", features = [] }
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
tauri = { version = "2", features = [] }
|
tauri = { version = "2", features = ["tray-icon"] }
|
||||||
tauri-plugin-opener = "2"
|
tauri-plugin-opener = "2"
|
||||||
tauri-plugin-dialog = "2"
|
tauri-plugin-dialog = "2"
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
@@ -36,3 +36,10 @@ oauth2 = "4.4"
|
|||||||
url = "2.5"
|
url = "2.5"
|
||||||
lettre = { version = "0.11", features = ["tokio1", "tokio1-native-tls", "builder"] }
|
lettre = { version = "0.11", features = ["tokio1", "tokio1-native-tls", "builder"] }
|
||||||
tauri-plugin-log = "2.0.0"
|
tauri-plugin-log = "2.0.0"
|
||||||
|
tauri-plugin-shell = "2.3.4"
|
||||||
|
base64 = "0.22"
|
||||||
|
screencapturekit = "0.2.0"
|
||||||
|
screencapturekit-sys = "0.2.8"
|
||||||
|
cocoa = "0.26.1"
|
||||||
|
objc = "0.2.7"
|
||||||
|
core-foundation = "0.10.1"
|
||||||
|
|||||||
@@ -110,6 +110,9 @@ func createAggregateDevice() {
|
|||||||
}
|
}
|
||||||
print("Found BlackHole 2ch (ID: \(blackHoleID))")
|
print("Found BlackHole 2ch (ID: \(blackHoleID))")
|
||||||
|
|
||||||
|
// --- PART 1: Hearbit Audio (Input: Mic + BlackHole) ---
|
||||||
|
print("\n--- Creating 'Hearbit Audio' (Input) ---")
|
||||||
|
|
||||||
// Default Input
|
// Default Input
|
||||||
var defaultInputID: AudioObjectID = 0
|
var defaultInputID: AudioObjectID = 0
|
||||||
var size = UInt32(MemoryLayout<AudioObjectID>.size)
|
var size = UInt32(MemoryLayout<AudioObjectID>.size)
|
||||||
@@ -125,19 +128,14 @@ func createAggregateDevice() {
|
|||||||
}
|
}
|
||||||
print("Found Default Input (ID: \(defaultInputID))")
|
print("Found Default Input (ID: \(defaultInputID))")
|
||||||
|
|
||||||
// Check for existing "Hearbit Audio" by UID
|
// Check for existing "Hearbit Audio"
|
||||||
let targetUID = "hearbit_audio_aggregate_v1"
|
let inputUID = "hearbit_audio_aggregate_v1"
|
||||||
if let existingID = findDeviceByUID(targetUID) {
|
if let existingID = findDeviceByUID(inputUID) {
|
||||||
print("Found existing Hearbit Audio device (ID: \(existingID)). Destroying to recreate...")
|
print("Found existing Hearbit Audio (ID: \(existingID)). Destroying...")
|
||||||
if AudioHardwareDestroyAggregateDevice(existingID) != noErr {
|
AudioHardwareDestroyAggregateDevice(existingID)
|
||||||
print("Warning: Failed to destroy existing device.")
|
|
||||||
} else {
|
|
||||||
print("Existing device destroyed.")
|
|
||||||
}
|
|
||||||
Thread.sleep(forTimeInterval: 0.5)
|
Thread.sleep(forTimeInterval: 0.5)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build SubDevice List
|
|
||||||
guard let bhUID = getStringProperty(objectID: blackHoleID, selector: kAudioDevicePropertyDeviceUID) else {
|
guard let bhUID = getStringProperty(objectID: blackHoleID, selector: kAudioDevicePropertyDeviceUID) else {
|
||||||
print("Error: Could not get BlackHole UID.")
|
print("Error: Could not get BlackHole UID.")
|
||||||
exit(1)
|
exit(1)
|
||||||
@@ -147,36 +145,47 @@ func createAggregateDevice() {
|
|||||||
exit(1)
|
exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dedup: if Mic IS BlackHole (user set BlackHole as default), don't duplicate
|
|
||||||
var subDevicesUIDs = [bhUID]
|
var subDevicesUIDs = [bhUID]
|
||||||
if micUID != bhUID {
|
if micUID != bhUID {
|
||||||
subDevicesUIDs.append(micUID)
|
subDevicesUIDs.append(micUID)
|
||||||
}
|
}
|
||||||
|
|
||||||
let subDevicesArray = subDevicesUIDs.map {
|
let subDevicesArray = subDevicesUIDs.map { [kAudioSubDeviceUIDKey: $0] }
|
||||||
[kAudioSubDeviceUIDKey: $0]
|
let inputDesc: [String: Any] = [
|
||||||
}
|
|
||||||
|
|
||||||
let desc: [String: Any] = [
|
|
||||||
kAudioAggregateDeviceNameKey: "Hearbit Audio",
|
kAudioAggregateDeviceNameKey: "Hearbit Audio",
|
||||||
kAudioAggregateDeviceUIDKey: targetUID,
|
kAudioAggregateDeviceUIDKey: inputUID,
|
||||||
kAudioAggregateDeviceIsPrivateKey: Int(0),
|
kAudioAggregateDeviceIsPrivateKey: Int(0),
|
||||||
kAudioAggregateDeviceIsStackedKey: Int(0),
|
kAudioAggregateDeviceIsStackedKey: Int(0),
|
||||||
kAudioAggregateDeviceSubDeviceListKey: subDevicesArray
|
kAudioAggregateDeviceSubDeviceListKey: subDevicesArray
|
||||||
]
|
]
|
||||||
|
|
||||||
print("Creating Aggregate Device with UIDs: \(subDevicesUIDs)")
|
var outInputID: AudioObjectID = 0
|
||||||
|
let errIn = AudioHardwareCreateAggregateDevice(inputDesc as CFDictionary, &outInputID)
|
||||||
var outID: AudioObjectID = 0
|
if errIn == noErr {
|
||||||
let err = AudioHardwareCreateAggregateDevice(desc as CFDictionary, &outID)
|
print("Success! Created 'Hearbit Audio' with ID: \(outInputID)")
|
||||||
|
|
||||||
if err == noErr {
|
|
||||||
print("Success! Created 'Hearbit Audio' with ID: \(outID)")
|
|
||||||
exit(0)
|
|
||||||
} else {
|
} else {
|
||||||
print("Failed to create device. Error code: \(err) (\(err.fourCC))")
|
print("Failed to create 'Hearbit Audio'. Error: \(errIn)")
|
||||||
exit(1)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// --- PART 2: Cleanup Unstable "Hearbit Speakers" ---
|
||||||
|
// The previous "Hearbit Speakers" device caused MS Teams to crash.
|
||||||
|
// We strictly remove it here to restore stability.
|
||||||
|
print("\n--- Cleaning up Unstable Devices ---")
|
||||||
|
let stopOutputUID = "hearbit_speakers_aggregate_v1"
|
||||||
|
if let existingOutID = findDeviceByUID(stopOutputUID) {
|
||||||
|
print("Found unstable 'Hearbit Speakers' (ID: \(existingOutID)). Removing to fix Teams crash...")
|
||||||
|
let errDist = AudioHardwareDestroyAggregateDevice(existingOutID)
|
||||||
|
if errDist == noErr {
|
||||||
|
print("Successfully removed unstable device.")
|
||||||
|
} else {
|
||||||
|
print("Warning: Failed to remove device. Error: \(errDist)")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
print("No unstable 'Hearbit Speakers' found. System is clean.")
|
||||||
|
}
|
||||||
|
|
||||||
|
exit(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
createAggregateDevice()
|
createAggregateDevice()
|
||||||
|
|||||||
65
src-tauri/src/apps.rs
Normal file
65
src-tauri/src/apps.rs
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
use cocoa::base::{id, nil};
|
||||||
|
use cocoa::foundation::{NSArray, NSAutoreleasePool, NSString};
|
||||||
|
use objc::{msg_send, sel, sel_impl};
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
#[derive(Serialize, Debug)]
|
||||||
|
pub struct RunningApp {
|
||||||
|
pub name: String,
|
||||||
|
pub bundle_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_running_applications() -> Vec<RunningApp> {
|
||||||
|
let mut apps = Vec::new();
|
||||||
|
|
||||||
|
unsafe {
|
||||||
|
let pool = NSAutoreleasePool::new(nil);
|
||||||
|
|
||||||
|
// [NSWorkspace sharedWorkspace]
|
||||||
|
let workspace_class = objc::runtime::Class::get("NSWorkspace").unwrap();
|
||||||
|
let shared_workspace: id = msg_send![workspace_class, sharedWorkspace];
|
||||||
|
|
||||||
|
// [sharedWorkspace runningApplications]
|
||||||
|
let running_apps: id = msg_send![shared_workspace, runningApplications];
|
||||||
|
let count: usize = msg_send![running_apps, count];
|
||||||
|
|
||||||
|
for i in 0..count {
|
||||||
|
let app: id = msg_send![running_apps, objectAtIndex: i];
|
||||||
|
|
||||||
|
// Check if it's a regular GUI application
|
||||||
|
// activationPolicy: 0 = regular, 1 = accessory, 2 = prohibited
|
||||||
|
let policy: isize = msg_send![app, activationPolicy];
|
||||||
|
if policy != 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let bundle_id_ns: id = msg_send![app, bundleIdentifier];
|
||||||
|
let name_ns: id = msg_send![app, localizedName];
|
||||||
|
|
||||||
|
if bundle_id_ns != nil && name_ns != nil {
|
||||||
|
let bundle_id = nsstring_to_string(bundle_id_ns);
|
||||||
|
let name = nsstring_to_string(name_ns);
|
||||||
|
|
||||||
|
apps.push(RunningApp { name, bundle_id });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// We don't drain the pool here as it might be handled by Tauri's main loop if we are called frequently,
|
||||||
|
// but for a one-off command it's safer.
|
||||||
|
let _: () = msg_send![pool, release];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort by name for better UI experience
|
||||||
|
apps.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
|
||||||
|
apps
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn nsstring_to_string(ns_string: id) -> String {
|
||||||
|
let char_ptr: *const std::os::raw::c_char = msg_send![ns_string, UTF8String];
|
||||||
|
if char_ptr.is_null() {
|
||||||
|
return String::new();
|
||||||
|
}
|
||||||
|
std::ffi::CStr::from_ptr(char_ptr)
|
||||||
|
.to_string_lossy()
|
||||||
|
.into_owned()
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use tauri::{AppHandle, Emitter};
|
use tauri::{AppHandle, Emitter};
|
||||||
|
use crate::emit_log;
|
||||||
use cpal::Sample;
|
use cpal::Sample;
|
||||||
use hound::WavWriter;
|
use hound::WavWriter;
|
||||||
use rubato::{Resampler, FastFixedIn, PolynomialDegree};
|
use rubato::{Resampler, FastFixedIn, PolynomialDegree};
|
||||||
@@ -11,6 +12,9 @@ pub struct AudioProcessor {
|
|||||||
vad_chunk_size: usize,
|
vad_chunk_size: usize,
|
||||||
vad_buffer: Vec<f32>,
|
vad_buffer: Vec<f32>,
|
||||||
|
|
||||||
|
// Audio Config
|
||||||
|
channel_count: u16,
|
||||||
|
|
||||||
// Resampler
|
// Resampler
|
||||||
resampler: FastFixedIn<f32>,
|
resampler: FastFixedIn<f32>,
|
||||||
resample_input_buffer: Vec<f32>,
|
resample_input_buffer: Vec<f32>,
|
||||||
@@ -21,6 +25,9 @@ pub struct AudioProcessor {
|
|||||||
last_speech_time: u64, // In samples or frames
|
last_speech_time: u64, // In samples or frames
|
||||||
hangover_samples: u64,
|
hangover_samples: u64,
|
||||||
|
|
||||||
|
// Waiting Mode
|
||||||
|
waiting_for_speech: bool,
|
||||||
|
|
||||||
// Ring Buffer (for pre-roll)
|
// Ring Buffer (for pre-roll)
|
||||||
ring_buffer: Vec<f32>,
|
ring_buffer: Vec<f32>,
|
||||||
ring_pos: usize,
|
ring_pos: usize,
|
||||||
@@ -33,16 +40,29 @@ pub struct AudioProcessor {
|
|||||||
// Event Emission
|
// Event Emission
|
||||||
app_handle: Option<AppHandle>,
|
app_handle: Option<AppHandle>,
|
||||||
last_event_time: std::time::Instant,
|
last_event_time: std::time::Instant,
|
||||||
|
|
||||||
|
// System Audio Queue for Mixing
|
||||||
|
pub system_queue: Arc<Mutex<std::collections::VecDeque<f32>>>,
|
||||||
|
|
||||||
|
// Recording Mode (voice or meeting)
|
||||||
|
recording_mode: String,
|
||||||
|
|
||||||
|
// Meeting mode: consecutive speech detection counter.
|
||||||
|
// Prevents false triggers from brief sounds; requires sustained speech.
|
||||||
|
meeting_speech_frames: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AudioProcessor {
|
impl AudioProcessor {
|
||||||
pub fn new(
|
pub fn new(
|
||||||
sample_rate: u32,
|
sample_rate: u32,
|
||||||
|
channel_count: u16,
|
||||||
writer: Arc<Mutex<WavWriter<std::io::BufWriter<std::fs::File>>>>,
|
writer: Arc<Mutex<WavWriter<std::io::BufWriter<std::fs::File>>>>,
|
||||||
app_handle: AppHandle
|
app_handle: AppHandle,
|
||||||
|
wait_for_speech: bool,
|
||||||
|
recording_mode: String,
|
||||||
) -> Result<Self, String> {
|
) -> Result<Self, String> {
|
||||||
let vad_sample_rate = 16000;
|
let vad_sample_rate = 16000;
|
||||||
let vad_chunk_size = 512; // Silero usually likes ~30ms which is 512 at 16k? No 16000 * 0.032 = 512.
|
let vad_chunk_size = 512;
|
||||||
|
|
||||||
// Initialize VAD
|
// Initialize VAD
|
||||||
let vad = VoiceActivityDetector::builder()
|
let vad = VoiceActivityDetector::builder()
|
||||||
@@ -51,8 +71,7 @@ impl AudioProcessor {
|
|||||||
.build()
|
.build()
|
||||||
.map_err(|e| format!("Failed to init VAD: {:?}", e))?;
|
.map_err(|e| format!("Failed to init VAD: {:?}", e))?;
|
||||||
|
|
||||||
// Initialize Resampler (Input Rate -> 16000) using FastFixedIn for speed/simplicity
|
// Initialize Resampler (Input Rate -> 16000)
|
||||||
// new(f_ratio, max_resample_ratio_relative, polyn_deg, chunk_size, channels)
|
|
||||||
let resampler = FastFixedIn::<f32>::new(
|
let resampler = FastFixedIn::<f32>::new(
|
||||||
16000.0 / sample_rate as f64,
|
16000.0 / sample_rate as f64,
|
||||||
1.0,
|
1.0,
|
||||||
@@ -61,20 +80,26 @@ impl AudioProcessor {
|
|||||||
1
|
1
|
||||||
).map_err(|e| format!("Failed to init Resampler: {:?}", e))?;
|
).map_err(|e| format!("Failed to init Resampler: {:?}", e))?;
|
||||||
|
|
||||||
// Pre-roll buffer (e.g. 0.5 seconds of high quality audio)
|
// Pre-roll buffer (3.0 seconds) * Channels (interleaved store)
|
||||||
let ring_curr_seconds = 1.0;
|
let ring_curr_seconds = 3.0;
|
||||||
let ring_size = (sample_rate as f32 * ring_curr_seconds) as usize;
|
// WavWriter writes interleaved, so we store interleaved.
|
||||||
|
let ring_size = (sample_rate as f32 * ring_curr_seconds) as usize * channel_count as usize;
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
vad,
|
vad,
|
||||||
vad_chunk_size,
|
vad_chunk_size,
|
||||||
vad_buffer: Vec::new(),
|
vad_buffer: Vec::new(),
|
||||||
|
channel_count,
|
||||||
resampler,
|
resampler,
|
||||||
resample_input_buffer: Vec::new(),
|
resample_input_buffer: Vec::new(),
|
||||||
resample_output_buffer: Vec::new(),
|
resample_output_buffer: Vec::new(),
|
||||||
is_speech_active: false,
|
is_speech_active: false,
|
||||||
last_speech_time: 0,
|
last_speech_time: 0,
|
||||||
hangover_samples: (sample_rate as f32 * 1.5) as u64, // 1.5s hangover
|
// Hangover counts "processed samples" which are actually frames * channels in current logic?
|
||||||
|
// Actually total_processed_samples usually counts FRAMES in audio terminology, but here we count elements.
|
||||||
|
// Let's stick to elements to match existing logic logic.
|
||||||
|
hangover_samples: (sample_rate as f32 * 1.5 * channel_count as f32) as u64,
|
||||||
|
waiting_for_speech: wait_for_speech,
|
||||||
ring_buffer: vec![0.0; ring_size],
|
ring_buffer: vec![0.0; ring_size],
|
||||||
ring_pos: 0,
|
ring_pos: 0,
|
||||||
ring_size,
|
ring_size,
|
||||||
@@ -83,34 +108,89 @@ impl AudioProcessor {
|
|||||||
total_processed_samples: 0,
|
total_processed_samples: 0,
|
||||||
app_handle: Some(app_handle),
|
app_handle: Some(app_handle),
|
||||||
last_event_time: std::time::Instant::now(),
|
last_event_time: std::time::Instant::now(),
|
||||||
|
system_queue: Arc::new(Mutex::new(std::collections::VecDeque::new())),
|
||||||
|
recording_mode,
|
||||||
|
meeting_speech_frames: 0,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn process(&mut self, data: &[f32]) {
|
pub fn process(&mut self, input_data: &[f32]) {
|
||||||
// 1. Add to Ring Buffer (always, for pre-roll)
|
// MIXING LOGIC:
|
||||||
|
// We have `input_data` (Microphone). We check `system_queue` for System Audio.
|
||||||
|
// System Audio is hardcoded to 2 channels (Stereo) in sc_audio.rs.
|
||||||
|
// Microphone `self.channel_count` can be 1 (Mono) or 2 (Stereo).
|
||||||
|
|
||||||
|
let mic_channels = self.channel_count as usize;
|
||||||
|
let mut mixed_data = input_data.to_vec();
|
||||||
|
let mut max_system_energy = 0.0;
|
||||||
|
|
||||||
|
let gain_mic = 1.0;
|
||||||
|
let gain_sys = 0.8; // Slightly lower system audio to prioritize speaker
|
||||||
|
|
||||||
|
if let Ok(mut queue) = self.system_queue.lock() {
|
||||||
|
let frames = mixed_data.len() / mic_channels;
|
||||||
|
|
||||||
|
for f in 0..frames {
|
||||||
|
// system_queue is always stereo (L, R, L, R...)
|
||||||
|
if let (Some(l), Some(r)) = (queue.pop_front(), queue.pop_front()) {
|
||||||
|
let abs_l = l.abs();
|
||||||
|
let abs_r = r.abs();
|
||||||
|
let current_sys_max = if abs_l > abs_r { abs_l } else { abs_r };
|
||||||
|
if current_sys_max > max_system_energy {
|
||||||
|
max_system_energy = current_sys_max;
|
||||||
|
}
|
||||||
|
|
||||||
|
if mic_channels == 1 {
|
||||||
|
// Mic is Mono: Mix System L+R down to Mono
|
||||||
|
let sys_mono = (l + r) / 2.0;
|
||||||
|
let mixed = (mixed_data[f] * gain_mic) + (sys_mono * gain_sys);
|
||||||
|
mixed_data[f] = mixed.max(-1.0).min(1.0);
|
||||||
|
} else {
|
||||||
|
// Mic is Stereo: Mix L-to-L and R-to-R
|
||||||
|
let f_start = f * 2;
|
||||||
|
let mixed_l = (mixed_data[f_start] * gain_mic) + (l * gain_sys);
|
||||||
|
let mixed_r = (mixed_data[f_start + 1] * gain_mic) + (r * gain_sys);
|
||||||
|
mixed_data[f_start] = mixed_l.max(-1.0).min(1.0);
|
||||||
|
mixed_data[f_start + 1] = mixed_r.max(-1.0).min(1.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let data = &mixed_data;
|
||||||
|
|
||||||
|
// 1. Add to Ring Buffer (Interleaved data - Record EVERYTHING)
|
||||||
for &sample in data {
|
for &sample in data {
|
||||||
self.ring_buffer[self.ring_pos] = sample;
|
self.ring_buffer[self.ring_pos] = sample;
|
||||||
self.ring_pos = (self.ring_pos + 1) % self.ring_size;
|
self.ring_pos = (self.ring_pos + 1) % self.ring_size;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Resample for VAD
|
// 2. Prepare VAD Signal (Mono Mixdown)
|
||||||
// We append new data to input buffer for resampler
|
// FRESH START LOGIC (v0.2.0):
|
||||||
self.resample_input_buffer.extend_from_slice(data);
|
// We expect standard Stereo Input.
|
||||||
|
|
||||||
// Process in chunks compatible with resampler
|
let channels = self.channel_count as usize;
|
||||||
// Actually rubato process_into_buffer needs waves of input.
|
let frame_count = data.len() / channels;
|
||||||
// Simplified: SincFixedIn wants a fixed number of input frames?
|
let mut vad_input_chunk = Vec::with_capacity(frame_count);
|
||||||
// Docs: "retrieve result... input buffer must contain needed number of frames"
|
|
||||||
// SincFixedIn: "input buffer used for resampling... must receive a fixed number of frames"
|
|
||||||
// Wait, SincFixedIn is fixed INPUT size. SincFixedOut is fixed OUTPUT size.
|
|
||||||
// We want to feed whatever we get.
|
|
||||||
// For simplicity, let's use a simpler resampling strategy or accept rubato's constraints.
|
|
||||||
// Rubato SincFixedIn: we must provide `input_frames_next` frames.
|
|
||||||
|
|
||||||
// Let's defer strict resampling and just use decimation if sample rate is multiple?
|
for i in 0..frame_count {
|
||||||
// No, user devices vary.
|
let frame_start = i * channels;
|
||||||
|
|
||||||
|
let mix_sample = if channels >= 2 {
|
||||||
|
// Stereo -> Average L + R
|
||||||
|
(data[frame_start] + data[frame_start + 1]) / 2.0
|
||||||
|
} else {
|
||||||
|
// Mono -> Take as is
|
||||||
|
data[frame_start]
|
||||||
|
};
|
||||||
|
|
||||||
|
vad_input_chunk.push(mix_sample);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// 3. Resample for VAD
|
||||||
|
self.resample_input_buffer.extend_from_slice(&vad_input_chunk);
|
||||||
|
|
||||||
// Handling Resampling properly:
|
|
||||||
let needed = self.resampler.input_frames_next();
|
let needed = self.resampler.input_frames_next();
|
||||||
while self.resample_input_buffer.len() >= needed {
|
while self.resample_input_buffer.len() >= needed {
|
||||||
let chunk: Vec<f32> = self.resample_input_buffer.drain(0..needed).collect();
|
let chunk: Vec<f32> = self.resample_input_buffer.drain(0..needed).collect();
|
||||||
@@ -124,66 +204,130 @@ impl AudioProcessor {
|
|||||||
self.vad_buffer.extend_from_slice(&waves_out[0][0..out_len]);
|
self.vad_buffer.extend_from_slice(&waves_out[0][0..out_len]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Update output buffer usage... logic is tricky with drain.
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Process VAD
|
// 4. Process VAD
|
||||||
while self.vad_buffer.len() >= self.vad_chunk_size {
|
while self.vad_buffer.len() >= self.vad_chunk_size {
|
||||||
let vad_chunk: Vec<f32> = self.vad_buffer.drain(0..self.vad_chunk_size).collect();
|
let vad_chunk: Vec<f32> = self.vad_buffer.drain(0..self.vad_chunk_size).collect();
|
||||||
// Run Detection
|
// Run Detection
|
||||||
// Run Detection
|
|
||||||
let probability = self.vad.predict(vad_chunk.clone());
|
let probability = self.vad.predict(vad_chunk.clone());
|
||||||
|
|
||||||
// Calculate RMS for this chunk to use as fallback/hybrid detection
|
let system_is_active = max_system_energy > 0.005; // Lowered to match trigger
|
||||||
let sq_sum: f32 = vad_chunk.iter().map(|x| x * x).sum();
|
let is_speech = probability > 0.9;
|
||||||
let rms = (sq_sum / vad_chunk.len() as f32).sqrt();
|
|
||||||
|
|
||||||
// Hybrid VAD: Probability > 0.4 OR RMS > 0.005 (approx -46dB)
|
if is_speech || system_is_active {
|
||||||
let is_speech = probability > 0.4 || rms > 0.005;
|
|
||||||
|
|
||||||
if is_speech {
|
|
||||||
self.is_speech_active = true;
|
self.is_speech_active = true;
|
||||||
self.last_speech_time = self.total_processed_samples;
|
self.last_speech_time = self.total_processed_samples;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Emit VAD event periodically (every 500ms)
|
// Emit VAD event periodically
|
||||||
if self.last_event_time.elapsed().as_millis() > 500 {
|
if self.last_event_time.elapsed().as_millis() > 500 {
|
||||||
// Calculate simple RMS of the current chunk for debugging
|
|
||||||
let sq_sum: f32 = vad_chunk.iter().map(|x| x * x).sum();
|
|
||||||
let rms = (sq_sum / vad_chunk.len() as f32).sqrt();
|
|
||||||
|
|
||||||
// Print debug info to stdout (viewable in terminal)
|
|
||||||
println!("VAD Debug: Prob={:.4}, RMS={:.6}, Speech={}", probability, rms, is_speech);
|
|
||||||
|
|
||||||
if let Some(app) = &self.app_handle {
|
if let Some(app) = &self.app_handle {
|
||||||
// Just sending probability is enough for now
|
#[derive(Clone, serde::Serialize)]
|
||||||
#[derive(serde::Serialize, Clone)]
|
|
||||||
struct VadEvent {
|
struct VadEvent {
|
||||||
probability: f32,
|
|
||||||
is_speech: bool,
|
is_speech: bool,
|
||||||
|
probability: f32,
|
||||||
}
|
}
|
||||||
let _ = app.emit("vad-event", VadEvent { probability, is_speech });
|
let _ = app.emit("vad-event", VadEvent {
|
||||||
|
probability,
|
||||||
|
is_speech: self.is_speech_active,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
self.last_event_time = std::time::Instant::now();
|
self.last_event_time = std::time::Instant::now();
|
||||||
|
self.is_speech_active = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// 4. Update Hangover and Check Write condition
|
// 4. Update Hangover and Check Write condition
|
||||||
|
if self.waiting_for_speech {
|
||||||
|
// TRIGGER CONDITION:
|
||||||
|
// 1. VAD says speech (Someone is talking)
|
||||||
|
// 2. AND System Audio has energy (Meaning audio is coming from the PC, i.e., Call started)
|
||||||
|
// Threshold 0.01 is roughly -40dB, should cover ringtones/speech easily but ignore silence/hiss.
|
||||||
|
|
||||||
|
let system_active = max_system_energy > 0.005;
|
||||||
|
|
||||||
|
// Periodically log energy to help debug why meeting mode might not start
|
||||||
|
if self.last_event_time.elapsed().as_millis() > 2000 && self.recording_mode == "meeting" {
|
||||||
|
if let Some(app) = &self.app_handle {
|
||||||
|
emit_log(app, "DEBUG", &format!(
|
||||||
|
"Waiting... SysEnergy: {:.4} (thr: 0.005), Speech: {}, SpeechFrames: {}/90 | SysQ empty: {}",
|
||||||
|
max_system_energy, self.is_speech_active, self.meeting_speech_frames,
|
||||||
|
if let Ok(q) = self.system_queue.lock() { q.is_empty() } else { true }
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MODE-SPECIFIC TRIGGER LOGIC:
|
||||||
|
// "voice" -> Trigger if user speaks (VAD) - immediate
|
||||||
|
// "meeting" -> Primary: system audio energy above threshold (immediate)
|
||||||
|
// Fallback: sustained speech for ~3 seconds (catches apps like
|
||||||
|
// Nextcloud Talk where ScreenCaptureKit may not capture audio).
|
||||||
|
// Brief speech resets the counter to prevent false triggers.
|
||||||
|
//
|
||||||
|
// The sustained speech counter uses VAD chunks (~32ms each at 16kHz/512).
|
||||||
|
// ~90 consecutive chunks ≈ ~3 seconds of sustained speech.
|
||||||
|
const MEETING_SPEECH_THRESHOLD: u32 = 90;
|
||||||
|
|
||||||
|
if self.recording_mode == "meeting" {
|
||||||
|
if self.is_speech_active || system_active {
|
||||||
|
self.meeting_speech_frames += 1;
|
||||||
|
} else {
|
||||||
|
// Reset if silence detected - prevents brief sounds from accumulating
|
||||||
|
self.meeting_speech_frames = self.meeting_speech_frames.saturating_sub(3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let trigger = if self.recording_mode == "voice" {
|
||||||
|
self.is_speech_active
|
||||||
|
} else {
|
||||||
|
// Immediate trigger on system audio energy
|
||||||
|
// OR sustained speech (~3s) as fallback for Electron/WebRTC apps
|
||||||
|
system_active || self.meeting_speech_frames >= MEETING_SPEECH_THRESHOLD
|
||||||
|
};
|
||||||
|
|
||||||
|
if trigger {
|
||||||
|
let reason = if system_active { "SystemAudio" } else { "SustainedSpeech" };
|
||||||
|
println!("Auto-Start: Trigger! (Mode: {}, Reason: {}, SysEnergy: {:.4}, SpeechFrames: {})", self.recording_mode, reason, max_system_energy, self.meeting_speech_frames);
|
||||||
|
self.waiting_for_speech = false;
|
||||||
|
|
||||||
|
// Flush Ring Buffer (Orderly: from ring_pos to end, then 0 to ring_pos)
|
||||||
|
let mut guard = self.writer.lock().unwrap();
|
||||||
|
let amplitude = i16::MAX as f32;
|
||||||
|
|
||||||
|
// Part 1: ring_pos to end
|
||||||
|
for i in self.ring_pos..self.ring_size {
|
||||||
|
let sample = self.ring_buffer[i];
|
||||||
|
guard.write_sample((sample * amplitude) as i16).ok();
|
||||||
|
}
|
||||||
|
// Part 2: 0 to ring_pos
|
||||||
|
for i in 0..self.ring_pos {
|
||||||
|
let sample = self.ring_buffer[i];
|
||||||
|
guard.write_sample((sample * amplitude) as i16).ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Emit event to notify frontend that "real" recording started
|
||||||
|
if let Some(app) = &self.app_handle {
|
||||||
|
let _ = app.emit("auto-recording-triggered", ());
|
||||||
|
}
|
||||||
|
|
||||||
|
} else {
|
||||||
|
// Still waiting, do not write to file.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Standard Recording Logic (Active or Hangover)
|
||||||
let time_since_speech = self.total_processed_samples.saturating_sub(self.last_speech_time);
|
let time_since_speech = self.total_processed_samples.saturating_sub(self.last_speech_time);
|
||||||
|
|
||||||
if self.is_speech_active || time_since_speech < self.hangover_samples {
|
// We write to file if:
|
||||||
// We are recording!
|
// 1. VAD thinks someone is speaking (Mic or System)
|
||||||
// Check if we just started (transition)
|
// 2. OR System audio energy is currently above threshold (Ensures calls are captured)
|
||||||
// Ideally we dump the ring buffer here if we just switched state.
|
// 3. OR we are within the hangover period
|
||||||
// Implementing perfect ring buffer dump is complex (need to track state changes better).
|
let system_is_active = max_system_energy > 0.005;
|
||||||
// MVP: Just Write Current Data if in state.
|
|
||||||
|
|
||||||
// Improvement: If we are in hangover, we just write.
|
|
||||||
// If we just detected speech (was not speech?), dump ring buffer?
|
|
||||||
// We'd need to know if we 'wrote' the ring buffer already.
|
|
||||||
|
|
||||||
// Simple Logic: just write all incoming data if (Now - LastSpeech < Hangover)
|
|
||||||
|
|
||||||
|
if self.is_speech_active || system_is_active || time_since_speech < self.hangover_samples {
|
||||||
let mut guard = self.writer.lock().unwrap();
|
let mut guard = self.writer.lock().unwrap();
|
||||||
for &sample in data {
|
for &sample in data {
|
||||||
let amplitude = i16::MAX as f32;
|
let amplitude = i16::MAX as f32;
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
984
src-tauri/src/lib.rs.bak
Normal file
984
src-tauri/src/lib.rs.bak
Normal file
@@ -0,0 +1,984 @@
|
|||||||
|
use tauri::{
|
||||||
|
AppHandle, Manager, State, Emitter,
|
||||||
|
menu::{Menu, MenuItem},
|
||||||
|
tray::{TrayIconBuilder, TrayIconEvent},
|
||||||
|
WindowEvent
|
||||||
|
};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::process::Command;
|
||||||
|
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
|
||||||
|
use std::time::Duration;
|
||||||
|
use tokio::time::sleep;
|
||||||
|
use base64::Engine;
|
||||||
|
|
||||||
|
mod audio_processor;
|
||||||
|
use audio_processor::AudioProcessor;
|
||||||
|
mod auth;
|
||||||
|
mod email;
|
||||||
|
mod sc_audio;
|
||||||
|
|
||||||
|
// State to hold the active recording stream
|
||||||
|
struct AppState {
|
||||||
|
recording_stream: Mutex<Option<cpal::Stream>>,
|
||||||
|
recording_file_path: Mutex<Option<String>>,
|
||||||
|
system_capture: Mutex<Option<sc_audio::SystemAudioCapture>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
struct AudioDevice {
|
||||||
|
id: String,
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, Clone)]
|
||||||
|
struct LogEvent {
|
||||||
|
level: String,
|
||||||
|
message: String,
|
||||||
|
timestamp: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn emit_log(app: &AppHandle, level: &str, message: &str) {
|
||||||
|
let log = LogEvent {
|
||||||
|
level: level.to_string(),
|
||||||
|
message: message.to_string(),
|
||||||
|
timestamp: chrono::Local::now().format("%H:%M:%S").to_string(),
|
||||||
|
};
|
||||||
|
let _ = app.emit("log-event", log);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn greet(name: &str) -> String {
|
||||||
|
format!("Hello, {}! You've been greeted from Rust!", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn get_input_devices() -> Result<Vec<AudioDevice>, String> {
|
||||||
|
let host = cpal::default_host();
|
||||||
|
let devices = host.input_devices().map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
let mut result = Vec::new();
|
||||||
|
for device in devices {
|
||||||
|
#[allow(deprecated)]
|
||||||
|
if let Ok(name) = device.name() {
|
||||||
|
// macOS often produces weird names, but let's just use what we get
|
||||||
|
result.push(AudioDevice {
|
||||||
|
id: name.clone(), // Using name as ID for simplicity in this MVP
|
||||||
|
name,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
async fn start_recording(app: AppHandle, state: State<'_, AppState>, device_id: String, save_path: Option<String>, custom_filename: Option<String>, wait_for_speech: Option<bool>, mode: String) -> Result<(), String> {
|
||||||
|
emit_log(&app, "INFO", &format!("Starting recording [Mode: {}] on device: {}", mode, device_id));
|
||||||
|
let host = cpal::default_host();
|
||||||
|
|
||||||
|
// Find device by name (using name as ID)
|
||||||
|
#[allow(deprecated)]
|
||||||
|
let device = host.input_devices()
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.find(|d| d.name().map(|n| n == device_id).unwrap_or(false))
|
||||||
|
.or_else(|| host.default_input_device())
|
||||||
|
.ok_or("No input device found")?;
|
||||||
|
|
||||||
|
// Select the configuration with the MAXIMUM number of channels
|
||||||
|
// This is crucial for "Hearbit Audio" (Aggregate) which lists 3 channels but might default to 2.
|
||||||
|
// Select Audio Configuration
|
||||||
|
// We prioritize 48kHz because System Audio (ScreenCaptureKit) acts best at 48k.
|
||||||
|
let supported_configs: Vec<_> = device.supported_input_configs().map_err(|e| e.to_string())?.collect();
|
||||||
|
|
||||||
|
// Try to find 48kHz specifically
|
||||||
|
// Note: cpal::SampleRate is likely a type alias for u32 here, so we pass 48000 directly.
|
||||||
|
let config = supported_configs.iter()
|
||||||
|
.find(|c| c.min_sample_rate() <= 48000 && c.max_sample_rate() >= 48000)
|
||||||
|
.map(|c| c.with_sample_rate(48000))
|
||||||
|
.or_else(|| {
|
||||||
|
// Fallback: Max sample rate
|
||||||
|
supported_configs.iter()
|
||||||
|
.max_by_key(|c| c.channels())
|
||||||
|
.map(|c| c.with_max_sample_rate())
|
||||||
|
})
|
||||||
|
.ok_or("No supported input configurations found")?;
|
||||||
|
|
||||||
|
emit_log(&app, "INFO", &format!("Selected Audio Config: {} Channels, {} Hz", config.channels(), config.sample_rate()));
|
||||||
|
|
||||||
|
let spec = hound::WavSpec {
|
||||||
|
channels: config.channels(),
|
||||||
|
sample_rate: config.sample_rate(),
|
||||||
|
bits_per_sample: 16,
|
||||||
|
sample_format: hound::SampleFormat::Int,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Determine file path: User provided or Temp
|
||||||
|
let filename = if let Some(name) = custom_filename {
|
||||||
|
// Sanitize filename
|
||||||
|
let safe_name: String = name.chars().map(|x| if x.is_alphanumeric() || x == ' ' || x == '-' || x == '_' { x } else { '_' }).collect();
|
||||||
|
format!("{}.wav", safe_name)
|
||||||
|
} else {
|
||||||
|
format!("recording_{}.wav", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs())
|
||||||
|
};
|
||||||
|
|
||||||
|
let file_path = if let Some(path) = save_path {
|
||||||
|
if path.trim().is_empty() {
|
||||||
|
std::env::temp_dir().join(&filename)
|
||||||
|
} else {
|
||||||
|
std::path::PathBuf::from(path).join(&filename)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
std::env::temp_dir().join(&filename)
|
||||||
|
};
|
||||||
|
|
||||||
|
let file_path_str = file_path.to_string_lossy().to_string();
|
||||||
|
emit_log(&app, "INFO", &format!("Saving recording to: {}", file_path_str));
|
||||||
|
|
||||||
|
let writer = hound::WavWriter::create(&file_path, spec).map_err(|e| e.to_string())?;
|
||||||
|
let writer = Arc::new(Mutex::new(writer));
|
||||||
|
let writer_clone = writer.clone();
|
||||||
|
|
||||||
|
// Initialize AudioProcessor (VAD)
|
||||||
|
// We pass the writer to it.
|
||||||
|
let should_wait = wait_for_speech.unwrap_or(false);
|
||||||
|
if should_wait {
|
||||||
|
emit_log(&app, "INFO", &format!("Recording started in WAITING mode (Trigger: {}).", if mode == "voice" { "Speech" } else { "System Audio" }));
|
||||||
|
}
|
||||||
|
|
||||||
|
let processor = AudioProcessor::new(config.sample_rate(), config.channels(), writer.clone(), app.clone(), should_wait, mode)
|
||||||
|
.map_err(|e| format!("Failed to create AudioProcessor: {}", e))?;
|
||||||
|
|
||||||
|
// Wrap processor in Arc<Mutex> so we can share/move it into callback
|
||||||
|
// Actually, cpal callback takes ownership of its closure state usually if 'move'.
|
||||||
|
// Since stream is on another thread, we need Send. AudioProcessor should be Send.
|
||||||
|
// However, the callback is called repeatedly. We need to keep state.
|
||||||
|
// The workaround is to wrap it in a Mutex.
|
||||||
|
let processor = Arc::new(Mutex::new(processor));
|
||||||
|
let processor_clone = processor.clone();
|
||||||
|
|
||||||
|
// --- SYSTEM AUDIO CAPTURE START ---
|
||||||
|
// Prevent Doubling: If user selected an aggregate device (Hearbit Audio/BlackHole),
|
||||||
|
// it ALREADY contains system audio. In that case, we don't need internal SCK capture.
|
||||||
|
let is_aggregate = device_id.contains("Hearbit") || device_id.contains("BlackHole");
|
||||||
|
|
||||||
|
if is_aggregate {
|
||||||
|
emit_log(&app, "INFO", "Aggregate device detected. Disabling internal System Audio Capture to prevent doubling.");
|
||||||
|
} else {
|
||||||
|
let mut sys_capture = sc_audio::SystemAudioCapture::new(config.sample_rate());
|
||||||
|
|
||||||
|
// Get the queue to share with the capture callback
|
||||||
|
let queue_clone = {
|
||||||
|
let p = processor.lock().unwrap();
|
||||||
|
p.system_queue.clone() // Access the pub field we added
|
||||||
|
};
|
||||||
|
|
||||||
|
let sys_callback = move |data: &[f32]| {
|
||||||
|
// Push to queue
|
||||||
|
if let Ok(mut q) = queue_clone.lock() {
|
||||||
|
q.extend(data.iter());
|
||||||
|
|
||||||
|
// Limit queue size to avoid memory leaks if main process loop is slow
|
||||||
|
while q.len() > 48000 * 5 { // 5 seconds buffer
|
||||||
|
q.pop_front();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
match sys_capture.start(sys_callback).await {
|
||||||
|
Ok(_) => emit_log(&app, "INFO", "System Audio Capture started."),
|
||||||
|
Err(e) => emit_log(&app, "WARN", &format!("System Audio Capture failed (Permissions?): {}", e)),
|
||||||
|
}
|
||||||
|
|
||||||
|
*state.system_capture.lock().unwrap() = Some(sys_capture);
|
||||||
|
}
|
||||||
|
// --- SYSTEM AUDIO CAPTURE END ---
|
||||||
|
|
||||||
|
let app_handle = app.clone();
|
||||||
|
let err_fn = move |err| {
|
||||||
|
eprintln!("an error occurred on stream: {}", err);
|
||||||
|
emit_log(&app_handle, "ERROR", &format!("Stream error: {}", err));
|
||||||
|
};
|
||||||
|
|
||||||
|
let stream = match config.sample_format() {
|
||||||
|
cpal::SampleFormat::F32 => device.build_input_stream(
|
||||||
|
&config.into(),
|
||||||
|
move |data: &[f32], _: &_| {
|
||||||
|
if let Ok(mut p) = processor_clone.lock() {
|
||||||
|
p.process(data);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
err_fn,
|
||||||
|
None
|
||||||
|
),
|
||||||
|
// For I16 and U16 we need to convert to F32 for our processor
|
||||||
|
cpal::SampleFormat::I16 => device.build_input_stream(
|
||||||
|
&config.into(),
|
||||||
|
move |data: &[i16], _: &_| {
|
||||||
|
// Convert i16 to f32
|
||||||
|
let f32_data: Vec<f32> = data.iter().map(|&s| s as f32 / i16::MAX as f32).collect();
|
||||||
|
if let Ok(mut p) = processor_clone.lock() {
|
||||||
|
p.process(&f32_data);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
err_fn,
|
||||||
|
None
|
||||||
|
),
|
||||||
|
cpal::SampleFormat::U16 => device.build_input_stream(
|
||||||
|
&config.into(),
|
||||||
|
move |data: &[u16], _: &_| {
|
||||||
|
// Convert u16 to f32
|
||||||
|
let f32_data: Vec<f32> = data.iter().map(|&s| (s as i32 - 32768) as f32 / 32768.0).collect();
|
||||||
|
if let Ok(mut p) = processor_clone.lock() {
|
||||||
|
p.process(&f32_data);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
err_fn,
|
||||||
|
None
|
||||||
|
),
|
||||||
|
_ => return Err("Unsupported sample format".to_string()),
|
||||||
|
}.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
stream.play().map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
// Store state
|
||||||
|
*state.recording_stream.lock().unwrap() = Some(stream);
|
||||||
|
*state.recording_file_path.lock().unwrap() = Some(file_path_str.clone());
|
||||||
|
|
||||||
|
emit_log(&app, "SUCCESS", &format!("Recording started. File: {}", file_path_str));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn stop_recording(app: AppHandle, state: State<'_, AppState>) -> Result<String, String> {
|
||||||
|
emit_log(&app, "INFO", "Stopping recording...");
|
||||||
|
// Drop stream to stop recording
|
||||||
|
{
|
||||||
|
let mut stream_guard = state.recording_stream.lock().unwrap();
|
||||||
|
// Also stop System Capture
|
||||||
|
let mut sys_guard = state.system_capture.lock().unwrap();
|
||||||
|
if let Some(sys) = sys_guard.as_mut() {
|
||||||
|
sys.stop();
|
||||||
|
}
|
||||||
|
*sys_guard = None;
|
||||||
|
|
||||||
|
if stream_guard.is_none() {
|
||||||
|
return Err("Not recording".to_string());
|
||||||
|
}
|
||||||
|
*stream_guard = None; // This drops the stream and stops recording
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return file path
|
||||||
|
let mut path_guard = state.recording_file_path.lock().unwrap();
|
||||||
|
let path = path_guard.take().ok_or("No recording path found".to_string())?;
|
||||||
|
emit_log(&app, "SUCCESS", &format!("Recording stopped. Saved to: {}", path));
|
||||||
|
Ok(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn pause_recording(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||||
|
emit_log(&app, "INFO", "Pausing recording...");
|
||||||
|
let stream_guard = state.recording_stream.lock().unwrap();
|
||||||
|
if let Some(stream) = stream_guard.as_ref() {
|
||||||
|
stream.pause().map_err(|e| e.to_string())?;
|
||||||
|
emit_log(&app, "SUCCESS", "Recording paused.");
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err("Not recording".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn resume_recording(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> {
|
||||||
|
emit_log(&app, "INFO", "Resuming recording...");
|
||||||
|
let stream_guard = state.recording_stream.lock().unwrap();
|
||||||
|
if let Some(stream) = stream_guard.as_ref() {
|
||||||
|
stream.play().map_err(|e| e.to_string())?;
|
||||||
|
emit_log(&app, "SUCCESS", "Recording resumed.");
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err("Not recording".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
struct ModelListResponse {
|
||||||
|
data: Vec<ModelData>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
struct ModelData {
|
||||||
|
id: String,
|
||||||
|
#[allow(dead_code)]
|
||||||
|
owned_by: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Structs for Infomaniak API responses
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
struct WhisperResponse {
|
||||||
|
text: Option<String>,
|
||||||
|
batch_id: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
struct ChatCompletionResponse {
|
||||||
|
choices: Vec<Choice>,
|
||||||
|
}
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
struct Choice {
|
||||||
|
message: Message,
|
||||||
|
}
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
struct Message {
|
||||||
|
#[allow(dead_code)]
|
||||||
|
content: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
struct ModelInfo {
|
||||||
|
id: String,
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
async fn get_available_models(app: AppHandle, api_key: String, product_id: String) -> Result<Vec<ModelInfo>, String> {
|
||||||
|
emit_log(&app, "INFO", "Fetching available models from Infomaniak...");
|
||||||
|
let client = reqwest::Client::new();
|
||||||
|
// Use the v2/openai compliant endpoint as per docs
|
||||||
|
let url = format!("https://api.infomaniak.com/2/ai/{}/openai/v1/models", product_id);
|
||||||
|
|
||||||
|
emit_log(&app, "DEBUG", &format!("GET {}", url));
|
||||||
|
|
||||||
|
let res = client.get(&url)
|
||||||
|
.header("Authorization", format!("Bearer {}", api_key))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
let msg = format!("Network error fetching models: {}", e);
|
||||||
|
emit_log(&app, "ERROR", &msg);
|
||||||
|
msg
|
||||||
|
})?;
|
||||||
|
|
||||||
|
if res.status().is_success() {
|
||||||
|
let raw_body = res.text().await.map_err(|e| e.to_string())?;
|
||||||
|
// println!("Models Raw Response: {}", raw_body);
|
||||||
|
let list: ModelListResponse = serde_json::from_str(&raw_body)
|
||||||
|
.map_err(|e| format!("Failed to parse models: {}. Body: {}", e, raw_body))?;
|
||||||
|
|
||||||
|
let models = list.data.into_iter()
|
||||||
|
.filter(|m| !m.id.to_lowercase().contains("mini_lm") && !m.id.to_lowercase().contains("bert") && !m.id.to_lowercase().contains("embedding"))
|
||||||
|
.map(|m| ModelInfo {
|
||||||
|
id: m.id.clone(),
|
||||||
|
name: m.id, // Use ID as name for now, or fetch more details if available
|
||||||
|
}).collect::<Vec<ModelInfo>>();
|
||||||
|
|
||||||
|
emit_log(&app, "SUCCESS", &format!("Loaded {} models.", models.len()));
|
||||||
|
Ok(models)
|
||||||
|
} else {
|
||||||
|
let err = res.text().await.unwrap_or_default();
|
||||||
|
emit_log(&app, "ERROR", &format!("Failed to fetch models: {}", err));
|
||||||
|
Err(format!("Failed to fetch models: {}", err))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
struct WhisperVerboseResponse {
|
||||||
|
text: Option<String>,
|
||||||
|
segments: Option<Vec<Segment>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
struct Segment {
|
||||||
|
start: f64,
|
||||||
|
end: f64,
|
||||||
|
text: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
async fn transcribe_audio(app: AppHandle, file_path: String, api_key: String, product_id: String) -> Result<String, String> {
|
||||||
|
emit_log(&app, "INFO", "Starting transcription with timestamps...");
|
||||||
|
let client = reqwest::Client::new();
|
||||||
|
|
||||||
|
// Prepare file part
|
||||||
|
let file_bytes = std::fs::read(&file_path).map_err(|e| e.to_string())?;
|
||||||
|
// We must use a known file name for the part, Infomaniak might care, or not.
|
||||||
|
let file_part = reqwest::multipart::Part::bytes(file_bytes)
|
||||||
|
.file_name("recording.wav")
|
||||||
|
.mime_str("audio/wav")
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
let form = reqwest::multipart::Form::new()
|
||||||
|
.part("file", file_part)
|
||||||
|
.text("model", "whisper")
|
||||||
|
.text("response_format", "verbose_json")
|
||||||
|
.text("timestamp_granularities[]", "segment"); // Crucial for accurate segments
|
||||||
|
|
||||||
|
let url = format!("https://api.infomaniak.com/1/ai/{}/openai/audio/transcriptions", product_id);
|
||||||
|
|
||||||
|
emit_log(&app, "DEBUG", &format!("POST {}", url));
|
||||||
|
|
||||||
|
let res = client.post(&url)
|
||||||
|
.header("Authorization", format!("Bearer {}", api_key))
|
||||||
|
.multipart(form)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
let msg = format!("Network error during transcription: {}", e);
|
||||||
|
emit_log(&app, "ERROR", &msg);
|
||||||
|
msg
|
||||||
|
})?;
|
||||||
|
|
||||||
|
if res.status().is_success() {
|
||||||
|
let raw_body = res.text().await.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
// Check if we got a batch ID
|
||||||
|
#[derive(serde::Deserialize)]
|
||||||
|
struct BatchResponse {
|
||||||
|
batch_id: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try parsing as batch response first (Infomaniak specific behavior)
|
||||||
|
if let Ok(batch_res) = serde_json::from_str::<BatchResponse>(&raw_body) {
|
||||||
|
if let Some(batch_id) = batch_res.batch_id {
|
||||||
|
emit_log(&app, "INFO", &format!("Transcription queued. Batch ID: {}", batch_id));
|
||||||
|
return poll_transcription(&app, &client, &api_key, &product_id, &batch_id).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If not batch, try parsing verbose response directly
|
||||||
|
// Log the raw body so we can see why it fails
|
||||||
|
emit_log(&app, "DEBUG", &format!("Direct Response (first 500 chars): {:.500}", raw_body));
|
||||||
|
|
||||||
|
let response: WhisperVerboseResponse = serde_json::from_str(&raw_body)
|
||||||
|
.map_err(|e| format!("Failed to decode JSON: {}. Body: {}", e, raw_body))?;
|
||||||
|
|
||||||
|
if let Some(segments) = response.segments {
|
||||||
|
emit_log(&app, "INFO", &format!("Found {} segments (Direct).", segments.len()));
|
||||||
|
for (i, seg) in segments.iter().take(3).enumerate() {
|
||||||
|
emit_log(&app, "DEBUG", &format!("Seg {}: start={}", i, seg.start));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Format timestamps: [MM:SS] Text
|
||||||
|
let mut formatted_transcript = String::new();
|
||||||
|
for segment in segments {
|
||||||
|
let start_mins = (segment.start / 60.0).floor() as u64;
|
||||||
|
let start_secs = (segment.start % 60.0).floor() as u64;
|
||||||
|
formatted_transcript.push_str(&format!("[{:02}:{:02}] {}\n", start_mins, start_secs, segment.text.trim()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback to raw text if segments empty
|
||||||
|
if formatted_transcript.trim().is_empty() {
|
||||||
|
if let Some(text) = response.text {
|
||||||
|
emit_log(&app, "SUCCESS", "Segments missing, using raw text.");
|
||||||
|
return Ok(text);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
emit_log(&app, "SUCCESS", "Transcription received with timestamps.");
|
||||||
|
return Ok(formatted_transcript);
|
||||||
|
}
|
||||||
|
} else if let Some(text) = response.text {
|
||||||
|
emit_log(&app, "SUCCESS", "Segments missing, using raw text.");
|
||||||
|
return Ok(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
emit_log(&app, "ERROR", "Response contained no recognized content.");
|
||||||
|
Err(format!("Response contained no recognized content. Body: {}", raw_body))
|
||||||
|
} else {
|
||||||
|
let error_text = res.text().await.unwrap_or_default();
|
||||||
|
emit_log(&app, "ERROR", &format!("Transcription failed: {}", error_text));
|
||||||
|
Err(format!("Transcription failed: {}", error_text))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn poll_transcription(app: &AppHandle, client: &reqwest::Client, api_key: &str, product_id: &str, batch_id: &str) -> Result<String, String> {
|
||||||
|
let status_url = format!("https://api.infomaniak.com/1/ai/{}/results/{}", product_id, batch_id);
|
||||||
|
|
||||||
|
let mut attempts = 0;
|
||||||
|
while attempts < 40 { // 40 * 2s = 80s timeout
|
||||||
|
attempts += 1;
|
||||||
|
sleep(Duration::from_secs(2)).await;
|
||||||
|
|
||||||
|
emit_log(app, "DEBUG", &format!("Polling status... Attempt {}", attempts));
|
||||||
|
let res = client.get(&status_url)
|
||||||
|
.header("Authorization", format!("Bearer {}", api_key))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("Polling error: {}", e))?;
|
||||||
|
|
||||||
|
if res.status().is_success() {
|
||||||
|
let json: serde_json::Value = res.json().await.map_err(|e| e.to_string())?;
|
||||||
|
// Check 'status'
|
||||||
|
if let Some(status) = json.get("status").and_then(|s| s.as_str()) {
|
||||||
|
if status == "success" {
|
||||||
|
// Download the result
|
||||||
|
let download_url = format!("https://api.infomaniak.com/1/ai/{}/results/{}/download", product_id, batch_id);
|
||||||
|
let dl_res = client.get(&download_url)
|
||||||
|
.header("Authorization", format!("Bearer {}", api_key))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
if dl_res.status().is_success() {
|
||||||
|
let content = dl_res.text().await.map_err(|e| e.to_string())?;
|
||||||
|
emit_log(app, "DEBUG", &format!("Poll Raw Content (first 500 chars): {:.500}", content));
|
||||||
|
|
||||||
|
// Try to parse as Verbose JSON to get timestamps
|
||||||
|
if let Ok(response) = serde_json::from_str::<WhisperVerboseResponse>(&content) {
|
||||||
|
if let Some(segments) = response.segments {
|
||||||
|
emit_log(app, "INFO", &format!("Found {} segments.", segments.len()));
|
||||||
|
// Log first 3 segments start times
|
||||||
|
for (i, seg) in segments.iter().take(3).enumerate() {
|
||||||
|
emit_log(app, "DEBUG", &format!("Seg {}: start={}", i, seg.start));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut formatted_transcript = String::new();
|
||||||
|
for segment in segments {
|
||||||
|
let start_mins = (segment.start / 60.0).floor() as u64;
|
||||||
|
let start_secs = (segment.start % 60.0).floor() as u64;
|
||||||
|
formatted_transcript.push_str(&format!("[{:02}:{:02}] {}\n", start_mins, start_secs, segment.text.trim()));
|
||||||
|
}
|
||||||
|
if !formatted_transcript.trim().is_empty() {
|
||||||
|
emit_log(app, "SUCCESS", "Transcription completed (async) with timestamps.");
|
||||||
|
return Ok(formatted_transcript);
|
||||||
|
} else {
|
||||||
|
emit_log(app, "WARN", "Segments found but empty content.");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
emit_log(app, "WARN", "Verbose parsed but no segments found.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(text) = response.text {
|
||||||
|
emit_log(app, "SUCCESS", "Transcription completed (async) - raw text (segments missing).");
|
||||||
|
return Ok(text);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
emit_log(app, "WARN", "Failed to parse poll content as WhisperVerboseResponse");
|
||||||
|
}
|
||||||
|
|
||||||
|
emit_log(app, "SUCCESS", "Transcription completed - returning raw content.");
|
||||||
|
// If not JSON or no text field, return raw content
|
||||||
|
return Ok(content);
|
||||||
|
} else {
|
||||||
|
emit_log(app, "ERROR", "Failed to download transcription results.");
|
||||||
|
return Err(format!("Download failed: {}", dl_res.status()));
|
||||||
|
}
|
||||||
|
} else if status == "failed" || status == "error" {
|
||||||
|
let err_msg = format!("Batch processing failed [Status: {}]. Full Response: {:?}", status, json);
|
||||||
|
emit_log(app, "ERROR", &err_msg);
|
||||||
|
return Err(err_msg);
|
||||||
|
}
|
||||||
|
// If 'processing' or 'pending', continue loop
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
emit_log(app, "ERROR", "Transcription timed out after 80s.");
|
||||||
|
Err("Transcription timed out".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
async fn summarize_text(app: AppHandle, text: String, api_key: String, product_id: String, prompt: String, model: String) -> Result<String, String> {
|
||||||
|
emit_log(&app, "INFO", "Starting summarization...");
|
||||||
|
let client = reqwest::Client::new();
|
||||||
|
let url = format!("https://api.infomaniak.com/2/ai/{}/openai/v1/chat/completions", product_id);
|
||||||
|
|
||||||
|
let messages = serde_json::json!([
|
||||||
|
{ "role": "system", "content": prompt },
|
||||||
|
{ "role": "user", "content": text }
|
||||||
|
]);
|
||||||
|
|
||||||
|
let model_to_use = if model.is_empty() { "mixtral".to_string() } else { model };
|
||||||
|
|
||||||
|
let body = serde_json::json!({
|
||||||
|
"model": model_to_use,
|
||||||
|
"messages": messages
|
||||||
|
});
|
||||||
|
|
||||||
|
emit_log(&app, "DEBUG", &format!("POST {}", url));
|
||||||
|
|
||||||
|
let res = client.post(&url)
|
||||||
|
.header("Authorization", format!("Bearer {}", api_key))
|
||||||
|
.header("Content-Type", "application/json")
|
||||||
|
.json(&body)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
let msg = format!("Network error during summarization: {}", e);
|
||||||
|
emit_log(&app, "ERROR", &msg);
|
||||||
|
msg
|
||||||
|
})?;
|
||||||
|
|
||||||
|
if res.status().is_success() {
|
||||||
|
let raw_body = res.text().await.map_err(|e| e.to_string())?;
|
||||||
|
// println!("Summarization Raw Response: {}", raw_body);
|
||||||
|
|
||||||
|
let response_body: ChatCompletionResponse = serde_json::from_str(&raw_body)
|
||||||
|
.map_err(|e| format!("Failed to decode JSON: {}. Body: {}", e, raw_body))?;
|
||||||
|
|
||||||
|
if let Some(choice) = response_body.choices.first() {
|
||||||
|
emit_log(&app, "SUCCESS", "Summarization received.");
|
||||||
|
Ok(choice.message.content.clone())
|
||||||
|
} else {
|
||||||
|
emit_log(&app, "WARN", "No summary generated in response.");
|
||||||
|
Err("No summary generated".to_string())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let error_text = res.text().await.unwrap_or_default();
|
||||||
|
emit_log(&app, "ERROR", &format!("Summarization failed: {}", error_text));
|
||||||
|
Err(format!("Summarization failed: {}", error_text))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
struct AudioMetadata {
|
||||||
|
duration: f64,
|
||||||
|
size: u64,
|
||||||
|
format: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper to find ffmpeg/ffprobe in common paths
|
||||||
|
fn resolve_binary_path(binary_name: &str) -> String {
|
||||||
|
let common_paths = [
|
||||||
|
format!("/opt/homebrew/bin/{}", binary_name),
|
||||||
|
format!("/usr/local/bin/{}", binary_name),
|
||||||
|
format!("/usr/bin/{}", binary_name),
|
||||||
|
];
|
||||||
|
|
||||||
|
for path in common_paths.iter() {
|
||||||
|
if std::path::Path::new(path).exists() {
|
||||||
|
return path.clone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback to expecting it in PATH
|
||||||
|
binary_name.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn get_audio_metadata(app: AppHandle, file_path: String) -> Result<AudioMetadata, String> {
|
||||||
|
emit_log(&app, "INFO", &format!("Getting metadata for: {}", file_path));
|
||||||
|
|
||||||
|
let path = std::path::Path::new(&file_path);
|
||||||
|
if !path.exists() {
|
||||||
|
return Err(format!("File not found: {}", file_path));
|
||||||
|
}
|
||||||
|
|
||||||
|
let size = std::fs::metadata(&file_path)
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.len();
|
||||||
|
|
||||||
|
// Use ffprobe to get duration
|
||||||
|
// Try resolved path first
|
||||||
|
let ffprobe_cmd = resolve_binary_path("ffprobe");
|
||||||
|
|
||||||
|
let output = Command::new(&ffprobe_cmd)
|
||||||
|
.args([
|
||||||
|
"-v", "error",
|
||||||
|
"-show_entries", "format=duration",
|
||||||
|
"-of", "default=noprint_wrappers=1:nokey=1",
|
||||||
|
&file_path
|
||||||
|
])
|
||||||
|
.output()
|
||||||
|
.map_err(|e| format!("Failed to execute ffprobe at '{}': {}", ffprobe_cmd, e))?;
|
||||||
|
|
||||||
|
let duration_str = String::from_utf8_lossy(&output.stdout);
|
||||||
|
let duration: f64 = duration_str.trim().parse().unwrap_or(0.0);
|
||||||
|
|
||||||
|
// Extension as format
|
||||||
|
let format = path.extension()
|
||||||
|
.and_then(|e| e.to_str())
|
||||||
|
.unwrap_or("unknown")
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
Ok(AudioMetadata {
|
||||||
|
duration,
|
||||||
|
size,
|
||||||
|
format,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn convert_to_mp3(app: AppHandle, wav_path: String) -> Result<String, String> {
|
||||||
|
emit_log(&app, "INFO", &format!("Converting to MP3: {}", wav_path));
|
||||||
|
|
||||||
|
let mp3_path = wav_path.replace(".wav", ".mp3");
|
||||||
|
let ffmpeg_cmd = resolve_binary_path("ffmpeg");
|
||||||
|
|
||||||
|
let output = Command::new(&ffmpeg_cmd)
|
||||||
|
.args([
|
||||||
|
"-i", &wav_path,
|
||||||
|
"-codec:a", "libmp3lame",
|
||||||
|
"-b:a", "64k",
|
||||||
|
"-y", // overwrite
|
||||||
|
&mp3_path
|
||||||
|
])
|
||||||
|
.output()
|
||||||
|
.map_err(|e| format!("Failed to execute ffmpeg at '{}': {}", ffmpeg_cmd, e))?;
|
||||||
|
|
||||||
|
if output.status.success() {
|
||||||
|
emit_log(&app, "SUCCESS", &format!("MP3 created: {}", mp3_path));
|
||||||
|
Ok(mp3_path)
|
||||||
|
} else {
|
||||||
|
let error = String::from_utf8_lossy(&output.stderr);
|
||||||
|
emit_log(&app, "ERROR", &format!("MP3 conversion failed: {}", error));
|
||||||
|
Err(format!("MP3 conversion failed: {}", error))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn chunk_audio(app: AppHandle, file_path: String, chunk_minutes: u32) -> Result<Vec<String>, String> {
|
||||||
|
emit_log(&app, "INFO", &format!("Chunking audio: {} ({}min chunks)", file_path, chunk_minutes));
|
||||||
|
|
||||||
|
let chunk_seconds = chunk_minutes * 60;
|
||||||
|
let ffprobe_cmd = resolve_binary_path("ffprobe");
|
||||||
|
let ffmpeg_cmd = resolve_binary_path("ffmpeg");
|
||||||
|
|
||||||
|
// Get total duration using ffprobe
|
||||||
|
let duration_output = Command::new(&ffprobe_cmd)
|
||||||
|
.args([
|
||||||
|
"-v", "error",
|
||||||
|
"-show_entries", "format=duration",
|
||||||
|
"-of", "default=noprint_wrappers=1:nokey=1",
|
||||||
|
&file_path
|
||||||
|
])
|
||||||
|
.output()
|
||||||
|
.map_err(|e| format!("Failed to get duration with '{}': {}", ffprobe_cmd, e))?;
|
||||||
|
|
||||||
|
let duration_str = String::from_utf8_lossy(&duration_output.stdout);
|
||||||
|
let duration: f64 = duration_str.trim().parse()
|
||||||
|
.map_err(|_| "Failed to parse duration".to_string())?;
|
||||||
|
|
||||||
|
let num_chunks = (duration / chunk_seconds as f64).ceil() as usize;
|
||||||
|
emit_log(&app, "INFO", &format!("Total duration: {}s, creating {} chunks", duration, num_chunks));
|
||||||
|
|
||||||
|
let mut chunk_paths = Vec::new();
|
||||||
|
let base_path = file_path.replace(".mp3", "");
|
||||||
|
|
||||||
|
for i in 0..num_chunks {
|
||||||
|
let start_time = i as u32 * chunk_seconds;
|
||||||
|
let chunk_path = format!("{}_chunk_{}.mp3", base_path, i);
|
||||||
|
|
||||||
|
let output = Command::new(&ffmpeg_cmd)
|
||||||
|
.args([
|
||||||
|
"-i", &file_path,
|
||||||
|
"-ss", &start_time.to_string(),
|
||||||
|
"-t", &chunk_seconds.to_string(),
|
||||||
|
"-c", "copy",
|
||||||
|
"-y",
|
||||||
|
&chunk_path
|
||||||
|
])
|
||||||
|
.output()
|
||||||
|
.map_err(|e| format!("Failed to create chunk {} with '{}': {}", i, ffmpeg_cmd, e))?;
|
||||||
|
|
||||||
|
if !output.status.success() {
|
||||||
|
let error = String::from_utf8_lossy(&output.stderr);
|
||||||
|
return Err(format!("Chunk {} failed: {}", i, error));
|
||||||
|
}
|
||||||
|
|
||||||
|
chunk_paths.push(chunk_path);
|
||||||
|
}
|
||||||
|
|
||||||
|
emit_log(&app, "SUCCESS", &format!("Created {} chunks", chunk_paths.len()));
|
||||||
|
Ok(chunk_paths)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn read_image_as_base64(app: AppHandle, file_path: String) -> Result<String, String> {
|
||||||
|
emit_log(&app, "INFO", &format!("Reading image as base64: {}", file_path));
|
||||||
|
|
||||||
|
let bytes = std::fs::read(&file_path)
|
||||||
|
.map_err(|e| format!("Failed to read file: {}", e))?;
|
||||||
|
|
||||||
|
// Detect image type from extension
|
||||||
|
let extension = std::path::Path::new(&file_path)
|
||||||
|
.extension()
|
||||||
|
.and_then(|e| e.to_str())
|
||||||
|
.unwrap_or("png")
|
||||||
|
.to_lowercase();
|
||||||
|
|
||||||
|
let mime_type = match extension.as_str() {
|
||||||
|
"jpg" | "jpeg" => "image/jpeg",
|
||||||
|
"png" => "image/png",
|
||||||
|
"svg" => "image/svg+xml",
|
||||||
|
"gif" => "image/gif",
|
||||||
|
_ => "image/png"
|
||||||
|
};
|
||||||
|
|
||||||
|
// Use base64 encoding
|
||||||
|
let base64_str = base64::prelude::BASE64_STANDARD.encode(&bytes);
|
||||||
|
let data_url = format!("data:{};base64,{}", mime_type, base64_str);
|
||||||
|
|
||||||
|
emit_log(&app, "SUCCESS", &format!("Image converted to base64 ({} bytes)", base64_str.len()));
|
||||||
|
Ok(data_url)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn open_audio_midi_setup() -> Result<(), String> {
|
||||||
|
Command::new("open")
|
||||||
|
.arg("-a")
|
||||||
|
.arg("Audio MIDI Setup")
|
||||||
|
.spawn()
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
fn create_hearbit_audio_device(app: AppHandle) -> Result<String, String> {
|
||||||
|
emit_log(&app, "INFO", "Attempting to create Hearbit Audio device...");
|
||||||
|
|
||||||
|
// Resolve resource path
|
||||||
|
let resource_path = app.path().resource_dir()
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.join("resources/create_hearbit_audio.swift");
|
||||||
|
|
||||||
|
if !resource_path.exists() {
|
||||||
|
// Fallback for dev environment where resources might not be bundled yet or different path
|
||||||
|
emit_log(&app, "WARN", &format!("Resource script not found at {:?}. Trying local src-tauri path.", resource_path));
|
||||||
|
}
|
||||||
|
|
||||||
|
// For now, in dev mode, we might need to point to the source location if bundle isn't active
|
||||||
|
// But let's try running it.
|
||||||
|
|
||||||
|
let output = Command::new("swift")
|
||||||
|
.arg(resource_path)
|
||||||
|
.output()
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
|
||||||
|
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
|
||||||
|
|
||||||
|
emit_log(&app, "DEBUG", &format!("Script Output: {}", stdout));
|
||||||
|
if !stderr.is_empty() {
|
||||||
|
emit_log(&app, "WARN", &format!("Script Stderr: {}", stderr));
|
||||||
|
}
|
||||||
|
|
||||||
|
if output.status.success() {
|
||||||
|
emit_log(&app, "SUCCESS", "Hearbit Audio device created successfully.");
|
||||||
|
Ok("Device created successfully".to_string())
|
||||||
|
} else {
|
||||||
|
emit_log(&app, "ERROR", "Failed to create device.");
|
||||||
|
Err(format!("Failed to create device: {} {}", stdout, stderr))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
async fn check_screen_recording_permission() -> bool {
|
||||||
|
sc_audio::check_permissions().await
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
async fn save_text_file(app: AppHandle, path: String, content: String) -> Result<(), String> {
|
||||||
|
emit_log(&app, "INFO", &format!("Saving text file to: {}", path));
|
||||||
|
match std::fs::write(&path, content) {
|
||||||
|
Ok(_) => {
|
||||||
|
emit_log(&app, "SUCCESS", "File saved successfully.");
|
||||||
|
Ok(())
|
||||||
|
},
|
||||||
|
Err(e) => {
|
||||||
|
emit_log(&app, "ERROR", &format!("Failed to save file: {}", e));
|
||||||
|
Err(e.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
async fn read_log_file(app: AppHandle) -> Result<String, String> {
|
||||||
|
let log_path = app.path().app_log_dir().map_err(|e| e.to_string())?.join("hearbit-ai.log");
|
||||||
|
if log_path.exists() {
|
||||||
|
let content = std::fs::read_to_string(&log_path).map_err(|e| e.to_string())?;
|
||||||
|
Ok(content)
|
||||||
|
} else {
|
||||||
|
Ok("No log file found yet.".to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||||
|
pub fn run() {
|
||||||
|
tauri::Builder::default()
|
||||||
|
.setup(|app| {
|
||||||
|
// Setup Tray Icon
|
||||||
|
let quit_i = MenuItem::with_id(app, "quit", "Quit Hearbit AI", true, None::<&str>).unwrap();
|
||||||
|
let show_i = MenuItem::with_id(app, "show", "Show Window", true, None::<&str>).unwrap();
|
||||||
|
let menu = Menu::with_items(app, &[&show_i, &quit_i]).unwrap();
|
||||||
|
|
||||||
|
let _tray = TrayIconBuilder::new()
|
||||||
|
.icon(app.default_window_icon().unwrap().clone())
|
||||||
|
.menu(&menu)
|
||||||
|
.show_menu_on_left_click(true)
|
||||||
|
.on_menu_event(|app, event| {
|
||||||
|
match event.id.as_ref() {
|
||||||
|
"quit" => app.exit(0),
|
||||||
|
"show" => {
|
||||||
|
if let Some(window) = app.get_webview_window("main") {
|
||||||
|
let _ = window.show();
|
||||||
|
let _ = window.set_focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.on_tray_icon_event(|tray, event| {
|
||||||
|
if let TrayIconEvent::Click { .. } = event {
|
||||||
|
let app = tray.app_handle();
|
||||||
|
if let Some(window) = app.get_webview_window("main") {
|
||||||
|
let _ = window.show();
|
||||||
|
let _ = window.set_focus();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.build(app)?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.on_window_event(|window, event| {
|
||||||
|
if let WindowEvent::CloseRequested { api, .. } = event {
|
||||||
|
// Prevent window from closing, just hide it
|
||||||
|
window.hide().unwrap();
|
||||||
|
api.prevent_close();
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.plugin(tauri_plugin_shell::init())
|
||||||
|
.plugin(tauri_plugin_log::Builder::default()
|
||||||
|
.targets([
|
||||||
|
tauri_plugin_log::Target::new(tauri_plugin_log::TargetKind::Stdout),
|
||||||
|
tauri_plugin_log::Target::new(tauri_plugin_log::TargetKind::LogDir { file_name: Some("hearbit-ai.log".to_string()) }),
|
||||||
|
])
|
||||||
|
.build())
|
||||||
|
.plugin(tauri_plugin_opener::init())
|
||||||
|
.plugin(tauri_plugin_dialog::init())
|
||||||
|
.plugin(tauri_plugin_fs::init())
|
||||||
|
.plugin(tauri_plugin_oauth::init())
|
||||||
|
.manage(AppState {
|
||||||
|
recording_stream: Mutex::new(None),
|
||||||
|
recording_file_path: Mutex::new(None),
|
||||||
|
system_capture: Mutex::new(None),
|
||||||
|
})
|
||||||
|
.invoke_handler(tauri::generate_handler![
|
||||||
|
greet,
|
||||||
|
get_input_devices,
|
||||||
|
start_recording,
|
||||||
|
stop_recording,
|
||||||
|
pause_recording,
|
||||||
|
resume_recording,
|
||||||
|
transcribe_audio,
|
||||||
|
summarize_text,
|
||||||
|
get_available_models,
|
||||||
|
open_audio_midi_setup,
|
||||||
|
create_hearbit_audio_device,
|
||||||
|
check_screen_recording_permission,
|
||||||
|
auth::start_auth_flow,
|
||||||
|
auth::get_calendar_events,
|
||||||
|
save_text_file,
|
||||||
|
read_log_file,
|
||||||
|
get_audio_metadata,
|
||||||
|
convert_to_mp3,
|
||||||
|
chunk_audio,
|
||||||
|
read_image_as_base64,
|
||||||
|
email::send_smtp_email
|
||||||
|
])
|
||||||
|
.run(tauri::generate_context!())
|
||||||
|
.expect("error while running tauri application");
|
||||||
|
}
|
||||||
311
src-tauri/src/sc_audio.rs
Normal file
311
src-tauri/src/sc_audio.rs
Normal file
@@ -0,0 +1,311 @@
|
|||||||
|
use cocoa::base::nil;
|
||||||
|
use objc::{msg_send, sel, sel_impl};
|
||||||
|
use screencapturekit_sys::{
|
||||||
|
cm_sample_buffer_ref::CMSampleBufferRef,
|
||||||
|
content_filter::{UnsafeContentFilter, UnsafeInitParams},
|
||||||
|
os_types::rc::Id,
|
||||||
|
shareable_content::{UnsafeSCRunningApplication, UnsafeSCShareableContent},
|
||||||
|
stream::UnsafeSCStream,
|
||||||
|
stream_configuration::UnsafeStreamConfiguration,
|
||||||
|
stream_error_handler::UnsafeSCStreamError,
|
||||||
|
stream_output_handler::UnsafeSCStreamOutput,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::emit_log;
|
||||||
|
use tauri::{AppHandle, Emitter, Manager}; // Ensure Emitter is verified for v2 (it is trait typically)
|
||||||
|
|
||||||
|
pub struct SystemAudioCapture {
|
||||||
|
stream: Option<Id<UnsafeSCStream>>,
|
||||||
|
sample_rate: u32,
|
||||||
|
excluded_apps: Vec<String>,
|
||||||
|
app_handle: Option<AppHandle>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct AudioOutputWrapper {
|
||||||
|
callback: Box<dyn Fn(&[f32]) + Send + Sync>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UnsafeSCStreamOutput for AudioOutputWrapper {
|
||||||
|
fn did_output_sample_buffer(&self, sample: Id<CMSampleBufferRef>, of_type: u8) {
|
||||||
|
if of_type == 1 {
|
||||||
|
// Audio
|
||||||
|
let buffers = sample.get_av_audio_buffer_list();
|
||||||
|
for buffer in buffers {
|
||||||
|
let data_u8 = buffer.data;
|
||||||
|
let data_f32: &[f32] = unsafe {
|
||||||
|
std::slice::from_raw_parts(data_u8.as_ptr() as *const f32, data_u8.len() / 4)
|
||||||
|
};
|
||||||
|
|
||||||
|
(self.callback)(data_f32);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ErrorHandler;
|
||||||
|
impl UnsafeSCStreamError for ErrorHandler {
|
||||||
|
fn handle_error(&self) {
|
||||||
|
// eprintln!("Stream Error");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn check_permissions() -> bool {
|
||||||
|
UnsafeSCShareableContent::get().is_ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SystemAudioCapture {
|
||||||
|
pub fn new(
|
||||||
|
sample_rate: u32,
|
||||||
|
excluded_apps: Vec<String>,
|
||||||
|
app_handle: Option<AppHandle>,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
stream: None,
|
||||||
|
sample_rate,
|
||||||
|
excluded_apps,
|
||||||
|
app_handle,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_shareable_content() -> Result<Id<UnsafeSCShareableContent>, String> {
|
||||||
|
UnsafeSCShareableContent::get().map_err(|_| format!("Failed to get content"))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Internal helper that takes content
|
||||||
|
fn build_filter_with_content(
|
||||||
|
&self,
|
||||||
|
content: Id<UnsafeSCShareableContent>,
|
||||||
|
) -> Result<Id<UnsafeContentFilter>, String> {
|
||||||
|
if let Some(app) = &self.app_handle {
|
||||||
|
emit_log(app, "TRACE", "[SCK] build_filter_with_content started.");
|
||||||
|
}
|
||||||
|
|
||||||
|
let displays = content.displays();
|
||||||
|
let display = displays.first().ok_or("No display found")?;
|
||||||
|
|
||||||
|
if let Some(app) = &self.app_handle {
|
||||||
|
emit_log(
|
||||||
|
app,
|
||||||
|
"DEBUG",
|
||||||
|
&format!("[SCK] Excluded Apps Config: {:?}", self.excluded_apps),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.excluded_apps.is_empty() {
|
||||||
|
if let Some(app) = &self.app_handle {
|
||||||
|
emit_log(
|
||||||
|
app,
|
||||||
|
"DEBUG",
|
||||||
|
"[SCK] Excluded list empty. Capturing entire display.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return Ok(UnsafeContentFilter::init(UnsafeInitParams::Display(
|
||||||
|
display.clone(),
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut apps_to_exclude = Vec::new();
|
||||||
|
let all_apps = content.applications();
|
||||||
|
|
||||||
|
if let Some(app) = &self.app_handle {
|
||||||
|
emit_log(
|
||||||
|
app,
|
||||||
|
"DEBUG",
|
||||||
|
&format!("[SCK] Found {} running applications.", all_apps.len()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prepare lowercase excluded list for case-insensitive matching
|
||||||
|
let excluded_lower: Vec<String> = self
|
||||||
|
.excluded_apps
|
||||||
|
.iter()
|
||||||
|
.map(|s| s.to_lowercase())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
// Known 3CX PWA Bundle-ID suffix (Chrome PWA).
|
||||||
|
// The full ID is "com.google.Chrome.app.dmmmfdbaapefjmjeomigbhpmjbbjgnph"
|
||||||
|
// which does NOT contain "3cx", so we must match by PWA ID.
|
||||||
|
const KNOWN_3CX_PWA_ID: &str = "dmmmfdbaapefjmjeomigbhpmjbbjgnph";
|
||||||
|
|
||||||
|
// First pass: Check if 3CX PWA is running.
|
||||||
|
// If it is, we must also protect the Chrome main process from exclusion,
|
||||||
|
// because ScreenCaptureKit routes PWA audio through the Chrome host process.
|
||||||
|
let threecx_pwa_running = all_apps.iter().any(|a| {
|
||||||
|
a.get_bundle_identifier()
|
||||||
|
.map(|bid| {
|
||||||
|
let bl = bid.to_lowercase();
|
||||||
|
bl.contains("3cx") || bl.contains(KNOWN_3CX_PWA_ID)
|
||||||
|
})
|
||||||
|
.unwrap_or(false)
|
||||||
|
});
|
||||||
|
|
||||||
|
if threecx_pwa_running {
|
||||||
|
if let Some(h) = &self.app_handle {
|
||||||
|
emit_log(
|
||||||
|
h,
|
||||||
|
"INFO",
|
||||||
|
"[SCK] 3CX detected as running. Chrome main process will be protected from exclusion.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for app in all_apps {
|
||||||
|
if let Some(bid) = app.get_bundle_identifier() {
|
||||||
|
let bid_lower = bid.to_lowercase();
|
||||||
|
|
||||||
|
// --- SAFETY CHECKS (ALLOWLIST) ---
|
||||||
|
|
||||||
|
// 1. ALWAYS Allow 3CX (native app OR known PWA Bundle-ID)
|
||||||
|
if bid_lower.contains("3cx") || bid_lower.contains(KNOWN_3CX_PWA_ID) {
|
||||||
|
if let Some(h) = &self.app_handle {
|
||||||
|
emit_log(h, "INFO", &format!("[SCK] ALLOWLIST: Found 3CX App ('{}'). Ensuring it is NOT excluded.", bid));
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. PROTECT Chrome main process when 3CX PWA is running.
|
||||||
|
// ScreenCaptureKit routes Chrome PWA audio through the main Chrome process.
|
||||||
|
// If we exclude Chrome while 3CX PWA is active, 3CX audio is lost.
|
||||||
|
if threecx_pwa_running && bid_lower == "com.google.chrome" {
|
||||||
|
if let Some(h) = &self.app_handle {
|
||||||
|
emit_log(
|
||||||
|
h,
|
||||||
|
"INFO",
|
||||||
|
"[SCK] ALLOWLIST: Preserving Chrome main process because 3CX PWA is running.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. PROTECT Chrome PWAs (prevent wildcard matching from "Google Chrome")
|
||||||
|
if bid_lower.contains("chrome.app") {
|
||||||
|
// Only exclude if the user has explicitly blocked THIS EXACT app ID.
|
||||||
|
if excluded_lower.contains(&bid_lower) {
|
||||||
|
if let Some(h) = &self.app_handle {
|
||||||
|
emit_log(
|
||||||
|
h,
|
||||||
|
"DEBUG",
|
||||||
|
&format!("[SCK] Excluding PWA App (Exact Match): '{}'", bid),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
apps_to_exclude.push(app);
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
// It's a PWA, and not exactly blocked.
|
||||||
|
// But if "Google Chrome" is blocked, `starts_with` would kill this.
|
||||||
|
// So we SKIP the rest of the loop to protect it.
|
||||||
|
if let Some(h) = &self.app_handle {
|
||||||
|
emit_log(h, "INFO", &format!("[SCK] ALLOWLIST: Preserving Chrome PWA ('{}') from wildcard exclusion.", bid));
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- STANDARD EXCLUSION LOGIC ---
|
||||||
|
if let Some(matched) = excluded_lower
|
||||||
|
.iter()
|
||||||
|
.find(|excluded| bid_lower.starts_with(*excluded))
|
||||||
|
{
|
||||||
|
if let Some(h) = &self.app_handle {
|
||||||
|
emit_log(
|
||||||
|
h,
|
||||||
|
"DEBUG",
|
||||||
|
&format!("[SCK] Excluding App: '{}' (Matches: '{}')", bid, matched),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
apps_to_exclude.push(app);
|
||||||
|
} else {
|
||||||
|
// Optional: Log what is KEPT (verbose)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NOTE: In screencapturekit-sys 0.2.8, DisplayIncludingApplicationsExceptingWindows
|
||||||
|
// actually calls initWithDisplay:excludingApplications: (it's a bug in the crate)
|
||||||
|
let filter_init = UnsafeInitParams::DisplayIncludingApplicationsExceptingWindows(
|
||||||
|
display.clone(),
|
||||||
|
apps_to_exclude,
|
||||||
|
Vec::new(),
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(UnsafeContentFilter::init(filter_init))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn build_filter(&self) -> Result<Id<UnsafeContentFilter>, String> {
|
||||||
|
let content = Self::get_shareable_content()?;
|
||||||
|
self.build_filter_with_content(content)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn start<F>(&mut self, callback: F) -> Result<(), String>
|
||||||
|
where
|
||||||
|
F: Fn(&[f32]) + Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
let filter = self.build_filter().await?;
|
||||||
|
|
||||||
|
let mut config = UnsafeStreamConfiguration::default();
|
||||||
|
config.width = 100;
|
||||||
|
config.height = 100;
|
||||||
|
config.captures_audio = 1;
|
||||||
|
config.sample_rate = self.sample_rate;
|
||||||
|
config.channel_count = 2;
|
||||||
|
config.excludes_current_process_audio = 1;
|
||||||
|
|
||||||
|
let output_wrapper = AudioOutputWrapper {
|
||||||
|
callback: Box::new(callback),
|
||||||
|
};
|
||||||
|
|
||||||
|
let stream = UnsafeSCStream::init(filter, config.into(), ErrorHandler);
|
||||||
|
stream.add_stream_output(output_wrapper, 1); // 1 = Audio
|
||||||
|
|
||||||
|
stream
|
||||||
|
.start_capture()
|
||||||
|
.map_err(|_| "Failed to start capture".to_string())?;
|
||||||
|
|
||||||
|
self.stream = Some(stream);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stop(&mut self) {
|
||||||
|
if let Some(stream) = &self.stream {
|
||||||
|
let _ = stream.stop_capture();
|
||||||
|
}
|
||||||
|
self.stream = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn refresh_filter(&mut self) -> Result<(), String> {
|
||||||
|
// Fallback to internal fetch
|
||||||
|
let content = Self::get_shareable_content()?;
|
||||||
|
self.refresh_with_content(content).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn refresh_with_content(
|
||||||
|
&mut self,
|
||||||
|
content: Id<UnsafeSCShareableContent>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let stream = match &self.stream {
|
||||||
|
Some(s) => s,
|
||||||
|
None => return Ok(()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let filter = self.build_filter_with_content(content)?;
|
||||||
|
|
||||||
|
// Call updateContentFilter:completionHandler:
|
||||||
|
// screencapturekit-sys 0.2.8 does not have this method exposed yet in UnsafeSCStream.
|
||||||
|
// We use msg_send! to call it directly on the underlying object.
|
||||||
|
unsafe {
|
||||||
|
// Get raw pointer to the underlying Objective-C objects.
|
||||||
|
// Since we don't have easy access to the inner pointer of Id<T> via methods,
|
||||||
|
// we cast the pointer to the Id wrapper itself to a pointer to a pointer.
|
||||||
|
// This assumes Id<T> is a transparent wrapper around a pointer.
|
||||||
|
let stream_ptr =
|
||||||
|
*(stream as *const Id<UnsafeSCStream> as *const *mut objc::runtime::Object);
|
||||||
|
let filter_ptr =
|
||||||
|
*(&filter as *const Id<UnsafeContentFilter> as *const *mut objc::runtime::Object);
|
||||||
|
|
||||||
|
let _: () =
|
||||||
|
msg_send![stream_ptr, updateContentFilter: filter_ptr completionHandler: nil];
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
103
src-tauri/src/sc_audio.rs.bak
Normal file
103
src-tauri/src/sc_audio.rs.bak
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
use screencapturekit_sys::{
|
||||||
|
os_types::rc::Id,
|
||||||
|
shareable_content::UnsafeSCShareableContent,
|
||||||
|
content_filter::{UnsafeContentFilter, UnsafeInitParams},
|
||||||
|
stream_configuration::UnsafeStreamConfiguration,
|
||||||
|
stream::UnsafeSCStream,
|
||||||
|
stream_error_handler::UnsafeSCStreamError,
|
||||||
|
stream_output_handler::UnsafeSCStreamOutput,
|
||||||
|
cm_sample_buffer_ref::CMSampleBufferRef,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub struct SystemAudioCapture {
|
||||||
|
stream: Option<Id<UnsafeSCStream>>,
|
||||||
|
sample_rate: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct AudioOutputWrapper {
|
||||||
|
callback: Box<dyn Fn(&[f32]) + Send + Sync>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UnsafeSCStreamOutput for AudioOutputWrapper {
|
||||||
|
fn did_output_sample_buffer(&self, sample: Id<CMSampleBufferRef>, of_type: u8) {
|
||||||
|
if of_type == 1 { // Audio
|
||||||
|
let buffers = sample.get_av_audio_buffer_list();
|
||||||
|
for buffer in buffers {
|
||||||
|
// Buffer data is u8, we usually get F32 from SCK if configured.
|
||||||
|
// Assuming f32 (Floating Point) based on our config.
|
||||||
|
// We need to convert [u8] to [f32].
|
||||||
|
let data_u8 = buffer.data;
|
||||||
|
let data_f32: &[f32] = unsafe {
|
||||||
|
std::slice::from_raw_parts(
|
||||||
|
data_u8.as_ptr() as *const f32,
|
||||||
|
data_u8.len() / 4,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
(self.callback)(data_f32);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ErrorHandler;
|
||||||
|
impl UnsafeSCStreamError for ErrorHandler {
|
||||||
|
fn handle_error(&self) {
|
||||||
|
// eprintln!("Stream Error");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn check_permissions() -> bool {
|
||||||
|
UnsafeSCShareableContent::get().is_ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SystemAudioCapture {
|
||||||
|
pub fn new(sample_rate: u32) -> Self {
|
||||||
|
Self { stream: None, sample_rate }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn start<F>(&mut self, callback: F) -> Result<(), String>
|
||||||
|
where F: Fn(&[f32]) + Send + Sync + 'static {
|
||||||
|
|
||||||
|
let content = UnsafeSCShareableContent::get().map_err(|e| format!("Failed to get content"))?;
|
||||||
|
let displays = content.displays();
|
||||||
|
let display = displays.first().ok_or("No display found")?;
|
||||||
|
|
||||||
|
let filter_init = UnsafeInitParams::Display(display.clone());
|
||||||
|
let filter = UnsafeContentFilter::init(filter_init);
|
||||||
|
|
||||||
|
// Wait, 'pixel_format' is OSType. b"BGRA" is &[u8;4].
|
||||||
|
// FourCharCode::from_chars exists in crate::os_types::four_char_code but we didn't import it.
|
||||||
|
// Actually, we can just use the Default and overwrite fields.
|
||||||
|
// But better: use Default and only set what we need.
|
||||||
|
|
||||||
|
let mut config = UnsafeStreamConfiguration::default();
|
||||||
|
config.width = 100;
|
||||||
|
config.height = 100;
|
||||||
|
config.captures_audio = 1;
|
||||||
|
config.sample_rate = self.sample_rate;
|
||||||
|
config.channel_count = 2;
|
||||||
|
config.excludes_current_process_audio = 0;
|
||||||
|
|
||||||
|
let output_wrapper = AudioOutputWrapper {
|
||||||
|
callback: Box::new(callback),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Convert config to Id<UnsafeStreamConfigurationRef> using Into
|
||||||
|
let stream = UnsafeSCStream::init(filter, config.into(), ErrorHandler);
|
||||||
|
|
||||||
|
stream.add_stream_output(output_wrapper, 1); // 1 = Audio
|
||||||
|
|
||||||
|
stream.start_capture().map_err(|e| "Failed to start capture".to_string())?;
|
||||||
|
|
||||||
|
self.stream = Some(stream);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stop(&mut self) {
|
||||||
|
if let Some(stream) = &self.stream {
|
||||||
|
stream.stop_capture();
|
||||||
|
}
|
||||||
|
self.stream = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "Hearbit AI",
|
"productName": "Hearbit AI",
|
||||||
"version": "1.1.0",
|
"version": "1.2.3",
|
||||||
"identifier": "com.hearbit-ai.desktop",
|
"identifier": "com.hearbit-ai.desktop",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "npm run dev",
|
"beforeDevCommand": "npm run dev",
|
||||||
|
|||||||
163
src/App.tsx
163
src/App.tsx
@@ -1,4 +1,5 @@
|
|||||||
import { useState } from 'react';
|
import { useState, useEffect, useCallback } from 'react';
|
||||||
|
import { invoke } from '@tauri-apps/api/core';
|
||||||
import { Settings as SettingsIcon } from "lucide-react";
|
import { Settings as SettingsIcon } from "lucide-react";
|
||||||
import Settings, { SmtpConfig, AzureConfig } from "./components/Settings";
|
import Settings, { SmtpConfig, AzureConfig } from "./components/Settings";
|
||||||
import Recorder from "./components/Recorder";
|
import Recorder from "./components/Recorder";
|
||||||
@@ -7,6 +8,7 @@ import TranscriptionView from "./components/TranscriptionView";
|
|||||||
import Tabs from "./components/Tabs";
|
import Tabs from "./components/Tabs";
|
||||||
import MeetingsView from "./components/MeetingsView";
|
import MeetingsView from "./components/MeetingsView";
|
||||||
import HistoryView from "./components/HistoryView";
|
import HistoryView from "./components/HistoryView";
|
||||||
|
import Import from "./components/Import";
|
||||||
import ToastContainer, { ToastMessage, ToastType } from "./components/ui/Toast";
|
import ToastContainer, { ToastMessage, ToastType } from "./components/ui/Toast";
|
||||||
|
|
||||||
export interface PromptTemplate {
|
export interface PromptTemplate {
|
||||||
@@ -24,8 +26,8 @@ export interface EmailTemplate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
const [view, setView] = useState<'recorder' | 'settings' | 'transcription' | 'meetings' | 'history'>('recorder');
|
const [view, setView] = useState<'recorder' | 'settings' | 'transcription' | 'meetings' | 'history' | 'import'>('recorder');
|
||||||
const [lastTab, setLastTab] = useState<'recorder' | 'transcription' | 'meetings' | 'history'>('recorder');
|
const [lastTab, setLastTab] = useState<'recorder' | 'transcription' | 'meetings' | 'history' | 'import'>('recorder');
|
||||||
|
|
||||||
|
|
||||||
// Auto-start recording state to handle "Join & Record" transition
|
// Auto-start recording state to handle "Join & Record" transition
|
||||||
@@ -59,6 +61,15 @@ function App() {
|
|||||||
return localStorage.getItem('hearbit_selected_model') || 'mixtral';
|
return localStorage.getItem('hearbit_selected_model') || 'mixtral';
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Daily Backup State
|
||||||
|
const [dailyBackupEnabled, setDailyBackupEnabled] = useState(() => localStorage.getItem('hearbit_daily_backup_enabled') === 'true');
|
||||||
|
const [dailyBackupPath, setDailyBackupPath] = useState(() => localStorage.getItem('hearbit_daily_backup_path') || '');
|
||||||
|
const [lastBackupDate, setLastBackupDate] = useState(() => localStorage.getItem('hearbit_last_backup_date') || '');
|
||||||
|
const [blockedApps, setBlockedApps] = useState<string[]>(() => {
|
||||||
|
const saved = localStorage.getItem('hearbit_blocked_apps');
|
||||||
|
return saved ? JSON.parse(saved) : [];
|
||||||
|
});
|
||||||
|
|
||||||
const handleModelChange = (model: string) => {
|
const handleModelChange = (model: string) => {
|
||||||
setSelectedModel(model);
|
setSelectedModel(model);
|
||||||
localStorage.setItem('hearbit_selected_model', model);
|
localStorage.setItem('hearbit_selected_model', model);
|
||||||
@@ -233,7 +244,10 @@ Thanks!`
|
|||||||
newSavePath: string,
|
newSavePath: string,
|
||||||
newSmtp: SmtpConfig,
|
newSmtp: SmtpConfig,
|
||||||
newAzure: AzureConfig,
|
newAzure: AzureConfig,
|
||||||
newEmailTemplates: EmailTemplate[]
|
newEmailTemplates: EmailTemplate[],
|
||||||
|
newDailyBackupEnabled: boolean,
|
||||||
|
newDailyBackupPath: string,
|
||||||
|
newBlockedApps: string[]
|
||||||
) => {
|
) => {
|
||||||
setApiKey(newApiKey);
|
setApiKey(newApiKey);
|
||||||
setProductId(newProductId);
|
setProductId(newProductId);
|
||||||
@@ -243,14 +257,22 @@ Thanks!`
|
|||||||
setAzureConfig(newAzure);
|
setAzureConfig(newAzure);
|
||||||
setEmailTemplates(newEmailTemplates);
|
setEmailTemplates(newEmailTemplates);
|
||||||
|
|
||||||
localStorage.setItem('infomaniak_api_key', newApiKey);
|
setDailyBackupEnabled(newDailyBackupEnabled);
|
||||||
localStorage.setItem('infomaniak_product_id', newProductId);
|
setDailyBackupPath(newDailyBackupPath);
|
||||||
localStorage.setItem('infomaniak_prompts', JSON.stringify(newPrompts));
|
setBlockedApps(newBlockedApps);
|
||||||
localStorage.setItem('infomaniak_save_path', newSavePath);
|
|
||||||
|
localStorage.setItem('hearbit_api_key', newApiKey);
|
||||||
|
localStorage.setItem('hearbit_product_id', newProductId);
|
||||||
|
localStorage.setItem('hearbit_prompts', JSON.stringify(newPrompts));
|
||||||
|
localStorage.setItem('hearbit_save_path', newSavePath);
|
||||||
localStorage.setItem('hearbit_smtp_config', JSON.stringify(newSmtp));
|
localStorage.setItem('hearbit_smtp_config', JSON.stringify(newSmtp));
|
||||||
localStorage.setItem('hearbit_azure_config', JSON.stringify(newAzure));
|
localStorage.setItem('hearbit_azure_config', JSON.stringify(newAzure));
|
||||||
localStorage.setItem('hearbit_email_templates', JSON.stringify(newEmailTemplates));
|
localStorage.setItem('hearbit_email_templates', JSON.stringify(newEmailTemplates));
|
||||||
|
|
||||||
|
localStorage.setItem('hearbit_daily_backup_enabled', String(newDailyBackupEnabled));
|
||||||
|
localStorage.setItem('hearbit_daily_backup_path', newDailyBackupPath);
|
||||||
|
localStorage.setItem('hearbit_blocked_apps', JSON.stringify(newBlockedApps));
|
||||||
|
|
||||||
setView(lastTab);
|
setView(lastTab);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -311,6 +333,14 @@ Thanks!`
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleRenameHistory = (id: string, newSubject: string) => {
|
||||||
|
const newHistory = history.map(item =>
|
||||||
|
item.id === id ? { ...item, subject: newSubject } : item
|
||||||
|
);
|
||||||
|
setHistory(newHistory);
|
||||||
|
localStorage.setItem('infomaniak_history', JSON.stringify(newHistory));
|
||||||
|
};
|
||||||
|
|
||||||
const handleDeleteHistory = (id: string) => {
|
const handleDeleteHistory = (id: string) => {
|
||||||
const newHistory = history.filter(item => item.id !== id);
|
const newHistory = history.filter(item => item.id !== id);
|
||||||
setHistory(newHistory);
|
setHistory(newHistory);
|
||||||
@@ -323,6 +353,80 @@ Thanks!`
|
|||||||
setView('transcription'); // Switch to Transcription view to see content
|
setView('transcription'); // Switch to Transcription view to see content
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const performBackup = useCallback(async (isAuto = false) => {
|
||||||
|
try {
|
||||||
|
if (isAuto && !dailyBackupEnabled) return;
|
||||||
|
|
||||||
|
const dataToBackup = {
|
||||||
|
apiKey,
|
||||||
|
productId,
|
||||||
|
prompts,
|
||||||
|
savePath,
|
||||||
|
smtp: smtpConfig,
|
||||||
|
azure: azureConfig,
|
||||||
|
emailTemplates,
|
||||||
|
history, // Including history!
|
||||||
|
// Also include daily backup settings so they persist on restore
|
||||||
|
dailyBackup: {
|
||||||
|
enabled: dailyBackupEnabled,
|
||||||
|
path: dailyBackupPath,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Always save as JSON (no encryption)
|
||||||
|
const content = JSON.stringify(dataToBackup, null, 2);
|
||||||
|
|
||||||
|
const dateStr = new Date().toISOString().slice(0, 10);
|
||||||
|
const fileName = `hearbit_backup_${isAuto ? 'auto_' : ''}${dateStr}.json`;
|
||||||
|
|
||||||
|
// Determine path: use specific daily backup path, or general savePath
|
||||||
|
const targetDir = (isAuto ? dailyBackupPath : savePath) || savePath;
|
||||||
|
|
||||||
|
if (!targetDir) {
|
||||||
|
if (!isAuto) addToast('No backup path configured.', 'error');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fullPath = `${targetDir}/${fileName}`;
|
||||||
|
|
||||||
|
await invoke('save_text_file', { path: fullPath, content });
|
||||||
|
|
||||||
|
if (isAuto) {
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
setLastBackupDate(now);
|
||||||
|
localStorage.setItem('hearbit_last_backup_date', now);
|
||||||
|
console.log("Auto-backup completed:", fullPath);
|
||||||
|
} else {
|
||||||
|
addToast(`Backup saved to ${fullPath}`, 'success');
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Backup failed:", e);
|
||||||
|
if (!isAuto) addToast(`Backup failed: ${e}`, 'error');
|
||||||
|
}
|
||||||
|
}, [apiKey, productId, prompts, savePath, smtpConfig, azureConfig, emailTemplates, history, dailyBackupEnabled, dailyBackupPath]);
|
||||||
|
|
||||||
|
// Check for Daily Backup on Mount / State Change
|
||||||
|
useEffect(() => {
|
||||||
|
if (!dailyBackupEnabled) return;
|
||||||
|
|
||||||
|
const check = async () => {
|
||||||
|
const today = new Date().toISOString().slice(0, 10);
|
||||||
|
const last = lastBackupDate ? lastBackupDate.slice(0, 10) : '';
|
||||||
|
|
||||||
|
if (last !== today) {
|
||||||
|
// Perform backup
|
||||||
|
await performBackup(true);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
check();
|
||||||
|
}, 5000); // Check 5s after load to allow state to settle
|
||||||
|
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, [dailyBackupEnabled, lastBackupDate, performBackup]);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -343,7 +447,7 @@ Thanks!`
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Tabs
|
<Tabs
|
||||||
currentTab={view as 'recorder' | 'transcription' | 'meetings' | 'history'}
|
currentTab={view as 'recorder' | 'transcription' | 'meetings' | 'history' | 'import'}
|
||||||
onTabChange={(t) => setView(t)}
|
onTabChange={(t) => setView(t)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -351,7 +455,8 @@ Thanks!`
|
|||||||
|
|
||||||
<div className="flex-1 flex h-full overflow-hidden relative">
|
<div className="flex-1 flex h-full overflow-hidden relative">
|
||||||
<div className="flex-1 flex flex-col h-full overflow-hidden relative">
|
<div className="flex-1 flex flex-col h-full overflow-hidden relative">
|
||||||
{view === 'recorder' && (
|
{/* Recorder - Persistent (Hidden via CSS to keep recording alive) */}
|
||||||
|
<div className="flex-1 flex flex-col h-full overflow-hidden" style={{ display: view === 'recorder' ? 'flex' : 'none' }}>
|
||||||
<Recorder
|
<Recorder
|
||||||
apiKey={apiKey}
|
apiKey={apiKey}
|
||||||
productId={productId}
|
productId={productId}
|
||||||
@@ -377,8 +482,10 @@ Thanks!`
|
|||||||
addToast={addToast}
|
addToast={addToast}
|
||||||
selectedModel={selectedModel}
|
selectedModel={selectedModel}
|
||||||
onModelChange={handleModelChange}
|
onModelChange={handleModelChange}
|
||||||
|
isVisible={view === 'recorder'}
|
||||||
|
blockedApps={blockedApps}
|
||||||
/>
|
/>
|
||||||
)}
|
</div>
|
||||||
|
|
||||||
{view === 'transcription' && (
|
{view === 'transcription' && (
|
||||||
<TranscriptionView
|
<TranscriptionView
|
||||||
@@ -410,6 +517,10 @@ Thanks!`
|
|||||||
history={history}
|
history={history}
|
||||||
onLoad={handleLoadHistory}
|
onLoad={handleLoadHistory}
|
||||||
onDelete={handleDeleteHistory}
|
onDelete={handleDeleteHistory}
|
||||||
|
onRename={handleRenameHistory}
|
||||||
|
smtpConfig={smtpConfig}
|
||||||
|
emailTemplates={emailTemplates}
|
||||||
|
addToast={addToast}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -429,6 +540,23 @@ Thanks!`
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{view === 'import' && (
|
||||||
|
<Import
|
||||||
|
apiKey={apiKey}
|
||||||
|
productId={productId}
|
||||||
|
prompts={prompts}
|
||||||
|
selectedModel={selectedModel}
|
||||||
|
onSaveToHistory={handleSaveToHistory}
|
||||||
|
onComplete={() => setView('transcription')}
|
||||||
|
addToast={addToast}
|
||||||
|
setTranscription={setTranscription}
|
||||||
|
setSummary={setSummary}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
{view === 'settings' && (
|
{view === 'settings' && (
|
||||||
@@ -442,6 +570,19 @@ Thanks!`
|
|||||||
smtpConfig={smtpConfig}
|
smtpConfig={smtpConfig}
|
||||||
azureConfig={azureConfig}
|
azureConfig={azureConfig}
|
||||||
emailTemplates={emailTemplates}
|
emailTemplates={emailTemplates}
|
||||||
|
|
||||||
|
// Pass new backup props
|
||||||
|
dailyBackupEnabled={dailyBackupEnabled}
|
||||||
|
dailyBackupPath={dailyBackupPath}
|
||||||
|
lastBackupDate={lastBackupDate}
|
||||||
|
|
||||||
|
// Pass history and update callback
|
||||||
|
history={history}
|
||||||
|
onHistoryUpdate={(newHistory) => {
|
||||||
|
setHistory(newHistory);
|
||||||
|
localStorage.setItem('infomaniak_history', JSON.stringify(newHistory));
|
||||||
|
}}
|
||||||
|
blockedApps={blockedApps}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -64,9 +64,14 @@ const EmailPreviewModal: React.FC<EmailPreviewModalProps> = ({
|
|||||||
const [activeTab, setActiveTab] = useState<'preview' | 'source'>('preview');
|
const [activeTab, setActiveTab] = useState<'preview' | 'source'>('preview');
|
||||||
|
|
||||||
const generateHtmlBody = (content: string, title: string) => {
|
const generateHtmlBody = (content: string, title: string) => {
|
||||||
// Simple heuristic: if it looks like HTML, treat as HTML. Otherwise, markdown.
|
// Check if it's a full HTML document
|
||||||
const isHtml = /^\s*<(!DOCTYPE|html|div|p|table)/i.test(content);
|
if (/^\s*<!DOCTYPE html/i.test(content) || /^\s*<html/i.test(content)) {
|
||||||
const formattedBody = isHtml ? content : formatMarkdownToHtml(content);
|
return content;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Simple heuristic: if it looks like HTML fragment (div, p, table), treat as HTML. Otherwise, markdown.
|
||||||
|
const isHtmlFragment = /^\s*<(div|p|table|section|header|footer)/i.test(content);
|
||||||
|
const formattedBody = isHtmlFragment ? content : formatMarkdownToHtml(content);
|
||||||
|
|
||||||
return `
|
return `
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
@@ -111,14 +116,17 @@ const EmailPreviewModal: React.FC<EmailPreviewModalProps> = ({
|
|||||||
// Replace placeholders
|
// Replace placeholders
|
||||||
const dateStr = new Date().toLocaleDateString();
|
const dateStr = new Date().toLocaleDateString();
|
||||||
let newSub = tmpl.subject.replace(/{{date}}/g, dateStr).replace(/{{subject}}/g, "Meeting");
|
let newSub = tmpl.subject.replace(/{{date}}/g, dateStr).replace(/{{subject}}/g, "Meeting");
|
||||||
// Note: We don't have the original 'recordingSubject' here easily without more prop drilling,
|
|
||||||
// so we default to "Meeting" or user can edit.
|
// Clean up JSON if necessary (e.g. remove markdown code blocks ```json ... ```)
|
||||||
// Actually, initialSubject usually contains "Meeting Summary", so we could parse it, but for now date/summary is most important.
|
let cleanSummary = initialBody;
|
||||||
|
if (initialBody.trim().startsWith('```')) {
|
||||||
|
cleanSummary = initialBody.replace(/^```(json)?/i, '').replace(/```$/, '').trim();
|
||||||
|
}
|
||||||
|
|
||||||
let newBody = tmpl.body
|
let newBody = tmpl.body
|
||||||
.replace(/{{date}}/g, dateStr)
|
.replace(/{{date}}/g, dateStr)
|
||||||
.replace(/{{subject}}/g, "the meeting")
|
.replace(/{{subject}}/g, "the meeting")
|
||||||
.replace(/{{summary}}/g, initialBody);
|
.replace(/{{summary}}/g, cleanSummary);
|
||||||
|
|
||||||
setSubject(newSub);
|
setSubject(newSub);
|
||||||
setBody(generateHtmlBody(newBody, newSub));
|
setBody(generateHtmlBody(newBody, newSub));
|
||||||
@@ -242,7 +250,7 @@ const EmailPreviewModal: React.FC<EmailPreviewModalProps> = ({
|
|||||||
srcDoc={body}
|
srcDoc={body}
|
||||||
className="w-full h-full border-none"
|
className="w-full h-full border-none"
|
||||||
title="Email Preview"
|
title="Email Preview"
|
||||||
sandbox="allow-same-origin"
|
sandbox="allow-same-origin allow-scripts"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
import { FileText, Trash2, Calendar } from 'lucide-react';
|
import { FileText, Trash2, Calendar, Pencil, Check, X, Mail } from 'lucide-react';
|
||||||
|
import { useState } from 'react';
|
||||||
|
import EmailPreviewModal from './EmailPreviewModal';
|
||||||
|
import { SmtpConfig } from './Settings';
|
||||||
|
import { EmailTemplate } from '../App';
|
||||||
|
import { ToastType } from './ui/Toast';
|
||||||
|
|
||||||
interface HistoryItem {
|
interface HistoryItem {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -13,9 +18,34 @@ interface HistoryViewProps {
|
|||||||
history: HistoryItem[];
|
history: HistoryItem[];
|
||||||
onLoad: (item: HistoryItem) => void;
|
onLoad: (item: HistoryItem) => void;
|
||||||
onDelete: (id: string) => void;
|
onDelete: (id: string) => void;
|
||||||
|
onRename: (id: string, newSubject: string) => void;
|
||||||
|
smtpConfig: SmtpConfig;
|
||||||
|
emailTemplates: EmailTemplate[];
|
||||||
|
addToast: (message: string, type: ToastType, duration?: number) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function HistoryView({ history, onLoad, onDelete }: HistoryViewProps) {
|
export default function HistoryView({ history, onLoad, onDelete, onRename, smtpConfig, emailTemplates, addToast }: HistoryViewProps) {
|
||||||
|
const [editingId, setEditingId] = useState<string | null>(null);
|
||||||
|
const [editValue, setEditValue] = useState("");
|
||||||
|
const [emailModalItem, setEmailModalItem] = useState<HistoryItem | null>(null);
|
||||||
|
|
||||||
|
const startEditing = (item: HistoryItem) => {
|
||||||
|
setEditingId(item.id);
|
||||||
|
setEditValue(item.subject || "Untitled Recording");
|
||||||
|
};
|
||||||
|
|
||||||
|
const saveEdit = () => {
|
||||||
|
if (editingId && editValue.trim()) {
|
||||||
|
onRename(editingId, editValue.trim());
|
||||||
|
setEditingId(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const cancelEdit = () => {
|
||||||
|
setEditingId(null);
|
||||||
|
setEditValue("");
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col w-full h-full bg-background p-6">
|
<div className="flex flex-col w-full h-full bg-background p-6">
|
||||||
<h1 className="text-2xl font-bold mb-6 flex items-center gap-2">
|
<h1 className="text-2xl font-bold mb-6 flex items-center gap-2">
|
||||||
@@ -33,35 +63,87 @@ export default function HistoryView({ history, onLoad, onDelete }: HistoryViewPr
|
|||||||
{history.map(item => (
|
{history.map(item => (
|
||||||
<div key={item.id} className="bg-card border border-border rounded-xl p-4 hover:shadow-md transition-all group">
|
<div key={item.id} className="bg-card border border-border rounded-xl p-4 hover:shadow-md transition-all group">
|
||||||
<div className="flex justify-between items-start">
|
<div className="flex justify-between items-start">
|
||||||
<div
|
<div className="flex-1">
|
||||||
className="flex-1 cursor-pointer"
|
{editingId === item.id ? (
|
||||||
onClick={() => onLoad(item)}
|
<div className="flex items-center gap-2 mb-2" onClick={(e) => e.stopPropagation()}>
|
||||||
>
|
<input
|
||||||
<h3 className="text-lg font-semibold group-hover:text-primary transition-colors mb-1">
|
autoFocus
|
||||||
{item.subject || "Untitled Recording"}
|
type="text"
|
||||||
</h3>
|
className="flex-1 bg-background border border-input rounded px-2 py-1 text-sm font-semibold focus:outline-none focus:ring-1 focus:ring-ring"
|
||||||
<div className="flex items-center gap-2 text-xs text-muted-foreground mb-2">
|
value={editValue}
|
||||||
|
onChange={(e) => setEditValue(e.target.value)}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter') saveEdit();
|
||||||
|
if (e.key === 'Escape') cancelEdit();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<button onClick={saveEdit} className="p-1 text-green-500 hover:bg-green-500/10 rounded">
|
||||||
|
<Check size={16} />
|
||||||
|
</button>
|
||||||
|
<button onClick={cancelEdit} className="p-1 text-muted-foreground hover:bg-muted rounded">
|
||||||
|
<X size={16} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div
|
||||||
|
className="cursor-pointer"
|
||||||
|
onClick={() => onLoad(item)}
|
||||||
|
>
|
||||||
|
<h3 className="text-lg font-semibold group-hover:text-primary transition-colors mb-1 flex items-center gap-2">
|
||||||
|
{item.subject || "Untitled Recording"}
|
||||||
|
<button
|
||||||
|
onClick={(e) => { e.stopPropagation(); startEditing(item); }}
|
||||||
|
className="opacity-0 group-hover:opacity-100 text-muted-foreground hover:text-foreground p-1 rounded hover:bg-muted transition-all"
|
||||||
|
title="Rename"
|
||||||
|
>
|
||||||
|
<Pencil size={14} />
|
||||||
|
</button>
|
||||||
|
</h3>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2 text-xs text-muted-foreground mb-2" onClick={() => !editingId && onLoad(item)}>
|
||||||
<Calendar size={12} />
|
<Calendar size={12} />
|
||||||
{item.date}
|
{item.date}
|
||||||
{item.filename && <span className="bg-secondary px-1.5 py-0.5 rounded text-[10px] font-mono">{item.filename}</span>}
|
{item.filename && <span className="bg-secondary px-1.5 py-0.5 rounded text-[10px] font-mono">{item.filename}</span>}
|
||||||
</div>
|
</div>
|
||||||
<p className="text-sm text-foreground/70 line-clamp-2">
|
<p className="text-sm text-foreground/70 line-clamp-2 cursor-pointer" onClick={() => !editingId && onLoad(item)}>
|
||||||
{item.summary ? item.summary.substring(0, 150) + "..." : "No summary available."}
|
{item.summary ? item.summary.substring(0, 150) + "..." : "No summary available."}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button
|
<div className="flex items-center gap-2">
|
||||||
onClick={(e) => { e.stopPropagation(); onDelete(item.id); }}
|
<button
|
||||||
className="text-muted-foreground hover:text-destructive p-2 rounded-lg hover:bg-destructive/10 transition-colors opacity-0 group-hover:opacity-100"
|
onClick={(e) => { e.stopPropagation(); setEmailModalItem(item); }}
|
||||||
title="Delete"
|
className="text-muted-foreground hover:text-primary p-2 rounded-lg hover:bg-primary/10 transition-colors opacity-0 group-hover:opacity-100"
|
||||||
>
|
title="Send Email"
|
||||||
<Trash2 size={18} />
|
>
|
||||||
</button>
|
<Mail size={18} />
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={(e) => { e.stopPropagation(); onDelete(item.id); }}
|
||||||
|
className="text-muted-foreground hover:text-destructive p-2 rounded-lg hover:bg-destructive/10 transition-colors opacity-0 group-hover:opacity-100"
|
||||||
|
title="Delete"
|
||||||
|
>
|
||||||
|
<Trash2 size={18} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<EmailPreviewModal
|
||||||
|
isOpen={emailModalItem !== null}
|
||||||
|
onClose={() => setEmailModalItem(null)}
|
||||||
|
initialRecipients={[]}
|
||||||
|
initialSubject={emailModalItem?.subject || "Meeting Summary"}
|
||||||
|
initialBody={emailModalItem?.summary || ""}
|
||||||
|
emailTemplates={emailTemplates}
|
||||||
|
smtpConfig={smtpConfig ? { ...smtpConfig, port: Number(smtpConfig.port) } : null}
|
||||||
|
addToast={addToast}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
411
src/components/Import.tsx
Normal file
411
src/components/Import.tsx
Normal file
@@ -0,0 +1,411 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { Upload, FileAudio, X, Check, Loader2 } from 'lucide-react';
|
||||||
|
import { invoke } from "@tauri-apps/api/core";
|
||||||
|
import { open } from '@tauri-apps/plugin-dialog';
|
||||||
|
import logo from '../assets/logo.png';
|
||||||
|
|
||||||
|
interface PromptTemplate {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
content: string;
|
||||||
|
keywords?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ImportProps {
|
||||||
|
apiKey: string;
|
||||||
|
productId: string;
|
||||||
|
prompts: PromptTemplate[];
|
||||||
|
selectedModel: string;
|
||||||
|
onSaveToHistory: (transcription: string, summary: string) => void;
|
||||||
|
onComplete: () => void; // Navigate to Transcription view
|
||||||
|
addToast: (msg: string, type: 'success' | 'error' | 'info', duration?: number) => void;
|
||||||
|
setTranscription: (text: string) => void;
|
||||||
|
setSummary: (text: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AudioMetadata {
|
||||||
|
duration: number;
|
||||||
|
size: number;
|
||||||
|
format: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
type ProcessingStage = 'idle' | 'validating' | 'transcribing' | 'summarizing' | 'complete';
|
||||||
|
|
||||||
|
const SUPPORTED_FORMATS = ['mp3', 'mp4', 'm4a', 'wav', 'flac', 'ogg', 'aac', 'wma'];
|
||||||
|
|
||||||
|
const Import: React.FC<ImportProps> = ({
|
||||||
|
apiKey,
|
||||||
|
productId,
|
||||||
|
prompts,
|
||||||
|
selectedModel,
|
||||||
|
onSaveToHistory,
|
||||||
|
onComplete,
|
||||||
|
addToast,
|
||||||
|
setTranscription,
|
||||||
|
setSummary
|
||||||
|
}) => {
|
||||||
|
const [selectedFile, setSelectedFile] = useState<string | null>(null);
|
||||||
|
const [metadata, setMetadata] = useState<AudioMetadata | null>(null);
|
||||||
|
const [meetingTitle, setMeetingTitle] = useState('');
|
||||||
|
const [stage, setStage] = useState<ProcessingStage>('idle');
|
||||||
|
const [selectedPromptId, setSelectedPromptId] = useState<string>('');
|
||||||
|
|
||||||
|
// Set default prompt
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (prompts.length > 0 && !selectedPromptId) {
|
||||||
|
setSelectedPromptId(prompts[0].id);
|
||||||
|
}
|
||||||
|
}, [prompts, selectedPromptId]);
|
||||||
|
|
||||||
|
const validateFile = (filePath: string): boolean => {
|
||||||
|
const extension = filePath.split('.').pop()?.toLowerCase();
|
||||||
|
if (!extension || !SUPPORTED_FORMATS.includes(extension)) {
|
||||||
|
addToast(`Unsupported format. Supported: ${SUPPORTED_FORMATS.join(', ').toUpperCase()}`, 'error', 5000);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const extractFilename = (path: string): string => {
|
||||||
|
const parts = path.split(/[/\\]/);
|
||||||
|
const filename = parts[parts.length - 1];
|
||||||
|
return filename.replace(/\.[^/.]+$/, ''); // Remove extension
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatDuration = (seconds: number): string => {
|
||||||
|
const mins = Math.floor(seconds / 60);
|
||||||
|
const secs = Math.floor(seconds % 60);
|
||||||
|
return `${mins}:${secs.toString().padStart(2, '0')}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatSize = (bytes: number): string => {
|
||||||
|
if (bytes < 1024 * 1024) {
|
||||||
|
return `${(bytes / 1024).toFixed(1)} KB`;
|
||||||
|
}
|
||||||
|
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFileSelect = async (filePath: string) => {
|
||||||
|
if (!validateFile(filePath)) return;
|
||||||
|
|
||||||
|
setStage('validating');
|
||||||
|
setSelectedFile(filePath);
|
||||||
|
setMeetingTitle(extractFilename(filePath));
|
||||||
|
|
||||||
|
try {
|
||||||
|
const meta = await invoke<AudioMetadata>('get_audio_metadata', { filePath });
|
||||||
|
setMetadata(meta);
|
||||||
|
setStage('idle');
|
||||||
|
addToast('File loaded successfully', 'success', 2000);
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Metadata error:', e);
|
||||||
|
setMetadata(null);
|
||||||
|
setStage('idle');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleManualSelect = async () => {
|
||||||
|
try {
|
||||||
|
const selected = await open({
|
||||||
|
multiple: false,
|
||||||
|
filters: [{
|
||||||
|
name: 'Audio/Video',
|
||||||
|
extensions: SUPPORTED_FORMATS
|
||||||
|
}]
|
||||||
|
});
|
||||||
|
|
||||||
|
if (selected && typeof selected === 'string') {
|
||||||
|
handleFileSelect(selected);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error('File picker error:', e);
|
||||||
|
addToast('Failed to open file picker', 'error');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleProcess = async () => {
|
||||||
|
if (!selectedFile) return;
|
||||||
|
if (!apiKey || !productId) {
|
||||||
|
addToast('Please configure API key in Settings', 'error');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Check file extension
|
||||||
|
const isWav = selectedFile.toLowerCase().endsWith('.wav');
|
||||||
|
let processFile = selectedFile;
|
||||||
|
|
||||||
|
// Convert WAV to MP3 if needed
|
||||||
|
if (isWav) {
|
||||||
|
setStage('validating');
|
||||||
|
addToast('Converting WAV to MP3...', 'info', 2000);
|
||||||
|
processFile = await invoke<string>('convert_to_mp3', { wavPath: selectedFile });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get file size to check if chunking needed
|
||||||
|
const metadata = await invoke<AudioMetadata>('get_audio_metadata', { filePath: processFile });
|
||||||
|
const sizeMB = metadata.size / (1024 * 1024);
|
||||||
|
|
||||||
|
let transText = '';
|
||||||
|
|
||||||
|
// Check if chunking needed for large files
|
||||||
|
if (sizeMB >= 18) {
|
||||||
|
// CHUNKING PATH for large files
|
||||||
|
setStage('validating');
|
||||||
|
addToast(`Large file (${sizeMB.toFixed(1)}MB). Splitting into chunks...`, 'info', 4000);
|
||||||
|
|
||||||
|
const chunks = await invoke<string[]>('chunk_audio', {
|
||||||
|
filePath: processFile,
|
||||||
|
chunkMinutes: 10
|
||||||
|
});
|
||||||
|
|
||||||
|
addToast(`Processing ${chunks.length} chunks...`, 'info', 4000);
|
||||||
|
|
||||||
|
let allTranscriptions: string[] = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < chunks.length; i++) {
|
||||||
|
setStage('transcribing');
|
||||||
|
addToast(`Transcribing chunk ${i + 1}/${chunks.length}...`, 'info', 2000);
|
||||||
|
const chunkText = await invoke<string>('transcribe_audio', {
|
||||||
|
filePath: chunks[i],
|
||||||
|
apiKey,
|
||||||
|
productId
|
||||||
|
});
|
||||||
|
allTranscriptions.push(chunkText);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Merge transcriptions
|
||||||
|
transText = allTranscriptions.join('\n\n--- Next Segment ---\n\n');
|
||||||
|
addToast('All chunks transcribed successfully!', 'success', 3000);
|
||||||
|
} else {
|
||||||
|
// NORMAL PATH for small files
|
||||||
|
setStage('transcribing');
|
||||||
|
transText = await invoke<string>('transcribe_audio', {
|
||||||
|
filePath: processFile,
|
||||||
|
apiKey,
|
||||||
|
productId
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
setTranscription(transText);
|
||||||
|
|
||||||
|
if (!transText || transText.trim().length === 0) {
|
||||||
|
addToast('No speech detected in file', 'error');
|
||||||
|
setStage('idle');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Smart prompt selection (copied from Recorder.tsx)
|
||||||
|
let activePrompt = prompts.find(p => p.id === selectedPromptId);
|
||||||
|
const lowerText = transText.toLowerCase();
|
||||||
|
let bestMatchId = selectedPromptId;
|
||||||
|
let maxMatches = 0;
|
||||||
|
|
||||||
|
for (const p of prompts) {
|
||||||
|
if (!p.keywords) continue;
|
||||||
|
let matches = 0;
|
||||||
|
for (const kw of p.keywords) {
|
||||||
|
if (lowerText.includes(kw.toLowerCase())) {
|
||||||
|
matches++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (matches > maxMatches) {
|
||||||
|
maxMatches = matches;
|
||||||
|
bestMatchId = p.id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bestMatchId !== selectedPromptId) {
|
||||||
|
const newPrompt = prompts.find(p => p.id === bestMatchId);
|
||||||
|
if (newPrompt) {
|
||||||
|
addToast(`Smart Select: Switched to "${newPrompt.name}"`, 'info', 3000);
|
||||||
|
activePrompt = newPrompt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const promptContent = activePrompt ? activePrompt.content : "Summarize this.";
|
||||||
|
|
||||||
|
setStage('summarizing');
|
||||||
|
const sumText = await invoke<string>('summarize_text', {
|
||||||
|
text: transText,
|
||||||
|
apiKey,
|
||||||
|
productId,
|
||||||
|
prompt: promptContent,
|
||||||
|
model: selectedModel
|
||||||
|
});
|
||||||
|
setSummary(sumText);
|
||||||
|
|
||||||
|
// Save to history
|
||||||
|
onSaveToHistory(transText, sumText);
|
||||||
|
|
||||||
|
setStage('complete');
|
||||||
|
addToast('Import complete!', 'success', 3000);
|
||||||
|
|
||||||
|
// Navigate to Transcription view
|
||||||
|
setTimeout(() => {
|
||||||
|
onComplete();
|
||||||
|
}, 1000);
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Processing error:', e);
|
||||||
|
addToast(`Error: ${e}`, 'error');
|
||||||
|
setStage('idle');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleReset = () => {
|
||||||
|
setSelectedFile(null);
|
||||||
|
setMetadata(null);
|
||||||
|
setMeetingTitle('');
|
||||||
|
setStage('idle');
|
||||||
|
};
|
||||||
|
|
||||||
|
const getStageInfo = () => {
|
||||||
|
switch (stage) {
|
||||||
|
case 'validating': return { icon: Loader2, text: 'Validating file...', color: 'text-blue-500' };
|
||||||
|
case 'transcribing': return { icon: Loader2, text: 'Transcribing audio...', color: 'text-purple-500' };
|
||||||
|
case 'summarizing': return { icon: Loader2, text: 'Generating summary...', color: 'text-green-500' };
|
||||||
|
case 'complete': return { icon: Check, text: 'Complete!', color: 'text-green-500' };
|
||||||
|
default: return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const stageInfo = getStageInfo();
|
||||||
|
const isProcessing = stage !== 'idle' && stage !== 'complete';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col w-full h-full bg-background relative">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="w-full flex justify-center items-center p-4 shrink-0">
|
||||||
|
<img src={localStorage.getItem('customLogo') || logo} alt="Logo" className="h-10 object-contain" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Main Content */}
|
||||||
|
<div className="flex-1 overflow-y-auto px-6 pb-6 flex flex-col items-center">
|
||||||
|
<h1 className="text-xl font-bold mb-2 text-foreground">Import Audio File</h1>
|
||||||
|
<p className="text-muted-foreground mb-6 text-center text-sm">
|
||||||
|
Select an audio file for transcription and summarization
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{/* File Selection Zone */}
|
||||||
|
<div
|
||||||
|
className={`w-full max-w-md border-2 border-dashed rounded-lg p-8 mb-6 transition-all ${selectedFile
|
||||||
|
? 'border-green-500 bg-green-500/5'
|
||||||
|
: 'border-border bg-secondary/30'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="flex flex-col items-center justify-center gap-4">
|
||||||
|
{selectedFile ? (
|
||||||
|
<>
|
||||||
|
<FileAudio size={48} className="text-green-500" />
|
||||||
|
<div className="text-center">
|
||||||
|
<p className="font-semibold text-foreground">{meetingTitle}</p>
|
||||||
|
{metadata && (
|
||||||
|
<p className="text-xs text-muted-foreground mt-1">
|
||||||
|
{formatDuration(metadata.duration)} • {formatSize(metadata.size)} • {metadata.format.toUpperCase()}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={handleReset}
|
||||||
|
className="text-xs text-muted-foreground hover:text-foreground flex items-center gap-1"
|
||||||
|
>
|
||||||
|
<X size={14} /> Change file
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Upload size={48} className="text-muted-foreground" />
|
||||||
|
<div className="text-center">
|
||||||
|
<p className="font-semibold text-foreground">Select Audio File</p>
|
||||||
|
<p className="text-xs text-muted-foreground mt-1">
|
||||||
|
Click below to browse your files
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={handleManualSelect}
|
||||||
|
disabled={isProcessing}
|
||||||
|
className="px-6 py-3 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 disabled:opacity-50 text-base font-semibold transition-all shadow-md hover:shadow-lg"
|
||||||
|
>
|
||||||
|
Browse Files
|
||||||
|
</button>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Supported: MP3, MP4, WAV, M4A, FLAC, OGG, AAC, WMA
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Configuration Section */}
|
||||||
|
{selectedFile && (
|
||||||
|
<div className="w-full max-w-md space-y-4">
|
||||||
|
{/* Meeting Title */}
|
||||||
|
<div>
|
||||||
|
<label className="text-xs font-semibold text-muted-foreground uppercase tracking-wider block mb-1">
|
||||||
|
Meeting Title
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={meetingTitle}
|
||||||
|
onChange={(e) => setMeetingTitle(e.target.value)}
|
||||||
|
disabled={isProcessing}
|
||||||
|
className="w-full p-2 text-sm bg-secondary rounded border border-border outline-none focus:ring-2 focus:ring-primary disabled:opacity-50"
|
||||||
|
placeholder="Enter meeting title..."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* AI Template */}
|
||||||
|
<div>
|
||||||
|
<label className="text-xs font-semibold text-muted-foreground uppercase tracking-wider block mb-1">
|
||||||
|
AI Template
|
||||||
|
</label>
|
||||||
|
<select
|
||||||
|
value={selectedPromptId}
|
||||||
|
onChange={(e) => setSelectedPromptId(e.target.value)}
|
||||||
|
disabled={isProcessing || prompts.length === 0}
|
||||||
|
className="w-full p-2 text-sm bg-secondary rounded border border-border outline-none focus:ring-2 focus:ring-primary disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{prompts.map(p => (
|
||||||
|
<option key={p.id} value={p.id}>{p.name}</option>
|
||||||
|
))}
|
||||||
|
{prompts.length === 0 && <option value="">No templates</option>}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Process Button */}
|
||||||
|
<button
|
||||||
|
onClick={handleProcess}
|
||||||
|
disabled={!selectedFile || isProcessing || !apiKey}
|
||||||
|
className="w-full py-3 text-base font-semibold bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-md hover:shadow-lg flex items-center justify-center gap-2"
|
||||||
|
>
|
||||||
|
{isProcessing ? (
|
||||||
|
<>
|
||||||
|
<Loader2 size={20} className="animate-spin" />
|
||||||
|
Processing...
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Upload size={20} />
|
||||||
|
Transcribe & Summarize
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{/* Progress Indicator */}
|
||||||
|
{stageInfo && (
|
||||||
|
<div className="flex items-center justify-center gap-2 p-3 bg-secondary/50 rounded-lg border border-border">
|
||||||
|
<stageInfo.icon size={16} className={`${stageInfo.color} ${stage !== 'complete' ? 'animate-spin' : ''}`} />
|
||||||
|
<span className={`text-sm font-medium ${stageInfo.color}`}>
|
||||||
|
{stageInfo.text}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Import;
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
import { Mic, Square, Users, Headphones } from 'lucide-react';
|
import { Mic, Square, Users, Headphones } from 'lucide-react';
|
||||||
import { invoke } from "@tauri-apps/api/core";
|
import { invoke } from "@tauri-apps/api/core";
|
||||||
import { listen } from '@tauri-apps/api/event';
|
import { listen } from '@tauri-apps/api/event';
|
||||||
@@ -42,6 +42,8 @@ interface RecorderProps {
|
|||||||
addToast: (msg: string, type: 'success' | 'error' | 'info', duration?: number) => void;
|
addToast: (msg: string, type: 'success' | 'error' | 'info', duration?: number) => void;
|
||||||
selectedModel: string;
|
selectedModel: string;
|
||||||
onModelChange: (model: string) => void;
|
onModelChange: (model: string) => void;
|
||||||
|
isVisible: boolean;
|
||||||
|
blockedApps: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
interface AudioDevice {
|
interface AudioDevice {
|
||||||
@@ -53,11 +55,15 @@ const Recorder: React.FC<RecorderProps> = ({
|
|||||||
apiKey, productId, prompts,
|
apiKey, productId, prompts,
|
||||||
setTranscription, setSummary,
|
setTranscription, setSummary,
|
||||||
onSaveToHistory, savePath, onRecordingComplete,
|
onSaveToHistory, savePath, onRecordingComplete,
|
||||||
onOpenSettings, addToast, selectedModel, onModelChange, ...props
|
onOpenSettings, addToast, selectedModel, onModelChange, blockedApps, ...props
|
||||||
}) => {
|
}) => {
|
||||||
const [isRecording, setIsRecording] = useState(false);
|
const [isRecording, setIsRecording] = useState(false);
|
||||||
const [isStopping, setIsStopping] = useState(false); // New lock state
|
const [isStopping, setIsStopping] = useState(false); // New lock state
|
||||||
const [isPaused, setIsPaused] = useState(false);
|
const [isPaused, setIsPaused] = useState(false);
|
||||||
|
const [isWaiting, setIsWaiting] = useState(false); // New state for Auto-Start
|
||||||
|
const [hasSpeechDetected, setHasSpeechDetected] = useState(false); // New tracking state
|
||||||
|
const [autoStartEnabled, setAutoStartEnabled] = useState(false); // Toggle state
|
||||||
|
|
||||||
const [status, setStatus] = useState<string>('Ready to record');
|
const [status, setStatus] = useState<string>('Ready to record');
|
||||||
const [selectedDevice, setSelectedDevice] = useState<string>('');
|
const [selectedDevice, setSelectedDevice] = useState<string>('');
|
||||||
const [selectedPromptId, setSelectedPromptId] = useState<string>('');
|
const [selectedPromptId, setSelectedPromptId] = useState<string>('');
|
||||||
@@ -68,11 +74,8 @@ const Recorder: React.FC<RecorderProps> = ({
|
|||||||
const [lastSpeechTime, setLastSpeechTime] = useState<number>(Date.now());
|
const [lastSpeechTime, setLastSpeechTime] = useState<number>(Date.now());
|
||||||
const [silenceDuration, setSilenceDuration] = useState(0);
|
const [silenceDuration, setSilenceDuration] = useState(0);
|
||||||
|
|
||||||
// Filtered devices based on mode
|
// Show all devices for both modes now (System Audio is captured natively)
|
||||||
const filteredDevices = devices.filter(d => {
|
const filteredDevices = devices;
|
||||||
const isVirtual = d.name.toLowerCase().includes('hearbit') || d.name.toLowerCase().includes('blackhole');
|
|
||||||
return recordingMode === 'meeting' ? isVirtual : !isVirtual;
|
|
||||||
});
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
loadDevices();
|
loadDevices();
|
||||||
@@ -121,15 +124,18 @@ const Recorder: React.FC<RecorderProps> = ({
|
|||||||
const aggregateDev = aliasedDevs.find(d => d.name === 'Hearbit Audio');
|
const aggregateDev = aliasedDevs.find(d => d.name === 'Hearbit Audio');
|
||||||
const virtualDev = aliasedDevs.find(d => d.name.includes('Hearbit Virtual'));
|
const virtualDev = aliasedDevs.find(d => d.name.includes('Hearbit Virtual'));
|
||||||
|
|
||||||
if (aggregateDev) {
|
if (recordingMode === 'meeting') {
|
||||||
setRecordingMode('meeting');
|
if (aggregateDev) {
|
||||||
setSelectedDevice(aggregateDev.id);
|
setSelectedDevice(aggregateDev.id);
|
||||||
} else if (virtualDev) {
|
} else if (virtualDev) {
|
||||||
setRecordingMode('meeting');
|
setSelectedDevice(virtualDev.id);
|
||||||
setSelectedDevice(virtualDev.id);
|
} else if (aliasedDevs.length > 0) {
|
||||||
} else {
|
setSelectedDevice(aliasedDevs[0].id);
|
||||||
setRecordingMode('voice');
|
}
|
||||||
if (aliasedDevs.length > 0) setSelectedDevice(aliasedDevs[0].id);
|
} else if (aliasedDevs.length > 0) {
|
||||||
|
// Voice mode: just pick first non-virtual if possible, otherwise first
|
||||||
|
const physicalMic = aliasedDevs.find(d => !d.name.includes('Hearbit') && !d.name.includes('BlackHole'));
|
||||||
|
setSelectedDevice(physicalMic ? physicalMic.id : aliasedDevs[0].id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -149,19 +155,36 @@ const Recorder: React.FC<RecorderProps> = ({
|
|||||||
|
|
||||||
const startRecording = async (deviceIdOverride?: string) => {
|
const startRecording = async (deviceIdOverride?: string) => {
|
||||||
try {
|
try {
|
||||||
setStatus('Starting...');
|
|
||||||
setStatus('Starting...');
|
setStatus('Starting...');
|
||||||
// Check override or state
|
// Check override or state
|
||||||
const targetDeviceId = deviceIdOverride || selectedDevice;
|
const targetDeviceId = deviceIdOverride || selectedDevice;
|
||||||
|
|
||||||
// Pass customFilename (camelCase key maps to snake_case in Rust automatically or we need to check Tauri mapping, usually it maps camel to camel? Rust expects snake. Let's use snake_case in invoke args to be safe)
|
// Pass customFilename (camelCase key maps to snake_case in Rust automatically or we need to check Tauri mapping, usually it maps camel to camel? Rust expects snake. Let's use snake_case in invoke args to be safe)
|
||||||
await invoke('start_recording', { deviceId: targetDeviceId, savePath: savePath || null, customFilename: props.recordingSubject || null });
|
await invoke('start_recording', {
|
||||||
|
deviceId: targetDeviceId,
|
||||||
|
savePath: savePath || null,
|
||||||
|
customFilename: props.recordingSubject || null,
|
||||||
|
waitForSpeech: autoStartEnabled, // Pass the toggle state
|
||||||
|
mode: recordingMode,
|
||||||
|
excludedApps: blockedApps
|
||||||
|
});
|
||||||
|
|
||||||
setIsRecording(true);
|
setIsRecording(true);
|
||||||
setIsPaused(false);
|
setIsPaused(false);
|
||||||
setTranscription('');
|
setTranscription('');
|
||||||
setSummary('');
|
setSummary('');
|
||||||
setStatus('Recording...');
|
setHasSpeechDetected(false); // Reset check for new session
|
||||||
addToast('Recording started', 'success', 2000);
|
|
||||||
|
if (autoStartEnabled) {
|
||||||
|
setIsWaiting(true);
|
||||||
|
setStatus('Waiting for audio...');
|
||||||
|
addToast('Standing by for audio...', 'info', 3000);
|
||||||
|
} else {
|
||||||
|
setIsWaiting(false);
|
||||||
|
setStatus('Recording...');
|
||||||
|
addToast('Recording started', 'success', 2000);
|
||||||
|
}
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
setStatus(`Error: ${e}`);
|
setStatus(`Error: ${e}`);
|
||||||
@@ -170,43 +193,97 @@ const Recorder: React.FC<RecorderProps> = ({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// VAD & Auto-Stop Logic
|
// Refs for interval access to avoid dependency cycles and stale closures
|
||||||
useEffect(() => {
|
const lastSpeechTimeRef = useRef<number>(Date.now());
|
||||||
let unlisten: () => void;
|
const isStoppingRef = useRef(false);
|
||||||
|
const autoStartEnabledRef = useRef(autoStartEnabled);
|
||||||
|
|
||||||
const setupListener = async () => {
|
// Update refs when state changes
|
||||||
unlisten = await listen<{ is_speech: boolean, probability: number }>('vad-event', (event) => {
|
useEffect(() => {
|
||||||
|
lastSpeechTimeRef.current = lastSpeechTime;
|
||||||
|
}, [lastSpeechTime]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
isStoppingRef.current = isStopping;
|
||||||
|
}, [isStopping]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
autoStartEnabledRef.current = autoStartEnabled;
|
||||||
|
}, [autoStartEnabled]);
|
||||||
|
|
||||||
|
// 1. Event Listeners Effect (Run ONCE when recording starts)
|
||||||
|
useEffect(() => {
|
||||||
|
let unlistenVAD: () => void;
|
||||||
|
let unlistenTrigger: () => void;
|
||||||
|
|
||||||
|
const setupListeners = async () => {
|
||||||
|
if (!isRecording) return;
|
||||||
|
|
||||||
|
console.log("Setting up VAD listeners...");
|
||||||
|
// VAD Event Listener
|
||||||
|
unlistenVAD = await listen<{ is_speech: boolean, probability: number }>('vad-event', (event) => {
|
||||||
if (event.payload.is_speech) {
|
if (event.payload.is_speech) {
|
||||||
setLastSpeechTime(Date.now());
|
setLastSpeechTime(Date.now());
|
||||||
|
lastSpeechTimeRef.current = Date.now();
|
||||||
setSilenceDuration(0);
|
setSilenceDuration(0);
|
||||||
|
setHasSpeechDetected(true); // Track positive speech
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Auto-Start Trigger Listener
|
||||||
|
unlistenTrigger = await listen('auto-recording-triggered', () => {
|
||||||
|
console.log("Auto-Start Triggered from Backend!");
|
||||||
|
setHasSpeechDetected(true); // Trigger counts as speech
|
||||||
|
setIsWaiting((prev) => {
|
||||||
|
if (prev) {
|
||||||
|
addToast("Audio detected! Recording started.", 'success', 4000);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return prev;
|
||||||
|
});
|
||||||
|
setStatus('Recording (Auto-Started)...');
|
||||||
|
setLastSpeechTime(Date.now());
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
if (isRecording && !isPaused) {
|
if (isRecording) {
|
||||||
setupListener();
|
setupListeners();
|
||||||
setLastSpeechTime(Date.now()); // Reset on start
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const interval = setInterval(() => {
|
return () => {
|
||||||
if (isRecording && !isPaused) {
|
// Cleanup listeners
|
||||||
const diff = (Date.now() - lastSpeechTime) / 1000;
|
if (unlistenVAD) unlistenVAD();
|
||||||
setSilenceDuration(diff);
|
if (unlistenTrigger) unlistenTrigger();
|
||||||
|
};
|
||||||
|
}, [isRecording, addToast]); // Dependencies for listener setup
|
||||||
|
|
||||||
// Auto-stop after 30 seconds of silence
|
// Ref for visibility to avoid closure staleness in interval
|
||||||
if (diff > 30 && !isStopping) { // Check lock
|
const isVisibleRef = useRef(props.isVisible);
|
||||||
console.log("Auto-stopping due to silence");
|
useEffect(() => {
|
||||||
addToast("Auto-stopping (Silence detected)", "info", 3000);
|
isVisibleRef.current = props.isVisible;
|
||||||
stopRecording();
|
}, [props.isVisible]);
|
||||||
}
|
|
||||||
|
// Auto-Stop Interval Effect
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isRecording || isPaused || isWaiting) return;
|
||||||
|
|
||||||
|
const interval = setInterval(() => {
|
||||||
|
const now = Date.now();
|
||||||
|
const timeSinceSpeech = (now - lastSpeechTimeRef.current) / 1000;
|
||||||
|
setSilenceDuration(timeSinceSpeech);
|
||||||
|
|
||||||
|
// AUTO STOP Logic
|
||||||
|
// Use Ref to get LATEST visibility instantly
|
||||||
|
if (isVisibleRef.current && timeSinceSpeech > 25 && !isStoppingRef.current) {
|
||||||
|
console.log("Auto-stopping due to silence...");
|
||||||
|
isStoppingRef.current = true;
|
||||||
|
addToast('Auto-stopped due to silence', 'info');
|
||||||
|
stopRecording();
|
||||||
}
|
}
|
||||||
}, 1000);
|
}, 1000);
|
||||||
|
|
||||||
return () => {
|
return () => clearInterval(interval);
|
||||||
if (unlisten) unlisten();
|
}, [isRecording, isPaused, isWaiting, recordingMode, addToast]); // Removed props.isVisible dependency (using Ref)
|
||||||
clearInterval(interval);
|
|
||||||
};
|
|
||||||
}, [isRecording, isPaused, lastSpeechTime]);
|
|
||||||
|
|
||||||
// Handle Auto Start Prop
|
// Handle Auto Start Prop
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -273,103 +350,182 @@ const Recorder: React.FC<RecorderProps> = ({
|
|||||||
try {
|
try {
|
||||||
setIsRecording(false);
|
setIsRecording(false);
|
||||||
setIsPaused(false);
|
setIsPaused(false);
|
||||||
setStatus('Processing...');
|
setIsWaiting(false); // Reset waiting state
|
||||||
|
setTranscription('');
|
||||||
|
setSummary('');
|
||||||
|
setHasSpeechDetected(false); // Reset checkiting state
|
||||||
|
setStatus('Saving recording...');
|
||||||
const filePath = await invoke<string>('stop_recording');
|
const filePath = await invoke<string>('stop_recording');
|
||||||
|
|
||||||
// Wait a moment for file flush (safety)
|
// NEW: Check if speech was actually detected during the session
|
||||||
await new Promise(r => setTimeout(r, 500));
|
// If we recorded 20s of silence (Auto-Stop), we shouldn't transcribe.
|
||||||
|
// IMPORTANT: Check applies to BOTH 'voice' and 'meeting' modes to prevent "Batch Null" errors on false triggers.
|
||||||
|
if (!hasSpeechDetected) {
|
||||||
|
console.log("No speech detected during recording. Skipping transcription.");
|
||||||
|
addToast("Recording discarded (No speech/audio detected)", 'info');
|
||||||
|
setStatus('Ready to record'); // Reset status text
|
||||||
|
|
||||||
setStatus('Transcribing (Infomaniak Whisper)...');
|
// If auto-start is on, we just loop back (in finally block).
|
||||||
const transText = await invoke<string>('transcribe_audio', {
|
// But we skip the expensive/failing API call.
|
||||||
filePath,
|
} else {
|
||||||
apiKey,
|
|
||||||
productId
|
|
||||||
});
|
|
||||||
setTranscription(transText);
|
|
||||||
|
|
||||||
// Check if transcription is empty or just whitespace
|
// Wait a moment for file flush (safety)
|
||||||
if (!transText || transText.trim().length === 0) {
|
await new Promise(r => setTimeout(r, 500));
|
||||||
setStatus('Done (No speech detected)');
|
|
||||||
setTranscription('(No speech detected. Check your microphone settings.)');
|
|
||||||
setTimeout(() => setStatus('Ready to record'), 3000);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Find selected prompt content - SMART SELECTION
|
// Confirm recording saved
|
||||||
let activePrompt = prompts.find(p => p.id === selectedPromptId);
|
addToast(`Recording saved locally: ${filePath.split('/').pop()}`, 'success', 3000);
|
||||||
|
setStatus('Converting to MP3...');
|
||||||
|
|
||||||
// Smart Auto-Select based on keywords
|
// Small delay to show the "saved" message
|
||||||
const lowerText = transText.toLowerCase();
|
await new Promise(r => setTimeout(r, 500));
|
||||||
let bestMatchId = selectedPromptId;
|
|
||||||
let maxMatches = 0;
|
|
||||||
|
|
||||||
for (const p of prompts) {
|
// Convert WAV to MP3 for smaller size
|
||||||
if (!p.keywords) continue;
|
const mp3Path = await invoke<string>('convert_to_mp3', { wavPath: filePath });
|
||||||
let matches = 0;
|
|
||||||
for (const kw of p.keywords) {
|
// Get file size to check if chunking needed
|
||||||
if (lowerText.includes(kw.toLowerCase())) {
|
interface AudioMetadata { duration: number; size: number; format: string; }
|
||||||
matches++;
|
const metadata = await invoke<AudioMetadata>('get_audio_metadata', { filePath: mp3Path });
|
||||||
|
const sizeMB = metadata.size / (1024 * 1024);
|
||||||
|
|
||||||
|
let transText = '';
|
||||||
|
|
||||||
|
// Check if chunking needed (only for Meeting mode and large files)
|
||||||
|
if (recordingMode === 'meeting' && sizeMB >= 18) {
|
||||||
|
// CHUNKING PATH for large meetings
|
||||||
|
setStatus(`Large file (${sizeMB.toFixed(1)}MB). Splitting into chunks...`);
|
||||||
|
const chunks = await invoke<string[]>('chunk_audio', {
|
||||||
|
filePath: mp3Path,
|
||||||
|
chunkMinutes: 10
|
||||||
|
});
|
||||||
|
|
||||||
|
addToast(`Processing ${chunks.length} chunks...`, 'info', 4000);
|
||||||
|
|
||||||
|
let allTranscriptions: string[] = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < chunks.length; i++) {
|
||||||
|
setStatus(`Transcribing chunk ${i + 1}/${chunks.length}...`);
|
||||||
|
const chunkText = await invoke<string>('transcribe_audio', {
|
||||||
|
filePath: chunks[i],
|
||||||
|
apiKey,
|
||||||
|
productId
|
||||||
|
});
|
||||||
|
allTranscriptions.push(chunkText);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Merge transcriptions
|
||||||
|
transText = allTranscriptions.join('\n\n--- Next Segment ---\n\n');
|
||||||
|
addToast('All chunks transcribed successfully!', 'success', 3000);
|
||||||
|
} else {
|
||||||
|
// NORMAL PATH for small files
|
||||||
|
setStatus('Transcribing (Infomaniak Whisper)...');
|
||||||
|
transText = await invoke<string>('transcribe_audio', {
|
||||||
|
filePath: mp3Path,
|
||||||
|
apiKey,
|
||||||
|
productId
|
||||||
|
});
|
||||||
}
|
}
|
||||||
if (matches > maxMatches) {
|
|
||||||
maxMatches = matches;
|
setTranscription(transText);
|
||||||
bestMatchId = p.id;
|
|
||||||
|
// Check if transcription is empty or just whitespace
|
||||||
|
if (!transText || transText.trim().length === 0) {
|
||||||
|
setStatus('Done (No speech detected)');
|
||||||
|
setTranscription('(No speech detected. Check your microphone settings.)');
|
||||||
|
setTimeout(() => setStatus('Ready to record'), 3000);
|
||||||
|
// allow finally block to restart loop
|
||||||
|
} else {
|
||||||
|
// Logic continues...
|
||||||
|
|
||||||
|
// Find selected prompt content - SMART SELECTION
|
||||||
|
let activePrompt = prompts.find(p => p.id === selectedPromptId);
|
||||||
|
|
||||||
|
// Smart Auto-Select based on keywords
|
||||||
|
const lowerText = transText.toLowerCase();
|
||||||
|
let bestMatchId = selectedPromptId;
|
||||||
|
let maxMatches = 0;
|
||||||
|
|
||||||
|
for (const p of prompts) {
|
||||||
|
if (!p.keywords) continue;
|
||||||
|
let matches = 0;
|
||||||
|
for (const kw of p.keywords) {
|
||||||
|
if (lowerText.includes(kw.toLowerCase())) {
|
||||||
|
matches++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (matches > maxMatches) {
|
||||||
|
maxMatches = matches;
|
||||||
|
bestMatchId = p.id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bestMatchId !== selectedPromptId) {
|
||||||
|
const newPrompt = prompts.find(p => p.id === bestMatchId);
|
||||||
|
if (newPrompt) {
|
||||||
|
console.log(`Smart Select: Switched to '${newPrompt.name}' with ${maxMatches} matches.`);
|
||||||
|
setStatus(`Smart Select: Using "${newPrompt.name}"...`);
|
||||||
|
addToast(`Smart Select: Switched to "${newPrompt.name}"`, 'success', 4000);
|
||||||
|
activePrompt = newPrompt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const promptContent = activePrompt ? activePrompt.content : "Summarize this.";
|
||||||
|
|
||||||
|
setStatus(`Summarizing (${selectedModel})...`);
|
||||||
|
const sumText = await invoke<string>('summarize_text', {
|
||||||
|
text: transText,
|
||||||
|
apiKey,
|
||||||
|
productId,
|
||||||
|
prompt: promptContent,
|
||||||
|
model: selectedModel
|
||||||
|
});
|
||||||
|
setSummary(sumText);
|
||||||
|
|
||||||
|
// Auto-save to history
|
||||||
|
onSaveToHistory(transText, sumText);
|
||||||
|
|
||||||
|
setStatus('Done!');
|
||||||
|
addToast('Transcription & Summary complete!', 'success', 4000);
|
||||||
|
onRecordingComplete(); // Auto-switch tab
|
||||||
|
setTimeout(() => setStatus('Ready to record'), 3000);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (bestMatchId !== selectedPromptId) {
|
|
||||||
const newPrompt = prompts.find(p => p.id === bestMatchId);
|
|
||||||
if (newPrompt) {
|
|
||||||
console.log(`Smart Select: Switched to '${newPrompt.name}' with ${maxMatches} matches.`);
|
|
||||||
setStatus(`Smart Select: Using "${newPrompt.name}"...`);
|
|
||||||
addToast(`Smart Select: Switched to "${newPrompt.name}"`, 'success', 4000);
|
|
||||||
activePrompt = newPrompt;
|
|
||||||
// Optional: Update UI selection? setSelectedPromptId(bestMatchId);
|
|
||||||
// Let's verify with user preference? For now, we override as "Magic".
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const promptContent = activePrompt ? activePrompt.content : "Summarize this.";
|
|
||||||
|
|
||||||
setStatus(`Summarizing (${selectedModel})...`);
|
|
||||||
const sumText = await invoke<string>('summarize_text', {
|
|
||||||
text: transText,
|
|
||||||
apiKey,
|
|
||||||
productId,
|
|
||||||
prompt: promptContent,
|
|
||||||
model: selectedModel
|
|
||||||
});
|
|
||||||
setSummary(sumText);
|
|
||||||
|
|
||||||
// Auto-save to history
|
|
||||||
onSaveToHistory(transText, sumText);
|
|
||||||
|
|
||||||
setStatus('Done!');
|
|
||||||
addToast('Transcription & Summary complete!', 'success', 4000);
|
|
||||||
onRecordingComplete(); // Auto-switch tab
|
|
||||||
setTimeout(() => setStatus('Ready to record'), 3000);
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
setStatus(`Error: ${e}`);
|
setStatus(`Error: ${e}`);
|
||||||
addToast(`Error processing: ${e}`, 'error');
|
addToast(`Error processing: ${e}`, 'error');
|
||||||
} finally {
|
} finally {
|
||||||
setIsStopping(false);
|
setIsStopping(false);
|
||||||
|
|
||||||
|
// AUTO-RESTART LOGIC
|
||||||
|
// Use REF to get the latest state (fix for "starts again even if I uncheck")
|
||||||
|
if (autoStartEnabledRef.current) {
|
||||||
|
console.log("Auto-Start enabled: Restarting listener loop...");
|
||||||
|
// Short delay to ensure backend cleanup
|
||||||
|
setTimeout(() => {
|
||||||
|
// Double check ref before restarting
|
||||||
|
if (autoStartEnabledRef.current) {
|
||||||
|
startRecording();
|
||||||
|
}
|
||||||
|
}, 1000);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col w-full h-full bg-background relative">
|
<div className="flex flex-col w-full h-full bg-background relative">
|
||||||
{/* Fixed Header - Reduced padding */}
|
{/* Fixed Header - Reduced padding */}
|
||||||
<div className="w-full flex justify-center items-center p-4 shrink-0">
|
<div className="w-full flex justify-center items-center p-4 shrink-0">
|
||||||
<img src={logo} alt="Logo" className="h-10 object-contain" />
|
<img src={localStorage.getItem('customLogo') || logo} alt="Logo" className="h-10 object-contain" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Scrollable Content - Reduced spacing */}
|
{/* Scrollable Content - Reduced spacing */}
|
||||||
<div className="flex-1 overflow-y-auto px-6 pb-6 flex flex-col items-center">
|
<div className="flex-1 overflow-y-auto px-6 pb-6 flex flex-col items-center">
|
||||||
<div className="mb-4 relative shrink-0">
|
<div className="mb-4 relative shrink-0">
|
||||||
<div className={`w-24 h-24 rounded-full flex items-center justify-center transition-all duration-300 ${isRecording ? (isPaused ? 'bg-yellow-500/10' : 'bg-red-500/10 animate-pulse') : 'bg-secondary'}`}>
|
<div className={`w-24 h-24 rounded-full flex items-center justify-center transition-all duration-300 ${isRecording ? (isWaiting ? 'bg-blue-500/20' : isPaused ? 'bg-yellow-500/10' : 'bg-red-500/10 animate-pulse') : 'bg-secondary'}`}>
|
||||||
{isRecording ? (
|
{isRecording ? (
|
||||||
<div className={`w-16 h-16 rounded-full flex items-center justify-center shadow-[0_0_20px_rgba(239,68,68,0.5)] ${isPaused ? 'bg-yellow-500' : 'bg-red-500'}`}>
|
<div className={`w-16 h-16 rounded-full flex items-center justify-center shadow-[0_0_20px_rgba(239,68,68,0.5)] ${isWaiting ? 'bg-blue-500 animate-pulse' : isPaused ? 'bg-yellow-500' : 'bg-red-500'}`}>
|
||||||
<Mic size={32} className="text-white animate-bounce" />
|
<Mic size={32} className="text-white animate-bounce" />
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
@@ -381,12 +537,12 @@ const Recorder: React.FC<RecorderProps> = ({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<h1 className="text-xl font-bold mb-1 text-foreground">
|
<h1 className="text-xl font-bold mb-1 text-foreground">
|
||||||
{isRecording ? (isPaused ? 'Paused' : 'Listening...') : 'Ready to Record'}
|
{isRecording ? (isWaiting ? 'Waiting for Audio...' : isPaused ? 'Paused' : 'Listening...') : 'Ready to Record'}
|
||||||
</h1>
|
</h1>
|
||||||
|
|
||||||
<p className="text-muted-foreground mb-4 text-center text-xs h-5">
|
<p className="text-muted-foreground mb-4 text-center text-xs h-5">
|
||||||
{status}
|
{status}
|
||||||
{isRecording && !isPaused && silenceDuration > 10 && (
|
{isRecording && !isPaused && !isWaiting && silenceDuration > 10 && (
|
||||||
<span className="block text-xs text-yellow-500 mt-0.5 opacity-80">
|
<span className="block text-xs text-yellow-500 mt-0.5 opacity-80">
|
||||||
Silence detected: {Math.floor(silenceDuration)}s
|
Silence detected: {Math.floor(silenceDuration)}s
|
||||||
</span>
|
</span>
|
||||||
@@ -395,30 +551,46 @@ const Recorder: React.FC<RecorderProps> = ({
|
|||||||
|
|
||||||
<div className="w-full max-w-sm space-y-3 mb-4 shrink-0">
|
<div className="w-full max-w-sm space-y-3 mb-4 shrink-0">
|
||||||
{!isRecording ? (
|
{!isRecording ? (
|
||||||
<button
|
<>
|
||||||
onClick={() => startRecording()}
|
<button
|
||||||
disabled={!apiKey || !productId}
|
onClick={() => startRecording()}
|
||||||
className="w-full py-3 text-base font-semibold bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-md hover:shadow-lg"
|
disabled={!apiKey || !productId}
|
||||||
>
|
className="w-full py-3 text-base font-semibold bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-md hover:shadow-lg"
|
||||||
{!apiKey ? 'Configure API Key First' : 'Start Recording'}
|
>
|
||||||
</button>
|
{!apiKey ? 'Configure API Key First' : (autoStartEnabled ? 'Standby (Auto-Start)' : 'Start Recording')}
|
||||||
|
</button>
|
||||||
|
<div className="flex items-center justify-center gap-2 mt-2">
|
||||||
|
<label className="flex items-center gap-2 cursor-pointer select-none">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={autoStartEnabled}
|
||||||
|
onChange={(e) => setAutoStartEnabled(e.target.checked)}
|
||||||
|
className="w-4 h-4 accent-primary rounded cursor-pointer"
|
||||||
|
/>
|
||||||
|
<span className="text-xs text-muted-foreground font-medium">Auto-start when audio detected</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
) : (
|
) : (
|
||||||
<div className="flex gap-2 w-full">
|
<div className="flex gap-2 w-full">
|
||||||
<button
|
{/* In Waiting mode, we can only Stop (Cancel) */}
|
||||||
onClick={togglePause}
|
{!isWaiting && (
|
||||||
className={`flex-1 py-4 text-lg font-semibold rounded-lg transition-all shadow-md hover:shadow-lg flex items-center justify-center gap-2 ${isPaused
|
<button
|
||||||
? 'bg-blue-600 text-white hover:bg-blue-700'
|
onClick={togglePause}
|
||||||
: 'bg-yellow-500 text-white hover:bg-yellow-600'
|
className={`flex-1 py-4 text-lg font-semibold rounded-lg transition-all shadow-md hover:shadow-lg flex items-center justify-center gap-2 ${isPaused
|
||||||
}`}
|
? 'bg-blue-600 text-white hover:bg-blue-700'
|
||||||
>
|
: 'bg-yellow-500 text-white hover:bg-yellow-600'
|
||||||
{isPaused ? 'Resume' : 'Pause'}
|
}`}
|
||||||
</button>
|
>
|
||||||
|
{isPaused ? 'Resume' : 'Pause'}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
<button
|
<button
|
||||||
onClick={stopRecording}
|
onClick={stopRecording}
|
||||||
className="flex-1 py-4 text-lg font-semibold bg-destructive text-destructive-foreground rounded-lg hover:bg-destructive/90 transition-all shadow-md hover:shadow-lg flex items-center justify-center gap-2"
|
className="flex-1 py-4 text-lg font-semibold bg-destructive text-destructive-foreground rounded-lg hover:bg-destructive/90 transition-all shadow-md hover:shadow-lg flex items-center justify-center gap-2"
|
||||||
>
|
>
|
||||||
<Square size={20} fill="currentColor" />
|
<Square size={20} fill="currentColor" />
|
||||||
Stop
|
{isWaiting ? 'Cancel' : 'Stop'}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -501,12 +673,20 @@ const Recorder: React.FC<RecorderProps> = ({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-col gap-2 mt-2 w-full">
|
<div className="flex flex-col gap-2 mt-2 w-full">
|
||||||
{recordingMode === 'meeting' && filteredDevices.length === 0 && (
|
{recordingMode === 'meeting' && (
|
||||||
<button
|
<button
|
||||||
onClick={onOpenSettings}
|
onClick={async () => {
|
||||||
|
const allowed = await invoke<boolean>('check_screen_recording_permission');
|
||||||
|
if (allowed) {
|
||||||
|
addToast('System Audio Permission: GRANTED ✅', 'success');
|
||||||
|
} else {
|
||||||
|
addToast('System Audio Permission: MISSING ❌. Please enable in System Settings -> Privacy -> Screen Recording', 'error', 5000);
|
||||||
|
// Open Settings?
|
||||||
|
}
|
||||||
|
}}
|
||||||
className="text-xs bg-primary/10 text-primary hover:bg-primary/20 w-full text-center border border-primary/20 rounded p-2 mb-2 font-semibold"
|
className="text-xs bg-primary/10 text-primary hover:bg-primary/20 w-full text-center border border-primary/20 rounded p-2 mb-2 font-semibold"
|
||||||
>
|
>
|
||||||
🪄 Create "Hearbit Audio" Device
|
🔒 Check Audio Permission
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
<button
|
<button
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { Save, FolderOpen, Lock, Upload, Download, Eye, EyeOff, Mail, FileText, ScrollText } from 'lucide-react';
|
import { Save, FolderOpen, Lock, Upload, Download, Mail, FileText, ScrollText, Headphones } from 'lucide-react';
|
||||||
import { save, open } from '@tauri-apps/plugin-dialog';
|
import { save, open } from '@tauri-apps/plugin-dialog';
|
||||||
// Removed writeTextFile as we use invoke 'save_text_file'
|
|
||||||
import { invoke } from '@tauri-apps/api/core';
|
import { invoke } from '@tauri-apps/api/core';
|
||||||
import { encryptData, decryptData } from '../utils/backup';
|
|
||||||
import EmailTemplateEditor from './EmailTemplateEditor';
|
import EmailTemplateEditor from './EmailTemplateEditor';
|
||||||
|
import logo from '../assets/logo.png';
|
||||||
|
|
||||||
import { PromptTemplate, EmailTemplate } from '../App';
|
import { PromptTemplate, EmailTemplate } from '../App';
|
||||||
|
|
||||||
@@ -16,6 +15,10 @@ interface SettingsProps {
|
|||||||
emailTemplates: EmailTemplate[];
|
emailTemplates: EmailTemplate[];
|
||||||
smtpConfig: SmtpConfig;
|
smtpConfig: SmtpConfig;
|
||||||
azureConfig: AzureConfig;
|
azureConfig: AzureConfig;
|
||||||
|
dailyBackupEnabled: boolean;
|
||||||
|
dailyBackupPath: string;
|
||||||
|
lastBackupDate: string;
|
||||||
|
history: any[];
|
||||||
onSave: (
|
onSave: (
|
||||||
apiKey: string,
|
apiKey: string,
|
||||||
productId: string,
|
productId: string,
|
||||||
@@ -23,9 +26,14 @@ interface SettingsProps {
|
|||||||
savePath: string,
|
savePath: string,
|
||||||
smtp: SmtpConfig,
|
smtp: SmtpConfig,
|
||||||
azure: AzureConfig,
|
azure: AzureConfig,
|
||||||
emailTemplates: EmailTemplate[]
|
emailTemplates: EmailTemplate[],
|
||||||
|
dailyBackupEnabled: boolean,
|
||||||
|
dailyBackupPath: string,
|
||||||
|
blockedApps: string[]
|
||||||
) => void;
|
) => void;
|
||||||
|
onHistoryUpdate: (history: any[]) => void;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
|
blockedApps: string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SmtpConfig {
|
export interface SmtpConfig {
|
||||||
@@ -42,6 +50,30 @@ export interface AzureConfig {
|
|||||||
tenantId: string;
|
tenantId: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const APP_PRESETS = [
|
||||||
|
{
|
||||||
|
category: 'Browsers',
|
||||||
|
apps: [
|
||||||
|
{ name: 'Safari', id: 'com.apple.Safari' },
|
||||||
|
{ name: 'Chrome', id: 'com.google.Chrome' },
|
||||||
|
{ name: 'Firefox', id: 'org.mozilla.firefox' },
|
||||||
|
{ name: 'Arc', id: 'company.thebrowser.Browser' },
|
||||||
|
{ name: 'Edge', id: 'com.microsoft.edgemac' },
|
||||||
|
{ name: 'Brave', id: 'com.brave.Browser' },
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
category: 'Music & Media',
|
||||||
|
apps: [
|
||||||
|
{ name: 'Apple Music', id: 'com.apple.Music' },
|
||||||
|
{ name: 'Spotify', id: 'com.spotify.client' },
|
||||||
|
{ name: 'Tidal', id: 'com.aspiro.Tidal' },
|
||||||
|
{ name: 'VLC', id: 'org.videolan.vlc' },
|
||||||
|
{ name: 'Podcasts', id: 'com.apple.podcasts' },
|
||||||
|
]
|
||||||
|
}
|
||||||
|
];
|
||||||
|
|
||||||
const Settings: React.FC<SettingsProps> = ({ apiKey, productId, prompts, savePath, onSave, onClose, ...props }) => {
|
const Settings: React.FC<SettingsProps> = ({ apiKey, productId, prompts, savePath, onSave, onClose, ...props }) => {
|
||||||
const [localApiKey, setLocalApiKey] = useState(apiKey);
|
const [localApiKey, setLocalApiKey] = useState(apiKey);
|
||||||
const [localProductId, setLocalProductId] = useState(productId);
|
const [localProductId, setLocalProductId] = useState(productId);
|
||||||
@@ -51,27 +83,36 @@ const Settings: React.FC<SettingsProps> = ({ apiKey, productId, prompts, savePat
|
|||||||
const [localEmailTemplates, setLocalEmailTemplates] = useState<EmailTemplate[]>(props.emailTemplates); // New state
|
const [localEmailTemplates, setLocalEmailTemplates] = useState<EmailTemplate[]>(props.emailTemplates); // New state
|
||||||
const [localSmtp, setLocalSmtp] = useState<SmtpConfig>(props.smtpConfig);
|
const [localSmtp, setLocalSmtp] = useState<SmtpConfig>(props.smtpConfig);
|
||||||
const [localAzure, setLocalAzure] = useState<AzureConfig>(props.azureConfig);
|
const [localAzure, setLocalAzure] = useState<AzureConfig>(props.azureConfig);
|
||||||
|
const [localDailyBackupEnabled, setLocalDailyBackupEnabled] = useState(props.dailyBackupEnabled);
|
||||||
|
const [localDailyBackupPath, setLocalDailyBackupPath] = useState(props.dailyBackupPath);
|
||||||
|
const [localBlockedApps, setLocalBlockedApps] = useState<string[]>(props.blockedApps);
|
||||||
|
const [runningApps, setRunningApps] = useState<{ name: string, bundle_id: string }[]>([]);
|
||||||
const [statusIdx, setStatusIdx] = useState<string | null>(null);
|
const [statusIdx, setStatusIdx] = useState<string | null>(null);
|
||||||
|
|
||||||
// Backup & Restore State
|
|
||||||
const [backupPassword, setBackupPassword] = useState('');
|
|
||||||
const [showPassword, setShowPassword] = useState(false);
|
|
||||||
const [isImportModalOpen, setIsImportModalOpen] = useState(false);
|
|
||||||
const [importFileContent, setImportFileContent] = useState<string | null>(null);
|
|
||||||
|
|
||||||
// Email Template Editor State
|
// Email Template Editor State
|
||||||
const [editingTemplate, setEditingTemplate] = useState<EmailTemplate | null>(null);
|
const [editingTemplate, setEditingTemplate] = useState<EmailTemplate | null>(null);
|
||||||
const [isEmailEditorOpen, setIsEmailEditorOpen] = useState(false);
|
const [isEmailEditorOpen, setIsEmailEditorOpen] = useState(false);
|
||||||
|
|
||||||
const [activeTab, setActiveTab] = useState<'general' | 'prompts' | 'email' | 'backup' | 'logs'>('general');
|
const [activeTab, setActiveTab] = useState<'general' | 'prompts' | 'email' | 'backup' | 'logs' | 'apps'>('general');
|
||||||
const [logs, setLogs] = useState<string>('Loading logs...');
|
const [logs, setLogs] = useState<string>('Loading logs...');
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (activeTab === 'logs') {
|
if (activeTab === 'logs') {
|
||||||
loadLogs();
|
loadLogs();
|
||||||
|
} else if (activeTab === 'general') {
|
||||||
|
loadRunningApps();
|
||||||
}
|
}
|
||||||
}, [activeTab]);
|
}, [activeTab]);
|
||||||
|
|
||||||
|
const loadRunningApps = async () => {
|
||||||
|
try {
|
||||||
|
const apps = await invoke<{ name: string, bundle_id: string }[]>('get_running_apps');
|
||||||
|
setRunningApps(apps);
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Failed to load running apps:", e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const loadLogs = async () => {
|
const loadLogs = async () => {
|
||||||
try {
|
try {
|
||||||
const content = await invoke<string>('read_log_file');
|
const content = await invoke<string>('read_log_file');
|
||||||
@@ -132,7 +173,18 @@ const Settings: React.FC<SettingsProps> = ({ apiKey, productId, prompts, savePat
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleSave = () => {
|
const handleSave = () => {
|
||||||
onSave(localApiKey, localProductId, localPrompts, localSavePath, localSmtp, localAzure, localEmailTemplates);
|
onSave(
|
||||||
|
localApiKey,
|
||||||
|
localProductId,
|
||||||
|
localPrompts,
|
||||||
|
localSavePath,
|
||||||
|
localSmtp,
|
||||||
|
localAzure,
|
||||||
|
localEmailTemplates,
|
||||||
|
localDailyBackupEnabled,
|
||||||
|
localDailyBackupPath,
|
||||||
|
localBlockedApps
|
||||||
|
);
|
||||||
onClose();
|
onClose();
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -153,10 +205,6 @@ const Settings: React.FC<SettingsProps> = ({ apiKey, productId, prompts, savePat
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleExport = async () => {
|
const handleExport = async () => {
|
||||||
if (!backupPassword) {
|
|
||||||
setStatusIdx('Error: Password required to encrypt backup.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
const data = {
|
const data = {
|
||||||
apiKey: localApiKey,
|
apiKey: localApiKey,
|
||||||
@@ -164,21 +212,28 @@ const Settings: React.FC<SettingsProps> = ({ apiKey, productId, prompts, savePat
|
|||||||
prompts: localPrompts,
|
prompts: localPrompts,
|
||||||
savePath: localSavePath,
|
savePath: localSavePath,
|
||||||
smtp: localSmtp,
|
smtp: localSmtp,
|
||||||
azure: localAzure
|
azure: localAzure,
|
||||||
|
emailTemplates: localEmailTemplates,
|
||||||
|
history: props.history,
|
||||||
|
dailyBackup: {
|
||||||
|
enabled: localDailyBackupEnabled,
|
||||||
|
path: localDailyBackupPath,
|
||||||
|
}
|
||||||
};
|
};
|
||||||
const encrypted = await encryptData(data, backupPassword);
|
|
||||||
|
// Always save as JSON (no encryption)
|
||||||
|
const content = JSON.stringify(data, null, 2);
|
||||||
|
|
||||||
const filePath = await save({
|
const filePath = await save({
|
||||||
defaultPath: `hearbit_backup_${new Date().toISOString().slice(0, 10)}.conf`,
|
defaultPath: `hearbit_backup_${new Date().toISOString().slice(0, 10)}.json`,
|
||||||
filters: [{
|
filters: [{
|
||||||
name: 'Hearbit Config',
|
name: 'Hearbit Config',
|
||||||
extensions: ['conf']
|
extensions: ['json']
|
||||||
}]
|
}]
|
||||||
});
|
});
|
||||||
|
|
||||||
if (filePath) {
|
if (filePath) {
|
||||||
// Use backend invoke to write file (bypasses fs scope issues)
|
await invoke('save_text_file', { path: filePath, content });
|
||||||
await invoke('save_text_file', { path: filePath, content: encrypted });
|
|
||||||
setStatusIdx(`Configuration exported to: ${filePath}`);
|
setStatusIdx(`Configuration exported to: ${filePath}`);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -198,41 +253,40 @@ const Settings: React.FC<SettingsProps> = ({ apiKey, productId, prompts, savePat
|
|||||||
const reader = new FileReader();
|
const reader = new FileReader();
|
||||||
reader.onload = (event) => {
|
reader.onload = (event) => {
|
||||||
if (event.target?.result) {
|
if (event.target?.result) {
|
||||||
setImportFileContent(event.target.result as string);
|
const content = event.target.result as string;
|
||||||
setIsImportModalOpen(true);
|
// Directly import without password modal since we don't use encryption
|
||||||
setBackupPassword('');
|
try {
|
||||||
|
const data = JSON.parse(content);
|
||||||
|
|
||||||
|
if (data.apiKey) setLocalApiKey(data.apiKey);
|
||||||
|
if (data.productId) setLocalProductId(data.productId);
|
||||||
|
if (data.prompts) setLocalPrompts(data.prompts);
|
||||||
|
if (data.emailTemplates) setLocalEmailTemplates(data.emailTemplates);
|
||||||
|
if (data.savePath) setLocalSavePath(data.savePath);
|
||||||
|
if (data.smtp) setLocalSmtp(data.smtp);
|
||||||
|
if (data.azure) setLocalAzure(data.azure);
|
||||||
|
if (data.dailyBackup) {
|
||||||
|
if (data.dailyBackup.enabled !== undefined) setLocalDailyBackupEnabled(data.dailyBackup.enabled);
|
||||||
|
if (data.dailyBackup.path) setLocalDailyBackupPath(data.dailyBackup.path);
|
||||||
|
}
|
||||||
|
if (data.blockedApps) setLocalBlockedApps(data.blockedApps);
|
||||||
|
// Import history!
|
||||||
|
if (data.history && Array.isArray(data.history)) {
|
||||||
|
props.onHistoryUpdate(data.history);
|
||||||
|
}
|
||||||
|
|
||||||
|
setStatusIdx('Configuration imported! Click Save to apply.');
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
setStatusIdx(`Import failed: ${error}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
reader.readAsText(file);
|
reader.readAsText(file);
|
||||||
e.target.value = '';
|
e.target.value = '';
|
||||||
};
|
};
|
||||||
|
|
||||||
const confirmImport = async () => {
|
|
||||||
if (!backupPassword) {
|
|
||||||
setStatusIdx('Error: Password required to decrypt.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!importFileContent) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const data = await decryptData(importFileContent, backupPassword);
|
|
||||||
if (data.apiKey) setLocalApiKey(data.apiKey);
|
|
||||||
if (data.productId) setLocalProductId(data.productId);
|
|
||||||
|
|
||||||
if (data.prompts) setLocalPrompts(data.prompts);
|
|
||||||
if (data.emailTemplates) setLocalEmailTemplates(data.emailTemplates);
|
|
||||||
if (data.savePath) setLocalSavePath(data.savePath);
|
|
||||||
if (data.smtp) setLocalSmtp(data.smtp);
|
|
||||||
if (data.azure) setLocalAzure(data.azure);
|
|
||||||
|
|
||||||
setStatusIdx('Configuration imported! Click Save to apply.');
|
|
||||||
setIsImportModalOpen(false);
|
|
||||||
setImportFileContent(null);
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e);
|
|
||||||
setStatusIdx('Import failed: Wrong password or corrupted file.');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCreateDevice = async () => {
|
const handleCreateDevice = async () => {
|
||||||
try {
|
try {
|
||||||
@@ -250,55 +304,13 @@ const Settings: React.FC<SettingsProps> = ({ apiKey, productId, prompts, savePat
|
|||||||
{ id: 'prompts', label: 'Prompts', icon: <FileText size={14} /> },
|
{ id: 'prompts', label: 'Prompts', icon: <FileText size={14} /> },
|
||||||
{ id: 'email', label: 'Email', icon: <Mail size={14} /> },
|
{ id: 'email', label: 'Email', icon: <Mail size={14} /> },
|
||||||
{ id: 'backup', label: 'Backup', icon: <Lock size={14} /> },
|
{ id: 'backup', label: 'Backup', icon: <Lock size={14} /> },
|
||||||
|
{ id: 'apps', label: 'Apps', icon: <Headphones size={14} /> },
|
||||||
{ id: 'logs', label: 'Logs', icon: <ScrollText size={14} /> },
|
{ id: 'logs', label: 'Logs', icon: <ScrollText size={14} /> },
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col h-full bg-background font-mono text-sm relative">
|
<div className="flex flex-col h-full bg-background font-mono text-sm relative">
|
||||||
{/* Import Password Modal */}
|
{/* Import Password Modal */}
|
||||||
{isImportModalOpen && (
|
|
||||||
<div className="absolute inset-0 z-50 bg-black/50 flex items-center justify-center p-4">
|
|
||||||
<div className="bg-background border border-border rounded-lg shadow-xl p-6 w-full max-w-sm space-y-4">
|
|
||||||
<div className="flex items-center gap-2 text-foreground font-semibold">
|
|
||||||
<Lock size={16} /> Import Configuration
|
|
||||||
</div>
|
|
||||||
<p className="text-muted-foreground text-xs">
|
|
||||||
Enter the password used to encrypt this backup file.
|
|
||||||
</p>
|
|
||||||
<div className="relative">
|
|
||||||
<input
|
|
||||||
type={showPassword ? "text" : "password"}
|
|
||||||
value={backupPassword}
|
|
||||||
onChange={(e) => setBackupPassword(e.target.value)}
|
|
||||||
placeholder="Backup Password"
|
|
||||||
className="w-full p-2 pr-8 rounded border border-border bg-secondary text-foreground focus:ring-2 focus:ring-primary outline-none"
|
|
||||||
/>
|
|
||||||
<button
|
|
||||||
onClick={() => setShowPassword(!showPassword)}
|
|
||||||
className="absolute right-2 top-2.5 text-muted-foreground hover:text-foreground"
|
|
||||||
>
|
|
||||||
{showPassword ? <EyeOff size={14} /> : <Eye size={14} />}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div className="flex justify-end gap-2 pt-2">
|
|
||||||
<button
|
|
||||||
onClick={() => setIsImportModalOpen(false)}
|
|
||||||
className="px-3 py-1.5 text-xs font-medium rounded border border-border hover:bg-secondary text-foreground transition-colors"
|
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={confirmImport}
|
|
||||||
disabled={!backupPassword}
|
|
||||||
className="px-3 py-1.5 text-xs font-medium rounded bg-primary text-primary-foreground hover:bg-primary/90 transition-colors disabled:opacity-50"
|
|
||||||
>
|
|
||||||
Decrypt & Import
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Email Template Editor Modal */}
|
{/* Email Template Editor Modal */}
|
||||||
<EmailTemplateEditor
|
<EmailTemplateEditor
|
||||||
isOpen={isEmailEditorOpen}
|
isOpen={isEmailEditorOpen}
|
||||||
@@ -382,6 +394,61 @@ const Settings: React.FC<SettingsProps> = ({ apiKey, productId, prompts, savePat
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="text-foreground font-semibold border-b border-border pb-2">📸 Branding</h3>
|
||||||
|
<div className="p-4 bg-secondary/20 rounded border border-border/50">
|
||||||
|
<div className="mb-3">
|
||||||
|
<div className="font-medium text-sm mb-2">Custom Logo</div>
|
||||||
|
<div className="text-xs text-muted-foreground mb-3">Upload your company logo to replace the default Livtec branding throughout the app.</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Logo Preview */}
|
||||||
|
<div className="flex items-center gap-4 mb-3">
|
||||||
|
<div className="w-20 h-20 bg-background border border-border rounded flex items-center justify-center overflow-hidden">
|
||||||
|
<img
|
||||||
|
src={localStorage.getItem('customLogo') || logo}
|
||||||
|
alt="Logo Preview"
|
||||||
|
className="max-w-full max-h-full object-contain"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex-1">
|
||||||
|
<button
|
||||||
|
onClick={async () => {
|
||||||
|
try {
|
||||||
|
const selected = await open({
|
||||||
|
filters: [{ name: 'Images', extensions: ['png', 'jpg', 'jpeg', 'svg'] }]
|
||||||
|
});
|
||||||
|
if (selected && typeof selected === 'string') {
|
||||||
|
const dataUrl = await invoke<string>('read_image_as_base64', { filePath: selected });
|
||||||
|
localStorage.setItem('customLogo', dataUrl);
|
||||||
|
setStatusIdx('Logo uploaded! Save settings to apply.');
|
||||||
|
// Force re-render
|
||||||
|
window.dispatchEvent(new Event('storage'));
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
setStatusIdx(`Logo upload failed: ${e}`);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="bg-secondary hover:bg-secondary/80 text-xs px-3 py-2 rounded border border-border transition-all flex items-center gap-2"
|
||||||
|
>
|
||||||
|
<Upload size={14} /> Upload Logo
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
localStorage.removeItem('customLogo');
|
||||||
|
setStatusIdx('Logo reset to default. Save to apply.');
|
||||||
|
window.dispatchEvent(new Event('storage'));
|
||||||
|
}}
|
||||||
|
className="mt-2 bg-secondary hover:bg-secondary/80 text-xs px-3 py-2 rounded border border-border transition-all text-muted-foreground"
|
||||||
|
>
|
||||||
|
Reset to Default
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="text-[10px] text-muted-foreground">Supported: PNG, JPG, SVG. Recommended: Square format, transparent background.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<h3 className="text-foreground font-semibold border-b border-border pb-2">System Intergration</h3>
|
<h3 className="text-foreground font-semibold border-b border-border pb-2">System Intergration</h3>
|
||||||
<div className="flex items-center justify-between p-4 bg-secondary/20 rounded border border-border/50">
|
<div className="flex items-center justify-between p-4 bg-secondary/20 rounded border border-border/50">
|
||||||
@@ -415,7 +482,7 @@ const Settings: React.FC<SettingsProps> = ({ apiKey, productId, prompts, savePat
|
|||||||
onClick={() => removePrompt(prompt.id)}
|
onClick={() => removePrompt(prompt.id)}
|
||||||
className="absolute top-2 right-2 text-muted-foreground hover:text-destructive opacity-0 group-hover:opacity-100 transition-opacity text-xs flex items-center gap-1"
|
className="absolute top-2 right-2 text-muted-foreground hover:text-destructive opacity-0 group-hover:opacity-100 transition-opacity text-xs flex items-center gap-1"
|
||||||
>
|
>
|
||||||
<EyeOff size={14} /> Remove
|
Remove
|
||||||
</button>
|
</button>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
@@ -563,31 +630,13 @@ const Settings: React.FC<SettingsProps> = ({ apiKey, productId, prompts, savePat
|
|||||||
|
|
||||||
{activeTab === 'backup' && (
|
{activeTab === 'backup' && (
|
||||||
<div className="space-y-6 max-w-xl">
|
<div className="space-y-6 max-w-xl">
|
||||||
|
{/* Manual Configuration Backup */}
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<h3 className="text-foreground font-semibold border-b border-border pb-2">Configuration Backup</h3>
|
<h3 className="text-foreground font-semibold border-b border-border pb-2">Manual Configuration Backup</h3>
|
||||||
<p className="text-xs text-muted-foreground">
|
<p className="text-xs text-muted-foreground">
|
||||||
Securely export your settings, including API keys and prompts. You must set a password to encrypt the backup file.
|
Export all your settings, including API keys, prompts, email templates, and history as JSON files.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<div className="relative">
|
|
||||||
<label className="block text-xs font-semibold text-muted-foreground mb-1 uppercase tracking-wide">
|
|
||||||
Encryption Password
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
type={showPassword ? "text" : "password"}
|
|
||||||
value={backupPassword}
|
|
||||||
onChange={(e) => setBackupPassword(e.target.value)}
|
|
||||||
placeholder="Enter a strong password"
|
|
||||||
className="w-full p-2 pr-8 rounded border border-border bg-secondary text-foreground focus:ring-2 focus:ring-primary outline-none text-sm"
|
|
||||||
/>
|
|
||||||
<button
|
|
||||||
onClick={() => setShowPassword(!showPassword)}
|
|
||||||
className="absolute right-2 top-8 text-muted-foreground hover:text-foreground"
|
|
||||||
>
|
|
||||||
{showPassword ? <EyeOff size={14} /> : <Eye size={14} />}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex gap-4 pt-2">
|
<div className="flex gap-4 pt-2">
|
||||||
<button
|
<button
|
||||||
onClick={handleExport}
|
onClick={handleExport}
|
||||||
@@ -604,12 +653,148 @@ const Settings: React.FC<SettingsProps> = ({ apiKey, productId, prompts, savePat
|
|||||||
<input
|
<input
|
||||||
type="file"
|
type="file"
|
||||||
id="import-file-input"
|
id="import-file-input"
|
||||||
accept=".conf"
|
accept=".json"
|
||||||
className="hidden"
|
className="hidden"
|
||||||
onChange={handleFileSelect}
|
onChange={handleFileSelect}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Daily Automated Backup */}
|
||||||
|
<div className="space-y-4 border-t border-border pt-6">
|
||||||
|
<h3 className="text-foreground font-semibold border-b border-border pb-2">Daily Automated Backup</h3>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Automatically backup your configuration once per day to prevent data loss. Backups are saved as JSON files.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
id="enable-daily-backup"
|
||||||
|
checked={localDailyBackupEnabled}
|
||||||
|
onChange={(e) => setLocalDailyBackupEnabled(e.target.checked)}
|
||||||
|
className="w-4 h-4"
|
||||||
|
/>
|
||||||
|
<label htmlFor="enable-daily-backup" className="text-sm text-foreground cursor-pointer">
|
||||||
|
Enable daily automated backup
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{localDailyBackupEnabled && (
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-semibold text-muted-foreground mb-1 uppercase tracking-wide">
|
||||||
|
Backup Location
|
||||||
|
</label>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={localDailyBackupPath}
|
||||||
|
onChange={(e) => setLocalDailyBackupPath(e.target.value)}
|
||||||
|
placeholder="Leave empty to use recordings folder"
|
||||||
|
className="flex-1 p-2 rounded border border-border bg-secondary text-foreground focus:ring-2 focus:ring-primary outline-none text-sm"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={async () => {
|
||||||
|
try {
|
||||||
|
const selected = await open({ directory: true, multiple: false });
|
||||||
|
if (selected && typeof selected === 'string') {
|
||||||
|
setLocalDailyBackupPath(selected);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="p-2 aspect-square flex items-center justify-center bg-secondary hover:bg-secondary/80 border border-border rounded text-foreground transition-all active:scale-95"
|
||||||
|
>
|
||||||
|
<FolderOpen size={16} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p className="text-[10px] text-muted-foreground mt-1">
|
||||||
|
Last backup: {props.lastBackupDate || 'Never'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === 'apps' && (
|
||||||
|
<div className="space-y-6 max-w-2xl h-full flex flex-col overflow-hidden">
|
||||||
|
<div className="space-y-4 flex-none">
|
||||||
|
<h3 className="text-foreground font-semibold border-b border-border pb-2 flex items-center gap-2">
|
||||||
|
<Lock size={16} /> Recording Filters
|
||||||
|
</h3>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Block specific apps to keep their audio out of your recordings (e.g., music or browser sounds).
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex-1 overflow-y-auto pr-2 space-y-6 custom-scrollbar">
|
||||||
|
{/* App Presets */}
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h4 className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider">Quick Select (Classic Apps)</h4>
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
{APP_PRESETS.map(group => (
|
||||||
|
<div key={group.category} className="space-y-2">
|
||||||
|
<h5 className="text-[11px] font-medium text-foreground/80">{group.category}</h5>
|
||||||
|
<div className="flex flex-wrap gap-1.5">
|
||||||
|
{group.apps.map(app => (
|
||||||
|
<button
|
||||||
|
key={app.id}
|
||||||
|
onClick={() => {
|
||||||
|
if (localBlockedApps.includes(app.id)) {
|
||||||
|
setLocalBlockedApps(localBlockedApps.filter(id => id !== app.id));
|
||||||
|
} else {
|
||||||
|
setLocalBlockedApps([...localBlockedApps, app.id]);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={`text-[10px] px-2 py-1 rounded border transition-all active:scale-95 ${localBlockedApps.includes(app.id)
|
||||||
|
? 'bg-primary/20 border-primary text-primary font-medium'
|
||||||
|
: 'bg-secondary/50 border-border/50 text-muted-foreground hover:border-border hover:text-foreground'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{app.name}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Running Apps */}
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h4 className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider">Currently Running</h4>
|
||||||
|
<div className="grid gap-2">
|
||||||
|
{runningApps.length > 0 ? (
|
||||||
|
runningApps.map(app => (
|
||||||
|
<label key={app.bundle_id} className="flex items-center justify-between p-3 bg-secondary/10 rounded border border-border/50 hover:bg-secondary/20 transition-colors cursor-pointer capitalize">
|
||||||
|
<div className="flex flex-col">
|
||||||
|
<span className="font-medium text-sm">{app.name}</span>
|
||||||
|
<span className="text-[10px] text-muted-foreground font-mono">{app.bundle_id}</span>
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={localBlockedApps.includes(app.bundle_id)}
|
||||||
|
onChange={(e) => {
|
||||||
|
if (e.target.checked) {
|
||||||
|
setLocalBlockedApps([...localBlockedApps, app.bundle_id]);
|
||||||
|
} else {
|
||||||
|
setLocalBlockedApps(localBlockedApps.filter(id => id !== app.bundle_id));
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="w-4 h-4 rounded border-border bg-secondary text-primary focus:ring-primary"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<div className="text-center py-8 text-muted-foreground text-xs italic border border-dashed border-border rounded">
|
||||||
|
No running applications detected.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
716
src/components/Settings.tsx.bak
Normal file
716
src/components/Settings.tsx.bak
Normal file
@@ -0,0 +1,716 @@
|
|||||||
|
import React, { useState, useEffect } from 'react';
|
||||||
|
import { Save, FolderOpen, Lock, Upload, Download, Mail, FileText, ScrollText } from 'lucide-react';
|
||||||
|
import { save, open } from '@tauri-apps/plugin-dialog';
|
||||||
|
import { invoke } from '@tauri-apps/api/core';
|
||||||
|
import EmailTemplateEditor from './EmailTemplateEditor';
|
||||||
|
import logo from '../assets/logo.png';
|
||||||
|
|
||||||
|
import { PromptTemplate, EmailTemplate } from '../App';
|
||||||
|
|
||||||
|
interface SettingsProps {
|
||||||
|
apiKey: string;
|
||||||
|
productId: string;
|
||||||
|
savePath: string;
|
||||||
|
prompts: PromptTemplate[];
|
||||||
|
emailTemplates: EmailTemplate[];
|
||||||
|
smtpConfig: SmtpConfig;
|
||||||
|
azureConfig: AzureConfig;
|
||||||
|
dailyBackupEnabled: boolean;
|
||||||
|
dailyBackupPath: string;
|
||||||
|
lastBackupDate: string;
|
||||||
|
history: any[];
|
||||||
|
onSave: (
|
||||||
|
apiKey: string,
|
||||||
|
productId: string,
|
||||||
|
prompts: PromptTemplate[],
|
||||||
|
savePath: string,
|
||||||
|
smtp: SmtpConfig,
|
||||||
|
azure: AzureConfig,
|
||||||
|
emailTemplates: EmailTemplate[],
|
||||||
|
dailyBackupEnabled: boolean,
|
||||||
|
dailyBackupPath: string
|
||||||
|
) => void;
|
||||||
|
onHistoryUpdate: (history: any[]) => void;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SmtpConfig {
|
||||||
|
host: string;
|
||||||
|
port: string;
|
||||||
|
user: string;
|
||||||
|
pass: string;
|
||||||
|
sender: string;
|
||||||
|
senderName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AzureConfig {
|
||||||
|
clientId: string;
|
||||||
|
tenantId: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const Settings: React.FC<SettingsProps> = ({ apiKey, productId, prompts, savePath, onSave, onClose, ...props }) => {
|
||||||
|
const [localApiKey, setLocalApiKey] = useState(apiKey);
|
||||||
|
const [localProductId, setLocalProductId] = useState(productId);
|
||||||
|
const [localSavePath, setLocalSavePath] = useState(savePath);
|
||||||
|
|
||||||
|
const [localPrompts, setLocalPrompts] = useState<PromptTemplate[]>(prompts);
|
||||||
|
const [localEmailTemplates, setLocalEmailTemplates] = useState<EmailTemplate[]>(props.emailTemplates); // New state
|
||||||
|
const [localSmtp, setLocalSmtp] = useState<SmtpConfig>(props.smtpConfig);
|
||||||
|
const [localAzure, setLocalAzure] = useState<AzureConfig>(props.azureConfig);
|
||||||
|
const [localDailyBackupEnabled, setLocalDailyBackupEnabled] = useState(props.dailyBackupEnabled);
|
||||||
|
const [localDailyBackupPath, setLocalDailyBackupPath] = useState(props.dailyBackupPath);
|
||||||
|
const [statusIdx, setStatusIdx] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Email Template Editor State
|
||||||
|
const [editingTemplate, setEditingTemplate] = useState<EmailTemplate | null>(null);
|
||||||
|
const [isEmailEditorOpen, setIsEmailEditorOpen] = useState(false);
|
||||||
|
|
||||||
|
const [activeTab, setActiveTab] = useState<'general' | 'prompts' | 'email' | 'backup' | 'logs'>('general');
|
||||||
|
const [logs, setLogs] = useState<string>('Loading logs...');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (activeTab === 'logs') {
|
||||||
|
loadLogs();
|
||||||
|
}
|
||||||
|
}, [activeTab]);
|
||||||
|
|
||||||
|
const loadLogs = async () => {
|
||||||
|
try {
|
||||||
|
const content = await invoke<string>('read_log_file');
|
||||||
|
setLogs(content);
|
||||||
|
} catch (e) {
|
||||||
|
setLogs(`Failed to load logs: ${e}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSaveLogs = async () => {
|
||||||
|
try {
|
||||||
|
const filePath = await save({
|
||||||
|
defaultPath: `hearbit_logs_${new Date().toISOString().slice(0, 10)}.log`,
|
||||||
|
filters: [{
|
||||||
|
name: 'Log File',
|
||||||
|
extensions: ['log', 'txt']
|
||||||
|
}]
|
||||||
|
});
|
||||||
|
|
||||||
|
if (filePath) {
|
||||||
|
await invoke('save_text_file', { path: filePath, content: logs });
|
||||||
|
setStatusIdx(`Logs exported to: ${filePath}`);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
setStatusIdx(`Failed to export logs: ${e}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handlePromptChange = (id: string, field: 'name' | 'content', value: string) => {
|
||||||
|
setLocalPrompts(localPrompts.map(p => p.id === id ? { ...p, [field]: value } : p));
|
||||||
|
};
|
||||||
|
|
||||||
|
const addPrompt = () => {
|
||||||
|
setLocalPrompts([...localPrompts, { id: Date.now().toString(), name: 'New Prompt', content: '' }]);
|
||||||
|
};
|
||||||
|
|
||||||
|
const removePrompt = (id: string) => {
|
||||||
|
setLocalPrompts(localPrompts.filter(p => p.id !== id));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSaveEmailTemplate = (template: EmailTemplate) => {
|
||||||
|
const exists = localEmailTemplates.find(t => t.id === template.id);
|
||||||
|
if (exists) {
|
||||||
|
setLocalEmailTemplates(localEmailTemplates.map(t => t.id === template.id ? template : t));
|
||||||
|
} else {
|
||||||
|
setLocalEmailTemplates([...localEmailTemplates, template]);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const openEmailEditor = (template: EmailTemplate | null) => {
|
||||||
|
setEditingTemplate(template);
|
||||||
|
setIsEmailEditorOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
|
const removeEmailTemplate = (id: string) => {
|
||||||
|
setLocalEmailTemplates(localEmailTemplates.filter(t => t.id !== id));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSave = () => {
|
||||||
|
onSave(
|
||||||
|
localApiKey,
|
||||||
|
localProductId,
|
||||||
|
localPrompts,
|
||||||
|
localSavePath,
|
||||||
|
localSmtp,
|
||||||
|
localAzure,
|
||||||
|
localEmailTemplates,
|
||||||
|
localDailyBackupEnabled,
|
||||||
|
localDailyBackupPath
|
||||||
|
);
|
||||||
|
onClose();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSelectFolder = async () => {
|
||||||
|
try {
|
||||||
|
const selected = await open({
|
||||||
|
directory: true,
|
||||||
|
multiple: false,
|
||||||
|
defaultPath: localSavePath || undefined,
|
||||||
|
});
|
||||||
|
if (selected && typeof selected === 'string') {
|
||||||
|
setLocalSavePath(selected);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Failed to open directory picker", e);
|
||||||
|
setStatusIdx('Error: Failed to open directory picker.');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleExport = async () => {
|
||||||
|
try {
|
||||||
|
const data = {
|
||||||
|
apiKey: localApiKey,
|
||||||
|
productId: localProductId,
|
||||||
|
prompts: localPrompts,
|
||||||
|
savePath: localSavePath,
|
||||||
|
smtp: localSmtp,
|
||||||
|
azure: localAzure,
|
||||||
|
emailTemplates: localEmailTemplates,
|
||||||
|
history: props.history,
|
||||||
|
dailyBackup: {
|
||||||
|
enabled: localDailyBackupEnabled,
|
||||||
|
path: localDailyBackupPath,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Always save as JSON (no encryption)
|
||||||
|
const content = JSON.stringify(data, null, 2);
|
||||||
|
|
||||||
|
const filePath = await save({
|
||||||
|
defaultPath: `hearbit_backup_${new Date().toISOString().slice(0, 10)}.json`,
|
||||||
|
filters: [{
|
||||||
|
name: 'Hearbit Config',
|
||||||
|
extensions: ['json']
|
||||||
|
}]
|
||||||
|
});
|
||||||
|
|
||||||
|
if (filePath) {
|
||||||
|
await invoke('save_text_file', { path: filePath, content });
|
||||||
|
setStatusIdx(`Configuration exported to: ${filePath}`);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
setStatusIdx(`Export failed: ${e}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const triggerImport = () => {
|
||||||
|
document.getElementById('import-file-input')?.click();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const file = e.target.files?.[0];
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = (event) => {
|
||||||
|
if (event.target?.result) {
|
||||||
|
const content = event.target.result as string;
|
||||||
|
// Directly import without password modal since we don't use encryption
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(content);
|
||||||
|
|
||||||
|
if (data.apiKey) setLocalApiKey(data.apiKey);
|
||||||
|
if (data.productId) setLocalProductId(data.productId);
|
||||||
|
if (data.prompts) setLocalPrompts(data.prompts);
|
||||||
|
if (data.emailTemplates) setLocalEmailTemplates(data.emailTemplates);
|
||||||
|
if (data.savePath) setLocalSavePath(data.savePath);
|
||||||
|
if (data.smtp) setLocalSmtp(data.smtp);
|
||||||
|
if (data.azure) setLocalAzure(data.azure);
|
||||||
|
if (data.dailyBackup) {
|
||||||
|
if (data.dailyBackup.enabled !== undefined) setLocalDailyBackupEnabled(data.dailyBackup.enabled);
|
||||||
|
if (data.dailyBackup.path) setLocalDailyBackupPath(data.dailyBackup.path);
|
||||||
|
}
|
||||||
|
// Import history!
|
||||||
|
if (data.history && Array.isArray(data.history)) {
|
||||||
|
props.onHistoryUpdate(data.history);
|
||||||
|
}
|
||||||
|
|
||||||
|
setStatusIdx('Configuration imported! Click Save to apply.');
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
setStatusIdx(`Import failed: ${error}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
reader.readAsText(file);
|
||||||
|
e.target.value = '';
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
const handleCreateDevice = async () => {
|
||||||
|
try {
|
||||||
|
setStatusIdx('Creating Hearbit Audio device...');
|
||||||
|
await invoke('create_hearbit_audio_device');
|
||||||
|
setStatusIdx('Success! "Hearbit Audio" device created.');
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
setStatusIdx(`Error: ${e}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const tabs = [
|
||||||
|
{ id: 'general', label: 'General', icon: <Save size={14} /> },
|
||||||
|
{ id: 'prompts', label: 'Prompts', icon: <FileText size={14} /> },
|
||||||
|
{ id: 'email', label: 'Email', icon: <Mail size={14} /> },
|
||||||
|
{ id: 'backup', label: 'Backup', icon: <Lock size={14} /> },
|
||||||
|
{ id: 'logs', label: 'Logs', icon: <ScrollText size={14} /> },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col h-full bg-background font-mono text-sm relative">
|
||||||
|
{/* Import Password Modal */}
|
||||||
|
{/* Email Template Editor Modal */}
|
||||||
|
<EmailTemplateEditor
|
||||||
|
isOpen={isEmailEditorOpen}
|
||||||
|
onClose={() => setIsEmailEditorOpen(false)}
|
||||||
|
template={editingTemplate}
|
||||||
|
onSave={handleSaveEmailTemplate}
|
||||||
|
smtpConfig={localSmtp}
|
||||||
|
addToast={(msg, type) => setStatusIdx(`${type === 'error' ? 'Error' : 'Success'}: ${msg}`)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="flex flex-col border-b border-border/40 bg-secondary/10">
|
||||||
|
<div className="p-4 flex justify-between items-center">
|
||||||
|
<h2 className="text-lg font-semibold tracking-tight">Settings</h2>
|
||||||
|
<button onClick={handleSave} className="flex items-center gap-2 bg-primary text-primary-foreground px-4 py-2 rounded font-semibold hover:bg-primary/90 transition-all active:scale-95 text-xs">
|
||||||
|
<Save size={16} /> Save Changes
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tabs */}
|
||||||
|
<div className="flex px-4 gap-2">
|
||||||
|
{tabs.map(tab => (
|
||||||
|
<button
|
||||||
|
key={tab.id}
|
||||||
|
onClick={() => setActiveTab(tab.id)}
|
||||||
|
className={`px-4 py-2 text-xs font-medium border-b-2 transition-colors flex items-center gap-2 ${activeTab === tab.id ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground'}`}
|
||||||
|
>
|
||||||
|
{tab.icon} {tab.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex-1 overflow-y-auto p-6">
|
||||||
|
{activeTab === 'general' && (
|
||||||
|
<div className="space-y-6 max-w-2xl">
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="text-foreground font-semibold border-b border-border pb-2">Application Keys</h3>
|
||||||
|
<div>
|
||||||
|
<label htmlFor="apiKey" className="block text-sm font-medium mb-1 text-foreground">API Key</label>
|
||||||
|
<input
|
||||||
|
id="apiKey"
|
||||||
|
type="password"
|
||||||
|
value={localApiKey}
|
||||||
|
onChange={(e) => setLocalApiKey(e.target.value)}
|
||||||
|
className="w-full p-2 rounded border border-border bg-secondary text-foreground focus:ring-2 focus:ring-primary outline-none font-mono text-sm"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label htmlFor="productId" className="block text-sm font-medium mb-1 text-foreground">Product ID</label>
|
||||||
|
<input
|
||||||
|
id="productId"
|
||||||
|
type="text"
|
||||||
|
value={localProductId}
|
||||||
|
onChange={(e) => setLocalProductId(e.target.value)}
|
||||||
|
className="w-full p-2 rounded border border-border bg-secondary text-foreground focus:ring-2 focus:ring-primary outline-none font-mono text-sm"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="text-foreground font-semibold border-b border-border pb-2">Storage</h3>
|
||||||
|
<div>
|
||||||
|
<label htmlFor="savePath" className="block text-sm font-medium mb-1 text-foreground">Custom Recordings Folder</label>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<input
|
||||||
|
id="savePath"
|
||||||
|
type="text"
|
||||||
|
value={localSavePath}
|
||||||
|
onChange={(e) => setLocalSavePath(e.target.value)}
|
||||||
|
placeholder="/Users/username/Desktop/Recordings"
|
||||||
|
className="flex-1 p-2 rounded border border-border bg-secondary text-foreground focus:ring-2 focus:ring-primary outline-none font-mono text-sm"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={handleSelectFolder}
|
||||||
|
className="p-2 aspect-square flex items-center justify-center bg-secondary hover:bg-secondary/80 border border-border rounded text-foreground transition-all active:scale-95"
|
||||||
|
title="Pick Folder"
|
||||||
|
>
|
||||||
|
<FolderOpen size={16} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="text-foreground font-semibold border-b border-border pb-2">📸 Branding</h3>
|
||||||
|
<div className="p-4 bg-secondary/20 rounded border border-border/50">
|
||||||
|
<div className="mb-3">
|
||||||
|
<div className="font-medium text-sm mb-2">Custom Logo</div>
|
||||||
|
<div className="text-xs text-muted-foreground mb-3">Upload your company logo to replace the default Livtec branding throughout the app.</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Logo Preview */}
|
||||||
|
<div className="flex items-center gap-4 mb-3">
|
||||||
|
<div className="w-20 h-20 bg-background border border-border rounded flex items-center justify-center overflow-hidden">
|
||||||
|
<img
|
||||||
|
src={localStorage.getItem('customLogo') || logo}
|
||||||
|
alt="Logo Preview"
|
||||||
|
className="max-w-full max-h-full object-contain"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex-1">
|
||||||
|
<button
|
||||||
|
onClick={async () => {
|
||||||
|
try {
|
||||||
|
const selected = await open({
|
||||||
|
filters: [{ name: 'Images', extensions: ['png', 'jpg', 'jpeg', 'svg'] }]
|
||||||
|
});
|
||||||
|
if (selected && typeof selected === 'string') {
|
||||||
|
const dataUrl = await invoke<string>('read_image_as_base64', { filePath: selected });
|
||||||
|
localStorage.setItem('customLogo', dataUrl);
|
||||||
|
setStatusIdx('Logo uploaded! Save settings to apply.');
|
||||||
|
// Force re-render
|
||||||
|
window.dispatchEvent(new Event('storage'));
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
setStatusIdx(`Logo upload failed: ${e}`);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="bg-secondary hover:bg-secondary/80 text-xs px-3 py-2 rounded border border-border transition-all flex items-center gap-2"
|
||||||
|
>
|
||||||
|
<Upload size={14} /> Upload Logo
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
localStorage.removeItem('customLogo');
|
||||||
|
setStatusIdx('Logo reset to default. Save to apply.');
|
||||||
|
window.dispatchEvent(new Event('storage'));
|
||||||
|
}}
|
||||||
|
className="mt-2 bg-secondary hover:bg-secondary/80 text-xs px-3 py-2 rounded border border-border transition-all text-muted-foreground"
|
||||||
|
>
|
||||||
|
Reset to Default
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="text-[10px] text-muted-foreground">Supported: PNG, JPG, SVG. Recommended: Square format, transparent background.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="text-foreground font-semibold border-b border-border pb-2">System Intergration</h3>
|
||||||
|
<div className="flex items-center justify-between p-4 bg-secondary/20 rounded border border-border/50">
|
||||||
|
<div>
|
||||||
|
<div className="font-medium text-sm">Hearbit Audio Device</div>
|
||||||
|
<div className="text-xs text-muted-foreground">Required for recording system audio (Teams, Zoom, etc.)</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={handleCreateDevice}
|
||||||
|
className="bg-secondary hover:bg-secondary/80 text-xs px-3 py-2 rounded border border-border transition-all active:scale-95 flex items-center gap-2"
|
||||||
|
>
|
||||||
|
<span>🪄</span> Create / Repair
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === 'prompts' && (
|
||||||
|
<div className="space-y-4 max-w-3xl">
|
||||||
|
<div className="flex justify-between items-center border-b border-border pb-2">
|
||||||
|
<h3 className="text-foreground font-semibold">AI Prompts</h3>
|
||||||
|
<button onClick={addPrompt} className="text-xs bg-primary text-primary-foreground px-3 py-1.5 rounded hover:bg-primary/90 transition-all active:scale-95">
|
||||||
|
+ Add Prompt
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="grid gap-4">
|
||||||
|
{localPrompts.map((prompt) => (
|
||||||
|
<div key={prompt.id} className="space-y-2 p-4 bg-secondary/10 rounded border border-border/50 relative group">
|
||||||
|
<button
|
||||||
|
onClick={() => removePrompt(prompt.id)}
|
||||||
|
className="absolute top-2 right-2 text-muted-foreground hover:text-destructive opacity-0 group-hover:opacity-100 transition-opacity text-xs flex items-center gap-1"
|
||||||
|
>
|
||||||
|
Remove
|
||||||
|
</button>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={prompt.name}
|
||||||
|
onChange={(e) => handlePromptChange(prompt.id, 'name', e.target.value)}
|
||||||
|
className="w-full p-1 bg-transparent border-b border-border/50 focus:border-primary outline-none font-semibold text-sm"
|
||||||
|
placeholder="Prompt Name"
|
||||||
|
/>
|
||||||
|
<textarea
|
||||||
|
value={prompt.content}
|
||||||
|
onChange={(e) => handlePromptChange(prompt.id, 'content', e.target.value)}
|
||||||
|
className="w-full p-2 bg-secondary/50 rounded border border-border/30 focus:border-primary outline-none text-xs resize-y min-h-[100px] font-mono"
|
||||||
|
placeholder="Prompt Content"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === 'email' && (
|
||||||
|
<div className="space-y-8 max-w-2xl">
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex justify-between items-center border-b border-border pb-2">
|
||||||
|
<h3 className="text-foreground font-semibold">Email Templates</h3>
|
||||||
|
<button
|
||||||
|
onClick={() => openEmailEditor(null)}
|
||||||
|
className="text-xs bg-primary text-primary-foreground px-3 py-1.5 rounded hover:bg-primary/90 transition-all active:scale-95"
|
||||||
|
>
|
||||||
|
+ Add Template
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-2">
|
||||||
|
{localEmailTemplates.map((template) => (
|
||||||
|
<div key={template.id} className="flex justify-between items-center p-4 bg-secondary/10 rounded border border-border/50 group hover:border-border/80 transition-colors">
|
||||||
|
<div className="flex-1 min-w-0 pr-4">
|
||||||
|
<div className="font-semibold text-sm truncate">{template.name}</div>
|
||||||
|
<div className="text-xs text-muted-foreground truncate">{template.subject}</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2 shrink-0">
|
||||||
|
<button
|
||||||
|
onClick={() => openEmailEditor(template)}
|
||||||
|
className="px-2 py-1 text-xs font-medium text-primary hover:bg-primary/10 rounded transition-colors"
|
||||||
|
>
|
||||||
|
Edit
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => removeEmailTemplate(template.id)}
|
||||||
|
className="px-2 py-1 text-xs font-medium text-muted-foreground hover:text-destructive hover:bg-destructive/10 rounded transition-colors"
|
||||||
|
>
|
||||||
|
Remove
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{localEmailTemplates.length === 0 && (
|
||||||
|
<div className="text-center p-8 text-muted-foreground text-xs italic border border-dashed border-border rounded">
|
||||||
|
No templates created yet.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="text-foreground font-semibold border-b border-border pb-2">SMTP Configuration</h3>
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-1 text-foreground">SMTP Host</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={localSmtp.host}
|
||||||
|
onChange={(e) => setLocalSmtp({ ...localSmtp, host: e.target.value })}
|
||||||
|
className="w-full p-2 rounded border border-border bg-secondary text-foreground focus:ring-2 focus:ring-primary outline-none font-mono text-sm"
|
||||||
|
placeholder="smtp.office365.com"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-1 text-foreground">Port</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={localSmtp.port}
|
||||||
|
onChange={(e) => setLocalSmtp({ ...localSmtp, port: e.target.value })}
|
||||||
|
className="w-full p-2 rounded border border-border bg-secondary text-foreground focus:ring-2 focus:ring-primary outline-none font-mono text-sm"
|
||||||
|
placeholder="587"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="col-span-2">
|
||||||
|
<label className="block text-sm font-medium mb-1 text-foreground">Sender Email</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={localSmtp.sender}
|
||||||
|
onChange={(e) => setLocalSmtp({ ...localSmtp, sender: e.target.value })}
|
||||||
|
className="w-full p-2 rounded border border-border bg-secondary text-foreground focus:ring-2 focus:ring-primary outline-none font-mono text-sm"
|
||||||
|
placeholder="you@company.com"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="col-span-2">
|
||||||
|
<label className="block text-sm font-medium mb-1 text-foreground">Sender Name (Optional)</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={localSmtp.senderName}
|
||||||
|
onChange={(e) => setLocalSmtp({ ...localSmtp, senderName: e.target.value })}
|
||||||
|
className="w-full p-2 rounded border border-border bg-secondary text-foreground focus:ring-2 focus:ring-primary outline-none font-mono text-sm"
|
||||||
|
placeholder="Hearbit Assistant"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-1 text-foreground">Username</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={localSmtp.user}
|
||||||
|
onChange={(e) => setLocalSmtp({ ...localSmtp, user: e.target.value })}
|
||||||
|
className="w-full p-2 rounded border border-border bg-secondary text-foreground focus:ring-2 focus:ring-primary outline-none font-mono text-sm"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-1 text-foreground">Password</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
value={localSmtp.pass}
|
||||||
|
onChange={(e) => setLocalSmtp({ ...localSmtp, pass: e.target.value })}
|
||||||
|
className="w-full p-2 rounded border border-border bg-secondary text-foreground focus:ring-2 focus:ring-primary outline-none font-mono text-sm"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="text-foreground font-semibold border-b border-border pb-2">Microsoft 365 (Azure AD)</h3>
|
||||||
|
<p className="text-xs text-muted-foreground">Optional configuration for advanced MS Graph integrations.</p>
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-1 text-foreground">Client ID</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={localAzure.clientId}
|
||||||
|
onChange={(e) => setLocalAzure({ ...localAzure, clientId: e.target.value })}
|
||||||
|
className="w-full p-2 rounded border border-border bg-secondary text-foreground focus:ring-2 focus:ring-primary outline-none font-mono text-sm"
|
||||||
|
placeholder="Application (client) ID"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === 'backup' && (
|
||||||
|
<div className="space-y-6 max-w-xl">
|
||||||
|
{/* Manual Configuration Backup */}
|
||||||
|
<div className="space-y-4">
|
||||||
|
<h3 className="text-foreground font-semibold border-b border-border pb-2">Manual Configuration Backup</h3>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Export all your settings, including API keys, prompts, email templates, and history as JSON files.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="flex gap-4 pt-2">
|
||||||
|
<button
|
||||||
|
onClick={handleExport}
|
||||||
|
className="flex-1 flex items-center justify-center gap-2 py-3 px-4 rounded-lg bg-secondary hover:bg-secondary/80 border border-border text-foreground transition-all font-semibold active:scale-95"
|
||||||
|
>
|
||||||
|
<Download size={18} /> Export Config
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={triggerImport}
|
||||||
|
className="flex-1 flex items-center justify-center gap-2 py-3 px-4 rounded-lg bg-secondary hover:bg-secondary/80 border border-border text-foreground transition-all font-semibold active:scale-95"
|
||||||
|
>
|
||||||
|
<Upload size={18} /> Import Config
|
||||||
|
</button>
|
||||||
|
<input
|
||||||
|
type="file"
|
||||||
|
id="import-file-input"
|
||||||
|
accept=".json"
|
||||||
|
className="hidden"
|
||||||
|
onChange={handleFileSelect}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Daily Automated Backup */}
|
||||||
|
<div className="space-y-4 border-t border-border pt-6">
|
||||||
|
<h3 className="text-foreground font-semibold border-b border-border pb-2">Daily Automated Backup</h3>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Automatically backup your configuration once per day to prevent data loss. Backups are saved as JSON files.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
id="enable-daily-backup"
|
||||||
|
checked={localDailyBackupEnabled}
|
||||||
|
onChange={(e) => setLocalDailyBackupEnabled(e.target.checked)}
|
||||||
|
className="w-4 h-4"
|
||||||
|
/>
|
||||||
|
<label htmlFor="enable-daily-backup" className="text-sm text-foreground cursor-pointer">
|
||||||
|
Enable daily automated backup
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{localDailyBackupEnabled && (
|
||||||
|
<div>
|
||||||
|
<label className="block text-xs font-semibold text-muted-foreground mb-1 uppercase tracking-wide">
|
||||||
|
Backup Location
|
||||||
|
</label>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={localDailyBackupPath}
|
||||||
|
onChange={(e) => setLocalDailyBackupPath(e.target.value)}
|
||||||
|
placeholder="Leave empty to use recordings folder"
|
||||||
|
className="flex-1 p-2 rounded border border-border bg-secondary text-foreground focus:ring-2 focus:ring-primary outline-none text-sm"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
onClick={async () => {
|
||||||
|
try {
|
||||||
|
const selected = await open({ directory: true, multiple: false });
|
||||||
|
if (selected && typeof selected === 'string') {
|
||||||
|
setLocalDailyBackupPath(selected);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error(e);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="p-2 aspect-square flex items-center justify-center bg-secondary hover:bg-secondary/80 border border-border rounded text-foreground transition-all active:scale-95"
|
||||||
|
>
|
||||||
|
<FolderOpen size={16} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p className="text-[10px] text-muted-foreground mt-1">
|
||||||
|
Last backup: {props.lastBackupDate || 'Never'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === 'logs' && (
|
||||||
|
<div className="space-y-4 max-w-4xl h-full flex flex-col">
|
||||||
|
<div className="flex justify-between items-center border-b border-border pb-2">
|
||||||
|
<h3 className="text-foreground font-semibold">Application Logs</h3>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<button
|
||||||
|
onClick={handleSaveLogs}
|
||||||
|
className="text-xs bg-secondary hover:bg-secondary/80 px-2 py-1 rounded border border-border transition-all active:scale-95 flex items-center gap-1"
|
||||||
|
>
|
||||||
|
<Download size={12} /> Export Logs
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={loadLogs}
|
||||||
|
className="text-xs bg-secondary hover:bg-secondary/80 px-2 py-1 rounded border border-border transition-all active:scale-95"
|
||||||
|
>
|
||||||
|
Refresh Logs
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex-1 bg-black text-white p-4 rounded font-mono text-xs overflow-auto whitespace-pre-wrap leading-relaxed shadow-inner">
|
||||||
|
{logs}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{
|
||||||
|
statusIdx && (
|
||||||
|
<div className={`p-2 text-xs text-center border-t ${statusIdx.includes('Error') || statusIdx.includes('failed') ? 'bg-destructive/10 border-destructive text-destructive' : 'bg-green-500/10 border-green-500 text-green-500'}`}>
|
||||||
|
{statusIdx}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
</div >
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Settings;
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Mic, FileText, Calendar } from 'lucide-react';
|
import { Mic, FileText, Calendar, Upload } from 'lucide-react';
|
||||||
|
|
||||||
interface TabsProps {
|
interface TabsProps {
|
||||||
currentTab: 'recorder' | 'transcription' | 'settings' | 'meetings' | 'history';
|
currentTab: 'recorder' | 'transcription' | 'settings' | 'meetings' | 'history' | 'import';
|
||||||
onTabChange: (tab: 'recorder' | 'transcription' | 'settings' | 'meetings' | 'history') => void;
|
onTabChange: (tab: 'recorder' | 'transcription' | 'settings' | 'meetings' | 'history' | 'import') => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
const Tabs: React.FC<TabsProps> = ({ currentTab, onTabChange }) => {
|
const Tabs: React.FC<TabsProps> = ({ currentTab, onTabChange }) => {
|
||||||
@@ -16,6 +16,13 @@ const Tabs: React.FC<TabsProps> = ({ currentTab, onTabChange }) => {
|
|||||||
<Mic size={16} />
|
<Mic size={16} />
|
||||||
Recording
|
Recording
|
||||||
</button>
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => onTabChange('import')}
|
||||||
|
className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${currentTab === 'import' ? 'bg-secondary text-foreground' : 'text-muted-foreground hover:text-foreground hover:bg-secondary/50'}`}
|
||||||
|
>
|
||||||
|
<Upload size={16} />
|
||||||
|
Import
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={() => onTabChange('transcription')}
|
onClick={() => onTabChange('transcription')}
|
||||||
className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${currentTab === 'transcription' ? 'bg-secondary text-foreground' : 'text-muted-foreground hover:text-foreground hover:bg-secondary/50'}`}
|
className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${currentTab === 'transcription' ? 'bg-secondary text-foreground' : 'text-muted-foreground hover:text-foreground hover:bg-secondary/50'}`}
|
||||||
|
|||||||
Reference in New Issue
Block a user