Example #1
0
	users.forEach(function(user) {

		try {
			return Meteor.call('addUserToRoom', {
				rid: item.rid,
				username: user.username,
			});
		} catch ({ error }) {
			if (error === 'cant-invite-for-direct-room') {
				RocketChat.Notifications.notifyUser(userId, 'message', {
					_id: Random.id(),
					rid: item.rid,
					ts: new Date,
					msg: TAPi18n.__('Cannot_invite_users_to_direct_rooms', null, currentUser.language),
				});
			} else {
				RocketChat.Notifications.notifyUser(userId, 'message', {
					_id: Random.id(),
					rid: item.rid,
					ts: new Date,
					msg: TAPi18n.__(error, null, currentUser.language),
				});
			}
		}
	});
Example #2
0
export const exampleMsg = () => {
	const record = Template.instance().record.get();
	return {
		_id: Random.id(),
		alias: record.alias,
		emoji: record.emoji,
		avatar: record.avatar,
		msg: 'Example message',
		bot: {
			i: Random.id(),
		},
		groupable: false,
		attachments: [{
			title: 'Rocket.Chat',
			title_link: 'https://rocket.chat',
			text: 'Rocket.Chat, the best open source chat',
			image_url: '/images/integration-attachment-example.png',
			color: '#764FA5',
		}],
		ts: new Date(),
		u: {
			_id: Random.id(),
			username: record.username,
		},
	};
};
Example #3
0
	it('do not increment achievement if no player', function() {
		const gameId = Random.id(5);
		const userId = Random.id(5);
		const listener = (new Ninja()).forGame(gameId, userId);
		Games.insert({_id: gameId, createdBy: userId, players: []});

		assert.equal(0, UserAchievements.find().count());
		listener.onGameFinished(new GameFinished(gameId, 121000));
		assert.equal(0, UserAchievements.find().count());
	});
Example #4
0
	it('do not increment achievement if no activated bonus in the game but game is under 2:00', function() {
		const gameId = Random.id(5);
		const creatorUserId = Random.id(5);
		const opponentUserId = Random.id(5);
		Games.insert({_id: gameId, createdBy: creatorUserId, players: [{id: creatorUserId}, {id: opponentUserId}]});
		const listener = (new Ninja()).forGame(gameId, creatorUserId);

		assert.equal(0, UserAchievements.find().count());
		listener.onGameFinished(new GameFinished(gameId, 120000));
		assert.equal(0, UserAchievements.find().count());
	});
Example #5
0
	it('do not increment achievement if there was an activated bonus in the game and user is host', function() {
		const gameId = Random.id(5);
		const creatorUserId = Random.id(5);
		const opponentUserId = Random.id(5);
		Games.insert({_id: gameId, createdBy: creatorUserId, players: [{id: creatorUserId}, {id: opponentUserId}]});
		const listener = (new Ninja()).forGame(gameId, creatorUserId);

		listener.onBonusCaught(new BonusCaught(gameId, 'a', {activatedBonusClass: 'a', targetPlayerKey: 'player1', bonusClass: 'a', activatorPlayerKey: 'player1'}));

		assert.equal(0, UserAchievements.find().count());
		listener.onGameFinished(new GameFinished(gameId, 121000));
		assert.equal(0, UserAchievements.find().count());
	});
Example #6
0
 it('sends no symbols for a private circuit when logged in as another user', (done) => {
   const collector = new PublicationCollector({ userId: Random.id() });
   collector.collect('symbols.inCircuit', privateCircuit._id, (collections) => {
     chai.assert.isUndefined(collections.Symbols);
     done();
   });
 });
Example #7
0
		describe('methods', () => {
			const userId = Random.id();
			let taskId;

			beforeEach(() => {
				Tasks.remove({});
				taskId = Tasks.insert({
					text: 'test task',
					createdAt: new Date(),
					owner: userId,
					username: '******',
				});
			});

			it('can delete owned task', () => {
				// Find the internal implementation of the task method so we can
				// test it in isolation
				const deleteTask = Meteor.server.method_handlers['tasks.remove'];
				// Set up a fake method invocation that looks like what the method expects
				const invocation = { userId };
				// Run the method with `this` set to the fake invocation
				deleteTask.apply(invocation, [taskId]);
				// Verify that the method does what we expected
				assert.equal(Tasks.find().count(), 0);
			});
		});
Example #8
0
renderer.code = function(code, lang, escaped) {
	if (this.options.highlight) {
		const out = this.options.highlight(code, lang);
		if (out != null && out !== code) {
			escaped = true;
			code = out;
		}
	}

	let text = null;

	if (!lang) {
		text = `<pre><code class="code-colors hljs">${ (escaped ? code : s.escapeHTML(code, true)) }</code></pre>`;
	} else {
		text = `<pre><code class="code-colors hljs ${ escape(lang, true) }">${ (escaped ? code : s.escapeHTML(code, true)) }</code></pre>`;
	}

	if (_.isString(msg)) {
		return text;
	}

	const token = `=!=${ Random.id() }=!=`;
	msg.tokens.push({
		highlight: true,
		token,
		text,
	});

	return token;
};
Example #9
0
	blockUnsafeImages(message) {
		if (this.enabled && this.serviceAccount && message && message.file && message.file._id) {
			const file = RocketChat.models.Uploads.findOne({ _id: message.file._id });
			if (file && file.type && file.type.indexOf('image') !== -1 && file.store === 'GoogleCloudStorage:Uploads' && file.GoogleStorage) {
				if (this.incCallCount(1)) {
					const bucket = this.storageClient.bucket(RocketChat.settings.get('FileUpload_GoogleStorage_Bucket'));
					const bucketFile = bucket.file(file.GoogleStorage.path);
					const results = Meteor.wrapAsync(this.visionClient.detectSafeSearch, this.visionClient)(bucketFile);
					if (results && results.adult === true) {
						FileUpload.getStore('Uploads').deleteById(file._id);
						const user = RocketChat.models.Users.findOneById(message.u && message.u._id);
						if (user) {
							RocketChat.Notifications.notifyUser(user._id, 'message', {
								_id: Random.id(),
								rid: message.rid,
								ts: new Date,
								msg: TAPi18n.__('Adult_images_are_not_allowed', {}, user.language),
							});
						}
						throw new Meteor.Error('GoogleVisionError: Image blocked');
					}
				} else {
					console.error('Google Vision: Usage limit exceeded');
				}
				return message;
			}
		}
	}
Example #10
0
        describe('methods', () => {
            //creating a task with a random userId
            const userId = Random.id();
            let taskId;
            beforEach(() => {
                Tasks.remove({});
                //testing our random task with the remove method
                taskId = Tasks.insert({
                    text: 'test task',
                    createdAt: new Date(),
                    owner: userId,
                    username: '******',
                });
            });

            it('can delete owned task', () => {
                //testing an isolated instance of the task
                const deleteTask = Meteor.server.method_handlers['tasks.remove'];
                //spy?
                const invocation = {
                    userId
                };
                //run using spy
                deleteTask.apply(incovation, [taskId]);
                //checking if we are getting the expected outcome
                assert.equal(Tasks.find().count(),0);
            });
        });
Example #11
0
  describe('emails.sendEnrollmentEmail', ()=> {
    const sendEnrollmentEmailHandler = Meteor.server.method_handlers['sendEnrollmentEmail'];
    let accountsSendEnrollmentEmailStub;

    const agencyId = Random.id();
    beforeEach(()=> {
      accountsSendEnrollmentEmailStub = sinon.stub(Accounts, 'sendEnrollmentEmail', ()=> true);
    });
    afterEach(()=> {
      Accounts.sendEnrollmentEmail.restore();
    });

    it('fails if user is not an administrator', ()=> {
      const invocation = {userId: testUserId};
      assert.throws(()=>sendEnrollmentEmailHandler.apply(invocation, [testUserId, agencyId]),
        'Must be an agency administrator to send enrollment email. [unauthorized]');
    });
    it('fails if user is an administrator but not for this agency', ()=> {
      const invocation = {userId: testUserId};
      Roles.addUsersToRoles(testUserId, ['administrator'], 'anotherAgency');
      assert.throws(()=>sendEnrollmentEmailHandler.apply(invocation, [testUserId, agencyId]),
        'Must be an agency administrator to send enrollment email. [unauthorized]');
    });
    it('Accounts.sendEnrollmentEmail is called', ()=> {
      const invocation = {userId: testUserId};
      Roles.addUsersToRoles(testUserId, ['administrator'], agencyId);
      sendEnrollmentEmailHandler.apply(invocation, [testUserId, agencyId]);
      assert(accountsSendEnrollmentEmailStub.calledOnce);
    });

  });
  it("should call StripeApi.methods.captureCharge with the proper parameters and return saved = true", function (done) {
    const paymentPackageId = Random.id();
    const paymentMethod = {
      processor: "Stripe",
      storedCard: "Visa 4242",
      paymentPackageId,
      paymentSettingsKey: "reaction-stripe",
      method: "credit",
      transactionId: "ch_17hZ4wBXXkbZQs3xL5JhlSgS",
      amount: 19.99,
      status: "approved",
      mode: "capture",
      createdAt: new Date()
    };

    // Stripe Charge Nock
    nock("https://api.stripe.com:443")
      .post(`/v1/charges/${paymentMethod.transactionId}/capture`)
      .reply(200, stripeCaptureResult); // .log(console.log);

    sandbox.stub(utils, "getStripeApi", function () {
      return "sk_fake_fake";
    });

    let captureResult = null;
    let captureError = null;
    Meteor.call("stripe/payment/capture", paymentMethod, function (error, result) {
      captureResult = result;
      captureError = error;
      expect(captureError).to.be.undefined;
      expect(captureResult).to.not.be.undefined;
      expect(captureResult.saved).to.be.true;
      done();
    });
  });
    describe('methods', () => {
      const userId = Random.id();
      let courseId;

      const now = new Date();
      beforeEach(() => {
        Courses.remove({});
        courseId = Courses.insert({
          name: 'Vinyasa Flow',
          start: new Date(),
          end  : new Date().setHour(now.getHour() + 1),
          studio: 'Chiswell Street',
          teacher: 'Issy',
          url  : 'http://www.flexlondon.com/',
        });
      });

      it('can delete owned course', () => {
        // use the actual implementation of the course method from the server
        const deleteCourse = Meteor.server.method_handlers['courses.remove'];

        // Make the input look similar on "this" in the function call
        const invocation = { userId };

        // run method with "this" set to fake invocation
        deleteCourse.apply(invocation, [courseId]);

        // verify that it worked
        assert.equal(Courses.find().count(), 0);
      });
    });
Example #14
0
	convertAppMessage(message) {
		if (!message) {
			return undefined;
		}

		const room = RocketChat.models.Rooms.findOneById(message.room.id);

		if (!room) {
			throw new Error('Invalid room provided on the message.');
		}

		let u;
		if (message.sender && message.sender.id) {
			const user = RocketChat.models.Users.findOneById(message.sender.id);

			if (user) {
				u = {
					_id: user._id,
					username: user.username,
					name: user.name,
				};
			} else {
				u = {
					_id: message.sender.id,
					username: message.sender.username,
					name: message.sender.name,
				};
			}
		}

		let editedBy;
		if (message.editor) {
			const editor = RocketChat.models.Users.findOneById(message.editor.id);
			editedBy = {
				_id: editor._id,
				username: editor.username,
			};
		}

		const attachments = this._convertAppAttachments(message.attachments);

		return {
			_id: message.id || Random.id(),
			rid: room._id,
			u,
			msg: message.text,
			ts: message.createdAt || new Date(),
			_updatedAt: message.updatedAt || new Date(),
			editedBy,
			editedAt: message.editedAt,
			emoji: message.emoji,
			avatar: message.avatarUrl,
			alias: message.alias,
			customFields: message.customFields,
			groupable: message.groupable,
			attachments,
			reactions: message.reactions,
		};
	}
	it('do not create achievement if not created if not gameId on invisible bonus caught', function() {
		Games.insert({_id: gameId, createdBy: userId, players: [{id: userId}, {id: opponentUserId}]});
		const listener = (new InvisibleInAPoint()).forGame(gameId, userId);

		assert.equal(0, UserAchievements.find().count());
		listener.onBonusCaught(new BonusCaught(Random.id(5), 'a', {activatedBonusClass: BONUS_INVISIBLE_MONSTER, targetPlayerKey: 'player1', bonusClass: 'a', activatorPlayerKey: 'player1'}));
		assert.equal(0, UserAchievements.find().count());
	});
 this.resetNewComment = () => {
     this.newComment = {
         _id: Random.id(),
         noi_dung: {},
         isActive: true,
         metadata: {}
     };
 };
	it('do not create achievement if not created if not userId on player won', function() {
		Games.insert({_id: gameId, createdBy: userId, gameDuration: 59000, players: [{id: userId}, {id: opponentUserId}]});

		assert.equal(0, UserAchievements.find().count());
		const listener = (new GamesWonUnderAMinute()).forGame(gameId, userId);
		listener.onPlayerWon(new PlayerWon(gameId, Random.id(5), 5, 0));
		assert.equal(0, UserAchievements.find().count());
	});
 it('does not assign amounts of selections of other users', function () {
   const otherUserId = Random.id();
   Factory.create('selection', { programId, program, userId: otherUserId});
   assign_initial_amounts.apply(invocation);
   user_selection = Selections.findOne({userId});
   other_selection = Selections.findOne({userId: otherUserId});
   expect(user_selection.amount).to.exist;
   expect(other_selection.amount).not.to.exist;
 });
	it('do not update achievement if not gameId on player won', function() {
		Games.insert({_id: gameId, createdBy: userId, gameDuration: 59000, players: [{id: userId}, {id: opponentUserId}]});
		UserAchievements.insert({userId: userId, achievementId: ACHIEVEMENT_GAMES_WON_UNDER_A_MINUTE, number: 1});

		const listener = (new GamesWonUnderAMinute()).forGame(gameId, userId);
		listener.onPlayerWon(new PlayerWon(Random.id(5), userId, 5, 0));

		assertGamesWonUnderAMinuteUserAchievementNumberEquals(1);
	});
Example #20
0
	encrypt(message) {
		let ts;
		if (isNaN(TimeSync.serverOffset())) {
			ts = new Date();
		} else {
			ts = new Date(Date.now() + TimeSync.serverOffset());
		}

		const data = new TextEncoder('UTF-8').encode(EJSON.stringify({
			_id: message._id,
			text: message.msg,
			userId: this.userId,
			ack: Random.id((Random.fraction() + 1) * 20),
			ts,
		}));
		const enc = this.encryptText(data);
		return enc;
	}
Example #21
0
function getCouponRec(template){
    const coupon = {
        _id:Random.id(),
        itemId:template.find('#select-item').value,
        discount:template.find('#coupon-discount').value,
        count:parseInt(template.find('#coupon-count').value)
    };
    if (checkNuber(coupon.discount) && checkNuber(coupon.count)) {return coupon;}
    else {return false;}
}
Example #22
0
	encryptText(data) {
		if (!_.isObject(data)) {
			data = new TextEncoder('UTF-8').encode(EJSON.stringify({ text: data, ack: Random.id((Random.fraction() + 1) * 20) }));
		}
		const iv = crypto.getRandomValues(new Uint8Array(12));

		return RocketChat.OTR.crypto.encrypt({
			name: 'AES-GCM',
			iv,
		}, this.sessionKey, data).then((cipherText) => {
			cipherText = new Uint8Array(cipherText);
			const output = new Uint8Array(iv.length + cipherText.length);
			output.set(iv, 0);
			output.set(cipherText, iv.length);
			return EJSON.stringify(output);
		}).catch(() => {
			throw new Meteor.Error('encryption-error', 'Encryption error.');
		});
	}
Example #23
0
	keys.forEach((key) => {
		RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', {
			_id: Random.id(),
			rid: item.rid,
			ts: new Date,
			msg: TAPi18n.__(Object.keys(key)[0], {
				postProcess: 'sprintf',
				sprintf: [key[Object.keys(key)[0]]],
			}, user.language),
		});
	});
Example #24
0
      before(() => {
        userId = Random.id();
        publicCircuit = Factory.create('circuit');
        privateCircuit = Factory.create('circuit', { userId });

        _.times(3, () => {
          Factory.create('symbol', { cid: publicCircuit._id });
          // TODO get rid of userId, https://github.com/meteor/symbols/pull/49
          Factory.create('symbol', { cid: privateCircuit._id, userId });
        });
      });
Example #25
0
export function paymentMethod(doc) {
  return {
    ...doc,
    processor: doc.processor ? doc.processor : randomProcessor(),
    storedCard: doc.storedCard ? doc.storedCard : "4242424242424242",
    transactionId: doc.transactionId ? doc.transactionId : Random.id(),
    status: doc.status ? doc.status : randomStatus(),
    mode: doc.mode ? doc.mode : randomMode(),
    authorization: "auth field",
    amount: doc.amount ? doc.amount : faker.commerce.price()
  };
}
    context('given a program', function () {
      const userId = Random.id();
      let programId;

      beforeEach(function () {
        categoryId = Factory.create('category')._id;
        programId = Factory.create('program', { userId, categoryId })._id;
      });

      describe('program', function () {
        it.skip('returns associated program', function () {
          const selection = Factory.create('selection', {userId, programId});
          // TODO: solve timing issues here
          expect(selection).to.exist;
          expect(selection.program()).to.exist;
          expect(selection.program()._id).to.equal(programid);
        });
      });

      describe('user', function () {
        it.skip('returns associated user', function () {
          // TODO: implement
        });
      });

      describe('validations', function () {
        it.skip('checks dangling user id', function () {
          // TODO: implement
        });

        it.skip('checks dangling program id', function () {
          // TODO: implement
        });
      });

      describe('selections.choose', function () {
        it('creates a new selection', function () {
          const chooseSelection  = Meteor.server.method_handlers['selections.choose'];
          const invocation = { userId };
          chooseSelection.apply(invocation, [programId, 'Yes'])
          expect(Selections.find().count()).to.equal(1);
        });

        it('rejects a new selection if not logged in', function () {
          const chooseSelection  = Meteor.server.method_handlers['selections.choose'];
          const invocation = { userId: null };
          expect(chooseSelection.apply.bind(chooseSelection, {
            userId: null
          }, [programId, 'Yes'])).to.throw('not-authorized');
          expect(Selections.find().count()).to.equal(0);
        });
      });
    });
Example #27
0
renderer.codespan = function(text) {
	text = `<code class="code-colors inline">${ text }</code>`;
	if (_.isString(msg)) {
		return text;
	}

	const token = `=!=${ Random.id() }=!=`;
	msg.tokens.push({
		token,
		text,
	});

	return token;
};
Example #28
0
 items: function () {
   const product = addProduct();
   const variant = Products.findOne({ ancestors: [product._id] });
   const childVariants = Products.find({ ancestors: [
     product._id, variant._id
   ] }).fetch();
   const selectedOption = Random.choice(childVariants);
   const product2 = addProduct();
   const variant2 = Products.findOne({ ancestors: [product2._id] });
   const childVariants2 = Products.find({ ancestors: [
     product2._id, variant2._id
   ] }).fetch();
   const selectedOption2 = Random.choice(childVariants2);
   return [{
     _id: itemIdOne,
     title: "firstItem",
     shopId: product.shopId,
     productId: product._id,
     quantity: 1,
     product: product,
     variants: selectedOption,
     workflow: {
       status: "new"
     }
   }, {
     _id: itemIdTwo,
     title: "secondItem",
     shopId: product2.shopId,
     productId: product2._id,
     quantity: 1,
     product: product2,
     variants: selectedOption2,
     workflow: {
       status: "new"
     }
   }];
 },
Example #29
0
      beforeEach(() => {
        // Clear
        Lists.remove({});
        Todos.remove({});

        // Create a list and a todo in that list
        listId = Factory.create('list')._id;
        todoId = Factory.create('todo', { listId })._id;

        // Create throwaway list, since the last public list can't be made private
        otherListId = Factory.create('list')._id;

        // Generate a 'user'
        userId = Random.id();
      });
Example #30
0
        describe('methods', () => {
            const userId = Random.id();
            let groupId;

            beforeEach(() => {
                Groups.remove({});
                const now = new Date();
                groupId = Groups.insert({
                    domain: 'pdrummond',
                    name: 'test',
                    createdAt: now,
                    updatedAt: now,
                    owner: userId,
                    username: '******'
                });
            });

            it('can update own group', () => {
                const method = Meteor.server.method_handlers['groups.update'];

                // Set up a fake method invocation that looks like what the method expects
                const invocation = { userId };

                // Run the method with `this` set to the fake invocation
                method.apply(invocation, [groupId, 'pdrummond-changed', 'test-changed']);

                var group = Groups.findOne(groupId);
                console.log("GROUP: " + JSON.stringify(group, null, 4));
                expect(group.domain).to.equal("pdrummond-changed");
                expect(group.name).to.equal("test-changed");
                expect(group.updatedAt.getTime()).to.not.equal(group.createdAt.getTime());
            });

            it('can delete owned group', () => {
                // Find the internal implementation of the group method so we can
                // test it in isolation
                const deleteGroup = Meteor.server.method_handlers['groups.remove'];

                // Set up a fake method invocation that looks like what the method expects
                const invocation = { userId };

                // Run the method with `this` set to the fake invocation
                deleteGroup.apply(invocation, [groupId]);

                // Verify that the method does what we expected
                assert.equal(Groups.find().count(), 0);
            });
        });