Repository: karigari/vscode-chat Branch: master Commit: ad72e38cb421 Files: 111 Total size: 327.5 KB Directory structure: gitextract_mypbxujs/ ├── .gitattributes ├── .github/ │ └── main.workflow ├── .gitignore ├── .prettierrc ├── .travis.yml ├── .vscode/ │ ├── extensions.json │ ├── launch.json │ ├── settings.json │ └── tasks.json ├── .vscodeignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── VISION.md ├── azure-pipelines.yml ├── docs/ │ ├── CONFIG.md │ ├── CONTRIBUTING.md │ ├── DISCORD.md │ ├── PROVIDERS.md │ └── SLACK.md ├── oauth-service/ │ ├── README.md │ ├── handler.ts │ ├── html/ │ │ ├── error.template.html │ │ ├── home.template.html │ │ └── success.template.html │ ├── html.d.ts │ ├── package.json │ ├── serverless.yml │ ├── source-map-install.js │ ├── tsconfig.json │ ├── utils.ts │ └── webpack.config.js ├── oauth-service-2/ │ ├── .gcloudignore │ ├── README.md │ ├── htmls.js │ ├── index.js │ ├── package.json │ └── utils.js ├── package.json ├── readme/ │ ├── logo.sketch │ └── screenshots.sketch ├── src/ │ ├── bots/ │ │ └── travis.ts │ ├── config/ │ │ ├── https-proxy-agent.d.ts │ │ ├── index.ts │ │ └── keychain.ts │ ├── constants.ts │ ├── controller/ │ │ ├── commands.ts │ │ ├── emoji-js.d.ts │ │ ├── index.ts │ │ ├── markdown-it-slack.d.ts │ │ └── markdowner.ts │ ├── discord/ │ │ └── index.ts │ ├── extension.ts │ ├── issues.ts │ ├── logger.ts │ ├── manager/ │ │ ├── chatManager.ts │ │ ├── index.ts │ │ ├── treeView.ts │ │ └── views.ts │ ├── onboarding.ts │ ├── slack/ │ │ ├── client.ts │ │ ├── common.ts │ │ ├── index.ts │ │ └── messenger.ts │ ├── status/ │ │ └── index.ts │ ├── store.ts │ ├── strings.ts │ ├── telemetry.ts │ ├── test/ │ │ ├── extension.test.ts │ │ ├── index.ts │ │ ├── manager.test.ts │ │ └── utils.test.ts │ ├── tree/ │ │ ├── base.ts │ │ ├── index.ts │ │ └── treeItem.ts │ ├── types.ts │ ├── uriHandler.ts │ ├── utils/ │ │ ├── index.ts │ │ └── keychain.ts │ ├── vslsSpaces/ │ │ ├── gravatar-api.d.ts │ │ └── index.ts │ └── webview/ │ └── index.ts ├── tsconfig.json ├── tslint.json ├── webpack.config.js └── webview/ ├── .gitignore ├── README.md ├── babel.config.js ├── package.json ├── src/ │ ├── App.vue │ ├── components/ │ │ ├── DateSeparator.vue │ │ ├── FormSection.vue │ │ ├── MarkdownElement.vue │ │ ├── MessageAuthor.vue │ │ ├── MessageContent.vue │ │ ├── MessageGroup.vue │ │ ├── MessageInput.vue │ │ ├── MessageItem.vue │ │ ├── MessageReaction.vue │ │ ├── MessageReactions.vue │ │ ├── MessageReplies.vue │ │ ├── MessageRepliesImages.vue │ │ ├── MessageReplyItem.vue │ │ ├── MessageTitle.vue │ │ ├── MessagesDateGroup.vue │ │ ├── MessagesSection.vue │ │ ├── StatusText.vue │ │ └── UserInfo.vue │ ├── main.js │ └── utils.js └── vue.config.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ # Set default behavior to automatically normalize line endings. * text=auto ================================================ FILE: .github/main.workflow ================================================ workflow "LSIF workflow" { resolves = ["arjun27/lsif-action@master"] on = "push" } action "arjun27/lsif-action@master" { uses = "arjun27/lsif-action@master" } workflow "Testing fork builds" { on = "pull_request" resolves = ["post gif on fail"] } action "post gif on fail" { uses = "arjun27/shaking-finger-action@patch-1" secrets = ["GITHUB_TOKEN"] } ================================================ FILE: .gitignore ================================================ out node_modules jspm_packages .vscode-test/ .vs *.vsix static tokens .serverless .webpack env.yml ================================================ FILE: .prettierrc ================================================ { "tabWidth": 4, "printWidth": 120 } ================================================ FILE: .travis.yml ================================================ sudo: false language: node_js node_js: - "10" - "9" before_install: - if [ $TRAVIS_OS_NAME == "linux" ]; then export CXX="g++-4.9" CC="gcc-4.9" DISPLAY=:99.0; sh -e /etc/init.d/xvfb start; sleep 3; fi install: - yarn - yarn run vscode:prepublish script: - yarn test notifications: slack: karigarihq:wyMAff0ihz5w5H2UKtrU2etP ================================================ FILE: .vscode/extensions.json ================================================ { // See http://go.microsoft.com/fwlink/?LinkId=827846 // for the documentation about the extensions.json format "recommendations": [ "eg2.tslint" ] } ================================================ FILE: .vscode/launch.json ================================================ // A launch configuration that compiles the extension and then opens it inside a new window // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 { "version": "0.2.0", "configurations": [ { "name": "Extension", "type": "extensionHost", "request": "launch", "runtimeExecutable": "${execPath}", "args": ["--extensionDevelopmentPath=${workspaceFolder}"], "outFiles": ["${workspaceFolder}/out/**/*.js"], "preLaunchTask": "watch", "env": { "IS_DEBUG": "true" } }, { "name": "Extension Tests", "type": "extensionHost", "request": "launch", "runtimeExecutable": "${execPath}", "args": [ "--extensionDevelopmentPath=${workspaceFolder}", "--extensionTestsPath=${workspaceFolder}/out/test" ], "outFiles": ["${workspaceFolder}/out/test/**/*.js"], "preLaunchTask": "watch", "env": { "IS_DEBUG": "true" } } ] } ================================================ FILE: .vscode/settings.json ================================================ // Place your settings in this file to overwrite default and user settings. { "files.exclude": { "out": false // set this to true to hide the "out" folder with the compiled JS files }, "search.exclude": { "out": true // set this to false to include "out" folder in search results }, // Turn off tsc task auto detection since we have the necessary tasks as npm scripts "typescript.tsc.autoDetect": "off" } ================================================ FILE: .vscode/tasks.json ================================================ // See https://go.microsoft.com/fwlink/?LinkId=733558 // for the documentation about the tasks.json format { "version": "2.0.0", "tasks": [ { "type": "shell", "label": "watch", "command": "npm run watch", "problemMatcher": "$tsc-watch", "isBackground": true, "presentation": { "reveal": "never" }, "group": { "kind": "build", "isDefault": true } } ] } ================================================ FILE: .vscodeignore ================================================ .vs/** .vscode/** .vscode-test/** out/test/** out/**/*.map src/** .gitignore tsconfig.json tslint.json tokens oauth-service/** oauth-service-2/** node_modules/** readme/** webview/** ================================================ FILE: CHANGELOG.md ================================================ # Changelog All notable changes to the Live Share Chat extension will be documented in this file. This follows the [Keep a Changelog](http://keepachangelog.com/) format. ## [0.35.0] - 2020-06-13 Fixed - Slack OAuth has been fixed. Since legacy tokens are deprecated, use the "Sign in with Slack" command to use Slack. ## [0.34.0] - 2020-06-03 - This version removes the VS Live Share integration bits, which have been now added to the main VS Live Share extension. ## [0.33.0] - 2020-03-23 ### Fixed - Recovery build: Bringing back Live Share integration for now. Will revert the recovery build once the new version of Live Share is released. ## [0.32.0] - 2020-03-22 ### Removed - The integration with VS Live Share has now moved into the core VS Live Share extension! Thanks to everyone who tried it out, and helped make it a core experience for using Live Share. ## [0.31.0] - 2019-12-19 ### Fixed - Fixes to initialization for Live Share Spaces increase reliability of the experience. ## [0.30.0] - 2019-12-19 ### Fixed - Fixes to initialization for Live Share Chat that increase reliability of the experience. ## [0.29.0] - 2019-11-06 ### Added - You can type `/invite` in a Live Share DM chat to invite your contacts into a Live Share collaboration session. ## [0.28.0] - 2019-10-30 ### Added - Updated readme to reflect recent improvements and changes. ## [0.27.1] - 2019-10-25 ### Fixed - Fixed overflow styling for at-mentions suggestion list. ## [0.27.0] - 2019-10-25 ### Added - Support for at-mentions: type `@` to get a list of suggestions to tag. Tagging a user does not notify them in this release—that's coming up soon! ## [0.25.0] - 2019-10-18 ### Added - Support for a `/clear` command that clears the message history in the current chat window. ## [0.24.0] - 2019-10-17 ### Added - Live Share Chat now supports typing events! ## [0.23.0] - 2019-10-17 ### Added - Live Share Chat now supports Direct Messages! You can DM your Live Share contacts—even outside Live Share sessions! ## [0.22.1] - 2019-09-15 ### Fixed - Fixed presence provider validation. ## [0.22.0] - 2019-09-14 ### Added - Renamed Live Share Communities provider to Live Share Spaces. ## [0.21.1] - 2019-09-04 ### Fixed - Fixed date to string conversion for message groups. ## [0.21.0] - 2019-08-19 ### Fixed - Add Live Share as an extension dependency to fix timing issues during activation ## [0.20.2] - 2019-08-14 ### Added - Live Share Communities: updated implementation for info messages ## [0.20.0] - 2019-08-13 ### Added - Live Share Communities: added support for info messages ## [0.19.0] - 2019-08-12 ### Added - Live Share Communities: added support to clear messages ## [0.18.0] - 2019-08-11 ### Added - Live Share: alert the guest if host does not have the extension installed. ### Fixed - Fixed a case where Live Share Chat was not initialized. ## [0.17.1] - 2019-08-08 ### Added - Render links correctly in Live Share and Live Share Communities chat. ## [0.17.0] - 2019-08-07 ### Added - Renamed the extension to Live Share Chat. ## [0.16.3] - 2019-08-07 ### Fixed - [Live Share Communities](https://github.com/vsls-contrib/communities) integration: Fix cases where current user is returned as undefined. - [Live Share Communities](https://github.com/vsls-contrib/communities) integration: Fix a bug where new members were not recognised with an avatar and name. ## [0.16.2] - 2019-08-04 ### Fixed - [Live Share Communities](https://github.com/vsls-contrib/communities) integration: Fix presence provider and timing issues. ## [0.16.1] - 2019-08-04 ### Added - [Live Share Communities](https://github.com/vsls-contrib/communities) integration: Auto-launch community chat when a community is joined. ## [0.16.0] - 2019-08-02 ### Added - Adds integration with [Live Share Communities](https://github.com/vsls-contrib/communities). ## [0.15.1] - 2019-05-12 ### Fixed - Fixes unwanted notification for Slack/Discord login when installed alongside VS Live Share. ## [0.15.0] - 2019-05-01 ### Removed - Removed onboarding tree view that would show Slack icon when no chat backend was configured. ## [0.14.0] - 2019-04-28 ### Added - Faster installation and startup times with Webpack bundling. - Updated setup instructions for Discord to call out potential ToS violation. ## [0.13.0] - 2019-04-09 ### Fixed - Fixes an issue where Live Share Chat would not work for guests on the collaboration session. ## [0.12.0] - 2019-02-24 ### Added - New configuration option to disable auto-launching the Live Share Chat window on a new Live Share session: `"chat.autoLaunchLiveShareChat": false`. ## [0.11.0] - 2019-02-03 ### Added - The VS Live Share chat window now shows up automatically for new VS Live Share sessions. ## [0.10.0] - 2019-01-21 ### Added - Added support for multiple workspaces in Slack. Run the `Sign in with Slack` command to add new workspaces; Use the tree view to change between Slack workspaces. ### Fixed - Render attachments in Discord messages. - Usability improvements in selecting which Slack channels should be shown. ## [0.9.2] - 2019-01-04 ### Fixed - "Account is required" errors while accessing the system keychain. ## [0.9.1] - 2018-12-31 ### Fixed - CPU load: Removed redundant extension activation events that were causing high CPU load. ## [0.9.0] - 2018-12-16 ### Added - Chat over VS Live Share now works alongside Slack and Discord: You can now chat with your collaboration session peers through VS Live Share, even if you are logged in on other chat providers. - Start chat over VS Live Share from the explorer view. ## [0.8.2] - 2018-11-20 ### Fixed - VS Live Share integration: Updated label for chat tree item. ## [0.8.1] - 2018-11-20 ### Fixed - Inviting online users to a Live Share session creates an IM channel with the user, if not already available. ## [0.8.0] - 2018-11-18 ### Added - Now you can update your presence status: go invisible on chat, or turn on do-not-disturb mode. Run the `Chat: Update your presence status` command (supports Slack and Discord). - VS Live Share integrations: - Show presence statuses for VS Live Share suggested contacts (for Slack and Discord) - Update your presence status from inside VS Live Share (for Slack and Discord) - Open VS Live Share chat from the VS Live Share explorer views ## [0.7.4] - 2018-11-05 ### Fixed - Fixed bad instantiation for users and channels state causing VS Live Share chat to not work. ## [0.7.3] - 2018-10-16 ### Fixed - Fixed channel loading for Slack workspaces that cross the user limit. ## [0.7.2] - 2018-10-15 ### Fixed - Fixed onboarding notification for Live Share users. ## [0.7.1] - 2018-10-15 ### Added - Chat over VS Live Share RPC is the default backend for users that have the Live Share extension. Users can optionally upgrade to Slack or Discord. - New status bar item to open the chat window during a VS Live Share session. - Unread message notification and user joined/left info messages for Live Share chat. ### Fixed - Slack messages are sent over websocket, to not count towards http rate limits. - Limit Slack channels to relevant channels only, by using the Slack conversations API. ## [0.7.0] - 2018-10-11 ### Added - Chat with VS Live Share session participants, without relying on a chat backend like Slack/Discord. To use this, start a Live Share session and run the `Chat with VS Live Share participants` command. ## [0.6.3] - 2018-10-09 ### Added - Added token validation for manual entry for Slack and Discord tokens. - Keychain access operations can now be retried in case access is denied. - Added workspace name to the status item notification. ## [0.6.2] - 2018-09-28 ### Fixed - Handle deactivated Slack users, and not show their direct messages and groups (thanks [Tristan Partin](https://github.com/tristan957)). - Private channels are now shown under the Channels view, and not Groups. ## [0.6.1] - 2018-09-22 ### Fixed - Fixed migration condition for pre-0.6.x installations (thanks [ACharLuk](https://github.com/acharluk)). ## [0.6.0] - 2018-09-21 ### Added - Added support for Discord as a chat provider, in addition to Slack. - [Breaking] Commands are now namespaced as "Chat: ...", instead of "Slack: ...". - Updates to extension metadata and readme: the extension is now called Team Chat. ## [0.5.11] - 2018-09-18 ### Added - Added support for replying to thread messages. ### Fixed - Fixed rendering of duplicate thread replies. ## [0.5.10] - 2018-09-17 ### Added - Added new configuration `chat.rejectTlsUnauthorized` for self-signed certificate users (thanks [Seth Bromberger](https://github.com/sbromberger)). - Load vue.js assets locally, removing dependency on the jsdelivr CDN. - Upgraded Slack dependency to keep up with the network library improvements upstream. ## [0.5.9] - 2018-09-04 ### Added - Support for muted channels: new messages in muted channels do not update the unread count. - Added support to expand thread messages to render replies, with text and file attachments. - Consistency between Slack clients for unread counts: marking messages as read from other Slack clients will update the unread count. - Unread messages are now highlighted in the webview. - Added documentation for [product roadmap](VISION.md) and [adding chat providers](docs/PROVIDERS.md). ### Fixed - The unread count does not include alerts for users joining/leaving channels anymore. ## [0.5.8] - 2018-08-31 ### Added - Added support for the system keychain to store authentication tokens. - Added a new command to sign out from Slack. ### Fixed - Fix handling of composition start/end events while composing messages (thanks [Yukai Huang](https://github.com/Yukaii)). - Opening Slack or changing channel without authentication now prompts users to authenticate. ## [0.5.7] - 2018-08-29 ### Added - Added support for "Sign in with Slack" from the activity bar. ### Fixed - New line characters in messages are rendered correctly. - Date separators show the correct month string. - Fixed event source property for webview telemetry. ## [0.5.6] - 2018-08-23 ### Added - Slack webview font size now matches the font size of your editor. - Introductory support for message threads: historical messages show the number of thread replies. Future releases will build on this to add full thread replies support. - Added anonymized telemetry data collection; this respects the telemetry setting in your editor and you can opt-out by setting `telemetry.enableTelemetry` to false. ### Fixed - Updated user display names to be consistent with Slack clients. ## [0.5.5] - 2018-08-20 ### Added - Added a fallback for "Sign in with Slack" for situations where the system-level URI scheme handler fails. ## [0.5.4] - 2018-08-18 ### Added - Added "Sign in with Slack" for an easier onboarding experience ## [0.5.3] - 2018-08-18 ### Fixed - Fixed issues with duplicated state when configuration gets changed in the editor. - Fixed unread message notifications for messages with files. ## [0.5.2] - 2018-08-18 ### Fixed - Fixed date separators computation for local time zones - Fixed a race condition where loading channel message history would assign messages to an incorrect channel. ## [0.5.1] - 2018-08-16 ### Fixed - Fixed extension activation for the VS Live Share activity bar. ## [0.5.0] - 2018-08-16 ### Added - Sidebar view to show channels, private groups and direct messages. - Support to show user presence (online/offline) in the sidebar view. - Better integration with VS Live Share: one-click action to invite users or channels to your collaboration session. - Minor improvements to extension setup for first-time users. ### Fixed - Fixed a case where the unread count would get updated incorrectly. ## [0.4.10] - 2018-08-14 ### Added - Slack username tags in messages are not cryptic anymore. - Better keyboard-only support: pressing tab will focus the input text box, ignoring other selectable HTML elements in the webview. - Added date separators on the messages UI ### Fixed - Fixed real-time UI updates for bot messages. - Fixed select-all behaviour through the cmd+A keybinding (needs VS Code 1.26+). ## [0.4.9] - 2018-08-13 ### Fixed - Fixed issue where new messages were not getting updated on the UI. ## [0.4.8] - 2018-08-09 ### Added - Added support to render message reactions, and live update UI as reactions are added or removed - The unread count now also reflects messages that were received before the extension gets activated, by calling the relevant Slack API. ### Fixed - Messages with files were not rendered correctly since the last Slack update. This has been fixed now. ## [0.4.7] - 2018-08-08 ### Added - Added a status bar item to show the number of new/unread messages. For now, this is available only after the chat panel has been opened once. ## [0.4.6] - 2018-08-08 ### Added - Added support for marking messages as read - Improved how multi-party DM group name are shown in the UI ## [0.4.5] - 2018-07-21 ### Added - Added support for network connections via proxies. To setup, add the `chat.proxyUrl` configuration. ## [0.4.4] - 2018-07-17 ### Fixed - Fixed demo gif on the Visual Studio Marketplace ## [0.4.3] - 2018-07-17 ### Added - Open Travis CI logs inside the editor, with the new extensible Providers support. New providers can be create for other Slack bots and integrations. - New demo gifs and examples in the README. ### Fixed - Fixed an issue where messages from a previously opened Slack channel would show up in the current view. ## [0.4.2] - 2018-07-15 ### Fixed - Fixed the change channel quick-pick prompt for workspaces that invite guest users. ## [0.4.1] - 2018-07-06 ### Added - Add a "reload channels" option to the channel switcher which refreshes the user/channels list from Slack API. ## [0.4.0] - 2018-07-06 ### Added - Adds "reverse initiation" for VS Live Share: a user can ask another user to host a Live Share session by sending the `/live request` command. The recipient can choose to accept the request, which would kickstart the shared session. ## [0.3.4] - 2018-07-04 ### Fixed - Fixes a bug that showed new messages sent via the extension as blank ## [0.3.3] - 2018-07-03 ### Added - Support for rendering file attachments, code snippets, multi-line messages - Support for rendering Slack app messages, with author, title, coloured border, and footer - Support for rendering message edits and deletions ### Fixed - Fixed click behaviour for links inside messages ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================

Chat for VS Code

Chat with your Slack and Discord teams from within VS Code

Screenshot

Visual Studio Marketplace Downloads Visual Studio Marketplace Rating Live Share enabled

> **0.34.0**: With this release, the integration with VS Live Share has now moved into the core VS Live Share extension! Thanks to everyone who tried it out, and helped make it a core experience for using Live Share. > > The extension now only supports Slack, Discord and Live Share Spaces as chat providers. # Features - **Quiet notifications**: Chat apps can be painfully distracting. This extension emphasizes on making chat useful, contextual, and without distracting notifications. - **Rich formatting**: Share markdown code snippets, and add emojis to your chat messages. - **Native look-and-feel**: Use chat in your preferred theme and grid editor layout.

Quiet notifications Rich formatting Theme and grid layout

# Get started with chat ## Slack To configure your Slack workspace, run the **Sign In with Slack** command in VS Code. Are you a Slack workspace admin? [Approve this app](https://slack.com/apps/ACB4LQKN1-slack-chat-for-vs-code) for your team. Start a new VS Live Share session within a Slack channel: Use the slash commands `/live share` and `/live end` to start and end a session. ## Discord Discord support is experimental. Please see [this doc](docs/DISCORD.md) to set it up. ## Live Share Spaces To explore richer ways to connect and collaborate with developers across your teams, classrooms and communities, check out [Live Share Spaces](https://marketplace.visualstudio.com/items?itemName=vsls-contrib.spaces). # Support - **Configuration settings**: To use behind a network proxy and other settings, see [CONFIGURATION](docs/CONFIG.md). - **Raise an issue**: Feel free to [report an issue](https://github.com/karigari/vscode-chat/issues), or find [me on Twitter](https://twitter.com/arjunattam) for any suggestions or support. # Developer docs - **Get started with contribution**: See [CONTRIBUTING](docs/CONTRIBUTING.md) to understand repo structure, building and testing. - **New chat integrations**: The implementation can be extended to support any chat provider, see [PROVIDERS](docs/PROVIDERS.md). - **Vision**: Read the [VISION](VISION.md) doc to understand the motivation behind this extension and the roadmap ahead. ================================================ FILE: VISION.md ================================================ # Vision This doc outlines our vision and product roadmap. The goal is to crystallize the driving ideas: for our community of users and contributors. On a tactical level, this will also help us prioritize feature requests. Suggestions to update this document are very welcome. Feel free to raise an issue or a pull request! My DMs are also open at [@arjunattam](http://twitter.com/arjunattam). ## The goal Editors have been historically built to maximize the productivity of one developer. Developers working in teams use version control tools and other services, in addition to their editor: services for project management, continuous integration, and crash reporting. Personified as bots on Slack, these services have evolved to become our peers in shipping quality code: our bots and our teammates now work in tandem. But there is a gap: this collaboration happens one step away from our code, and that leads to context switches, and consequently knowledge falling through the cracks. This extension is an experiment to see how the editor can evolve to become the center of collaboration for engineering teams. Perhaps like an IDE for our teams, to maximize team productivity. ## Use-cases I think of collaboration on an axis of real-time: on one end, there are synchronous use-cases (like pair programming), and then there are asynchronous ones on the other (reviewing pull requests). With this extension, we want to target **the synchronous half** of that axis. This implies not focusing on teams that collaborate only asynchronously, such as open source projects with longer development cycles. ### Sync collaboration Chat is a natural fit for synchronous collaboration, and therefore these use-cases will be a focus. Integration with the excellent [VS Live Share extension](https://aka.ms/vsls) is and will continue to be a focus area. ### Pseudo-sync collaboration Engineering teams that run on Slack often collaborate in a pseudo-synchronous level, where collaboration is close to real-time, except when developers are deep in their code. The goal is to further improve the flexibility. For example, the following frequent tasks should take just a click: - Open a build log from your remote CI tool, and go to the failed tests in the code - Open a teammate's commit diff for a quick code review on chat - Open a Sentry crash report inside the VS Code debugger, to show state of the call stack and variable values at the time of the crash And you will have your teammates alongside for a quick discussion without losing focus. Pseudo-sync use-cases are also a good place for teams to start sync sessions, and the extension will assist that transition. ## Chat providers While Slack offered us an excellent API to kick-start the above, there is no reason for this extension to be tied to just Slack. The goal is to support other chat providers that teams use. See [PROVIDERS](docs/PROVIDERS.md) for more details on how that works. ## Healthy notifications Chat notifications can be unhealthy: we need our focused time to think deeply about the code we write. The extension will always prioritize this need, and strive for a healthy balance between collaboration and focused solo time. ================================================ FILE: azure-pipelines.yml ================================================ queue: name: Hosted VS2017 steps: - task: NodeTool@0 inputs: versionSpec: '10.x' - script: | npm install npm run compile - task: RichCodeNavIndexer@0 inputs: serviceConnection: 'rich-code-nav' githubServiceConnection: 'vsls-contrib' languages: typescript ================================================ FILE: docs/CONFIG.md ================================================ # Configuration ## Network proxy To use this extension behind a proxy, configure the proxy url. ```json { "chat.proxyUrl": "YOUR_PROXY_URL" } ``` ## Self-signed certificates If you have overriding self-signed SSL certificates, you can set the `rejectTlsUnauthorized` config to false. ```json { "chat.rejectTlsUnauthorized": false } ``` ## Telemetry This extension collects anonymized telemetry data to improve the product. This respects your editor's telemetry settings, and you can opt-out by setting the `enableTelemetry` setting to `false`. ```json { "telemetry.enableTelemetry": false } ``` ## Auto-launch Live Share Chat By default, the extension auto-launches the Live Share Chat window every time a new Live Share session is started. This behaviour can be disabled: ```json { "chat.autoLaunchLiveShareChat": false } ``` ================================================ FILE: docs/CONTRIBUTING.md ================================================ # Contributing The repo is actively developed, and you are welcome to [submit feature requests](https://github.com/karigari/vscode-chat/issues/new) and pull requests. [Issues](https://github.com/karigari/vscode-chat/issues) are the best place to look for contribution ideas. If you want to work on something, just create a discussion thread (on PRs/issues) and we will help you get started. ## Repo structure The repo has three parts: 1. Main extension code in TypeScript, in `src/**` 2. Webview UI code, written with Vue.js, in `src/webview/**` 3. OAuth service, built with the Serverless framework, in `oauth-service/**` ## Building Open the project inside VS Code, and start debugging (F5). This will launch a new VS Code window (the extension development host) with the development code. See [this guide](https://code.visualstudio.com/docs/extensions/developing-extensions) to get started with development. When you run a debug session, the `npm run watch` task starts up. This watches for file changes, recompiles, and you can reload the extension development host window to get the new code. ## Known issue The watch command does not watch for CSS file changes. This means if you make changes to the `src/ui/static.css` file, you need to restart the `npm run watch` command manually. Best to make CSS changes live, with the Chrome dev tools, and then make file changes. ## Styling The code is styled with [Prettier](https://prettier.io). ## Tests `npm run test` Tests can only be run when VS Code is not running. If you want to run tests alongside development, use VS Code Insiders for development. ================================================ FILE: docs/DISCORD.md ================================================ # Discord Setup ## Warning The Discord integration involves an unofficial approach to getting the token, and is not recommended. The approach is similar to how users can potentially automate their logins ("create self-bots"), which are not allowed by the Discord ToS. The goal is to move to [Discord RPC](https://discordapp.com/developers/docs/topics/rpc#proxied-api-requests) in the near-term, which supports proxied API/websocket requests with OAuth. Discord RPC is in private beta at the moment. If you have any suggestions to improve this flow, please [create an issue](https://github.com/karigari/vscode-chat/issues). ## Obtaining the token To set up Discord inside VS Code, you need to have your **Discord token**. To obtain your token, follow the steps [given here](https://discordhelp.net/discord-token). This is an unofficial token setup, one that is used by other Discord clients ([Discline](https://github.com/MitchWeaver/Discline), [terminal-discord](https://github.com/xynxynxyn/terminal-discord)), and the recommended approach by a Discord team member, as [given here](https://github.com/discordapp/discord-api-docs/issues/69#issuecomment-223886862): > Instead, log in on the discord client, pop open the web inspector, (ctrl/cmd shift I), and type localStorage.token in the console to get your auth token. ## Configuring the token Once you have the token, run the following commands from the VS Code command palette: 1. Run **Chat: Configure Access Token**, select "Discord", and then paste your token in the input box. The token will be saved securely in your system keychain. 2. Next, you will be prompted to choose your primary Discord guild. If you don't want to select now, you can run the **Chat: Change Workspace** command later. ================================================ FILE: docs/PROVIDERS.md ================================================ # Chat providers The goal of this extension is to open up support for other chat providers, in addition to Slack and Discord. Chat providers can be added by implementing the `IChatProvider` [interface](src/interfaces/index.ts). Providers will use a common set of types for `User`, `Channel`, `Message`. For reference, see the implementation [for Slack](src/slack/index.ts) and [for Discord](src/discord/index.ts). ## Supported features The extension supports the following features for Slack. Other chat providers can implement one or more features, depending on their API. 1. [Authentication](#authentication): Users can sign in with chat provider's OAuth 2. [Messaging](#messaging): Users can open a chat channel in a webview, and then send and receive messages 3. [Channels list](#channels-list): Users can see the list of public channels, direct messages and private groups (with unread counts) in the tree view 4. [Unreads](#unreads): Users can see the unread count in the status bar 5. [Presence](#presence): Users can see other online users in the Live Share tree view (requires VS Live Share) 6. [Collaboration invites](#collaboration-invites): Users can invite users or channels for a Live Share collaboration session (requires VS Live Share) ## Authentication Slack uses OAuth with `client` scope. The result of a successful auth flow is a token string which is saved in the keychain. The other features are dependent on a successful authentication. Requirements for providers - Provide a "Sign in with X" link to launch OAuth flow - Auth flow should return a token string that can be saved to system keychain ## Messaging In addition to normal send/receive of messages in real-time, the Slack integration also supports threaded message replies, message reactions and file attachments. These are incorporated in the `Message` data type. Requirements for providers - API support to receive messages in real-time (Slack uses websocket) - API support to send messages, as the authenticated user (not a bot) - Optionally: thread replies, emoji reactions, file attachments ## Channels list Slack supports three channel types: `channel` (public channels), `im` (direct messages), and `group` (private groups). These are fetched (from API, and then onwards from local storage) when the extension is activated. Requirements for providers - API support to fetch channels and users ## Unreads The unread count can be historical (unread messages before user comes online) and in real-time (new messages when the user is online). Requirements for providers - Historical unreads: API support to return unread count for every channel - Real-time unreads: The real-time messaging API can be used to update a running unread count for new messages - API support to mark messages as read (which takes the count to 0) - If the provider has other clients, then the API should support real-time updates to maintain unread count consistent with the other clients. ## Presence User presence (online/offline status) shows green dots next to direct messaging channels in the tree view. When VS Live Share is available, a list of online users is shown in the Live Share activity bar, to send one-click collaboration invites. Requirements for providers - API support for real-time support for user presence updates ## Collaboration invites To start a VS Live Share collaboration session, the extension supports one-click collaboration invites. The requirements for this are similar to the messaging feature. Requirements for providers - API support to receive real-time messages in the background - API support to send messages ================================================ FILE: docs/SLACK.md ================================================ # Slack authorization Many users have reported running into `access_denied` issues on Slack, and this doc attempts to list potential solutions to the problem. In case you have questions about permission levels or what this extension accesses, please report an issue with your question. ## Admin approval required Some workspaces require an explicit admin approval before users can install specific apps. If your workspace needs this, please forward [this link](https://slack.com/apps/ACB4LQKN1-slack-chat-for-vs-code) to your workspace admins. ## Slack App Directory Some workspaces also restrict apps that are only approved by the Slack app review process. Getting this done is in our backlog, and you can track progress in [this issue](https://github.com/karigari/vscode-chat/issues/78). For now, you will need to manually approve the app for your workspace. This can be done by any admin of the workspace. Please use [this link](https://slack.com/apps/ACB4LQKN1-slack-chat-for-vs-code) for that. ## Free workspace app limit If you are on a free Slack workspace, you can only have 10 installed apps. Attempting to install any more gives an `access_denied` error. To make this work without upgrading your Slack plan, you will need to remove an existing app. ================================================ FILE: oauth-service/README.md ================================================ # oauth-service This is a serverless app to handle OAuth redirection for the Slack Chat extension, and it is deployed on AWS Lambda. To deploy a new version of this service, run ``` serverless deploy --verbose ``` To test this service locally, run ``` serverless offline start ``` This service requires the `env.yml` file with the SLACK_CLIENT_ID and SLACK_CLIENT_SECRET keys. ## Custom domain The oauth service runs on a custom domain ([vscode.chat](https://vscode.chat)), configured with the [serverless-domain-manager](https://github.com/amplify-education/serverless-domain-manager) plugin. The following command needs to run before a new deploy if there are any changes to the yml, wrt function route definitions. ``` serverless create_domain ``` ================================================ FILE: oauth-service/handler.ts ================================================ import { APIGatewayEvent, Callback, Context, Handler } from "aws-lambda"; import * as request from "request-promise-native"; import { parseQueryParams, getIssueUrl, getRedirect, getRedirectError } from "./utils"; import errorHtml from "./html/error.template.html"; import successHtml from "./html/success.template.html"; import homeHtml from "./html/home.template.html"; interface TokenAPIResponse { accessToken: string; teamId?: string; expiresIn?: Date; refreshToken?: string; error: string; } const getSlackToken = async (code: string): Promise => { const uri = "https://slack.com/api/oauth.access"; var options = { uri, json: true, qs: { client_id: process.env.SLACK_CLIENT_ID, client_secret: process.env.SLACK_CLIENT_SECRET, code, // When testing locally, pass the redirect_uri to slack // redirect_uri: "http://localhost:3000/slack_redirect" } }; const result = await request.get(options); const { ok, error, access_token, team_id } = result; if (!ok) { return { accessToken: null, error }; } else { return { accessToken: access_token, teamId: team_id, error: null }; } }; const getDiscordToken = async (code: string): Promise => { const uri = "https://discordapp.com/api/v6/oauth2/token"; var options = { uri, method: "POST", formData: { client_id: process.env.DISCORD_CLIENT_ID, client_secret: process.env.DISCORD_CLIENT_SECRET, grant_type: "authorization_code", code } }; try { const result = await request.post(options); const parsed = JSON.parse(result); var t = new Date(); t.setSeconds(t.getSeconds() + parsed.expires_in); return { accessToken: parsed.access_token, expiresIn: t, refreshToken: parsed.refresh_token, error: null }; } catch (error) { return { accessToken: null, error: error.message }; } }; const renderSuccess = ( token: string, service: string, teamId: string, cb: Callback ) => { const redirect = getRedirect(token, service, teamId); const response = { statusCode: 200, headers: { "Content-Type": "text/html" }, body: successHtml .replace(/{{redirect}}/g, redirect) .replace(/{{token}}/g, token) }; cb(null, response); }; const renderError = (error: string, service: string, cb: Callback) => { const issueUrl = getIssueUrl(error, service); const redirect = getRedirectError(error, service); const response = { statusCode: 200, headers: { "Content-Type": "text/html" }, body: errorHtml .replace(/{{error}}/g, error) .replace(/{{redirect}}/g, redirect) .replace(/{{issues}}/g, issueUrl) }; cb(null, response); }; export const slackRedirect: Handler = ( event: APIGatewayEvent, context: Context, cb: Callback ) => { const { error, code } = parseQueryParams(event); if (!!code) { const tokenPromise = getSlackToken(code); tokenPromise.then(result => { const { accessToken, error, teamId } = result; if (!accessToken) { renderError(error, "slack", cb); } else { renderSuccess(accessToken, "slack", teamId, cb); } }); } if (!!error) { renderError(error, "slack", cb); } }; export const discordRedirect: Handler = ( event: APIGatewayEvent, context: Context, cb: Callback ) => { const { error, code } = parseQueryParams(event); if (!!code) { const tokenPromise = getDiscordToken(code); tokenPromise.then(result => { const { accessToken, error } = result; if (!accessToken) { renderError(error, "discord", cb); } else { renderSuccess(accessToken, "discord", "team-id", cb); } }); } if (!!error) { renderError(error, "discord", cb); } }; export const home: Handler = ( event: APIGatewayEvent, context: Context, cb: Callback ) => { const response = { statusCode: 200, headers: { "Content-Type": "text/html" }, body: homeHtml }; cb(null, response); }; ================================================ FILE: oauth-service/html/error.template.html ================================================ Slack Chat for VS Code

We have run into an error: {{error}}

If this is not right, please report an issue

================================================ FILE: oauth-service/html/home.template.html ================================================ Slack Chat for VS Code ================================================ FILE: oauth-service/html/success.template.html ================================================ Slack Chat for VS Code

Redirecting to VS Code...

Unable to redirect? Configure manually.

Report an issue

================================================ FILE: oauth-service/html.d.ts ================================================ declare module "*.html" { const value: string; export default value; } ================================================ FILE: oauth-service/package.json ================================================ { "name": "vscode-chat-oauth-service", "description": "Serverless app to handle Slack OAuth for vscode-chat", "version": "1.0.0", "main": "handler.js", "scripts": { "start": "npx serverless offline start" }, "dependencies": { "request": "^2.88.0", "request-promise-native": "^1.0.5", "source-map-support": "^0.5.0" }, "devDependencies": { "@types/aws-lambda": "8.10.1", "@types/node": "^8.0.57", "html-loader": "^0.5.5", "serverless-domain-manager": "^2.6.0", "serverless-offline": "^3.25.8", "serverless-webpack": "^5.1.1", "ts-loader": "^4.2.0", "typescript": "^2.8.1", "webpack": "^4.5.0" } } ================================================ FILE: oauth-service/serverless.yml ================================================ service: name: vscode-chat-oauth-service plugins: - serverless-webpack - serverless-offline - serverless-domain-manager provider: name: aws runtime: nodejs8.10 environment: ${file(./env.yml):${opt:stage, self:provider.stage}} functions: slack-redirect: handler: handler.slackRedirect timeout: 10 events: - http: method: get path: slack_redirect discord-redirect: handler: handler.discordRedirect timeout: 10 events: - http: method: get path: discord_redirect home: handler: handler.home events: - http: method: get path: / custom: customDomain: domainName: vscode.chat certificateArn: arn:aws:acm:us-east-1:750374355341:certificate/dd3d7f2f-e25f-46b9-8cad-93784e9b2e9b stage: ${self:provider.stage} createRoute53Record: true ================================================ FILE: oauth-service/source-map-install.js ================================================ require('source-map-support').install(); ================================================ FILE: oauth-service/tsconfig.json ================================================ { "compilerOptions": { "sourceMap": true, "target": "es6", "lib": [ "esnext" ], "moduleResolution": "node" }, "exclude": [ "node_modules" ] } ================================================ FILE: oauth-service/utils.ts ================================================ import { APIGatewayEvent } from "aws-lambda"; export const parseQueryParams = (event: APIGatewayEvent) => { const { queryStringParameters } = event; let error, code; if (!!queryStringParameters) { code = queryStringParameters.code; error = queryStringParameters.error; } else { error = "no_code_param"; } return { code, error }; }; export const getIssueUrl = (errorMessage: string, serviceName: string) => { const encode = encodeURIComponent; const title = `[oauth-service] Sign in with ${serviceName} failed: ${errorMessage}`; const body = `- Extension version:\n- VS Code version:`; const baseUrl = "https://github.com/karigari/vscode-chat/issues/new/"; return `${baseUrl}?title=${encode(title)}&body=${encode(body)}`; }; export const getRedirect = (token: string, service: string, team: string) => { return `vscode://karigari.chat/redirect?token=${token}&service=${service}&team=${team}`; }; export const getRedirectError = (errorMessage: string, serviceName: string) => { return `vscode://karigari.chat/error?msg=${errorMessage}&service=${serviceName}`; }; ================================================ FILE: oauth-service/webpack.config.js ================================================ const path = require("path"); const slsw = require("serverless-webpack"); const entries = {}; Object.keys(slsw.lib.entries).forEach( key => (entries[key] = ["./source-map-install.js", slsw.lib.entries[key]]) ); module.exports = { mode: slsw.lib.webpack.isLocal ? "development" : "production", entry: entries, devtool: "source-map", resolve: { extensions: [".js", ".jsx", ".json", ".ts", ".tsx", ".html"] }, output: { libraryTarget: "commonjs", path: path.join(__dirname, ".webpack"), filename: "[name].js" }, target: "node", module: { rules: [ { test: /\.tsx?$/, loader: "ts-loader" }, { test: /\.html$/, loader: "html-loader" } ] } }; ================================================ FILE: oauth-service-2/.gcloudignore ================================================ # This file specifies files that are *not* uploaded to Google Cloud Platform # using gcloud. It follows the same syntax as .gitignore, with the addition of # "#!include" directives (which insert the entries of the given .gitignore-style # file at that point). # # For more information, run: # $ gcloud topic gcloudignore # .gcloudignore # If you would like to upload your .git directory, .gitignore file or files # from your .gitignore file, remove the corresponding line # below: .git .gitignore node_modules ================================================ FILE: oauth-service-2/README.md ================================================ # Oauth redirection service ## Running locally ``` npm start ``` ## Deployment ``` gcloud functions deploy slackRedirect --set-env-vars SLACK_CLIENT_ID=,SLACK_CLIENT_SECRET= --runtime nodejs10 --trigger-http ``` ================================================ FILE: oauth-service-2/htmls.js ================================================ exports.success = ` Slack Chat for VS Code

Redirecting to VS Code...

Unable to redirect? Configure manually.

Report an issue

` exports.error = ` Slack Chat for VS Code

We have run into an error: {{error}}

If this is not right, please report an issue

` ================================================ FILE: oauth-service-2/index.js ================================================ //@ts-check const utils = require('./utils'); const htmls = require('./htmls'); const request = require('request-promise-native'); async function getSlackToken(code) { const uri = "https://slack.com/api/oauth.access"; var options = { uri, json: true, qs: { client_id: process.env.SLACK_CLIENT_ID, client_secret: process.env.SLACK_CLIENT_SECRET, code, // When testing locally, pass the redirect_uri to slack redirect_uri: "https://us-central1-eco-theater-119616.cloudfunctions.net/slackRedirect" } }; const result = await request.get(options); const { ok, error, access_token, team_id } = result; if (!ok) { return { accessToken: null, error }; } else { return { accessToken: access_token, teamId: team_id, error: null }; } } const renderSuccess = (token, service, teamId, response) => { const redirect = utils.redirectUrl(token, service, teamId); response.set('Content-Type', 'text/html'); response.status(200).send( htmls.success .replace(/{{redirect}}/g, redirect) .replace(/{{token}}/g, token) ); }; const renderError = (error, service, response) => { const issueUrl = utils.issueUrl(error, service); const redirect = utils.redirectError(error, service); response.set('Content-Type', 'text/html'); response.status(200).send( htmls.error .replace(/{{error}}/g, error) .replace(/{{redirect}}/g, redirect) .replace(/{{issues}}/g, issueUrl) ); }; exports.slackRedirect = async (req, res) => { const { error, code } = req.query; if (!!code) { const tokenPromise = getSlackToken(code); tokenPromise.then(result => { const { accessToken, error, teamId } = result; if (!accessToken) { renderError(error, "slack", res); } else { renderSuccess(accessToken, "slack", teamId, res); } }); } else { renderError(error, "slack", res); } }; ================================================ FILE: oauth-service-2/package.json ================================================ { "name": "oauth-service-2", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "functions-framework --target=slackRedirect" }, "author": "", "license": "ISC", "devDependencies": { "@google-cloud/functions-framework": "^1.5.1" }, "dependencies": { "request": "^2.88.2", "request-promise-native": "^1.0.8" } } ================================================ FILE: oauth-service-2/utils.js ================================================ exports.redirectUrl = (token, service, team) => { return `vscode://karigari.chat/redirect?token=${token}&service=${service}&team=${team}`; } exports.issueUrl = (errorMessage, serviceName) => { const encode = encodeURIComponent; const title = `[oauth-service] Sign in with ${serviceName} failed: ${errorMessage}`; const body = `- Extension version:\n- VS Code version:`; const baseUrl = "https://github.com/karigari/vscode-chat/issues/new/"; return `${baseUrl}?title=${encode(title)}&body=${encode(body)}`; }; exports.redirectError = (errorMessage, serviceName) => { return `vscode://karigari.chat/error?msg=${errorMessage}&service=${serviceName}`; }; ================================================ FILE: package.json ================================================ { "name": "chat", "displayName": "Chat", "description": "Chat with your Slack and Discord teams from within VS Code", "version": "0.35.0", "homepage": "https://github.com/vsls-contrib/chat", "license": "SEE LICENSE IN LICENSE", "repository": { "type": "git", "url": "https://github.com/vsls-contrib/chat.git" }, "bugs": { "url": "https://github.com/vsls-contrib/chat/issues" }, "publisher": "karigari", "engines": { "vscode": "^1.26.0" }, "icon": "public/icon.png", "galleryBanner": { "color": "#233f6c", "theme": "dark" }, "categories": [ "Other" ], "keywords": [ "slack", "discord", "collaboration", "chat", "live" ], "activationEvents": [ "*" ], "main": "./out/extension", "contributes": { "configuration": { "type": "object", "title": "Team Chat", "properties": { "chat.slack.legacyToken": { "type": "string", "default": null, "description": "[Deprecated] Run the \"Sign In with Slack\" command instead." }, "chat.proxyUrl": { "type": "string", "default": null, "description": "Proxy URL for network connections to the Slack http/websocket requests." }, "chat.rejectTlsUnauthorized": { "type": "boolean", "default": true, "description": "Set this to false to accept unauthorized SSL connections. Defaults to true." }, "chat.providers": { "type": "array", "default": null, "description": "[Experimental] Open bot links inside VS Code. For travis-ci.org, set configuration [\"travis\"]." }, "chat.autoLaunchLiveShareChat": { "type": "boolean", "default": true, "description": "If enabled, the Live Share Chat window will auto-launch when a collaboration session is started." } } }, "commands": [ { "command": "extension.chat.openChatPanel", "title": "Open", "category": "Chat" }, { "command": "extension.chat.changeChannel", "title": "Change Channel", "category": "Chat", "icon": { "light": "public/icons/light/search.svg", "dark": "public/icons/dark/search.svg" } }, { "command": "extension.chat.changeWorkspace", "title": "Change Workspace", "category": "Chat" }, { "command": "extension.chat.authenticate", "title": "Sign In with Slack", "category": "Chat" }, { "command": "extension.chat.signout", "title": "Sign Out", "category": "Chat" }, { "command": "extension.chat.configureToken", "title": "Configure Access Token", "category": "Chat" }, { "command": "extension.chat.updateSelfPresence", "title": "Update your presence status", "category": "Chat" }, { "command": "extension.chat.startLiveShare", "title": "Invite to Live Share", "category": "Chat", "icon": { "light": "public/icons/light/share.svg", "dark": "public/icons/dark/share.svg" } }, { "command": "extension.chat.chatWithSpace", "title": "Open Chat", "category": "Chat", "icon": { "light": "public/icons/light/chat.svg", "dark": "public/icons/dark/chat.svg" } } ], "views": { "chatActivityViewSlack": [ { "id": "chat.treeView.workspaces.slack", "name": "Workspaces", "when": "chat:slack" }, { "id": "chat.treeView.unreads.slack", "name": "Unreads", "when": "chat:slack" }, { "id": "chat.treeView.channels.slack", "name": "Channels", "when": "chat:slack" }, { "id": "chat.treeView.groups.slack", "name": "Groups", "when": "chat:slack" }, { "id": "chat.treeView.ims.slack", "name": "Direct Messages", "when": "chat:slack" } ], "chatActivityViewDiscord": [ { "id": "chat.treeView.workspaces.discord", "name": "Workspaces", "when": "chat:discord" }, { "id": "chat.treeView.unreads.discord", "name": "Unreads", "when": "chat:discord" }, { "id": "chat.treeView.channels.discord", "name": "Channels", "when": "chat:discord" }, { "id": "chat.treeView.groups.discord", "name": "Groups", "when": "chat:discord" }, { "id": "chat.treeView.ims.discord", "name": "Direct Messages", "when": "chat:discord" } ] }, "viewsContainers": { "activitybar": [ { "id": "chatActivityViewSlack", "title": "Slack", "icon": "public/icons/activity-bar-slack-icon.svg", "when": "chat:slack" }, { "id": "chatActivityViewDiscord", "title": "Discord", "icon": "public/icons/activity-bar-discord-icon.svg", "when": "chat:discord" } ] }, "menus": { "view/item/context": [ { "command": "extension.chat.startLiveShare", "when": "chat:vslsEnabled && viewItem == channel", "group": "inline" }, { "command": "extension.chat.chatWithSpace", "when": "view == liveshare.spaces && viewItem =~ /^space/", "group": "chat@1" }, { "command": "extension.chat.chatWithSpace", "when": "view == liveshare.spaces && viewItem =~ /^space/", "group": "inline@1" } ], "view/title": [ { "command": "extension.chat.changeChannel", "when": "view =~ /^chat.treeView(?!.onboarding)/", "group": "navigation@1" } ], "commandPalette": [ { "command": "extension.chat.openChatPanel", "when": "false" }, { "command": "extension.chat.updateSelfPresence", "when": "false" }, { "command": "extension.chat.startLiveShare", "when": "false" }, { "command": "extension.chat.chatWithSpace", "when": "false" } ] } }, "scripts": { "compile": "webpack", "compile:tsc": "tsc -p ./", "postcompile": "npm run webview", "watch": "tsc-watch -p ./", "postinstall": "node ./node_modules/vscode/bin/install", "test": "npm run compile:tsc && node ./node_modules/vscode/bin/test", "webview": "cd webview && npm run build", "vscode:prepublish": "npm run compile" }, "devDependencies": { "@types/http-proxy-agent": "^2.0.0", "@types/keytar": "^4.0.1", "@types/markdown-it": "^0.0.7", "@types/mixpanel": "^2.14.0", "@types/mocha": "^2.2.42", "@types/node": "*", "@types/request-promise-native": "^1.0.15", "@types/semver": "^5.5.0", "@types/webpack": "^4.4.10", "native-modules": "^1.1.0", "shx": "^0.3.2", "ts-loader": "^5.3.3", "ts-mockito": "^2.3.1", "tsc-watch": "^1.0.22", "tslint": "^5.8.0", "typescript": "^3.1.4", "vscode": "^1.1.6", "webpack": "^4.28.3", "webpack-cli": "^3.2.0" }, "dependencies": { "@slack/client": "^4.6.0", "discord.js": "^11.4.2", "emoji-js": "^3.4.1", "gravatar-api": "^1.5.0", "https-proxy-agent": "^2.2.1", "mixpanel": "^0.9.2", "request": "^2.88.0", "request-promise-native": "^1.0.5", "semver": "^5.5.1", "vsls": "^0.3.1291" } } ================================================ FILE: src/bots/travis.ts ================================================ import * as vscode from "vscode"; import * as rp from "request-promise-native"; import { CommandHandler, CommandResponse, MessageCommand } from "../controller/commands"; import { TRAVIS_SCHEME } from "../constants"; function getTravisBuild(username: string, reponame: string, build: string) { return rp({ baseUrl: "https://api.travis-ci.org/", uri: `repos/${username}/${reponame}/builds/${build}`, json: true, headers: { Accept: "application/vnd.travis-ci.2.1+json" } }).then(response => { const { jobs } = response; if (jobs) { return rp({ baseUrl: "https://api.travis-ci.org/", uri: `jobs/${jobs[0].id}/log` }); } }); } function stripAnsiEscapes(input: string) { // Credits: https://stackoverflow.com/a/29497680/1469222 return input.replace( /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, "" ); } export class TravisLinkHandler implements CommandHandler { handle(cmd: MessageCommand): Promise { const { subcommand } = cmd; const { path } = vscode.Uri.parse(subcommand); const matched = path.match(/^\/(.+)\/(.+)\/(.+)\/(.+)$/); if (!!matched && matched.length) { const user = matched[1]; const repo = matched[2]; const buildId = matched[4]; vscode.window.showTextDocument( vscode.Uri.parse(`${TRAVIS_SCHEME}://${user}/${repo}/${buildId}`), { viewColumn: vscode.ViewColumn.One } ); } const response: CommandResponse = { sendToSlack: false, response: "" }; return Promise.resolve(response); } } class TravisDocumentContentProvider implements vscode.TextDocumentContentProvider { provideTextDocumentContent(uri: vscode.Uri): vscode.ProviderResult { const { authority, path } = uri; const splitPath = path.split("/"); return getTravisBuild(authority, splitPath[1], splitPath[2]).then( response => stripAnsiEscapes(response) ); } } export default new TravisDocumentContentProvider(); ================================================ FILE: src/config/https-proxy-agent.d.ts ================================================ // foo.d.ts declare module "https-proxy-agent"; ================================================ FILE: src/config/index.ts ================================================ import * as vscode from "vscode"; import * as https from "https"; import * as HttpsProxyAgent from "https-proxy-agent"; import { CONFIG_ROOT, SelfCommands } from "../constants"; import { KeychainHelper } from "./keychain"; const TOKEN_CONFIG_KEY = "slack.legacyToken"; const TELEMETRY_CONFIG_ROOT = "telemetry"; const TELEMETRY_CONFIG_KEY = "enableTelemetry"; const CREDENTIAL_SERVICE_NAME = "vscode-chat"; const VSLS_CHAT_TOKEN = "vsls-placeholder-token"; const getAccountName = (provider: string, teamId?: string) => { return !!teamId ? `${provider} (${teamId})` : provider; }; export class ConfigHelper { static getRootConfig() { return vscode.workspace.getConfiguration(CONFIG_ROOT); } static updateRootConfig(section: string, value: any): Promise { // Convert Thenable to Promise to be able to use Promise.all const rootConfig = this.getRootConfig(); return new Promise((resolve, reject) => { rootConfig.update(section, value, vscode.ConfigurationTarget.Global).then( result => { return resolve(result); }, error => { return reject(error); } ); }); } static async getToken( service: string, teamId?: string ): Promise { if (service === "vslsSpaces") { return VSLS_CHAT_TOKEN; } const accountName = getAccountName(service, teamId); const keychainToken: string | null = await KeychainHelper.get( CREDENTIAL_SERVICE_NAME, accountName ); return keychainToken; } static clearTokenFromSettings() { this.updateRootConfig(TOKEN_CONFIG_KEY, undefined); } static async setToken( token: string, providerName: string, teamId?: string ): Promise { // TODO: it is possible that the keychain will fail // See https://github.com/Microsoft/vscode-pull-request-github/commit/306dc5d27460599f3402f4b9e01d97bf638c639f const accountName = getAccountName(providerName, teamId); await KeychainHelper.set(CREDENTIAL_SERVICE_NAME, accountName, token); // When token is set, we need to call reset vscode.commands.executeCommand(SelfCommands.SETUP_NEW_PROVIDER, { newInitialState: { provider: providerName, teamId } }); } static async clearToken(provider: string, teamId?: string): Promise { await KeychainHelper.clear( CREDENTIAL_SERVICE_NAME, getAccountName(provider, teamId) ); } static getProxyUrl() { // Stored under CONFIG_ROOT.proxyUrl const { proxyUrl } = this.getRootConfig(); return proxyUrl; } static getTlsRejectUnauthorized() { const { rejectTlsUnauthorized } = this.getRootConfig(); return rejectTlsUnauthorized; } static getAutoLaunchLiveShareChat() { const { autoLaunchLiveShareChat } = this.getRootConfig(); return autoLaunchLiveShareChat; } static hasTelemetry(): boolean { const config = vscode.workspace.getConfiguration(TELEMETRY_CONFIG_ROOT); return !!config.get(TELEMETRY_CONFIG_KEY); } static hasTravisProvider(): boolean { // Stored under CONFIG_ROOT.providers, which is string[] const { providers } = this.getRootConfig(); return providers && providers.indexOf("travis") >= 0; } static getCustomAgent() { const proxyUrl = this.getProxyUrl(); if (!!proxyUrl) { return new HttpsProxyAgent(proxyUrl); } const rejectUnauthorized = this.getTlsRejectUnauthorized(); if (!rejectUnauthorized) { return new https.Agent({ rejectUnauthorized: false }); } } } ================================================ FILE: src/config/keychain.ts ================================================ import * as vscode from "vscode"; import * as str from "../strings"; import { keychain } from "../utils/keychain"; import IssueReporter from "../issues"; import Logger from "../logger"; const UNDEFINED_ERROR = "System keychain is undefined"; export class KeychainHelper { // Adds retry to keychain operations if we are denied access static async handleException(error: Error, retryCall: Function) { Logger.log(`Keychain access: ${error}`); const actionItems = [str.RETRY, str.REPORT_ISSUE]; const action = await vscode.window.showInformationMessage( str.KEYCHAIN_ERROR, ...actionItems ); switch (action) { case str.RETRY: return retryCall(); case str.REPORT_ISSUE: const title = "Unable to access keychain"; return IssueReporter.openNewIssue(title, `${error}`); } } static async get(service: string, account: string) { try { if (!keychain) { throw new Error(UNDEFINED_ERROR); } const password = await keychain.getPassword(service, account); return password; } catch (error) { // If user denies, we can catch the error // On Mac, this looks like `Error: User canceled the operation.` return this.handleException(error, () => this.get(service, account)); } } static async set(service: string, account: string, password: string) { try { if (!keychain) { throw new Error(UNDEFINED_ERROR); } await keychain.setPassword(service, account, password); } catch (error) { return this.handleException(error, () => this.set(service, account, password) ); } } static async clear(service: string, account: string) { try { if (!keychain) { throw new Error(UNDEFINED_ERROR); } await keychain.deletePassword(service, account); } catch (error) { return this.handleException(error, () => this.clear(service, account)); } } } ================================================ FILE: src/constants.ts ================================================ export const CONFIG_ROOT = "chat"; export const EXTENSION_ID = "karigari.chat"; export const OUTPUT_CHANNEL_NAME = "Team Chat"; export const CONFIG_AUTO_LAUNCH = "chat.autoLaunchLiveShareChat"; // Is there a way to get this url from the vsls extension? export const LIVE_SHARE_BASE_URL = `insiders.liveshare.vsengsaas.visualstudio.com`; export const VSLS_EXTENSION_ID = `ms-vsliveshare.vsliveshare`; export const VSLS_EXTENSION_PACK_ID = `ms-vsliveshare.vsliveshare-pack`; export const VSLS_SPACES_EXTENSION_ID = `vsls-contrib.spaces`; export const LiveShareCommands = { START: "liveshare.start", END: "liveshare.end", JOIN: "liveshare.join" }; export const VSCodeCommands = { OPEN: "vscode.open", OPEN_SETTINGS: "workbench.action.openSettings" }; export const SelfCommands = { OPEN_WEBVIEW: "extension.chat.openChatPanel", CHANGE_WORKSPACE: "extension.chat.changeWorkspace", CHANGE_CHANNEL: "extension.chat.changeChannel", SIGN_IN: "extension.chat.authenticate", SIGN_OUT: "extension.chat.signout", CONFIGURE_TOKEN: "extension.chat.configureToken", LIVE_SHARE_FROM_MENU: "extension.chat.startLiveShare", LIVE_SHARE_SLASH: "extension.chat.slashLiveShare", LIVE_SHARE_SESSION_CHANGED: "extension.chat.vslsSessionChanged", RESET_STORE: "extension.chat.reset", SETUP_NEW_PROVIDER: "extension.chat.setupNewProvider", FETCH_REPLIES: "extension.chat.fetchReplies", UPDATE_MESSAGES: "extension.chat.updateMessages", CLEAR_MESSAGES: "extension.chat.clearMessages", UPDATE_MESSAGE_REPLIES: "extension.chat.updateReplies", UPDATE_PRESENCE_STATUSES: "extension.chat.updatePresenceStatuses", UPDATE_SELF_PRESENCE: "extension.chat.updateSelfPresence", UPDATE_SELF_PRESENCE_VIA_VSLS: "extension.chat.updateSelfPresenceVsls", ADD_MESSAGE_REACTION: "extension.chat.addMessageReaction", REMOVE_MESSAGE_REACTION: "extension.chat.removeMessageReaction", SEND_MESSAGE: "extension.chat.sendMessage", SEND_THREAD_REPLY: "extension.chat.sendThreadReply", SEND_TYPING: "extension.chat.sendTypingMessage", SHOW_TYPING: "extension.chat.showTypingMessage", INVITE_LIVE_SHARE_CONTACT: "extension.chat.inviteLiveShareContact", CHANNEL_MARKED: "extension.chat.updateChannelMark", HANDLE_INCOMING_LINKS: "extension.chat.handleIncomingLinks", SEND_TO_WEBVIEW: "extension.chat.sendToWebview", CHAT_WITH_VSLS_SPACE: "extension.chat.chatWithSpace", VSLS_SPACE_JOINED: "extension.chat.vslsSpaceJoined" }; export const SLASH_COMMANDS: any = { live: { share: { action: LiveShareCommands.START, options: { suppressNotification: true } }, end: { action: LiveShareCommands.END, options: {} } } }; // Reverse commands are acted on when received from Slack export const REVERSE_SLASH_COMMANDS = { live: { request: {} } }; // Internal uri schemes export const TRAVIS_BASE_URL = `travis-ci.org`; export const TRAVIS_SCHEME = "chat-travis-ci"; // Slack App const REDIRECT_URI = `https://us-central1-eco-theater-119616.cloudfunctions.net/slackRedirect` const SLACK_OAUTH_BASE = `https://slack.com/oauth/authorize?scope=client&client_id=282186700213.419156835749`; export const SLACK_OAUTH = `${SLACK_OAUTH_BASE}&redirect_uri=${REDIRECT_URI}` // Discord const DISCORD_SCOPES = ["identify", "rpc.api", "messages.read", "guilds"]; const DISCORD_SCOPE_STRING = DISCORD_SCOPES.join("%20"); const DISCORD_CLIENT_ID = "486416707951394817"; export const DISCORD_OAUTH = `https://discordapp.com/oauth2/authorize?client_id=${DISCORD_CLIENT_ID}&response_type=code&scope=${DISCORD_SCOPE_STRING}`; // Telemetry export const MIXPANEL_TOKEN = "14c9fea2bf4e06ba766e16eca1bce728"; ================================================ FILE: src/controller/commands.ts ================================================ import * as vscode from "vscode"; import * as vsls from "vsls"; import { SLASH_COMMANDS, LIVE_SHARE_BASE_URL, TRAVIS_BASE_URL, VSCodeCommands } from "../constants"; import { TravisLinkHandler } from "../bots/travis"; import { ConfigHelper } from "../config"; export interface MessageCommand { namespace: string; subcommand: string; } export interface CommandResponse { sendToSlack: Boolean; response: string; } export interface CommandHandler { handle: (cmd: MessageCommand) => Promise; } class VscodeCommandHandler implements CommandHandler { execute = (command: string, ...rest: any[]): Promise => { // Wraps the executeCommand thenable into a promise // https://github.com/Microsoft/vscode/issues/11693#issuecomment-247495996 return new Promise((resolve, reject) => { vscode.commands.executeCommand(command, ...rest).then( result => { return resolve(result); }, error => { vscode.window.showErrorMessage(error.toString()); return reject(error); } ); }); }; handle = (cmd: MessageCommand): Promise => { const { namespace, subcommand } = cmd; const commands = SLASH_COMMANDS[namespace]; const { action, options } = commands[subcommand]; return this.execute(action, options).then((response: vscode.Uri) => { // We append to the URL so our link parsing works // TODO(arjun) Uri is only valid for `/live share` command const responseString = response ? `<${response.toString()}>` : ""; const sendToSlack = namespace === "live" && subcommand === "share"; return { sendToSlack, response: responseString }; }); }; } class OpenCommandHandler extends VscodeCommandHandler { handle = async (cmd: MessageCommand): Promise => { const { subcommand } = cmd; let uri: vscode.Uri | undefined; try { uri = vscode.Uri.parse(subcommand); switch (uri.authority) { case LIVE_SHARE_BASE_URL: const liveshare = await vsls.getApi(); const opts: vsls.JoinOptions = { newWindow: false }; if (liveshare) { await liveshare.join(uri, opts); } break; case TRAVIS_BASE_URL: if (ConfigHelper.hasTravisProvider()) { const travisHandler = new TravisLinkHandler(); return travisHandler.handle(cmd); } default: return this.execute(VSCodeCommands.OPEN, uri); } } catch (err) { // return new Promise((_, reject) => reject()); } }; } /** * Finds the correct command handler for the given command * and runs it */ export default class CommandDispatch { handle = (message: MessageCommand): Promise => { const { namespace, subcommand } = message; if (namespace === "open") { // We might have to convert this into const openHandler = new OpenCommandHandler(); return openHandler.handle(message); } else { // Others are all vs code commands const vscodeHandler = new VscodeCommandHandler(); return vscodeHandler.handle(message); } }; } ================================================ FILE: src/controller/emoji-js.d.ts ================================================ // foo.d.ts declare module "emoji-js"; ================================================ FILE: src/controller/index.ts ================================================ import * as vscode from "vscode"; import WebviewContainer from "../webview"; import { SLASH_COMMANDS, REVERSE_SLASH_COMMANDS, SelfCommands } from "../constants"; import Logger from "../logger"; import CommandDispatch, { MessageCommand } from "./commands"; import markdownTransform from "./markdowner"; export const getCommand = (text: string): MessageCommand | undefined => { const pattern = /^\/(\w+) (\w+)$/; const trimmed = text.trim(); const matched = trimmed.match(pattern); if (matched) { return { namespace: matched[1], subcommand: matched[2] }; } }; class ViewController { ui: WebviewContainer | undefined; isUIReady: Boolean = false; // Vuejs loaded pendingMessage: UIMessage | undefined = undefined; currentSource: EventSource | undefined; currentProvider: string | undefined; currentChannelId: string | undefined; constructor( private context: vscode.ExtensionContext, private onUIDispose: (provider: string | undefined, source: EventSource | undefined) => void, private onUIVisible: (provider: string | undefined) => void, private onUIFocus: (provider: string | undefined) => void ) {} isUILoaded = () => !!this.ui; loadUi = () => { if (this.ui) { this.ui.reveal(); } else { const { extensionPath } = this.context; this.ui = new WebviewContainer( extensionPath, () => { this.ui = undefined; this.isUIReady = false; this.onUIDispose(this.currentProvider, this.currentSource); }, isVisible => (isVisible ? this.onUIVisible(this.currentProvider) : null) ); this.ui.setMessageHandler(this.sendToExtension); } }; dispatchCommand(command: MessageCommand) { const handler = new CommandDispatch(); handler.handle(command).then(result => { if (!!result) { const { sendToSlack, response } = result; if (sendToSlack && response) { this.sendTextMessage(response); } } }); } isValidCommand = (text: string, commandList: { [name: string]: any }) => { const parsed = getCommand(text); if (parsed) { const { namespace, subcommand } = parsed; if (namespace in commandList) { const subcommands = Object.keys(commandList[namespace]); return subcommands.indexOf(subcommand) >= 0; } } return false; }; isValidReverseCommand = (text: string) => { return this.isValidCommand(text, REVERSE_SLASH_COMMANDS); }; handleCommand = (text: string) => { if (this.isValidCommand(text, SLASH_COMMANDS)) { const parsed = getCommand(text); if (!!parsed) { const { namespace, subcommand } = parsed; if (namespace === "live" && subcommand === "share") { // Temporary bypass for "/live share" till we move // all of this to the common command handlers return vscode.commands.executeCommand(SelfCommands.LIVE_SHARE_SLASH, { provider: this.currentProvider }); } else { return this.dispatchCommand(parsed); } } } if (text === "/clear") { return vscode.commands.executeCommand(SelfCommands.CLEAR_MESSAGES, { channelId: this.currentChannelId, provider: this.currentProvider }); } if (text === "/invite") { return vscode.commands.executeCommand(SelfCommands.INVITE_LIVE_SHARE_CONTACT, { channelId: this.currentChannelId, provider: this.currentProvider }); } if (this.isValidReverseCommand(text)) { return this.sendTextMessage(text); } // TODO(arjun): if not valid, then we need to parse and make a chat.command // API call, instead of sending it as a simple text message. // Docs: https://github.com/ErikKalkoken/slackApiDoc/blob/master/chat.command.md return this.sendTextMessage(text); }; handleInternal = (message: any) => { const { text } = message; if (text === "is_ready") { this.isUIReady = true; return this.pendingMessage ? this.sendToUI(this.pendingMessage) : null; } if (text === "is_focused") { this.onUIFocus(this.currentProvider); } if (text === "fetch_replies") { const { parentTimestamp } = message; vscode.commands.executeCommand(SelfCommands.FETCH_REPLIES, { parentTimestamp, provider: this.currentProvider }); } if (text === "is_typing") { vscode.commands.executeCommand(SelfCommands.SEND_TYPING, { channelId: this.currentChannelId, provider: this.currentProvider }); } }; sendTextMessage = (text: string) => { return vscode.commands.executeCommand(SelfCommands.SEND_MESSAGE, { text, provider: this.currentProvider }); }; sendThreadReply = (payload: any) => { const { text, parentTimestamp } = payload; return vscode.commands.executeCommand(SelfCommands.SEND_THREAD_REPLY, { text, parentTimestamp, provider: this.currentProvider }); }; sendToExtension = (message: ExtensionMessage) => { const { type, text } = message; Logger.log(`Sending to extension (${type}) ${text}`); switch (type) { case "internal": return this.handleInternal(message); case "link": return this.dispatchCommand({ namespace: "open", subcommand: text }); case "command": return this.handleCommand(text); case "text": return text ? this.sendTextMessage(text) : null; case "thread_reply": return this.sendThreadReply(text); } }; handleReverseCommands = (uiMessage: UIMessage) => { // TODO: Reverse commands are disabled, until we fix this // Reverse commands are slash commands fired by other Slack users // For example, `/live request` requests someone to host a session const { currentUser, messages } = uiMessage; let handledMessages: ChannelMessages = {}; Object.keys(messages).forEach(ts => { // Any of these messages might be reverse commands const { text, userId } = messages[ts]; const notCurrentUser = currentUser.id !== userId; // let textHTML = messages[ts].textHTML; if (this.isValidReverseCommand(text) && notCurrentUser) { if (text === "/live request") { const confirmation = `Accept`; // textHTML = `${str.LIVE_REQUEST_MESSAGE} ${confirmation}`; } } handledMessages[ts] = { ...messages[ts] // textHTML }; }); return { ...uiMessage, messages: handledMessages }; }; updateCurrentState = (provider: string, channelId: string, source: EventSource) => { this.currentProvider = provider; this.currentChannelId = channelId; this.currentSource = source; }; sendToUI = (uiMessage: UIMessage) => { const { provider: incomingProvider, channel: incomingChannel } = uiMessage; if (!!this.ui && this.ui.isVisible()) { // The webview is visible => we check if the incoming message is valid. const isSameProvider = !this.currentProvider || incomingProvider === this.currentProvider; const isSameChannel = !this.currentChannelId || incomingChannel.id === this.currentChannelId; if (!isSameChannel || !isSameProvider) { return; // Ignore this message. } } if (!this.isUIReady) { this.pendingMessage = uiMessage; } else { const { messages } = uiMessage; const size = Object.keys(messages).length; Logger.log(`Sending to webview: ${size} messages`); // Handle markdown const mdMessages = markdownTransform(uiMessage); // Handle reverse slash commands // Since this overwrites the textHTML field, it should happen // after the markdown const message = this.handleReverseCommands(mdMessages); // Send to UI after markdown if (this.ui) { this.ui.update(message); this.pendingMessage = undefined; } } }; } export default ViewController; ================================================ FILE: src/controller/markdown-it-slack.d.ts ================================================ // foo.d.ts declare module "markdown-it-slack"; ================================================ FILE: src/controller/markdowner.ts ================================================ import * as EmojiConvertor from "emoji-js"; export const parseUsernames = (uiMessage: UIMessage): UIMessage => { // Find and replace names like <@UBCQ8LF28> // TODO: fix this for channel names, which show up as <#C8A187ZRQ|general> const { messages, users } = uiMessage; let newMessages: ChannelMessages = {}; Object.keys(messages).map(ts => { const message = messages[ts]; let { text } = message; const matched = text.match(/<@([A-Z0-9]+)>/); if (matched && matched.length > 0) { const userId = matched[1]; if (userId in users) { const { name } = users[userId]; text = text.replace(matched[0], `@${name}`); } } newMessages[ts] = { ...message, text }; }); return { ...uiMessage, messages: newMessages }; }; export const emojify = (messages: ChannelMessages): ChannelMessages => { // Even though we are using markdown-it-slack, it does not support // emoji skin tones. If that changes, we can remove this method. const emoji = new EmojiConvertor(); emoji.allow_native = true; // We have added node_modules/emoji-datasource to vscodeignore since we use // allow_native. If this changes, we might have to use emoji sheets (through CDN?) emoji.replace_mode = "unified"; let emojifiedMessages: ChannelMessages = {}; Object.keys(messages).forEach(key => { const message = messages[key]; const { text, reactions } = message; emojifiedMessages[key] = { ...message, reactions: reactions ? reactions.map(reaction => ({ ...reaction, name: emoji.replace_colons(reaction.name) })) : [], text: emoji.replace_colons(text ? text : "") }; }); return emojifiedMessages; }; const parseSimpleLinks = (messages: ChannelMessages): ChannelMessages => { let parsed: ChannelMessages = {}; Object.keys(messages).forEach(key => { const { content, text } = messages[key]; let newContent: MessageContent | undefined = undefined; const URL_REGEX = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=;\^]*)/; const re = new RegExp(`${URL_REGEX.source}`, "g"); if (!!content) { newContent = { ...content, text: content.text ? content.text.replace(re, function(a, b, c, d, e) { return `[${a}](${a})`; }) : "", footer: content.footer ? content.footer.replace(re, function(a, b, c, d, e) { return `[${a}](${a})`; }) : "" }; } parsed[key] = { ...messages[key], text: text ? text.replace(re, function(a, b, c, d, e) { return `[${a}](${a})`; }) : "", content: newContent }; }); return parsed; } export const parseSlackLinks = (messages: ChannelMessages): ChannelMessages => { // Looks for pattern, and replaces them with normal markdown // The |pattern can be optional let parsed: ChannelMessages = {}; Object.keys(messages).forEach(key => { const { content, text } = messages[key]; let newContent: MessageContent | undefined = undefined; const URL_REGEX = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=;\^]*)/; const SLACK_MODIFIER = /(|.[^><]+)/; const re = new RegExp(`<(${URL_REGEX.source})(${SLACK_MODIFIER.source})>`, "g"); if (!!content) { newContent = { ...content, text: content.text ? content.text.replace(re, function(a, b, c, d, e) { return e ? `[${e.substr(1)}](${b})` : `[${b}](${b})`; }) : "", footer: content.footer ? content.footer.replace(re, function(a, b, c, d, e) { return e ? `[${e.substr(1)}](${b})` : `[${b}](${b})`; }) : "" }; } parsed[key] = { ...messages[key], text: text ? text.replace(re, function(a, b, c, d, e) { return e ? `[${e.substr(1)}](${b})` : `[${b}](${b})`; }) : "", content: newContent }; }); return parsed; }; const transformChain = (uiMessage: UIMessage): UIMessage => { const { messages } = parseUsernames(uiMessage); const linkParser = uiMessage.provider === "vslsSpaces" ? parseSimpleLinks : parseSlackLinks; return { ...uiMessage, messages: linkParser(emojify(messages)) }; }; export default transformChain; ================================================ FILE: src/discord/index.ts ================================================ import * as vscode from "vscode"; import * as Discord from "discord.js"; import * as rp from "request-promise-native"; import { SelfCommands } from "../constants"; import { toTitleCase } from "../utils"; import Logger from "../logger"; const HISTORY_LIMIT = 50; const MEMBER_LIMIT = 500; const getPresence = (presence: Discord.Presence): UserPresence => { const { status } = presence; switch (status) { case "online": return UserPresence.available; case "dnd": return UserPresence.doNotDisturb; case "idle": return UserPresence.idle; case "offline": return UserPresence.offline; } }; const getMessageContent = ( raw: Discord.Message ): MessageContent | undefined => { const { embeds } = raw; if (!!embeds && embeds.length > 0) { const firstEmbed = embeds[0]; return { author: ``, pretext: ``, title: firstEmbed.title, titleLink: firstEmbed.url, text: firstEmbed.description, footer: `` }; } }; const getMessage = (raw: Discord.Message): Message => { const { author, createdTimestamp, content, reactions, editedTimestamp } = raw; const timestamp = (createdTimestamp / 1000).toString(); let attachment = undefined; const attachments = raw.attachments.array(); if (attachments.length > 0) { // This only shows the first attachment const selected = attachments[0]; attachment = { name: selected.filename, permalink: selected.url }; } return { timestamp, userId: author.id, text: content, isEdited: !!editedTimestamp, content: getMessageContent(raw), replies: {}, attachment, reactions: reactions.map(rxn => ({ name: rxn.emoji.name, count: rxn.count, userIds: rxn.users.map(user => user.id) })) }; }; const getUser = (raw: Discord.User): User => { const { id: userId, username, avatar, presence } = raw; return { id: userId, name: username, fullName: username, imageUrl: getImageUrl(userId, avatar), smallImageUrl: getSmallImageUrl(userId, avatar), presence: getPresence(presence) }; }; const DEFAULT_AVATARS = [ "https://discordapp.com/assets/dd4dbc0016779df1378e7812eabaa04d.png", "https://discordapp.com/assets/0e291f67c9274a1abdddeb3fd919cbaa.png", "https://discordapp.com/assets/6debd47ed13483642cf09e832ed0bc1b.png", "https://discordapp.com/assets/322c936a8c8be1b803cd94861bdfa868.png", "https://discordapp.com/assets/1cbd08c76f8af6dddce02c5138971129.png" ]; const getAvatarUrl = (userId: string, avatar: string, size: number) => { if (!avatar) { return DEFAULT_AVATARS[Math.floor(Math.random() * DEFAULT_AVATARS.length)]; } else { // size can be any power of two between 16 and 2048 return `https://cdn.discordapp.com/avatars/${userId}/${avatar}.png?size=${size}`; } }; const getImageUrl = (userId: string, avatar: string) => getAvatarUrl(userId, avatar, 128); const getSmallImageUrl = (userId: string, avatar: string) => getAvatarUrl(userId, avatar, 32); export class DiscordChatProvider implements IChatProvider { client: Discord.Client; mutedChannels: Set = new Set([]); imChannels: Channel[] = []; constructor(private token: string, private manager: IManager) { this.client = new Discord.Client(); } async validateToken(): Promise { const response = await rp({ baseUrl: `https://discordapp.com/api/v6`, uri: `/users/@me`, json: true, headers: { Authorization: `${this.token}` } }); const { id, username: name } = response; return { id, name, teams: [], currentTeamId: undefined, provider: Providers.discord }; } connect(): Promise { return new Promise(resolve => { this.client.on("ready", () => { const { id, username: name } = this.client.user; const teams = this.client.guilds.array().map(guild => ({ id: guild.id, name: guild.name })); const currentUser: CurrentUser = { id, name, teams, currentTeamId: undefined, provider: Providers.discord }; resolve(currentUser); }); if (process.env.IS_DEBUG === "true") { // Debug logs for local testing this.client.on("debug", info => console.log("Discord client log:", info) ); } this.client.on("presenceUpdate", (_, newMember: Discord.GuildMember) => { const { id: userId, presence } = newMember; vscode.commands.executeCommand(SelfCommands.UPDATE_PRESENCE_STATUSES, { userId, presence: getPresence(presence), provider: "discord" }); }); this.client.on("message", msg => { this.handleIncomingMessage(msg); this.handleIncomingLinks(msg); }); this.client.on("messageUpdate", (_, msg: Discord.Message) => { this.handleIncomingMessage(msg); }); this.client.on("error", error => { Logger.log(`[ERROR] Discord: ${error.message}`); }); this.client.login(this.token); }); } handleIncomingMessage(msg: Discord.Message) { // If message has guild, we check for current guild // Else, message is from a DM or group DM const currentGuild = this.getCurrentGuild(); const { guild } = msg; if (!currentGuild) { return; } if (!guild || guild.id === currentGuild.id) { let newMessages: ChannelMessages = {}; const channelId = msg.channel.id; const parsed = getMessage(msg); const { timestamp } = parsed; newMessages[timestamp] = parsed; vscode.commands.executeCommand(SelfCommands.UPDATE_MESSAGES, { channelId, messages: newMessages, provider: "discord" }); } } handleIncomingLinks(msg: Discord.Message) { // For vsls invitations const currentGuild = this.getCurrentGuild(); const { guild } = msg; if (!currentGuild) { return; } if (!guild || guild.id === currentGuild.id) { const parsed = getMessage(msg); let uri: vscode.Uri | undefined; try { const { text } = parsed; if (text.startsWith("http")) { uri = vscode.Uri.parse(parsed.text); vscode.commands.executeCommand(SelfCommands.HANDLE_INCOMING_LINKS, { provider: "discord", senderId: parsed.userId, uri }); } } catch (e) {} } } isConnected(): boolean { return !!this.client && !!this.client.readyTimestamp; } getUserPreferences(): Promise { const mutedChannels = Array.from(this.mutedChannels); return Promise.resolve({ mutedChannels }); } getCurrentGuild(): Discord.Guild | undefined { const currentUserInfo = this.manager.store.getCurrentUser("discord"); if (!!currentUserInfo) { const { currentTeamId } = currentUserInfo; return this.client.guilds.find(guild => guild.id === currentTeamId); } } async fetchUsers(): Promise { const guild = this.getCurrentGuild(); const readyTimestamp = (this.client.readyTimestamp / 1000.0).toString(); let users: Users = {}; // We first build users from IM channels, and then from the guild members this.imChannels = this.client.channels .filter(channel => channel.type === "dm") .map(channel => { const dmChannel = channel; const { id, recipient } = dmChannel; const user = getUser(recipient); users[user.id] = user; return { id, name: recipient.username, type: ChannelType.im, readTimestamp: readyTimestamp, unreadCount: 0 }; }); if (!!guild) { // Getting guild members requires knowing the guild const response = await guild.fetchMembers("", MEMBER_LIMIT); response.members.forEach(member => { const { user: discordUser, roles } = member; const hoistedRole = roles.find(role => role.hoist); let roleName = undefined; if (!!hoistedRole) { roleName = toTitleCase(hoistedRole.name); } const user = getUser(discordUser); users[user.id] = { ...user, roleName }; }); } return users; } async fetchUserInfo(userId: string): Promise { const discordUser = await this.client.fetchUser(userId); return getUser(discordUser); } fetchChannels(users: Users): Promise { // This fetches channels of the current guild, and (group) DMs. // For unreads, we are not retrieving historical unreads, not clear if API supports that. const readyTimestamp = (this.client.readyTimestamp / 1000.0).toString(); const guild = this.getCurrentGuild(); let categories: { [id: string]: string } = {}; if (!!guild) { guild.channels .filter(channel => channel.type === "category") .forEach(channel => { const { id: channelId, name, muted } = channel; categories[channelId] = name; if (muted) { this.mutedChannels.add(channelId); } }); const currentUserInfo = this.manager.store.getCurrentUser("discord"); const guildChannels: Channel[] = guild.channels .filter(channel => channel.type !== "category") .filter(channel => { if (!!currentUserInfo) { const userId = currentUserInfo.id; const permissions = channel.permissionsFor(userId); const permissionFlag = Discord.Permissions.FLAGS.VIEW_CHANNEL; if (!!permissions && permissionFlag) { return permissions.has(permissionFlag); } } return false; }) .map(channel => { const { name, id, parentID } = channel; return { id, name, categoryName: categories[parentID], type: ChannelType.channel, readTimestamp: readyTimestamp, unreadCount: 0 }; }); const groupChannels = this.client.channels .filter(channel => channel.type === "group") .map(channel => { const groupChannel = channel; const { id, recipients } = groupChannel; return { id, name: recipients.map(recipient => recipient.username).join(", "), type: ChannelType.group, readTimestamp: readyTimestamp, unreadCount: 0 }; }); return Promise.resolve([ ...guildChannels, ...this.imChannels, ...groupChannels ]); } return Promise.resolve([]); } async loadChannelHistory(channelId: string): Promise { const channel: any = this.client.channels.find( channel => channel.id === channelId ); // channel.fetchMessages will break for voice channels const messages: Discord.Message[] = await channel.fetchMessages({ limit: HISTORY_LIMIT }); let result: ChannelMessages = {}; messages.forEach(message => { const parsed = getMessage(message); const { timestamp } = parsed; result[timestamp] = parsed; }); return result; } sendMessage( text: string, currentUserId: string, channelId: string ): Promise { const channel: any = this.client.channels.find( channel => channel.id === channelId ); return channel.send(text); } fetchChannelInfo(channel: Channel): Promise { return Promise.resolve(channel); } subscribePresence(users: Users): void {} sendThreadReply() { return Promise.resolve(); } async updateSelfPresence( presence: UserPresence ): Promise { let status: Discord.PresenceStatus; switch (presence) { case UserPresence.available: status = "online"; break; case UserPresence.doNotDisturb: status = "dnd"; break; case UserPresence.idle: status = "idle"; break; case UserPresence.invisible: status = "invisible"; break; default: throw new Error("status not supported by discord"); } const response = await this.client.user.setPresence({ status }); // response.presence.status is always `invisible` // Hence we return the original presence input as success return presence; } destroy(): Promise { if (!!this.client) { return this.client.destroy(); } return Promise.resolve(); } async markChannel(channel: Channel, ts: string): Promise { // Discord does not have a concept of timestamp, it will acknowledge everything // return Promise.resolve(channel); const { id: channelId } = channel; const discordChannel: any = this.client.channels.find( channel => channel.id === channelId ); await discordChannel.acknowledge(); return { ...channel, readTimestamp: ts }; } fetchThreadReplies(channelId: string, ts: string): Promise { // Never called. Discord has no threads. return Promise.resolve(); } createIMChannel(user: User): Promise { // This is required to share vsls links with users that // do not have corresponding DM channels return Promise.resolve(undefined); } async sendTyping(currentUserId: string, channelId: string) { } } ================================================ FILE: src/extension.ts ================================================ import * as vscode from "vscode"; import * as vsls from "vsls"; import ViewController from "./controller"; import Manager from "./manager"; import Logger from "./logger"; import { Store } from "./store"; import * as str from "./strings"; import { SelfCommands, SLACK_OAUTH, DISCORD_OAUTH, CONFIG_ROOT, CONFIG_AUTO_LAUNCH, TRAVIS_SCHEME, VSLS_SPACES_EXTENSION_ID } from "./constants"; import travis from "./bots/travis"; import { ExtensionUriHandler } from "./uriHandler"; import * as utils from "./utils"; import { askForAuth } from "./onboarding"; import { ConfigHelper } from "./config"; import TelemetryReporter from "./telemetry"; import IssueReporter from "./issues"; let store: Store; let manager: Manager; let controller: ViewController; let telemetry: TelemetryReporter; let typingTimers: { [key: string]: NodeJS.Timer | undefined } = {}; export function activate(context: vscode.ExtensionContext) { Logger.log("Activating vscode-chat"); store = new Store(context); manager = new Manager(store); telemetry = new TelemetryReporter(manager); // telemetry.record( // EventType.activationStarted, // undefined, // undefined, // undefined // ); controller = new ViewController( context, (provider, source) => onUIDispose(provider, source), provider => { if (provider) { const lastChannelId = manager.store.getLastChannelId(provider); if (lastChannelId) { return manager.loadChannelHistory(provider, lastChannelId); } } }, provider => (!!provider ? manager.updateReadMarker(provider) : undefined) ); const setupFreshInstall = () => { const installationId = manager.store.generateInstallationId(); telemetry.setUniqueId(installationId); telemetry.record(EventType.extensionInstalled, undefined, undefined, undefined); }; const handleNoToken = (canPromptForAuth: boolean) => { const hasVsls = utils.hasVslsExtension() || utils.hasVslsExtensionPack(); if (canPromptForAuth && !hasVsls) { askForAuth(); } throw new Error(str.TOKEN_NOT_FOUND); }; const initializeToken = async (canPromptForAuth: boolean, newInitialState: InitialState | undefined) => { await manager.initializeToken(newInitialState); if (!manager.isTokenInitialized) { setTimeout(() => handleNoToken(canPromptForAuth), 5 * 1000); } }; const setup = async (canPromptForAuth: boolean, newInitialState: InitialState | undefined): Promise => { await store.runStateMigrations(); const isFreshInstall = !manager.store.installationId; if (isFreshInstall) { setupFreshInstall(); } if (!manager.isTokenInitialized || !!newInitialState) { // We force initialization if we are provided a newInitialState await initializeToken(canPromptForAuth, newInitialState); } await manager.initializeProviders(); if (manager.isProviderEnabled("discord")) { if (!manager.getCurrentTeamIdFor("discord")) { await askForWorkspace("discord"); } } // TODO: In discord, user preferences are available after channels are fetched manager.updateUserPrefsForAll(); // async update await manager.initializeStateForAll(); manager.subscribePresenceForAll(); }; const sendMessage = (providerName: string, text: string, parentTimestamp: string | undefined) => { const lastChannelId = manager.store.getLastChannelId(providerName); telemetry.record(EventType.messageSent, undefined, lastChannelId, providerName); manager.updateReadMarker(providerName); if (!!lastChannelId) { // lastChannelId should always exist since this will only be // called after loading the webview (which requires lastChannelId) return manager.sendMessage(providerName, text, lastChannelId, parentTimestamp); } }; const askForChannel = async ( providerName: string | undefined ): Promise<{ channel: Channel; providerName: string } | undefined> => { // This can be called with an undefined providerName, in which // case we show channels from all available providers. let channelList = manager.getChannelLabels(providerName).sort((a, b) => b.unread - a.unread); const quickpickItems: vscode.QuickPickItem[] = channelList.map(channelLabel => { const description = `${channelLabel.providerName} · ${channelLabel.teamName}`; return { label: channelLabel.label, detail: channelLabel.channel.categoryName, description }; }); const finalList = [...quickpickItems, { label: str.RELOAD_CHANNELS }]; const selected = await vscode.window.showQuickPick(finalList, { placeHolder: str.CHANGE_CHANNEL_TITLE, matchOnDetail: true, matchOnDescription: true }); if (!!selected) { if (selected.label === str.RELOAD_CHANNELS) { let currentProvider = providerName; if (!currentProvider) { const providers = manager.store.getCurrentUserForAll().map(userInfo => userInfo.provider); currentProvider = await askForProvider(providers); } if (!!currentProvider) { await manager.fetchUsers(currentProvider); await manager.fetchChannels(currentProvider); return askForChannel(providerName); } } const selectedChannelLabel = channelList.find( x => x.label === selected.label && x.channel.categoryName === selected.detail ); if (!!selectedChannelLabel) { const { channel, providerName } = selectedChannelLabel; return { channel, providerName: providerName.toLowerCase() }; } } }; const openChatWebview = async (chatArgs?: ChatArgs) => { let provider = !!chatArgs ? chatArgs.providerName : undefined; let channelId = !!chatArgs ? chatArgs.channelId : undefined; const source = !!chatArgs ? chatArgs.source : EventSource.command; if (!chatArgs) { const selected = await askForChannel(undefined); if (!!selected) { provider = selected.providerName; channelId = selected.channel.id; } } if (!!provider && !!channelId) { controller.updateCurrentState(provider, channelId, source); controller.loadUi(); await setup(true, undefined); await manager.updateWebviewForProvider(provider, channelId); telemetry.record(EventType.viewOpened, source, channelId, provider); manager.loadChannelHistory(provider, channelId); } }; const onUIDispose = (provider: string | undefined, openSource: EventSource | undefined) => { }; const askForWorkspace = async (provider: string): Promise => { const currentUserInfo = manager.store.getCurrentUser(provider); if (!!currentUserInfo) { const { teams } = currentUserInfo; const labels = teams.map(team => team.name); const selected = await vscode.window.showQuickPick([...labels], { placeHolder: str.CHANGE_WORKSPACE_TITLE }); if (!!selected) { return teams.find(team => team.name === selected); } } }; const changeWorkspace = async (providerAndTeam?: any) => { let provider: string | undefined, team; if (!providerAndTeam) { const currentUsers = manager.store.getCurrentUserForAll(); const withMultipleTeams = currentUsers.filter(userInfo => userInfo.teams.length > 1); provider = await askForProvider(withMultipleTeams.map(userInfo => userInfo.provider)); if (!provider) { return; } const userInfo = withMultipleTeams.find(userInfo => userInfo.provider === provider); if (!!userInfo) { const teamNames = userInfo.teams.map(team => team.name); const selection = await vscode.window.showQuickPick(teamNames, { placeHolder: str.CHANGE_PROVIDER_TITLE }); if (selection) { team = userInfo.teams.find(team => team.name === selection); } } } else { provider = providerAndTeam.provider; team = providerAndTeam.team; } if (provider && team) { const isDifferentTeam = team.id !== manager.getCurrentTeamIdFor(provider); if (isDifferentTeam) { manager.updateCurrentWorkspace(provider, team); await manager.clearOldWorkspace(provider); await setup(false, { provider, teamId: team.id }); } } }; const changeChannel = async (args?: ChatArgs) => { const provider = args ? args.providerName : undefined; telemetry.record(EventType.channelChanged, !!args ? args.source : EventSource.command, undefined, provider); const selected = await askForChannel(provider); if (!!selected) { let chatArgs: any = { ...args }; chatArgs.channelId = selected.channel.id; chatArgs.providerName = selected.providerName; return openChatWebview(chatArgs); } }; const shareVslsLink = async (chatArgs: ChatArgs) => { // This method can assume chatArgs to have one of channel and user const { providerName } = chatArgs; const liveshare = await vsls.getApi(); if (!!liveshare) { const vslsUri = await liveshare.share({ suppressNotification: true }); let channelId = chatArgs.channelId; const user = chatArgs.user; if (!channelId && user) { const newChannel = await manager.createIMChannel(chatArgs.providerName, user); if (!!newChannel) { channelId = newChannel.id; } } telemetry.record(EventType.vslsShared, EventSource.activity, channelId, providerName); if (vslsUri && channelId) { manager.sendMessage(providerName, vslsUri.toString(), channelId, undefined); } } }; const startOAuth = (args?: any) => { const hasArgs = !!args && !!args.source; const provider = "slack"; // Only Slack OAuth is supported const urls = { slack: SLACK_OAUTH, discord: DISCORD_OAUTH }; telemetry.record(EventType.authStarted, hasArgs ? args.source : EventSource.command, undefined, provider); return utils.openUrl(urls[provider]); }; const reset = async () => { // Reset clears all state from local storage (except for vsls chat // related state, since that does not get affected via call paths to reset) manager.clearAll(); manager.updateAllUI(); await setup(false, undefined); }; const signout = async () => { await manager.signout(); }; const updateSelfPresence = async (provider: string, presence: UserPresence) => { const isSlack = provider === "slack"; let durationInMinutes = 0; if (presence === UserPresence.doNotDisturb && isSlack) { // Ask for duration for dnd.snooze for slack implementation const options: { [label: string]: number } = { "20 minutes": 20, "1 hour": 60, "2 hours": 120, "4 hours": 240, "8 hours": 480, "24 hours": 1440 }; const selected = await vscode.window.showQuickPick(Object.keys(options), { placeHolder: str.SELECT_DND_DURATION }); durationInMinutes = !!selected ? options[selected] : 0; } manager.updateSelfPresence(provider, presence, durationInMinutes); }; const askForSelfPresence = async () => { // Called when user triggers a change for self presence // using manual command. const enabledProviders = manager.getEnabledProviders(); const providerNames = enabledProviders.map(element => element.provider); const provider = providerNames.find(provider => provider !== "vsls"); if (!!provider) { const isSlack = provider === "slack"; const currentPresence = manager.getCurrentUserPresence(provider); const presenceChoices = [UserPresence.available, UserPresence.doNotDisturb, UserPresence.invisible]; if (!isSlack) { // Slack does not have the idle option presenceChoices.push(UserPresence.idle); } const items: vscode.QuickPickItem[] = presenceChoices.map(choice => { const isCurrent = currentPresence === choice; return { label: utils.camelCaseToTitle(choice), description: isCurrent ? "current" : "" }; }); const status = await vscode.window.showQuickPick(items, { placeHolder: str.SELECT_SELF_PRESENCE }); if (!!status) { const presence = utils.titleCaseToCamel(status.label) as UserPresence; updateSelfPresence(provider, presence); } } }; const fetchReplies = (provider: string, parentTimestamp: string) => { manager.fetchThreadReplies(provider, parentTimestamp); }; const resetConfiguration = (event: vscode.ConfigurationChangeEvent) => { const affectsExtension = event.affectsConfiguration(CONFIG_ROOT); if (affectsExtension) { // We can have a tighter check here to prevent losing slack/discord setup // whenever the config changes. const needsReset = !event.affectsConfiguration(CONFIG_AUTO_LAUNCH); if (needsReset) { reset(); } } }; const setVslsContext = () => { const isEnabled = utils.hasVslsExtension(); utils.setVsContext("chat:vslsEnabled", isEnabled); }; const askForProvider = async (enabledProviders: string[]) => { // VSLS providers are no longer supported. The user can still have these in their store. // Remove these from the list. const values = (enabledProviders.map(name => utils.toTitleCase(name))).filter(p => p !== 'Vsls'); const selection = await vscode.window.showQuickPick(values, { placeHolder: str.CHANGE_PROVIDER_TITLE }); return !!selection ? selection.toLowerCase() : undefined; }; const configureToken = async () => { const provider = await askForProvider(["slack", "discord"]); telemetry.record(EventType.tokenConfigured, EventSource.command, undefined, provider); if (!!provider) { const inputToken = await vscode.window.showInputBox({ placeHolder: str.TOKEN_PLACEHOLDER, password: true }); if (!!inputToken) { const sanitisedToken = utils.sanitiseTokenString(inputToken); try { const tokenUser = await manager.validateToken(provider, sanitisedToken); if (!!tokenUser) { const teamId = provider === "slack" ? tokenUser.currentTeamId : undefined; return ConfigHelper.setToken(sanitisedToken, provider, teamId); } } catch (error) { const actionItems = [str.REPORT_ISSUE]; const messageResult = await vscode.window.showErrorMessage( str.INVALID_TOKEN(utils.toTitleCase(provider)), ...actionItems ); if (!!messageResult && messageResult === str.REPORT_ISSUE) { const issue = `[${provider}] Invalid token`; IssueReporter.openNewIssue(issue, ""); } return; } } } }; const getContactFromItem = async (item: any) => { let contact: vsls.Contact | undefined; if (!!item.space) { // This is a space member, we need to convert to an LS contact const { email } = item; const api = (await vsls.getApi())!; const { contacts } = await api.getContacts([email]); contact = contacts[email]; } else { contact = item.contactModel.contact; } return contact; }; const openVslsSpaceChat = async (spaceName: string) => { const api = utils.getExtension(VSLS_SPACES_EXTENSION_ID)!.exports; const { name, email } = api.getUserInfo(); await manager.store.updateCurrentUser("vslsSpaces", { id: email, name, teams: [], currentTeamId: undefined, provider: Providers.vslsSpaces }); return openChatWebview({ providerName: "vslsSpaces", channelId: spaceName, source: EventSource.command }); }; // Setup real-time messenger and updated local state setup(true, undefined); // Setup context for conditional views setVslsContext(); const uriHandler = new ExtensionUriHandler(); context.subscriptions.push( vscode.commands.registerCommand(SelfCommands.OPEN_WEBVIEW, openChatWebview), vscode.commands.registerCommand(SelfCommands.CHANGE_WORKSPACE, changeWorkspace), vscode.commands.registerCommand(SelfCommands.CHANGE_CHANNEL, changeChannel), vscode.commands.registerCommand(SelfCommands.SIGN_IN, startOAuth), vscode.commands.registerCommand(SelfCommands.SIGN_OUT, signout), vscode.commands.registerCommand(SelfCommands.RESET_STORE, reset), vscode.commands.registerCommand(SelfCommands.SETUP_NEW_PROVIDER, ({ newInitialState }) => setup(false, newInitialState) ), vscode.commands.registerCommand(SelfCommands.CONFIGURE_TOKEN, configureToken), vscode.commands.registerCommand(SelfCommands.SEND_MESSAGE, ({ text, provider }) => sendMessage(provider, text, undefined) ), vscode.commands.registerCommand(SelfCommands.SEND_THREAD_REPLY, ({ text, parentTimestamp, provider }) => sendMessage(provider, text, parentTimestamp) ), vscode.commands.registerCommand(SelfCommands.LIVE_SHARE_FROM_MENU, (item: ChatTreeNode) => { return shareVslsLink({ channelId: item.channel ? item.channel.id : undefined, user: item.user, providerName: item.providerName, source: EventSource.activity }); }), vscode.commands.registerCommand(SelfCommands.LIVE_SHARE_SLASH, ({ provider }) => { const channelId = manager.store.getLastChannelId(provider); shareVslsLink({ channelId, user: undefined, providerName: provider, source: EventSource.slash }); }), vscode.commands.registerCommand( SelfCommands.LIVE_SHARE_SESSION_CHANGED, async ({ isSessionActive, currentUser }) => { if (!currentUser) { // If the currentUser is undefined, don't launch the window return; } const enabledProviders = manager.getEnabledProviders().map(e => e.provider); const eventType = isSessionActive ? EventType.vslsStarted : EventType.vslsEnded; telemetry.record(eventType, undefined, undefined, undefined); } ), vscode.commands.registerCommand(SelfCommands.FETCH_REPLIES, ({ parentTimestamp, provider }) => fetchReplies(provider, parentTimestamp) ), vscode.commands.registerCommand(SelfCommands.UPDATE_MESSAGES, ({ channelId, messages, provider }) => { manager.updateMessages(provider, channelId, messages); }), vscode.commands.registerCommand(SelfCommands.CLEAR_MESSAGES, ({ channelId, provider }) => { manager.clearMessages(provider, channelId); }), vscode.commands.registerCommand( SelfCommands.ADD_MESSAGE_REACTION, ({ userId, msgTimestamp, channelId, reactionName, provider }) => { manager.addReaction(provider, channelId, msgTimestamp, userId, reactionName); } ), vscode.commands.registerCommand( SelfCommands.REMOVE_MESSAGE_REACTION, ({ userId, msgTimestamp, channelId, reactionName, provider }) => { manager.removeReaction(provider, channelId, msgTimestamp, userId, reactionName); } ), vscode.commands.registerCommand(SelfCommands.UPDATE_PRESENCE_STATUSES, ({ userId, presence, provider }) => { manager.updatePresenceForUser(provider, userId, presence); }), vscode.commands.registerCommand(SelfCommands.UPDATE_SELF_PRESENCE, askForSelfPresence), vscode.commands.registerCommand(SelfCommands.UPDATE_SELF_PRESENCE_VIA_VSLS, ({ presence, provider }) => { // Disabled to test auto-away fix // updateSelfPresence(provider, presence) }), vscode.commands.registerCommand( SelfCommands.CHANNEL_MARKED, ({ channelId, readTimestamp, unreadCount, provider }) => { return manager.updateChannelMarked(provider, channelId, readTimestamp, unreadCount); } ), vscode.commands.registerCommand( SelfCommands.UPDATE_MESSAGE_REPLIES, ({ provider, channelId, parentTimestamp, reply }) => { manager.updateMessageReply(provider, parentTimestamp, channelId, reply); } ), vscode.commands.registerCommand(SelfCommands.SHOW_TYPING, ({ provider, typingUserId, channelId }) => { manager.updateWebviewForProvider(provider, channelId, typingUserId); const key = `${channelId}:${typingUserId}`; if (typingTimers[key]) { clearTimeout(typingTimers[key] as NodeJS.Timer); typingTimers[key] = undefined; } const newTimer = setTimeout(() => { // This removes typing status --> this timeout should be larger than // the time period between typing events sent from the wire + the time // it takes to transfer them over the wire. manager.updateWebviewForProvider(provider, channelId, undefined); }, 5000); typingTimers[key] = newTimer; }), vscode.commands.registerCommand(SelfCommands.SEND_TO_WEBVIEW, ({ uiMessage }) => controller.sendToUI(uiMessage) ), vscode.commands.registerCommand(SelfCommands.CHAT_WITH_VSLS_SPACE, ({ space }) => { const { name: spaceName } = space; return openVslsSpaceChat(spaceName); }), vscode.commands.registerCommand(SelfCommands.VSLS_SPACE_JOINED, async ({ name }) => { // Update store and launch the webview await manager.fetchUsers("vslsSpaces"); await manager.fetchChannels("vslsSpaces"); return openVslsSpaceChat(name); }), vscode.workspace.onDidChangeConfiguration(resetConfiguration), vscode.workspace.registerTextDocumentContentProvider(TRAVIS_SCHEME, travis), vscode.window.registerUriHandler(uriHandler), manager, telemetry ); // telemetry.record( // EventType.activationEnded, // undefined, // undefined, // undefined // ); } export function deactivate() {} ================================================ FILE: src/issues.ts ================================================ import { openUrl, getVersions } from "./utils"; const BASE_ISSUES_URL = "https://github.com/karigari/vscode-chat/issues/new"; export default class IssueReporter { static getVersionString() { const { extension, os, editor } = getVersions(); return `- Extension Version: ${extension}\n- OS Version: ${os}\n- VSCode version: ${editor}`; } static getUrl(query: object) { const getParams = (p: object) => Object.entries(p) .map(kv => kv.map(encodeURIComponent).join("=")) .join("&"); return `${BASE_ISSUES_URL}?${getParams(query)}`; } static openNewIssue(title: string, body: string) { const versions = this.getVersionString(); const bodyText = `${body}\n\n${versions}`.replace(/\n/g, "%0A"); const params = { title: `[vscode] ${title}`, body: bodyText }; return openUrl(this.getUrl(params)); } } ================================================ FILE: src/logger.ts ================================================ import * as vscode from "vscode"; import { OUTPUT_CHANNEL_NAME } from "./constants"; export default class Logger { static output: vscode.OutputChannel | undefined; static setup() { this.output = this.output || vscode.window.createOutputChannel(OUTPUT_CHANNEL_NAME); } private static get timestamp(): string { const now = new Date(); return now.toLocaleString(); } private static logOnConsole(message: string): void { console.log(message); } private static logOnOutput(message: string): void { if (this.output === undefined) { this.setup(); } if (!!this.output) { this.output.appendLine(message); } } static log(message: any): void { const logLine = `[${this.timestamp}] Chat: ${message}`; return process.env.IS_DEBUG === "true" ? this.logOnConsole(logLine) : this.logOnOutput(logLine); } } ================================================ FILE: src/manager/chatManager.ts ================================================ import { isSuperset, difference, toTitleCase } from "../utils"; export class ChatProviderManager { messages: Messages = {}; currentUserPrefs: UserPreferences = {}; stateFetchedAt: Date | undefined; constructor( private store: IStore, public providerName: string, public teamId: string | undefined, private chatProvider: IChatProvider, private parentManager: IManager ) {} getTeams(): Team[] { // Due to design limitation we can only work with one team at a time, // and so this only returns the current team. (or else, Discord shows // multiple status items for unread messages.) const currentTeam = this.getCurrentTeam(); return !!currentTeam ? [currentTeam] : []; } getCurrentTeam(): Team | undefined { const currentUser = this.store.getCurrentUser(this.providerName); return !!currentUser ? currentUser.teams.find(team => team.id === currentUser.currentTeamId) : undefined; } initializeProvider = async (): Promise => { const isConnected = this.chatProvider.isConnected(); const isAuthenticated = this.isAuthenticated(); let currentUser = this.store.getCurrentUser(this.providerName); if (!(isConnected && isAuthenticated)) { if (!!this.chatProvider) { currentUser = await this.chatProvider.connect(); this.store.updateCurrentUser(this.providerName, currentUser); } } return currentUser; }; isAuthenticated() { const currentUserInfo = this.store.getCurrentUser(this.providerName); return !!currentUserInfo && !!currentUserInfo.id; } destroy() { this.chatProvider.destroy(); } updateWebviewForLastChannel() { const lastChannelId = this.store.getLastChannelId(this.providerName); if (!!lastChannelId) { this.parentManager.updateWebviewForProvider(this.providerName, lastChannelId); } } async fetchThreadReplies(parentTimestamp: string) { const currentChannelId = this.store.getLastChannelId(this.providerName); if (!!currentChannelId) { const message = await this.chatProvider.fetchThreadReplies(currentChannelId, parentTimestamp); if (!!message) { let messages: ChannelMessages = {}; messages[parentTimestamp] = message; this.updateMessages(currentChannelId, messages); } } } updateSelfPresence = async (presence: UserPresence, durationInMinutes: number) => { const currentUserInfo = this.store.getCurrentUser(this.providerName); if (!!currentUserInfo) { const presenceResult = await this.chatProvider.updateSelfPresence(presence, durationInMinutes); if (!!presenceResult) { this.updatePresenceForUser(currentUserInfo.id, presenceResult); } } }; updatePresenceForUser = (userId: string, presence: UserPresence) => { const users = this.store.getUsers(this.providerName); if (userId in users) { const existingPresence = users[userId].presence; if (existingPresence === UserPresence.invisible && presence === UserPresence.offline) { // If we know user is `invisible`, then `offline` presence change // should be ignored. This will only happen for self. return; } this.store.updateUser(this.providerName, userId, { ...users[userId], presence }); if (presence !== existingPresence) { this.parentManager.updateTreeViewsForProvider(this.providerName); } } }; sendMessage = (text: string, channelId: string, parentTimestamp: string | undefined): Promise => { const currentUserInfo = this.store.getCurrentUser(this.providerName); if (!!currentUserInfo) { if (!!parentTimestamp) { // This is a thread reply return this.chatProvider.sendThreadReply(text, currentUserInfo.id, channelId, parentTimestamp); } else { // THis is a normal message return this.chatProvider.sendMessage(text, currentUserInfo.id, channelId); } } return Promise.resolve(); }; clearMessages = (channelId: string) => { const existingMessages = channelId in this.messages ? this.messages[channelId] : {}; const deletedMessages: any = {}; Object.keys(existingMessages).forEach((ts: string) => { deletedMessages[ts] = undefined; }); return this.updateMessages(channelId, deletedMessages); }; updateMessages = (channelId: string, messages: ChannelMessagesWithUndefined) => { const existingMessages = channelId in this.messages ? this.messages[channelId] : {}; const deletedTimestamps = Object.keys(messages).filter(ts => typeof messages[ts] === "undefined"); const newMessages: ChannelMessages = {}; Object.keys(existingMessages).forEach(ts => { const isDeleted = deletedTimestamps.indexOf(ts) >= 0; if (!isDeleted) { newMessages[ts] = existingMessages[ts]; } }); Object.keys(messages).forEach(ts => { const message = messages[ts]; if (!!message) { newMessages[ts] = message; } }); this.messages[channelId] = newMessages; // Remove undefined, after message deleted Object.keys(this.messages[channelId]).forEach(key => { if (typeof this.messages[channelId][key] === "undefined") { delete this.messages[channelId][key]; } }); // Check if we have all users. Since there is no `bots.list` Slack API // method, it is possible that a bot user is not in our store const users = this.store.getUsers(this.providerName); const knownUserIds = new Set(Object.keys(users)); const channelMessages = this.messages[channelId]; const entries = Object.entries(channelMessages); const userIds = new Set(entries.map(([_, message]) => message.userId)); if (!isSuperset(knownUserIds, userIds)) { this.fillUpUsers(difference(userIds, knownUserIds)); } this.updateWebviewForLastChannel(); this.parentManager.updateStatusItemsForProvider(this.providerName); this.parentManager.updateTreeViewsForProvider(this.providerName); }; sendTyping = (channelId: string) => { const currentUser = this.store.getCurrentUser(this.providerName); if (currentUser) { return this.chatProvider.sendTyping(currentUser.id, channelId) } }; private async fillUpUsers(missingIds: Set): Promise { // missingIds are user/bot ids that we don't have in the store. We will // fetch their details, and then update the UI. const users = this.store.getUsers(this.providerName); const usersCopy: Users = { ...users }; let ids = Array.from(missingIds); await Promise.all( ids.map(async userId => { let user = await this.chatProvider.fetchUserInfo(userId); if (!!user) { const { id } = user; usersCopy[id] = user; } }) ); this.store.updateUsers(this.providerName, usersCopy); this.updateWebviewForLastChannel(); } updateMessageReply(parentTimestamp: string, channelId: string, reply: MessageReply) { // We need to have the message in our store, else we // ignore this reply const messages = channelId in this.messages ? this.messages[channelId] : {}; const message = parentTimestamp in messages ? messages[parentTimestamp] : undefined; if (!!message) { let newMessages: ChannelMessages = {}; const replyTs = reply.timestamp; let replies: MessageReplies = { ...message.replies }; replies[replyTs] = { ...reply }; newMessages[parentTimestamp] = { ...message, replies }; this.updateMessages(channelId, newMessages); } } removeReaction(channelId: string, msgTimestamp: string, userId: string, reactionName: string) { if (channelId in this.messages) { const channelMessages = this.messages[channelId]; if (msgTimestamp in channelMessages) { const message = channelMessages[msgTimestamp]; let { reactions } = message; reactions = reactions .map(r => { if (r.name === reactionName) { return { ...r, count: r.count - 1, userIds: r.userIds.filter(u => u !== userId) }; } else { return { ...r }; } }) .filter(r => r.count > 0); const newMessage = { ...message, reactions }; const newMessages: ChannelMessages = {}; newMessages[msgTimestamp] = newMessage; this.updateMessages(channelId, newMessages); } } } addReaction(channelId: string, msgTimestamp: string, userId: string, reactionName: string) { if (channelId in this.messages) { const channelMessages = this.messages[channelId]; if (msgTimestamp in channelMessages) { const message = channelMessages[msgTimestamp]; let { reactions } = message; const existing = reactions.find(r => r.name === reactionName); if (existing) { reactions = reactions.map(r => { if (r.name === reactionName) { return { ...existing, count: existing.count + 1, userIds: [...existing.userIds, userId] }; } else { return { ...r }; } }); } else { reactions = [...reactions, { name: reactionName, userIds: [userId], count: 1 }]; } const newMessage = { ...message, reactions }; const newMessages: ChannelMessages = {}; newMessages[msgTimestamp] = newMessage; this.updateMessages(channelId, newMessages); } } } async loadChannelHistory(channelId: string): Promise { try { const messages = await this.chatProvider.loadChannelHistory(channelId); return this.updateMessages(channelId, messages); } catch (error) { return console.error(error); } } async updateUserPrefs() { const response = await this.chatProvider.getUserPreferences(); if (!!response) { // We could also save the muted channels to local storage this.currentUserPrefs = response; this.parentManager.updateStatusItemsForProvider(this.providerName); } } async createIMChannel(user: User): Promise { const channel = await this.chatProvider.createIMChannel(user); if (!!channel) { await this.updateChannel(channel); return channel; } } subscribeForPresence() { const users = this.store.getUsers(this.providerName); if (!!this.chatProvider) { this.chatProvider.subscribePresence(users); } } updateChannel = async (newChannel: Channel) => { // Adds/updates channel in this.channels let found = false; const channels = this.store.getChannels(this.providerName); let updatedChannels = channels.map(channel => { const { id } = channel; if (id === newChannel.id) { found = true; return { ...channel, ...newChannel }; } else { return channel; } }); if (!found) { updatedChannels = [...updatedChannels, newChannel]; } await this.store.updateChannels(this.providerName, updatedChannels); this.parentManager.updateTreeViewsForProvider(this.providerName); }; updateChannelMarked(channelId: string, readTimestamp: string, unreadCount: number) { const channel = this.getChannel(channelId); if (!!channel) { this.updateChannel({ ...channel, readTimestamp, unreadCount }); this.updateWebviewForLastChannel(); this.parentManager.updateStatusItemsForProvider(this.providerName); this.parentManager.updateTreeViewsForProvider(this.providerName); } } fetchUnreadCounts = async (channels: Channel[]) => { // We have to fetch twice here because Slack does not return the // historical unread counts for channels in the list API. const promises = channels.map(async channel => { const newChannel = await this.chatProvider.fetchChannelInfo(channel); if (!!newChannel && newChannel.unreadCount !== channel.unreadCount) { return this.updateChannel(newChannel); } }); await Promise.all(promises); this.parentManager.updateStatusItemsForProvider(this.providerName); }; fetchUsers = async (): Promise => { const users = await this.chatProvider.fetchUsers(); let usersWithPresence: Users = {}; const existingUsers = this.store.getUsers(this.providerName); Object.keys(users).forEach(userId => { // This handles two different chat providers: // In slack, we will get isOnline as undefined, because this API // does not know about user presence // In discord, we will get true/false const existingUser = userId in existingUsers ? existingUsers[userId] : null; const newUser = users[userId]; let calculatedPresence: UserPresence; if (newUser.presence !== UserPresence.unknown) { calculatedPresence = newUser.presence; } else { calculatedPresence = !!existingUser ? existingUser.presence : UserPresence.unknown; } usersWithPresence[userId] = { ...users[userId], presence: calculatedPresence }; }); this.store.updateUsers(this.providerName, usersWithPresence); return usersWithPresence; }; fetchChannels = async (): Promise => { const users = this.store.getUsers(this.providerName); const channels = await this.chatProvider.fetchChannels(users); await this.store.updateChannels(this.providerName, channels); this.parentManager.updateTreeViewsForProvider(this.providerName); this.fetchUnreadCounts(channels); return channels; }; private shouldFetchNew = (lastFetchedAt: Date | undefined): boolean => { if (!lastFetchedAt) { return true; } const now = new Date(); const difference = now.valueOf() - lastFetchedAt.valueOf(); const FETCH_THRESHOLD = 15 * 60 * 1000; // 15-mins return difference > FETCH_THRESHOLD; }; async initializeState(): Promise { const users = this.store.getUsers(this.providerName); const hasCachedUsers = Object.keys(users).length !== 0; if (!hasCachedUsers) { await this.fetchUsers(); const channels = this.store.getChannels(this.providerName); const hasCachedChannels = channels.length !== 0; if (!hasCachedChannels) { await this.fetchChannels(); this.stateFetchedAt = new Date(); } return; } // We already have a copy of the state, but if it's old, we run an async update if (this.shouldFetchNew(this.stateFetchedAt)) { this.fetchUsers().then(users => { this.fetchChannels(); this.stateFetchedAt = new Date(); }); } } getChannel(channelId: string | undefined): Channel | undefined { if (!!channelId) { const channels = this.store.getChannels(this.providerName); return channels.find(channel => channel.id === channelId); } } getLastTimestamp(): string | undefined { const channelId = this.store.getLastChannelId(this.providerName); const channelMessages = !!channelId && channelId in this.messages ? this.messages[channelId] : {}; const timestamps = Object.keys(channelMessages).map(tsString => +tsString); if (timestamps.length > 0) { return Math.max(...timestamps).toString(); } } async updateReadMarker(): Promise { const channelId = this.store.getLastChannelId(this.providerName); const channel = this.getChannel(channelId); const lastTs = this.getLastTimestamp(); if (channel && lastTs) { const { readTimestamp } = channel; const hasNewerMsgs = !!readTimestamp ? +readTimestamp < +lastTs : true; if (hasNewerMsgs) { const incremented = (+lastTs + 1).toString(); // Slack API workaround const updatedChannel = await this.chatProvider.markChannel(channel, incremented); if (!!updatedChannel) { this.updateChannel(updatedChannel); this.updateWebviewForLastChannel(); this.parentManager.updateStatusItemsForProvider(this.providerName); this.parentManager.updateTreeViewsForProvider(this.providerName); } } } } private isChannelMuted(channelId: string): boolean { const { mutedChannels } = this.currentUserPrefs; return !!mutedChannels && mutedChannels.indexOf(channelId) >= 0; } getUnreadCount(channel: Channel): number { const { id, readTimestamp, unreadCount } = channel; if (this.isChannelMuted(id)) { // This channel is muted, so return 0 return 0; } const currentUserInfo = this.store.getCurrentUser(this.providerName); if (!currentUserInfo) { // Can be undefined during async update on vsls chat return 0; } const messages = id in this.messages ? this.messages[id] : {}; const unreadMessages = Object.keys(messages).filter(ts => { const isDifferentUser = messages[ts].userId !== currentUserInfo.id; const isNewTimestamp = !!readTimestamp ? +ts > +readTimestamp : false; return isDifferentUser && isNewTimestamp; }); return unreadCount ? unreadCount : unreadMessages.length; } getChannelLabels(): ChannelLabel[] { const channels = this.store.getChannels(this.providerName); const users = this.store.getUsers(this.providerName); const providerName = toTitleCase(this.providerName); const currentTeam = this.getCurrentTeam(); const teamName = !!currentTeam ? currentTeam.name : ""; return channels.map(channel => { const unread = this.getUnreadCount(channel); const { name, type, id } = channel; const isMuted = this.isChannelMuted(id); let presence: UserPresence = UserPresence.unknown; if (type === ChannelType.im) { const relatedUserId = Object.keys(users).find(value => { const user = users[value]; const { name: username } = user; // Same issue as getIMChannel(), so we handle both return `@${username}` === name || username === name; }); if (!!relatedUserId) { const relatedUser = users[relatedUserId]; presence = relatedUser.presence; } } let label; if (unread > 0) { label = `${name} ${unread > 0 ? `(${unread} new)` : ""}`; } else if (isMuted) { label = `${name} (muted)`; } else { label = `${name}`; } return { channel, unread, label, presence, providerName, teamName }; }); } getUserPresence(userId: string) { const user = this.store.getUser(this.providerName, userId); return !!user ? user.presence : undefined; } getCurrentUserPresence = () => { const currentUser = this.store.getCurrentUser(this.providerName); return !!currentUser ? this.getUserPresence(currentUser.id) : undefined; }; } ================================================ FILE: src/manager/index.ts ================================================ import * as vscode from "vscode"; import { hasVslsSpacesExtension } from "../utils"; import { DiscordChatProvider } from "../discord"; import { SlackChatProvider } from "../slack"; import { ViewsManager } from "./views"; import { ConfigHelper } from "../config"; import { ChatProviderManager } from "./chatManager"; import { SelfCommands } from "../constants"; import { VslsSpacesProvider } from "../vslsSpaces"; export default class Manager implements IManager, vscode.Disposable { isTokenInitialized: boolean = false; viewsManager: ViewsManager; chatProviders = new Map(); constructor(public store: IStore) { this.viewsManager = new ViewsManager(this); } getEnabledProviders(newInitialState?: InitialState): InitialState[] { // if newInitialState is specified, enabled list must include it let currentUserInfos = this.store.getCurrentUserForAll(); let providerTeamIds: { [provider: string]: string | undefined } = {}; currentUserInfos.forEach(currentUser => { const { provider } = currentUser; if (provider !== "vslsSpaces") { // This provider is dependent on installed extensions, not the user state providerTeamIds[currentUser.provider] = currentUser.currentTeamId; } }); const hasVslsSpaces = hasVslsSpacesExtension(); if (hasVslsSpaces) { providerTeamIds[Providers.vslsSpaces] = undefined; } if (!!newInitialState) { providerTeamIds[newInitialState.provider] = newInitialState.teamId; } if (!!providerTeamIds[Providers.discord]) { providerTeamIds[Providers.discord] = undefined; } return Object.keys(providerTeamIds).map(provider => ({ provider, teamId: providerTeamIds[provider] })); } isProviderEnabled(provider: string): boolean { const cp = this.chatProviders.get(provider as Providers); return !!cp; } getCurrentTeamIdFor(provider: string) { const currentUser = this.store.getCurrentUser(provider); return !!currentUser ? currentUser.currentTeamId : undefined; } getCurrentUserFor(provider: string) { return this.store.getCurrentUser(provider); } getChatProvider(providerName: Providers) { return this.chatProviders.get(providerName); } instantiateChatProvider(token: string, provider: string): IChatProvider { switch (provider) { case "discord": return new DiscordChatProvider(token, this); case "slack": return new SlackChatProvider(token, this); case "vslsSpaces": return new VslsSpacesProvider(); default: throw new Error(`unsupport chat provider: ${provider}`); } } async validateToken(provider: string, token: string) { const chatProvider = this.instantiateChatProvider(token, provider); const currentUser = await chatProvider.validateToken(); return currentUser; } isAuthenticated(providerName: string | undefined): boolean { const cp = this.chatProviders.get(providerName as Providers); return !!cp ? cp.isAuthenticated() : false; } migrateTokenForSlack = async (teamId: string) => { // Migration for 0.10.x const teamToken = await ConfigHelper.getToken("slack", teamId); if (!teamToken) { const slackToken = await ConfigHelper.getToken("slack"); if (!!slackToken) { await ConfigHelper.setToken(slackToken, "slack", teamId); await ConfigHelper.clearToken("slack"); } } }; initializeToken = async (newInitialState?: InitialState) => { let enabledProviderStates = this.getEnabledProviders(newInitialState); if (Object.keys(enabledProviderStates).length === 0) { // Do this to ensure we load vsls, need to delay for vscode.getExtension // to work properly right after installation (and no restart). const delay = (ms: number) => new Promise(res => setTimeout(res, ms)); await delay(5 * 1000); enabledProviderStates = this.getEnabledProviders(newInitialState); } for (const initialState of enabledProviderStates) { const { provider: stateProvider, teamId } = initialState; const provider = stateProvider as Providers; if (!!provider) { if (provider === Providers.slack && !!teamId) { this.migrateTokenForSlack(teamId); } const token = await ConfigHelper.getToken(provider, teamId); if (!!token) { const existingProvider = this.chatProviders.get(provider); if (!existingProvider || existingProvider.teamId !== teamId) { const chatProvider = this.instantiateChatProvider(token, provider); const chatManager = new ChatProviderManager(this.store, provider, teamId, chatProvider, this); this.chatProviders.set(provider, chatManager); } this.isTokenInitialized = true; } } } this.initializeViewsManager(); }; initializeViewsManager = () => { const enabledProviders = Array.from(this.chatProviders.keys()); let providerTeams: { [provider: string]: Team[] } = {}; enabledProviders.forEach(provider => { const chatProvider = this.chatProviders.get(provider); if (!!chatProvider) { providerTeams[provider] = chatProvider.getTeams(); } }); this.viewsManager.initialize(enabledProviders, providerTeams); }; initializeProviders = async (): Promise => { for (let entry of Array.from(this.chatProviders.entries())) { let chatProvider = entry[1]; try { await chatProvider.initializeProvider(); } catch (err) { // try-catch will save vsls in case vslsSpaces crashes because // it cannot find exports for the vslsSpaces extension. console.log(err); } } }; async initializeStateForAll() { for (let entry of Array.from(this.chatProviders.entries())) { let chatProvider = entry[1]; await chatProvider.initializeState(); } } subscribePresenceForAll() { for (let entry of Array.from(this.chatProviders.entries())) { let chatProvider = entry[1]; chatProvider.subscribeForPresence(); } } async updateUserPrefsForAll() { for (let entry of Array.from(this.chatProviders.entries())) { let chatProvider = entry[1]; await chatProvider.updateUserPrefs(); } } async signout() { // This will sign out of slack and discord. vsls depends only on whether // the vsls extension has been installed. let hasSignedOut = false; for (let entry of Array.from(this.chatProviders.entries())) { let providerName = entry[0]; await ConfigHelper.clearToken(providerName); hasSignedOut = true; } if (hasSignedOut) { // When token state is cleared, we need to call reset vscode.commands.executeCommand(SelfCommands.RESET_STORE, { newProvider: undefined }); } } clearAll() { // This method clears local storage for slack/discord, but not vsls const enabledProviders = Array.from(this.chatProviders.keys()); enabledProviders.forEach(provider => { this.store.clearProviderState(provider); const chatProvider = this.chatProviders.get(provider); if (!!chatProvider) { chatProvider.destroy(); this.chatProviders.delete(provider); } }); this.isTokenInitialized = false; } async clearOldWorkspace(provider: string) { // Clears users and channels so that we are loading them again await this.store.updateUsers(provider, {}); await this.store.updateChannels(provider, []); await this.store.updateLastChannelId(provider, undefined); } async updateWebviewForProvider(provider: string, channelId: string, typingUserId?: string) { const currentUser = this.store.getCurrentUser(provider); const channels = this.store.getChannels(provider); const channel = channels.find(channel => channel.id === channelId); if (!!currentUser && !!channel) { await this.store.updateLastChannelId(provider, channelId); const users = this.store.getUsers(provider); const allMessages = this.getMessages(provider); const messages = allMessages[channel.id] || {}; let typingUser: User | undefined; if (typingUserId) { typingUser = users[typingUserId]; } this.viewsManager.updateWebview(currentUser, provider, users, channel, messages, typingUser); } } updateStatusItemsForProvider(provider: string) { const cp = this.chatProviders.get(provider as Providers); if (!!cp) { const teams = cp.getTeams(); teams.forEach(team => { this.viewsManager.updateStatusItem(provider, team); }); } } updateTreeViewsForProvider(provider: string) { this.viewsManager.updateTreeViews(provider); } updateAllUI() { const providers = Array.from(this.chatProviders.keys()); providers.forEach(provider => { const lastChannelId = this.store.getLastChannelId(provider); if (!!lastChannelId) { this.updateWebviewForProvider(provider, lastChannelId); } this.updateStatusItemsForProvider(provider); this.updateTreeViewsForProvider(provider); }); } dispose() { this.viewsManager.dispose(); } getChannelLabels(provider: string | undefined): ChannelLabel[] { // Return channel labels from all providers if input provider is undefined let channelLabels: ChannelLabel[] = []; for (let entry of Array.from(this.chatProviders.entries())) { const cp = entry[1]; const providerName = entry[0]; if (!provider || provider === providerName) { channelLabels = [...channelLabels, ...cp.getChannelLabels()]; } } return channelLabels; } getUserForId(provider: string, userId: string) { const cachedUser = this.store.getUser(provider, userId); return cachedUser; } getIMChannel(provider: string, user: User): Channel | undefined { // DM channels look like `name` const channels = this.store.getChannels(provider); const { name } = user; return channels.find(channel => channel.name === name); } async createIMChannel(providerName: string, user: User): Promise { const cp = this.chatProviders.get(providerName as Providers); return !!cp ? await cp.createIMChannel(user) : undefined; } getUserPresence(provider: string, userId: string) { const cp = this.chatProviders.get(provider as Providers); return !!cp ? cp.getUserPresence(userId) : undefined; } getCurrentUserPresence = (provider: string) => { const cp = this.chatProviders.get(provider as Providers); return !!cp ? cp.getCurrentUserPresence() : undefined; }; updateCurrentWorkspace = async (provider: string, team: Team): Promise => { const existingUserInfo = this.getCurrentUserFor(provider); if (!!existingUserInfo) { const newCurrentUser: CurrentUser = { ...existingUserInfo, currentTeamId: team.id }; return this.store.updateCurrentUser(provider, newCurrentUser); } }; async loadChannelHistory(providerName: string, channelId: string): Promise { const cp = this.chatProviders.get(providerName as Providers); return !!cp ? cp.loadChannelHistory(channelId) : undefined; } async updateReadMarker(providerName: string): Promise { const cp = this.chatProviders.get(providerName as Providers); return !!cp ? cp.updateReadMarker() : undefined; } sendMessage = async ( providerName: string, text: string, channelId: string, parentTimestamp: string | undefined ): Promise => { const cp = this.chatProviders.get(providerName as Providers); return !!cp ? cp.sendMessage(text, channelId, parentTimestamp) : undefined; }; updateSelfPresence = async (providerName: string, presence: UserPresence, durationInMinutes: number) => { const cp = this.chatProviders.get(providerName as Providers); return !!cp ? cp.updateSelfPresence(presence, durationInMinutes) : undefined; }; addReaction(providerName: string, channelId: string, msgTimestamp: string, userId: string, reactionName: string) { const cp = this.chatProviders.get(providerName as Providers); return !!cp ? cp.addReaction(channelId, msgTimestamp, userId, reactionName) : undefined; } removeReaction( providerName: string, channelId: string, msgTimestamp: string, userId: string, reactionName: string ) { const cp = this.chatProviders.get(providerName as Providers); return !!cp ? cp.removeReaction(channelId, msgTimestamp, userId, reactionName) : undefined; } async fetchThreadReplies(providerName: string, parentTimestamp: string) { const cp = this.chatProviders.get(providerName as Providers); return !!cp ? cp.fetchThreadReplies(parentTimestamp) : undefined; } updateMessageReply(providerName: string, parentTimestamp: string, channelId: string, reply: MessageReply) { const cp = this.chatProviders.get(providerName as Providers); return !!cp ? cp.updateMessageReply(parentTimestamp, channelId, reply) : undefined; } updateMessages(providerName: string, channelId: string, messages: ChannelMessagesWithUndefined) { const cp = this.chatProviders.get(providerName as Providers); return !!cp ? cp.updateMessages(channelId, messages) : undefined; } clearMessages(providerName: string, channelId: string) { const cp = this.chatProviders.get(providerName as Providers); return !!cp ? cp.clearMessages(channelId) : undefined; } updateChannelMarked(provider: string, channelId: string, readTimestamp: string, unreadCount: number) { const cp = this.chatProviders.get(provider as Providers); return !!cp ? cp.updateChannelMarked(channelId, readTimestamp, unreadCount) : undefined; } updatePresenceForUser = (providerName: string, userId: string, presence: UserPresence) => { const cp = this.chatProviders.get(providerName as Providers); return !!cp ? cp.updatePresenceForUser(userId, presence) : undefined; }; getChannel = (provider: string, channelId: string | undefined): Channel | undefined => { const cp = this.chatProviders.get(provider as Providers); return !!cp ? cp.getChannel(channelId) : undefined; }; fetchUsers = (providerName: string) => { const cp = this.chatProviders.get(providerName as Providers); return !!cp ? cp.fetchUsers() : undefined; }; fetchChannels = (providerName: string) => { const cp = this.chatProviders.get(providerName as Providers); return !!cp ? cp.fetchChannels() : undefined; }; getMessages = (providerName: string): Messages => { const cp = this.chatProviders.get(providerName as Providers); return !!cp ? cp.messages : {}; }; getUnreadCount = (provider: string, channel: Channel) => { const cp = this.chatProviders.get(provider as Providers); return !!cp ? cp.getUnreadCount(channel) : 0; }; } ================================================ FILE: src/manager/treeView.ts ================================================ import * as vscode from "vscode"; import { WorkspacesTreeProvider, UnreadsTreeProvider, ChannelTreeProvider, GroupTreeProvider, IMsTreeProvider } from "../tree"; export class TreeViewManager implements vscode.Disposable { workspacesTreeProvider: WorkspacesTreeProvider; unreadsTreeProvider: UnreadsTreeProvider; channelsTreeProvider: ChannelTreeProvider; imsTreeProvider: IMsTreeProvider; groupsTreeProvider: GroupTreeProvider; constructor(public provider: string) { this.workspacesTreeProvider = new WorkspacesTreeProvider(provider); this.unreadsTreeProvider = new UnreadsTreeProvider(provider); this.channelsTreeProvider = new ChannelTreeProvider(provider); this.groupsTreeProvider = new GroupTreeProvider(provider); this.imsTreeProvider = new IMsTreeProvider(provider); } updateData(currentUserInfo: CurrentUser, channelLabels: ChannelLabel[]) { this.workspacesTreeProvider.updateCurrentUser(currentUserInfo); this.unreadsTreeProvider.updateChannels(channelLabels); this.channelsTreeProvider.updateChannels(channelLabels); this.groupsTreeProvider.updateChannels(channelLabels); this.imsTreeProvider.updateChannels(channelLabels); } dispose() { this.workspacesTreeProvider.dispose(); this.unreadsTreeProvider.dispose(); this.channelsTreeProvider.dispose(); this.groupsTreeProvider.dispose(); this.imsTreeProvider.dispose(); } } ================================================ FILE: src/manager/views.ts ================================================ import * as vscode from "vscode"; import { TreeViewManager } from "./treeView"; import { BaseStatusItem, UnreadsStatusItem } from "../status"; import { OnboardingTreeProvider } from "../onboarding"; import { SelfCommands } from "../constants"; import { setVsContext, difference } from "../utils"; const PROVIDERS_WITH_TREE = ["slack", "discord"]; const getStatusItemKey = (provider: string, team: Team) => { return `${provider}:${team.id}`; }; export class ViewsManager implements vscode.Disposable { statusItems: Map = new Map(); treeViews: Map = new Map(); onboardingTree: OnboardingTreeProvider | undefined; constructor(private parentManager: IManager) {} initialize(enabledProviders: string[], providerTeams: { [providerName: string]: Team[] }) { const statusItemKeys = new Map(); enabledProviders.forEach(provider => { const teams = providerTeams[provider]; teams.forEach(team => { statusItemKeys.set(getStatusItemKey(provider, team), { provider, team }); }); }); this.initializeStatusItems(statusItemKeys); this.initializeTreeViews(enabledProviders); const showOnboarding = false; // Overriding showOnboarding to be always false, so that vsls extension // pack users don't see a slack icon in the activity bar. // const showOnboarding = nonVslsProviders.length === 0; if (showOnboarding && !this.onboardingTree) { // We need to initialize the tree here this.onboardingTree = new OnboardingTreeProvider(); } else if (!showOnboarding && !!this.onboardingTree) { // Dispose the tree as we don't need it anymore this.onboardingTree.dispose(); this.onboardingTree = undefined; } } initializeStatusItems(newKeyMap: Map) { // Ensure new keys have status items in the map and // no longer used keys are removed. const existingKeysSet = new Set(Array.from(this.statusItems.keys())); const newKeysSet = new Set(Array.from(newKeyMap.keys())); const keysToRemove = difference(existingKeysSet, newKeysSet); const keysToAdd = difference(newKeysSet, existingKeysSet); keysToRemove.forEach(key => { const statusItem = this.statusItems.get(key); if (!!statusItem) { statusItem.dispose(); this.statusItems.delete(key); } }); keysToAdd.forEach(key => { const providerAndTeam = newKeyMap.get(key); if (!!providerAndTeam) { const { provider, team } = providerAndTeam; this.statusItems.set(key, new UnreadsStatusItem(provider, team)); } }); } initializeTreeViews(enabledProviders: string[]) { PROVIDERS_WITH_TREE.forEach(provider => { const hasProviderEnabled = enabledProviders.indexOf(provider) >= 0; setVsContext(`chat:${provider}`, hasProviderEnabled); }); const enabledTreeProviders = new Set(enabledProviders.filter(p => PROVIDERS_WITH_TREE.indexOf(p) >= 0)); const existingTreeProviders = new Set(Array.from(this.treeViews.keys())); const treesToAdd = difference(enabledTreeProviders, existingTreeProviders); const treesToRemove = difference(existingTreeProviders, enabledTreeProviders); treesToRemove.forEach(treeProvider => { const treeView = this.treeViews.get(treeProvider); if (!!treeView) { treeView.dispose(); this.treeViews.delete(treeProvider); } }); treesToAdd.forEach(treeProvider => { this.treeViews.set(treeProvider, new TreeViewManager(treeProvider)); }); } updateStatusItem(provider: string, team: Team) { const statusItem = this.statusItems.get(getStatusItemKey(provider, team)); if (statusItem) { const channels = this.parentManager.store.getChannels(provider); const unreads = channels.map(channel => { return this.parentManager.getUnreadCount(provider, channel); }); const totalUnreads = unreads.reduce((a, b) => a + b, 0); statusItem.updateCount(totalUnreads); } } updateTreeViews(provider: string) { const treeViewForProvider = this.treeViews.get(provider); if (!!treeViewForProvider && this.parentManager.isAuthenticated(provider)) { const channelLabels = this.parentManager.getChannelLabels(provider); const currentUserInfo = this.parentManager.getCurrentUserFor(provider); if (!!currentUserInfo) { treeViewForProvider.updateData(currentUserInfo, channelLabels); } } } updateWebview( currentUser: CurrentUser, provider: string, users: Users, channel: Channel, messages: ChannelMessages, typingUser?: User ) { const { fontFamily, fontSize } = vscode.workspace.getConfiguration("editor"); let statusText = ``; if (typingUser) { statusText = `${typingUser.name} is typing...` } let uiMessage: UIMessage = { fontFamily, fontSize, provider, messages, users, currentUser, channel, statusText // atMentions: Object.values(users) }; vscode.commands.executeCommand(SelfCommands.SEND_TO_WEBVIEW, { uiMessage }); } dispose() { for (let entry of Array.from(this.statusItems.entries())) { let statusItem = entry[1]; statusItem.dispose(); } for (let entry of Array.from(this.treeViews.entries())) { let treeView = entry[1]; treeView.dispose(); } if (!!this.onboardingTree) { this.onboardingTree.dispose(); } } } ================================================ FILE: src/onboarding.ts ================================================ import * as vscode from "vscode"; import * as str from "./strings"; import { SelfCommands } from "./constants"; import { openUrl } from "./utils"; export const setupSlack = () => { vscode.commands.executeCommand(SelfCommands.SIGN_IN, { source: EventSource.info, service: "slack" }); }; export const setupDiscord = () => { openUrl( "https://github.com/karigari/vscode-chat/blob/master/docs/DISCORD.md" ); }; export const askForAuth = async () => { const actionItems = [str.SETUP_SLACK, str.SETUP_DISCORD]; const selected = await vscode.window.showInformationMessage( str.TOKEN_NOT_FOUND, ...actionItems ); switch (selected) { case str.SETUP_SLACK: setupSlack(); break; case str.SETUP_DISCORD: setupDiscord(); break; } }; class CustomOnboardingTreeItem extends vscode.TreeItem { constructor(label: string, command: string) { super(label); this.command = { command, title: "", arguments: [{ source: EventSource.activity }] }; } } interface OnboardingTreeNode { label: string; command: string; } const OnboardingCommands = { SETUP_SLACK: "extension.chat.onboarding.slack", SETUP_DISCORD: "extension.chat.onboarding.discord" }; export class OnboardingTreeProvider implements vscode.TreeDataProvider, vscode.Disposable { // private vslsViewId = "chat.treeView.onboarding.vsls"; private mainViewId = "chat.treeView.onboarding.main"; private _disposables: vscode.Disposable[] = []; constructor() { this._disposables.push( // vscode.window.registerTreeDataProvider(this.vslsViewId, this), vscode.window.registerTreeDataProvider(this.mainViewId, this), vscode.commands.registerCommand( OnboardingCommands.SETUP_SLACK, setupSlack ), vscode.commands.registerCommand( OnboardingCommands.SETUP_DISCORD, setupDiscord ) ); } dispose() { this._disposables.forEach(dispose => dispose.dispose()); } getChildren(element?: OnboardingTreeNode) { return Promise.resolve([ { label: str.SETUP_SLACK, command: OnboardingCommands.SETUP_SLACK }, { label: str.SETUP_DISCORD, command: OnboardingCommands.SETUP_DISCORD } ]); } getTreeItem(element: OnboardingTreeNode): vscode.TreeItem { const { label, command } = element; return new CustomOnboardingTreeItem(label, command); } } ================================================ FILE: src/slack/client.ts ================================================ import { WebClient, WebClientOptions } from "@slack/client"; import { ConfigHelper } from "../config"; import Logger from "../logger"; import { IDNDStatusForUser } from "./common"; interface ISnoozeAPIResponse { ok: boolean; snooze_enabled: boolean; snooze_endtime: number; snooze_remaining: number; } const CHANNEL_HISTORY_LIMIT = 50; const USER_LIST_LIMIT = 1000; // User-defined type guard // https://github.com/Microsoft/TypeScript/issues/20707#issuecomment-351874491 function notUndefined(x: T | undefined): x is T { return x !== undefined; } const getFile = (rawFile: any) => { return { name: rawFile.name, permalink: rawFile.permalink }; }; const getContent = (attachment: any) => { return { author: attachment.author_name, authorIcon: attachment.author_icon, pretext: attachment.pretext, title: attachment.title, titleLink: attachment.title_link, text: attachment.text, footer: attachment.footer, borderColor: attachment.color }; }; const getReaction = (reaction: any) => ({ name: `:${reaction.name}:`, count: reaction.count, userIds: reaction.users }); const getUser = (member: any): User => { const { id, profile, real_name, name, deleted } = member; const { display_name, image_72, image_24 } = profile; return { id, // Conditional required for bots like @paperbot name: display_name ? display_name : name, email: profile.email, fullName: real_name, internalName: name, imageUrl: image_72, smallImageUrl: image_24, presence: UserPresence.unknown, isDeleted: deleted }; }; export const getMessage = (raw: any): ChannelMessages => { const { files, ts, user, text, edited, bot_id } = raw; const { attachments, reactions, replies } = raw; let parsed: ChannelMessages = {}; parsed[ts] = { userId: user ? user : bot_id, timestamp: ts, isEdited: !!edited, text: text, attachment: files ? getFile(files[0]) : undefined, reactions: reactions ? reactions.map((reaction: any) => getReaction(reaction)) : [], content: attachments ? getContent(attachments[0]) : undefined, replies: replies ? replies.map((reply: any) => ({ userId: reply.user, timestamp: reply.ts })) : [] }; return parsed; }; export default class SlackAPIClient { client: WebClient; constructor(private token: string) { let options: WebClientOptions = { retryConfig: { retries: 1 } }; const customAgent = ConfigHelper.getCustomAgent(); if (!!customAgent) { options.agent = customAgent; } this.client = new WebClient(token, options); this.client.on("rate_limited", retryAfter => { Logger.log(`Slack client rate limited: paused for ${retryAfter} seconds`); }); } authTest = async (): Promise => { const response: any = await this.client.auth.test(); const { ok } = response; if (ok) { const { team, user, user_id, team_id } = response; return { id: user_id, name: user, teams: [{ id: team_id, name: team }], currentTeamId: team_id, provider: Providers.slack }; } }; getConversationHistory = async ( channel: string ): Promise => { const response: any = await this.client.apiCall("conversations.history", { channel, limit: CHANNEL_HISTORY_LIMIT }); const { messages, ok } = response; let result = {}; if (ok) { messages.forEach((rawMessage: any) => { result = { ...result, ...getMessage(rawMessage) }; }); } return result; }; async getUsers(): Promise { const response: any = await this.client.apiCall("users.list", { limit: USER_LIST_LIMIT }); const { members, ok } = response; let users: Users = {}; if (ok) { members.forEach((member: any) => { const user = getUser(member); const { id } = user; users[id] = user; }); return users; } return {}; } async getBotInfo(botId: string): Promise { const response: any = await this.client.bots.info({ bot: botId }); const { bot, ok } = response; if (ok) { const { id, name, icons } = bot; return { id, name, fullName: name, imageUrl: icons.image_72, smallImageUrl: icons.image_24, presence: UserPresence.unknown, isBot: true }; } } async getUserInfo(userId: string): Promise { const response: any = await this.client.users.info({ user: userId }); const { ok, user } = response; if (ok) { return getUser(user); } } async getChannels(users: Users): Promise { const response: any = await this.client.conversations.list({ exclude_archived: true, types: "public_channel, private_channel, mpim, im" }); const { ok, channels } = response; const userValues = Object.keys(users).map(key => users[key]); if (ok) { return channels .map((channel: any) => { const { is_channel, is_mpim, is_im, is_group, is_member } = channel; if (is_channel && is_member) { // Public channels return { id: channel.id, name: channel.name, type: ChannelType.channel }; } if (is_group && !is_mpim) { // Private channels return { id: channel.id, name: channel.name, type: ChannelType.channel }; } if (is_group && is_mpim) { // Groups (multi-party direct messages) // Example name: mpdm-user.name--username2--user3-1 let { id, name } = channel; const matched = name.match(/mpdm-([^-]+)((--[^-]+)*)-\d+/); if (matched) { const first = matched[1]; const rest = matched[2] .split("--") .filter((element: string) => !!element); const members = [first, ...rest]; const memberUsers = members .map(memberName => userValues.find( ({ internalName }) => internalName === memberName ) ) .filter(notUndefined); const isAnyUserDeleted = memberUsers.filter( ({ isDeleted }) => isDeleted ); if (isAnyUserDeleted.length > 0) { return null; } else { name = memberUsers.map(({ name }) => name).join(", "); return { id: id, name: name, type: ChannelType.group }; } } } if (is_im) { // Direct messages const { id, user: userId } = channel; if (userId in users) { const user = users[userId]; if (!user.isDeleted) { const name = user.name; return { id, name, type: ChannelType.im }; } } } }) .filter(Boolean); } return []; } getChannelInfo = async ( originalChannel: Channel ): Promise => { const { id, type } = originalChannel; let response: any; let channel; try { switch (type) { case "group": response = await this.client.groups.info({ channel: id }); channel = response.group; break; case "channel": response = await this.client.channels.info({ channel: id }); channel = response.channel; break; case "im": response = await this.client.conversations.info({ channel: id }); channel = response.channel; break; } const { unread_count_display, last_read } = channel; return { ...originalChannel, unreadCount: unread_count_display, readTimestamp: last_read }; } catch (error) { // TODO: this is failing for private groups -> need to investigate why console.log("Error fetching channel:", originalChannel.name); } }; sendMessage = ( channelId: string, text: string, threadTs: string ): Promise => { return this.client.chat.postMessage({ channel: channelId, text, thread_ts: threadTs, as_user: true }); }; markChannel = async ( channel: Channel, ts: string ): Promise => { const { id, type } = channel; let response: any; switch (type) { case ChannelType.channel: response = await this.client.channels.mark({ channel: id, ts }); break; case ChannelType.group: response = await this.client.groups.mark({ channel: id, ts }); break; case ChannelType.im: response = await this.client.im.mark({ channel: id, ts }); break; } const { ok } = response; if (ok) { return { ...channel, readTimestamp: ts, unreadCount: 0 }; } }; openIMChannel = async (user: User): Promise => { const { id, name } = user; let response: any = await this.client.im.open({ user: id, return_im: true }); const { ok, channel } = response; if (ok) { return { id: channel.id, name: `@${name}`, type: ChannelType.im, unreadCount: 0, readTimestamp: undefined }; } }; getUserPrefs = async (): Promise => { // Undocumented API: https://github.com/ErikKalkoken/slackApiDoc/blob/master/users.prefs.get.md let response: any = await this.client.apiCall("users.prefs.get"); const { ok, prefs } = response; if (ok) { const { muted_channels } = prefs; return { mutedChannels: muted_channels.split(",") }; } }; getReplies = async ( channelId: string, messageTimestamp: string ): Promise => { // https://api.slack.com/methods/conversations.replies let response: any = await this.client.conversations.replies({ channel: channelId, ts: messageTimestamp }); // Does not handle has_more in the response yet, could break // for large threads const { ok, messages } = response; if (ok) { const parent = messages.find((msg: any) => msg.thread_ts === msg.ts); const replies = messages.filter((msg: any) => msg.thread_ts !== msg.ts); const parentMessage = getMessage(parent); return { ...parentMessage[messageTimestamp], replies: replies.map((reply: any) => ({ userId: reply.user, timestamp: reply.ts, text: reply.text, attachment: !!reply.files ? getFile(reply.files[0]) : null })) }; } }; setUserPresence = async (presence: "auto" | "away"): Promise => { const response = await this.client.users.setPresence({ presence }); return response.ok; }; setUserSnooze = async (durationInMinutes: number): Promise => { const response = (await this.client.dnd.setSnooze({ num_minutes: durationInMinutes })) as ISnoozeAPIResponse; return response.ok && response.snooze_enabled; }; endUserSnooze = async (): Promise => { const response = await this.client.dnd.endSnooze(); return response.ok; }; endUserDnd = async (): Promise => { const response = await this.client.dnd.endDnd(); return response.ok; }; getDndTeamInfo = async (): Promise => { const response: any = await this.client.dnd.teamInfo(); const users: IDNDStatusForUser = response.users; let result: IDNDStatusForUser = {}; const userIds = Object.keys(users); userIds.forEach(userId => { const { dnd_enabled } = users[userId]; if (!!dnd_enabled) { result[userId] = users[userId]; } }); return result; }; } ================================================ FILE: src/slack/common.ts ================================================ export interface IDNDStatus { dnd_enabled: boolean; next_dnd_start_ts: number; next_dnd_end_ts: number; // The following fields are only available for the // DND_UPDATED_SELF event. snooze_enabled?: boolean; snooze_endtime?: number; snooze_remaining?: number; } export interface IDNDStatusForUser { [userId: string]: IDNDStatus; } ================================================ FILE: src/slack/index.ts ================================================ import * as vscode from "vscode"; import { SelfCommands } from "../constants"; import SlackAPIClient from "./client"; import SlackMessenger from "./messenger"; import { IDNDStatusForUser, IDNDStatus } from "./common"; const stripLinkSymbols = (text: string): string => { // To send out live share links and render them correctly, // we append to the link text. However, this is not // handled by normal Slack clients, and should be removed before // we actually send the message via the RTM API // This is hacky, and we will need a better solution - perhaps // we could make all rendering manipulations on the extension side // before sending the message to Vuejs for rendering if (text.startsWith("<") && text.endsWith(">")) { return text.substr(1, text.length - 2); } else { return text; } }; export class SlackChatProvider implements IChatProvider { private client: SlackAPIClient; private messenger: SlackMessenger; private teamDndState: IDNDStatusForUser = {}; private dndTimers: NodeJS.Timer[] = []; constructor(private token: string, private manager: IManager) { this.client = new SlackAPIClient(this.token); this.messenger = new SlackMessenger( this.token, (userId: string, presence: "active" | "away") => this.onPresenceChanged(userId, presence), (userId: string, dndState: IDNDStatus) => this.onDndStateChanged(userId, dndState) ); } public validateToken(): Promise { // This is creating a new client, since getToken from keychain // is not called before validation return this.client.authTest(); } public connect(): Promise { return this.messenger.start(); } public isConnected(): boolean { return !!this.messenger && this.messenger.isConnected(); } public subscribePresence(users: Users) { return this.messenger.subscribePresence(users); } public createIMChannel(user: User): Promise { return this.client.openIMChannel(user); } public fetchUsers(): Promise { // async update for dnd statuses this.client.getDndTeamInfo().then(response => { this.teamDndState = response; this.updateDndTimers(); }); return this.client.getUsers(); } public fetchChannels(users: Users): Promise { // users argument is required to associate IM channels // with users return this.client.getChannels(users); } private onPresenceChanged(userId: string, rawPresence: "active" | "away") { // This method is called from the websocket client // Here, we parse the incoming raw presence (active / away), and use our // known dnd related information, to find the final answer for this user let presence: UserPresence = UserPresence.unknown; switch (rawPresence) { case "active": presence = UserPresence.available; break; case "away": presence = UserPresence.offline; break; } if (presence === UserPresence.available) { // Check user has dnd active right now const userDnd = this.teamDndState[userId]; if (!!userDnd) { const current = +new Date() / 1000.0; if ( current > userDnd.next_dnd_start_ts && current < userDnd.next_dnd_end_ts ) { presence = UserPresence.doNotDisturb; } } } this.updateUserPresence(userId, presence); } private updateUserPresence(userId: string, presence: UserPresence) { vscode.commands.executeCommand(SelfCommands.UPDATE_PRESENCE_STATUSES, { userId, presence, provider: "slack" }); } private onDndStateChanged(userId: string, dndState: IDNDStatus) { this.teamDndState[userId] = dndState; this.updateDndTimerForUser(userId); } private updateDndTimers() { const userIds = Object.keys(this.teamDndState); userIds.forEach(userId => { this.updateDndTimerForUser(userId); }); } private updateDndTimerForUser(userId: string) { const dndState = this.teamDndState[userId]; const currentTime = +new Date() / 1000.0; const { next_dnd_end_ts: dndEnd, next_dnd_start_ts: dndStart } = dndState; if (currentTime < dndStart) { // Impending start event, so we will define a start timer const delay = (dndStart - currentTime) * 1000; const timer = setTimeout(() => { // If user is available, change to dnd const presence = this.manager.getUserPresence("slack", userId); if (presence === UserPresence.available) { this.updateUserPresence(userId, UserPresence.doNotDisturb); } }, delay); this.dndTimers.push(timer); } if (currentTime < dndEnd) { // Impending end event, so define a start timer const delay = (dndEnd - currentTime) * 1000; const timer = setTimeout(() => { // If user is dnd, change to available const presence = this.manager.getUserPresence("slack", userId); if (presence === UserPresence.doNotDisturb) { this.updateUserPresence(userId, UserPresence.available); } }, delay); this.dndTimers.push(timer); } } public fetchUserInfo(userId: string): Promise { if (userId.startsWith("B")) { return this.client.getBotInfo(userId); } else { return this.client.getUserInfo(userId); } } public loadChannelHistory(channelId: string): Promise { return this.client.getConversationHistory(channelId); } public getUserPreferences(): Promise { return this.client.getUserPrefs(); } public markChannel( channel: Channel, timestamp: string ): Promise { return this.client.markChannel(channel, timestamp); } public fetchThreadReplies( channelId: string, timestamp: string ): Promise { return this.client.getReplies(channelId, timestamp); } public fetchChannelInfo(channel: Channel): Promise { return this.client.getChannelInfo(channel); } public sendThreadReply( text: string, currentUserId: string, channelId: string, parentTimestamp: string ) { const cleanText = stripLinkSymbols(text); return this.client.sendMessage(channelId, cleanText, parentTimestamp); } public async sendMessage( text: string, currentUserId: string, channelId: string ) { const cleanText = stripLinkSymbols(text); try { const result = await this.messenger.sendMessage(channelId, cleanText); // TODO: this is not the correct timestamp to attach, since the // API might get delayed, because of network issues let newMessages: ChannelMessages = {}; newMessages[result.ts] = { userId: currentUserId, timestamp: result.ts, text, content: undefined, reactions: [], replies: {} }; vscode.commands.executeCommand(SelfCommands.UPDATE_MESSAGES, { channelId, messages: newMessages, provider: "slack" }); } catch (error) { return console.error(error); } } public async updateSelfPresence( presence: UserPresence, durationInMinutes: number ): Promise { let response; const currentPresence = this.manager.getCurrentUserPresence("slack"); switch (presence) { case UserPresence.doNotDisturb: response = await this.client.setUserSnooze(durationInMinutes); break; case UserPresence.available: if (currentPresence === UserPresence.doNotDisturb) { // client.endUserDnd() can handle both situations -- when user is on // snooze, and when user is on a scheduled dnd response = await this.client.endUserDnd(); } else { response = await this.client.setUserPresence("auto"); } break; case UserPresence.invisible: response = await this.client.setUserPresence("away"); break; default: throw new Error(`unsupported presence type`); } return !!response ? presence : undefined; } public destroy(): Promise { if (!!this.messenger) { this.messenger.disconnect(); } this.dndTimers.forEach(timer => { clearTimeout(timer); }); return Promise.resolve(); } async sendTyping(currentUserId: string, channelId: string) { } } ================================================ FILE: src/slack/messenger.ts ================================================ import * as vscode from "vscode"; import { RTMClient, RTMClientOptions } from "@slack/client"; import { ConfigHelper } from "../config"; import { getMessage } from "./client"; import { SelfCommands } from "../constants"; import { IDNDStatus } from "./common"; const RTMEvents = { AUTHENTICATED: "authenticated", MESSAGE: "message", ERROR: "unable_to_rtm_start", REACTION_ADDED: "reaction_added", REACTION_REMOVED: "reaction_removed", PRESENCE_CHANGE: "presence_change", CHANNEL_MARKED: "channel_marked", GROUP_MARKED: "group_marked", IM_MARKED: "im_marked", DND_UPDATED_SELF: "dnd_updated", DND_UPDATED_USER: "dnd_updated_user" }; const EventSubTypes = { EDITED: "message_changed", DELETED: "message_deleted", REPLIED: "message_replied" }; class SlackMessenger { rtmClient: RTMClient; constructor( token: string, private onPresenceChanged: any, private onDndStateChanged: any ) { // We can also use { useRtmConnect: false } for rtm.start // instead of rtm.connect, which has more fields in the payload let options: RTMClientOptions = {}; const customAgent = ConfigHelper.getCustomAgent(); if (!!customAgent) { options.agent = customAgent; } this.rtmClient = new RTMClient(token, options); this.rtmClient.on(RTMEvents.MESSAGE, event => { const { subtype } = event; let newMessages: ChannelMessagesWithUndefined = {}; switch (subtype) { case EventSubTypes.DELETED: const { deleted_ts } = event; newMessages[deleted_ts] = undefined; break; case EventSubTypes.EDITED: const { message } = event; newMessages = { ...getMessage(message) }; break; case EventSubTypes.REPLIED: // We ignore this type, since these events also show up as normal messages // TODO: We might want to use some of these types (copied over from Slack docs): // "You may also notice thread_subscribed, thread_unsubscribed, thread_marked update_thread_state event types" break; default: const { text, attachments, files, thread_ts, ts } = event; if (!!thread_ts && !!ts && thread_ts !== ts) { // This is a thread reply const { user, text, channel } = event; const reply: MessageReply = { userId: user, timestamp: ts, text }; vscode.commands.executeCommand( SelfCommands.UPDATE_MESSAGE_REPLIES, { parentTimestamp: thread_ts, channelId: channel, reply, provider: "slack" } ); } else { const hasAttachment = attachments && attachments.length > 0; const hasFiles = files && files.length > 0; if (!!text || hasAttachment || hasFiles) { const message = getMessage(event); newMessages = { ...newMessages, ...message }; this.handleMessageLinks(message); } } } // On sending messages, this also gets called, which means we // send duplicate messages to the webview. vscode.commands.executeCommand(SelfCommands.UPDATE_MESSAGES, { channelId: event.channel, messages: newMessages, provider: "slack" }); }); this.rtmClient.on(RTMEvents.REACTION_ADDED, event => { const { user: userId, reaction: reactionName, item } = event; const { channel: channelId, ts: msgTimestamp } = item; vscode.commands.executeCommand(SelfCommands.ADD_MESSAGE_REACTION, { userId, channelId, msgTimestamp, reactionName, provider: "slack" }); }); this.rtmClient.on(RTMEvents.REACTION_REMOVED, event => { const { user: userId, reaction: reactionName, item } = event; const { channel: channelId, ts: msgTimestamp } = item; vscode.commands.executeCommand(SelfCommands.REMOVE_MESSAGE_REACTION, { userId, channelId, msgTimestamp, reactionName, provider: "slack" }); }); this.rtmClient.on(RTMEvents.CHANNEL_MARKED, event => { const { channel, ts, unread_count_display } = event; vscode.commands.executeCommand(SelfCommands.CHANNEL_MARKED, { channelId: channel, readTimestamp: ts, unreadCount: unread_count_display, provider: "slack" }); }); this.rtmClient.on(RTMEvents.GROUP_MARKED, event => { const { channel, ts, unread_count_display } = event; vscode.commands.executeCommand(SelfCommands.CHANNEL_MARKED, { channelId: channel, readTimestamp: ts, unreadCount: unread_count_display, provider: "slack" }); }); this.rtmClient.on(RTMEvents.IM_MARKED, event => { const { channel, ts, unread_count_display } = event; vscode.commands.executeCommand(SelfCommands.CHANNEL_MARKED, { channelId: channel, readTimestamp: ts, unreadCount: unread_count_display, provider: "slack" }); }); this.rtmClient.on(RTMEvents.PRESENCE_CHANGE, event => { const { user: userId, presence: rawPresence } = event; this.onPresenceChanged(userId, rawPresence); }); this.rtmClient.on(RTMEvents.DND_UPDATED_SELF, event => { // This is a no-op, since the DND_UPDATED_USER handler does everything const { user: userId } = event; const dndStatus: IDNDStatus = event.dnd_status; }); this.rtmClient.on(RTMEvents.DND_UPDATED_USER, event => { // This event is not fired when the snooze ends for a user // Hence, we need to maintain that via dnd timers const { user: userId } = event; const dndStatus: IDNDStatus = event.dnd_status; this.onDndStateChanged(userId, dndStatus); }); } isConnected(): boolean { return !!this.rtmClient && this.rtmClient.connected; } start = (): Promise => { return new Promise((resolve, reject) => { this.rtmClient.once(RTMEvents.AUTHENTICATED, response => { const { ok, team, self } = response; if (ok) { const { id, name } = self; const { id: teamId, name: teamName } = team; return resolve({ id, name, teams: [{ id: teamId, name: teamName }], currentTeamId: teamId, provider: Providers.slack }); } }); this.rtmClient.once(RTMEvents.ERROR, error => { return reject(error); }); // Note, rtm.start is heavily rate-limited this.rtmClient.start(); }); }; sendMessage = (channelId: string, text: string) => { return this.rtmClient.sendMessage(text, channelId); }; handleMessageLinks = (incoming: ChannelMessages) => { const messageTs = Object.keys(incoming)[0]; const message = incoming[messageTs]; let { text, userId } = message; let uri: vscode.Uri | undefined; if (text.startsWith("<") && text.endsWith(">")) { text = text.substring(1, text.length - 1); // Strip link symbols } try { if (text.startsWith("http")) { uri = vscode.Uri.parse(text); vscode.commands.executeCommand(SelfCommands.HANDLE_INCOMING_LINKS, { provider: "slack", senderId: userId, uri }); } } catch (err) {} }; subscribePresence = (users: Users) => { this.rtmClient.subscribePresence(Object.keys(users)); }; disconnect() { if (!!this.rtmClient) { return this.rtmClient.disconnect(); } } } export default SlackMessenger; ================================================ FILE: src/status/index.ts ================================================ import * as vscode from "vscode"; import { SelfCommands } from "../constants"; const CHAT_OCTICON = "$(comment-discussion)"; export abstract class BaseStatusItem { protected item: vscode.StatusBarItem; protected disposableCommand: vscode.Disposable; protected unreadCount: number = 0; protected isVisible: boolean = false; constructor(baseCommand: string, commandArgs: ChatArgs, commandModifier: string) { this.item = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left); // We construct a new command to send args with base command // From: https://github.com/Microsoft/vscode/issues/22353#issuecomment-325293438 const compound = `${baseCommand}.${commandModifier}.status`; this.disposableCommand = vscode.commands.registerCommand(compound, () => { return vscode.commands.executeCommand(baseCommand, commandArgs); }); this.item.command = compound; } abstract updateCount(unreads: number): void; show() { if (!this.isVisible) { this.item.show(); this.isVisible = true; } } hide() { if (this.isVisible) { this.item.hide(); this.isVisible = false; } } dispose() { this.item.dispose(); this.disposableCommand.dispose(); } } export class UnreadsStatusItem extends BaseStatusItem { teamName: string; providerName: string; constructor(providerName: string, team: Team) { const baseCommand = SelfCommands.CHANGE_CHANNEL; let chatArgs: ChatArgs = { providerName, source: EventSource.status }; const modifier = `${providerName}.${team.id}`; // This ensures discord teams have separate items super(baseCommand, chatArgs, modifier); this.providerName = providerName; this.teamName = team.name; } updateCount(unreads: number) { this.unreadCount = unreads; this.item.text = `${CHAT_OCTICON} ${this.teamName}: ${unreads} new`; return this.unreadCount > 0 ? this.show() : this.hide(); } } ================================================ FILE: src/store.ts ================================================ import * as vscode from "vscode"; import * as semver from "semver"; import { uuidv4, getExtensionVersion } from "./utils"; // Large discord communities can have lots of users/channels // More than the quota of context.globalState const VALUE_LENGTH_LIMIT = 100; const MESSAGE_HISTORY_LIMIT = 50; const stateKeys = { EXTENSION_VERSION: "extensionVersion", INSTALLATION_ID: "installationId", LAST_CHANNEL_ID: "lastChannelId", CHANNELS: "channels", USER_INFO: "userInfo", USERS: "users", MESSAGE_HISTORY: "messagesHistory" }; export class Store implements IStore { public installationId: string | undefined; public existingVersion: string | undefined; private currentUserInfo: { [provider: string]: CurrentUser }; private channels: { [provider: string]: Channel[] }; private users: { [provider: string]: Users }; private lastChannelId: { [provider: string]: string }; constructor(private context: vscode.ExtensionContext) { this.loadInitialState(); } loadInitialState() { const { globalState } = this.context; this.installationId = globalState.get(stateKeys.INSTALLATION_ID); this.existingVersion = globalState.get(stateKeys.EXTENSION_VERSION); this.channels = globalState.get(stateKeys.CHANNELS) || {}; this.currentUserInfo = globalState.get(stateKeys.USER_INFO) || {}; this.users = globalState.get(stateKeys.USERS) || {}; this.lastChannelId = globalState.get(stateKeys.LAST_CHANNEL_ID) || {}; } async runStateMigrations() { const currentVersion = getExtensionVersion(); if (!!currentVersion && this.existingVersion !== currentVersion) { if (!!this.existingVersion) { if (semver.lt(this.existingVersion, "0.9.0")) { await this.migrateFor09x(); } } this.updateExtensionVersion(currentVersion); this.loadInitialState(); } } async migrateFor09x() { // Run migrations for 0.9.x const { globalState } = this.context; const currentUser: any = globalState.get(stateKeys.USER_INFO); if (!!currentUser) { const { provider } = currentUser; if (!!provider) { const channels = globalState.get(stateKeys.CHANNELS); const users = globalState.get(stateKeys.USERS); const lastChannelId = globalState.get(stateKeys.LAST_CHANNEL_ID); await globalState.update(stateKeys.USER_INFO, { [provider]: currentUser }); await globalState.update(stateKeys.CHANNELS, { [provider]: channels }); await globalState.update(stateKeys.USERS, { [provider]: users }); await globalState.update(stateKeys.LAST_CHANNEL_ID, { [provider]: lastChannelId }); } } } generateInstallationId(): string { const uuidStr = uuidv4(); const { globalState } = this.context; globalState.update(stateKeys.INSTALLATION_ID, uuidStr); this.installationId = uuidStr; return uuidStr; } updateExtensionVersion(version: string) { const { globalState } = this.context; return globalState.update(stateKeys.EXTENSION_VERSION, version); } getCurrentUser = (provider: string): CurrentUser | undefined => { return this.currentUserInfo[provider]; }; getCurrentUserForAll = (): CurrentUser[] => { const providers = Object.keys(this.currentUserInfo); return providers.map(provider => this.currentUserInfo[provider]); }; getUsers = (provider: string): Users => { return this.users[provider] || {}; }; getUser = (provider: string, userId: string): User | undefined => { const providerUsers = this.users[provider] || {}; return providerUsers[userId]; }; getChannels = (provider: string): Channel[] => { return this.channels[provider] || []; }; getLastChannelId = (provider: string): string | undefined => { return this.lastChannelId[provider]; }; updateLastChannelId = (provider: string, channelId: string | undefined): Thenable => { const lastChannels = { ...this.lastChannelId, [provider]: channelId }; this.lastChannelId = this.getObjectWithoutUndefined(lastChannels); return this.context.globalState.update(stateKeys.LAST_CHANNEL_ID, this.lastChannelId); }; updateUsers = (provider: string, users: Users): Thenable => { let newUsers = users; this.users = { ...this.users, [provider]: newUsers }; const totalUserCount = Object.values(this.users) .map(usersObject => Object.keys(usersObject).length) .reduce((acc, curr) => acc + curr); const isUnderCacheSizeLimit = totalUserCount <= VALUE_LENGTH_LIMIT; if (isUnderCacheSizeLimit) { return this.context.globalState.update(stateKeys.USERS, this.users); } return Promise.resolve(); }; updateUser = (provider: string, userId: string, user: User) => { // NOTE: This does not store to the local storage const providerUsers = this.users[provider] || {}; this.users = { ...this.users, [provider]: { ...providerUsers, [userId]: { ...user } } }; }; updateChannels = (provider: string, channels: Channel[]): Thenable => { this.channels = { ...this.channels, [provider]: channels }; const totalChannelCount = Object.values(this.channels) .map(channels => channels.length) .reduce((acc, curr) => acc + curr); const isUnderCacheSizeLimit = totalChannelCount <= VALUE_LENGTH_LIMIT; if (isUnderCacheSizeLimit) { return this.context.globalState.update(stateKeys.CHANNELS, this.channels); } return Promise.resolve(); }; updateCurrentUser = (provider: string, userInfo: CurrentUser | undefined): Thenable => { const cachedCurrentUser = this.currentUserInfo[provider]; let newCurrentUser: CurrentUser | undefined; if (!userInfo) { newCurrentUser = userInfo; // Resetting userInfo } else { // Copy cover the currentTeamId from existing state, if available let currentTeamId = !!cachedCurrentUser ? cachedCurrentUser.currentTeamId : undefined; if (!!userInfo.currentTeamId) { currentTeamId = userInfo.currentTeamId; } newCurrentUser = { ...userInfo, currentTeamId }; // If this is Slack, our local state might know of more workspaces if (provider === "slack" && !!cachedCurrentUser) { let mergedTeams: any = {}; const { teams: newTeams } = userInfo; const { teams: existingTeams } = cachedCurrentUser; existingTeams.forEach(team => (mergedTeams[team.id] = team)); newTeams.forEach(team => (mergedTeams[team.id] = team)); const teams = Object.keys(mergedTeams).map(key => mergedTeams[key]); newCurrentUser = { ...newCurrentUser, teams }; } } const updatedCurrentUserInfo = { ...this.currentUserInfo, [provider]: !!newCurrentUser ? { ...newCurrentUser } : undefined }; this.currentUserInfo = this.getObjectWithoutUndefined(updatedCurrentUserInfo); return this.context.globalState.update(stateKeys.USER_INFO, this.currentUserInfo); }; updateMessageHistory = (channelId: string, messages: ChannelMessages) => { const existingMessages = this.context.globalState.get(stateKeys.MESSAGE_HISTORY) || {}; const timestamps = Object.keys(messages).map(t => +t); let filteredTimestamps = timestamps; if (timestamps.length > MESSAGE_HISTORY_LIMIT) { const sortedTimestamps = timestamps.sort((a, b) => (b - a)) filteredTimestamps = sortedTimestamps.slice(0, MESSAGE_HISTORY_LIMIT); } let filteredMessages: ChannelMessages = {}; filteredTimestamps.forEach(ts => { filteredMessages[`${ts}`] = messages[`${ts}`] }) return this.context.globalState.update(stateKeys.MESSAGE_HISTORY, { ...existingMessages, [channelId]: filteredMessages }); } getMessageHistoryForChannel = (channelId: string) => { const allMessages: Messages = this.context.globalState.get(stateKeys.MESSAGE_HISTORY) || {}; return allMessages[channelId] || {}; } async clearProviderState(provider: string): Promise { this.currentUserInfo = this.getObjectWithoutUndefined({ ...this.currentUserInfo, [provider]: undefined }); this.users = this.getObjectWithoutUndefined({ ...this.users, [provider]: undefined }); this.channels = this.getObjectWithoutUndefined({ ...this.channels, [provider]: undefined }); this.lastChannelId = this.getObjectWithoutUndefined({ ...this.lastChannelId, [provider]: undefined }); await this.context.globalState.update(stateKeys.USER_INFO, this.currentUserInfo); await this.context.globalState.update(stateKeys.USERS, this.users); await this.context.globalState.update(stateKeys.CHANNELS, this.channels); return this.context.globalState.update(stateKeys.LAST_CHANNEL_ID, this.lastChannelId); } private getObjectWithoutUndefined = (input: any) => { // Remove undefined values from the input object let withoutUndefined: any = {}; Object.keys(input).forEach(key => { const value = input[key]; if (!!value) { withoutUndefined[key] = value; } }); return withoutUndefined; }; } ================================================ FILE: src/strings.ts ================================================ export const CHANGE_CHANNEL_TITLE = "Select a channel"; export const CHANGE_WORKSPACE_TITLE = "Select a workspace"; export const CHANGE_PROVIDER_TITLE = "Select a provider"; export const RELOAD_CHANNELS = "Reload Channels..."; export const TOKEN_NOT_FOUND = "Setup Team Chat to work for your account."; export const SETUP_SLACK = "Set up Slack"; export const SETUP_DISCORD = "Set up Discord"; export const REPORT_ISSUE = "Report issue"; export const RETRY = "Retry"; export const KEYCHAIN_ERROR = "The Team Chat extension is unable to access the system keychain."; export const TOKEN_PLACEHOLDER = "Paste token here"; export const AUTH_FAILED_MESSAGE = "Sign in failed. Help us get better by reporting an issue."; export const INVALID_TOKEN = (provider: string) => `The ${provider} token cannot be validated. Please enter a valid token.`; export const INVALID_COMMAND = (text: string) => `${text} is not a recognised command.`; export const UPLOADED_FILE = (link: string) => `uploaded a file: ${link}`; export const LIVE_REQUEST_MESSAGE = "wants to start a Live Share session"; export const LIVE_SHARE_INVITE = (name: string) => `${name} has invited you to a Live Share collaboration session.`; export const LIVE_SHARE_CHAT_NO_SESSION = "Chat requires an active Live Share collaboration session."; export const LIVE_SHARE_INFO_MESSAGES = { started: "_has started the Live Share session_", ended: "_has ended the Live Share session_", joined: "_has joined the Live Share session_", left: "_has left the Live Share session_" }; export const LIVE_SHARE_CONFIRM_SIGN_OUT = (provider: string) => `To use chat over VS Live Share, you need to sign out of your ${provider} account.`; export const SIGN_OUT = "Sign out"; export const SELECT_SELF_PRESENCE = "Select your presence status"; export const SELECT_DND_DURATION = "Select snooze duration for Slack"; export const UNABLE_TO_MATCH_CONTACT = "Could not start chat: unable to match this contact."; export const NO_LIVE_SHARE_CHAT_ON_HOST = "Live Share Chat is unavailable for this session, since the host does not have it."; ================================================ FILE: src/telemetry.ts ================================================ import * as vscode from "vscode"; import * as Mixpanel from "mixpanel"; import { MIXPANEL_TOKEN } from "./constants"; import { ConfigHelper } from "./config"; import Manager from "./manager"; import { getVersions, Versions, hasVslsExtensionPack } from "./utils"; const BATCH_SIZE = 10; const INTERVAL_TIMEOUT = 30 * 60 * 1000; // 30 mins in ms export default class TelemetryReporter implements vscode.Disposable { private hasUserOptIn: boolean = false; private uniqueId: string | undefined; // TODO: remove undefined private mixpanel: Mixpanel.Mixpanel | undefined; private versions: Versions; private hasExtensionPack: boolean; private pendingEvents: TelemetryEvent[] = []; private interval: NodeJS.Timer | undefined; constructor(private manager: Manager) { const { installationId } = this.manager.store; this.uniqueId = installationId; this.versions = getVersions(); if (process.env.IS_DEBUG !== "true") { this.hasUserOptIn = ConfigHelper.hasTelemetry(); } if (this.hasUserOptIn) { this.mixpanel = Mixpanel.init(MIXPANEL_TOKEN); this.interval = setInterval(() => { if (this.pendingEvents.length > 0) { return this.flushBatch(); } }, INTERVAL_TIMEOUT); } this.hasExtensionPack = hasVslsExtensionPack(); } setUniqueId(uniqueId: string) { this.uniqueId = uniqueId; } dispose(): Promise { if (!!this.interval) { clearInterval(this.interval); } if (this.pendingEvents.length > 0) { return this.flushBatch(); } return Promise.resolve(); } record( name: EventType, source: EventSource | undefined, channelId: string | undefined, // TODO: change this to channelType provider: string | undefined ) { let channelType = undefined; if (!!channelId && !!provider) { const channel = this.manager.getChannel(provider, channelId); channelType = !!channel ? channel.type : undefined; } const event: TelemetryEvent = { type: name, time: new Date(), properties: { provider, source: source, channel_type: channelType } }; if (this.hasUserOptIn) { this.pendingEvents.push(event); const hasActivationEvents = name === EventType.activationEnded || name === EventType.activationStarted; if (this.pendingEvents.length >= BATCH_SIZE || hasActivationEvents) { this.flushBatch(); } } } getMxEvent(event: TelemetryEvent): Mixpanel.Event { const { os, extension, editor } = this.versions; const { type: name, properties, time } = event; const { provider } = properties; return { event: name, properties: { distinct_id: this.uniqueId, extension_version: extension, os_version: os, editor_version: editor, has_extension_pack: this.hasExtensionPack, is_authenticated: this.manager.isAuthenticated(provider), ...properties, time } }; } flushBatch(): Promise { const copy = [...this.pendingEvents]; const events = copy.map(event => this.getMxEvent(event)); this.pendingEvents = []; return new Promise((resolve, reject) => { if (!this.mixpanel) { resolve(); } else { this.mixpanel.track_batch(events, error => { if (!error) { resolve(); } else { // We are not going to retry with `copy` reject(); } }); } }); } } ================================================ FILE: src/test/extension.test.ts ================================================ // // Note: This example test is leveraging the Mocha test framework. // Please refer to their documentation on https://mochajs.org/ for help. // import * as assert from "assert"; import * as vscode from "vscode"; import * as myExtension from "../extension"; // Defines a Mocha test suite to group tests of similar kind together suite("Extension Tests", function () { // Defines a Mocha unit test test("Something 1", function () { assert.equal(-1, [1, 2, 3].indexOf(5)); assert.equal(-1, [1, 2, 3].indexOf(0)); }); }); ================================================ FILE: src/test/index.ts ================================================ // // PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING // // This file is providing the test runner to use when running extension tests. // By default the test runner in use is Mocha based. // // You can provide your own test runner if you want to override it by exporting // a function run(testRoot: string, clb: (error:Error) => void) that the extension // host can call to run the tests. The test runner is expected to use console.log // to report the results back to the caller. When the tests are finished, return // a possible error to the callback or null if none. import * as testRunner from "vscode/lib/testrunner"; // You can directly control Mocha options by uncommenting the following lines // See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info testRunner.configure({ ui: "tdd", // the TDD UI is being used in extension.test.ts (suite, test, etc.) useColors: true // colored output from test results }); module.exports = testRunner; ================================================ FILE: src/test/manager.test.ts ================================================ import * as assert from "assert"; import { Store } from "../store"; import Manager from "../manager"; import { mock, instance, verify, when } from "ts-mockito"; import { ChatProviderManager } from "../manager/chatManager"; import { SlackChatProvider } from "../slack"; let mockedStore = mock(Store); let store = instance(mockedStore); let manager: Manager = new Manager(store); let slackProvider = new SlackChatProvider("test-token", manager); let slackManager = new ChatProviderManager( store, "slack", "test-team-id", slackProvider, manager ); manager.chatProviders.set("slack" as Providers, slackManager); suite("Manager tests", function() { setup(() => { const currentUser = { id: "user-id", name: "user-name", teams: [], currentTeamId: "team-id", provider: Providers.slack }; when(mockedStore.getCurrentUserForAll()).thenReturn([{ ...currentUser }]); when(mockedStore.getCurrentUser("slack")).thenReturn({ ...currentUser }); manager.initializeToken(); }); test("Get enabled providers works", function() { const enabledProviders = manager.getEnabledProviders().map(e => e.provider); assert.equal(enabledProviders.indexOf("slack") >= 0, true); }); test("Clear all works", function() { assert.notEqual(manager.chatProviders.get("slack" as Providers), undefined); manager.clearAll(); verify(mockedStore.clearProviderState("slack")).once(); assert.equal(manager.chatProviders.get("slack" as Providers), undefined); }); test("Authentication check works", function() { assert.equal(slackManager.isAuthenticated(), true); when(mockedStore.getCurrentUser("slack")).thenReturn(undefined); assert.equal(slackManager.isAuthenticated(), false); }); }); ================================================ FILE: src/test/utils.test.ts ================================================ import * as assert from "assert"; import { sanitiseTokenString } from "../utils"; suite("utility function tests", function() { setup(() => {}); test("sanitise token works", function() { assert.equal(sanitiseTokenString('"token"'), "token"); assert.equal(sanitiseTokenString(" token"), "token"); assert.equal(sanitiseTokenString(' "token"'), "token"); }); }); ================================================ FILE: src/tree/base.ts ================================================ import * as vscode from "vscode"; import { ChannelTreeItem } from "./treeItem"; import { equals, notUndefined } from "../utils"; export interface ISortingFunction { (a: ChannelLabel, b: ChannelLabel): number; } export interface IFilterFunction { (a: ChannelLabel): boolean; } export class BaseChannelsListTreeProvider implements vscode.TreeDataProvider, vscode.Disposable { private _onDidChangeTreeData = new vscode.EventEmitter(); readonly onDidChangeTreeData? = this._onDidChangeTreeData.event; protected _disposables: vscode.Disposable[] = []; protected sortingFn: ISortingFunction = (a: ChannelLabel, b: ChannelLabel) => a.label.localeCompare(b.label); protected filterFn: IFilterFunction = () => true; protected channelLabels: ChannelLabel[] = []; constructor(protected providerName: string, protected viewId: string) { this._disposables.push( vscode.window.registerTreeDataProvider(this.viewId, this) ); } dispose() { this._disposables.forEach(dispose => dispose.dispose()); } async refresh(treeItem?: ChatTreeNode) { return treeItem ? this._onDidChangeTreeData.fire(treeItem) : this._onDidChangeTreeData.fire(); } getLabelsObject( channeLabels: ChannelLabel[] ): { [channelId: string]: ChannelLabel } { let result: { [channelId: string]: ChannelLabel } = {}; channeLabels.forEach(label => { const { channel } = label; result[channel.id] = label; }); return result; } updateChannels(channelLabels: ChannelLabel[]) { const filtered = channelLabels.filter(this.filterFn).sort(this.sortingFn); const prevLabels = this.getLabelsObject(this.channelLabels); const newLabels = this.getLabelsObject(filtered); this.channelLabels = filtered; const prevKeys = new Set(Object.keys(prevLabels)); const newKeys = new Set(Object.keys(newLabels)); if (!equals(prevKeys, newKeys)) { // We have new channels, so we are replacing everything // Can potentially optimize this return this.refresh(); } // Looking for changes in presence and unread Object.keys(newLabels).forEach(channelId => { const newLabel = newLabels[channelId]; const prevLabel = prevLabels[channelId]; if (prevLabel.unread !== newLabel.unread) { // Can we send just this element? this.refresh(); } if (prevLabel.presence !== newLabel.presence) { // Can we send just this element? this.refresh(); } }); } getParent = (element: ChatTreeNode): vscode.ProviderResult => { const { channel } = element; if (!!channel && !!channel.categoryName) { return Promise.resolve(this.getItemForCategory(channel.categoryName)); } }; getChildren = ( element?: ChatTreeNode ): vscode.ProviderResult => { if (!element) { return this.getRootChildren(); } if (!!element && element.isCategory) { return this.getChildrenForCategory(element); } }; getChildrenForCategory = ( element: ChatTreeNode ): vscode.ProviderResult => { const { label: category } = element; const channels = this.channelLabels .filter(channelLabel => { const { channel } = channelLabel; return channel.categoryName === category; }) .map(this.getItemForChannel); return Promise.resolve(channels); }; getRootChildren = (): vscode.ProviderResult => { const channelsWithoutCategories = this.channelLabels .filter(channelLabel => !channelLabel.channel.categoryName) .map(this.getItemForChannel); const categories: string[] = this.channelLabels .map(channelLabel => channelLabel.channel.categoryName) .filter(notUndefined); const uniqueCategories = categories .filter((item, pos) => categories.indexOf(item) === pos) .map(category => this.getItemForCategory(category)); return Promise.resolve([...channelsWithoutCategories, ...uniqueCategories]); }; getItemForChannel = (channelLabel: ChannelLabel): ChatTreeNode => { const { label, presence, channel } = channelLabel; return { label, presence, channel, isCategory: false, user: undefined, team: undefined, providerName: this.providerName }; }; getItemForCategory = (category: string): ChatTreeNode => { return { label: category, presence: UserPresence.unknown, isCategory: true, channel: undefined, user: undefined, team: undefined, providerName: this.providerName }; }; getTreeItem = (element: ChatTreeNode): vscode.TreeItem => { const { label, presence, isCategory, channel, user } = element; const treeItem = new ChannelTreeItem( label, presence, isCategory, this.providerName, channel, user ); return treeItem; }; } ================================================ FILE: src/tree/index.ts ================================================ import * as vscode from "vscode"; import { BaseChannelsListTreeProvider, IFilterFunction, ISortingFunction } from "./base"; import { WorkspaceTreeItem } from "./treeItem"; import { equals, notUndefined } from "../utils"; export class WorkspacesTreeProvider extends BaseChannelsListTreeProvider { protected filterFn: IFilterFunction = c => c.unread > 0; protected sortingFn: ISortingFunction = (a, b) => b.unread - a.unread; private userInfo: CurrentUser | undefined; constructor(provider: string) { super(provider, `chat.treeView.workspaces.${provider}`); } updateCurrentUser(userInfo: CurrentUser) { if (!this.userInfo) { this.userInfo = userInfo; this.refresh(); } else { const existingTeamIds = this.userInfo.teams.map(team => team.id); const newTeamIds = userInfo.teams.map(team => team.id); const hasTeamsChanged = !equals( new Set(existingTeamIds), new Set(newTeamIds) ); const hasCurrentChanged = this.userInfo.currentTeamId !== userInfo.currentTeamId; if (hasCurrentChanged || hasTeamsChanged) { this.userInfo = userInfo; this.refresh(); } } } getChildren = ( element?: ChatTreeNode ): vscode.ProviderResult => { if (!element) { if (!!this.userInfo) { const { teams } = this.userInfo; return teams.map(this.getItemForTeam); } } }; getItemForTeam = (team: Team): ChatTreeNode => { let label = team.name; if (!!this.userInfo) { if (this.userInfo.currentTeamId === team.id) { label = `${label} (active)`; } } return { label, presence: UserPresence.unknown, isCategory: false, channel: undefined, user: undefined, team: team, providerName: this.providerName }; }; getTreeItem = (element: ChatTreeNode): vscode.TreeItem => { const { label, team, providerName } = element; const treeItem = new WorkspaceTreeItem(label, providerName, team); return treeItem; }; } export class UnreadsTreeProvider extends BaseChannelsListTreeProvider { protected filterFn: IFilterFunction = c => c.unread > 0; protected sortingFn: ISortingFunction = (a, b) => b.unread - a.unread; constructor(provider: string) { super(provider, `chat.treeView.unreads.${provider}`); } } export class ChannelTreeProvider extends BaseChannelsListTreeProvider { protected filterFn: IFilterFunction = c => c.channel.type === ChannelType.channel; constructor(provider: string) { super(provider, `chat.treeView.channels.${provider}`); } } export class GroupTreeProvider extends BaseChannelsListTreeProvider { protected filterFn: IFilterFunction = c => c.channel.type === ChannelType.group; constructor(provider: string) { super(provider, `chat.treeView.groups.${provider}`); } } export class IMsTreeProvider extends BaseChannelsListTreeProvider { protected filterFn: IFilterFunction = c => c.channel.type === ChannelType.im; constructor(provider: string) { super(provider, `chat.treeView.ims.${provider}`); } } export class OnlineUsersTreeProvider extends BaseChannelsListTreeProvider { private users: User[] = []; private imChannels: { [userId: string]: Channel } = {}; private DM_ROLE_NAME = "Direct Messages"; private OTHERS_ROLE_NAME = "Others"; constructor(providerName: string) { super(providerName, `chat.treeView.onlineUsers.${providerName}`); } updateData( currentUser: CurrentUser, users: Users, imChannels: { [userId: string]: Channel } ) { const { id: currentId } = currentUser; const ALLOWED_PRESENCE = [ UserPresence.available, UserPresence.doNotDisturb, UserPresence.idle ]; const prevUserIds = new Set(this.users.map(user => user.id)); this.users = Object.keys(users) .map(userId => users[userId]) .filter(user => ALLOWED_PRESENCE.indexOf(user.presence) >= 0) .filter(user => user.id !== currentId); // Can't have the self user in this list const newUserIds = new Set(this.users.map(user => user.id)); this.imChannels = imChannels; if (!equals(prevUserIds, newUserIds)) { return this.refresh(); } } getItemForUser(user: User): ChatTreeNode { return { label: user.name, presence: user.presence, isCategory: false, user, channel: this.imChannels[user.id], team: undefined, providerName: this.providerName }; } getChildrenForCategory = (element: ChatTreeNode) => { const { label: role } = element; if (role === this.DM_ROLE_NAME) { const dmUserIds = Object.keys(this.imChannels); return Promise.resolve( this.users .filter(user => dmUserIds.indexOf(user.id) >= 0) .map(user => this.getItemForUser(user)) ); } if (role === this.OTHERS_ROLE_NAME) { const usersWithoutRoles = this.users.filter(user => !user.roleName); return Promise.resolve( usersWithoutRoles.map(user => this.getItemForUser(user)) ); } const users = this.users .filter(user => user.roleName === role) .map(user => this.getItemForUser(user)); return Promise.resolve(users); }; getRootChildren = (): vscode.ProviderResult => { if (this.providerName === "slack") { return Promise.resolve(this.users.map(user => this.getItemForUser(user))); } // Since Discord guilds can have lots of members, we want to ensure all // members are categorised for easy navigation. // For this, we introduced 2 roles: "Direct Messages" and "Others" // const dmRoles = this. let rootElements = []; const dmUserIds = Object.keys(this.imChannels); if (dmUserIds.length > 0) { rootElements.push(this.getItemForCategory(this.DM_ROLE_NAME)); } const roles = this.users .filter(user => !!user.roleName) .map(user => user.roleName); const uniqueRoles = roles .filter((item, pos) => roles.indexOf(item) === pos) .filter(notUndefined) .map(role => this.getItemForCategory(role)); if (uniqueRoles.length > 0) { rootElements = [...rootElements, ...uniqueRoles]; } const usersWithoutRoles = this.users.filter(user => !user.roleName); if (usersWithoutRoles.length > 0) { rootElements.push(this.getItemForCategory(this.OTHERS_ROLE_NAME)); } return Promise.resolve(rootElements); }; getParent = (element: ChatTreeNode): vscode.ProviderResult => { return; }; } ================================================ FILE: src/tree/treeItem.ts ================================================ import * as vscode from "vscode"; import * as path from "path"; import { SelfCommands, EXTENSION_ID } from "../constants"; const selfExtension = vscode.extensions.getExtension(EXTENSION_ID) as vscode.Extension; const BASE_PATH = path.join(selfExtension.extensionPath, "public", "icons", "presence"); const PRESENCE_ICONS = { green: path.join(BASE_PATH, "green.svg"), red: path.join(BASE_PATH, "red.svg"), yellow: path.join(BASE_PATH, "yellow.svg") }; export class WorkspaceTreeItem extends vscode.TreeItem { constructor(label: string, provider: string, team: Team | undefined) { super(label); if (!!team) { this.command = { command: SelfCommands.CHANGE_WORKSPACE, title: "", arguments: [{ team, provider }] }; } } } export class ChannelTreeItem extends vscode.TreeItem { constructor( label: string, presence: UserPresence, isCategory: boolean, providerName: string, channel?: Channel, user?: User ) { super(label); if (!!channel) { // This is a channel item this.contextValue = "channel"; const chatArgs: ChatArgs = { channelId: channel ? channel.id : undefined, user, providerName, source: EventSource.activity }; this.command = { command: SelfCommands.OPEN_WEBVIEW, title: "", arguments: [chatArgs] }; } switch (presence) { case UserPresence.available: this.iconPath = { light: PRESENCE_ICONS.green, dark: PRESENCE_ICONS.green }; break; case UserPresence.doNotDisturb: this.iconPath = { light: PRESENCE_ICONS.red, dark: PRESENCE_ICONS.red }; break; case UserPresence.idle: this.iconPath = { light: PRESENCE_ICONS.yellow, dark: PRESENCE_ICONS.yellow }; break; } if (isCategory) { this.collapsibleState = vscode.TreeItemCollapsibleState.Collapsed; } } } ================================================ FILE: src/types.ts ================================================ interface IChatProvider { validateToken: () => Promise; fetchUsers: () => Promise; fetchUserInfo: (userId: string) => Promise; fetchChannels: (users: Users) => Promise; fetchChannelInfo: (channel: Channel) => Promise; loadChannelHistory: (channelId: string) => Promise; getUserPreferences: () => Promise; markChannel: (channel: Channel, ts: string) => Promise; fetchThreadReplies: (channelId: string, ts: string) => Promise; sendMessage: (text: string, currentUserId: string, channelId: string) => Promise; sendTyping: (currentUserId: string, channelId: string) => Promise; sendThreadReply: (text: string, currentUserId: string, channelId: string, parentTimestamp: string) => Promise; connect: () => Promise; isConnected: () => boolean; updateSelfPresence: (presence: UserPresence, durationInMinutes: number) => Promise; subscribePresence: (users: Users) => void; createIMChannel: (user: User) => Promise; destroy: () => Promise; } const enum UserPresence { unknown = "unknown", available = "available", idle = "idle", doNotDisturb = "doNotDisturb", invisible = "invisible", offline = "offline" } interface User { id: string; name: string; email?: string; // Discord does not have emails, hence the ? fullName: string; internalName?: string; // Used by slack provider to associate DMs imageUrl: string; smallImageUrl: string; presence: UserPresence; isBot?: boolean; isDeleted?: boolean; roleName?: string; } interface UserPreferences { mutedChannels?: string[]; } const enum Providers { slack = "slack", discord = "discord", vslsSpaces = "vslsSpaces" } interface CurrentUser { id: string; name: string; teams: Team[]; currentTeamId: string | undefined; provider: Providers; } interface Team { // Team represents workspace for Slack, guild for Discord id: string; name: string; } interface Users { [id: string]: User; } interface MessageAttachment { name: string; permalink: string; } interface MessageContent { author: string; authorIcon?: string; pretext: string; title: string; titleLink: string; text: string; footer: string; borderColor?: string; } interface MessageReaction { name: string; count: number; userIds: string[]; } interface MessageReply { userId: string; timestamp: string; text?: string; attachment?: MessageAttachment; } interface MessageReplies { [timestamp: string]: MessageReply; } interface Message { timestamp: string; userId: string; text: string; isEdited?: Boolean; attachment?: MessageAttachment; content: MessageContent | undefined; reactions: MessageReaction[]; replies: MessageReplies; // TODO - add // subscribed (for threads) } interface ChannelMessages { [timestamp: string]: Message; } interface ChannelMessagesWithUndefined { [timestamp: string]: Message | undefined; } interface Messages { [channelId: string]: ChannelMessages; } const enum ChannelType { channel = "channel", group = "group", im = "im" } interface IContactMetadata { id: string; email: string; } interface Channel { id: string; name: string; type: ChannelType; readTimestamp: string | undefined; unreadCount: number; categoryName?: string; // for Discord contactMetadata?: IContactMetadata; // for Live Share DMs } interface ChannelLabel { channel: Channel; providerName: string; teamName: string; unread: number; label: string; presence: UserPresence; } const enum MessageType { text = "text", thread_reply = "thread_reply", command = "command", link = "link", internal = "internal" } interface ExtensionMessage { type: MessageType; text: string; } interface UIMessage { fontFamily: string; fontSize: string; provider: string; messages: ChannelMessages; users: Users; channel: Channel; currentUser: CurrentUser; statusText: string; // atMentions: User[]; } interface UIMessageDateGroup { groups: UIMessageGroup[]; date: string; } interface UIMessageGroup { messages: Message[]; userId: string; user: User; minTimestamp: string; key: string; } interface IStore { installationId: string | undefined; // TODO: remove undefined existingVersion: string | undefined; generateInstallationId: () => string; getCurrentUser: (provider: string) => CurrentUser | undefined; getCurrentUserForAll: () => CurrentUser[]; getUsers: (provider: string) => Users; getUser: (provider: string, userId: string) => User | undefined; getChannels: (provider: string) => Channel[]; getLastChannelId: (provider: string) => string | undefined; updateUsers: (provider: string, users: Users) => Thenable; updateUser: (provider: string, userId: string, user: User) => void; updateChannels: (provider: string, channels: Channel[]) => Thenable; updateCurrentUser: (provider: string, userInfo: CurrentUser | undefined) => Thenable; updateLastChannelId: (provider: string, channelId: string | undefined) => Thenable; clearProviderState: (provider: string) => Promise; updateExtensionVersion: (version: string) => Thenable; getMessageHistoryForChannel: (channelId: string) => ChannelMessages; updateMessageHistory: (channelId: string, messages: ChannelMessages) => Thenable; } interface IManager { isTokenInitialized: boolean; store: IStore; isAuthenticated: (provider: string) => boolean; getChannel: (provider: string, channelId: string | undefined) => Channel | undefined; getIMChannel: (provider: string, user: User) => Channel | undefined; getChannelLabels: (provider: string) => any; getUnreadCount: (provider: string, channel: Channel) => number; getCurrentUserFor: (provider: string) => CurrentUser | undefined; getUserPresence: (provider: string, userId: string) => UserPresence | undefined; getCurrentUserPresence: (provider: string) => UserPresence | undefined; updateAllUI: () => void; updateTreeViewsForProvider: (provider: string) => void; updateStatusItemsForProvider: (provider: string) => void; updateWebviewForProvider: (provider: string, channelId: string) => void; getMessages: (provider: string) => Messages; } interface IViewsManager { updateTreeViews: (provider: string) => void; updateWebview: (provider: string) => void; updateStatusItem: (provider: string, team: Team) => void; } interface ChatArgs { channelId?: string; user?: User; providerName: string; source: EventSource; } const enum EventSource { status = "status_item", command = "command_palette", activity = "activity_bar", info = "info_message", slash = "slash_command", vslsContacts = "vsls_contacts_panel", vslsStarted = "vsls_started" } const enum EventType { extensionInstalled = "extension_installed", viewOpened = "webview_opened", messageSent = "message_sent", vslsShared = "vsls_shared", vslsStarted = "vsls_started", vslsEnded = "vsls_ended", tokenConfigured = "token_configured", channelChanged = "channel_changed", authStarted = "auth_started", activationStarted = "activation_started", activationEnded = "activation_ended" } interface EventProperties { provider: string | undefined; source: EventSource | undefined; channel_type: ChannelType | undefined; } interface TelemetryEvent { type: EventType; time: Date; properties: EventProperties; } interface ChatTreeNode { label: string; channel: Channel | undefined; user: User | undefined; team: Team | undefined; isCategory: boolean; presence: UserPresence; providerName: string; } type InitialState = { provider: string; teamId: string | undefined; }; ================================================ FILE: src/uriHandler.ts ================================================ import * as vscode from "vscode"; import * as str from "./strings"; import IssueReporter from "./issues"; import { ConfigHelper } from "./config"; export class ExtensionUriHandler implements vscode.UriHandler { handleUri(uri: vscode.Uri): vscode.ProviderResult { // vscode://karigari.chat/redirect?url=foobar const { path, query } = uri; const parsed = this.parseQuery(query); const { token, msg, service, team } = parsed; switch (path) { case "/redirect": return ConfigHelper.setToken(token, service, team); case "/error": return this.showIssuePrompt(msg, service); } } showIssuePrompt(errorMsg: string, service: string) { const actionItems = [str.REPORT_ISSUE]; vscode.window .showWarningMessage(str.AUTH_FAILED_MESSAGE, ...actionItems) .then(selected => { switch (selected) { case str.REPORT_ISSUE: const issue = `Sign in with ${service} failed: ${errorMsg}`; IssueReporter.openNewIssue(issue, issue); } }); } parseQuery(queryString: string): any { // From https://stackoverflow.com/a/13419367 const filtered = queryString[0] === "?" ? queryString.substr(1) : queryString; const pairs = filtered.split("&"); var query: { [key: string]: string } = {}; for (var i = 0; i < pairs.length; i++) { var pair = pairs[i].split("="); const key: string = decodeURIComponent(pair[0]); const value: string = decodeURIComponent(pair[1] || ""); query[key] = value; } return query; } } ================================================ FILE: src/utils/index.ts ================================================ import * as vscode from "vscode"; import * as os from "os"; import { VSCodeCommands, EXTENSION_ID, VSLS_EXTENSION_PACK_ID, VSLS_EXTENSION_ID, VSLS_SPACES_EXTENSION_ID } from "../constants"; export const openUrl = (url: string) => { const parsedUrl = vscode.Uri.parse(url); return vscode.commands.executeCommand(VSCodeCommands.OPEN, parsedUrl); }; export const openSettings = () => { vscode.commands.executeCommand(VSCodeCommands.OPEN_SETTINGS); }; export const setVsContext = (name: string, value: boolean) => { return vscode.commands.executeCommand("setContext", name, value); }; export const getExtension = ( extensionId: string ): vscode.Extension | undefined => { return vscode.extensions.getExtension(extensionId); }; export interface Versions { os: string; extension: string; editor: string; } export const getExtensionVersion = (): string => { const extension = getExtension(EXTENSION_ID); return !!extension ? extension.packageJSON.version : undefined; }; export const getVersions = (): Versions => { return { os: `${os.type()} ${os.arch()} ${os.release()}`, extension: getExtensionVersion(), editor: vscode.version }; }; export const hasVslsExtensionPack = (): boolean => { return !!getExtension(VSLS_EXTENSION_PACK_ID); }; export const hasVslsExtension = (): boolean => { return !!getExtension(VSLS_EXTENSION_ID); }; export const hasVslsSpacesExtension = (): boolean => { return !!getExtension(VSLS_SPACES_EXTENSION_ID); } export const sanitiseTokenString = (token: string) => { const trimmed = token.trim(); const sansQuotes = trimmed.replace(/['"]+/g, ""); return sansQuotes; }; export function uuidv4(): string { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) { var r = (Math.random() * 16) | 0, v = c === "x" ? r : (r & 0x3) | 0x8; return v.toString(16); }); } export function isSuperset(set: Set, subset: Set): boolean { for (var elem of subset) { if (!set.has(elem)) { return false; } } return true; } export function difference(setA: Set, setB: Set) { var _difference = new Set(setA); for (var elem of setB) { _difference.delete(elem); } return _difference; } export function equals(setA: Set, setB: Set) { if (setA.size !== setB.size) { return false; } for (var a of setA) { if (!setB.has(a)) { return false; } } return true; } // User-defined type guard // https://github.com/Microsoft/TypeScript/issues/20707#issuecomment-351874491 export function notUndefined(x: T | undefined): x is T { return x !== undefined; } export function toTitleCase(str: string) { return str.replace(/\w\S*/g, function(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); } export function toDateString(date: Date) { // Returns ISO-format date string for a given date let month = (date.getMonth() + 1).toString(); let day = date.getDate().toString(); if (month.length === 1) { month = `0${month}`; } if (day.length === 1) { day = `0${day}`; } return `${date.getFullYear()}-${month}-${day}`; } export function camelCaseToTitle(text: string) { var result = text.replace(/([A-Z])/g, " $1"); return result.charAt(0).toUpperCase() + result.slice(1); } export function titleCaseToCamel(text: string) { var result = text.replace(/ /g, ""); return result.charAt(0).toLowerCase() + result.slice(1); } ================================================ FILE: src/utils/keychain.ts ================================================ // From https://github.com/Microsoft/vscode-pull-request-github/blob/master/src/common/keychain.ts import * as vscode from "vscode"; // keytar depends on a native module shipped in vscode, so this is // how we load it import * as keytarType from "keytar"; function getNodeModule(moduleName: string): T | undefined { const vscodeRequire = eval("require"); try { return vscodeRequire( `${vscode.env.appRoot}/node_modules.asar/${moduleName}` ); } catch (err) { // Not in ASAR. } try { return vscodeRequire(`${vscode.env.appRoot}/node_modules/${moduleName}`); } catch (err) { // Not available. } return undefined; } export const keychain = getNodeModule("keytar"); ================================================ FILE: src/vslsSpaces/gravatar-api.d.ts ================================================ // foo.d.ts declare module "gravatar-api"; ================================================ FILE: src/vslsSpaces/index.ts ================================================ import * as vscode from "vscode"; import * as gravatar from "gravatar-api"; import { VSLS_SPACES_EXTENSION_ID, SelfCommands } from "../constants"; import { getExtension } from "../utils"; interface IMessage { type: string; content: string; timestamp: string; sender: string; } interface IUser { name: string; email: string; } const toMessage = (msg: IMessage) => ({ timestamp: (Date.parse(msg.timestamp) / 1000.0).toString(), userId: msg.sender, text: msg.type === "info_message" ? `_${msg.content}_` : msg.content, content: undefined, reactions: [], replies: {} }); function sleep(ms: number) { return new Promise(resolve => setTimeout(resolve, ms)); } export class VslsSpacesProvider implements IChatProvider { isListenerSetup: boolean = false; currentUser: IUser | undefined; constructor() { // Waiting for the extension to get activated setTimeout(() => { this.setupListeners(); }, 5000); } setupListeners() { const extension = getExtension(VSLS_SPACES_EXTENSION_ID); if (extension && extension.isActive) { const exports = extension.exports; exports.setMessageCallback((data: any) => { this.onNewMessage(data); }); exports.setSpaceCallback((name: string) => { this.onNewSpace(name); }); exports.setClearMessagesCallback((name: string) => { this.onClearMessages(name); }); exports.setUserChangedCallback(({ name, email }: IUser) => { this.connect(); }); this.isListenerSetup = true; } } async getApi() { let extension = getExtension(VSLS_SPACES_EXTENSION_ID)!; if (extension.isActive) { if (!this.isListenerSetup) { this.setupListeners(); } return extension.exports; } else { await sleep(5000); // Give 5 secs for extension to activate extension = getExtension(VSLS_SPACES_EXTENSION_ID)!; return extension.exports; } } async connect(): Promise { const api = await this.getApi(); if (api) { const userInfo: IUser | undefined = api.getUserInfo(); if (userInfo) { const { name, email } = userInfo; this.currentUser = userInfo; return { id: email, name, teams: [], currentTeamId: undefined, provider: Providers.vslsSpaces }; } } } onNewMessage(data: any) { const { name, messages } = data; const chatMessages: Message[] = messages.map(toMessage); let channelMessages: ChannelMessages = {}; chatMessages.forEach(msg => { channelMessages[msg.timestamp] = msg; }); vscode.commands.executeCommand(SelfCommands.UPDATE_MESSAGES, { channelId: name, messages: channelMessages, provider: "vslsSpaces" }); } onNewSpace(spaceName: string) { vscode.commands.executeCommand(SelfCommands.VSLS_SPACE_JOINED, { name: spaceName }); } onClearMessages(spaceName: string) { vscode.commands.executeCommand(SelfCommands.CLEAR_MESSAGES, { channelId: spaceName, provider: "vslsSpaces" }); } isConnected(): boolean { return !!this.currentUser; } async sendMessage(text: string, currentUserId: string, channelId: string) { const api = await this.getApi(); api.sendMessage(channelId, text); } async fetchUsers(): Promise { const api = await this.getApi(); const users: User[] = api.getUsers().map(({ name, email }: any) => { const avatar = gravatar.imageUrl({ email, parameters: { size: "200", d: "retro" }, secure: true }); return { id: email, name, email, fullName: name, imageUrl: avatar, smallImageUrl: avatar, presence: UserPresence.available }; }); let usersToSend: Users = {}; users.forEach(u => { usersToSend[u.id] = u; }); return usersToSend; } async fetchUserInfo(userId: string): Promise { const users = await this.fetchUsers(); return users[userId]; } async fetchChannels(users: Users): Promise { const api = await this.getApi(); const spaces = api.getSpaces(); const channels: Channel[] = spaces.map((name: string) => ({ id: name, name, type: ChannelType.channel, readTimestamp: undefined, unreadCount: 0 })); return channels; } async loadChannelHistory(channelId: string) { const api = await this.getApi(); const messages: IMessage[] = await api.getChannelHistory(channelId); const chatMessages: Message[] = messages.map(toMessage); let channelMessages: ChannelMessages = {}; chatMessages.forEach(msg => { channelMessages[msg.timestamp] = msg; }); return channelMessages; } subscribePresence(users: Users) {} getUserPreferences(): Promise { return Promise.resolve({}); } async validateToken(): Promise { return; } async fetchChannelInfo(channel: Channel): Promise { return undefined; } async markChannel( channel: Channel, ts: string ): Promise { return undefined; } async fetchThreadReplies( channelId: string, ts: string ): Promise { return undefined; } async sendThreadReply( text: string, currentUserId: string, channelId: string, parentTimestamp: string ) {} async updateSelfPresence( presence: UserPresence, durationInMinutes: number ) { return undefined; } async createIMChannel(user: User): Promise { return undefined; } async destroy() {} async sendTyping(currentUserId: string, channelId: string) { } } ================================================ FILE: src/webview/index.ts ================================================ import * as vscode from "vscode"; import * as path from "path"; import { toDateString } from "../utils"; const SAME_GROUP_TIME = 5 * 60; // seconds interface MessageWithUnread extends Message { isUnread: boolean; } export default class WebviewContainer { panel: vscode.WebviewPanel; constructor( extensionPath: string, private onDidDispose: () => void, private onDidChangeViewState: (isVisible: Boolean) => void ) { const baseVuePath = path.join(extensionPath, "static"); const staticPath = vscode.Uri.file(baseVuePath).with({ scheme: "vscode-resource" }); this.panel = vscode.window.createWebviewPanel( "chatPanel", "Chat", vscode.ViewColumn.Beside, { enableScripts: true, retainContextWhenHidden: true, localResourceRoots: [vscode.Uri.file(baseVuePath)] } ); this.panel.webview.html = getWebviewContent(staticPath.toString()); // Handle on did dispose for webview panel this.panel.onDidDispose(() => this.onDidDispose()); // Handle tab switching event this.panel.onDidChangeViewState(event => { const { visible } = event.webviewPanel; this.onDidChangeViewState(visible); }); } setMessageHandler(msgHandler: (message: ExtensionMessage) => void) { this.panel.webview.onDidReceiveMessage((message: ExtensionMessage) => msgHandler(message) ); } update(uiMessage: UIMessage) { const { messages, users, channel, currentUser } = uiMessage; const annotated = this.getAnnotatedMessages(messages, channel, currentUser); const groups = this.getMessageGroups(annotated, users); this.panel.webview.postMessage({ ...uiMessage, messages: groups }); this.panel.title = !!channel ? channel.name : ""; } reveal() { this.panel.reveal(); } getAnnotatedMessages( messages: ChannelMessages, channel: Channel, currentUser: CurrentUser ): ChannelMessages { if (!!channel) { // Annotates every message with isUnread (boolean) const { readTimestamp } = channel; let result: { [ts: string]: MessageWithUnread } = {}; Object.keys(messages).forEach(ts => { const message = messages[ts]; const isDifferentUser = message.userId !== currentUser.id; const isUnread = !!readTimestamp && isDifferentUser && +ts > +readTimestamp; result[ts] = { ...message, isUnread }; }); return result; } else { return messages; } } getMessageGroups(input: ChannelMessages, users: Users): UIMessageDateGroup[] { let result: { [date: string]: ChannelMessages } = {}; Object.keys(input).forEach(ts => { const date = new Date(+ts * 1000); const dateStr = toDateString(date); if (!(dateStr in result)) { result[dateStr] = {}; } result[dateStr][ts] = input[ts]; }); return Object.keys(result) .sort((a, b) => a.localeCompare(b)) .map(date => { const messages = result[date]; const groups = this.getMessageGroupsForDate(messages, users); return { groups, date }; }); } getMessageGroupsForDate( input: ChannelMessages, users: Users ): UIMessageGroup[] { const timestamps = Object.keys(input).sort((a, b) => +a - +b); // ascending const initial = { current: {}, groups: [] }; const result = timestamps.reduce((accumulator: any, ts) => { const { current, groups } = accumulator; const message = input[ts]; const isSameUser = current.userId ? message.userId === current.userId : false; const isSameTime = current.ts ? +ts - +current.ts < SAME_GROUP_TIME : false; if (isSameUser && isSameTime) { return { groups, current: { ...current, ts, messages: [...current.messages, message] } }; } else { const currentGroup = { messages: [message], userId: message.userId, user: users[message.userId], minTimestamp: ts, ts, key: ts }; return { groups: current.ts ? [...groups, current] : [...groups], current: currentGroup }; } }, initial); const { current, groups } = result; return current.ts ? [...groups, current] : groups; } isVisible() { return this.panel.visible; } } function getWebviewContent(staticPath: string) { return ` Chat
`; } ================================================ FILE: tsconfig.json ================================================ { "compilerOptions": { "module": "commonjs", "target": "es2017", "outDir": "out", "lib": ["es6", "esnext"], "sourceMap": true, "rootDir": "src", /* Strict Type-Checking Option */ "strict": true, /* Added to compile vsls contact protocol */ "experimentalDecorators": true, "strictPropertyInitialization": false }, "exclude": [ "node_modules", ".vscode-test", "out/**", "static", "scripts", "oauth-service" ] } ================================================ FILE: tslint.json ================================================ { "rules": { "no-string-throw": true, "no-unused-expression": true, "no-duplicate-variable": true, "curly": true, "class-name": true, "triple-equals": true }, "defaultSeverity": "warning" } ================================================ FILE: webpack.config.js ================================================ //@ts-check const path = require("path"); const webpack = require("webpack"); /** @type webpack.Configuration */ const config = { entry: "./src/extension.ts", mode: "production", devtool: "source-map", target: "node", module: { rules: [ { test: /\.ts$/, use: "ts-loader" } ] }, resolve: { extensions: [".ts", ".js", ".json"] }, output: { filename: "extension.js", path: path.resolve(__dirname, "out"), libraryTarget: "commonjs2" }, externals: { vscode: "commonjs vscode" } }; module.exports = config; ================================================ FILE: webview/.gitignore ================================================ .DS_Store node_modules /dist # local env files .env.local .env.*.local # Log files npm-debug.log* yarn-debug.log* yarn-error.log* # Editor directories and files .idea .vscode *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: webview/README.md ================================================ # webview The webview is built on Vue 2.x. You might need to install `@vue/cli` globally to build this. ``` yarn build ``` This can be also be triggered from the root directory -- and this needs to be done everytime the webview is changed. ``` npm run webview ``` ================================================ FILE: webview/babel.config.js ================================================ module.exports = { presets: [ '@vue/app' ] } ================================================ FILE: webview/package.json ================================================ { "name": "webview", "version": "0.1.0", "private": true, "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lint": "vue-cli-service lint" }, "dependencies": { "core-js": "^2.6.5", "markdown-it": "^10.0.0", "markdown-it-slack": "^1.2.0", "tributejs": "^3.7.3", "vue": "^2.6.10", "vue-tribute": "^1.0.3" }, "devDependencies": { "@vue/cli-plugin-babel": "^3.11.0", "@vue/cli-plugin-eslint": "^3.11.0", "@vue/cli-service": "^3.11.0", "babel-eslint": "^10.0.1", "eslint": "^5.16.0", "eslint-plugin-vue": "^5.0.0", "vue-template-compiler": "^2.6.10" }, "eslintConfig": { "root": true, "env": { "node": true }, "extends": [ "plugin:vue/essential", "eslint:recommended" ], "rules": { "no-console": "off", "no-unused-vars": "off" }, "parserOptions": { "parser": "babel-eslint" } }, "postcss": { "plugins": { "autoprefixer": {} } }, "browserslist": [ "> 1%", "last 2 versions" ] } ================================================ FILE: webview/src/App.vue ================================================ ================================================ FILE: webview/src/components/DateSeparator.vue ================================================ ================================================ FILE: webview/src/components/FormSection.vue ================================================ ================================================ FILE: webview/src/components/MarkdownElement.vue ================================================ ================================================ FILE: webview/src/components/MessageAuthor.vue ================================================ ================================================ FILE: webview/src/components/MessageContent.vue ================================================ ================================================ FILE: webview/src/components/MessageGroup.vue ================================================ ================================================ FILE: webview/src/components/MessageInput.vue ================================================ ================================================ FILE: webview/src/components/MessageItem.vue ================================================ ================================================ FILE: webview/src/components/MessageReaction.vue ================================================ ================================================ FILE: webview/src/components/MessageReactions.vue ================================================ ================================================ FILE: webview/src/components/MessageReplies.vue ================================================ ================================================ FILE: webview/src/components/MessageRepliesImages.vue ================================================ ================================================ FILE: webview/src/components/MessageReplyItem.vue ================================================ ================================================ FILE: webview/src/components/MessageTitle.vue ================================================ ================================================ FILE: webview/src/components/MessagesDateGroup.vue ================================================ ================================================ FILE: webview/src/components/MessagesSection.vue ================================================ ================================================ FILE: webview/src/components/StatusText.vue ================================================ ================================================ FILE: webview/src/components/UserInfo.vue ================================================ ================================================ FILE: webview/src/main.js ================================================ import Vue from 'vue' import App from './App.vue' var app = new Vue({ template: ` `, props: ['data'], components: { App }, el: '#app', }) window.addEventListener('message', event => { app.data = event.data; }) ================================================ FILE: webview/src/utils.js ================================================ export const vscode = acquireVsCodeApi(); export function sendMessage(text, type) { vscode.postMessage({ type, text }); } export function formattedTime(ts) { const d = new Date(+ts * 1000); return d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); } export function openLink(href) { return sendMessage(href, "link"); } ================================================ FILE: webview/vue.config.js ================================================ module.exports = { publicPath: './', // This is required to serve build output w/o an HTTP server runtimeCompiler: true, // This is required to be able to use template tags filenameHashing: false, // Pin names so we can import them easiy outputDir: '../static' }