diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index dd85ed699b76..d6d6abd54ed1 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -1,42 +1,253 @@ # Contributing to Rocket.Chat -:+1::tada: First off, thanks for taking the time to contribute! :tada::+1: +**First off, thanks for taking the time to contribute! :tada::+1:** -The following is a set of guidelines for contributing to Rocket.Chat and its packages, which are hosted in the [Rocket.Chat Organization](https://github.com/RocketChat) on GitHub. +> There are many ways to contribute to Rocket.Chat even if you're not technical or a developer: +> +> * Email us at marketing@rocket.chat to tell us how much you love the project +> * Write about us in your blogs +> * Fix some small typos in our [documentation](https://docs.rocket.chat/contributing) +> * Become our [GitHub sponsor](https://github.com/sponsors/RocketChat) +> * Tell others about us and help us spread the word +> +> Every bit of contribution is appreciated 🙂 thank you! + +The following is a set of guidelines for contributing to Rocket.Chat, which are hosted in the [Rocket.Chat Organization](https://github.com/RocketChat) on GitHub. __Note:__ If there's a feature you'd like, there's a bug you'd like to fix, or you'd just like to get involved please raise an issue and start a conversation. We'll help as much as we can so you can get contributing - although we may not always be able to respond right away :) -## ECMAScript 2015 vs CoffeeScript +## Setup + +Your development workstation needs to have at least 8GB or RAM to be able to build the Rocket.Chat's source code. + +Rocket.Chat runs on top of [Meteor](https://www.meteor.com/). To run it on development mode you need to [install Meteor](https://www.meteor.com/install) and clone/download the Rocket.Chat's code, then just open the code folder and run: +```shell +meteor npm install && meteor +``` +It should build and run the application and database for you, now you can access the UI on (http://localhost:3000) + +It's not necessary to install Nodejs or NPM, every time you need to use them you can run `meteor node` or `meteor npm`. + +It's important to always run the NPM commands using `meteor npm` to ensure that you are installing the modules using the right Nodejs version. + +## Coding + +We provide a [.editorconfig](../.editorconfig) file that will help you to keep some standards in place. + +### ECMAScript vs TypeScript + +We are currently adopting TypeScript as the default language on our projects, the current codebase will be migrated incrementally from JavaScript to TypeScript. + +While we still have a lot of JavaScript files you should not create new ones. As much as possible new code contributions should be in **TypeScript**. -While we still have a lot of CoffeeScript files you should not create new ones. New code contributions should be in **ECMAScript 2015**. +### Blaze vs React -## Coding standards +We are currently adopting React over Blaze as our UI engine, the current codebase is under migration and will continue. You will still find Blaze templates in our code. Code changes or contributions may need to be made in Blaze while we continue to evolve our components library. -Most of the coding standards are covered by `.editorconfig` and `.eslintrc.js`. +[Fuselage](https://github.com/RocketChat/Rocket.Chat.Fuselage) is our component library based on React, check it out when contributing to the Rocket.Chat UI and feel free to contribute new components or fixes. + +### Standards + +Most of the coding standards are covered by ESLint configured at [.eslintrc](../.eslintrc), and most of them came from our own [ESLint Config Package](https://github.com/RocketChat/eslint-config-rocketchat). Things not covered by `eslint`: -* `exports`/`module.exports` should be at the end of the file -* Longer, descriptive variable names are preferred, e.g. `error` vs `err` +* Prefer longer/descriptive variable names, e.g. `error` vs `err`, unless dealing with common record properties already shortened, e.g. `rid` and `uid` +* Use return early pattern. [See more](https://blog.timoxley.com/post/47041269194/avoid-else-return-early) +* Prefer `Promise` over `callbacks` +* Prefer `await` over `then/catch` +* Don't create queries outside models, the query description should be inside the model class. +* Don't hardcode fields inside models. Same method can be used for different purposes, using different fields. +* Prefer create REST endpoints over Meteor methods +* Prefer call REST endpoints over Meteor methods when both are available +* v1 REST endpoints should follow the following pattern: `/api/v1/dashed-namespace.camelCaseAction` +* Prefer TypeScript over JavaScript. Check [ECMAScript vs TypeScript](#ecmascript-vs-typescript) -We acknowledge all the code does not meet these standards but we are working to change this over time. +#### Blaze +* Import the HTML file from it's sibling JS/TS file ### Syntax check Before submitting a PR you should get no errors on `eslint`. -To check your files, first install `eslint`: +To check your files run: + +```shell +meteor npm run lint +``` + +## Tests + +There are 2 types of tests we run on Rocket.Chat, **Unit** tests and **End to End** tests. The major difference is that End to End tests require a Rocket.Chat instance running to execute the API and UI checks. + +### End to End Tests + +First you need to run a Rocket.Chat server on **Test Mode** and on a **Empty Database**: +```shell +# Running with a local mongodb database +MONGO_URL=mongodb://localhost/empty MONGO_OPLOG_URL=mongodb://localhost/local TEST_MODE=true meteor +``` +```shell +# Running with a local mongodb database but cleaning it before +mongo --eval "db.dropDatabase()" empty && MONGO_URL=mongodb://localhost/empty MONGO_OPLOG_URL=mongodb://localhost/local TEST_MODE=true meteor +``` + +Now you can run the tests: +```shell +meteor npm test +``` + +### Unit Tests + +Unit tests are simpler to setup and run. They do not require a working Rocket.Chat instance. +```shell +meteor npm run testunit +``` + +It's possible to run on watch mode as well: +```shell +meteor npm run testunit-watch +``` + + + +## Before Push your code + +It's important to run the lint and tests before push your code or submit a Pull Request, otherwise your contribution may fail quickly on the CI. Reviewers are forced to demand fixes and the review of your contribution will be further delayed. + +Rocket.Chat uses [husky](https://www.npmjs.com/package/husky) to run the **lint** and **unit tests** before proceed to the code push process, so you may notice a delay when pushing your code to your repository. + +## Choosing a good PR title + +It is very important to note that we use PR titles when creating our change log. Keep this in mind when you title your PR. Make sure the title makes sense to a person reading a releases' change log! + +Keep your PR's title as short and concise as possible, use PR's description section, which you can find in the PR's template, to provide more details into the changelog. + +Good titles require thinking from a user's point of view. Don't get technical and talk code or architecture. What is the actual user-facing feature or the bug fixed? For example: + +``` +[NEW] Allow search permissions and settings by name instead of only ID +``` + +Even it's being something new in the code the users already expect the filter to filter by what they see (translations), a better one would be: + +``` +[FIX] Permissions' search doesn't filter base on presented translation, only on internal ids +``` + +## Choosing the right PR tag + +You can use several tags do describe your PR, i.e.: `[FIX]`, `[NEW]`, etc. You can use the descriptions below to better understand the meaning of each one, and decide which one you should use: + +### `[NEW]` + +#### When +- When adding a new feature that is important to the end user + +#### How + +Do not start repeating the section (`Add ...` or `New ...`) +Always describe what's being fixed, improved or added and not *how* it was fixed, improved or added. + +Exemple of **bad** PR titles: + +``` +[NEW] Add ability to set tags in the Omnichannel room closing dialog +[NEW] Adds ability for Rocket.Chat Apps to create discussions +[NEW] Add MMS support to Voxtelesys +[NEW] Add Color variable to left sidebar +``` + +Exemple of **good** PR titles: ``` -npm install -g eslint +[NEW] Ability to set tags in the Omnichannel room closing dialog +[NEW] Ability for Rocket.Chat Apps to create discussions +[NEW] MMS support to Voxtelesys +[NEW] Color variable to left sidebar ``` -Then run: +### `[FIX]` + +#### When +- When fixing something not working or behaving wrong from the end user perspective + +#### How + +Always describe what's being fixed and not *how* it was fixed. + +Exemple of a **bad** PR title: ``` -eslint . +[FIX] Add Content-Type for public files with JWT ``` -# Contributor License Agreement +Exemple of a **good** PR title: + +``` +[FIX] Missing Content-Type header for public files with JWT +``` + +### `[IMPROVE]` + +#### When +- When a change enhances a not buggy behavior. When in doubt if it's a Improve or Fix prefer to use as fix. + +#### How +Always describe what's being improved and not *how* it was improved. + +Exemple of **good** PR title: + +``` +[IMPROVE] Displays Nothing found on admin sidebar when search returns nothing +``` + +### `[BREAK]` + +#### When +- When the changes affect a working feature + +##### Back-End +- When the API contract (data structure and endpoints) are limited, expanded as required or removed +- When the business logic (permissions and roles) are limited, expanded (without migration) or removed + +##### Front-End +- When the change limits (format, size, etc) or removes the ability of read or change the data (when the limitation was not caused by the back-end) + +### Second tag e.g. `[NEW][ENTERPRISE]` + +Use a second tag to group entries on the change log, we currently use it only for the Enterprise items but we are going to expand it's usage soon, please do not use it until we create a patter for it. + +### Minor Changes + +For those PRs that aren't important for the end user, we are working on a better pattern, but for now please use the same tags, use them without the brackets and in camel case: + +``` +Fix: Missing Content-Type header for public files with JWT +``` + +All those PRs will be grouped under the `Minor changes` section which is collapsed, so users can expand it to check for those minor things but they are not visible directly on changelog. + +## Security Best Practices + +- Never expose unnecessary data to the APIs' responses +- Always check for permissions or create new ones when you must expose sensitive data +- Never provide new APIs without rate limiters +- Always escape the user's input when rendering data +- Always limit the user's input size on server side +- Always execute the validations on the server side even when executing on the client side as well + +## Performance Best Practices + +- Prefer inform the fields you want, and only the necessary ones, when querying data from database over query the full documents +- Limit the number of returned records to a reasonable value +- Check if the query is using indexes, it it's not create new indexes +- Prefer queues over long executions +- Create new metrics to mesure things whenever possible +- Cache data and returns whenever possible + +## Contributor License Agreement + +To have your contribution accepted you must sign our [Contributor License Agreement](https://cla-assistant.io/RocketChat/Rocket.Chat). In case you submit a Pull Request before sign the CLA GitHub will alert you with a new comment asking you to sign and will block the Pull Request from be merged by us. Please review and sign our CLA at https://cla-assistant.io/RocketChat/Rocket.Chat diff --git a/.github/workflows/build_and_test.yml b/.github/workflows/build_and_test.yml index 2d74d00f0e17..bf8c1bed7ff9 100644 --- a/.github/workflows/build_and_test.yml +++ b/.github/workflows/build_and_test.yml @@ -227,7 +227,7 @@ jobs: MONGO_URL: mongodb://localhost:27017/rocketchat MONGO_OPLOG_URL: mongodb://localhost:27017/local run: | - for i in $(seq 1 5); do (docker exec mongo mongo rocketchat --eval 'db.dropDatabase()') && xvfb-run --auto-servernum npm test && s=0 && break || s=$? && sleep 1; done; (exit $s) + for i in $(seq 1 5); do (docker exec mongo mongo rocketchat --eval 'db.dropDatabase()') && xvfb-run --auto-servernum npm run testci && s=0 && break || s=$? && sleep 1; done; (exit $s) # notification: # runs-on: ubuntu-latest diff --git a/.scripts/start.js b/.scripts/start.js index aa9e3b334757..1159290bbbb9 100644 --- a/.scripts/start.js +++ b/.scripts/start.js @@ -112,7 +112,7 @@ function startChimp() { startProcess({ name: 'Chimp', command: 'npm', - params: ['run', 'testci'], + params: ['test'], // command: 'exit', // params: ['2'], options: { diff --git a/app/apps/server/bridges/internal.js b/app/apps/server/bridges/internal.js index ef883a68437f..db6671541907 100644 --- a/app/apps/server/bridges/internal.js +++ b/app/apps/server/bridges/internal.js @@ -6,6 +6,10 @@ export class AppInternalBridge { } getUsernamesOfRoomById(roomId) { + if (!roomId) { + return []; + } + const records = Subscriptions.findByRoomIdWhenUsernameExists(roomId, { fields: { 'u.username': 1, diff --git a/app/apps/server/bridges/listeners.js b/app/apps/server/bridges/listeners.js index 259b937b1686..c3d481da7386 100644 --- a/app/apps/server/bridges/listeners.js +++ b/app/apps/server/bridges/listeners.js @@ -1,10 +1,53 @@ -import { AppInterface } from '@rocket.chat/apps-engine/server/compiler'; +import { AppInterface } from '@rocket.chat/apps-engine/definition/metadata'; export class AppListenerBridge { constructor(orch) { this.orch = orch; } + async handleEvent(event, ...payload) { + const method = (() => { + switch (event) { + case AppInterface.IPreMessageSentPrevent: + case AppInterface.IPreMessageSentExtend: + case AppInterface.IPreMessageSentModify: + case AppInterface.IPostMessageSent: + case AppInterface.IPreMessageDeletePrevent: + case AppInterface.IPostMessageDeleted: + case AppInterface.IPreMessageUpdatedPrevent: + case AppInterface.IPreMessageUpdatedExtend: + case AppInterface.IPreMessageUpdatedModify: + case AppInterface.IPostMessageUpdated: + return 'messageEvent'; + case AppInterface.IPreRoomCreatePrevent: + case AppInterface.IPreRoomCreateExtend: + case AppInterface.IPreRoomCreateModify: + case AppInterface.IPostRoomCreate: + case AppInterface.IPreRoomDeletePrevent: + case AppInterface.IPostRoomDeleted: + case AppInterface.IPreRoomUserJoined: + case AppInterface.IPostRoomUserJoined: + return 'roomEvent'; + case AppInterface.IPostExternalComponentOpened: + case AppInterface.IPostExternalComponentClosed: + return 'externalComponentEvent'; + /** + * @deprecated please prefer the AppInterface.IPostLivechatRoomClosed event + */ + case AppInterface.ILivechatRoomClosedHandler: + case AppInterface.IPostLivechatRoomStarted: + case AppInterface.IPostLivechatRoomClosed: + case AppInterface.IPostLivechatAgentAssigned: + case AppInterface.IPostLivechatAgentUnassigned: + return 'livechatEvent'; + case AppInterface.IUIKitInteractionHandler: + return 'uiKitInteractionEvent'; + } + })(); + + return this[method](event, ...payload); + } + async messageEvent(inte, message) { const msg = this.orch.getConverters().get('messages').convertMessage(message); const result = await this.orch.getManager().getListenerManager().executeListener(inte, msg); @@ -13,56 +56,44 @@ export class AppListenerBridge { return result; } return this.orch.getConverters().get('messages').convertAppMessage(result); - - // try { - - // } catch (e) { - // this.orch.debugLog(`${ e.name }: ${ e.message }`); - // this.orch.debugLog(e.stack); - // } } - async roomEvent(inte, room) { + async roomEvent(inte, room, ...payload) { const rm = this.orch.getConverters().get('rooms').convertRoom(room); - const result = await this.orch.getManager().getListenerManager().executeListener(inte, rm); + + const params = (() => { + switch (inte) { + case AppInterface.IPreRoomUserJoined: + case AppInterface.IPostRoomUserJoined: + const [joiningUser, invitingUser] = payload; + return { + room: rm, + joiningUser: this.orch.getConverters().get('users').convertToApp(joiningUser), + invitingUser: this.orch.getConverters().get('users').convertToApp(invitingUser), + }; + default: + return rm; + } + })(); + + const result = await this.orch.getManager().getListenerManager().executeListener(inte, params); if (typeof result === 'boolean') { return result; } return this.orch.getConverters().get('rooms').convertAppRoom(result); - - // try { - - // } catch (e) { - // this.orch.debugLog(`${ e.name }: ${ e.message }`); - // this.orch.debugLog(e.stack); - // } } async externalComponentEvent(inte, externalComponent) { - const result = await this.orch.getManager().getListenerManager().executeListener(inte, externalComponent); - - return result; + return this.orch.getManager().getListenerManager().executeListener(inte, externalComponent); } async uiKitInteractionEvent(inte, action) { return this.orch.getManager().getListenerManager().executeListener(inte, action); - - // try { - - // } catch (e) { - // this.orch.debugLog(`${ e.name }: ${ e.message }`); - // this.orch.debugLog(e.stack); - // } } async livechatEvent(inte, data) { switch (inte) { - case AppInterface.IPostLivechatRoomStarted: - case AppInterface.IPostLivechatRoomClosed: - const room = this.orch.getConverters().get('rooms').convertRoom(data); - - return this.orch.getManager().getListenerManager().executeListener(inte, room); case AppInterface.IPostLivechatAgentAssigned: case AppInterface.IPostLivechatAgentUnassigned: return this.orch.getManager().getListenerManager().executeListener(inte, { @@ -70,7 +101,9 @@ export class AppListenerBridge { agent: this.orch.getConverters().get('users').convertToApp(data.user), }); default: - break; + const room = this.orch.getConverters().get('rooms').convertRoom(data); + + return this.orch.getManager().getListenerManager().executeListener(inte, room); } } } diff --git a/app/apps/server/converters/rooms.js b/app/apps/server/converters/rooms.js index 8c8aedbe1448..001ca0de6cbb 100644 --- a/app/apps/server/converters/rooms.js +++ b/app/apps/server/converters/rooms.js @@ -116,6 +116,7 @@ export class AppRoomsConverter { customFields: 'customFields', isWaitingResponse: 'waitingResponse', isOpen: 'open', + _USERNAMES: '_USERNAMES', isDefault: (room) => { const result = !!room.default; delete room.default; diff --git a/app/apps/server/index.js b/app/apps/server/index.js index aa24a2d78926..ad3096af3158 100644 --- a/app/apps/server/index.js +++ b/app/apps/server/index.js @@ -1,3 +1,3 @@ import './cron'; -export { Apps } from './orchestrator'; +export { Apps, AppEvents } from './orchestrator'; diff --git a/app/apps/server/orchestrator.js b/app/apps/server/orchestrator.js index da9fca47fe61..2034b02ad13e 100644 --- a/app/apps/server/orchestrator.js +++ b/app/apps/server/orchestrator.js @@ -1,5 +1,7 @@ -import { Meteor } from 'meteor/meteor'; +import { EssentialAppDisabledException } from '@rocket.chat/apps-engine/definition/exceptions'; +import { AppInterface } from '@rocket.chat/apps-engine/definition/metadata'; import { AppManager } from '@rocket.chat/apps-engine/server/AppManager'; +import { Meteor } from 'meteor/meteor'; import { Logger } from '../../logger'; import { AppsLogsModel, AppsModel, AppsPersistenceModel, Permissions } from '../../models'; @@ -16,7 +18,6 @@ function isTesting() { return process.env.TEST_MODE === 'true'; } - class AppServerOrchestrator { constructor() { this._isInitialized = false; @@ -155,8 +156,23 @@ class AppServerOrchestrator { return this._manager.updateAppsMarketplaceInfo(apps) .then(() => this._manager.get()); } + + async triggerEvent(event, ...payload) { + if (!this.isLoaded()) { + return; + } + + return this.getBridges().getListenerBridge().handleEvent(event, ...payload).catch((error) => { + if (error instanceof EssentialAppDisabledException) { + throw new Meteor.Error('error-essential-app-disabled'); + } + + throw error; + }); + } } +export const AppEvents = AppInterface; export const Apps = new AppServerOrchestrator(); settings.addGroup('General', function() { diff --git a/app/chatpal-search/server/provider/provider.js b/app/chatpal-search/server/provider/provider.js index 18ee9a36f42b..6ce02e17b8f6 100644 --- a/app/chatpal-search/server/provider/provider.js +++ b/app/chatpal-search/server/provider/provider.js @@ -3,6 +3,7 @@ import { Meteor } from 'meteor/meteor'; import { searchProviderService, SearchProvider } from '../../../search/server'; import ChatpalLogger from '../utils/logger'; import { Subscriptions } from '../../../models'; +import { baseUrl } from '../utils/settings'; import Index from './index'; @@ -16,7 +17,9 @@ class ChatpalProvider extends SearchProvider { constructor() { super('chatpalProvider'); - this.chatpalBaseUrl = 'https://beta.chatpal.io/v1'; + this.chatpalBaseUrl = `${ baseUrl }`; + + ChatpalLogger.debug(`Using ${ this.chatpalBaseUrl } as chatpal base url`); this._settings.add('Backend', 'select', 'cloud', { values: [ @@ -220,24 +223,24 @@ class ChatpalProvider extends SearchProvider { if (this._settings.get('Backend') === 'cloud') { config.baseurl = this.chatpalBaseUrl; config.language = this._settings.get('Main_Language'); - config.searchpath = '/search/search'; - config.updatepath = '/search/update'; - config.pingpath = '/search/ping'; - config.clearpath = '/search/clear'; - config.suggestionpath = '/search/suggest'; + config.searchpath = 'search/search'; + config.updatepath = 'search/update'; + config.pingpath = 'search/ping'; + config.clearpath = 'search/clear'; + config.suggestionpath = 'search/suggest'; config.httpOptions = { headers: { 'X-Api-Key': this._settings.get('API_Key'), }, }; } else { - config.baseurl = this._settings.get('Base_URL').endsWith('/') ? this._settings.get('Base_URL').slice(0, -1) : this._settings.get('Base_URL'); + config.baseurl = this._settings.get('Base_URL').replace(/\/?$/, '/'); config.language = this._settings.get('Main_Language'); - config.searchpath = '/chatpal/search'; - config.updatepath = '/chatpal/update'; - config.pingpath = '/chatpal/ping'; - config.clearpath = '/chatpal/clear'; - config.suggestionpath = '/chatpal/suggest'; + config.searchpath = 'chatpal/search'; + config.updatepath = 'chatpal/update'; + config.pingpath = 'chatpal/ping'; + config.clearpath = 'chatpal/clear'; + config.suggestionpath = 'chatpal/suggest'; config.httpOptions = { headers: this._parseHeaders(), }; diff --git a/app/chatpal-search/server/utils/settings.js b/app/chatpal-search/server/utils/settings.js new file mode 100644 index 000000000000..a1450bc16b6d --- /dev/null +++ b/app/chatpal-search/server/utils/settings.js @@ -0,0 +1 @@ +export const baseUrl = (process.env.CHATPAL_URL || 'https://api.chatpal.io/v1').replace(/\/?$/, '/'); diff --git a/app/chatpal-search/server/utils/utils.js b/app/chatpal-search/server/utils/utils.js index 91b1ffe64f22..5707ca59b15c 100644 --- a/app/chatpal-search/server/utils/utils.js +++ b/app/chatpal-search/server/utils/utils.js @@ -1,10 +1,12 @@ import { Meteor } from 'meteor/meteor'; import { HTTP } from 'meteor/http'; +import { baseUrl } from './settings'; + Meteor.methods({ 'chatpalUtilsCreateKey'(email) { try { - const response = HTTP.call('POST', 'https://beta.chatpal.io/v1/account', { data: { email, tier: 'free' } }); + const response = HTTP.call('POST', `${ baseUrl }account`, { data: { email, tier: 'free' } }); if (response.statusCode === 201) { return response.data.key; } @@ -15,7 +17,7 @@ Meteor.methods({ }, 'chatpalUtilsGetTaC'(lang) { try { - const response = HTTP.call('GET', `https://beta.chatpal.io/v1/terms/${ lang }.html`); + const response = HTTP.call('GET', `${ baseUrl }terms/${ lang }.html`); if (response.statusCode === 200) { return response.content; } diff --git a/app/lib/server/functions/addUserToRoom.js b/app/lib/server/functions/addUserToRoom.js index 1e9878aadcd6..77627bba2585 100644 --- a/app/lib/server/functions/addUserToRoom.js +++ b/app/lib/server/functions/addUserToRoom.js @@ -1,8 +1,10 @@ +import { AppsEngineException } from '@rocket.chat/apps-engine/definition/exceptions'; import { Meteor } from 'meteor/meteor'; -import { Rooms, Subscriptions, Messages } from '../../../models'; +import { AppEvents, Apps } from '../../../apps/server'; import { callbacks } from '../../../callbacks'; -import { roomTypes, RoomMemberActions } from '../../../utils/server'; +import { Messages, Rooms, Subscriptions } from '../../../models'; +import { RoomMemberActions, roomTypes } from '../../../utils/server'; export const addUserToRoom = function(rid, user, inviter, silenced) { const now = new Date(); @@ -27,6 +29,14 @@ export const addUserToRoom = function(rid, user, inviter, silenced) { callbacks.run('beforeJoinRoom', user, room); } + Promise.await(Apps.triggerEvent(AppEvents.IPreRoomUserJoined, room, user, inviter).catch((error) => { + if (error instanceof AppsEngineException) { + throw new Meteor.Error('error-app-prevented', error.message); + } + + throw error; + })); + Subscriptions.createWithRoomAndUser(room, user, { ts: now, open: true, @@ -59,6 +69,8 @@ export const addUserToRoom = function(rid, user, inviter, silenced) { // Keep the current event callbacks.run('afterJoinRoom', user, room); + + Apps.triggerEvent(AppEvents.IPostRoomUserJoined, room, user, inviter); }); } diff --git a/app/lib/server/functions/createDirectRoom.js b/app/lib/server/functions/createDirectRoom.js index 5474e2d67473..31702b2e96ba 100644 --- a/app/lib/server/functions/createDirectRoom.js +++ b/app/lib/server/functions/createDirectRoom.js @@ -1,7 +1,12 @@ +import { AppsEngineException } from '@rocket.chat/apps-engine/definition/exceptions'; +import { Meteor } from 'meteor/meteor'; + +import { Apps } from '../../../apps/server'; +import { callbacks } from '../../../callbacks/server'; import { Rooms, Subscriptions } from '../../../models/server'; import { settings } from '../../../settings/server'; import { getDefaultSubscriptionPref } from '../../../utils/server'; -import { callbacks } from '../../../callbacks/server'; + const generateSubscription = (fname, name, user, extra) => ({ alert: false, @@ -40,7 +45,7 @@ export const createDirectRoom = function(members, roomExtraData = {}, options = const isNewRoom = !room; - const rid = room?._id || Rooms.insert({ + const roomInfo = { ...uids.length === 2 && { _id: uids.join('') }, // Deprecated: using users' _id to compose the room _id is deprecated t: 'd', usernames, @@ -49,7 +54,34 @@ export const createDirectRoom = function(members, roomExtraData = {}, options = ts: new Date(), uids, ...roomExtraData, - }); + }; + + if (isNewRoom) { + roomInfo._USERNAMES = usernames; + + const prevent = Promise.await(Apps.triggerEvent('IPreRoomCreatePrevent', roomInfo).catch((error) => { + if (error instanceof AppsEngineException) { + throw new Meteor.Error('error-app-prevented', error.message); + } + + throw error; + })); + if (prevent) { + throw new Meteor.Error('error-app-prevented', 'A Rocket.Chat App prevented the room creation.'); + } + + let result; + result = Promise.await(Apps.triggerEvent('IPreRoomCreateExtend', roomInfo)); + result = Promise.await(Apps.triggerEvent('IPreRoomCreateModify', result)); + + if (typeof result === 'object') { + Object.assign(roomInfo, result); + } + + delete roomInfo._USERNAMES; + } + + const rid = room?._id || Rooms.insert(roomInfo); if (members.length === 1) { // dm to yourself Subscriptions.upsert({ rid, 'u._id': members[0]._id }, { @@ -80,6 +112,8 @@ export const createDirectRoom = function(members, roomExtraData = {}, options = const insertedRoom = Rooms.findOneById(rid); callbacks.run('afterCreateDirectRoom', insertedRoom, { members }); + + Apps.triggerEvent('IPostRoomCreate', insertedRoom); } return { diff --git a/app/lib/server/functions/createRoom.js b/app/lib/server/functions/createRoom.js index 9b43a9c16080..3d5d4ca886ee 100644 --- a/app/lib/server/functions/createRoom.js +++ b/app/lib/server/functions/createRoom.js @@ -1,14 +1,16 @@ +import { AppsEngineException } from '@rocket.chat/apps-engine/definition/exceptions'; import { Meteor } from 'meteor/meteor'; import _ from 'underscore'; import s from 'underscore.string'; -import { Users, Rooms, Subscriptions } from '../../../models'; -import { callbacks } from '../../../callbacks'; +import { Apps } from '../../../apps/server'; import { addUserRoles } from '../../../authorization'; +import { callbacks } from '../../../callbacks'; +import { Rooms, Subscriptions, Users } from '../../../models'; import { getValidRoomName } from '../../../utils'; -import { Apps } from '../../../apps/server'; import { createDirectRoom } from './createDirectRoom'; + export const createRoom = function(type, name, owner, members = [], readOnly, extraData = {}, options = {}) { callbacks.run('beforeCreateRoom', { type, name, owner, members, readOnly, extraData, options }); @@ -62,21 +64,30 @@ export const createRoom = function(type, name, owner, members = [], readOnly, ex ro: readOnly === true, }; - if (Apps && Apps.isLoaded()) { - const prevent = Promise.await(Apps.getBridges().getListenerBridge().roomEvent('IPreRoomCreatePrevent', room)); - if (prevent) { - throw new Meteor.Error('error-app-prevented-creation', 'A Rocket.Chat App prevented the room creation.'); + room._USERNAMES = members; + + const prevent = Promise.await(Apps.triggerEvent('IPreRoomCreatePrevent', room).catch((error) => { + if (error instanceof AppsEngineException) { + throw new Meteor.Error('error-app-prevented', error.message); } - let result; - result = Promise.await(Apps.getBridges().getListenerBridge().roomEvent('IPreRoomCreateExtend', room)); - result = Promise.await(Apps.getBridges().getListenerBridge().roomEvent('IPreRoomCreateModify', result)); + throw error; + })); - if (typeof result === 'object') { - room = Object.assign(room, result); - } + if (prevent) { + throw new Meteor.Error('error-app-prevented', 'A Rocket.Chat App prevented the room creation.'); + } + + let result; + result = Promise.await(Apps.triggerEvent('IPreRoomCreateExtend', room)); + result = Promise.await(Apps.triggerEvent('IPreRoomCreateModify', result)); + + if (typeof result === 'object') { + Object.assign(room, result); } + delete room._USERNAMES; + if (type === 'c') { callbacks.run('beforeCreateChannel', owner, room); } @@ -119,11 +130,7 @@ export const createRoom = function(type, name, owner, members = [], readOnly, ex callbacks.run('afterCreateRoom', owner, room); }); - if (Apps && Apps.isLoaded()) { - // This returns a promise, but it won't mutate anything about the message - // so, we don't really care if it is successful or fails - Apps.getBridges().getListenerBridge().roomEvent('IPostRoomCreate', room); - } + Apps.triggerEvent('IPostRoomCreate', room); return { rid: room._id, // backwards compatible diff --git a/app/livechat/client/views/app/livechatCurrentChats.js b/app/livechat/client/views/app/livechatCurrentChats.js index b8493dfeab53..bb5dbd0915d4 100644 --- a/app/livechat/client/views/app/livechatCurrentChats.js +++ b/app/livechat/client/views/app/livechatCurrentChats.js @@ -506,8 +506,6 @@ Template.livechatCurrentChats.onCreated(async function() { this.customFields.set(customFields); } }); - - this.loadDefaultFilters(); }); Template.livechatCurrentChats.onRendered(function() { @@ -516,4 +514,6 @@ Template.livechatCurrentChats.onRendered(function() { todayHighlight: true, format: moment.localeData().longDateFormat('L').toLowerCase(), }); + + this.loadDefaultFilters(); }); diff --git a/app/livechat/server/lib/Helper.js b/app/livechat/server/lib/Helper.js index 3f008a98f8e0..8a7c9ada3a25 100644 --- a/app/livechat/server/lib/Helper.js +++ b/app/livechat/server/lib/Helper.js @@ -1,4 +1,3 @@ -import { AppInterface } from '@rocket.chat/apps-engine/server/compiler'; import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { MongoInternals } from 'meteor/mongo'; @@ -8,7 +7,7 @@ import { Livechat } from './Livechat'; import { RoutingManager } from './RoutingManager'; import { callbacks } from '../../../callbacks/server'; import { settings } from '../../../settings'; -import { Apps } from '../../../apps/server'; +import { Apps, AppEvents } from '../../../apps/server'; export const createLivechatRoom = (rid, name, guest, roomInfo = {}, extraData = {}) => { check(rid, String); @@ -45,7 +44,7 @@ export const createLivechatRoom = (rid, name, guest, roomInfo = {}, extraData = const roomId = Rooms.insert(room); - Apps.getBridges().getListenerBridge().livechatEvent(AppInterface.IPostLivechatRoomStarted, room); + Apps.getBridges().getListenerBridge().livechatEvent(AppEvents.IPostLivechatRoomStarted, room); callbacks.run('livechat.newRoom', room); return roomId; }; @@ -167,7 +166,7 @@ export const removeAgentFromSubscription = (rid, { _id, username }) => { Subscriptions.removeByRoomIdAndUserId(rid, _id); Messages.createUserLeaveWithRoomIdAndUser(rid, { _id, username }); - Apps.getBridges().getListenerBridge().livechatEvent(AppInterface.IPostLivechatAgentUnassigned, { room, user }); + Apps.getBridges().getListenerBridge().livechatEvent(AppEvents.IPostLivechatAgentUnassigned, { room, user }); }; export const parseAgentCustomFields = (customFields) => { diff --git a/app/livechat/server/lib/Livechat.js b/app/livechat/server/lib/Livechat.js index 9eb1c5ffdb70..b57571205fa4 100644 --- a/app/livechat/server/lib/Livechat.js +++ b/app/livechat/server/lib/Livechat.js @@ -1,6 +1,5 @@ import dns from 'dns'; -import { AppInterface } from '@rocket.chat/apps-engine/server/compiler'; import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; import { Random } from 'meteor/random'; @@ -38,7 +37,7 @@ import { updateMessage } from '../../../lib/server/functions/updateMessage'; import { deleteMessage } from '../../../lib/server/functions/deleteMessage'; import { FileUpload } from '../../../file-upload/server'; import { normalizeTransferredByData, parseAgentCustomFields } from './Helper'; -import { Apps } from '../../../apps/server'; +import { Apps, AppEvents } from '../../../apps/server'; export const Livechat = { Analytics, @@ -372,11 +371,11 @@ export const Livechat = { Meteor.defer(() => { /** - * @deprecated the `AppInterface.ILivechatRoomClosedHandler` event will be removed + * @deprecated the `AppEvents.ILivechatRoomClosedHandler` event will be removed * in the next major version of the Apps-Engine */ - Apps.getBridges().getListenerBridge().livechatEvent(AppInterface.ILivechatRoomClosedHandler, room); - Apps.getBridges().getListenerBridge().livechatEvent(AppInterface.IPostLivechatRoomClosed, room); + Apps.getBridges().getListenerBridge().livechatEvent(AppEvents.ILivechatRoomClosedHandler, room); + Apps.getBridges().getListenerBridge().livechatEvent(AppEvents.IPostLivechatRoomClosed, room); callbacks.run('livechat.closeRoom', room); }); diff --git a/app/livechat/server/lib/RoutingManager.js b/app/livechat/server/lib/RoutingManager.js index 2f4579f29b7b..f654415af4a8 100644 --- a/app/livechat/server/lib/RoutingManager.js +++ b/app/livechat/server/lib/RoutingManager.js @@ -1,4 +1,3 @@ -import { AppInterface } from '@rocket.chat/apps-engine/server/compiler'; import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; @@ -12,7 +11,7 @@ import { createLivechatSubscription, } from './Helper'; import { callbacks } from '../../../callbacks/server'; import { LivechatRooms, Rooms, Messages, Users, LivechatInquiry } from '../../../models/server'; -import { Apps } from '../../../apps/server'; +import { Apps, AppEvents } from '../../../apps/server'; export const RoutingManager = { methodName: null, @@ -81,7 +80,7 @@ export const RoutingManager = { Messages.createCommandWithRoomIdAndUser('connected', rid, user); dispatchAgentDelegated(rid, agent.agentId); - Apps.getBridges().getListenerBridge().livechatEvent(AppInterface.IPostLivechatAgentAssigned, { room, user }); + Apps.getBridges().getListenerBridge().livechatEvent(AppEvents.IPostLivechatAgentAssigned, { room, user }); return inquiry; }, diff --git a/app/models/server/models/Users.js b/app/models/server/models/Users.js index 6b388bfa3402..c9515a3b03e7 100644 --- a/app/models/server/models/Users.js +++ b/app/models/server/models/Users.js @@ -523,7 +523,7 @@ export class Users extends Base { } findOneByEmailAddress(emailAddress, options) { - const query = { 'emails.address': new RegExp(`^${ s.escapeRegExp(emailAddress) }$`, 'i') }; + const query = { 'emails.address': String(emailAddress).trim().toLowerCase() }; return this.findOne(query, options); } diff --git a/app/reactions/client/init.js b/app/reactions/client/init.js index 81d3c44ecb9f..81c48cb6aca0 100644 --- a/app/reactions/client/init.js +++ b/app/reactions/client/init.js @@ -2,6 +2,7 @@ import { Meteor } from 'meteor/meteor'; import { Blaze } from 'meteor/blaze'; import { Template } from 'meteor/templating'; +import { roomTypes } from '../../utils/client'; import { Rooms } from '../../models'; import { MessageAction } from '../../ui-utils'; import { messageArgs } from '../../ui-utils/client/lib/messageArgs'; @@ -17,13 +18,7 @@ Template.room.events({ const user = Meteor.user(); const room = Rooms.findOne({ _id: rid }); - if (room.ro && !room.reactWhenReadOnly) { - if (!Array.isArray(room.unmuted) || room.unmuted.indexOf(user.username) === -1) { - return false; - } - } - - if (Array.isArray(room.muted) && room.muted.indexOf(user.username) !== -1) { + if (roomTypes.readOnly(room._id, user._id)) { return false; } @@ -73,21 +68,15 @@ Meteor.startup(function() { return false; } - if (room.ro && !room.reactWhenReadOnly) { - if (!Array.isArray(room.unmuted) || room.unmuted.indexOf(user.username) === -1) { - return false; - } - } - - if (Array.isArray(room.muted) && room.muted.indexOf(user.username) !== -1) { + if (!subscription) { return false; } - if (!subscription) { + if (message.private) { return false; } - if (message.private) { + if (roomTypes.readOnly(room._id, user._id)) { return false; } diff --git a/app/reactions/client/methods/setReaction.js b/app/reactions/client/methods/setReaction.js index db58a8b4ea66..14ec5010f7f6 100644 --- a/app/reactions/client/methods/setReaction.js +++ b/app/reactions/client/methods/setReaction.js @@ -4,6 +4,7 @@ import _ from 'underscore'; import { Messages, Rooms, Subscriptions } from '../../../models'; import { callbacks } from '../../../callbacks'; import { emoji } from '../../../emoji'; +import { roomTypes } from '../../../utils/client'; Meteor.methods({ setReaction(reaction, messageId) { @@ -16,25 +17,19 @@ Meteor.methods({ const message = Messages.findOne({ _id: messageId }); const room = Rooms.findOne({ _id: message.rid }); - if (room.ro && !room.reactWhenReadOnly) { - if (!Array.isArray(room.unmuted) || room.unmuted.indexOf(user.username) === -1) { - return false; - } - } - - if (Array.isArray(room.muted) && room.muted.indexOf(user.username) !== -1) { + if (message.private) { return false; } - if (!Subscriptions.findOne({ rid: message.rid })) { + if (!emoji.list[reaction]) { return false; } - if (message.private) { + if (roomTypes.readOnly(room._id, user._id)) { return false; } - if (!emoji.list[reaction]) { + if (!Subscriptions.findOne({ rid: message.rid })) { return false; } diff --git a/app/reactions/server/setReaction.js b/app/reactions/server/setReaction.js index f9a6751e6134..52adec6d8c29 100644 --- a/app/reactions/server/setReaction.js +++ b/app/reactions/server/setReaction.js @@ -3,11 +3,12 @@ import { Random } from 'meteor/random'; import { TAPi18n } from 'meteor/rocketchat:tap-i18n'; import _ from 'underscore'; -import { Messages, EmojiCustom, Subscriptions, Rooms } from '../../models'; +import { Messages, EmojiCustom, Rooms } from '../../models'; import { Notifications } from '../../notifications'; import { callbacks } from '../../callbacks'; import { emoji } from '../../emoji'; import { isTheLastMessage, msgStream } from '../../lib'; +import { hasPermission } from '../../authorization/server/functions/hasPermission'; const removeUserReaction = (message, reaction, username) => { message.reactions[reaction].usernames.splice(message.reactions[reaction].usernames.indexOf(username), 1); @@ -17,16 +18,17 @@ const removeUserReaction = (message, reaction, username) => { return message; }; -export function setReaction(room, user, message, reaction, shouldReact) { +async function setReaction(room, user, message, reaction, shouldReact) { reaction = `:${ reaction.replace(/:/g, '') }:`; if (!emoji.list[reaction] && EmojiCustom.findByNameOrAlias(reaction).count() === 0) { throw new Meteor.Error('error-not-allowed', 'Invalid emoji provided.', { method: 'setReaction' }); } - if (room.ro && !room.reactWhenReadOnly) { - if (!Array.isArray(room.unmuted) || room.unmuted.indexOf(user.username) === -1) { - return false; + if (room.ro === true && (!room.reactWhenReadOnly && !hasPermission(user._id, 'post-readonly', room._id))) { + // Unless the user was manually unmuted + if (!(room.unmuted || []).includes(user.username)) { + throw new Error('You can\'t send messages because the room is readonly.'); } } @@ -38,8 +40,6 @@ export function setReaction(room, user, message, reaction, shouldReact) { msg: TAPi18n.__('You_have_been_muted', {}, user.language), }); return false; - } if (!Subscriptions.findOne({ rid: message.rid })) { - return false; } const userAlreadyReacted = Boolean(message.reactions) && Boolean(message.reactions[reaction]) && message.reactions[reaction].usernames.indexOf(user.username) !== -1; @@ -92,18 +92,18 @@ Meteor.methods({ setReaction(reaction, messageId, shouldReact) { const user = Meteor.user(); - const message = Messages.findOneById(messageId); - - const room = Meteor.call('canAccessRoom', message.rid, Meteor.userId()); - if (!user) { throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'setReaction' }); } + const message = Messages.findOneById(messageId); + if (!message) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'setReaction' }); } + const room = Meteor.call('canAccessRoom', message.rid, Meteor.userId()); + if (!room) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'setReaction' }); } diff --git a/app/ui-flextab/client/tabs/inviteUsers.js b/app/ui-flextab/client/tabs/inviteUsers.js index 784a5757ab27..e8e0783f068b 100644 --- a/app/ui-flextab/client/tabs/inviteUsers.js +++ b/app/ui-flextab/client/tabs/inviteUsers.js @@ -7,7 +7,7 @@ import { Deps } from 'meteor/deps'; import toastr from 'toastr'; import { settings } from '../../../settings'; -import { t } from '../../../utils'; +import { t, handleError } from '../../../utils/client'; import { AutoComplete } from '../../../meteor-autocomplete/client'; const acEvents = { @@ -106,7 +106,7 @@ Template.inviteUsers.events({ users, }, function(err) { if (err) { - return toastr.error(err); + return handleError(err); } toastr.success(t('Users_added')); instance.selectedUsers.set([]); diff --git a/app/ui-message/client/blocks/index.js b/app/ui-message/client/blocks/index.js index 5e332705c1d4..d081ff82163b 100644 --- a/app/ui-message/client/blocks/index.js +++ b/app/ui-message/client/blocks/index.js @@ -1,4 +1,10 @@ +import { HTML } from 'meteor/htmljs'; + import { createTemplateForComponent } from '../../../../client/reactAdapters'; -createTemplateForComponent('ModalBlock', () => import('./ModalBlock')); +createTemplateForComponent('ModalBlock', () => import('./ModalBlock'), { + // eslint-disable-next-line new-cap + renderContainerView: () => HTML.DIV({ class: 'rc-multiselect', style: 'display: flex; width:100%;' }), +}); + createTemplateForComponent('Blocks', () => import('./MessageBlock')); diff --git a/app/ui-message/client/message.html b/app/ui-message/client/message.html index d2e0bef5ceb9..5269bcc5711e 100644 --- a/app/ui-message/client/message.html +++ b/app/ui-message/client/message.html @@ -176,11 +176,9 @@ {{/unless}} {{#if broadcast}} - {{#with msg.u}} - - {{/with}} + {{/if}} {{#unless hideReactions}}