diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..4b47958 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,71 @@ +name: Build and Release Teams Helper + +on: + push: + tags: + - 'v*' + +permissions: + contents: write + +jobs: + build: + runs-on: windows-latest + + steps: + - name: Checkout Code + uses: actions/checkout@v3 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: 3.9 + + - name: Install Dependencies + run: | + pip install -r requirements.txt + pip install pyinstaller + + - name: Build Executable + run: | + pyinstaller --clean --onefile --noconsole --icon=icon.ico --add-data "icon.ico;." --name TeamsHelper main.py + + - name: Upload Artifact + uses: actions/upload-artifact@v4 + with: + name: TeamsHelper-Executable + path: dist/TeamsHelper.exe + + release: + needs: build + runs-on: ubuntu-latest + + steps: + - name: Download Built Executable + uses: actions/download-artifact@v4 + with: + name: TeamsHelper-Executable + path: dist + + - name: Create GitHub Release + id: create_release + uses: actions/create-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: ${{ github.ref_name }} + release_name: Teams Helper ${{ github.ref_name }} + body: | + This release includes the latest version of Teams Helper. + draft: false + prerelease: false + + - name: Upload to Release + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} + asset_path: dist/TeamsHelper.exe + asset_name: TeamsHelper-${{ github.ref_name }}.exe + asset_content_type: application/octet-stream diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..82f9275 --- /dev/null +++ b/.gitignore @@ -0,0 +1,162 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/latest/usage/project/#working-with-version-control +.pdm.toml +.pdm-python +.pdm-build/ + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..d1be143 --- /dev/null +++ b/README.md @@ -0,0 +1,132 @@ + +# Microsoft Teams Helper App + +## Overview +The **Microsoft Teams Helper App** is a desktop application that integrates with the Microsoft Teams client to record audio during meetings. It provides seamless audio recording by combining inputs from your microphone and the Stereo Mix. + +### Key Features +- **Automatic Audio Recording**: Starts recording automatically when the meeting state changes. +- **Changeable Recording Folder**: Modify the default recording folder through the settings menu. +- **Lightweight Integration**: Uses the local Teams client API to avoid additional permissions or configurations. +- **Logs and Recording Management**: Logs are saved in the recording folder for troubleshooting. + +--- + +## Setup +1. Download TeamsHelper-v1.x.exe from ([Releases](https://github.com/kyvaith/TeamsHelper/releases)) to your Windows computer that runs the New Teams client +2. In Microsoft Teams, enable the Third-Party + API ([see Microsoft documentation](https://support.microsoft.com/en-us/office/connect-to-third-party-devices-in-microsoft-teams-aabca9f2-47bb-407f-9f9b-81a104a883d6?storagetype=live)) +3. Enable Stereo Mix in your system +4. Run the application. You can find it in the system tray + +## Enabling Stereo Mix on Windows + +To ensure proper functionality, you may need to enable Stereo Mix on your system: +1. Right-click on the speaker icon in the system tray. +2. Select **"Sounds"**. +3. Navigate to the **"Recording"** tab. +4. If **"Stereo Mix"** or **"Sound Mixer"** is listed but disabled, right-click it and choose **"Enable"**. +5. If it's not listed: + - Right-click in an empty space and check both **"Show Disabled Devices"** and **"Show Disconnected Devices"**. + - Look for **"Stereo Mix"** or **"Sound Mixer"**, right-click, and select **"Enable"**. +6. Click **"OK"** to save your changes. + +--- + +## Notices +- **Pull Requests, Issues, and Feature Requests are welcomed!** +- This integration supports only the **New Teams (2.0 client)**. +- **Logs** are stored in `app.log` in the recordings folder. +- The **recordings folder** can be changed through the settings menu. +- The app uses the **local Teams client API** instead of Azure/M365 for simplicity. + +### Advantages of Local Teams API +- **No permissions or app registrations** required in Azure. +- Organizations don't need to approve additional exceptions for security policies. + +### Limitations of Local Teams API +- The app cannot detect meetings joined via other clients, such as mobile or web. + +--- + +## API Details + +### Example Connections +1. **Before Token Acquisition**: + ``` + ws://localhost:8124?protocol-version=2.0.0&manufacturer=Kyvaith&device=TeamsHelper&app=TeamsHelper&app-version=1.0 + ``` +2. **After Token Acquisition**: + ``` + ws://localhost:8124?token=&protocol-version=2.0.0&manufacturer=Kyvaith&device=TeamsHelper&app=TeamsHelper&app-version=1.0 + ``` + +### Example Updates and Requests +1. **Teams -> Client Update**: + ```json + { + "meetingUpdate": { + "meetingState": { + "isMuted": false, + "isVideoOn": false, + "isHandRaised": false, + "isInMeeting": true, + "isRecordingOn": false, + "isBackgroundBlurred": false, + "isSharing": false, + "hasUnreadMessages": false + }, + "meetingPermissions": { + "canToggleMute": true, + "canToggleVideo": true, + "canToggleHand": true, + "canToggleBlur": false, + "canLeave": true, + "canReact": true, + "canToggleShareTray": true, + "canToggleChat": true, + "canStopSharing": false, + "canPair": false + } + } + } + ``` + +2. **Client -> Teams Request Toggle Mute**: + ```json + { + "requestId": 1, + "apiVersion": "2.0.0", + "action": "toggle-mute" + } + ``` + +3. **Teams -> Client Request Confirmation**: + ```json + { + "requestId": 2, + "response": "Success" + } + ``` + +4. **Client -> Teams Token Refresh**: + ```json + { + "tokenRefresh": "132cf8d9-403f-4d71-9067-8390160224cb" + } + ``` + +### Reference Document (Legacy Teams) +For more details on the legacy Teams API, refer to the [Microsoft Teams WebSocket API Documentation](https://lostdomain.notion.site/Microsoft-Teams-WebSocket-API-5c042838bc3e4731bdfe679e864ab52a). + +--- + +## License + +This project is licensed under the **Apache License 2.0**. See the [LICENSE](LICENSE) file for details. + +--- + +## Contributing + +Contributions are welcome! Please open issues or pull requests for new features, bug fixes, or documentation improvements. diff --git a/icon.ico b/icon.ico new file mode 100644 index 0000000..15072c3 Binary files /dev/null and b/icon.ico differ diff --git a/main.py b/main.py new file mode 100644 index 0000000..5954b76 --- /dev/null +++ b/main.py @@ -0,0 +1,373 @@ +""" +Teams Helper +Version: 1.0 +Author: Tomasz Witke +License: Apache License 2.0 + +Description: +A desktop application for managing audio recordings during Microsoft Teams meetings. +""" + +import os +import sys +import threading +import logging +import signal +import json +import time +from datetime import datetime +from tkinter import Tk, messagebox, filedialog, StringVar, Label, Entry, Button + +import numpy as np +import sounddevice as sd +import lameenc +from pystray import Icon, Menu, MenuItem +from PIL import Image +from websocket import create_connection, WebSocketConnectionClosedException +import configparser + + +class TeamsHelperRecorder: + """ + Main recorder class for Teams Helper. + Handles audio recording, settings management, and integration with Teams API. + """ + def __init__(self, sample_rate=44100, channels=2, buffer_size=1024): + self.sample_rate = sample_rate + self.channels = channels + self.buffer_size = buffer_size + self.recording = False + self.stop_flag = False + self.frames = [] + self.ws = None + self.can_toggle_mute = False + self.record_all_meetings = True # Default to True + + # Paths and settings + self.settings_file = os.path.join(os.getenv("APPDATA"), "teamshelper", "settings.ini") + self.output_dir = self.load_settings() + os.makedirs(self.output_dir, exist_ok=True) + self.tray_icon = None + + # Logging setup + self.configure_logging() + + # LAME MP3 encoder setup + self.encoder = lameenc.Encoder() + self.encoder.set_bit_rate(128) + self.encoder.set_in_sample_rate(self.sample_rate) + self.encoder.set_channels(self.channels) + self.encoder.set_quality(2) + + def get_icon_path(self): + """ + Get the path to the `icon.ico` file. + Handles both development and compiled (PyInstaller) environments. + """ + if hasattr(sys, "_MEIPASS"): + return os.path.join(sys._MEIPASS, "icon.ico") + return os.path.join(os.path.dirname(__file__), "icon.ico") + + def set_tray_icon(self, icon): + """ + Set the tray icon object for the application. + """ + self.tray_icon = icon + self.update_tray_title() + + def update_tray_title(self): + """ + Update the tray icon's title based on the recording state. + """ + if self.tray_icon: + state = "Recording" if self.recording else "Idle" + self.tray_icon.title = f"Teams Helper - {state}" + + def load_settings(self): + """ + Load application settings from the configuration file. + If the file does not exist, create it with default values. + """ + config = configparser.ConfigParser() + default_folder = os.path.join(os.path.expanduser("~"), "Downloads", "Recordings") + if os.path.exists(self.settings_file): + config.read(self.settings_file) + return config.get("Settings", "output_dir", fallback=default_folder) + else: + os.makedirs(os.path.dirname(self.settings_file), exist_ok=True) + self.save_settings(default_folder) + return default_folder + + def save_settings(self, output_dir): + """ + Save application settings to the configuration file. + """ + config = configparser.ConfigParser() + config["Settings"] = {"output_dir": output_dir} + with open(self.settings_file, "w") as configfile: + config.write(configfile) + self.output_dir = output_dir + os.makedirs(self.output_dir, exist_ok=True) + self.configure_logging() + + def configure_logging(self): + """ + Configure logging to save logs in the output directory. + """ + self.log_file = os.path.join(self.output_dir, "app.log") + logging.basicConfig( + filename=self.log_file, + level=logging.DEBUG, + format="%(asctime)s - %(levelname)s - %(message)s", + ) + logging.getLogger("PIL").setLevel(logging.WARNING) + logging.info("Teams Helper started. Recordings and logs will be saved in '%s'.", self.output_dir) + + def show_error(self, title, message): + """ + Display an error message in a popup window. + """ + logging.error(f"{title}: {message}") + root = Tk() + root.withdraw() # Hide the main Tkinter window + messagebox.showerror(title, message) + root.destroy() + + def show_settings_window(self): + """ + Display the settings window for changing the output directory. + """ + def settings_window(): + def browse_folder(): + """ + Open a dialog to select a new folder. + """ + folder = filedialog.askdirectory(initialdir=self.output_dir) + if folder: + folder_var.set(folder) + + def save_settings(): + """ + Save the selected folder and close the settings window. + """ + selected_folder = folder_var.get() + if os.path.isdir(selected_folder): + self.save_settings(selected_folder) + messagebox.showinfo("Settings", f"Folder changed to: {selected_folder}") + root.destroy() + else: + messagebox.showerror("Error", "The selected folder does not exist. Please select a valid folder.") + + # Create the settings window + root = Tk() + root.title("Settings") + root.geometry("500x150") + root.iconbitmap(self.get_icon_path()) + + # Current folder label and entry + folder_var = StringVar(value=self.output_dir) + Label(root, text="Current Recording Folder:", anchor="w").pack(fill="x", padx=10, pady=5) + Entry(root, textvariable=folder_var, state="readonly", width=60).pack(fill="x", padx=10, pady=5) + + # Buttons + Button(root, text="Browse...", command=browse_folder).pack(side="left", padx=10, pady=10) + Button(root, text="Save", command=save_settings).pack(side="right", padx=10, pady=10) + + root.mainloop() + + threading.Thread(target=settings_window, daemon=True).start() + + def toggle_record_all_meetings(self): + """ + Toggle the setting to record all meetings automatically. + """ + self.record_all_meetings = not self.record_all_meetings + state = "enabled" if self.record_all_meetings else "disabled" + print(f"[INFO] Record All Meetings is now {state}.") + logging.info("Record All Meetings toggled to: %s", state) + + def connect_to_teams(self): + """ + Establish a WebSocket connection to the Teams API. + Monitors meeting events and triggers recording. + """ + base_url = "ws://localhost:8124" + url = f"{base_url}?protocol-version=2.0.0&manufacturer=Kyvaith&device=TeamsHelper&app=TeamsHelper&app-version=1.0" + + print("[INFO] Connecting to Microsoft Teams API...") + logging.info("Connecting to Microsoft Teams API...") + + try: + self.ws = create_connection(url) + self.ws.settimeout(1) # Non-blocking mode + logging.info("Connected to Microsoft Teams WebSocket.") + print("[INFO] Connected to Microsoft Teams WebSocket.") + + while not self.stop_flag: + try: + message = self.ws.recv() + self.handle_teams_update(message) + except WebSocketConnectionClosedException: + logging.warning("WebSocket connection closed.") + print("[WARN] WebSocket connection closed.") + break + except Exception as e: + time.sleep(0.1) + + if self.ws: + self.ws.close() + print("[INFO] WebSocket connection closed.") + logging.info("WebSocket connection closed.") + + except Exception as e: + self.show_error("Teams API Connection Error", f"Failed to connect to Teams API: {e}") + + def handle_teams_update(self, message): + """ + Process updates from Microsoft Teams WebSocket API. + """ + try: + logging.debug("Received WebSocket message: %s", message) + update = json.loads(message) + + # Extract the meeting permissions and status + meeting_permissions = update.get("meetingUpdate", {}).get("meetingPermissions", {}) + can_toggle_mute = meeting_permissions.get("canToggleMute", False) + + # Start or stop recording based on meeting state + if self.record_all_meetings: + if can_toggle_mute and not self.can_toggle_mute: + self.can_toggle_mute = True + self.start_recording() + elif not can_toggle_mute and self.can_toggle_mute: + self.can_toggle_mute = False + self.stop_recording() + + except Exception as e: + self.show_error("Teams API Update Error", str(e)) + + def start_recording(self): + """ + Start the audio recording process. + """ + print("[INFO] Starting recording...") + logging.info("Starting recording...") + self.recording = True + self.update_tray_title() + self.recording_thread = threading.Thread(target=self.record_audio) + self.recording_thread.start() + + def record_audio(self): + """ + Record audio from both Stereo Mix and Microphone. + """ + try: + stereo_mix_device = self.get_device_by_name("Stereo Mix") + microphone_device = self.get_device_by_name("Microphone") + + if stereo_mix_device is None or microphone_device is None: + raise RuntimeError("Required audio devices not found.") + + formatted_time = datetime.now().strftime("%Y-%m-%d %H-%M-%S") + mp3_file = os.path.join(self.output_dir, f"Recording {formatted_time}.mp3") + print(f"[INFO] Recording directly to {mp3_file}") + + with open(mp3_file, "wb") as mp3: + with sd.InputStream(samplerate=self.sample_rate, + channels=self.channels, + dtype='int16', + device=stereo_mix_device, + blocksize=self.buffer_size) as stereo_stream, \ + sd.InputStream(samplerate=self.sample_rate, + channels=self.channels, + dtype='int16', + device=microphone_device, + blocksize=self.buffer_size) as mic_stream: + + while self.recording: + stereo_data, _ = stereo_stream.read(self.buffer_size) + mic_data, _ = mic_stream.read(self.buffer_size) + combined_data = np.add(stereo_data, mic_data, dtype=np.int32) + + # Normalize audio if it exceeds 16-bit range + max_value = np.max(np.abs(combined_data)) + if max_value > 32767: + scaling_factor = 32767 / max_value + combined_data = (combined_data * scaling_factor).astype(np.int16) + else: + combined_data = combined_data.astype(np.int16) + + mp3_data = self.encoder.encode(combined_data.tobytes()) + mp3.write(mp3_data) + + mp3.write(self.encoder.flush()) + + print(f"[INFO] Recording saved as {mp3_file}") + except Exception as e: + self.show_error("Recording Error", str(e)) + + def stop_recording(self): + """ + Stop the audio recording process. + """ + print("[INFO] Stopping recording...") + logging.info("Stopping recording...") + self.recording = False + self.update_tray_title() + if hasattr(self, "recording_thread"): + self.recording_thread.join() + + def get_device_by_name(self, device_name): + """ + Find an audio device by its name. + """ + devices = sd.query_devices() + for i, device in enumerate(devices): + if device_name.lower() in device.get("name", "").lower(): + return i + return None + + +def create_tray_icon(recorder): + """ + Create the system tray icon with context menu. + """ + def exit_app(icon, item): + recorder.stop_flag = True + icon.stop() + sys.exit(0) + + menu = Menu( + MenuItem( + "Record All Meetings", + lambda icon, item: recorder.toggle_record_all_meetings(), + checked=lambda item: recorder.record_all_meetings, + ), + MenuItem("Settings", lambda icon, item: recorder.show_settings_window()), + MenuItem("Exit", exit_app), + ) + + icon_path = recorder.get_icon_path() + icon_image = Image.open(icon_path) + icon = Icon("Teams Helper", icon_image, "Teams Helper - Idle", menu) + recorder.set_tray_icon(icon) + return icon + + +def main(): + """ + Main entry point for the application. + """ + recorder = TeamsHelperRecorder() + tray_icon = create_tray_icon(recorder) + + # Start Teams WebSocket connection in a separate thread + threading.Thread(target=recorder.connect_to_teams, daemon=True).start() + + signal.signal(signal.SIGINT, lambda sig, frame: tray_icon.stop()) + + tray_icon.run() + + +if __name__ == "__main__": + main() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..545a37b --- /dev/null +++ b/requirements.txt @@ -0,0 +1,9 @@ +sounddevice +numpy +pyinstaller +lameenc +pystray +pillow +pywin32 +olefile +websocket-client diff --git a/teams_helper.spec b/teams_helper.spec new file mode 100644 index 0000000..33e1573 --- /dev/null +++ b/teams_helper.spec @@ -0,0 +1,44 @@ +# teams_helper.spec +# Generated for building the Teams Helper application into a standalone executable. + +# Import PyInstaller build spec functionalities +block_cipher = None + +a = Analysis( + ['main.py'], # Main entry point of the application + pathex=['.'], # Include current directory + binaries=[], + datas=[], + hiddenimports=['lameenc', 'pystray', 'PIL.Image', 'PIL.ImageDraw'], + hookspath=[], + runtime_hooks=[], + excludes=[], + win_no_prefer_redirects=False, + win_private_assemblies=False, + cipher=block_cipher, +) +pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) + +exe = EXE( + pyz, + a.scripts, + [], + exclude_binaries=True, + name='TeamsHelper', + debug=False, + bootloader_ignore_signals=False, + strip=False, + upx=True, + console=False, # Use False if you want a GUI app (no console window) + icon='icon.ico', # Optional: Path to your icon file +) + +coll = COLLECT( + exe, + a.binaries, + a.zipfiles, + a.datas, + strip=False, + upx=True, + name='TeamsHelper', +)