Example #1
0
Meteor.startup(function() {
	TimeSync.loggingEnabled = false;

	Session.setDefault('AvatarRandom', 0);

	window.lastMessageWindow = {};
	window.lastMessageWindowHistory = {};

	Tracker.autorun(function(computation) {
		if (!Meteor.userId() && !RocketChat.settings.get('Accounts_AllowAnonymousRead')) {
			return;
		}
		Meteor.subscribe('userData');
		Meteor.subscribe('activeUsers');
		computation.stop();
	});

	let status = undefined;
	Tracker.autorun(function() {
		if (!Meteor.userId()) {
			return;
		}
		const user = RocketChat.models.Users.findOne(Meteor.userId(), {
			fields: {
				status: 1,
				'settings.preferences.idleTimeLimit': 1,
				'settings.preferences.enableAutoAway': 1,
			},
		});

		if (!user) {
			return;
		}

		if (RocketChat.getUserPreference(user, 'enableAutoAway')) {
			const idleTimeLimit = RocketChat.getUserPreference(user, 'idleTimeLimit') || 300;
			UserPresence.awayTime = idleTimeLimit * 1000;
		} else {
			delete UserPresence.awayTime;
			UserPresence.stopTimer();
		}

		UserPresence.start();

		if (user.status !== status) {
			status = user.status;
			fireGlobalEvent('status-changed', status);
		}
	});
});
Example #2
0
Router.go = (path, params, query) => {
  let actualPath;

  const routerGo = () => {
    if (typeof path === "string" && path.startsWith("/")) {
      actualPath = path;
    } else {
      actualPath = Router.pathFor(path, {
        hash: {
          ...params,
          query
        }
      });
    }

    if (window) {
      history.push(actualPath);
    }
  };

  // if Router is in a non ready/initialized state yet, wait until it is
  if (!Router.ready()) {
    Tracker.autorun(routerReadyWaitFor => {
      if (Router.ready()) {
        routerReadyWaitFor.stop();
        routerGo();
      }
    });

    return;
  }

  routerGo();
};
Example #3
0
Meteor.startup(function() {
	Tracker.autorun(function() {
		if (Meteor.userId()) {
			Meteor.call('getUserRoles', (error, results) => {
				if (error) {
					return handleError(error);
				}

				for (const record of results) {
					UserRoles.upsert({ _id: record._id }, record);
				}
			});

			RocketChat.Notifications.onLogged('roles-change', function(role) {
				if (role.type === 'added') {
					if (role.scope) {
						RoomRoles.upsert({ rid: role.scope, 'u._id': role.u._id }, { $setOnInsert: { u: role.u }, $addToSet: { roles: role._id } });
					} else {
						UserRoles.upsert({ _id: role.u._id }, { $addToSet: { roles: role._id }, $set: { username: role.u.username } });
						ChatMessage.update({ 'u._id': role.u._id }, { $addToSet: { roles: role._id } }, { multi: true });
					}
				} else if (role.type === 'removed') {
					if (role.scope) {
						RoomRoles.update({ rid: role.scope, 'u._id': role.u._id }, { $pull: { roles: role._id } });
					} else {
						UserRoles.update({ _id: role.u._id }, { $pull: { roles: role._id } });
						ChatMessage.update({ 'u._id': role.u._id }, { $pull: { roles: role._id } }, { multi: true });
					}
				} else if (role.type === 'changed') {
					ChatMessage.update({ roles: role._id }, { $inc: { rerender: 1 } }, { multi: true });
				}
			});
		}
	});
});
Example #4
0
FlowRouter.subscriptions = function() {
	Tracker.autorun(() => {
		if (Meteor.userId()) {
			this.register('userData', Meteor.subscribe('userData'));
			this.register('activeUsers', Meteor.subscribe('activeUsers'));
		}
	});
};
Example #5
0
Template.avatarPrompt.onRendered(function() {
	Tracker.afterFlush(function() {
		if (!RocketChat.settings.get('Accounts_AllowUserAvatarChange')) {
			FlowRouter.go('home');
		}
		SideNav.setFlex('accountFlex');
		SideNav.openFlex();
	});
});
Example #6
0
Meteor.subscribe('demand', () => {
  Tracker.autorun(() => {
    const latest = Demand.find({}, {sort: {_id:-1}, limit:1}).fetch()[0];
    window.fossil.set(latest.fossil);
    window.nuclear.set(latest.nuclear);
    window.green.set(latest.green);
    window.other.set(latest.other);
  });
});
Example #7
0
	Tracker.autorun(function() {
		let unreadCount = 0;
		let unreadAlert = false;

		const subscriptions = ChatSubscription.find({ open: true, hideUnreadStatus: { $ne: true } }, { fields: { unread: 1, alert: 1, rid: 1, t: 1, name: 1, ls: 1, unreadAlert: 1 } });

		let openedRoomId = undefined;
		Tracker.nonreactive(function() {
			if (['channel', 'group', 'direct'].includes(FlowRouter.getRouteName())) {
				openedRoomId = Session.get('openedRoom');
			}
		});

		for (const subscription of subscriptions.fetch()) {
			fireGlobalEvent('unread-changed-by-subscription', subscription);

			if (subscription.alert || subscription.unread > 0) {
				// This logic is duplicated in /client/notifications/notification.coffee.
				const hasFocus = readMessage.isEnable();
				const subscriptionIsTheOpenedRoom = openedRoomId === subscription.rid;
				if (hasFocus && subscriptionIsTheOpenedRoom) {
					// The user has probably read all messages in this room.
					// TODO: readNow() should return whether it has actually marked the room as read.
					Meteor.setTimeout(function() {
						readMessage.readNow();
					}, 500);
				}

				// Increment the total unread count.
				unreadCount += subscription.unread;
				if (subscription.alert === true && subscription.unreadAlert !== 'nothing') {
					const userUnreadAlert = getUserPreference(Meteor.userId(), 'unreadAlert');
					if (subscription.unreadAlert === 'all' || userUnreadAlert !== false) {
						unreadAlert = '•';
					}
				}
			}

			if (RoomManager.openedRooms[subscription.t + subscription.name]) {
				readMessage.refreshUnreadMark(subscription.rid);
			}
		}

		menu.updateUnreadBars();

		if (unreadCount > 0) {
			if (unreadCount > 999) {
				Session.set('unread', '999+');
			} else {
				Session.set('unread', unreadCount);
			}
		} else if (unreadAlert !== false) {
			Session.set('unread', unreadAlert);
		} else {
			Session.set('unread', '');
		}
	});
Example #8
0
 componentDidMount() {
     this.linksTracker = Tracker.autorun(() => {
         Meteor.subscribe("links");
         const links = Links.find({
             visible: Session.get("showVisible")
         }).fetch();
         this.setState({ links });
     });
 }
Example #9
0
Meteor.startup(() => {
  let title = 'Score Keep';

  Tracker.autorun(() => {
      ReactDOM.render(
          <App title={title} />,
          document.querySelector('#app')
      );
  });
});
Example #10
0
  this.editList = () => {
    this.state.set ( 'editing', true );

    // force the template to redraw based on the reactive change
    Tracker.flush ();
    // We need to wait for the fade in animation to complete to reliably focus the input
    Meteor.setTimeout ( () => {
      this.$ ( '.js-edit-form input[type=text]' ).focus ();
    }, 400 );
  };
Example #11
0
 componentDidMount() {
   console.log('componentDidMount LinksList');
   this.linksTracker = Tracker.autorun(() => {
     Meteor.subscribe('links');
     const links = Links.find({
       visible: Session.get('showVisible')
     }).fetch();
     this.setState({ links });
   });
 }
Example #12
0
	/*
	 * Adds an option in Channel Settings
	 * @config (object)
	 *   id: option id (required)
	 *   template (string): template name to render (required)
	 *   validation (function): if option should be displayed
 */
	addOption(config) {
		if (config == null || config.id == null) {
			return false;
		}
		return Tracker.nonreactive(() => {
			const opts = this.options.get();
			opts[config.id] = config;
			return this.options.set(opts);
		});
	}
Example #13
0
Meteor.startup(function () {
  Tracker.autorun(function () {
    // initialize client routing
    if (Reaction.Subscriptions.Packages.ready() && Reaction.Subscriptions.Shops.ready()) {
      if (!Router._initialized) {
        Router.initPackageRoutes();
      }
    }
  });
});
Template.livechatAnalytics.onRendered(() => {
	Tracker.autorun(() => {
		if (templateInstance.daterange.get() && templateInstance.analyticsOptions.get() && templateInstance.chartOptions.get()) {
			updateAnalyticsOverview();
			updateAnalyticsChart();
		}

	});

});
Example #15
0
 componentDidMount() {
   // Tracker is used to determine if a user has `hasShopSwitcherAccess` permission
   // If they do not, set the shop one time, and then not again
   // If the user does have hasShopSwitcherAccess` permission, shop is set by this.renderShopSelect()
   this.tracker = Tracker.autorun(() => {
     if (!Reaction.hasShopSwitcherAccess()) {
       this.onShopSelectChange(null, Reaction.getSellerShopId());
     }
   });
 }
Example #16
0
			}, (err) => {
				if (err && err.error) {
					return Materialize.toast(err.error, 4000);
				}

				Materialize.toast('Proyecto borrado exitosamente', 4000);
				instance.selectedProject.set('');
				Tracker.afterFlush(() => {
					$('select').material_select();
				});
			});
Example #17
0
File: done.js Project: SunFed/store
Template.paypalDone.onCreated(function () {
  const payerId = Reaction.Router.getQueryParam("PayerID");
  const token = Reaction.Router.getQueryParam("token");
  const prefix = Reaction.getShopPrefix();
  this.checkoutUrl = `${prefix}/cart/checkout`;
  // wait for cart to be ready
  Tracker.autorun(function (c) {
    if (Reaction.Subscriptions.Cart.ready()) {
      const cart = Cart.findOne();
      if (!cart) {
        Logger.warn("Could not find valid cart");
        return;
      }
      c.stop();
      if (Session.get("expressToken") !== token) {
        Session.set("expressToken", token);
        Meteor.call("confirmPaymentAuthorization", cart._id, token, payerId, function (error, result) {
          if (error) {
            if (isDuplicate(error)) {
              Reaction.Router.go("cart/completed", {}, {
                _id: cart._id
              });
            }
            const msg = (error !== null ? error.error : void 0);
            showError(msg);
          }

          if (result) {
            let status;
            let mode = "authorize";
            // Normalize status depending on results
            if (result.PAYMENTSTATUS === "Pending") {
              status = "created";
            } else if (result.PAYMENTSTATUS === "Completed") { // If we set capture at auth this will be completed
              status = "completed";
              mode = "capture";
            } else {
              status = result.PAYMENTSTATUS;
            }
            const paymentMethod = buildPaymentMethod(result, status, mode);

            Meteor.call("cart/submitPayment", paymentMethod, function (payError, payResult) {
              if (!payResult && payError) {
                Logger.warn(payError, "Error received during submitting Payment via Paypal");
                showError(payError);
                Session.set("guestCheckoutFlow", true);
              }
            });
          }
        });
      }
    }
  });
});
Example #18
0
  this.editList = () => {
    this.state.set('editing', true);

    // force the template to redraw based on the reactive change
    Tracker.flush();
    // TODO -- I think velocity introduces a timeout before actually setting opacity on the
    //   element, so I can't focus it for a moment.
    Meteor.setTimeout(() => {
      this.$('.js-edit-form input[type=text]').focus();
    });
  };
 LoginButtons.prototype._initAutorun = function () {
     var _this = this;
     this.autorunComputation = tracker_1.Tracker.autorun(function () {
         _this.zone.run(function () {
             _this.currentUser = meteor_1.Meteor.user();
             _this.currentUserId = meteor_1.Meteor.userId();
             _this.isLoggingIn = meteor_1.Meteor.loggingIn();
             _this.isLoggedIn = !!meteor_1.Meteor.user();
         });
     });
 };
Example #20
0
 const observable = pickStream(propsStream, propsList).switchMap(props => Observable.create((observer) => {
   let autorunHandler;
   Tracker.nonreactive(() => {
     autorunHandler = Tracker.autorun(() => {
       observer.next(getMeteorData(props));
     });
   });
   return () => {
     autorunHandler.stop();
   };
 }));
Example #21
0
Template['views_search'].onCreated(function() {

  template = this;
  template.coopsVar = new ReactiveVar([]);

  Tracker.autorun(function() {
    db.coops.getAll().then(function(coops) {
      template.coopsVar.set(coops);
    })
  });
});
Example #22
0
Meteor.startup(function() {
	Tracker.autorun(function() {
		if (isSetNotNull(() => emoji.packages.emojione)) {
			if (isSetNotNull(() => getUserPreference(Meteor.userId(), 'convertAsciiEmoji'))) {
				emoji.packages.emojione.ascii = getUserPreference(Meteor.userId(), 'convertAsciiEmoji');
			} else {
				emoji.packages.emojione.ascii = true;
			}
		}
	});
});
Meteor.startup(function() {
	Tracker.autorun(function() {
		const user = RocketChat.models.Users.findOne({ _id: Meteor.userId() }, { fields: { statusConnection: 1, utcOffset: 1 } });
		if (user && user.statusConnection === 'online') {
			const utcOffset = moment().utcOffset() / 60;
			if (user.utcOffset !== utcOffset) {
				Meteor.call('userSetUtcOffset', utcOffset);
			}
		}
	});
});
 it('get the last DDP message reactively', function (done) {
   setTimeout(function () {
      Meteor.call('__ddp-messages-test-send-message__', { name: 'test',  data: { foo: 'bar' }});
   }, 500);
   Tracker.autorun(function () {
     const msg = getLastDDPMessage('test');
     if (msg) {
       expect(msg).to.deep.equal({ foo: 'bar' });
       done();
     }
   });
 });
Example #25
0
Meteor.startup(function () {
  BlazeLayout.setRoot('body')

  TimeSync.loggingEnabled = false

  Tracker.autorun((tracker) => {
    try {
      UserStatus.startMonitor({ threshold: 30000 })
      tracker.stop()
    } catch (e) { }
  })
})
export default () => {
  const store = createStore(reducers, applyMiddleware(thunk));

  Tracker.autorun(() => {
    store.dispatch({
      type: 'SET_MESSAGES',
      messages: Messages.find().fetch(),
    });
  });

  return store;
};
Meteor.startup(function() {
	Tracker.autorun(function() {
		const userId = Meteor.userId();
		const rid = Session.get('openedRoom');

		if (!userId || !rid) {
			return;
		}

		reloadUsersFromRoomMessages(userId, rid);
	});
});
Example #28
0
			}, (err) => {
				if (err && err.error) {
					return Materialize.toast(err.error, 4000);
				}

				$('#platings').val('');
				$('#plating').val('');
				Materialize.toast('Datos de enchape actualizados exitosamente', 4000);
				Tracker.afterFlush(() => {
					$('select').material_select();
				});
			});
Example #29
0
Meteor.startup(function() {
	Tracker.autorun(function() {
		if (Meteor.userId()) {
			Notifications.onUser('webrtc', (type, data) => {
				if (data.room == null) {
					return;
				}
				const webrtc = WebRTC.getInstanceByRoomId(data.room);
				webrtc.transport.onUserStream(type, data);
			});
		}
	});
});
Example #30
0
			}, (err) => {
				if (err && err.error) {
					return Materialize.toast(err.error, 4000);
				}

				Materialize.toast('Enchape borrado exitosamente', 4000);
				instance.selectedPlating.set('');
				$('#platings').val('');
				$('#plating').val('');
				Tracker.afterFlush(() => {
					$('select').material_select();
				});
			});