Example #1
0
File: main.js Project: Fabs/meteor
Meteor.startup(() => {
  let doc = collection.findOne();

  if (! doc) {
    collection.insert({ count: 0 });
    doc = collection.findOne();
  }

  collection.update(doc._id, {
    $inc: { count: 1 }
  });

  console.log("count: " + collection.findOne().count);
});
  client._livedata_data = function (msg) {
    if (msg.collection == productsName) {
      var fields = msg.fields;

      test.isTrue(quotes.findOne({_id: fields.quoteId}));
      test.equal(fields.name, names[fields.price / 1000]);

    } else if (msg.collection == quotesName) {
      test.equal(msg.fields, quotes.findOne({_id: msg.id}, {fields: {_id: 0}}));

    } else if (msg.msg == 'ready') {
      client.disconnect();
      done();
    }
  };
 insert: function(userId, doc) {
   let antenna = Antennas.findOne({ name: doc.name });
   if (antenna) {
     throw new Meteor.Error(403, 'This antenna already exists in the database.');
   }
   return Roles.userIsInRole(userId, ['admin']);
 },
      }, (error, newId2) => {
        expect(!!error).toBe(false);
        expect(typeof newId2).toBe('string');

        const doc = RES.findOne(newId2);
        expect(doc instanceof Object).toBe(true);
        expect(doc.bar).toBe('');

        // Don't remove empty strings for an update either
        RES.update({
          _id: newId1
        }, {
          $set: {
            bar: ''
          }
        }, {
          removeEmptyStrings: false
        }, (error, result) => {
          expect(!!error).toBe(false);
          expect(result).toBe(1);

          const doc = RES.findOne(newId1);
          expect(doc instanceof Object).toBe(true);
          expect(doc.bar).toBe('');
          done();
        });
      });
	publishCardset: function (id, kind, price, visible) {
		check(id, String);
		check(kind, String);
		check(visible, Boolean);

		// Make sure only the task owner can make a task private
		let cardset = Cardsets.findOne(id);
		if (UserPermissions.isAdmin() || UserPermissions.isOwner(cardset.owner)) {
			Cardsets.update(id, {
				$set: {
					kind: kind,
					price: price.toString().replace(",", "."),
					visible: visible
				}
			});
			if (kind !== "personal") {
				Meteor.users.update(Meteor.user()._id, {
					$set: {
						visible: true
					}
				});
			}
		} else {
			throw new Meteor.Error("not-authorized");
		}
	},
	updateCardset: function (id, name, description, cardType, difficulty, sortType) {
		check(id, String);
		check(name, String);
		check(description, String);
		check(cardType, Number);
		check(difficulty, Number);
		check(sortType, Number);
		// Make sure only the task owner can make a task private
		let cardset = Cardsets.findOne(id);
		if (UserPermissions.isAdmin() || UserPermissions.isOwner(cardset.owner)) {
			if (cardset.learningActive) {
				cardType = cardset.cardType;
			}

			Cardsets.update(id, {
				$set: {
					name: name.trim(),
					description: description,
					dateUpdated: new Date(),
					cardType: cardType,
					difficulty: difficulty,
					noDifficulty: !CardType.gotDifficultyLevel(cardType),
					sortType: sortType
				}
			}, {trimStrings: false});
			Cards.update({cardset_id: id}, {
				$set: {
					cardType: cardType
				}
			}, {trimStrings: false});
		} else {
			throw new Meteor.Error("not-authorized");
		}
	},
	Meteor.publish("workloadCardsets", function () {
		if (this.userId && UserPermissions.isNotBlockedOrFirstLogin()) {
			let workload = Workload.find({user_id: this.userId}, {fields: {cardset_id: 1}}).fetch();
			let filter = [];
			for (let i = 0, workloadLength = workload.length; i < workloadLength; i++) {
				if ((Leitner.find({cardset_id: workload[i].cardset_id}).count() !== 0) || (Wozniak.find({cardset_id: workload[i].cardset_id}).count() !== 0)) {
					filter.push(workload[i].cardset_id);
				}
			}
			let cardsets = [];
			let cardset;
			for (let i = 0, filterLength = filter.length; i < filterLength; i++) {
				cardset = Cardsets.findOne({_id: filter[i]}, {
					fields: {
						_id: 1,
						shuffled: 1,
						cardGroups: 1
					}
				});
				if (cardset !== undefined) {
					cardsets.push(filter[i]);
					if (cardset.shuffled) {
						for (let k = 0, cardGroupsLength = cardset.cardGroups.length; k < cardGroupsLength; k++) {
							cardsets.push(cardset.cardGroups[k]);
						}
					}
				}
			}
			return Cardsets.find({_id: {$in: cardsets}});
		} else {
			this.ready();
		}
	});
	deleteCards: function (id) {
		check(id, String);
		// Make sure only the task owner can make a task private
		let cardset = Cardsets.findOne(id);
		if (UserPermissions.isAdmin() || UserPermissions.isOwner(cardset.owner)) {
			Cards.remove({
				cardset_id: id
			});
			Cardsets.update({
					_id: id
				},
				{
					$set: {
						quantity: 0,
						kind: 'personal',
						reviewed: false,
						request: false,
						visible: false
					}
				}
			);
			Meteor.call('updateShuffledCardsetQuantity', cardset._id);
			Leitner.remove({
				cardset_id: id
			});
			Wozniak.remove({
				cardset_id: id
			});
		} else {
			throw new Meteor.Error("not-authorized");
		}
	},
	updateBonus: function (id, maxWorkload, daysBeforeReset, dateStart, dateEnd, intervals, registrationPeriod, maxBonusPoints) {
		check(id, String);
		check(maxWorkload, Number);
		check(daysBeforeReset, Number);
		check(dateStart, Date);
		check(dateEnd, Date);
		check(intervals, [Number]);
		check(registrationPeriod, Date);
		check(maxBonusPoints, Number);

		let cardset = Cardsets.findOne(id);
		if (cardset !== undefined && cardset.learningActive && (UserPermissions.isAdmin() || UserPermissions.isOwner(cardset.owner))) {
			intervals = intervals.sort(
				function (a, b) {
					return a - b;
				}
			);
			Cardsets.update(id, {
				$set: {
					maxCards: maxWorkload,
					daysBeforeReset: daysBeforeReset,
					learningStart: dateStart,
					learningEnd: dateEnd,
					learningInterval: intervals,
					registrationPeriod: registrationPeriod,
					"workload.bonus.maxPoints": Math.floor(maxBonusPoints)
				}
			});
			return cardset._id;
		} else {
			throw new Meteor.Error("not-authorized");
		}
	},
	deleteCardset: function (id) {
		check(id, String);
		// Make sure only the task owner can make a task private
		let cardset = Cardsets.findOne(id);
		if (UserPermissions.isAdmin() || UserPermissions.isOwner(cardset.owner)) {
			Cardsets.remove(id);
			Cards.remove({
				cardset_id: id
			});
			Meteor.call('updateShuffledCardsetQuantity', id);
			Leitner.remove({
				cardset_id: id
			});
			Wozniak.remove({
				cardset_id: id
			});
			Notifications.remove({
				link_id: id
			});
			Ratings.remove({
				cardset_id: id
			});
			Workload.remove({
				cardset_id: id
			});
			Meteor.call('updateCardsetCount', Meteor.userId());
		} else {
			throw new Meteor.Error("not-authorized");
		}
	},
      Dapple['maker-otc'].objects.otc.offers(idx.toNumber(), (error, data) => {
        if (!error) {
          const offer = Offers.findOne({ _id: idx.toString() });

          if (offer) {
            const [, , , , , active] = data;
            Offers.syncOffer(idx.toNumber());
            /**
             * When the order matching is enabled there is check on the contract side
             * before the creating new order.
             * It checks if the new order is about to match existing one. There are couple of scenarios:
             *
             *  - New order is filled in completely but the existing one is completed partially or completely
             *    = then no order is actually created on the blockchain so the UI has offer is transaction id only.
             *
             *  - New order is not filled in completely but fills the existing one completely
             *    = then new order is created with the remainings after the matching is done.
             *
             * Transaction hash of the event in the first case scenario, corresponds to the transaction hash,
             * used to store the offer on the client. In order to update the UI accordingly, when the first scenario is met
             * we used the transaction has to remove the new order from the collection.
             * */
            Offers.remove(result.transactionHash);
            if (!active) {
              Offers.remove(idx.toString());
            }
          }
        }
      });
  /**
   * Get the count of the cursor.
   *
   * @params {Object} searchDefinition Search definition
   *
   * @returns {Cursor.count}
   *
   * @private
   */
  _getCount(searchDefinition) {
    let countDoc = this._collection.findOne('searchCount' + JSON.stringify(searchDefinition));

    if (countDoc) {
      return countDoc.count;
    }
  }
Example #13
0
	deleteTranscript: function (card_id) {
		let card = Cards.findOne(card_id);
		if (card.owner === Meteor.userId() || UserPermissions.isAdmin()) {
			let result = Cards.remove(card_id);
			Meteor.call('updateTranscriptCount', Meteor.userId());
			return result;
		}
	},
Example #14
0
	trashFindOneById(_id, options) {
		const query = {
			_id,
			__collection__: this.name,
		};

		return trash.findOne(query, options);
	}
Example #15
0
 'findStudentForUserId':function(){
   //console.log('inside server findStudentForUserId '+this.userId);
    if (! this.userId) {
       throw new Meteor.Error('not-authorized');
    }
   const dbStudent = Students.findOne({_id:this.userId});
   return dbStudent;
 },
const checkForWatcher = () => {
    const current = Servers.findOne({ watcher: true });
    if (current) {
        return true;
    }
    setAsWatcher();
    return false;
};
  client._livedata_data = function (msg) {
    if (msg.msg == 'added') {
      test.equal(msg.collection, quotesName);
      client.call('changePagination', 'replies', msg.id, 2);
      
      var quote = quotes.findOne({_id: msg.id});
      test.equal(msg.fields.replies, quote.replies.slice(0, 2));

    } else if (msg.msg == 'changed') {
      test.equal(msg.collection, quotesName);

      var quote = quotes.findOne({_id: msg.id});
      test.equal(msg.fields.replies, quote.replies.slice(2, 4));

    } else if (msg.msg == 'updated') {
      client.disconnect();
    }
  };
        }, (error, result) => {
          expect(!!error).toBe(false);
          expect(result).toBe(1);

          const doc = RES.findOne(newId1);
          expect(doc instanceof Object).toBe(true);
          expect(doc.bar).toBe('');
          done();
        });
 'songs.insert':function(track){
   let s = Songs.findOne({"track.id":track.id});
   if(!s){
      Songs.insert({
        track:track,
        addedOn : new Date()
      });
    }
 },
Example #20
0
        testHandler: (onComplete) => {
            const marieAsAuthor = Authors.findOne({ username: '******' });
            const stephenAsCommentAuthor = CommentAuthors.findOne({ username: '******' });

            asyncExpect(() => expect(marieAsAuthor).to.be.defined, onComplete);
            asyncExpect(() => expect(stephenAsCommentAuthor).to.not.be.defined, onComplete);

            onComplete();
        },
  'Characters.toggleSkill': function(id, skill) {
    const character = Characters.findOne(id);

    if (character.skills[skill]) {
      Characters.update(id, { $unset: { [`skills.${skill}`]: '' } });
    } else {
      Characters.update(id, { $set: { [`skills.${skill}`]: 1 } });
    }
  },
Example #22
0
        testHandler: (onComplete) => {
            const albertAsAuthor = Authors.findOne({ username: '******' });
            const albertAsCommentAuthor = CommentAuthors.findOne({ username: '******' });

            asyncExpect(() => expect(albertAsAuthor).to.be.defined, onComplete);
            asyncExpect(() => expect(albertAsCommentAuthor).to.be.defined, onComplete);

            onComplete();
        },
Example #23
0
 Meteor.publish("documentsByName", function (name) {
   var docs = Documents.find({name: name});
   var doc = Documents.findOne({name: name})
   this.onStop(() => {
     if (doc) Documents.update({ _id: doc._id}, { $inc: { watchingCount: -1 }})
   })
   if (doc) Documents.update({ _id: doc._id},
                             { $inc: { watchingCount: 1, visitorsCount: 1 }})
   return docs;
 });
Example #24
0
export function getAuth(userId) {
    var auth;

    if (userId) {
        var email = getEmail(userId);
        auth = Authorizations.findOne({"email": email});
    }

    return auth;
}
Example #25
0
Roles.createRole = role => {
  role = role.trim().toLowerCase();
  try {
    if (!rolesDb.findOne({name: role})) {
      return rolesDb.insert({name: role});
    }
  }
  catch (e) {
    throw new Error("Roles: problem inserting role. " + e);
  }
};
Example #26
0
Router.route('/contractinfo', function () {
  var req = this.request;
  var res = this.response;
  if (Contract.find().count()==0){
    res.end("");
  }
  else{
    var contractaddress = Contract.findOne().address;
    res.end(contractaddress);
  }
}, {where: 'server'});
Example #27
0
	updateCard: function (card_id, subject, content1, content2, content3, content4, content5, content6, centerTextElement,alignType, learningGoalLevel, backgroundStyle, learningIndex, learningUnit) {
		check(card_id, String);
		check(subject, String);
		check(content1, String);
		check(content2, String);
		check(content3, String);
		check(content4, String);
		check(content5, String);
		check(content6, String);
		check(centerTextElement, [Boolean]);
		check(alignType, [Number]);
		check(learningGoalLevel, Number);
		check(backgroundStyle, Number);
		check(learningIndex, String);
		check(learningUnit, String);
		let card = Cards.findOne(card_id);
		let cardset = Cardsets.findOne(card.cardset_id);
		let isOwner = false;
		if (card.cardset_id === "-1") {
			isOwner = true;
		} else {
			isOwner = UserPermissions.isOwner(cardset.owner);
		}
		if (UserPermissions.isAdmin() || isOwner) {
			if (subject === "") {
				throw new Meteor.Error("Missing subject");
			}
			Cards.update(card_id, {
				$set: {
					subject: subject.trim(),
					front: content1,
					back: content2,
					hint: content3,
					lecture: content4,
					top: content5,
					bottom: content6,
					centerTextElement: centerTextElement,
					alignType: alignType,
					learningGoalLevel: learningGoalLevel,
					backgroundStyle: backgroundStyle,
					learningIndex: learningIndex,
					learningUnit: learningUnit,
					dateUpdated: new Date()
				}
			}, {trimStrings: false});
			Cardsets.update(card.cardset_id, {
				$set: {
					dateUpdated: new Date()
				}
			});
		} else {
			throw new Meteor.Error("not-authorized");
		}
	}
Example #28
0
Router.route('/nodeinfo', function () {
  var req = this.request;
  var res = this.response;
  if (Contract.find().count()==0){
    res.end("");
  }
  else{
    var enode = Enode.findOne().enode;
    res.end(enode);
  }
}, {where: 'server'});
			return function(doc) {
				if (doCheckWithHC) {
					// let hcDoc = HierarchicalUserProperties._HierarchyCollection.findOne({_id: doc.nodeId});
					let hcDoc = WBSCollection.findOne({ _id: doc.nodeId });
					const hcUsnList = hcDoc.upstreamNodeIdList.sort();
					const ownUsnList = (doc.upstreamNodeIdList || ['!!!!!!']).sort();
					console.log('-----\n', msg, arguments, _.isEqual(hcUsnList, ownUsnList) ? ['Ok.'] : ['****** NOT OK! ******', doc, hcDoc], '\n-----');
				} else {
					console.log('-----\n', msg, arguments, '\n-----');
				}
			};
Example #30
0
export function getNextSequence(name) {
    var ndocs = Counters.update(
        {_id: name},
        {$inc: {seq: 1}},
        {multi: false},
        {upsert: false}
    );

    var doc = Counters.findOne({_id: name});

    return doc.seq;
}