Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- define(["platform-config", "underscore", "jquery", "backbone",
- "init",
- "common-services/utils",
- "common-services/ServicesLoader",
- "services/Connection",
- "utils",
- "views/SimpleLayout",
- "views/ReadingZoneMainView",
- "views/InterestSettingsView",
- "views/InterestsLinksSidebarView",
- "views/UserVerificationView",
- "views/CollectionsAdminView",
- "views/ErrorView",
- "views/SignupView",
- "views/ResetPasswordView",
- "views/DialogAuthView",
- "views/ArticleView",
- "views/CreateCollectionView",
- "views/AddArticleToCollectionsView",
- "backbone.layoutmanager",
- "jquery.hammer"
- ],
- function (platformConfig, _, $, Backbone, init, commonUtils, servicesLoader, Connection, utils, SimpleLayout,
- ReadingZoneMainView, InterestSettingsView, InterestsLinksSidebarView, UserVerificationView,
- CollectionsAdminView, ErrorView, SginupView, ResetPasswordView, DialogAuthView, ArticleView,
- CreateCollectionView, AddArticleToCollectionsView) {
- 'use strict';
- var SERVICE = {
- UPDATES: 'updates',
- LOGIN: 'login',
- // BOOKMARKS: 'bookmarks',
- INTERESTS: 'interests',
- PERSONALIZED_ARTICLES: 'personalized-articles',
- KEEN: 'keen',
- SESSION_TRACKER: 'session-tracker',
- FACEBOOK: 'facebook',
- GOOGLE: 'google',
- ARTICLE: 'article',
- COLLECTIONS: 'collections',
- CHANNELS_MAP: 'channels-map',
- ME_CHANNELS_MAP: 'me-channels-map'
- };
- var TABS = {
- ARTICLES: {
- id: '#page-content--article',
- index: 0,
- active: true
- },
- COLLECTIONS: {
- id: '#page-content--collections',
- index: 1,
- active: false
- },
- PROFILE: {
- id: '#page-content--profile',
- index: 2,
- active: false
- },
- VERIFICATION: {
- id: '#page-content--verification',
- index: 3,
- active: false
- },
- COLLECTIONS_ADMIN: {
- id: '#page-content--collections-admin',
- index: 4,
- active: false
- }
- };
- function _showWaitingSpinner(show) {
- utils.showSpinner('.waiting-spinner', show);
- }
- function fbReportSignupSuccess(provider) {
- var loginSrv = window.miServices.get(SERVICE.LOGIN);
- loginSrv.getProfile()
- .then(function (profile) {
- var isLead = profile.userType === 'lead';
- Backbone.trigger('fb:event', 'SIGNUP', {
- STATE: 'completed',
- USER_CATEGORY: isLead ? 'lead' : 'user', //TODO: adapt field name when is ready
- CREATION_DATE: profile.timeCreated, //TODO: adapt field name when is ready
- CONVERSION_DATE: isLead ? (new Date()).toJSON() : profile.timeCreated, //TODO: adapt field name when is ready
- INTERESTS: profile.speciality,
- PARTNER_RELATION: '',
- AUTHENTICATION_PROVIDER: provider
- });
- });
- }
- function fbReportSigninSuccess(provider) {
- Backbone.trigger('fb:event', 'SIGNIN', {
- STATE: 'completed',
- AUTHENTICATION_PROVIDER: provider
- });
- }
- function fbReportSignupFail(provider, error) {
- Backbone.trigger('fb:event', 'SIGNUP', {
- STATE: 'failed',
- ERROR: error,
- AUTHENTICATION_PROVIDER: provider
- });
- }
- var DEFAULT_COLOR = 'rgb(181, 80, 222)';
- function _colorize(articles, channelsConfig) {
- articles.map(function (article) {
- var config = channelsConfig[article.channel];
- article.color = config ? config.color : DEFAULT_COLOR;
- article.channelName = config ? config.name : article.channel;
- });
- return articles;
- }
- return _.extend({}, {
- // Application Constructor
- initialize: function (config) {
- this.config = config;
- this.bindEvents();
- window.Connection = Connection;
- },
- _createRouter: function () {
- var app = this;
- var Router = Backbone.Router.extend({
- routes: {
- "": "home",
- "logout": "logout",
- "login/:email": "login",
- "interest/:interest": "interest",
- "profile/settings": "settings",
- "profile/remove-interest/:interest": "settingsRemoveInterest",
- "editor/published/": "editorViewPublished",
- "editor/published/:interest": "editorViewPublished",
- "editor/not-published/": "editorViewNotPublished",
- "editor/not-published/:interest": "editorViewNotPublished",
- "editor/skipped/": "editorViewSkipped",
- "editor/skipped/:interest": "editorViewSkipped",
- "reset-password/": "resetPassword",
- "article/:articleId": "showArticle"
- },
- home: function () {
- if (!app._loaded) { // handle during page load
- Backbone.trigger('keen:event', {
- type: 'page',
- action: 'show',
- name: 'home'
- });
- }
- },
- interest: function (interest) {
- $(".mdl-layout__tab:eq(0) span").click();
- Backbone.trigger("interest-selected", {
- interest: interest
- });
- app._showArticles(interest);
- $(".mdl-layout__content").animate({
- scrollTop: 0
- }, 500, "swing");
- this.hideDrawer();
- Backbone.trigger('keen:event', {
- type: 'page',
- action: 'show',
- name: 'interest-articles'
- });
- Backbone.trigger('keen:event', {
- type: 'channel',
- action: 'open',
- channelId: interest,
- channelType: 'interest',
- mimeType: 'mixed'
- });
- },
- settings: function () {
- $(".mdl-layout__tab:eq(1) span").click();
- this.hideDrawer();
- Backbone.trigger('keen:event', {
- type: 'page',
- action: 'show',
- name: 'interest-settings'
- });
- },
- settingsRemoveInterest: function (interest) {
- app._removeInterest(interest);
- },
- hideDrawer: function () {
- if ($('.mdl-layout__drawer.is-visible').length > 0) {
- var layout = document.querySelector('.mdl-layout');
- layout.MaterialLayout.toggleDrawer();
- }
- },
- editorViewPublished: function (interest) {
- app._renderEditorPublished(interest);
- },
- editorViewNotPublished: function (interest) {
- app._renderEditorNotPublished(interest);
- },
- editorViewSkipped: function (interest) {
- app._renderEditorSkipped(interest);
- },
- logout: function () {
- app._logout();
- },
- login: function (email) {
- app._login(email);
- },
- resetPassword: function () {
- app._resetPassword();
- },
- showArticle: function (articleId) {
- app._showArticle(articleId);
- }
- });
- this._router = new Router();
- Backbone.history.start({pushState: true});
- return commonUtils.resolvedPromise();
- },
- _navigate: function (path) {
- this._router.navigate(path, {
- trigger: true
- });
- },
- _back: function () {
- window.history.back();
- },
- // Bind Event Listeners
- //
- // Bind any events that are required on startup. Common events are:
- // 'load', 'deviceready', 'offline', and 'online'.
- bindEvents: function () {
- document.addEventListener('deviceready', _.bind(this.onDeviceReady, this), false);
- // this.onDeviceReady();
- },
- // deviceready Event Handler
- //
- // The scope of 'this' is the event. In order to call the 'receivedEvent'
- // function, we must explicitly call 'app.receivedEvent(...);'
- onDeviceReady: function () {
- _showWaitingSpinner(true);
- $('.config-title').text(platformConfig.title);
- this._loadServices(this.config.services)
- .then(_.bind(this._initAnalytics, this))
- .then(_.bind(this._initSessionTracking, this))
- .then(_.bind(this._initInterests, this))
- .then(_.bind(this._initChannels, this))
- .then(_.bind(this._autoLogin, this))
- .then(_.bind(this._renderLayoutTabArticle, this))
- .then(_.bind(this._renderTabArticle, this))
- .then(_.bind(this._displayProfileSettings, this))
- .then(_.bind(this._displayMyCollections, this))
- .then(_.bind(this._displayUserVerification, this))
- .then(_.bind(this._displayCollectionsAdmin, this))
- .then(_.bind(this._createRouter, this))
- .then(_.bind(this._loadMainListeners, this))
- .then(_.bind(this._publisherModeConfiguration, this))
- .then(_.bind(this._hideLoadingSpinner, this))
- .then(_.bind(this._updateSignOutButtonState, this))
- .then(_.bind(function () {
- var loginService = window.miServices.get(SERVICE.LOGIN);
- this.dialogAuth = new DialogAuthView({});
- this.dialogAuth.setElement('#dialogs').render();
- Backbone.on('hide-auth-buttons', _.bind(function () {
- $('.login-signin-buttons-container').addClass('hidden');
- $('.responsive-login-register-buttons').addClass('hidden');
- if (!this.checkIsItDevice()) {
- $('.sign-out-button-container').removeClass('hidden');
- } else {
- $('.responsive-sign-out-button').removeClass('hidden');
- }
- }, this));
- Backbone.on('show-auth-buttons', _.bind(function () {
- if (!this.checkIsItDevice()) {
- $('.login-signin-buttons-container').removeClass('hidden');
- $('.sign-out-button-container').addClass('hidden');
- } else {
- $('.responsive-login-register-buttons').removeClass('hidden');
- $('.responsive-sign-out-button').addClass('hidden');
- }
- }, this));
- Backbone.on('editor:show-skipped', _.bind(function () {
- this._navigate('editor/skipped/');
- }, this));
- Backbone.on('editor:show-published', _.bind(function () {
- this._navigate('editor/published/');
- }, this));
- Backbone.on('editor:show-unpublished', _.bind(function () {
- this._navigate('editor/not-published/');
- }, this));
- Backbone.on('show-article-excerpt', _.bind(function (articleId) {
- this._navigate('article/' + articleId);
- }, this));
- loginService.on(loginService.loginStateChangedEventName, _.bind(function () {
- loginService.getProfile()
- .then(_.bind(function (profile) {
- if (profile) {
- this._displayMyCollections();
- this._displayProfileSettings();
- this._displayUserVerification();
- this._displayCollectionsAdmin();
- } else {
- if ($("#profile-page-link").is(":visible") ||
- $("#verification-page-link").is(":visible") ||
- $("#collections-page-link").is(":visible") ||
- $("#collections-admin-page-link").is(":visible")) {
- window.location.reload();
- }
- }
- }, this))
- .fail(function (err) {
- console.error(err);
- });
- }, this));
- this._loaded = true;
- _showWaitingSpinner(false);
- if (this._showLogin) {
- this.dialogAuth._login = true;
- this.dialogAuth._email = this._email;
- delete this._showLogin;
- delete this._email;
- }
- $('.signin-button').click(_.bind(function () {
- this.dialogAuth.showHideModalDialog("login", true);
- }, this));
- $('.signup-button').click(_.bind(function () {
- this.dialogAuth.showHideModalDialog("register", true);
- }, this));
- $('.signout-button').click(_.bind(function () {
- this._navigate('logout');
- }, this));
- $('.responsive-signin-button').click(_.bind(function () {
- this.dialogAuth.showHideModalDialog("login", true);
- }, this));
- $('.responsive-signup-button').click(_.bind(function () {
- this.dialogAuth.showHideModalDialog("register", true);
- }, this));
- $('.responsive-signout-button').click(_.bind(function () {
- window.location.replace("#logout/");
- window.location.href = "#logout/";
- }, this));
- loginService.getProfile().then(_.bind(function (user) {
- if (!user) {
- Backbone.trigger("show-auth-buttons");
- _.delay(_.bind(function () {
- loginService.getProfile().then(_.bind(function (user) {
- if (!user) {
- if (!this.dialogAuth.isDialogCurrentlyShowing()) {
- this.dialogAuth.showHideModalDialog("login", true);
- }
- } else {
- Backbone.trigger("hide-auth-buttons");
- }
- }, this));
- }, this), 5000);
- } else {
- Backbone.trigger("hide-auth-buttons");
- }
- }, this));
- return commonUtils.resolvedPromise();
- }, this))
- .fail(_.bind(function (error) {
- this._hideLoadingSpinner();
- _showWaitingSpinner(false);
- $('.mdl-spinner').css('display', 'none');
- var errorView = new ErrorView();
- $(TABS.ARTICLES.id).append(errorView.el);
- console.error(error);
- return errorView.render().promise();
- }, this));
- /* jshint ignore:start */
- $('.close-chip').click(_.bind(function (event) {
- sessionStorage.setItem('disableChip', true);
- $('#openInApp').addClass('hidden');
- event.stopPropagation();
- }, this));
- $('#openInApp').click(function () {
- window.location.replace(platformConfig.appLink);
- });
- if (!sessionStorage.getItem('disableChip') && this.checkIsItDevice()) {
- $('#openInApp').removeClass('hidden');
- }
- },
- _initAnalytics: function () {
- var keenSrv = window.miServices.get(SERVICE.KEEN);
- if (keenSrv) {
- Backbone.on('keen:event', function (data, sendExtendedInfo) {
- keenSrv.trackEvent(data, sendExtendedInfo);
- });
- console.info('Keen analytics is initialized');
- } else {
- console.info('Keen analytics is not configured');
- }
- var fbSrv = window.miServices.get(SERVICE.FACEBOOK);
- function _logFBEvent(eventName, params) {
- // for testing
- // console.log('FB event: ' + eventName + ': ' + JSON.stringify(params));
- fbSrv.logEvent(eventName, params);
- }
- if (fbSrv) {
- Backbone.on('fb:event', function (eventName, params) {
- if ((eventName === "SIGNIN" || eventName === "SIGNUP") && params && params.STATE === 'completed') {
- Backbone.trigger('hide-auth-buttons');
- Backbone.trigger('hide-auth-dialogs');
- }
- var loginSrv = window.miServices.get(SERVICE.LOGIN);
- loginSrv.getProfile()
- .then(function (profile) {
- if (profile) {
- params.USER_ID = profile.id;
- }
- _logFBEvent(eventName, params);
- })
- .fail(function () {
- _logFBEvent(eventName, params);
- });
- });
- console.info('FB analytics is initialized');
- } else {
- console.info('FB analytics is not configured');
- }
- return commonUtils.resolvedPromise();
- },
- _initSessionTracking: function () {
- var sessionSrv = window.miServices.get(SERVICE.SESSION_TRACKER);
- if (sessionSrv) {
- if (sessionSrv.isNewSession()) {
- Backbone.trigger('keen:event', {
- type: 'session',
- action: 'start'
- }, true);
- }
- }
- },
- _initInterests: function () {
- var interestsService = window.miServices.get(SERVICE.INTERESTS);
- return interestsService.update();
- },
- _initChannels: function () {
- var channelsMapService = window.miServices.get(SERVICE.CHANNELS_MAP);
- return channelsMapService.update()
- .then(function () {
- var srv = window.miServices.get(SERVICE.ME_CHANNELS_MAP);
- return srv.update();
- });
- },
- _loadServices: function (servicesConfig) {
- var dfd = $.Deferred();
- servicesLoader.loadServices(servicesConfig)
- .always(function (servicesRegistry) {
- window.miServices = servicesRegistry;
- dfd.resolve();
- });
- return dfd.promise();
- },
- _loadMainListeners: function () {
- Backbone.on('interest-changed', _.bind(function () {
- this._showArticles();
- }, this));
- Backbone.on('show-progress', _.bind(_showWaitingSpinner, window, true));
- Backbone.on('hide-progress', _.bind(_showWaitingSpinner, window, false));
- Backbone.on('signup', _.bind(this._showSignupDialog, this));
- Backbone.on('social-login', _.bind(function (socialProviderName) {
- _showWaitingSpinner(true);
- Backbone.trigger('fb:event', 'SIGNIN', {
- STATE: 'started',
- AUTHENTICATION_PROVIDER: socialProviderName
- });
- this._onSocialLogin(socialProviderName)
- .then(_.bind(function (signedUp) {
- _showWaitingSpinner(false);
- var navigationPath = signedUp === true ? 'profile/settings' : ''; // new/existing user
- if (signedUp) {
- fbReportSignupSuccess(socialProviderName);
- } else {
- fbReportSigninSuccess(socialProviderName);
- }
- this._navigate(navigationPath);
- }, this))
- .fail(function (err) {
- _showWaitingSpinner(false);
- Backbone.trigger('social-login-failed', err);
- Backbone.trigger('fb:event', 'SIGNIN', {
- STATE: 'failed',
- AUTHENTICATION_PROVIDER: socialProviderName
- });
- });
- }, this));
- Backbone.on('personalize', _.bind(function () {
- this._navigate("profile/settings");
- }, this));
- Backbone.on('create-collection', _.bind(function () {
- var view = new CreateCollectionView();
- $('body').append(view.render().$el);
- view.on('cancel', _.bind(function () {
- view.remove();
- }, this));
- }, this));
- Backbone.on('add-article-to-collections', _.bind(function (articleId) {
- var articleSrv = window.miServices.get(SERVICE.ARTICLE);
- var collectionSrv = window.miServices.get(SERVICE.COLLECTIONS);
- articleSrv.getArticle(articleId)
- .then(_.bind(function (article) {
- collectionSrv.getCollections(null, 1000, null, null, null)
- .then(_.bind(function (collections) {
- var view = new AddArticleToCollectionsView({
- article: article,
- collections: collections
- });
- $('body').append(view.render().$el);
- view.on('done', _.bind(function () {
- view.remove();
- }, this));
- }, this))
- .fail(function (err) {
- //TODO: error handling
- });
- }, this))
- .fail(function (err) {
- //TODO: error handling
- });
- }, this));
- $('#personalize-nav').hammer().on('tap', _.bind(function () {
- this._navigate("profile/settings");
- }, this));
- $('#articles-page-link').hammer().on('tap', _.bind(function () {
- this._navigate("/");
- Backbone.trigger('keen:event', {
- type: 'page',
- action: 'show',
- name: 'home'
- });
- }, this));
- //HACK: TODO: move when fixed into router.settings();
- $('#profile-page-link').hammer().on('tap', function () {
- Backbone.trigger('keen:event', {
- type: 'page',
- action: 'show',
- name: 'interest-settings'
- });
- });
- var loginService = window.miServices.get(SERVICE.LOGIN);
- loginService.on(loginService.loginStateChangedEventName,
- _.bind(function () {
- this._updateSignOutButtonState();
- var srv = window.miServices.get(SERVICE.PERSONALIZED_ARTICLES);
- this._showArticles()
- .then(_.bind(srv.isEditor, srv))
- .then(_.bind(this._publisherModeConfiguration, this))
- .then(function () {
- _showWaitingSpinner(false);
- });
- }, this));
- },
- _autoLogin: function () {
- var srv = window.miServices.get(SERVICE.LOGIN);
- var dfd = $.Deferred();
- srv.isLoggedIn()
- .then(function (isLoggedIn) {
- if (isLoggedIn) {
- return commonUtils.resolvedPromise();
- }
- var accessToken = utils.getParam('t');
- if (_.isUndefined(accessToken)) {
- return commonUtils.resolvedPromise();
- }
- var refreshToken = utils.getParam('r');
- if (_.isUndefined(accessToken)) {
- return commonUtils.resolvedPromise();
- }
- return srv.setAccessToken({'access_token': accessToken, 'refresh_token': refreshToken});
- })
- .always(_.bind(dfd.resolve, dfd));
- return dfd.promise();
- },
- _renderEditorPublished: function (interest) {
- var srv = window.miServices.get(SERVICE.PERSONALIZED_ARTICLES);
- this._updateArticlesList(srv, srv.ARTICLE_STATE.PUBLISHED, interest);
- },
- _renderEditorNotPublished: function (interest) {
- var srv = window.miServices.get(SERVICE.PERSONALIZED_ARTICLES);
- this._updateArticlesList(srv, srv.ARTICLE_STATE.NOT_PUBLISHED, interest);
- },
- _renderEditorSkipped: function (interest) {
- var srv = window.miServices.get(SERVICE.PERSONALIZED_ARTICLES);
- this._updateArticlesList(srv, srv.ARTICLE_STATE.SKIPPED, interest);
- },
- _updateSignOutButtonState: function () {
- var dfd = $.Deferred();
- var srv = window.miServices.get(SERVICE.LOGIN);
- srv.isLoggedIn()
- .then(function (loggedIn) {
- if (loggedIn) {
- $('body').addClass('logged-in');
- } else {
- $('body').removeClass('logged-in');
- }
- dfd.resolve();
- })
- .fail(_.bind(dfd.resolve, dfd)); // always success
- return dfd.promise();
- },
- _updateArticlesList: function (srv, forArticlesState, interest) {
- if (forArticlesState === this._lastArticlesState) {
- this._showArticles(interest);
- } else {
- _showWaitingSpinner(true);
- this._updateEditorModeLinks(forArticlesState);
- this._showArticles(interest, forArticlesState)
- .then(_.bind(function () {
- this._lastArticlesState = forArticlesState;
- }, this))
- .then(function () {
- _showWaitingSpinner(false);
- })
- .fail(function (err) {
- _showWaitingSpinner(false);
- console.error(err);
- });
- }
- },
- _updateEditorModeLinks: function (forArticlesState) {
- var $editorMode = $('.editor-view-mode');
- $editorMode.removeClass('editor-view-mode-published editor-view-mode-not-published editor-view-mode-skipped');
- $editorMode.addClass('editor-view-mode-' + forArticlesState);
- },
- generateTemplate: function (template, data) {
- return template({"interest": data});
- },
- _getInterestsList: function (channelConfig) {
- var dfd = $.Deferred();
- var particlesSrv = window.miServices.get(SERVICE.PERSONALIZED_ARTICLES);
- var loginSrv = window.miServices.get(SERVICE.LOGIN);
- var publishingMode = false;
- particlesSrv.isPublishingMode()
- .then(function (isPublishingMode) {
- publishingMode = isPublishingMode;
- if (!isPublishingMode) {
- return loginSrv.getProfile();
- } else {
- return commonUtils.resolvedPromise();
- }
- })
- .then(_.bind(function (profile) {
- var interestSrv = window.miServices.get(SERVICE.INTERESTS);
- var newsItems = [];
- _.each(channelConfig, function (config, key) {
- if (config.isNews) {
- newsItems.push({
- id: key,
- name: config.name,
- isNews: true
- });
- }
- });
- newsItems.sort(function (a, b) {
- return a.name < b.name;
- });
- if (profile) {
- return interestSrv.getItems()
- .then(function (interests) {
- var profileInterests = [];
- if (profile.speciality) {
- _.each(interests, function (interest) {
- if (profile.speciality.indexOf(interest.name) > -1) {
- profileInterests.push({
- id: interest.id,
- name: interest.name
- });
- }
- });
- }
- var allItems = newsItems.concat(profileInterests);
- return commonUtils.resolvedPromise(allItems);
- });
- } else {
- if (publishingMode) {
- return interestSrv.getItems()
- .then(function (interests) {
- var allItems = newsItems.concat(interests);
- return commonUtils.resolvedPromise(allItems);
- });
- } else {
- return commonUtils.resolvedPromise([]);
- }
- }
- }, this))
- .then(_.bind(dfd.resolve, dfd))
- .fail(_.bind(dfd.reject, dfd));
- return dfd.promise();
- },
- _getPublishingViewMode: function () {
- if (!$('body').hasClass('editor-publishing')) {
- return '';
- }
- var $editorMode = $('.editor-view-mode');
- if ($editorMode.hasClass('editor-view-mode-published')) {
- return 'published';
- }
- if ($editorMode.hasClass('editor-view-mode-not-published')) {
- return 'not-published';
- }
- if ($editorMode.hasClass('editor-view-mode-skipped')) {
- return 'skipped';
- }
- return ''; // should not be reached
- },
- _renderInterestLinks: function (chanelConfig) {
- var dfd = $.Deferred();
- var nav = $('#interests-nav');
- nav.children().remove();
- this._getInterestsList(chanelConfig)
- .then(_.bind(function (interests) {
- var view = new InterestsLinksSidebarView({
- model: interests
- });
- view.render().promise()
- .done(function () {
- nav.append(view.el);
- dfd.resolve();
- });
- view.on('interest-selected', _.bind(function (interest) {
- var publishingViewMode = this._getPublishingViewMode();
- var path;
- if (publishingViewMode) {
- this._navigate(['/editor', publishingViewMode, interest].join('/'));
- } else {
- this._navigate("/interest/" + interest);
- }
- }, this));
- }, this))
- .fail(function (err) {
- console.error(err);
- dfd.reject(err);
- });
- return dfd.promise();
- },
- _renderLayoutTabArticle: function () {
- var dfd = $.Deferred();
- var layout = new SimpleLayout({});
- this._layoutTabArticle = layout;
- $(TABS.ARTICLES.id).append(layout.el);
- return layout.render().promise();
- },
- _renderTabArticle: function () {
- var view = new ReadingZoneMainView();
- this.mainView = view;
- view.on('command', _.bind(this._onChangeArticleState, this));
- view.on('load-more', _.bind(this._onLoadMore, this));
- var dfd = $.Deferred();
- this._layoutTabArticle.pushView(view)
- .then(_.bind(this._showArticles, this))
- .then(_.bind(this._scrollToArticle, this))
- .then(_.bind(dfd.resolve, dfd))
- .fail(function (err) {
- console.error(err);
- dfd.resolve();
- });
- return dfd.promise();
- },
- _onLoadMore: function (nextPartIndex, interestId) {
- console.log('loading part with index: ' + nextPartIndex);
- var srv = window.miServices.get(SERVICE.PERSONALIZED_ARTICLES);
- var promise,
- articlesState = this._getPublishingViewMode();
- if (interestId) {
- promise = srv.getInterestArticles(articlesState, interestId, nextPartIndex);
- } else {
- promise = srv.getInterestsArticles(articlesState, undefined, nextPartIndex);
- }
- promise.then(_.bind(function (data) {
- var rawArticles = data.result || data.articles || [];
- if (rawArticles.length > 0 && _.isArray(rawArticles[0].articles)) {
- rawArticles = _.chain(rawArticles).pluck("articles").flatten().sortBy("creationDate").value();
- } else {
- rawArticles = rawArticles;
- }
- var articles = _colorize(rawArticles, data.channelConfig);
- this.mainView.showArticles(articles, nextPartIndex, true);
- }, this));
- },
- _displayProfileSettings: function () {
- var loginSrv = window.miServices.get(SERVICE.LOGIN);
- loginSrv.getProfile()
- .then(_.bind(function (profile) {
- if (profile) {
- this._renderLayoutTabProfile();
- this._renderTabProfile();
- } else {
- $('#profile-page-link').hide();
- $('#personalize-nav').hide();
- }
- }, this))
- .fail(function (err) {
- console.error(err);
- });
- },
- _renderLayoutTabProfile: function () {
- $('#profile-page-link').show();
- $('#personalize-nav').show();
- var layout = new SimpleLayout({});
- this._layoutTabProfile = layout;
- $(TABS.PROFILE.id).append(layout.el);
- return layout.render().promise();
- },
- _renderTabProfile: function () {
- if (!this.profileView) {
- this.profileView = new InterestSettingsView();
- this._layoutTabProfile.pushView(this.profileView);
- }
- },
- _displayMyCollections: function () {
- var loginSrv = window.miServices.get(SERVICE.LOGIN);
- loginSrv.getProfile()
- .then(_.bind(function (profile) {
- if (profile) {
- this._renderLayoutTabCollections();
- this._renderTabCollections();
- } else {
- $('#collections-page-link').hide();
- }
- }, this))
- .fail(function (err) {
- console.error(err);
- });
- },
- _renderLayoutTabCollections: function () {
- $('#collections-page-link').show();
- $('#personalize-nav').show();
- var layout = new SimpleLayout({});
- this._layoutTabProfile = layout;
- $(TABS.COLLECTIONS.id).append(layout.el);
- return layout.render().promise();
- },
- _renderTabCollections: function () {
- if (!this.collectionsView) {
- this.collectionsView = new InterestSettingsView();
- this._layoutTabProfile.pushView(this.collectionsView);
- }
- },
- _displayUserVerification: function () {
- var loginSrv = window.miServices.get(SERVICE.LOGIN);
- var particlesSrv = window.miServices.get(SERVICE.PERSONALIZED_ARTICLES);
- loginSrv.getProfile()
- .then(_.bind(function (profile) {
- if (profile) {
- return particlesSrv.isEditor();
- }
- }, this))
- .then(_.bind(function (isEditor) {
- if (isEditor) {
- this._renderLayoutTabVerification();
- this._renderTabVerification();
- } else {
- $('#verification-page-link').hide();
- }
- }, this))
- .fail(function (err) {
- console.error(err);
- });
- },
- _renderLayoutTabVerification: function () {
- $('#verification-page-link').show();
- var layout = new SimpleLayout({});
- this._layoutTabVerification = layout;
- $(TABS.VERIFICATION.id).append(layout.el);
- return layout.render().promise();
- },
- _renderTabVerification: function () {
- if (!this.verificationView) {
- this.verificationView = new UserVerificationView();
- this._layoutTabVerification.pushView(this.verificationView);
- }
- },
- _displayCollectionsAdmin: function () {
- var loginSrv = window.miServices.get(SERVICE.LOGIN);
- var particlesSrv = window.miServices.get(SERVICE.PERSONALIZED_ARTICLES);
- loginSrv.getProfile()
- .then(_.bind(function (profile) {
- if (profile) {
- return particlesSrv.isEditor();
- }
- }, this))
- .then(_.bind(function (isEditor) {
- if (isEditor) {
- this._renderLayoutTabCollectionsAdmin();
- this._renderTabCollectionsAdmin();
- } else {
- $('#collections-admin-page-link').hide();
- }
- }, this))
- .fail(function (err) {
- console.error(err);
- });
- },
- _renderLayoutTabCollectionsAdmin: function () {
- $('#collections-admin-page-link').show();
- var layout = new SimpleLayout({});
- this._layoutTabCollectionsAdmin = layout;
- $(TABS.COLLECTIONS_ADMIN.id).append(layout.el);
- return layout.render().promise();
- },
- _renderTabCollectionsAdmin: function () {
- if (!this.collectionsAdminView) {
- this.collectionsAdminView = new CollectionsAdminView();
- this._layoutTabCollectionsAdmin.pushView(this.collectionsAdminView);
- }
- },
- _onChangeArticleState: function (action, articleId) {
- console.log('change article state: ' + action + ', id: ' + articleId);
- var srv = window.miServices.get(SERVICE.PERSONALIZED_ARTICLES);
- srv.changePublishingStatus(articleId, action)
- .then(function () {
- utils.notifyInfo('Article state changed');
- Backbone.trigger('article-state-chaged', articleId, action);
- Backbone.trigger('keen:event', {
- type: 'publishing',
- action: action,
- articleId: articleId
- });
- })
- .fail(function (err) {
- utils.notifyError('Fail to change article state');
- console.error(err);
- });
- },
- _showArticles: function (selectedInterest, forArticlesState) {
- var srv = window.miServices.get(SERVICE.PERSONALIZED_ARTICLES);
- var channelConfig, promise;
- if (selectedInterest) {
- var articlesState = this._getPublishingViewMode();
- if (this.newslettersView) { // reload articles after newsletters view
- delete this.newslettersView;
- promise = srv.getInterestArticles(articlesState, selectedInterest)
- .then(_.bind(function (data) {
- var articles = _colorize(data.articles, data.channelConfig);
- channelConfig = data.channelConfig;
- return this.mainView.showArticles(articles, selectedInterest);
- }, this));
- } else {
- promise = srv.getInterestArticles(articlesState, selectedInterest)
- .then(_.bind(function (data) {
- var articles = _colorize(data.articles, data.channelConfig);
- channelConfig = data.channelConfig;
- return this.mainView.showArticles(articles, selectedInterest);
- }, this));
- }
- } else {
- promise = srv.getInterestsArticles(forArticlesState)
- .then(_.bind(function (interests) {
- var result = interests.result;
- var articles = [];
- if (result.length > 0 && !_.isUndefined(result[0].articles)) {
- articles = _.chain(result).pluck("articles").flatten().sortBy("creationDate").value();
- } else {
- articles = result;
- }
- articles = _colorize(articles, interests.channelConfig);
- channelConfig = interests.channelConfig;
- return this.mainView.showArticles(articles);
- }, this));
- }
- return promise.then(_.bind(function () {
- this._renderInterestLinks(channelConfig);
- }, this));
- },
- _removeInterest: function (interest) {
- console.log('NYI: remove interest: ' + interest);
- var loginSrv = window.miServices.get(SERVICE.LOGIN);
- loginSrv.getProfile()
- .then(function (profile) {
- if (!profile) { // not loged in
- return commonUtils.resolvedPromise();
- }
- var interests = [];
- if (profile.speciality) {
- interests = profile.speciality.split(';');
- }
- interests = _.filter(interests, function (item) {
- return item !== interest;
- });
- profile.speciality = interests.join(';');
- return loginSrv.updateProfile(profile);
- })
- .then(_.bind(function () {
- return this._navigate('profile/settings');
- }, this))
- .fail(function (err) {
- console.error(err);
- });
- },
- _publisherModeConfiguration: function () {
- var dfd = $.Deferred();
- var srv = window.miServices.get(SERVICE.PERSONALIZED_ARTICLES);
- srv.isPublishingMode()
- .then(_.bind(function (isPublishingMode, isEditor) {
- if (isEditor) {
- $('body').addClass('editor');
- if (!this._publishingModeInitialized) {
- $('.editor-label input').change(_.bind(function (evt) {
- var $switch = $('.editor-label .mdl-switch');
- var checked = $switch.hasClass('is-checked');
- this._switchViewMode(checked ? 'publisher' : 'user');
- srv.setPublishingMode(checked);
- _showWaitingSpinner(true);
- this._showArticles()
- .then(function () {
- _showWaitingSpinner(false);
- })
- .fail(function (err) {
- console.error(err);
- _showWaitingSpinner(false);
- });
- }, this));
- this._publishingModeInitialized = true;
- }
- } else {
- $('body').removeClass('editor');
- }
- if (isPublishingMode) {
- this._switchViewMode('publisher');
- }
- dfd.resolve();
- }, this));
- return dfd.promise();
- },
- _switchViewMode: function (mode) {
- var mswitch = $('.editor-label input').parent()[0].MaterialSwitch;
- switch (mode) {
- case 'user':
- $('body').removeClass('editor-publishing');
- mswitch.off();
- this._navigate('');
- break;
- case 'publisher':
- $('body').addClass('editor-publishing');
- mswitch.on();
- this._navigate('editor/published/');
- break;
- }
- },
- _hideLoadingSpinner: function () {
- $('#loading').css('display', 'none');
- },
- _scrollToArticle: function () {
- function waitForElementToDisplay(selector, time) {
- if (document.querySelector(selector) != null) {
- var articleId = utils.getParam("articleId");
- var articleCard = document.getElementById(articleId);
- if (articleCard) {
- var container = $('.mdl-layout__content');
- var scrollTo = $(articleCard);
- var DELTA = 10;
- container.animate({
- scrollTop: scrollTo.offset().top - (container.scrollTop() + scrollTo.height() + container.offset().top + DELTA)
- });
- }
- } else {
- setTimeout(function () {
- waitForElementToDisplay(selector, time);
- }, time);
- }
- }
- waitForElementToDisplay('.reading-view', 300);
- },
- _updateDataAfterLogin: function () {
- var srv = window.miServices.get(SERVICE.UPDATES);
- if (srv) {
- return srv.update('login');
- }
- return utils.resolvedPromise();
- },
- // _login: function(fieldValues) {
- // var srv = window.miServices.get(SERVICE.LOGIN);
- // return srv.login(fieldValues.email, fieldValues.password);
- // },
- _logout: function () {
- _showWaitingSpinner(true);
- var srv = window.miServices.get(SERVICE.LOGIN);
- srv.logout().always(_.bind(function () {
- _showWaitingSpinner(false);
- Backbone.trigger('show-auth-buttons');
- this._navigate("");
- }, this));
- },
- _initUserProfile: function () {
- var loginSrv = window.miServices.get(SERVICE.LOGIN);
- return loginSrv.getProfile(true)
- .then(function (profile) {
- return loginSrv.updateProfile(profile);
- });
- },
- _showSignupDialog: function () {
- var dfd = $.Deferred();
- Backbone.trigger('fb:event', 'SIGNUP', {
- STATE: 'started',
- PARTNER_RELATION: ''
- });
- var loginSrv = window.miServices.get(SERVICE.LOGIN);
- var view = new SginupView({
- title: 'Sign Up'
- });
- $('body').append(view.render().$el);
- view.on('signup', _.bind(function (cmd, data) {
- switch (cmd) {
- case 'facebook':
- this._onSocialLogin(cmd)
- .then(_.bind(function (signedUp) {
- view.remove();
- var navigationPath = signedUp === true ? 'profile/settings' : ''; // new/existing user
- if (signedUp) {
- fbReportSignupSuccess('facebook');
- } else {
- fbReportSigninSuccess('facebook');
- }
- this._navigate(navigationPath);
- }, this))
- .fail(function (err) {
- console.error(err);
- view.showError(err);
- fbReportSignupFail('facebook', err);
- });
- break;
- case 'google':
- this._onSocialLogin(cmd)
- .then(_.bind(function (signedUp) {
- view.remove();
- var navigationPath = signedUp === true ? 'profile/settings' : ''; // new/existing user
- if (signedUp) {
- fbReportSignupSuccess('google');
- } else {
- fbReportSigninSuccess('google');
- }
- this._navigate(navigationPath);
- }, this))
- .fail(function (err) {
- console.error(err);
- view.showError(err);
- fbReportSignupFail('google', err);
- });
- break;
- case 'mi':
- console.log(data);
- loginSrv.signup(data)
- .then(_.bind(function () {
- console.log('signup successfull');
- return this._initUserProfile();
- }, this))
- .then(function () {
- Backbone.trigger('keen:event', {
- type: 'signup',
- action: 'create-account',
- success: true
- });
- fbReportSignupSuccess('mi');
- return commonUtils.resolvedPromise();
- })
- .then(_.bind(function () {
- console.log('empty profile initialized');
- view.remove();
- this._navigate('profile/settings');
- }, this))
- .fail(function (err) {
- console.error(err);
- var errMsg = 'Signup Error';
- if (!_.isUndefined(err.message)) {
- errMsg = err.message;
- }
- view.showError(errMsg);
- Backbone.trigger('keen:event', {
- type: 'signup',
- action: 'create-account',
- success: false,
- error: errMsg
- });
- fbReportSignupFail('mi', errMsg);
- });
- break;
- case 'cancel':
- Backbone.trigger('fb:event', 'SIGNUP', {
- STATE: 'aborted',
- PARTNER_RELATION: ''
- });
- break;
- }
- }, this));
- return dfd.promise();
- },
- _onSocialLogin: function (socialProvider) {
- var dfd = $.Deferred();
- var loginSrv = window.miServices.get(SERVICE.LOGIN);
- switch (socialProvider) {
- case 'facebook':
- var fbSrv = window.miServices.get(SERVICE.FACEBOOK);
- fbSrv.showAuthentication()
- .then(_.bind(function (profileData, authData) {
- console.log('FB logged in');
- console.log(profileData);
- console.log(authData);
- loginSrv.loginSocial(socialProvider, profileData.id, fbSrv.getProviderData())
- .then(function () {
- Backbone.trigger('keen:event', {
- type: 'login',
- action: 'login-facebook',
- success: true
- });
- return commonUtils.resolvedPromise();
- })
- .then(_.bind(dfd.resolve, dfd))
- .fail(_.bind(function (err) {
- if (err.todo === 'register-social-account') {
- var accountData = {
- email: profileData.original.email,
- profile: profileData
- };
- loginSrv.signupSocial(accountData, fbSrv.getProviderData())
- .then(_.bind(this._initUserProfile, this))
- .then(function () {
- Backbone.trigger('keen:event', {
- type: 'signup',
- action: 'signup-facebook',
- success: true
- });
- return commonUtils.resolvedPromise();
- })
- .then(_.bind(dfd.resolve, dfd, true))
- .fail(function (err) {
- Backbone.trigger('keen:event', {
- type: 'signup',
- action: 'signup-facebook',
- success: false,
- error: err
- });
- dfd.reject(err);
- });
- } else {
- dfd.reject(err);
- }
- }, this));
- }, this))
- .fail(function (err) {
- console.error(err);
- Backbone.trigger('keen:event', {
- type: 'login',
- action: 'login-facebook',
- success: false,
- error: err
- });
- dfd.reject(err);
- });
- break;
- case 'google':
- var gSrv = window.miServices.get(SERVICE.GOOGLE);
- gSrv.showAuthentication()
- .then(_.bind(function (profileData, authData) {
- console.log('Google logged in');
- console.log(profileData);
- console.log(authData);
- loginSrv.loginSocial(socialProvider, profileData.id, gSrv.getProviderData())
- .then(function () {
- Backbone.trigger('keen:event', {
- type: 'login',
- action: 'login-google',
- success: true
- });
- return commonUtils.resolvedPromise();
- })
- .then(_.bind(dfd.resolve, dfd))
- .fail(_.bind(function (err) {
- if (err.todo === 'register-social-account') {
- var accountData = {
- email: profileData.original.email,
- profile: profileData
- };
- loginSrv.signupSocial(accountData, gSrv.getProviderData())
- .then(_.bind(this._initUserProfile, this))
- .then(function () {
- Backbone.trigger('keen:event', {
- type: 'signup',
- action: 'signup-google',
- success: true
- });
- return commonUtils.resolvedPromise();
- })
- .then(_.bind(dfd.resolve, dfd, true))
- .fail(function (err) {
- Backbone.trigger('keen:event', {
- type: 'signup',
- action: 'signup-google',
- success: false,
- error: err
- });
- dfd.reject(err);
- });
- } else {
- dfd.reject(err);
- }
- }, this));
- }, this))
- .fail(function (err) {
- console.error(err);
- Backbone.trigger('keen:event', {
- type: 'login',
- action: 'login-google',
- success: false,
- error: err
- });
- dfd.reject(err);
- });
- break;
- default:
- dfd.reject({
- message: 'Not recognized social Provider: ' + socialProvider
- });
- }
- return dfd.promise();
- },
- _resetPassword: function () {
- var view = new ResetPasswordView();
- $('body').append(view.render().$el);
- view.on('reset-password', _.bind(function (email) {
- var loginSrv = window.miServices.get(SERVICE.LOGIN);
- loginSrv.resetPassword(email)
- .then(function () {
- _showWaitingSpinner(false);
- view.showSuccess();
- })
- .fail(function (err) {
- var msg = 'Fail to reset password';
- if (err.message) {
- msg = err.message;
- } else {
- if (err.errors && err.errors.length > 0) {
- msg = err.errors[0];
- }
- }
- _showWaitingSpinner(false);
- view.showError(msg);
- });
- }, this));
- view.on('closed', function () {
- window.history.back();
- });
- },
- _showArticle: function (articleId) {
- var articleService = window.miServices.get(SERVICE.ARTICLE);
- articleService.getArticle(articleId)
- .then(_.bind(function (article) {
- var view = new ArticleView({
- article: article
- });
- this.mainView = view;
- $('meta[property="og:title"]').attr('content', article.title);
- $('meta[property="og:url"]').attr('content', platformConfig.readingZoneUrl + 'wrapper/article/' + article._id);
- if (article.journal === 'youtube.com') {
- $('meta[property="og:description"]').attr('content', article.content);
- } else {
- $('meta[property="og:description"]').attr('content', article.excerpt);
- }
- if (article.previewImageUrl) {
- $('meta[property="og:image"]').attr('content', platformConfig.readingZoneUrl + 'wrapper/proxy?url=' + encodeURIComponent(article.previewImageUrl));
- }
- var dfd = $.Deferred();
- this._layoutTabArticle.pushView(view)
- .then(_.bind(dfd.resolve, dfd))
- .fail(function (err) {
- console.error(err);
- dfd.resolve();
- });
- view.on('back', _.bind(function () {
- this._renderTabArticle();
- this._back();
- }, this));
- return dfd.promise();
- }, this))
- .fail(function (err) {
- //TODO: error handling
- });
- },
- _login: function (email) {
- this._showLogin = true;
- this._email = email;
- },
- checkIsItDevice: function () {
- /* jshint ignore:start */
- var ua = navigator.userAgent;
- var checker = {
- iphone: ua.match(/(iPhone|iPod|iPad)/),
- blackberry: ua.match(/BlackBerry/),
- android: ua.match(/Android/)
- };
- return (checker.iphone || checker.blackberry || checker.android);
- /* jshint ignore:end */
- }
- });
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement