Skip to content

Commit

Permalink
Merge branch 'develop' into chore/settings-small-issues
Browse files Browse the repository at this point in the history
  • Loading branch information
dougfabris committed Jun 30, 2022
2 parents e5faff8 + b01685d commit 10b8979
Show file tree
Hide file tree
Showing 132 changed files with 1,269 additions and 848 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,5 @@ yarn-error.log*

.nvmrc
.idea/

*.tsbuildinfo
6 changes: 3 additions & 3 deletions .kodiak.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ block_on_neutral_required_check_runs = true
blocking_labels = ["stat: needs QA", "Invalid PR Title"]
prioritize_ready_to_merge = true


[merge.message]
title = "pull_request_title" # default: "github_default"
body = "pull_request_body" # default: "github_default"
title = "pull_request_title"
body = "empty"
include_coauthors=true

[merge.automerge_dependencies]
versions = ["minor", "patch"]
usernames = ["dependabot"]
Expand Down
1 change: 0 additions & 1 deletion _templates/package/new/package.json.ejs.t
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ to: packages/<%= name %>/package.json
"lint:fix": "eslint --ext .js,.jsx,.ts,.tsx . --fix",
"jest": "jest",
"build": "rm -rf dist && tsc -p tsconfig.json",
"dev": "tsc -p tsconfig.json --watch --preserveWatchOutput"
},
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
Expand Down
3 changes: 2 additions & 1 deletion _templates/package/new/tsconfig.json.ejs.t
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ to: packages/<%= name %>/tsconfig.json
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist"
"outDir": "./dist",
"composite": true
},
"include": ["./src/**/*"]
}
2 changes: 1 addition & 1 deletion apps/meteor/app/api/server/v1/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,7 @@ API.v1.addRoute(
{
authRequired: false,
rateLimiterOptions: {
numRequestsAllowed: settings.get('Rate_Limiter_Limit_RegisterUser'),
numRequestsAllowed: settings.get('Rate_Limiter_Limit_RegisterUser') ?? 1,
intervalTimeInMS: settings.get('API_Enable_Rate_Limiter_Limit_Time_Default'),
},
validateParams: isUserRegisterParamsPOST,
Expand Down
12 changes: 11 additions & 1 deletion apps/meteor/app/apps/server/bridges/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,16 @@ export class AppSettingBridge extends ServerSettingBridge {
throw new Error(`The setting "${setting.id}" is not readable.`);
}

throw new Error('Method not implemented.');
await Settings.updateValueById(setting.id, setting.value);
}

protected async incrementValue(id: string, value: number, appId: string): Promise<void> {
this.orch.debugLog(`The App ${appId} is incrementing the value of the setting ${id}.`);

if (!(await this.isReadableById(id, appId))) {
throw new Error(`The setting "${id}" is not readable.`);
}

await Settings.incrementValueById(id, value);
}
}
32 changes: 32 additions & 0 deletions apps/meteor/app/apps/server/communication/rest.js
Original file line number Diff line number Diff line change
Expand Up @@ -528,6 +528,38 @@ export class AppsRestApi {
},
);

this.api.addRoute(
':id/versions',
{ authRequired: true, permissionsRequired: ['manage-apps'] },
{
get() {
const baseUrl = orchestrator.getMarketplaceUrl();

const headers = {}; // DO NOT ATTACH THE FRAMEWORK/ENGINE VERSION HERE.
const token = getWorkspaceAccessToken();
if (token) {
headers.Authorization = `Bearer ${token}`;
}

let result;
try {
result = HTTP.get(`${baseUrl}/v1/apps/${this.urlParams.id}`, {
headers,
});
} catch (e) {
return handleError('Unable to access Marketplace. Does the server has access to the internet?', e);
}

if (!result || result.statusCode !== 200) {
orchestrator.getRocketChatLogger().error('Error getting the App versions from the Marketplace:', result.data);
return API.v1.failure();
}

return API.v1.success({ apps: result.data });
},
},
);

this.api.addRoute(
':id/sync',
{ authRequired: true, permissionsRequired: ['manage-apps'] },
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/lib/server/functions/loadMessageHistory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export const loadMessageHistory = function loadMessageHistory({
if (ls != null) {
const firstMessage = messages[messages.length - 1];

if ((firstMessage != null ? firstMessage.ts : undefined) > ls) {
if (firstMessage && new Date(firstMessage.ts) > new Date(ls)) {
// delete options.limit;
const unreadMessages = Messages.findVisibleByRoomIdBetweenTimestampsNotContainingTypes(
rid,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ export function getEmailData({ message, receiver, sender, subscription, room, em
// Reply-To header with format "username+messageId@domain"
email.headers['Reply-To'] = `${replyto.split('@')[0].split(settings.get('Direct_Reply_Separator'))[0]}${settings.get(
'Direct_Reply_Separator',
)}${message._id}@${replyto.split('@')[1]}`;
)}${message.tmid || message._id}@${replyto.split('@')[1]}`;
}

metrics.notificationsSent.inc({ notification_type: 'email' });
Expand Down
194 changes: 83 additions & 111 deletions apps/meteor/app/lib/server/lib/interceptDirectReplyEmails.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { Meteor } from 'meteor/meteor';
import POP3Lib from '@rocket.chat/poplib';
import { simpleParser } from 'mailparser';

import { settings } from '../../../settings/server';
import { SystemLogger } from '../../../../server/lib/logger/system';
import { settings } from '../../../settings';
import { IMAPInterceptor } from '../../../../server/email/IMAPInterceptor';
import { processDirectEmail } from '.';

export class IMAPIntercepter extends IMAPInterceptor {
export class DirectReplyIMAPInterceptor extends IMAPInterceptor {
constructor(imapConfig, options = {}) {
imapConfig = {
user: settings.get('Direct_Reply_Username'),
Expand All @@ -23,154 +21,128 @@ export class IMAPIntercepter extends IMAPInterceptor {

super(imapConfig, options);

this.on(
'email',
Meteor.bindEnvironment((email) => processDirectEmail(email)),
);
this.on('email', (email) => processDirectEmail(email));
}
}

export class POP3Intercepter {
constructor() {
this.pop3 = new POP3Lib(settings.get('Direct_Reply_Port'), settings.get('Direct_Reply_Host'), {
enabletls: !settings.get('Direct_Reply_IgnoreTLS'),
debug: settings.get('Direct_Reply_Debug') ? console.log : false,
// debug: settings.get('Direct_Reply_Debug') ? console.log : false,
debug: console.log,
});

this.totalMsgCount = 0;
this.currentMsgCount = 0;

this.pop3.on(
'connect',
Meteor.bindEnvironment(() => {
this.pop3.login(settings.get('Direct_Reply_Username'), settings.get('Direct_Reply_Password'));
}),
);

this.pop3.on(
'login',
Meteor.bindEnvironment((status) => {
if (status) {
// run on start
this.pop3.list();
} else {
SystemLogger.info('Unable to Log-in ....');
}
}),
);
this.pop3.on('connect', () => {
console.log('Pop connect');
this.pop3.login(settings.get('Direct_Reply_Username'), settings.get('Direct_Reply_Password'));
});

this.pop3.on('login', (status) => {
if (!status) {
return console.log('Unable to Log-in ....');
}
console.log('Pop logged');
// run on start
this.pop3.list();
});

// on getting list of all emails
this.pop3.on(
'list',
Meteor.bindEnvironment((status, msgcount) => {
if (status) {
if (msgcount > 0) {
this.totalMsgCount = msgcount;
this.currentMsgCount = 1;
// Retrieve email
this.pop3.retr(this.currentMsgCount);
} else {
this.pop3.quit();
}
} else {
SystemLogger.info('Cannot Get Emails ....');
}
}),
);
this.pop3.on('list', (status, msgcount) => {
if (!status) {
console.log('Cannot Get Emails ....');
}
if (msgcount === 0) {
return this.pop3.quit();
}

this.totalMsgCount = msgcount;
this.currentMsgCount = 1;
// Retrieve email
this.pop3.retr(this.currentMsgCount);
});

// on retrieved email
this.pop3.on(
'retr',
Meteor.bindEnvironment((status, msgnumber, data) => {
if (status) {
// parse raw email data to JSON object
simpleParser(
data,
Meteor.bindEnvironment((err, mail) => {
this.initialProcess(mail);
}),
);

this.currentMsgCount += 1;

// delete email
this.pop3.dele(msgnumber);
} else {
SystemLogger.info('Cannot Retrieve Message ....');
}
}),
);
this.pop3.on('retr', (status, msgnumber, data) => {
if (!status) {
return console.log('Cannot Retrieve Message ....');
}

// parse raw email data to JSON object
simpleParser(data, (err, mail) => {
processDirectEmail(mail);
});

this.currentMsgCount += 1;

// delete email
this.pop3.dele(msgnumber);
});

// on email deleted
this.pop3.on(
'dele',
Meteor.bindEnvironment((status) => {
if (status) {
// get next email
if (this.currentMsgCount <= this.totalMsgCount) {
this.pop3.retr(this.currentMsgCount);
} else {
// parsed all messages.. so quitting
this.pop3.quit();
}
} else {
SystemLogger.info('Cannot Delete Message....');
}
}),
);
this.pop3.on('dele', (status) => {
if (!status) {
return console.log('Cannot Delete Message....');
}

// get next email
if (this.currentMsgCount <= this.totalMsgCount) {
return this.pop3.retr(this.currentMsgCount);
}

// parsed all messages.. so quitting
this.pop3.quit();
});

// invalid server state
this.pop3.on('invalid-state', function (cmd) {
SystemLogger.info(`Invalid state. You tried calling ${cmd}`);
console.log(`Invalid state. You tried calling ${cmd}`);
});

this.pop3.on('error', function (cmd) {
console.log(`error state. You tried calling ${cmd}`);
});

// locked => command already running, not finished yet
this.pop3.on('locked', function (cmd) {
SystemLogger.info(`Current command has not finished yet. You tried calling ${cmd}`);
console.log(`Current command has not finished yet. You tried calling ${cmd}`);
});
}

initialProcess(mail) {
const email = {
headers: {
'from': mail.from.text,
'to': mail.to.text,
'date': mail.date,
'message-id': mail.messageId,
},
body: mail.text,
};

processDirectEmail(email);
}
}
export let POP3;

export class POP3Helper {
constructor() {
constructor(frequency) {
this.frequency = frequency;
this.running = false;
}

start() {
// run every x-minutes
if (settings.get('Direct_Reply_Frequency')) {
POP3 = new POP3Intercepter();

this.running = Meteor.setInterval(() => {
// get new emails and process
POP3 = new POP3Intercepter();
}, Math.max(settings.get('Direct_Reply_Frequency') * 60 * 1000, 2 * 60 * 1000));
}
this.POP3 = new POP3Intercepter();
}

isActive() {
return this.running;
}

start() {
this.log('POP3 started');
this.running = setInterval(() => {
// get new emails and process
this.POP3 = new POP3Intercepter();
}, Math.max(this.frequency * 60 * 1000, 2 * 60 * 1000));
}

log(...args) {
console.log(...args);
}

stop(callback = new Function()) {
this.log('POP3 stop called');
if (this.isActive()) {
Meteor.clearInterval(this.running);
clearInterval(this.running);
}
callback();
this.log('POP3 stopped');
}
}
Loading

0 comments on commit 10b8979

Please sign in to comment.